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