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