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