1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
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 the Constant* classes.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "llvm/IR/Constants.h"
14 #include "ConstantFold.h"
15 #include "LLVMContextImpl.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/GetElementPtrTypeIterator.h"
21 #include "llvm/IR/GlobalValue.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Operator.h"
25 #include "llvm/IR/PatternMatch.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/ManagedStatic.h"
30 #include "llvm/Support/MathExtras.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include <algorithm>
33
34 using namespace llvm;
35 using namespace PatternMatch;
36
37 //===----------------------------------------------------------------------===//
38 // Constant Class
39 //===----------------------------------------------------------------------===//
40
isNegativeZeroValue() const41 bool Constant::isNegativeZeroValue() const {
42 // Floating point values have an explicit -0.0 value.
43 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
44 return CFP->isZero() && CFP->isNegative();
45
46 // Equivalent for a vector of -0.0's.
47 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
48 if (CV->getElementType()->isFloatingPointTy() && CV->isSplat())
49 if (CV->getElementAsAPFloat(0).isNegZero())
50 return true;
51
52 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
53 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
54 if (SplatCFP && SplatCFP->isZero() && SplatCFP->isNegative())
55 return true;
56
57 // We've already handled true FP case; any other FP vectors can't represent -0.0.
58 if (getType()->isFPOrFPVectorTy())
59 return false;
60
61 // Otherwise, just use +0.0.
62 return isNullValue();
63 }
64
65 // Return true iff this constant is positive zero (floating point), negative
66 // zero (floating point), or a null value.
isZeroValue() const67 bool Constant::isZeroValue() const {
68 // Floating point values have an explicit -0.0 value.
69 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
70 return CFP->isZero();
71
72 // Equivalent for a vector of -0.0's.
73 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
74 if (CV->getElementType()->isFloatingPointTy() && CV->isSplat())
75 if (CV->getElementAsAPFloat(0).isZero())
76 return true;
77
78 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
79 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
80 if (SplatCFP && SplatCFP->isZero())
81 return true;
82
83 // Otherwise, just use +0.0.
84 return isNullValue();
85 }
86
isNullValue() const87 bool Constant::isNullValue() const {
88 // 0 is null.
89 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
90 return CI->isZero();
91
92 // +0.0 is null.
93 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
94 return CFP->isZero() && !CFP->isNegative();
95
96 // constant zero is zero for aggregates, cpnull is null for pointers, none for
97 // tokens.
98 return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this) ||
99 isa<ConstantTokenNone>(this);
100 }
101
isAllOnesValue() const102 bool Constant::isAllOnesValue() const {
103 // Check for -1 integers
104 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
105 return CI->isMinusOne();
106
107 // Check for FP which are bitcasted from -1 integers
108 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
109 return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
110
111 // Check for constant vectors which are splats of -1 values.
112 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
113 if (Constant *Splat = CV->getSplatValue())
114 return Splat->isAllOnesValue();
115
116 // Check for constant vectors which are splats of -1 values.
117 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
118 if (CV->isSplat()) {
119 if (CV->getElementType()->isFloatingPointTy())
120 return CV->getElementAsAPFloat(0).bitcastToAPInt().isAllOnesValue();
121 return CV->getElementAsAPInt(0).isAllOnesValue();
122 }
123 }
124
125 return false;
126 }
127
isOneValue() const128 bool Constant::isOneValue() const {
129 // Check for 1 integers
130 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
131 return CI->isOne();
132
133 // Check for FP which are bitcasted from 1 integers
134 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
135 return CFP->getValueAPF().bitcastToAPInt().isOneValue();
136
137 // Check for constant vectors which are splats of 1 values.
138 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
139 if (Constant *Splat = CV->getSplatValue())
140 return Splat->isOneValue();
141
142 // Check for constant vectors which are splats of 1 values.
143 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
144 if (CV->isSplat()) {
145 if (CV->getElementType()->isFloatingPointTy())
146 return CV->getElementAsAPFloat(0).bitcastToAPInt().isOneValue();
147 return CV->getElementAsAPInt(0).isOneValue();
148 }
149 }
150
151 return false;
152 }
153
isNotOneValue() const154 bool Constant::isNotOneValue() const {
155 // Check for 1 integers
156 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
157 return !CI->isOneValue();
158
159 // Check for FP which are bitcasted from 1 integers
160 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
161 return !CFP->getValueAPF().bitcastToAPInt().isOneValue();
162
163 // Check that vectors don't contain 1
164 if (auto *VTy = dyn_cast<VectorType>(this->getType())) {
165 unsigned NumElts = VTy->getNumElements();
166 for (unsigned i = 0; i != NumElts; ++i) {
167 Constant *Elt = this->getAggregateElement(i);
168 if (!Elt || !Elt->isNotOneValue())
169 return false;
170 }
171 return true;
172 }
173
174 // It *may* contain 1, we can't tell.
175 return false;
176 }
177
isMinSignedValue() const178 bool Constant::isMinSignedValue() const {
179 // Check for INT_MIN integers
180 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
181 return CI->isMinValue(/*isSigned=*/true);
182
183 // Check for FP which are bitcasted from INT_MIN integers
184 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
185 return CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
186
187 // Check for constant vectors which are splats of INT_MIN values.
188 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
189 if (Constant *Splat = CV->getSplatValue())
190 return Splat->isMinSignedValue();
191
192 // Check for constant vectors which are splats of INT_MIN values.
193 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
194 if (CV->isSplat()) {
195 if (CV->getElementType()->isFloatingPointTy())
196 return CV->getElementAsAPFloat(0).bitcastToAPInt().isMinSignedValue();
197 return CV->getElementAsAPInt(0).isMinSignedValue();
198 }
199 }
200
201 return false;
202 }
203
isNotMinSignedValue() const204 bool Constant::isNotMinSignedValue() const {
205 // Check for INT_MIN integers
206 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
207 return !CI->isMinValue(/*isSigned=*/true);
208
209 // Check for FP which are bitcasted from INT_MIN integers
210 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
211 return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
212
213 // Check that vectors don't contain INT_MIN
214 if (auto *VTy = dyn_cast<VectorType>(this->getType())) {
215 unsigned NumElts = VTy->getNumElements();
216 for (unsigned i = 0; i != NumElts; ++i) {
217 Constant *Elt = this->getAggregateElement(i);
218 if (!Elt || !Elt->isNotMinSignedValue())
219 return false;
220 }
221 return true;
222 }
223
224 // It *may* contain INT_MIN, we can't tell.
225 return false;
226 }
227
isFiniteNonZeroFP() const228 bool Constant::isFiniteNonZeroFP() const {
229 if (auto *CFP = dyn_cast<ConstantFP>(this))
230 return CFP->getValueAPF().isFiniteNonZero();
231 auto *VTy = dyn_cast<VectorType>(getType());
232 if (!VTy)
233 return false;
234 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
235 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
236 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
237 return false;
238 }
239 return true;
240 }
241
isNormalFP() const242 bool Constant::isNormalFP() const {
243 if (auto *CFP = dyn_cast<ConstantFP>(this))
244 return CFP->getValueAPF().isNormal();
245 auto *VTy = dyn_cast<FixedVectorType>(getType());
246 if (!VTy)
247 return false;
248 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
249 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
250 if (!CFP || !CFP->getValueAPF().isNormal())
251 return false;
252 }
253 return true;
254 }
255
hasExactInverseFP() const256 bool Constant::hasExactInverseFP() const {
257 if (auto *CFP = dyn_cast<ConstantFP>(this))
258 return CFP->getValueAPF().getExactInverse(nullptr);
259 auto *VTy = dyn_cast<FixedVectorType>(getType());
260 if (!VTy)
261 return false;
262 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
263 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
264 if (!CFP || !CFP->getValueAPF().getExactInverse(nullptr))
265 return false;
266 }
267 return true;
268 }
269
isNaN() const270 bool Constant::isNaN() const {
271 if (auto *CFP = dyn_cast<ConstantFP>(this))
272 return CFP->isNaN();
273 auto *VTy = dyn_cast<FixedVectorType>(getType());
274 if (!VTy)
275 return false;
276 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
277 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
278 if (!CFP || !CFP->isNaN())
279 return false;
280 }
281 return true;
282 }
283
isElementWiseEqual(Value * Y) const284 bool Constant::isElementWiseEqual(Value *Y) const {
285 // Are they fully identical?
286 if (this == Y)
287 return true;
288
289 // The input value must be a vector constant with the same type.
290 auto *VTy = dyn_cast<VectorType>(getType());
291 if (!isa<Constant>(Y) || !VTy || VTy != Y->getType())
292 return false;
293
294 // TODO: Compare pointer constants?
295 if (!(VTy->getElementType()->isIntegerTy() ||
296 VTy->getElementType()->isFloatingPointTy()))
297 return false;
298
299 // They may still be identical element-wise (if they have `undef`s).
300 // Bitcast to integer to allow exact bitwise comparison for all types.
301 Type *IntTy = VectorType::getInteger(VTy);
302 Constant *C0 = ConstantExpr::getBitCast(const_cast<Constant *>(this), IntTy);
303 Constant *C1 = ConstantExpr::getBitCast(cast<Constant>(Y), IntTy);
304 Constant *CmpEq = ConstantExpr::getICmp(ICmpInst::ICMP_EQ, C0, C1);
305 return isa<UndefValue>(CmpEq) || match(CmpEq, m_One());
306 }
307
containsUndefElement() const308 bool Constant::containsUndefElement() const {
309 if (auto *VTy = dyn_cast<VectorType>(getType())) {
310 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i)
311 if (isa<UndefValue>(getAggregateElement(i)))
312 return true;
313 }
314
315 return false;
316 }
317
containsConstantExpression() const318 bool Constant::containsConstantExpression() const {
319 if (auto *VTy = dyn_cast<VectorType>(getType())) {
320 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i)
321 if (isa<ConstantExpr>(getAggregateElement(i)))
322 return true;
323 }
324
325 return false;
326 }
327
328 /// Constructor to create a '0' constant of arbitrary type.
getNullValue(Type * Ty)329 Constant *Constant::getNullValue(Type *Ty) {
330 switch (Ty->getTypeID()) {
331 case Type::IntegerTyID:
332 return ConstantInt::get(Ty, 0);
333 case Type::HalfTyID:
334 return ConstantFP::get(Ty->getContext(),
335 APFloat::getZero(APFloat::IEEEhalf()));
336 case Type::BFloatTyID:
337 return ConstantFP::get(Ty->getContext(),
338 APFloat::getZero(APFloat::BFloat()));
339 case Type::FloatTyID:
340 return ConstantFP::get(Ty->getContext(),
341 APFloat::getZero(APFloat::IEEEsingle()));
342 case Type::DoubleTyID:
343 return ConstantFP::get(Ty->getContext(),
344 APFloat::getZero(APFloat::IEEEdouble()));
345 case Type::X86_FP80TyID:
346 return ConstantFP::get(Ty->getContext(),
347 APFloat::getZero(APFloat::x87DoubleExtended()));
348 case Type::FP128TyID:
349 return ConstantFP::get(Ty->getContext(),
350 APFloat::getZero(APFloat::IEEEquad()));
351 case Type::PPC_FP128TyID:
352 return ConstantFP::get(Ty->getContext(),
353 APFloat(APFloat::PPCDoubleDouble(),
354 APInt::getNullValue(128)));
355 case Type::PointerTyID:
356 return ConstantPointerNull::get(cast<PointerType>(Ty));
357 case Type::StructTyID:
358 case Type::ArrayTyID:
359 case Type::FixedVectorTyID:
360 case Type::ScalableVectorTyID:
361 return ConstantAggregateZero::get(Ty);
362 case Type::TokenTyID:
363 return ConstantTokenNone::get(Ty->getContext());
364 default:
365 // Function, Label, or Opaque type?
366 llvm_unreachable("Cannot create a null constant of that type!");
367 }
368 }
369
getIntegerValue(Type * Ty,const APInt & V)370 Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
371 Type *ScalarTy = Ty->getScalarType();
372
373 // Create the base integer constant.
374 Constant *C = ConstantInt::get(Ty->getContext(), V);
375
376 // Convert an integer to a pointer, if necessary.
377 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
378 C = ConstantExpr::getIntToPtr(C, PTy);
379
380 // Broadcast a scalar to a vector, if necessary.
381 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
382 C = ConstantVector::getSplat(VTy->getElementCount(), C);
383
384 return C;
385 }
386
getAllOnesValue(Type * Ty)387 Constant *Constant::getAllOnesValue(Type *Ty) {
388 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
389 return ConstantInt::get(Ty->getContext(),
390 APInt::getAllOnesValue(ITy->getBitWidth()));
391
392 if (Ty->isFloatingPointTy()) {
393 APFloat FL = APFloat::getAllOnesValue(Ty->getFltSemantics(),
394 Ty->getPrimitiveSizeInBits());
395 return ConstantFP::get(Ty->getContext(), FL);
396 }
397
398 VectorType *VTy = cast<VectorType>(Ty);
399 return ConstantVector::getSplat(VTy->getElementCount(),
400 getAllOnesValue(VTy->getElementType()));
401 }
402
getAggregateElement(unsigned Elt) const403 Constant *Constant::getAggregateElement(unsigned Elt) const {
404 if (const ConstantAggregate *CC = dyn_cast<ConstantAggregate>(this))
405 return Elt < CC->getNumOperands() ? CC->getOperand(Elt) : nullptr;
406
407 if (const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(this))
408 return Elt < CAZ->getNumElements() ? CAZ->getElementValue(Elt) : nullptr;
409
410 if (const UndefValue *UV = dyn_cast<UndefValue>(this))
411 return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr;
412
413 if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
414 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
415 : nullptr;
416 return nullptr;
417 }
418
getAggregateElement(Constant * Elt) const419 Constant *Constant::getAggregateElement(Constant *Elt) const {
420 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
421 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt)) {
422 // Check if the constant fits into an uint64_t.
423 if (CI->getValue().getActiveBits() > 64)
424 return nullptr;
425 return getAggregateElement(CI->getZExtValue());
426 }
427 return nullptr;
428 }
429
destroyConstant()430 void Constant::destroyConstant() {
431 /// First call destroyConstantImpl on the subclass. This gives the subclass
432 /// a chance to remove the constant from any maps/pools it's contained in.
433 switch (getValueID()) {
434 default:
435 llvm_unreachable("Not a constant!");
436 #define HANDLE_CONSTANT(Name) \
437 case Value::Name##Val: \
438 cast<Name>(this)->destroyConstantImpl(); \
439 break;
440 #include "llvm/IR/Value.def"
441 }
442
443 // When a Constant is destroyed, there may be lingering
444 // references to the constant by other constants in the constant pool. These
445 // constants are implicitly dependent on the module that is being deleted,
446 // but they don't know that. Because we only find out when the CPV is
447 // deleted, we must now notify all of our users (that should only be
448 // Constants) that they are, in fact, invalid now and should be deleted.
449 //
450 while (!use_empty()) {
451 Value *V = user_back();
452 #ifndef NDEBUG // Only in -g mode...
453 if (!isa<Constant>(V)) {
454 dbgs() << "While deleting: " << *this
455 << "\n\nUse still stuck around after Def is destroyed: " << *V
456 << "\n\n";
457 }
458 #endif
459 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
460 cast<Constant>(V)->destroyConstant();
461
462 // The constant should remove itself from our use list...
463 assert((use_empty() || user_back() != V) && "Constant not removed!");
464 }
465
466 // Value has no outstanding references it is safe to delete it now...
467 deleteConstant(this);
468 }
469
deleteConstant(Constant * C)470 void llvm::deleteConstant(Constant *C) {
471 switch (C->getValueID()) {
472 case Constant::ConstantIntVal:
473 delete static_cast<ConstantInt *>(C);
474 break;
475 case Constant::ConstantFPVal:
476 delete static_cast<ConstantFP *>(C);
477 break;
478 case Constant::ConstantAggregateZeroVal:
479 delete static_cast<ConstantAggregateZero *>(C);
480 break;
481 case Constant::ConstantArrayVal:
482 delete static_cast<ConstantArray *>(C);
483 break;
484 case Constant::ConstantStructVal:
485 delete static_cast<ConstantStruct *>(C);
486 break;
487 case Constant::ConstantVectorVal:
488 delete static_cast<ConstantVector *>(C);
489 break;
490 case Constant::ConstantPointerNullVal:
491 delete static_cast<ConstantPointerNull *>(C);
492 break;
493 case Constant::ConstantDataArrayVal:
494 delete static_cast<ConstantDataArray *>(C);
495 break;
496 case Constant::ConstantDataVectorVal:
497 delete static_cast<ConstantDataVector *>(C);
498 break;
499 case Constant::ConstantTokenNoneVal:
500 delete static_cast<ConstantTokenNone *>(C);
501 break;
502 case Constant::BlockAddressVal:
503 delete static_cast<BlockAddress *>(C);
504 break;
505 case Constant::UndefValueVal:
506 delete static_cast<UndefValue *>(C);
507 break;
508 case Constant::ConstantExprVal:
509 if (isa<UnaryConstantExpr>(C))
510 delete static_cast<UnaryConstantExpr *>(C);
511 else if (isa<BinaryConstantExpr>(C))
512 delete static_cast<BinaryConstantExpr *>(C);
513 else if (isa<SelectConstantExpr>(C))
514 delete static_cast<SelectConstantExpr *>(C);
515 else if (isa<ExtractElementConstantExpr>(C))
516 delete static_cast<ExtractElementConstantExpr *>(C);
517 else if (isa<InsertElementConstantExpr>(C))
518 delete static_cast<InsertElementConstantExpr *>(C);
519 else if (isa<ShuffleVectorConstantExpr>(C))
520 delete static_cast<ShuffleVectorConstantExpr *>(C);
521 else if (isa<ExtractValueConstantExpr>(C))
522 delete static_cast<ExtractValueConstantExpr *>(C);
523 else if (isa<InsertValueConstantExpr>(C))
524 delete static_cast<InsertValueConstantExpr *>(C);
525 else if (isa<GetElementPtrConstantExpr>(C))
526 delete static_cast<GetElementPtrConstantExpr *>(C);
527 else if (isa<CompareConstantExpr>(C))
528 delete static_cast<CompareConstantExpr *>(C);
529 else
530 llvm_unreachable("Unexpected constant expr");
531 break;
532 default:
533 llvm_unreachable("Unexpected constant");
534 }
535 }
536
canTrapImpl(const Constant * C,SmallPtrSetImpl<const ConstantExpr * > & NonTrappingOps)537 static bool canTrapImpl(const Constant *C,
538 SmallPtrSetImpl<const ConstantExpr *> &NonTrappingOps) {
539 assert(C->getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
540 // The only thing that could possibly trap are constant exprs.
541 const ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
542 if (!CE)
543 return false;
544
545 // ConstantExpr traps if any operands can trap.
546 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
547 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(CE->getOperand(i))) {
548 if (NonTrappingOps.insert(Op).second && canTrapImpl(Op, NonTrappingOps))
549 return true;
550 }
551 }
552
553 // Otherwise, only specific operations can trap.
554 switch (CE->getOpcode()) {
555 default:
556 return false;
557 case Instruction::UDiv:
558 case Instruction::SDiv:
559 case Instruction::URem:
560 case Instruction::SRem:
561 // Div and rem can trap if the RHS is not known to be non-zero.
562 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
563 return true;
564 return false;
565 }
566 }
567
canTrap() const568 bool Constant::canTrap() const {
569 SmallPtrSet<const ConstantExpr *, 4> NonTrappingOps;
570 return canTrapImpl(this, NonTrappingOps);
571 }
572
573 /// Check if C contains a GlobalValue for which Predicate is true.
574 static bool
ConstHasGlobalValuePredicate(const Constant * C,bool (* Predicate)(const GlobalValue *))575 ConstHasGlobalValuePredicate(const Constant *C,
576 bool (*Predicate)(const GlobalValue *)) {
577 SmallPtrSet<const Constant *, 8> Visited;
578 SmallVector<const Constant *, 8> WorkList;
579 WorkList.push_back(C);
580 Visited.insert(C);
581
582 while (!WorkList.empty()) {
583 const Constant *WorkItem = WorkList.pop_back_val();
584 if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
585 if (Predicate(GV))
586 return true;
587 for (const Value *Op : WorkItem->operands()) {
588 const Constant *ConstOp = dyn_cast<Constant>(Op);
589 if (!ConstOp)
590 continue;
591 if (Visited.insert(ConstOp).second)
592 WorkList.push_back(ConstOp);
593 }
594 }
595 return false;
596 }
597
isThreadDependent() const598 bool Constant::isThreadDependent() const {
599 auto DLLImportPredicate = [](const GlobalValue *GV) {
600 return GV->isThreadLocal();
601 };
602 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
603 }
604
isDLLImportDependent() const605 bool Constant::isDLLImportDependent() const {
606 auto DLLImportPredicate = [](const GlobalValue *GV) {
607 return GV->hasDLLImportStorageClass();
608 };
609 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
610 }
611
isConstantUsed() const612 bool Constant::isConstantUsed() const {
613 for (const User *U : users()) {
614 const Constant *UC = dyn_cast<Constant>(U);
615 if (!UC || isa<GlobalValue>(UC))
616 return true;
617
618 if (UC->isConstantUsed())
619 return true;
620 }
621 return false;
622 }
623
needsRelocation() const624 bool Constant::needsRelocation() const {
625 if (isa<GlobalValue>(this))
626 return true; // Global reference.
627
628 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
629 return BA->getFunction()->needsRelocation();
630
631 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) {
632 if (CE->getOpcode() == Instruction::Sub) {
633 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
634 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
635 if (LHS && RHS && LHS->getOpcode() == Instruction::PtrToInt &&
636 RHS->getOpcode() == Instruction::PtrToInt) {
637 Constant *LHSOp0 = LHS->getOperand(0);
638 Constant *RHSOp0 = RHS->getOperand(0);
639
640 // While raw uses of blockaddress need to be relocated, differences
641 // between two of them don't when they are for labels in the same
642 // function. This is a common idiom when creating a table for the
643 // indirect goto extension, so we handle it efficiently here.
644 if (isa<BlockAddress>(LHSOp0) && isa<BlockAddress>(RHSOp0) &&
645 cast<BlockAddress>(LHSOp0)->getFunction() ==
646 cast<BlockAddress>(RHSOp0)->getFunction())
647 return false;
648
649 // Relative pointers do not need to be dynamically relocated.
650 if (auto *LHSGV = dyn_cast<GlobalValue>(LHSOp0->stripPointerCasts()))
651 if (auto *RHSGV = dyn_cast<GlobalValue>(RHSOp0->stripPointerCasts()))
652 if (LHSGV->isDSOLocal() && RHSGV->isDSOLocal())
653 return false;
654 }
655 }
656 }
657
658 bool Result = false;
659 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
660 Result |= cast<Constant>(getOperand(i))->needsRelocation();
661
662 return Result;
663 }
664
665 /// If the specified constantexpr is dead, remove it. This involves recursively
666 /// eliminating any dead users of the constantexpr.
removeDeadUsersOfConstant(const Constant * C)667 static bool removeDeadUsersOfConstant(const Constant *C) {
668 if (isa<GlobalValue>(C)) return false; // Cannot remove this
669
670 while (!C->use_empty()) {
671 const Constant *User = dyn_cast<Constant>(C->user_back());
672 if (!User) return false; // Non-constant usage;
673 if (!removeDeadUsersOfConstant(User))
674 return false; // Constant wasn't dead
675 }
676
677 const_cast<Constant*>(C)->destroyConstant();
678 return true;
679 }
680
681
removeDeadConstantUsers() const682 void Constant::removeDeadConstantUsers() const {
683 Value::const_user_iterator I = user_begin(), E = user_end();
684 Value::const_user_iterator LastNonDeadUser = E;
685 while (I != E) {
686 const Constant *User = dyn_cast<Constant>(*I);
687 if (!User) {
688 LastNonDeadUser = I;
689 ++I;
690 continue;
691 }
692
693 if (!removeDeadUsersOfConstant(User)) {
694 // If the constant wasn't dead, remember that this was the last live use
695 // and move on to the next constant.
696 LastNonDeadUser = I;
697 ++I;
698 continue;
699 }
700
701 // If the constant was dead, then the iterator is invalidated.
702 if (LastNonDeadUser == E)
703 I = user_begin();
704 else
705 I = std::next(LastNonDeadUser);
706 }
707 }
708
replaceUndefsWith(Constant * C,Constant * Replacement)709 Constant *Constant::replaceUndefsWith(Constant *C, Constant *Replacement) {
710 assert(C && Replacement && "Expected non-nullptr constant arguments");
711 Type *Ty = C->getType();
712 if (match(C, m_Undef())) {
713 assert(Ty == Replacement->getType() && "Expected matching types");
714 return Replacement;
715 }
716
717 // Don't know how to deal with this constant.
718 auto *VTy = dyn_cast<FixedVectorType>(Ty);
719 if (!VTy)
720 return C;
721
722 unsigned NumElts = VTy->getNumElements();
723 SmallVector<Constant *, 32> NewC(NumElts);
724 for (unsigned i = 0; i != NumElts; ++i) {
725 Constant *EltC = C->getAggregateElement(i);
726 assert((!EltC || EltC->getType() == Replacement->getType()) &&
727 "Expected matching types");
728 NewC[i] = EltC && match(EltC, m_Undef()) ? Replacement : EltC;
729 }
730 return ConstantVector::get(NewC);
731 }
732
733
734 //===----------------------------------------------------------------------===//
735 // ConstantInt
736 //===----------------------------------------------------------------------===//
737
ConstantInt(IntegerType * Ty,const APInt & V)738 ConstantInt::ConstantInt(IntegerType *Ty, const APInt &V)
739 : ConstantData(Ty, ConstantIntVal), Val(V) {
740 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
741 }
742
getTrue(LLVMContext & Context)743 ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
744 LLVMContextImpl *pImpl = Context.pImpl;
745 if (!pImpl->TheTrueVal)
746 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
747 return pImpl->TheTrueVal;
748 }
749
getFalse(LLVMContext & Context)750 ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
751 LLVMContextImpl *pImpl = Context.pImpl;
752 if (!pImpl->TheFalseVal)
753 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
754 return pImpl->TheFalseVal;
755 }
756
getTrue(Type * Ty)757 Constant *ConstantInt::getTrue(Type *Ty) {
758 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
759 ConstantInt *TrueC = ConstantInt::getTrue(Ty->getContext());
760 if (auto *VTy = dyn_cast<VectorType>(Ty))
761 return ConstantVector::getSplat(VTy->getElementCount(), TrueC);
762 return TrueC;
763 }
764
getFalse(Type * Ty)765 Constant *ConstantInt::getFalse(Type *Ty) {
766 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
767 ConstantInt *FalseC = ConstantInt::getFalse(Ty->getContext());
768 if (auto *VTy = dyn_cast<VectorType>(Ty))
769 return ConstantVector::getSplat(VTy->getElementCount(), FalseC);
770 return FalseC;
771 }
772
773 // Get a ConstantInt from an APInt.
get(LLVMContext & Context,const APInt & V)774 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
775 // get an existing value or the insertion position
776 LLVMContextImpl *pImpl = Context.pImpl;
777 std::unique_ptr<ConstantInt> &Slot = pImpl->IntConstants[V];
778 if (!Slot) {
779 // Get the corresponding integer type for the bit width of the value.
780 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
781 Slot.reset(new ConstantInt(ITy, V));
782 }
783 assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
784 return Slot.get();
785 }
786
get(Type * Ty,uint64_t V,bool isSigned)787 Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
788 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
789
790 // For vectors, broadcast the value.
791 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
792 return ConstantVector::getSplat(VTy->getElementCount(), C);
793
794 return C;
795 }
796
get(IntegerType * Ty,uint64_t V,bool isSigned)797 ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, bool isSigned) {
798 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
799 }
800
getSigned(IntegerType * Ty,int64_t V)801 ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
802 return get(Ty, V, true);
803 }
804
getSigned(Type * Ty,int64_t V)805 Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
806 return get(Ty, V, true);
807 }
808
get(Type * Ty,const APInt & V)809 Constant *ConstantInt::get(Type *Ty, const APInt& V) {
810 ConstantInt *C = get(Ty->getContext(), V);
811 assert(C->getType() == Ty->getScalarType() &&
812 "ConstantInt type doesn't match the type implied by its value!");
813
814 // For vectors, broadcast the value.
815 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
816 return ConstantVector::getSplat(VTy->getElementCount(), C);
817
818 return C;
819 }
820
get(IntegerType * Ty,StringRef Str,uint8_t radix)821 ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str, uint8_t radix) {
822 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
823 }
824
825 /// Remove the constant from the constant table.
destroyConstantImpl()826 void ConstantInt::destroyConstantImpl() {
827 llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
828 }
829
830 //===----------------------------------------------------------------------===//
831 // ConstantFP
832 //===----------------------------------------------------------------------===//
833
TypeToFloatSemantics(Type * Ty)834 static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
835 if (Ty->isHalfTy())
836 return &APFloat::IEEEhalf();
837 if (Ty->isBFloatTy())
838 return &APFloat::BFloat();
839 if (Ty->isFloatTy())
840 return &APFloat::IEEEsingle();
841 if (Ty->isDoubleTy())
842 return &APFloat::IEEEdouble();
843 if (Ty->isX86_FP80Ty())
844 return &APFloat::x87DoubleExtended();
845 else if (Ty->isFP128Ty())
846 return &APFloat::IEEEquad();
847
848 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
849 return &APFloat::PPCDoubleDouble();
850 }
851
get(Type * Ty,double V)852 Constant *ConstantFP::get(Type *Ty, double V) {
853 LLVMContext &Context = Ty->getContext();
854
855 APFloat FV(V);
856 bool ignored;
857 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
858 APFloat::rmNearestTiesToEven, &ignored);
859 Constant *C = get(Context, FV);
860
861 // For vectors, broadcast the value.
862 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
863 return ConstantVector::getSplat(VTy->getElementCount(), C);
864
865 return C;
866 }
867
get(Type * Ty,const APFloat & V)868 Constant *ConstantFP::get(Type *Ty, const APFloat &V) {
869 ConstantFP *C = get(Ty->getContext(), V);
870 assert(C->getType() == Ty->getScalarType() &&
871 "ConstantFP type doesn't match the type implied by its value!");
872
873 // For vectors, broadcast the value.
874 if (auto *VTy = dyn_cast<VectorType>(Ty))
875 return ConstantVector::getSplat(VTy->getElementCount(), C);
876
877 return C;
878 }
879
get(Type * Ty,StringRef Str)880 Constant *ConstantFP::get(Type *Ty, StringRef Str) {
881 LLVMContext &Context = Ty->getContext();
882
883 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
884 Constant *C = get(Context, FV);
885
886 // For vectors, broadcast the value.
887 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
888 return ConstantVector::getSplat(VTy->getElementCount(), C);
889
890 return C;
891 }
892
getNaN(Type * Ty,bool Negative,uint64_t Payload)893 Constant *ConstantFP::getNaN(Type *Ty, bool Negative, uint64_t Payload) {
894 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
895 APFloat NaN = APFloat::getNaN(Semantics, Negative, Payload);
896 Constant *C = get(Ty->getContext(), NaN);
897
898 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
899 return ConstantVector::getSplat(VTy->getElementCount(), C);
900
901 return C;
902 }
903
getQNaN(Type * Ty,bool Negative,APInt * Payload)904 Constant *ConstantFP::getQNaN(Type *Ty, bool Negative, APInt *Payload) {
905 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
906 APFloat NaN = APFloat::getQNaN(Semantics, Negative, Payload);
907 Constant *C = get(Ty->getContext(), NaN);
908
909 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
910 return ConstantVector::getSplat(VTy->getElementCount(), C);
911
912 return C;
913 }
914
getSNaN(Type * Ty,bool Negative,APInt * Payload)915 Constant *ConstantFP::getSNaN(Type *Ty, bool Negative, APInt *Payload) {
916 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
917 APFloat NaN = APFloat::getSNaN(Semantics, Negative, Payload);
918 Constant *C = get(Ty->getContext(), NaN);
919
920 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
921 return ConstantVector::getSplat(VTy->getElementCount(), C);
922
923 return C;
924 }
925
getNegativeZero(Type * Ty)926 Constant *ConstantFP::getNegativeZero(Type *Ty) {
927 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
928 APFloat NegZero = APFloat::getZero(Semantics, /*Negative=*/true);
929 Constant *C = get(Ty->getContext(), NegZero);
930
931 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
932 return ConstantVector::getSplat(VTy->getElementCount(), C);
933
934 return C;
935 }
936
937
getZeroValueForNegation(Type * Ty)938 Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
939 if (Ty->isFPOrFPVectorTy())
940 return getNegativeZero(Ty);
941
942 return Constant::getNullValue(Ty);
943 }
944
945
946 // ConstantFP accessors.
get(LLVMContext & Context,const APFloat & V)947 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
948 LLVMContextImpl* pImpl = Context.pImpl;
949
950 std::unique_ptr<ConstantFP> &Slot = pImpl->FPConstants[V];
951
952 if (!Slot) {
953 Type *Ty;
954 if (&V.getSemantics() == &APFloat::IEEEhalf())
955 Ty = Type::getHalfTy(Context);
956 else if (&V.getSemantics() == &APFloat::BFloat())
957 Ty = Type::getBFloatTy(Context);
958 else if (&V.getSemantics() == &APFloat::IEEEsingle())
959 Ty = Type::getFloatTy(Context);
960 else if (&V.getSemantics() == &APFloat::IEEEdouble())
961 Ty = Type::getDoubleTy(Context);
962 else if (&V.getSemantics() == &APFloat::x87DoubleExtended())
963 Ty = Type::getX86_FP80Ty(Context);
964 else if (&V.getSemantics() == &APFloat::IEEEquad())
965 Ty = Type::getFP128Ty(Context);
966 else {
967 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble() &&
968 "Unknown FP format");
969 Ty = Type::getPPC_FP128Ty(Context);
970 }
971 Slot.reset(new ConstantFP(Ty, V));
972 }
973
974 return Slot.get();
975 }
976
getInfinity(Type * Ty,bool Negative)977 Constant *ConstantFP::getInfinity(Type *Ty, bool Negative) {
978 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
979 Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
980
981 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
982 return ConstantVector::getSplat(VTy->getElementCount(), C);
983
984 return C;
985 }
986
ConstantFP(Type * Ty,const APFloat & V)987 ConstantFP::ConstantFP(Type *Ty, const APFloat &V)
988 : ConstantData(Ty, ConstantFPVal), Val(V) {
989 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
990 "FP type Mismatch");
991 }
992
isExactlyValue(const APFloat & V) const993 bool ConstantFP::isExactlyValue(const APFloat &V) const {
994 return Val.bitwiseIsEqual(V);
995 }
996
997 /// Remove the constant from the constant table.
destroyConstantImpl()998 void ConstantFP::destroyConstantImpl() {
999 llvm_unreachable("You can't ConstantFP->destroyConstantImpl()!");
1000 }
1001
1002 //===----------------------------------------------------------------------===//
1003 // ConstantAggregateZero Implementation
1004 //===----------------------------------------------------------------------===//
1005
getSequentialElement() const1006 Constant *ConstantAggregateZero::getSequentialElement() const {
1007 if (auto *AT = dyn_cast<ArrayType>(getType()))
1008 return Constant::getNullValue(AT->getElementType());
1009 return Constant::getNullValue(cast<VectorType>(getType())->getElementType());
1010 }
1011
getStructElement(unsigned Elt) const1012 Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
1013 return Constant::getNullValue(getType()->getStructElementType(Elt));
1014 }
1015
getElementValue(Constant * C) const1016 Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
1017 if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
1018 return getSequentialElement();
1019 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
1020 }
1021
getElementValue(unsigned Idx) const1022 Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
1023 if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
1024 return getSequentialElement();
1025 return getStructElement(Idx);
1026 }
1027
getNumElements() const1028 unsigned ConstantAggregateZero::getNumElements() const {
1029 Type *Ty = getType();
1030 if (auto *AT = dyn_cast<ArrayType>(Ty))
1031 return AT->getNumElements();
1032 if (auto *VT = dyn_cast<VectorType>(Ty))
1033 return VT->getNumElements();
1034 return Ty->getStructNumElements();
1035 }
1036
1037 //===----------------------------------------------------------------------===//
1038 // UndefValue Implementation
1039 //===----------------------------------------------------------------------===//
1040
getSequentialElement() const1041 UndefValue *UndefValue::getSequentialElement() const {
1042 if (ArrayType *ATy = dyn_cast<ArrayType>(getType()))
1043 return UndefValue::get(ATy->getElementType());
1044 return UndefValue::get(cast<VectorType>(getType())->getElementType());
1045 }
1046
getStructElement(unsigned Elt) const1047 UndefValue *UndefValue::getStructElement(unsigned Elt) const {
1048 return UndefValue::get(getType()->getStructElementType(Elt));
1049 }
1050
getElementValue(Constant * C) const1051 UndefValue *UndefValue::getElementValue(Constant *C) const {
1052 if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
1053 return getSequentialElement();
1054 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
1055 }
1056
getElementValue(unsigned Idx) const1057 UndefValue *UndefValue::getElementValue(unsigned Idx) const {
1058 if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
1059 return getSequentialElement();
1060 return getStructElement(Idx);
1061 }
1062
getNumElements() const1063 unsigned UndefValue::getNumElements() const {
1064 Type *Ty = getType();
1065 if (auto *AT = dyn_cast<ArrayType>(Ty))
1066 return AT->getNumElements();
1067 if (auto *VT = dyn_cast<VectorType>(Ty))
1068 return VT->getNumElements();
1069 return Ty->getStructNumElements();
1070 }
1071
1072 //===----------------------------------------------------------------------===//
1073 // ConstantXXX Classes
1074 //===----------------------------------------------------------------------===//
1075
1076 template <typename ItTy, typename EltTy>
rangeOnlyContains(ItTy Start,ItTy End,EltTy Elt)1077 static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
1078 for (; Start != End; ++Start)
1079 if (*Start != Elt)
1080 return false;
1081 return true;
1082 }
1083
1084 template <typename SequentialTy, typename ElementTy>
getIntSequenceIfElementsMatch(ArrayRef<Constant * > V)1085 static Constant *getIntSequenceIfElementsMatch(ArrayRef<Constant *> V) {
1086 assert(!V.empty() && "Cannot get empty int sequence.");
1087
1088 SmallVector<ElementTy, 16> Elts;
1089 for (Constant *C : V)
1090 if (auto *CI = dyn_cast<ConstantInt>(C))
1091 Elts.push_back(CI->getZExtValue());
1092 else
1093 return nullptr;
1094 return SequentialTy::get(V[0]->getContext(), Elts);
1095 }
1096
1097 template <typename SequentialTy, typename ElementTy>
getFPSequenceIfElementsMatch(ArrayRef<Constant * > V)1098 static Constant *getFPSequenceIfElementsMatch(ArrayRef<Constant *> V) {
1099 assert(!V.empty() && "Cannot get empty FP sequence.");
1100
1101 SmallVector<ElementTy, 16> Elts;
1102 for (Constant *C : V)
1103 if (auto *CFP = dyn_cast<ConstantFP>(C))
1104 Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
1105 else
1106 return nullptr;
1107 return SequentialTy::getFP(V[0]->getType(), Elts);
1108 }
1109
1110 template <typename SequenceTy>
getSequenceIfElementsMatch(Constant * C,ArrayRef<Constant * > V)1111 static Constant *getSequenceIfElementsMatch(Constant *C,
1112 ArrayRef<Constant *> V) {
1113 // We speculatively build the elements here even if it turns out that there is
1114 // a constantexpr or something else weird, since it is so uncommon for that to
1115 // happen.
1116 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
1117 if (CI->getType()->isIntegerTy(8))
1118 return getIntSequenceIfElementsMatch<SequenceTy, uint8_t>(V);
1119 else if (CI->getType()->isIntegerTy(16))
1120 return getIntSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
1121 else if (CI->getType()->isIntegerTy(32))
1122 return getIntSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
1123 else if (CI->getType()->isIntegerTy(64))
1124 return getIntSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
1125 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1126 if (CFP->getType()->isHalfTy() || CFP->getType()->isBFloatTy())
1127 return getFPSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
1128 else if (CFP->getType()->isFloatTy())
1129 return getFPSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
1130 else if (CFP->getType()->isDoubleTy())
1131 return getFPSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
1132 }
1133
1134 return nullptr;
1135 }
1136
ConstantAggregate(Type * T,ValueTy VT,ArrayRef<Constant * > V)1137 ConstantAggregate::ConstantAggregate(Type *T, ValueTy VT,
1138 ArrayRef<Constant *> V)
1139 : Constant(T, VT, OperandTraits<ConstantAggregate>::op_end(this) - V.size(),
1140 V.size()) {
1141 llvm::copy(V, op_begin());
1142
1143 // Check that types match, unless this is an opaque struct.
1144 if (auto *ST = dyn_cast<StructType>(T)) {
1145 if (ST->isOpaque())
1146 return;
1147 for (unsigned I = 0, E = V.size(); I != E; ++I)
1148 assert(V[I]->getType() == ST->getTypeAtIndex(I) &&
1149 "Initializer for struct element doesn't match!");
1150 }
1151 }
1152
ConstantArray(ArrayType * T,ArrayRef<Constant * > V)1153 ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
1154 : ConstantAggregate(T, ConstantArrayVal, V) {
1155 assert(V.size() == T->getNumElements() &&
1156 "Invalid initializer for constant array");
1157 }
1158
get(ArrayType * Ty,ArrayRef<Constant * > V)1159 Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
1160 if (Constant *C = getImpl(Ty, V))
1161 return C;
1162 return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
1163 }
1164
getImpl(ArrayType * Ty,ArrayRef<Constant * > V)1165 Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
1166 // Empty arrays are canonicalized to ConstantAggregateZero.
1167 if (V.empty())
1168 return ConstantAggregateZero::get(Ty);
1169
1170 for (unsigned i = 0, e = V.size(); i != e; ++i) {
1171 assert(V[i]->getType() == Ty->getElementType() &&
1172 "Wrong type in array element initializer");
1173 }
1174
1175 // If this is an all-zero array, return a ConstantAggregateZero object. If
1176 // all undef, return an UndefValue, if "all simple", then return a
1177 // ConstantDataArray.
1178 Constant *C = V[0];
1179 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
1180 return UndefValue::get(Ty);
1181
1182 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
1183 return ConstantAggregateZero::get(Ty);
1184
1185 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1186 // the element type is compatible with ConstantDataVector. If so, use it.
1187 if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
1188 return getSequenceIfElementsMatch<ConstantDataArray>(C, V);
1189
1190 // Otherwise, we really do want to create a ConstantArray.
1191 return nullptr;
1192 }
1193
getTypeForElements(LLVMContext & Context,ArrayRef<Constant * > V,bool Packed)1194 StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
1195 ArrayRef<Constant*> V,
1196 bool Packed) {
1197 unsigned VecSize = V.size();
1198 SmallVector<Type*, 16> EltTypes(VecSize);
1199 for (unsigned i = 0; i != VecSize; ++i)
1200 EltTypes[i] = V[i]->getType();
1201
1202 return StructType::get(Context, EltTypes, Packed);
1203 }
1204
1205
getTypeForElements(ArrayRef<Constant * > V,bool Packed)1206 StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
1207 bool Packed) {
1208 assert(!V.empty() &&
1209 "ConstantStruct::getTypeForElements cannot be called on empty list");
1210 return getTypeForElements(V[0]->getContext(), V, Packed);
1211 }
1212
ConstantStruct(StructType * T,ArrayRef<Constant * > V)1213 ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
1214 : ConstantAggregate(T, ConstantStructVal, V) {
1215 assert((T->isOpaque() || V.size() == T->getNumElements()) &&
1216 "Invalid initializer for constant struct");
1217 }
1218
1219 // ConstantStruct accessors.
get(StructType * ST,ArrayRef<Constant * > V)1220 Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
1221 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
1222 "Incorrect # elements specified to ConstantStruct::get");
1223
1224 // Create a ConstantAggregateZero value if all elements are zeros.
1225 bool isZero = true;
1226 bool isUndef = false;
1227
1228 if (!V.empty()) {
1229 isUndef = isa<UndefValue>(V[0]);
1230 isZero = V[0]->isNullValue();
1231 if (isUndef || isZero) {
1232 for (unsigned i = 0, e = V.size(); i != e; ++i) {
1233 if (!V[i]->isNullValue())
1234 isZero = false;
1235 if (!isa<UndefValue>(V[i]))
1236 isUndef = false;
1237 }
1238 }
1239 }
1240 if (isZero)
1241 return ConstantAggregateZero::get(ST);
1242 if (isUndef)
1243 return UndefValue::get(ST);
1244
1245 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
1246 }
1247
ConstantVector(VectorType * T,ArrayRef<Constant * > V)1248 ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
1249 : ConstantAggregate(T, ConstantVectorVal, V) {
1250 assert(V.size() == T->getNumElements() &&
1251 "Invalid initializer for constant vector");
1252 }
1253
1254 // ConstantVector accessors.
get(ArrayRef<Constant * > V)1255 Constant *ConstantVector::get(ArrayRef<Constant*> V) {
1256 if (Constant *C = getImpl(V))
1257 return C;
1258 auto *Ty = FixedVectorType::get(V.front()->getType(), V.size());
1259 return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
1260 }
1261
getImpl(ArrayRef<Constant * > V)1262 Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
1263 assert(!V.empty() && "Vectors can't be empty");
1264 auto *T = FixedVectorType::get(V.front()->getType(), V.size());
1265
1266 // If this is an all-undef or all-zero vector, return a
1267 // ConstantAggregateZero or UndefValue.
1268 Constant *C = V[0];
1269 bool isZero = C->isNullValue();
1270 bool isUndef = isa<UndefValue>(C);
1271
1272 if (isZero || isUndef) {
1273 for (unsigned i = 1, e = V.size(); i != e; ++i)
1274 if (V[i] != C) {
1275 isZero = isUndef = false;
1276 break;
1277 }
1278 }
1279
1280 if (isZero)
1281 return ConstantAggregateZero::get(T);
1282 if (isUndef)
1283 return UndefValue::get(T);
1284
1285 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1286 // the element type is compatible with ConstantDataVector. If so, use it.
1287 if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
1288 return getSequenceIfElementsMatch<ConstantDataVector>(C, V);
1289
1290 // Otherwise, the element type isn't compatible with ConstantDataVector, or
1291 // the operand list contains a ConstantExpr or something else strange.
1292 return nullptr;
1293 }
1294
getSplat(ElementCount EC,Constant * V)1295 Constant *ConstantVector::getSplat(ElementCount EC, Constant *V) {
1296 if (!EC.Scalable) {
1297 // If this splat is compatible with ConstantDataVector, use it instead of
1298 // ConstantVector.
1299 if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
1300 ConstantDataSequential::isElementTypeCompatible(V->getType()))
1301 return ConstantDataVector::getSplat(EC.Min, V);
1302
1303 SmallVector<Constant *, 32> Elts(EC.Min, V);
1304 return get(Elts);
1305 }
1306
1307 Type *VTy = VectorType::get(V->getType(), EC);
1308
1309 if (V->isNullValue())
1310 return ConstantAggregateZero::get(VTy);
1311 else if (isa<UndefValue>(V))
1312 return UndefValue::get(VTy);
1313
1314 Type *I32Ty = Type::getInt32Ty(VTy->getContext());
1315
1316 // Move scalar into vector.
1317 Constant *UndefV = UndefValue::get(VTy);
1318 V = ConstantExpr::getInsertElement(UndefV, V, ConstantInt::get(I32Ty, 0));
1319 // Build shuffle mask to perform the splat.
1320 SmallVector<int, 8> Zeros(EC.Min, 0);
1321 // Splat.
1322 return ConstantExpr::getShuffleVector(V, UndefV, Zeros);
1323 }
1324
get(LLVMContext & Context)1325 ConstantTokenNone *ConstantTokenNone::get(LLVMContext &Context) {
1326 LLVMContextImpl *pImpl = Context.pImpl;
1327 if (!pImpl->TheNoneToken)
1328 pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));
1329 return pImpl->TheNoneToken.get();
1330 }
1331
1332 /// Remove the constant from the constant table.
destroyConstantImpl()1333 void ConstantTokenNone::destroyConstantImpl() {
1334 llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");
1335 }
1336
1337 // Utility function for determining if a ConstantExpr is a CastOp or not. This
1338 // can't be inline because we don't want to #include Instruction.h into
1339 // Constant.h
isCast() const1340 bool ConstantExpr::isCast() const {
1341 return Instruction::isCast(getOpcode());
1342 }
1343
isCompare() const1344 bool ConstantExpr::isCompare() const {
1345 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
1346 }
1347
isGEPWithNoNotionalOverIndexing() const1348 bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
1349 if (getOpcode() != Instruction::GetElementPtr) return false;
1350
1351 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
1352 User::const_op_iterator OI = std::next(this->op_begin());
1353
1354 // The remaining indices may be compile-time known integers within the bounds
1355 // of the corresponding notional static array types.
1356 for (; GEPI != E; ++GEPI, ++OI) {
1357 if (isa<UndefValue>(*OI))
1358 continue;
1359 auto *CI = dyn_cast<ConstantInt>(*OI);
1360 if (!CI || (GEPI.isBoundedSequential() &&
1361 (CI->getValue().getActiveBits() > 64 ||
1362 CI->getZExtValue() >= GEPI.getSequentialNumElements())))
1363 return false;
1364 }
1365
1366 // All the indices checked out.
1367 return true;
1368 }
1369
hasIndices() const1370 bool ConstantExpr::hasIndices() const {
1371 return getOpcode() == Instruction::ExtractValue ||
1372 getOpcode() == Instruction::InsertValue;
1373 }
1374
getIndices() const1375 ArrayRef<unsigned> ConstantExpr::getIndices() const {
1376 if (const ExtractValueConstantExpr *EVCE =
1377 dyn_cast<ExtractValueConstantExpr>(this))
1378 return EVCE->Indices;
1379
1380 return cast<InsertValueConstantExpr>(this)->Indices;
1381 }
1382
getPredicate() const1383 unsigned ConstantExpr::getPredicate() const {
1384 return cast<CompareConstantExpr>(this)->predicate;
1385 }
1386
getShuffleMask() const1387 ArrayRef<int> ConstantExpr::getShuffleMask() const {
1388 return cast<ShuffleVectorConstantExpr>(this)->ShuffleMask;
1389 }
1390
getShuffleMaskForBitcode() const1391 Constant *ConstantExpr::getShuffleMaskForBitcode() const {
1392 return cast<ShuffleVectorConstantExpr>(this)->ShuffleMaskForBitcode;
1393 }
1394
1395 Constant *
getWithOperandReplaced(unsigned OpNo,Constant * Op) const1396 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
1397 assert(Op->getType() == getOperand(OpNo)->getType() &&
1398 "Replacing operand with value of different type!");
1399 if (getOperand(OpNo) == Op)
1400 return const_cast<ConstantExpr*>(this);
1401
1402 SmallVector<Constant*, 8> NewOps;
1403 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1404 NewOps.push_back(i == OpNo ? Op : getOperand(i));
1405
1406 return getWithOperands(NewOps);
1407 }
1408
getWithOperands(ArrayRef<Constant * > Ops,Type * Ty,bool OnlyIfReduced,Type * SrcTy) const1409 Constant *ConstantExpr::getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
1410 bool OnlyIfReduced, Type *SrcTy) const {
1411 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
1412
1413 // If no operands changed return self.
1414 if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
1415 return const_cast<ConstantExpr*>(this);
1416
1417 Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
1418 switch (getOpcode()) {
1419 case Instruction::Trunc:
1420 case Instruction::ZExt:
1421 case Instruction::SExt:
1422 case Instruction::FPTrunc:
1423 case Instruction::FPExt:
1424 case Instruction::UIToFP:
1425 case Instruction::SIToFP:
1426 case Instruction::FPToUI:
1427 case Instruction::FPToSI:
1428 case Instruction::PtrToInt:
1429 case Instruction::IntToPtr:
1430 case Instruction::BitCast:
1431 case Instruction::AddrSpaceCast:
1432 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
1433 case Instruction::Select:
1434 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2], OnlyIfReducedTy);
1435 case Instruction::InsertElement:
1436 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
1437 OnlyIfReducedTy);
1438 case Instruction::ExtractElement:
1439 return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
1440 case Instruction::InsertValue:
1441 return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices(),
1442 OnlyIfReducedTy);
1443 case Instruction::ExtractValue:
1444 return ConstantExpr::getExtractValue(Ops[0], getIndices(), OnlyIfReducedTy);
1445 case Instruction::ShuffleVector:
1446 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], getShuffleMask(),
1447 OnlyIfReducedTy);
1448 case Instruction::GetElementPtr: {
1449 auto *GEPO = cast<GEPOperator>(this);
1450 assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));
1451 return ConstantExpr::getGetElementPtr(
1452 SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),
1453 GEPO->isInBounds(), GEPO->getInRangeIndex(), OnlyIfReducedTy);
1454 }
1455 case Instruction::ICmp:
1456 case Instruction::FCmp:
1457 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1],
1458 OnlyIfReducedTy);
1459 default:
1460 assert(getNumOperands() == 2 && "Must be binary operator?");
1461 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData,
1462 OnlyIfReducedTy);
1463 }
1464 }
1465
1466
1467 //===----------------------------------------------------------------------===//
1468 // isValueValidForType implementations
1469
isValueValidForType(Type * Ty,uint64_t Val)1470 bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
1471 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1472 if (Ty->isIntegerTy(1))
1473 return Val == 0 || Val == 1;
1474 return isUIntN(NumBits, Val);
1475 }
1476
isValueValidForType(Type * Ty,int64_t Val)1477 bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
1478 unsigned NumBits = Ty->getIntegerBitWidth();
1479 if (Ty->isIntegerTy(1))
1480 return Val == 0 || Val == 1 || Val == -1;
1481 return isIntN(NumBits, Val);
1482 }
1483
isValueValidForType(Type * Ty,const APFloat & Val)1484 bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
1485 // convert modifies in place, so make a copy.
1486 APFloat Val2 = APFloat(Val);
1487 bool losesInfo;
1488 switch (Ty->getTypeID()) {
1489 default:
1490 return false; // These can't be represented as floating point!
1491
1492 // FIXME rounding mode needs to be more flexible
1493 case Type::HalfTyID: {
1494 if (&Val2.getSemantics() == &APFloat::IEEEhalf())
1495 return true;
1496 Val2.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &losesInfo);
1497 return !losesInfo;
1498 }
1499 case Type::BFloatTyID: {
1500 if (&Val2.getSemantics() == &APFloat::BFloat())
1501 return true;
1502 Val2.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven, &losesInfo);
1503 return !losesInfo;
1504 }
1505 case Type::FloatTyID: {
1506 if (&Val2.getSemantics() == &APFloat::IEEEsingle())
1507 return true;
1508 Val2.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &losesInfo);
1509 return !losesInfo;
1510 }
1511 case Type::DoubleTyID: {
1512 if (&Val2.getSemantics() == &APFloat::IEEEhalf() ||
1513 &Val2.getSemantics() == &APFloat::BFloat() ||
1514 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1515 &Val2.getSemantics() == &APFloat::IEEEdouble())
1516 return true;
1517 Val2.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &losesInfo);
1518 return !losesInfo;
1519 }
1520 case Type::X86_FP80TyID:
1521 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1522 &Val2.getSemantics() == &APFloat::BFloat() ||
1523 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1524 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1525 &Val2.getSemantics() == &APFloat::x87DoubleExtended();
1526 case Type::FP128TyID:
1527 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1528 &Val2.getSemantics() == &APFloat::BFloat() ||
1529 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1530 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1531 &Val2.getSemantics() == &APFloat::IEEEquad();
1532 case Type::PPC_FP128TyID:
1533 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1534 &Val2.getSemantics() == &APFloat::BFloat() ||
1535 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1536 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1537 &Val2.getSemantics() == &APFloat::PPCDoubleDouble();
1538 }
1539 }
1540
1541
1542 //===----------------------------------------------------------------------===//
1543 // Factory Function Implementation
1544
get(Type * Ty)1545 ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
1546 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
1547 "Cannot create an aggregate zero of non-aggregate type!");
1548
1549 std::unique_ptr<ConstantAggregateZero> &Entry =
1550 Ty->getContext().pImpl->CAZConstants[Ty];
1551 if (!Entry)
1552 Entry.reset(new ConstantAggregateZero(Ty));
1553
1554 return Entry.get();
1555 }
1556
1557 /// Remove the constant from the constant table.
destroyConstantImpl()1558 void ConstantAggregateZero::destroyConstantImpl() {
1559 getContext().pImpl->CAZConstants.erase(getType());
1560 }
1561
1562 /// Remove the constant from the constant table.
destroyConstantImpl()1563 void ConstantArray::destroyConstantImpl() {
1564 getType()->getContext().pImpl->ArrayConstants.remove(this);
1565 }
1566
1567
1568 //---- ConstantStruct::get() implementation...
1569 //
1570
1571 /// Remove the constant from the constant table.
destroyConstantImpl()1572 void ConstantStruct::destroyConstantImpl() {
1573 getType()->getContext().pImpl->StructConstants.remove(this);
1574 }
1575
1576 /// Remove the constant from the constant table.
destroyConstantImpl()1577 void ConstantVector::destroyConstantImpl() {
1578 getType()->getContext().pImpl->VectorConstants.remove(this);
1579 }
1580
getSplatValue(bool AllowUndefs) const1581 Constant *Constant::getSplatValue(bool AllowUndefs) const {
1582 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1583 if (isa<ConstantAggregateZero>(this))
1584 return getNullValue(cast<VectorType>(getType())->getElementType());
1585 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
1586 return CV->getSplatValue();
1587 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1588 return CV->getSplatValue(AllowUndefs);
1589
1590 // Check if this is a constant expression splat of the form returned by
1591 // ConstantVector::getSplat()
1592 const auto *Shuf = dyn_cast<ConstantExpr>(this);
1593 if (Shuf && Shuf->getOpcode() == Instruction::ShuffleVector &&
1594 isa<UndefValue>(Shuf->getOperand(1))) {
1595
1596 const auto *IElt = dyn_cast<ConstantExpr>(Shuf->getOperand(0));
1597 if (IElt && IElt->getOpcode() == Instruction::InsertElement &&
1598 isa<UndefValue>(IElt->getOperand(0))) {
1599
1600 ArrayRef<int> Mask = Shuf->getShuffleMask();
1601 Constant *SplatVal = IElt->getOperand(1);
1602 ConstantInt *Index = dyn_cast<ConstantInt>(IElt->getOperand(2));
1603
1604 if (Index && Index->getValue() == 0 &&
1605 std::all_of(Mask.begin(), Mask.end(), [](int I) { return I == 0; }))
1606 return SplatVal;
1607 }
1608 }
1609
1610 return nullptr;
1611 }
1612
getSplatValue(bool AllowUndefs) const1613 Constant *ConstantVector::getSplatValue(bool AllowUndefs) const {
1614 // Check out first element.
1615 Constant *Elt = getOperand(0);
1616 // Then make sure all remaining elements point to the same value.
1617 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1618 Constant *OpC = getOperand(I);
1619 if (OpC == Elt)
1620 continue;
1621
1622 // Strict mode: any mismatch is not a splat.
1623 if (!AllowUndefs)
1624 return nullptr;
1625
1626 // Allow undefs mode: ignore undefined elements.
1627 if (isa<UndefValue>(OpC))
1628 continue;
1629
1630 // If we do not have a defined element yet, use the current operand.
1631 if (isa<UndefValue>(Elt))
1632 Elt = OpC;
1633
1634 if (OpC != Elt)
1635 return nullptr;
1636 }
1637 return Elt;
1638 }
1639
getUniqueInteger() const1640 const APInt &Constant::getUniqueInteger() const {
1641 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1642 return CI->getValue();
1643 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1644 const Constant *C = this->getAggregateElement(0U);
1645 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1646 return cast<ConstantInt>(C)->getValue();
1647 }
1648
1649 //---- ConstantPointerNull::get() implementation.
1650 //
1651
get(PointerType * Ty)1652 ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
1653 std::unique_ptr<ConstantPointerNull> &Entry =
1654 Ty->getContext().pImpl->CPNConstants[Ty];
1655 if (!Entry)
1656 Entry.reset(new ConstantPointerNull(Ty));
1657
1658 return Entry.get();
1659 }
1660
1661 /// Remove the constant from the constant table.
destroyConstantImpl()1662 void ConstantPointerNull::destroyConstantImpl() {
1663 getContext().pImpl->CPNConstants.erase(getType());
1664 }
1665
get(Type * Ty)1666 UndefValue *UndefValue::get(Type *Ty) {
1667 std::unique_ptr<UndefValue> &Entry = Ty->getContext().pImpl->UVConstants[Ty];
1668 if (!Entry)
1669 Entry.reset(new UndefValue(Ty));
1670
1671 return Entry.get();
1672 }
1673
1674 /// Remove the constant from the constant table.
destroyConstantImpl()1675 void UndefValue::destroyConstantImpl() {
1676 // Free the constant and any dangling references to it.
1677 getContext().pImpl->UVConstants.erase(getType());
1678 }
1679
get(BasicBlock * BB)1680 BlockAddress *BlockAddress::get(BasicBlock *BB) {
1681 assert(BB->getParent() && "Block must have a parent");
1682 return get(BB->getParent(), BB);
1683 }
1684
get(Function * F,BasicBlock * BB)1685 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1686 BlockAddress *&BA =
1687 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1688 if (!BA)
1689 BA = new BlockAddress(F, BB);
1690
1691 assert(BA->getFunction() == F && "Basic block moved between functions");
1692 return BA;
1693 }
1694
BlockAddress(Function * F,BasicBlock * BB)1695 BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1696 : Constant(Type::getInt8PtrTy(F->getContext(), F->getAddressSpace()),
1697 Value::BlockAddressVal, &Op<0>(), 2) {
1698 setOperand(0, F);
1699 setOperand(1, BB);
1700 BB->AdjustBlockAddressRefCount(1);
1701 }
1702
lookup(const BasicBlock * BB)1703 BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
1704 if (!BB->hasAddressTaken())
1705 return nullptr;
1706
1707 const Function *F = BB->getParent();
1708 assert(F && "Block must have a parent");
1709 BlockAddress *BA =
1710 F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB));
1711 assert(BA && "Refcount and block address map disagree!");
1712 return BA;
1713 }
1714
1715 /// Remove the constant from the constant table.
destroyConstantImpl()1716 void BlockAddress::destroyConstantImpl() {
1717 getFunction()->getType()->getContext().pImpl
1718 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1719 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1720 }
1721
handleOperandChangeImpl(Value * From,Value * To)1722 Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To) {
1723 // This could be replacing either the Basic Block or the Function. In either
1724 // case, we have to remove the map entry.
1725 Function *NewF = getFunction();
1726 BasicBlock *NewBB = getBasicBlock();
1727
1728 if (From == NewF)
1729 NewF = cast<Function>(To->stripPointerCasts());
1730 else {
1731 assert(From == NewBB && "From does not match any operand");
1732 NewBB = cast<BasicBlock>(To);
1733 }
1734
1735 // See if the 'new' entry already exists, if not, just update this in place
1736 // and return early.
1737 BlockAddress *&NewBA =
1738 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1739 if (NewBA)
1740 return NewBA;
1741
1742 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1743
1744 // Remove the old entry, this can't cause the map to rehash (just a
1745 // tombstone will get added).
1746 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1747 getBasicBlock()));
1748 NewBA = this;
1749 setOperand(0, NewF);
1750 setOperand(1, NewBB);
1751 getBasicBlock()->AdjustBlockAddressRefCount(1);
1752
1753 // If we just want to keep the existing value, then return null.
1754 // Callers know that this means we shouldn't delete this value.
1755 return nullptr;
1756 }
1757
1758 //---- ConstantExpr::get() implementations.
1759 //
1760
1761 /// This is a utility function to handle folding of casts and lookup of the
1762 /// cast in the ExprConstants map. It is used by the various get* methods below.
getFoldedCast(Instruction::CastOps opc,Constant * C,Type * Ty,bool OnlyIfReduced=false)1763 static Constant *getFoldedCast(Instruction::CastOps opc, Constant *C, Type *Ty,
1764 bool OnlyIfReduced = false) {
1765 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1766 // Fold a few common cases
1767 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1768 return FC;
1769
1770 if (OnlyIfReduced)
1771 return nullptr;
1772
1773 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1774
1775 // Look up the constant in the table first to ensure uniqueness.
1776 ConstantExprKeyType Key(opc, C);
1777
1778 return pImpl->ExprConstants.getOrCreate(Ty, Key);
1779 }
1780
1781 #if !defined(NDEBUG)
1782 #define assertCastIsValid(op, S, Ty, msg) \
1783 do { \
1784 if (LLVM_UNLIKELY(!CastInst::castIsValid((op), (S), (Ty)))) { \
1785 errs() << msg << ": op=" << ((int)op) << " S = "; \
1786 (S)->getType()->dump(); \
1787 errs() << "Ty = "; \
1788 (Ty)->dump(); \
1789 assert(false && msg); \
1790 } \
1791 } while (false)
1792 #else
1793 #define assertCastIsValid(op, S, Ty, msg) \
1794 assert(CastInst::castIsValid((op), (S), (Ty)) && msg)
1795 #endif
1796
getCast(unsigned oc,Constant * C,Type * Ty,bool OnlyIfReduced)1797 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty,
1798 bool OnlyIfReduced) {
1799 Instruction::CastOps opc = Instruction::CastOps(oc);
1800 assert(Instruction::isCast(opc) && "opcode out of range");
1801 assert(C && Ty && "Null arguments to getCast");
1802 assertCastIsValid(opc, C, Ty, "Invalid constantexpr cast!");
1803
1804 switch (opc) {
1805 default:
1806 llvm_unreachable("Invalid cast opcode");
1807 case Instruction::Trunc:
1808 return getTrunc(C, Ty, OnlyIfReduced);
1809 case Instruction::ZExt:
1810 return getZExt(C, Ty, OnlyIfReduced);
1811 case Instruction::SExt:
1812 return getSExt(C, Ty, OnlyIfReduced);
1813 case Instruction::FPTrunc:
1814 return getFPTrunc(C, Ty, OnlyIfReduced);
1815 case Instruction::FPExt:
1816 return getFPExtend(C, Ty, OnlyIfReduced);
1817 case Instruction::UIToFP:
1818 return getUIToFP(C, Ty, OnlyIfReduced);
1819 case Instruction::SIToFP:
1820 return getSIToFP(C, Ty, OnlyIfReduced);
1821 case Instruction::FPToUI:
1822 return getFPToUI(C, Ty, OnlyIfReduced);
1823 case Instruction::FPToSI:
1824 return getFPToSI(C, Ty, OnlyIfReduced);
1825 case Instruction::PtrToInt:
1826 return getPtrToInt(C, Ty, OnlyIfReduced);
1827 case Instruction::IntToPtr:
1828 return getIntToPtr(C, Ty, OnlyIfReduced);
1829 case Instruction::BitCast:
1830 return getBitCast(C, Ty, OnlyIfReduced);
1831 case Instruction::AddrSpaceCast:
1832 return getAddrSpaceCast(C, Ty, OnlyIfReduced);
1833 }
1834 }
1835
getZExtOrBitCast(Constant * C,Type * Ty)1836 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
1837 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1838 return getBitCast(C, Ty);
1839 return getZExt(C, Ty);
1840 }
1841
getSExtOrBitCast(Constant * C,Type * Ty)1842 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
1843 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1844 return getBitCast(C, Ty);
1845 return getSExt(C, Ty);
1846 }
1847
getTruncOrBitCast(Constant * C,Type * Ty)1848 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
1849 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1850 return getBitCast(C, Ty);
1851 return getTrunc(C, Ty);
1852 }
1853
getPointerCast(Constant * S,Type * Ty)1854 Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
1855 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1856 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
1857 "Invalid cast");
1858
1859 if (Ty->isIntOrIntVectorTy())
1860 return getPtrToInt(S, Ty);
1861
1862 unsigned SrcAS = S->getType()->getPointerAddressSpace();
1863 if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
1864 return getAddrSpaceCast(S, Ty);
1865
1866 return getBitCast(S, Ty);
1867 }
1868
getPointerBitCastOrAddrSpaceCast(Constant * S,Type * Ty)1869 Constant *ConstantExpr::getPointerBitCastOrAddrSpaceCast(Constant *S,
1870 Type *Ty) {
1871 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1872 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
1873
1874 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
1875 return getAddrSpaceCast(S, Ty);
1876
1877 return getBitCast(S, Ty);
1878 }
1879
getIntegerCast(Constant * C,Type * Ty,bool isSigned)1880 Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty, bool isSigned) {
1881 assert(C->getType()->isIntOrIntVectorTy() &&
1882 Ty->isIntOrIntVectorTy() && "Invalid cast");
1883 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1884 unsigned DstBits = Ty->getScalarSizeInBits();
1885 Instruction::CastOps opcode =
1886 (SrcBits == DstBits ? Instruction::BitCast :
1887 (SrcBits > DstBits ? Instruction::Trunc :
1888 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1889 return getCast(opcode, C, Ty);
1890 }
1891
getFPCast(Constant * C,Type * Ty)1892 Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
1893 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1894 "Invalid cast");
1895 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1896 unsigned DstBits = Ty->getScalarSizeInBits();
1897 if (SrcBits == DstBits)
1898 return C; // Avoid a useless cast
1899 Instruction::CastOps opcode =
1900 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1901 return getCast(opcode, C, Ty);
1902 }
1903
getTrunc(Constant * C,Type * Ty,bool OnlyIfReduced)1904 Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
1905 if (C->getType() == Ty)
1906 return C;
1907 #ifndef NDEBUG
1908 bool fromVec = isa<VectorType>(C->getType());
1909 bool toVec = isa<VectorType>(Ty);
1910 #endif
1911 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1912 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1913 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
1914 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1915 "SrcTy must be larger than DestTy for Trunc!");
1916
1917 return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
1918 }
1919
getSExt(Constant * C,Type * Ty,bool OnlyIfReduced)1920 Constant *ConstantExpr::getSExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
1921 #ifndef NDEBUG
1922 bool fromVec = isa<VectorType>(C->getType());
1923 bool toVec = isa<VectorType>(Ty);
1924 #endif
1925 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1926 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1927 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
1928 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1929 "SrcTy must be smaller than DestTy for SExt!");
1930
1931 return getFoldedCast(Instruction::SExt, C, Ty, OnlyIfReduced);
1932 }
1933
getZExt(Constant * C,Type * Ty,bool OnlyIfReduced)1934 Constant *ConstantExpr::getZExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
1935 #ifndef NDEBUG
1936 bool fromVec = isa<VectorType>(C->getType());
1937 bool toVec = isa<VectorType>(Ty);
1938 #endif
1939 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1940 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1941 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
1942 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1943 "SrcTy must be smaller than DestTy for ZExt!");
1944
1945 return getFoldedCast(Instruction::ZExt, C, Ty, OnlyIfReduced);
1946 }
1947
getFPTrunc(Constant * C,Type * Ty,bool OnlyIfReduced)1948 Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
1949 #ifndef NDEBUG
1950 bool fromVec = isa<VectorType>(C->getType());
1951 bool toVec = isa<VectorType>(Ty);
1952 #endif
1953 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1954 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1955 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1956 "This is an illegal floating point truncation!");
1957 return getFoldedCast(Instruction::FPTrunc, C, Ty, OnlyIfReduced);
1958 }
1959
getFPExtend(Constant * C,Type * Ty,bool OnlyIfReduced)1960 Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty, bool OnlyIfReduced) {
1961 #ifndef NDEBUG
1962 bool fromVec = isa<VectorType>(C->getType());
1963 bool toVec = isa<VectorType>(Ty);
1964 #endif
1965 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1966 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1967 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1968 "This is an illegal floating point extension!");
1969 return getFoldedCast(Instruction::FPExt, C, Ty, OnlyIfReduced);
1970 }
1971
getUIToFP(Constant * C,Type * Ty,bool OnlyIfReduced)1972 Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
1973 #ifndef NDEBUG
1974 bool fromVec = isa<VectorType>(C->getType());
1975 bool toVec = isa<VectorType>(Ty);
1976 #endif
1977 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1978 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1979 "This is an illegal uint to floating point cast!");
1980 return getFoldedCast(Instruction::UIToFP, C, Ty, OnlyIfReduced);
1981 }
1982
getSIToFP(Constant * C,Type * Ty,bool OnlyIfReduced)1983 Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
1984 #ifndef NDEBUG
1985 bool fromVec = isa<VectorType>(C->getType());
1986 bool toVec = isa<VectorType>(Ty);
1987 #endif
1988 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1989 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1990 "This is an illegal sint to floating point cast!");
1991 return getFoldedCast(Instruction::SIToFP, C, Ty, OnlyIfReduced);
1992 }
1993
getFPToUI(Constant * C,Type * Ty,bool OnlyIfReduced)1994 Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced) {
1995 #ifndef NDEBUG
1996 bool fromVec = isa<VectorType>(C->getType());
1997 bool toVec = isa<VectorType>(Ty);
1998 #endif
1999 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2000 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
2001 "This is an illegal floating point to uint cast!");
2002 return getFoldedCast(Instruction::FPToUI, C, Ty, OnlyIfReduced);
2003 }
2004
getFPToSI(Constant * C,Type * Ty,bool OnlyIfReduced)2005 Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced) {
2006 #ifndef NDEBUG
2007 bool fromVec = isa<VectorType>(C->getType());
2008 bool toVec = isa<VectorType>(Ty);
2009 #endif
2010 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2011 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
2012 "This is an illegal floating point to sint cast!");
2013 return getFoldedCast(Instruction::FPToSI, C, Ty, OnlyIfReduced);
2014 }
2015
getPtrToInt(Constant * C,Type * DstTy,bool OnlyIfReduced)2016 Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy,
2017 bool OnlyIfReduced) {
2018 assert(C->getType()->isPtrOrPtrVectorTy() &&
2019 "PtrToInt source must be pointer or pointer vector");
2020 assert(DstTy->isIntOrIntVectorTy() &&
2021 "PtrToInt destination must be integer or integer vector");
2022 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2023 if (isa<VectorType>(C->getType()))
2024 assert(cast<VectorType>(C->getType())->getNumElements() ==
2025 cast<VectorType>(DstTy)->getNumElements() &&
2026 "Invalid cast between a different number of vector elements");
2027 if (C->getType()->getPointerAddressSpace() == 200) { // FIXME: hardcoded AS200
2028 assert(DstTy->getIntegerBitWidth() <= 64);
2029 }
2030 return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
2031 }
2032
getIntToPtr(Constant * C,Type * DstTy,bool OnlyIfReduced)2033 Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy,
2034 bool OnlyIfReduced) {
2035 assert(C->getType()->isIntOrIntVectorTy() &&
2036 "IntToPtr source must be integer or integer vector");
2037 assert(DstTy->isPtrOrPtrVectorTy() &&
2038 "IntToPtr destination must be a pointer or pointer vector");
2039 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2040 if (isa<VectorType>(C->getType()))
2041 assert(cast<VectorType>(C->getType())->getNumElements() ==
2042 cast<VectorType>(DstTy)->getNumElements() &&
2043 "Invalid cast between a different number of vector elements");
2044 if (DstTy->getPointerAddressSpace() == 200) { // FIXME: hardcoded AS200
2045 assert(C->getType()->getIntegerBitWidth() <= 64);
2046 }
2047 return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
2048 }
2049
getBitCast(Constant * C,Type * DstTy,bool OnlyIfReduced)2050 Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy,
2051 bool OnlyIfReduced) {
2052 assertCastIsValid(Instruction::BitCast, C, DstTy,
2053 "Invalid constantexpr bitcast!");
2054
2055 // It is common to ask for a bitcast of a value to its own type, handle this
2056 // speedily.
2057 if (C->getType() == DstTy) return C;
2058
2059 return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
2060 }
2061
getAddrSpaceCast(Constant * C,Type * DstTy,bool OnlyIfReduced)2062 Constant *ConstantExpr::getAddrSpaceCast(Constant *C, Type *DstTy,
2063 bool OnlyIfReduced) {
2064 assertCastIsValid(Instruction::AddrSpaceCast, C, DstTy,
2065 "Invalid constantexpr addrspacecast!");
2066
2067 // Canonicalize addrspacecasts between different pointer types by first
2068 // bitcasting the pointer type and then converting the address space.
2069 PointerType *SrcScalarTy = cast<PointerType>(C->getType()->getScalarType());
2070 PointerType *DstScalarTy = cast<PointerType>(DstTy->getScalarType());
2071 Type *DstElemTy = DstScalarTy->getElementType();
2072 if (SrcScalarTy->getElementType() != DstElemTy) {
2073 Type *MidTy = PointerType::get(DstElemTy, SrcScalarTy->getAddressSpace());
2074 if (VectorType *VT = dyn_cast<VectorType>(DstTy)) {
2075 // Handle vectors of pointers.
2076 MidTy = FixedVectorType::get(MidTy, VT->getNumElements());
2077 }
2078 C = getBitCast(C, MidTy);
2079 }
2080 return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
2081 }
2082
get(unsigned Opcode,Constant * C,unsigned Flags,Type * OnlyIfReducedTy)2083 Constant *ConstantExpr::get(unsigned Opcode, Constant *C, unsigned Flags,
2084 Type *OnlyIfReducedTy) {
2085 // Check the operands for consistency first.
2086 assert(Instruction::isUnaryOp(Opcode) &&
2087 "Invalid opcode in unary constant expression");
2088
2089 #ifndef NDEBUG
2090 switch (Opcode) {
2091 case Instruction::FNeg:
2092 assert(C->getType()->isFPOrFPVectorTy() &&
2093 "Tried to create a floating-point operation on a "
2094 "non-floating-point type!");
2095 break;
2096 default:
2097 break;
2098 }
2099 #endif
2100
2101 if (Constant *FC = ConstantFoldUnaryInstruction(Opcode, C))
2102 return FC;
2103
2104 if (OnlyIfReducedTy == C->getType())
2105 return nullptr;
2106
2107 Constant *ArgVec[] = { C };
2108 ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
2109
2110 LLVMContextImpl *pImpl = C->getContext().pImpl;
2111 return pImpl->ExprConstants.getOrCreate(C->getType(), Key);
2112 }
2113
get(unsigned Opcode,Constant * C1,Constant * C2,unsigned Flags,Type * OnlyIfReducedTy)2114 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
2115 unsigned Flags, Type *OnlyIfReducedTy) {
2116 // Check the operands for consistency first.
2117 assert(Instruction::isBinaryOp(Opcode) &&
2118 "Invalid opcode in binary constant expression");
2119 assert(C1->getType() == C2->getType() &&
2120 "Operand types in binary constant expression should match");
2121
2122 #ifndef NDEBUG
2123 switch (Opcode) {
2124 case Instruction::Add:
2125 case Instruction::Sub:
2126 case Instruction::Mul:
2127 case Instruction::UDiv:
2128 case Instruction::SDiv:
2129 case Instruction::URem:
2130 case Instruction::SRem:
2131 assert(C1->getType()->isIntOrIntVectorTy() &&
2132 "Tried to create an integer operation on a non-integer type!");
2133 break;
2134 case Instruction::FAdd:
2135 case Instruction::FSub:
2136 case Instruction::FMul:
2137 case Instruction::FDiv:
2138 case Instruction::FRem:
2139 assert(C1->getType()->isFPOrFPVectorTy() &&
2140 "Tried to create a floating-point operation on a "
2141 "non-floating-point type!");
2142 break;
2143 case Instruction::And:
2144 case Instruction::Or:
2145 case Instruction::Xor:
2146 assert(C1->getType()->isIntOrIntVectorTy() &&
2147 "Tried to create a logical operation on a non-integral type!");
2148 break;
2149 case Instruction::Shl:
2150 case Instruction::LShr:
2151 case Instruction::AShr:
2152 assert(C1->getType()->isIntOrIntVectorTy() &&
2153 "Tried to create a shift operation on a non-integer type!");
2154 break;
2155 default:
2156 break;
2157 }
2158 #endif
2159
2160 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
2161 return FC;
2162
2163 if (OnlyIfReducedTy == C1->getType())
2164 return nullptr;
2165
2166 Constant *ArgVec[] = { C1, C2 };
2167 ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
2168
2169 LLVMContextImpl *pImpl = C1->getContext().pImpl;
2170 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
2171 }
2172
getSizeOf(Type * Ty)2173 Constant *ConstantExpr::getSizeOf(Type* Ty) {
2174 // sizeof is implemented as: (i64) gep (Ty*)null, 1
2175 // Note that a non-inbounds gep is used, as null isn't within any object.
2176 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
2177 Constant *GEP = getGetElementPtr(
2178 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
2179 return getPtrToInt(GEP,
2180 Type::getInt64Ty(Ty->getContext()));
2181 }
2182
getAlignOf(Type * Ty)2183 Constant *ConstantExpr::getAlignOf(Type* Ty) {
2184 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
2185 // Note that a non-inbounds gep is used, as null isn't within any object.
2186 Type *AligningTy = StructType::get(Type::getInt1Ty(Ty->getContext()), Ty);
2187 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo(0));
2188 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
2189 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
2190 Constant *Indices[2] = { Zero, One };
2191 Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
2192 return getPtrToInt(GEP,
2193 Type::getInt64Ty(Ty->getContext()));
2194 }
2195
getOffsetOf(StructType * STy,unsigned FieldNo)2196 Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
2197 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
2198 FieldNo));
2199 }
2200
getOffsetOf(Type * Ty,Constant * FieldNo)2201 Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
2202 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
2203 // Note that a non-inbounds gep is used, as null isn't within any object.
2204 Constant *GEPIdx[] = {
2205 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
2206 FieldNo
2207 };
2208 Constant *GEP = getGetElementPtr(
2209 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
2210 return getPtrToInt(GEP,
2211 Type::getInt64Ty(Ty->getContext()));
2212 }
2213
getCompare(unsigned short Predicate,Constant * C1,Constant * C2,bool OnlyIfReduced)2214 Constant *ConstantExpr::getCompare(unsigned short Predicate, Constant *C1,
2215 Constant *C2, bool OnlyIfReduced) {
2216 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2217
2218 switch (Predicate) {
2219 default: llvm_unreachable("Invalid CmpInst predicate");
2220 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
2221 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
2222 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
2223 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
2224 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
2225 case CmpInst::FCMP_TRUE:
2226 return getFCmp(Predicate, C1, C2, OnlyIfReduced);
2227
2228 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
2229 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
2230 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
2231 case CmpInst::ICMP_SLE:
2232 return getICmp(Predicate, C1, C2, OnlyIfReduced);
2233 }
2234 }
2235
getSelect(Constant * C,Constant * V1,Constant * V2,Type * OnlyIfReducedTy)2236 Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2,
2237 Type *OnlyIfReducedTy) {
2238 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
2239
2240 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
2241 return SC; // Fold common cases
2242
2243 if (OnlyIfReducedTy == V1->getType())
2244 return nullptr;
2245
2246 Constant *ArgVec[] = { C, V1, V2 };
2247 ConstantExprKeyType Key(Instruction::Select, ArgVec);
2248
2249 LLVMContextImpl *pImpl = C->getContext().pImpl;
2250 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
2251 }
2252
getGetElementPtr(Type * Ty,Constant * C,ArrayRef<Value * > Idxs,bool InBounds,Optional<unsigned> InRangeIndex,Type * OnlyIfReducedTy)2253 Constant *ConstantExpr::getGetElementPtr(Type *Ty, Constant *C,
2254 ArrayRef<Value *> Idxs, bool InBounds,
2255 Optional<unsigned> InRangeIndex,
2256 Type *OnlyIfReducedTy) {
2257 if (!Ty)
2258 Ty = cast<PointerType>(C->getType()->getScalarType())->getElementType();
2259 else
2260 assert(Ty ==
2261 cast<PointerType>(C->getType()->getScalarType())->getElementType());
2262
2263 if (Constant *FC =
2264 ConstantFoldGetElementPtr(Ty, C, InBounds, InRangeIndex, Idxs))
2265 return FC; // Fold a few common cases.
2266
2267 // Get the result type of the getelementptr!
2268 Type *DestTy = GetElementPtrInst::getIndexedType(Ty, Idxs);
2269 assert(DestTy && "GEP indices invalid!");
2270 unsigned AS = C->getType()->getPointerAddressSpace();
2271 Type *ReqTy = DestTy->getPointerTo(AS);
2272
2273 ElementCount EltCount = {0, false};
2274 if (VectorType *VecTy = dyn_cast<VectorType>(C->getType()))
2275 EltCount = VecTy->getElementCount();
2276 else
2277 for (auto Idx : Idxs)
2278 if (VectorType *VecTy = dyn_cast<VectorType>(Idx->getType()))
2279 EltCount = VecTy->getElementCount();
2280
2281 if (EltCount.Min != 0)
2282 ReqTy = VectorType::get(ReqTy, EltCount);
2283
2284 if (OnlyIfReducedTy == ReqTy)
2285 return nullptr;
2286
2287 // Look up the constant in the table first to ensure uniqueness
2288 std::vector<Constant*> ArgVec;
2289 ArgVec.reserve(1 + Idxs.size());
2290 ArgVec.push_back(C);
2291 auto GTI = gep_type_begin(Ty, Idxs), GTE = gep_type_end(Ty, Idxs);
2292 for (; GTI != GTE; ++GTI) {
2293 auto *Idx = cast<Constant>(GTI.getOperand());
2294 assert(
2295 (!isa<VectorType>(Idx->getType()) ||
2296 cast<VectorType>(Idx->getType())->getElementCount() == EltCount) &&
2297 "getelementptr index type missmatch");
2298
2299 if (GTI.isStruct() && Idx->getType()->isVectorTy()) {
2300 Idx = Idx->getSplatValue();
2301 } else if (GTI.isSequential() && EltCount.Min != 0 &&
2302 !Idx->getType()->isVectorTy()) {
2303 Idx = ConstantVector::getSplat(EltCount, Idx);
2304 }
2305 ArgVec.push_back(Idx);
2306 }
2307
2308 unsigned SubClassOptionalData = InBounds ? GEPOperator::IsInBounds : 0;
2309 if (InRangeIndex && *InRangeIndex < 63)
2310 SubClassOptionalData |= (*InRangeIndex + 1) << 1;
2311 const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
2312 SubClassOptionalData, None, None, Ty);
2313
2314 LLVMContextImpl *pImpl = C->getContext().pImpl;
2315 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2316 }
2317
getICmp(unsigned short pred,Constant * LHS,Constant * RHS,bool OnlyIfReduced)2318 Constant *ConstantExpr::getICmp(unsigned short pred, Constant *LHS,
2319 Constant *RHS, bool OnlyIfReduced) {
2320 assert(LHS->getType() == RHS->getType());
2321 assert(CmpInst::isIntPredicate((CmpInst::Predicate)pred) &&
2322 "Invalid ICmp Predicate");
2323
2324 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2325 return FC; // Fold a few common cases...
2326
2327 if (OnlyIfReduced)
2328 return nullptr;
2329
2330 // Look up the constant in the table first to ensure uniqueness
2331 Constant *ArgVec[] = { LHS, RHS };
2332 // Get the key type with both the opcode and predicate
2333 const ConstantExprKeyType Key(Instruction::ICmp, ArgVec, pred);
2334
2335 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2336 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
2337 ResultTy = VectorType::get(ResultTy, VT->getElementCount());
2338
2339 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
2340 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
2341 }
2342
getFCmp(unsigned short pred,Constant * LHS,Constant * RHS,bool OnlyIfReduced)2343 Constant *ConstantExpr::getFCmp(unsigned short pred, Constant *LHS,
2344 Constant *RHS, bool OnlyIfReduced) {
2345 assert(LHS->getType() == RHS->getType());
2346 assert(CmpInst::isFPPredicate((CmpInst::Predicate)pred) &&
2347 "Invalid FCmp Predicate");
2348
2349 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2350 return FC; // Fold a few common cases...
2351
2352 if (OnlyIfReduced)
2353 return nullptr;
2354
2355 // Look up the constant in the table first to ensure uniqueness
2356 Constant *ArgVec[] = { LHS, RHS };
2357 // Get the key type with both the opcode and predicate
2358 const ConstantExprKeyType Key(Instruction::FCmp, ArgVec, pred);
2359
2360 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2361 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
2362 ResultTy = VectorType::get(ResultTy, VT->getElementCount());
2363
2364 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
2365 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
2366 }
2367
getExtractElement(Constant * Val,Constant * Idx,Type * OnlyIfReducedTy)2368 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx,
2369 Type *OnlyIfReducedTy) {
2370 assert(Val->getType()->isVectorTy() &&
2371 "Tried to create extractelement operation on non-vector type!");
2372 assert(Idx->getType()->isIntegerTy() &&
2373 "Extractelement index must be an integer type!");
2374
2375 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
2376 return FC; // Fold a few common cases.
2377
2378 Type *ReqTy = cast<VectorType>(Val->getType())->getElementType();
2379 if (OnlyIfReducedTy == ReqTy)
2380 return nullptr;
2381
2382 // Look up the constant in the table first to ensure uniqueness
2383 Constant *ArgVec[] = { Val, Idx };
2384 const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
2385
2386 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2387 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2388 }
2389
getInsertElement(Constant * Val,Constant * Elt,Constant * Idx,Type * OnlyIfReducedTy)2390 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2391 Constant *Idx, Type *OnlyIfReducedTy) {
2392 assert(Val->getType()->isVectorTy() &&
2393 "Tried to create insertelement operation on non-vector type!");
2394 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType() &&
2395 "Insertelement types must match!");
2396 assert(Idx->getType()->isIntegerTy() &&
2397 "Insertelement index must be i32 type!");
2398
2399 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2400 return FC; // Fold a few common cases.
2401
2402 if (OnlyIfReducedTy == Val->getType())
2403 return nullptr;
2404
2405 // Look up the constant in the table first to ensure uniqueness
2406 Constant *ArgVec[] = { Val, Elt, Idx };
2407 const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
2408
2409 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2410 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
2411 }
2412
getShuffleVector(Constant * V1,Constant * V2,ArrayRef<int> Mask,Type * OnlyIfReducedTy)2413 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2414 ArrayRef<int> Mask,
2415 Type *OnlyIfReducedTy) {
2416 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2417 "Invalid shuffle vector constant expr operands!");
2418
2419 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2420 return FC; // Fold a few common cases.
2421
2422 unsigned NElts = Mask.size();
2423 auto V1VTy = cast<VectorType>(V1->getType());
2424 Type *EltTy = V1VTy->getElementType();
2425 bool TypeIsScalable = isa<ScalableVectorType>(V1VTy);
2426 Type *ShufTy = VectorType::get(EltTy, NElts, TypeIsScalable);
2427
2428 if (OnlyIfReducedTy == ShufTy)
2429 return nullptr;
2430
2431 // Look up the constant in the table first to ensure uniqueness
2432 Constant *ArgVec[] = {V1, V2};
2433 ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec, 0, 0, None, Mask);
2434
2435 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2436 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
2437 }
2438
getInsertValue(Constant * Agg,Constant * Val,ArrayRef<unsigned> Idxs,Type * OnlyIfReducedTy)2439 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2440 ArrayRef<unsigned> Idxs,
2441 Type *OnlyIfReducedTy) {
2442 assert(Agg->getType()->isFirstClassType() &&
2443 "Non-first-class type for constant insertvalue expression");
2444
2445 assert(ExtractValueInst::getIndexedType(Agg->getType(),
2446 Idxs) == Val->getType() &&
2447 "insertvalue indices invalid!");
2448 Type *ReqTy = Val->getType();
2449
2450 if (Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs))
2451 return FC;
2452
2453 if (OnlyIfReducedTy == ReqTy)
2454 return nullptr;
2455
2456 Constant *ArgVec[] = { Agg, Val };
2457 const ConstantExprKeyType Key(Instruction::InsertValue, ArgVec, 0, 0, Idxs);
2458
2459 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2460 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2461 }
2462
getExtractValue(Constant * Agg,ArrayRef<unsigned> Idxs,Type * OnlyIfReducedTy)2463 Constant *ConstantExpr::getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs,
2464 Type *OnlyIfReducedTy) {
2465 assert(Agg->getType()->isFirstClassType() &&
2466 "Tried to create extractelement operation on non-first-class type!");
2467
2468 Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
2469 (void)ReqTy;
2470 assert(ReqTy && "extractvalue indices invalid!");
2471
2472 assert(Agg->getType()->isFirstClassType() &&
2473 "Non-first-class type for constant extractvalue expression");
2474 if (Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs))
2475 return FC;
2476
2477 if (OnlyIfReducedTy == ReqTy)
2478 return nullptr;
2479
2480 Constant *ArgVec[] = { Agg };
2481 const ConstantExprKeyType Key(Instruction::ExtractValue, ArgVec, 0, 0, Idxs);
2482
2483 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2484 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2485 }
2486
getNeg(Constant * C,bool HasNUW,bool HasNSW)2487 Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
2488 assert(C->getType()->isIntOrIntVectorTy() &&
2489 "Cannot NEG a nonintegral value!");
2490 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
2491 C, HasNUW, HasNSW);
2492 }
2493
getFNeg(Constant * C)2494 Constant *ConstantExpr::getFNeg(Constant *C) {
2495 assert(C->getType()->isFPOrFPVectorTy() &&
2496 "Cannot FNEG a non-floating-point value!");
2497 return get(Instruction::FNeg, C);
2498 }
2499
getNot(Constant * C)2500 Constant *ConstantExpr::getNot(Constant *C) {
2501 assert(C->getType()->isIntOrIntVectorTy() &&
2502 "Cannot NOT a nonintegral value!");
2503 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
2504 }
2505
getAdd(Constant * C1,Constant * C2,bool HasNUW,bool HasNSW)2506 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
2507 bool HasNUW, bool HasNSW) {
2508 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2509 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2510 return get(Instruction::Add, C1, C2, Flags);
2511 }
2512
getFAdd(Constant * C1,Constant * C2)2513 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
2514 return get(Instruction::FAdd, C1, C2);
2515 }
2516
getSub(Constant * C1,Constant * C2,bool HasNUW,bool HasNSW)2517 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
2518 bool HasNUW, bool HasNSW) {
2519 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2520 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2521 return get(Instruction::Sub, C1, C2, Flags);
2522 }
2523
getFSub(Constant * C1,Constant * C2)2524 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
2525 return get(Instruction::FSub, C1, C2);
2526 }
2527
getMul(Constant * C1,Constant * C2,bool HasNUW,bool HasNSW)2528 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
2529 bool HasNUW, bool HasNSW) {
2530 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2531 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2532 return get(Instruction::Mul, C1, C2, Flags);
2533 }
2534
getFMul(Constant * C1,Constant * C2)2535 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
2536 return get(Instruction::FMul, C1, C2);
2537 }
2538
getUDiv(Constant * C1,Constant * C2,bool isExact)2539 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
2540 return get(Instruction::UDiv, C1, C2,
2541 isExact ? PossiblyExactOperator::IsExact : 0);
2542 }
2543
getSDiv(Constant * C1,Constant * C2,bool isExact)2544 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
2545 return get(Instruction::SDiv, C1, C2,
2546 isExact ? PossiblyExactOperator::IsExact : 0);
2547 }
2548
getFDiv(Constant * C1,Constant * C2)2549 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
2550 return get(Instruction::FDiv, C1, C2);
2551 }
2552
getURem(Constant * C1,Constant * C2)2553 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
2554 return get(Instruction::URem, C1, C2);
2555 }
2556
getSRem(Constant * C1,Constant * C2)2557 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
2558 return get(Instruction::SRem, C1, C2);
2559 }
2560
getFRem(Constant * C1,Constant * C2)2561 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
2562 return get(Instruction::FRem, C1, C2);
2563 }
2564
getAnd(Constant * C1,Constant * C2)2565 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
2566 return get(Instruction::And, C1, C2);
2567 }
2568
getOr(Constant * C1,Constant * C2)2569 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
2570 return get(Instruction::Or, C1, C2);
2571 }
2572
getXor(Constant * C1,Constant * C2)2573 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
2574 return get(Instruction::Xor, C1, C2);
2575 }
2576
getShl(Constant * C1,Constant * C2,bool HasNUW,bool HasNSW)2577 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
2578 bool HasNUW, bool HasNSW) {
2579 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2580 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2581 return get(Instruction::Shl, C1, C2, Flags);
2582 }
2583
getLShr(Constant * C1,Constant * C2,bool isExact)2584 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
2585 return get(Instruction::LShr, C1, C2,
2586 isExact ? PossiblyExactOperator::IsExact : 0);
2587 }
2588
getAShr(Constant * C1,Constant * C2,bool isExact)2589 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
2590 return get(Instruction::AShr, C1, C2,
2591 isExact ? PossiblyExactOperator::IsExact : 0);
2592 }
2593
getBinOpIdentity(unsigned Opcode,Type * Ty,bool AllowRHSConstant)2594 Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty,
2595 bool AllowRHSConstant) {
2596 assert(Instruction::isBinaryOp(Opcode) && "Only binops allowed");
2597
2598 // Commutative opcodes: it does not matter if AllowRHSConstant is set.
2599 if (Instruction::isCommutative(Opcode)) {
2600 switch (Opcode) {
2601 case Instruction::Add: // X + 0 = X
2602 case Instruction::Or: // X | 0 = X
2603 case Instruction::Xor: // X ^ 0 = X
2604 return Constant::getNullValue(Ty);
2605 case Instruction::Mul: // X * 1 = X
2606 return ConstantInt::get(Ty, 1);
2607 case Instruction::And: // X & -1 = X
2608 return Constant::getAllOnesValue(Ty);
2609 case Instruction::FAdd: // X + -0.0 = X
2610 // TODO: If the fadd has 'nsz', should we return +0.0?
2611 return ConstantFP::getNegativeZero(Ty);
2612 case Instruction::FMul: // X * 1.0 = X
2613 return ConstantFP::get(Ty, 1.0);
2614 default:
2615 llvm_unreachable("Every commutative binop has an identity constant");
2616 }
2617 }
2618
2619 // Non-commutative opcodes: AllowRHSConstant must be set.
2620 if (!AllowRHSConstant)
2621 return nullptr;
2622
2623 switch (Opcode) {
2624 case Instruction::Sub: // X - 0 = X
2625 case Instruction::Shl: // X << 0 = X
2626 case Instruction::LShr: // X >>u 0 = X
2627 case Instruction::AShr: // X >> 0 = X
2628 case Instruction::FSub: // X - 0.0 = X
2629 return Constant::getNullValue(Ty);
2630 case Instruction::SDiv: // X / 1 = X
2631 case Instruction::UDiv: // X /u 1 = X
2632 return ConstantInt::get(Ty, 1);
2633 case Instruction::FDiv: // X / 1.0 = X
2634 return ConstantFP::get(Ty, 1.0);
2635 default:
2636 return nullptr;
2637 }
2638 }
2639
getBinOpAbsorber(unsigned Opcode,Type * Ty)2640 Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
2641 switch (Opcode) {
2642 default:
2643 // Doesn't have an absorber.
2644 return nullptr;
2645
2646 case Instruction::Or:
2647 return Constant::getAllOnesValue(Ty);
2648
2649 case Instruction::And:
2650 case Instruction::Mul:
2651 return Constant::getNullValue(Ty);
2652 }
2653 }
2654
2655 /// Remove the constant from the constant table.
destroyConstantImpl()2656 void ConstantExpr::destroyConstantImpl() {
2657 getType()->getContext().pImpl->ExprConstants.remove(this);
2658 }
2659
getOpcodeName() const2660 const char *ConstantExpr::getOpcodeName() const {
2661 return Instruction::getOpcodeName(getOpcode());
2662 }
2663
GetElementPtrConstantExpr(Type * SrcElementTy,Constant * C,ArrayRef<Constant * > IdxList,Type * DestTy)2664 GetElementPtrConstantExpr::GetElementPtrConstantExpr(
2665 Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy)
2666 : ConstantExpr(DestTy, Instruction::GetElementPtr,
2667 OperandTraits<GetElementPtrConstantExpr>::op_end(this) -
2668 (IdxList.size() + 1),
2669 IdxList.size() + 1),
2670 SrcElementTy(SrcElementTy),
2671 ResElementTy(GetElementPtrInst::getIndexedType(SrcElementTy, IdxList)) {
2672 Op<0>() = C;
2673 Use *OperandList = getOperandList();
2674 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2675 OperandList[i+1] = IdxList[i];
2676 }
2677
getSourceElementType() const2678 Type *GetElementPtrConstantExpr::getSourceElementType() const {
2679 return SrcElementTy;
2680 }
2681
getResultElementType() const2682 Type *GetElementPtrConstantExpr::getResultElementType() const {
2683 return ResElementTy;
2684 }
2685
2686 //===----------------------------------------------------------------------===//
2687 // ConstantData* implementations
2688
getElementType() const2689 Type *ConstantDataSequential::getElementType() const {
2690 if (ArrayType *ATy = dyn_cast<ArrayType>(getType()))
2691 return ATy->getElementType();
2692 return cast<VectorType>(getType())->getElementType();
2693 }
2694
getRawDataValues() const2695 StringRef ConstantDataSequential::getRawDataValues() const {
2696 return StringRef(DataElements, getNumElements()*getElementByteSize());
2697 }
2698
isElementTypeCompatible(Type * Ty)2699 bool ConstantDataSequential::isElementTypeCompatible(Type *Ty) {
2700 if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() || Ty->isDoubleTy())
2701 return true;
2702 if (auto *IT = dyn_cast<IntegerType>(Ty)) {
2703 switch (IT->getBitWidth()) {
2704 case 8:
2705 case 16:
2706 case 32:
2707 case 64:
2708 return true;
2709 default: break;
2710 }
2711 }
2712 return false;
2713 }
2714
getNumElements() const2715 unsigned ConstantDataSequential::getNumElements() const {
2716 if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2717 return AT->getNumElements();
2718 return cast<VectorType>(getType())->getNumElements();
2719 }
2720
2721
getElementByteSize() const2722 uint64_t ConstantDataSequential::getElementByteSize() const {
2723 return getElementType()->getPrimitiveSizeInBits()/8;
2724 }
2725
2726 /// Return the start of the specified element.
getElementPointer(unsigned Elt) const2727 const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
2728 assert(Elt < getNumElements() && "Invalid Elt");
2729 return DataElements+Elt*getElementByteSize();
2730 }
2731
2732
2733 /// Return true if the array is empty or all zeros.
isAllZeros(StringRef Arr)2734 static bool isAllZeros(StringRef Arr) {
2735 for (char I : Arr)
2736 if (I != 0)
2737 return false;
2738 return true;
2739 }
2740
2741 /// This is the underlying implementation of all of the
2742 /// ConstantDataSequential::get methods. They all thunk down to here, providing
2743 /// the correct element type. We take the bytes in as a StringRef because
2744 /// we *want* an underlying "char*" to avoid TBAA type punning violations.
getImpl(StringRef Elements,Type * Ty)2745 Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
2746 #ifndef NDEBUG
2747 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty))
2748 assert(isElementTypeCompatible(ATy->getElementType()));
2749 else
2750 assert(isElementTypeCompatible(cast<VectorType>(Ty)->getElementType()));
2751 #endif
2752 // If the elements are all zero or there are no elements, return a CAZ, which
2753 // is more dense and canonical.
2754 if (isAllZeros(Elements))
2755 return ConstantAggregateZero::get(Ty);
2756
2757 // Do a lookup to see if we have already formed one of these.
2758 auto &Slot =
2759 *Ty->getContext()
2760 .pImpl->CDSConstants.insert(std::make_pair(Elements, nullptr))
2761 .first;
2762
2763 // The bucket can point to a linked list of different CDS's that have the same
2764 // body but different types. For example, 0,0,0,1 could be a 4 element array
2765 // of i8, or a 1-element array of i32. They'll both end up in the same
2766 /// StringMap bucket, linked up by their Next pointers. Walk the list.
2767 ConstantDataSequential **Entry = &Slot.second;
2768 for (ConstantDataSequential *Node = *Entry; Node;
2769 Entry = &Node->Next, Node = *Entry)
2770 if (Node->getType() == Ty)
2771 return Node;
2772
2773 // Okay, we didn't get a hit. Create a node of the right class, link it in,
2774 // and return it.
2775 if (isa<ArrayType>(Ty))
2776 return *Entry = new ConstantDataArray(Ty, Slot.first().data());
2777
2778 assert(isa<VectorType>(Ty));
2779 return *Entry = new ConstantDataVector(Ty, Slot.first().data());
2780 }
2781
destroyConstantImpl()2782 void ConstantDataSequential::destroyConstantImpl() {
2783 // Remove the constant from the StringMap.
2784 StringMap<ConstantDataSequential*> &CDSConstants =
2785 getType()->getContext().pImpl->CDSConstants;
2786
2787 StringMap<ConstantDataSequential*>::iterator Slot =
2788 CDSConstants.find(getRawDataValues());
2789
2790 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2791
2792 ConstantDataSequential **Entry = &Slot->getValue();
2793
2794 // Remove the entry from the hash table.
2795 if (!(*Entry)->Next) {
2796 // If there is only one value in the bucket (common case) it must be this
2797 // entry, and removing the entry should remove the bucket completely.
2798 assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
2799 getContext().pImpl->CDSConstants.erase(Slot);
2800 } else {
2801 // Otherwise, there are multiple entries linked off the bucket, unlink the
2802 // node we care about but keep the bucket around.
2803 for (ConstantDataSequential *Node = *Entry; ;
2804 Entry = &Node->Next, Node = *Entry) {
2805 assert(Node && "Didn't find entry in its uniquing hash table!");
2806 // If we found our entry, unlink it from the list and we're done.
2807 if (Node == this) {
2808 *Entry = Node->Next;
2809 break;
2810 }
2811 }
2812 }
2813
2814 // If we were part of a list, make sure that we don't delete the list that is
2815 // still owned by the uniquing map.
2816 Next = nullptr;
2817 }
2818
2819 /// getFP() constructors - Return a constant of array type with a float
2820 /// element type taken from argument `ElementType', and count taken from
2821 /// argument `Elts'. The amount of bits of the contained type must match the
2822 /// number of bits of the type contained in the passed in ArrayRef.
2823 /// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
2824 /// that this can return a ConstantAggregateZero object.
getFP(Type * ElementType,ArrayRef<uint16_t> Elts)2825 Constant *ConstantDataArray::getFP(Type *ElementType, ArrayRef<uint16_t> Elts) {
2826 assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&
2827 "Element type is not a 16-bit float type");
2828 Type *Ty = ArrayType::get(ElementType, Elts.size());
2829 const char *Data = reinterpret_cast<const char *>(Elts.data());
2830 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
2831 }
getFP(Type * ElementType,ArrayRef<uint32_t> Elts)2832 Constant *ConstantDataArray::getFP(Type *ElementType, ArrayRef<uint32_t> Elts) {
2833 assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");
2834 Type *Ty = ArrayType::get(ElementType, Elts.size());
2835 const char *Data = reinterpret_cast<const char *>(Elts.data());
2836 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2837 }
getFP(Type * ElementType,ArrayRef<uint64_t> Elts)2838 Constant *ConstantDataArray::getFP(Type *ElementType, ArrayRef<uint64_t> Elts) {
2839 assert(ElementType->isDoubleTy() &&
2840 "Element type is not a 64-bit float type");
2841 Type *Ty = ArrayType::get(ElementType, Elts.size());
2842 const char *Data = reinterpret_cast<const char *>(Elts.data());
2843 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2844 }
2845
getString(LLVMContext & Context,StringRef Str,bool AddNull)2846 Constant *ConstantDataArray::getString(LLVMContext &Context,
2847 StringRef Str, bool AddNull) {
2848 if (!AddNull) {
2849 const uint8_t *Data = Str.bytes_begin();
2850 return get(Context, makeArrayRef(Data, Str.size()));
2851 }
2852
2853 SmallVector<uint8_t, 64> ElementVals;
2854 ElementVals.append(Str.begin(), Str.end());
2855 ElementVals.push_back(0);
2856 return get(Context, ElementVals);
2857 }
2858
2859 /// get() constructors - Return a constant with vector type with an element
2860 /// count and element type matching the ArrayRef passed in. Note that this
2861 /// can return a ConstantAggregateZero object.
get(LLVMContext & Context,ArrayRef<uint8_t> Elts)2862 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
2863 auto *Ty = FixedVectorType::get(Type::getInt8Ty(Context), Elts.size());
2864 const char *Data = reinterpret_cast<const char *>(Elts.data());
2865 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
2866 }
get(LLVMContext & Context,ArrayRef<uint16_t> Elts)2867 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
2868 auto *Ty = FixedVectorType::get(Type::getInt16Ty(Context), Elts.size());
2869 const char *Data = reinterpret_cast<const char *>(Elts.data());
2870 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
2871 }
get(LLVMContext & Context,ArrayRef<uint32_t> Elts)2872 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
2873 auto *Ty = FixedVectorType::get(Type::getInt32Ty(Context), Elts.size());
2874 const char *Data = reinterpret_cast<const char *>(Elts.data());
2875 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2876 }
get(LLVMContext & Context,ArrayRef<uint64_t> Elts)2877 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
2878 auto *Ty = FixedVectorType::get(Type::getInt64Ty(Context), Elts.size());
2879 const char *Data = reinterpret_cast<const char *>(Elts.data());
2880 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2881 }
get(LLVMContext & Context,ArrayRef<float> Elts)2882 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
2883 auto *Ty = FixedVectorType::get(Type::getFloatTy(Context), Elts.size());
2884 const char *Data = reinterpret_cast<const char *>(Elts.data());
2885 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2886 }
get(LLVMContext & Context,ArrayRef<double> Elts)2887 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
2888 auto *Ty = FixedVectorType::get(Type::getDoubleTy(Context), Elts.size());
2889 const char *Data = reinterpret_cast<const char *>(Elts.data());
2890 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2891 }
2892
2893 /// getFP() constructors - Return a constant of vector type with a float
2894 /// element type taken from argument `ElementType', and count taken from
2895 /// argument `Elts'. The amount of bits of the contained type must match the
2896 /// number of bits of the type contained in the passed in ArrayRef.
2897 /// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
2898 /// that this can return a ConstantAggregateZero object.
getFP(Type * ElementType,ArrayRef<uint16_t> Elts)2899 Constant *ConstantDataVector::getFP(Type *ElementType,
2900 ArrayRef<uint16_t> Elts) {
2901 assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&
2902 "Element type is not a 16-bit float type");
2903 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
2904 const char *Data = reinterpret_cast<const char *>(Elts.data());
2905 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
2906 }
getFP(Type * ElementType,ArrayRef<uint32_t> Elts)2907 Constant *ConstantDataVector::getFP(Type *ElementType,
2908 ArrayRef<uint32_t> Elts) {
2909 assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");
2910 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
2911 const char *Data = reinterpret_cast<const char *>(Elts.data());
2912 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2913 }
getFP(Type * ElementType,ArrayRef<uint64_t> Elts)2914 Constant *ConstantDataVector::getFP(Type *ElementType,
2915 ArrayRef<uint64_t> Elts) {
2916 assert(ElementType->isDoubleTy() &&
2917 "Element type is not a 64-bit float type");
2918 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
2919 const char *Data = reinterpret_cast<const char *>(Elts.data());
2920 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2921 }
2922
getSplat(unsigned NumElts,Constant * V)2923 Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
2924 assert(isElementTypeCompatible(V->getType()) &&
2925 "Element type not compatible with ConstantData");
2926 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2927 if (CI->getType()->isIntegerTy(8)) {
2928 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
2929 return get(V->getContext(), Elts);
2930 }
2931 if (CI->getType()->isIntegerTy(16)) {
2932 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
2933 return get(V->getContext(), Elts);
2934 }
2935 if (CI->getType()->isIntegerTy(32)) {
2936 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
2937 return get(V->getContext(), Elts);
2938 }
2939 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
2940 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
2941 return get(V->getContext(), Elts);
2942 }
2943
2944 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2945 if (CFP->getType()->isHalfTy()) {
2946 SmallVector<uint16_t, 16> Elts(
2947 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2948 return getFP(V->getType(), Elts);
2949 }
2950 if (CFP->getType()->isBFloatTy()) {
2951 SmallVector<uint16_t, 16> Elts(
2952 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2953 return getFP(V->getType(), Elts);
2954 }
2955 if (CFP->getType()->isFloatTy()) {
2956 SmallVector<uint32_t, 16> Elts(
2957 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2958 return getFP(V->getType(), Elts);
2959 }
2960 if (CFP->getType()->isDoubleTy()) {
2961 SmallVector<uint64_t, 16> Elts(
2962 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2963 return getFP(V->getType(), Elts);
2964 }
2965 }
2966 return ConstantVector::getSplat({NumElts, false}, V);
2967 }
2968
2969
getElementAsInteger(unsigned Elt) const2970 uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
2971 assert(isa<IntegerType>(getElementType()) &&
2972 "Accessor can only be used when element is an integer");
2973 const char *EltPtr = getElementPointer(Elt);
2974
2975 // The data is stored in host byte order, make sure to cast back to the right
2976 // type to load with the right endianness.
2977 switch (getElementType()->getIntegerBitWidth()) {
2978 default: llvm_unreachable("Invalid bitwidth for CDS");
2979 case 8:
2980 return *reinterpret_cast<const uint8_t *>(EltPtr);
2981 case 16:
2982 return *reinterpret_cast<const uint16_t *>(EltPtr);
2983 case 32:
2984 return *reinterpret_cast<const uint32_t *>(EltPtr);
2985 case 64:
2986 return *reinterpret_cast<const uint64_t *>(EltPtr);
2987 }
2988 }
2989
getElementAsAPInt(unsigned Elt) const2990 APInt ConstantDataSequential::getElementAsAPInt(unsigned Elt) const {
2991 assert(isa<IntegerType>(getElementType()) &&
2992 "Accessor can only be used when element is an integer");
2993 const char *EltPtr = getElementPointer(Elt);
2994
2995 // The data is stored in host byte order, make sure to cast back to the right
2996 // type to load with the right endianness.
2997 switch (getElementType()->getIntegerBitWidth()) {
2998 default: llvm_unreachable("Invalid bitwidth for CDS");
2999 case 8: {
3000 auto EltVal = *reinterpret_cast<const uint8_t *>(EltPtr);
3001 return APInt(8, EltVal);
3002 }
3003 case 16: {
3004 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3005 return APInt(16, EltVal);
3006 }
3007 case 32: {
3008 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
3009 return APInt(32, EltVal);
3010 }
3011 case 64: {
3012 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
3013 return APInt(64, EltVal);
3014 }
3015 }
3016 }
3017
getElementAsAPFloat(unsigned Elt) const3018 APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
3019 const char *EltPtr = getElementPointer(Elt);
3020
3021 switch (getElementType()->getTypeID()) {
3022 default:
3023 llvm_unreachable("Accessor can only be used when element is float/double!");
3024 case Type::HalfTyID: {
3025 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3026 return APFloat(APFloat::IEEEhalf(), APInt(16, EltVal));
3027 }
3028 case Type::BFloatTyID: {
3029 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3030 return APFloat(APFloat::BFloat(), APInt(16, EltVal));
3031 }
3032 case Type::FloatTyID: {
3033 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
3034 return APFloat(APFloat::IEEEsingle(), APInt(32, EltVal));
3035 }
3036 case Type::DoubleTyID: {
3037 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
3038 return APFloat(APFloat::IEEEdouble(), APInt(64, EltVal));
3039 }
3040 }
3041 }
3042
getElementAsFloat(unsigned Elt) const3043 float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
3044 assert(getElementType()->isFloatTy() &&
3045 "Accessor can only be used when element is a 'float'");
3046 return *reinterpret_cast<const float *>(getElementPointer(Elt));
3047 }
3048
getElementAsDouble(unsigned Elt) const3049 double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
3050 assert(getElementType()->isDoubleTy() &&
3051 "Accessor can only be used when element is a 'float'");
3052 return *reinterpret_cast<const double *>(getElementPointer(Elt));
3053 }
3054
getElementAsConstant(unsigned Elt) const3055 Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
3056 if (getElementType()->isHalfTy() || getElementType()->isBFloatTy() ||
3057 getElementType()->isFloatTy() || getElementType()->isDoubleTy())
3058 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
3059
3060 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
3061 }
3062
isString(unsigned CharSize) const3063 bool ConstantDataSequential::isString(unsigned CharSize) const {
3064 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(CharSize);
3065 }
3066
isCString() const3067 bool ConstantDataSequential::isCString() const {
3068 if (!isString())
3069 return false;
3070
3071 StringRef Str = getAsString();
3072
3073 // The last value must be nul.
3074 if (Str.back() != 0) return false;
3075
3076 // Other elements must be non-nul.
3077 return Str.drop_back().find(0) == StringRef::npos;
3078 }
3079
isSplatData() const3080 bool ConstantDataVector::isSplatData() const {
3081 const char *Base = getRawDataValues().data();
3082
3083 // Compare elements 1+ to the 0'th element.
3084 unsigned EltSize = getElementByteSize();
3085 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
3086 if (memcmp(Base, Base+i*EltSize, EltSize))
3087 return false;
3088
3089 return true;
3090 }
3091
isSplat() const3092 bool ConstantDataVector::isSplat() const {
3093 if (!IsSplatSet) {
3094 IsSplatSet = true;
3095 IsSplat = isSplatData();
3096 }
3097 return IsSplat;
3098 }
3099
getSplatValue() const3100 Constant *ConstantDataVector::getSplatValue() const {
3101 // If they're all the same, return the 0th one as a representative.
3102 return isSplat() ? getElementAsConstant(0) : nullptr;
3103 }
3104
3105 //===----------------------------------------------------------------------===//
3106 // handleOperandChange implementations
3107
3108 /// Update this constant array to change uses of
3109 /// 'From' to be uses of 'To'. This must update the uniquing data structures
3110 /// etc.
3111 ///
3112 /// Note that we intentionally replace all uses of From with To here. Consider
3113 /// a large array that uses 'From' 1000 times. By handling this case all here,
3114 /// ConstantArray::handleOperandChange is only invoked once, and that
3115 /// single invocation handles all 1000 uses. Handling them one at a time would
3116 /// work, but would be really slow because it would have to unique each updated
3117 /// array instance.
3118 ///
handleOperandChange(Value * From,Value * To)3119 void Constant::handleOperandChange(Value *From, Value *To) {
3120 Value *Replacement = nullptr;
3121 switch (getValueID()) {
3122 default:
3123 llvm_unreachable("Not a constant!");
3124 #define HANDLE_CONSTANT(Name) \
3125 case Value::Name##Val: \
3126 Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To); \
3127 break;
3128 #include "llvm/IR/Value.def"
3129 }
3130
3131 // If handleOperandChangeImpl returned nullptr, then it handled
3132 // replacing itself and we don't want to delete or replace anything else here.
3133 if (!Replacement)
3134 return;
3135
3136 // I do need to replace this with an existing value.
3137 assert(Replacement != this && "I didn't contain From!");
3138
3139 // Everyone using this now uses the replacement.
3140 replaceAllUsesWith(Replacement);
3141
3142 // Delete the old constant!
3143 destroyConstant();
3144 }
3145
handleOperandChangeImpl(Value * From,Value * To)3146 Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To) {
3147 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3148 Constant *ToC = cast<Constant>(To);
3149
3150 SmallVector<Constant*, 8> Values;
3151 Values.reserve(getNumOperands()); // Build replacement array.
3152
3153 // Fill values with the modified operands of the constant array. Also,
3154 // compute whether this turns into an all-zeros array.
3155 unsigned NumUpdated = 0;
3156
3157 // Keep track of whether all the values in the array are "ToC".
3158 bool AllSame = true;
3159 Use *OperandList = getOperandList();
3160 unsigned OperandNo = 0;
3161 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
3162 Constant *Val = cast<Constant>(O->get());
3163 if (Val == From) {
3164 OperandNo = (O - OperandList);
3165 Val = ToC;
3166 ++NumUpdated;
3167 }
3168 Values.push_back(Val);
3169 AllSame &= Val == ToC;
3170 }
3171
3172 if (AllSame && ToC->isNullValue())
3173 return ConstantAggregateZero::get(getType());
3174
3175 if (AllSame && isa<UndefValue>(ToC))
3176 return UndefValue::get(getType());
3177
3178 // Check for any other type of constant-folding.
3179 if (Constant *C = getImpl(getType(), Values))
3180 return C;
3181
3182 // Update to the new value.
3183 return getContext().pImpl->ArrayConstants.replaceOperandsInPlace(
3184 Values, this, From, ToC, NumUpdated, OperandNo);
3185 }
3186
handleOperandChangeImpl(Value * From,Value * To)3187 Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To) {
3188 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3189 Constant *ToC = cast<Constant>(To);
3190
3191 Use *OperandList = getOperandList();
3192
3193 SmallVector<Constant*, 8> Values;
3194 Values.reserve(getNumOperands()); // Build replacement struct.
3195
3196 // Fill values with the modified operands of the constant struct. Also,
3197 // compute whether this turns into an all-zeros struct.
3198 unsigned NumUpdated = 0;
3199 bool AllSame = true;
3200 unsigned OperandNo = 0;
3201 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
3202 Constant *Val = cast<Constant>(O->get());
3203 if (Val == From) {
3204 OperandNo = (O - OperandList);
3205 Val = ToC;
3206 ++NumUpdated;
3207 }
3208 Values.push_back(Val);
3209 AllSame &= Val == ToC;
3210 }
3211
3212 if (AllSame && ToC->isNullValue())
3213 return ConstantAggregateZero::get(getType());
3214
3215 if (AllSame && isa<UndefValue>(ToC))
3216 return UndefValue::get(getType());
3217
3218 // Update to the new value.
3219 return getContext().pImpl->StructConstants.replaceOperandsInPlace(
3220 Values, this, From, ToC, NumUpdated, OperandNo);
3221 }
3222
handleOperandChangeImpl(Value * From,Value * To)3223 Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To) {
3224 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3225 Constant *ToC = cast<Constant>(To);
3226
3227 SmallVector<Constant*, 8> Values;
3228 Values.reserve(getNumOperands()); // Build replacement array...
3229 unsigned NumUpdated = 0;
3230 unsigned OperandNo = 0;
3231 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3232 Constant *Val = getOperand(i);
3233 if (Val == From) {
3234 OperandNo = i;
3235 ++NumUpdated;
3236 Val = ToC;
3237 }
3238 Values.push_back(Val);
3239 }
3240
3241 if (Constant *C = getImpl(Values))
3242 return C;
3243
3244 // Update to the new value.
3245 return getContext().pImpl->VectorConstants.replaceOperandsInPlace(
3246 Values, this, From, ToC, NumUpdated, OperandNo);
3247 }
3248
handleOperandChangeImpl(Value * From,Value * ToV)3249 Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV) {
3250 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
3251 Constant *To = cast<Constant>(ToV);
3252
3253 SmallVector<Constant*, 8> NewOps;
3254 unsigned NumUpdated = 0;
3255 unsigned OperandNo = 0;
3256 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3257 Constant *Op = getOperand(i);
3258 if (Op == From) {
3259 OperandNo = i;
3260 ++NumUpdated;
3261 Op = To;
3262 }
3263 NewOps.push_back(Op);
3264 }
3265 assert(NumUpdated && "I didn't contain From!");
3266
3267 if (Constant *C = getWithOperands(NewOps, getType(), true))
3268 return C;
3269
3270 // Update to the new value.
3271 return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
3272 NewOps, this, From, To, NumUpdated, OperandNo);
3273 }
3274
getAsInstruction() const3275 Instruction *ConstantExpr::getAsInstruction() const {
3276 SmallVector<Value *, 4> ValueOperands(op_begin(), op_end());
3277 ArrayRef<Value*> Ops(ValueOperands);
3278
3279 switch (getOpcode()) {
3280 case Instruction::Trunc:
3281 case Instruction::ZExt:
3282 case Instruction::SExt:
3283 case Instruction::FPTrunc:
3284 case Instruction::FPExt:
3285 case Instruction::UIToFP:
3286 case Instruction::SIToFP:
3287 case Instruction::FPToUI:
3288 case Instruction::FPToSI:
3289 case Instruction::PtrToInt:
3290 case Instruction::IntToPtr:
3291 case Instruction::BitCast:
3292 case Instruction::AddrSpaceCast:
3293 return CastInst::Create((Instruction::CastOps)getOpcode(),
3294 Ops[0], getType());
3295 case Instruction::Select:
3296 return SelectInst::Create(Ops[0], Ops[1], Ops[2]);
3297 case Instruction::InsertElement:
3298 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2]);
3299 case Instruction::ExtractElement:
3300 return ExtractElementInst::Create(Ops[0], Ops[1]);
3301 case Instruction::InsertValue:
3302 return InsertValueInst::Create(Ops[0], Ops[1], getIndices());
3303 case Instruction::ExtractValue:
3304 return ExtractValueInst::Create(Ops[0], getIndices());
3305 case Instruction::ShuffleVector:
3306 return new ShuffleVectorInst(Ops[0], Ops[1], getShuffleMask());
3307
3308 case Instruction::GetElementPtr: {
3309 const auto *GO = cast<GEPOperator>(this);
3310 if (GO->isInBounds())
3311 return GetElementPtrInst::CreateInBounds(GO->getSourceElementType(),
3312 Ops[0], Ops.slice(1));
3313 return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
3314 Ops.slice(1));
3315 }
3316 case Instruction::ICmp:
3317 case Instruction::FCmp:
3318 return CmpInst::Create((Instruction::OtherOps)getOpcode(),
3319 (CmpInst::Predicate)getPredicate(), Ops[0], Ops[1]);
3320 case Instruction::FNeg:
3321 return UnaryOperator::Create((Instruction::UnaryOps)getOpcode(), Ops[0]);
3322 default:
3323 assert(getNumOperands() == 2 && "Must be binary operator?");
3324 BinaryOperator *BO =
3325 BinaryOperator::Create((Instruction::BinaryOps)getOpcode(),
3326 Ops[0], Ops[1]);
3327 if (isa<OverflowingBinaryOperator>(BO)) {
3328 BO->setHasNoUnsignedWrap(SubclassOptionalData &
3329 OverflowingBinaryOperator::NoUnsignedWrap);
3330 BO->setHasNoSignedWrap(SubclassOptionalData &
3331 OverflowingBinaryOperator::NoSignedWrap);
3332 }
3333 if (isa<PossiblyExactOperator>(BO))
3334 BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);
3335 return BO;
3336 }
3337 }
3338