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