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