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