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