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/Constants.h" 15 #include "LLVMContextImpl.h" 16 #include "ConstantFold.h" 17 #include "llvm/DerivedTypes.h" 18 #include "llvm/GlobalValue.h" 19 #include "llvm/Instructions.h" 20 #include "llvm/Module.h" 21 #include "llvm/Operator.h" 22 #include "llvm/ADT/FoldingSet.h" 23 #include "llvm/ADT/StringExtras.h" 24 #include "llvm/ADT/StringMap.h" 25 #include "llvm/Support/Compiler.h" 26 #include "llvm/Support/Debug.h" 27 #include "llvm/Support/ErrorHandling.h" 28 #include "llvm/Support/ManagedStatic.h" 29 #include "llvm/Support/MathExtras.h" 30 #include "llvm/Support/raw_ostream.h" 31 #include "llvm/Support/GetElementPtrTypeIterator.h" 32 #include "llvm/ADT/DenseMap.h" 33 #include "llvm/ADT/SmallVector.h" 34 #include "llvm/ADT/STLExtras.h" 35 #include <algorithm> 36 #include <cstdarg> 37 using namespace llvm; 38 39 //===----------------------------------------------------------------------===// 40 // Constant Class 41 //===----------------------------------------------------------------------===// 42 43 bool Constant::isNegativeZeroValue() const { 44 // Floating point values have an explicit -0.0 value. 45 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this)) 46 return CFP->isZero() && CFP->isNegative(); 47 48 // Otherwise, just use +0.0. 49 return isNullValue(); 50 } 51 52 bool Constant::isNullValue() const { 53 // 0 is null. 54 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this)) 55 return CI->isZero(); 56 57 // +0.0 is null. 58 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this)) 59 return CFP->isZero() && !CFP->isNegative(); 60 61 // constant zero is zero for aggregates and cpnull is null for pointers. 62 return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this); 63 } 64 65 // Constructor to create a '0' constant of arbitrary type... 66 Constant *Constant::getNullValue(Type *Ty) { 67 switch (Ty->getTypeID()) { 68 case Type::IntegerTyID: 69 return ConstantInt::get(Ty, 0); 70 case Type::FloatTyID: 71 return ConstantFP::get(Ty->getContext(), 72 APFloat::getZero(APFloat::IEEEsingle)); 73 case Type::DoubleTyID: 74 return ConstantFP::get(Ty->getContext(), 75 APFloat::getZero(APFloat::IEEEdouble)); 76 case Type::X86_FP80TyID: 77 return ConstantFP::get(Ty->getContext(), 78 APFloat::getZero(APFloat::x87DoubleExtended)); 79 case Type::FP128TyID: 80 return ConstantFP::get(Ty->getContext(), 81 APFloat::getZero(APFloat::IEEEquad)); 82 case Type::PPC_FP128TyID: 83 return ConstantFP::get(Ty->getContext(), 84 APFloat(APInt::getNullValue(128))); 85 case Type::PointerTyID: 86 return ConstantPointerNull::get(cast<PointerType>(Ty)); 87 case Type::StructTyID: 88 case Type::ArrayTyID: 89 case Type::VectorTyID: 90 return ConstantAggregateZero::get(Ty); 91 default: 92 // Function, Label, or Opaque type? 93 assert(!"Cannot create a null constant of that type!"); 94 return 0; 95 } 96 } 97 98 Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) { 99 Type *ScalarTy = Ty->getScalarType(); 100 101 // Create the base integer constant. 102 Constant *C = ConstantInt::get(Ty->getContext(), V); 103 104 // Convert an integer to a pointer, if necessary. 105 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy)) 106 C = ConstantExpr::getIntToPtr(C, PTy); 107 108 // Broadcast a scalar to a vector, if necessary. 109 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 110 C = ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C)); 111 112 return C; 113 } 114 115 Constant *Constant::getAllOnesValue(Type *Ty) { 116 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty)) 117 return ConstantInt::get(Ty->getContext(), 118 APInt::getAllOnesValue(ITy->getBitWidth())); 119 120 if (Ty->isFloatingPointTy()) { 121 APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(), 122 !Ty->isPPC_FP128Ty()); 123 return ConstantFP::get(Ty->getContext(), FL); 124 } 125 126 SmallVector<Constant*, 16> Elts; 127 VectorType *VTy = cast<VectorType>(Ty); 128 Elts.resize(VTy->getNumElements(), getAllOnesValue(VTy->getElementType())); 129 assert(Elts[0] && "Not a vector integer type!"); 130 return cast<ConstantVector>(ConstantVector::get(Elts)); 131 } 132 133 void Constant::destroyConstantImpl() { 134 // When a Constant is destroyed, there may be lingering 135 // references to the constant by other constants in the constant pool. These 136 // constants are implicitly dependent on the module that is being deleted, 137 // but they don't know that. Because we only find out when the CPV is 138 // deleted, we must now notify all of our users (that should only be 139 // Constants) that they are, in fact, invalid now and should be deleted. 140 // 141 while (!use_empty()) { 142 Value *V = use_back(); 143 #ifndef NDEBUG // Only in -g mode... 144 if (!isa<Constant>(V)) { 145 dbgs() << "While deleting: " << *this 146 << "\n\nUse still stuck around after Def is destroyed: " 147 << *V << "\n\n"; 148 } 149 #endif 150 assert(isa<Constant>(V) && "References remain to Constant being destroyed"); 151 Constant *CV = cast<Constant>(V); 152 CV->destroyConstant(); 153 154 // The constant should remove itself from our use list... 155 assert((use_empty() || use_back() != V) && "Constant not removed!"); 156 } 157 158 // Value has no outstanding references it is safe to delete it now... 159 delete this; 160 } 161 162 /// canTrap - Return true if evaluation of this constant could trap. This is 163 /// true for things like constant expressions that could divide by zero. 164 bool Constant::canTrap() const { 165 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!"); 166 // The only thing that could possibly trap are constant exprs. 167 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this); 168 if (!CE) return false; 169 170 // ConstantExpr traps if any operands can trap. 171 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) 172 if (CE->getOperand(i)->canTrap()) 173 return true; 174 175 // Otherwise, only specific operations can trap. 176 switch (CE->getOpcode()) { 177 default: 178 return false; 179 case Instruction::UDiv: 180 case Instruction::SDiv: 181 case Instruction::FDiv: 182 case Instruction::URem: 183 case Instruction::SRem: 184 case Instruction::FRem: 185 // Div and rem can trap if the RHS is not known to be non-zero. 186 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue()) 187 return true; 188 return false; 189 } 190 } 191 192 /// isConstantUsed - Return true if the constant has users other than constant 193 /// exprs and other dangling things. 194 bool Constant::isConstantUsed() const { 195 for (const_use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) { 196 const Constant *UC = dyn_cast<Constant>(*UI); 197 if (UC == 0 || isa<GlobalValue>(UC)) 198 return true; 199 200 if (UC->isConstantUsed()) 201 return true; 202 } 203 return false; 204 } 205 206 207 208 /// getRelocationInfo - This method classifies the entry according to 209 /// whether or not it may generate a relocation entry. This must be 210 /// conservative, so if it might codegen to a relocatable entry, it should say 211 /// so. The return values are: 212 /// 213 /// NoRelocation: This constant pool entry is guaranteed to never have a 214 /// relocation applied to it (because it holds a simple constant like 215 /// '4'). 216 /// LocalRelocation: This entry has relocations, but the entries are 217 /// guaranteed to be resolvable by the static linker, so the dynamic 218 /// linker will never see them. 219 /// GlobalRelocations: This entry may have arbitrary relocations. 220 /// 221 /// FIXME: This really should not be in VMCore. 222 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const { 223 if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) { 224 if (GV->hasLocalLinkage() || GV->hasHiddenVisibility()) 225 return LocalRelocation; // Local to this file/library. 226 return GlobalRelocations; // Global reference. 227 } 228 229 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this)) 230 return BA->getFunction()->getRelocationInfo(); 231 232 // While raw uses of blockaddress need to be relocated, differences between 233 // two of them don't when they are for labels in the same function. This is a 234 // common idiom when creating a table for the indirect goto extension, so we 235 // handle it efficiently here. 236 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) 237 if (CE->getOpcode() == Instruction::Sub) { 238 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0)); 239 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1)); 240 if (LHS && RHS && 241 LHS->getOpcode() == Instruction::PtrToInt && 242 RHS->getOpcode() == Instruction::PtrToInt && 243 isa<BlockAddress>(LHS->getOperand(0)) && 244 isa<BlockAddress>(RHS->getOperand(0)) && 245 cast<BlockAddress>(LHS->getOperand(0))->getFunction() == 246 cast<BlockAddress>(RHS->getOperand(0))->getFunction()) 247 return NoRelocation; 248 } 249 250 PossibleRelocationsTy Result = NoRelocation; 251 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) 252 Result = std::max(Result, 253 cast<Constant>(getOperand(i))->getRelocationInfo()); 254 255 return Result; 256 } 257 258 259 /// getVectorElements - This method, which is only valid on constant of vector 260 /// type, returns the elements of the vector in the specified smallvector. 261 /// This handles breaking down a vector undef into undef elements, etc. For 262 /// constant exprs and other cases we can't handle, we return an empty vector. 263 void Constant::getVectorElements(SmallVectorImpl<Constant*> &Elts) const { 264 assert(getType()->isVectorTy() && "Not a vector constant!"); 265 266 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) { 267 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) 268 Elts.push_back(CV->getOperand(i)); 269 return; 270 } 271 272 VectorType *VT = cast<VectorType>(getType()); 273 if (isa<ConstantAggregateZero>(this)) { 274 Elts.assign(VT->getNumElements(), 275 Constant::getNullValue(VT->getElementType())); 276 return; 277 } 278 279 if (isa<UndefValue>(this)) { 280 Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType())); 281 return; 282 } 283 284 // Unknown type, must be constant expr etc. 285 } 286 287 288 /// removeDeadUsersOfConstant - If the specified constantexpr is dead, remove 289 /// it. This involves recursively eliminating any dead users of the 290 /// constantexpr. 291 static bool removeDeadUsersOfConstant(const Constant *C) { 292 if (isa<GlobalValue>(C)) return false; // Cannot remove this 293 294 while (!C->use_empty()) { 295 const Constant *User = dyn_cast<Constant>(C->use_back()); 296 if (!User) return false; // Non-constant usage; 297 if (!removeDeadUsersOfConstant(User)) 298 return false; // Constant wasn't dead 299 } 300 301 const_cast<Constant*>(C)->destroyConstant(); 302 return true; 303 } 304 305 306 /// removeDeadConstantUsers - If there are any dead constant users dangling 307 /// off of this constant, remove them. This method is useful for clients 308 /// that want to check to see if a global is unused, but don't want to deal 309 /// with potentially dead constants hanging off of the globals. 310 void Constant::removeDeadConstantUsers() const { 311 Value::const_use_iterator I = use_begin(), E = use_end(); 312 Value::const_use_iterator LastNonDeadUser = E; 313 while (I != E) { 314 const Constant *User = dyn_cast<Constant>(*I); 315 if (User == 0) { 316 LastNonDeadUser = I; 317 ++I; 318 continue; 319 } 320 321 if (!removeDeadUsersOfConstant(User)) { 322 // If the constant wasn't dead, remember that this was the last live use 323 // and move on to the next constant. 324 LastNonDeadUser = I; 325 ++I; 326 continue; 327 } 328 329 // If the constant was dead, then the iterator is invalidated. 330 if (LastNonDeadUser == E) { 331 I = use_begin(); 332 if (I == E) break; 333 } else { 334 I = LastNonDeadUser; 335 ++I; 336 } 337 } 338 } 339 340 341 342 //===----------------------------------------------------------------------===// 343 // ConstantInt 344 //===----------------------------------------------------------------------===// 345 346 ConstantInt::ConstantInt(IntegerType *Ty, const APInt& V) 347 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) { 348 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type"); 349 } 350 351 ConstantInt *ConstantInt::getTrue(LLVMContext &Context) { 352 LLVMContextImpl *pImpl = Context.pImpl; 353 if (!pImpl->TheTrueVal) 354 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1); 355 return pImpl->TheTrueVal; 356 } 357 358 ConstantInt *ConstantInt::getFalse(LLVMContext &Context) { 359 LLVMContextImpl *pImpl = Context.pImpl; 360 if (!pImpl->TheFalseVal) 361 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0); 362 return pImpl->TheFalseVal; 363 } 364 365 Constant *ConstantInt::getTrue(Type *Ty) { 366 VectorType *VTy = dyn_cast<VectorType>(Ty); 367 if (!VTy) { 368 assert(Ty->isIntegerTy(1) && "True must be i1 or vector of i1."); 369 return ConstantInt::getTrue(Ty->getContext()); 370 } 371 assert(VTy->getElementType()->isIntegerTy(1) && 372 "True must be vector of i1 or i1."); 373 SmallVector<Constant*, 16> Splat(VTy->getNumElements(), 374 ConstantInt::getTrue(Ty->getContext())); 375 return ConstantVector::get(Splat); 376 } 377 378 Constant *ConstantInt::getFalse(Type *Ty) { 379 VectorType *VTy = dyn_cast<VectorType>(Ty); 380 if (!VTy) { 381 assert(Ty->isIntegerTy(1) && "False must be i1 or vector of i1."); 382 return ConstantInt::getFalse(Ty->getContext()); 383 } 384 assert(VTy->getElementType()->isIntegerTy(1) && 385 "False must be vector of i1 or i1."); 386 SmallVector<Constant*, 16> Splat(VTy->getNumElements(), 387 ConstantInt::getFalse(Ty->getContext())); 388 return ConstantVector::get(Splat); 389 } 390 391 392 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap 393 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the 394 // operator== and operator!= to ensure that the DenseMap doesn't attempt to 395 // compare APInt's of different widths, which would violate an APInt class 396 // invariant which generates an assertion. 397 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) { 398 // Get the corresponding integer type for the bit width of the value. 399 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth()); 400 // get an existing value or the insertion position 401 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy); 402 ConstantInt *&Slot = Context.pImpl->IntConstants[Key]; 403 if (!Slot) Slot = new ConstantInt(ITy, V); 404 return Slot; 405 } 406 407 Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) { 408 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned); 409 410 // For vectors, broadcast the value. 411 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 412 return ConstantVector::get(SmallVector<Constant*, 413 16>(VTy->getNumElements(), C)); 414 415 return C; 416 } 417 418 ConstantInt* ConstantInt::get(IntegerType* Ty, uint64_t V, 419 bool isSigned) { 420 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned)); 421 } 422 423 ConstantInt* ConstantInt::getSigned(IntegerType* Ty, int64_t V) { 424 return get(Ty, V, true); 425 } 426 427 Constant *ConstantInt::getSigned(Type *Ty, int64_t V) { 428 return get(Ty, V, true); 429 } 430 431 Constant *ConstantInt::get(Type* Ty, const APInt& V) { 432 ConstantInt *C = get(Ty->getContext(), V); 433 assert(C->getType() == Ty->getScalarType() && 434 "ConstantInt type doesn't match the type implied by its value!"); 435 436 // For vectors, broadcast the value. 437 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 438 return ConstantVector::get( 439 SmallVector<Constant *, 16>(VTy->getNumElements(), C)); 440 441 return C; 442 } 443 444 ConstantInt* ConstantInt::get(IntegerType* Ty, StringRef Str, 445 uint8_t radix) { 446 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix)); 447 } 448 449 //===----------------------------------------------------------------------===// 450 // ConstantFP 451 //===----------------------------------------------------------------------===// 452 453 static const fltSemantics *TypeToFloatSemantics(Type *Ty) { 454 if (Ty->isFloatTy()) 455 return &APFloat::IEEEsingle; 456 if (Ty->isDoubleTy()) 457 return &APFloat::IEEEdouble; 458 if (Ty->isX86_FP80Ty()) 459 return &APFloat::x87DoubleExtended; 460 else if (Ty->isFP128Ty()) 461 return &APFloat::IEEEquad; 462 463 assert(Ty->isPPC_FP128Ty() && "Unknown FP format"); 464 return &APFloat::PPCDoubleDouble; 465 } 466 467 /// get() - This returns a constant fp for the specified value in the 468 /// specified type. This should only be used for simple constant values like 469 /// 2.0/1.0 etc, that are known-valid both as double and as the target format. 470 Constant *ConstantFP::get(Type* Ty, double V) { 471 LLVMContext &Context = Ty->getContext(); 472 473 APFloat FV(V); 474 bool ignored; 475 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()), 476 APFloat::rmNearestTiesToEven, &ignored); 477 Constant *C = get(Context, FV); 478 479 // For vectors, broadcast the value. 480 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 481 return ConstantVector::get( 482 SmallVector<Constant *, 16>(VTy->getNumElements(), C)); 483 484 return C; 485 } 486 487 488 Constant *ConstantFP::get(Type* Ty, StringRef Str) { 489 LLVMContext &Context = Ty->getContext(); 490 491 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str); 492 Constant *C = get(Context, FV); 493 494 // For vectors, broadcast the value. 495 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 496 return ConstantVector::get( 497 SmallVector<Constant *, 16>(VTy->getNumElements(), C)); 498 499 return C; 500 } 501 502 503 ConstantFP* ConstantFP::getNegativeZero(Type* Ty) { 504 LLVMContext &Context = Ty->getContext(); 505 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF(); 506 apf.changeSign(); 507 return get(Context, apf); 508 } 509 510 511 Constant *ConstantFP::getZeroValueForNegation(Type* Ty) { 512 if (VectorType *PTy = dyn_cast<VectorType>(Ty)) 513 if (PTy->getElementType()->isFloatingPointTy()) { 514 SmallVector<Constant*, 16> zeros(PTy->getNumElements(), 515 getNegativeZero(PTy->getElementType())); 516 return ConstantVector::get(zeros); 517 } 518 519 if (Ty->isFloatingPointTy()) 520 return getNegativeZero(Ty); 521 522 return Constant::getNullValue(Ty); 523 } 524 525 526 // ConstantFP accessors. 527 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) { 528 DenseMapAPFloatKeyInfo::KeyTy Key(V); 529 530 LLVMContextImpl* pImpl = Context.pImpl; 531 532 ConstantFP *&Slot = pImpl->FPConstants[Key]; 533 534 if (!Slot) { 535 Type *Ty; 536 if (&V.getSemantics() == &APFloat::IEEEsingle) 537 Ty = Type::getFloatTy(Context); 538 else if (&V.getSemantics() == &APFloat::IEEEdouble) 539 Ty = Type::getDoubleTy(Context); 540 else if (&V.getSemantics() == &APFloat::x87DoubleExtended) 541 Ty = Type::getX86_FP80Ty(Context); 542 else if (&V.getSemantics() == &APFloat::IEEEquad) 543 Ty = Type::getFP128Ty(Context); 544 else { 545 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble && 546 "Unknown FP format"); 547 Ty = Type::getPPC_FP128Ty(Context); 548 } 549 Slot = new ConstantFP(Ty, V); 550 } 551 552 return Slot; 553 } 554 555 ConstantFP *ConstantFP::getInfinity(Type *Ty, bool Negative) { 556 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty); 557 return ConstantFP::get(Ty->getContext(), 558 APFloat::getInf(Semantics, Negative)); 559 } 560 561 ConstantFP::ConstantFP(Type *Ty, const APFloat& V) 562 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) { 563 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) && 564 "FP type Mismatch"); 565 } 566 567 bool ConstantFP::isExactlyValue(const APFloat &V) const { 568 return Val.bitwiseIsEqual(V); 569 } 570 571 //===----------------------------------------------------------------------===// 572 // ConstantXXX Classes 573 //===----------------------------------------------------------------------===// 574 575 576 ConstantArray::ConstantArray(ArrayType *T, 577 const std::vector<Constant*> &V) 578 : Constant(T, ConstantArrayVal, 579 OperandTraits<ConstantArray>::op_end(this) - V.size(), 580 V.size()) { 581 assert(V.size() == T->getNumElements() && 582 "Invalid initializer vector for constant array"); 583 Use *OL = OperandList; 584 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end(); 585 I != E; ++I, ++OL) { 586 Constant *C = *I; 587 assert(C->getType() == T->getElementType() && 588 "Initializer for array element doesn't match array element type!"); 589 *OL = C; 590 } 591 } 592 593 Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) { 594 for (unsigned i = 0, e = V.size(); i != e; ++i) { 595 assert(V[i]->getType() == Ty->getElementType() && 596 "Wrong type in array element initializer"); 597 } 598 LLVMContextImpl *pImpl = Ty->getContext().pImpl; 599 // If this is an all-zero array, return a ConstantAggregateZero object 600 if (!V.empty()) { 601 Constant *C = V[0]; 602 if (!C->isNullValue()) 603 return pImpl->ArrayConstants.getOrCreate(Ty, V); 604 605 for (unsigned i = 1, e = V.size(); i != e; ++i) 606 if (V[i] != C) 607 return pImpl->ArrayConstants.getOrCreate(Ty, V); 608 } 609 610 return ConstantAggregateZero::get(Ty); 611 } 612 613 /// ConstantArray::get(const string&) - Return an array that is initialized to 614 /// contain the specified string. If length is zero then a null terminator is 615 /// added to the specified string so that it may be used in a natural way. 616 /// Otherwise, the length parameter specifies how much of the string to use 617 /// and it won't be null terminated. 618 /// 619 Constant *ConstantArray::get(LLVMContext &Context, StringRef Str, 620 bool AddNull) { 621 std::vector<Constant*> ElementVals; 622 ElementVals.reserve(Str.size() + size_t(AddNull)); 623 for (unsigned i = 0; i < Str.size(); ++i) 624 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), Str[i])); 625 626 // Add a null terminator to the string... 627 if (AddNull) { 628 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), 0)); 629 } 630 631 ArrayType *ATy = ArrayType::get(Type::getInt8Ty(Context), ElementVals.size()); 632 return get(ATy, ElementVals); 633 } 634 635 /// getTypeForElements - Return an anonymous struct type to use for a constant 636 /// with the specified set of elements. The list must not be empty. 637 StructType *ConstantStruct::getTypeForElements(LLVMContext &Context, 638 ArrayRef<Constant*> V, 639 bool Packed) { 640 SmallVector<Type*, 16> EltTypes; 641 for (unsigned i = 0, e = V.size(); i != e; ++i) 642 EltTypes.push_back(V[i]->getType()); 643 644 return StructType::get(Context, EltTypes, Packed); 645 } 646 647 648 StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V, 649 bool Packed) { 650 assert(!V.empty() && 651 "ConstantStruct::getTypeForElements cannot be called on empty list"); 652 return getTypeForElements(V[0]->getContext(), V, Packed); 653 } 654 655 656 ConstantStruct::ConstantStruct(StructType *T, 657 const std::vector<Constant*> &V) 658 : Constant(T, ConstantStructVal, 659 OperandTraits<ConstantStruct>::op_end(this) - V.size(), 660 V.size()) { 661 assert((T->isOpaque() || V.size() == T->getNumElements()) && 662 "Invalid initializer vector for constant structure"); 663 Use *OL = OperandList; 664 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end(); 665 I != E; ++I, ++OL) { 666 Constant *C = *I; 667 assert((T->isOpaque() || C->getType() == T->getElementType(I-V.begin())) && 668 "Initializer for struct element doesn't match struct element type!"); 669 *OL = C; 670 } 671 } 672 673 // ConstantStruct accessors. 674 Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) { 675 // Create a ConstantAggregateZero value if all elements are zeros. 676 for (unsigned i = 0, e = V.size(); i != e; ++i) 677 if (!V[i]->isNullValue()) 678 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V); 679 680 assert((ST->isOpaque() || ST->getNumElements() == V.size()) && 681 "Incorrect # elements specified to ConstantStruct::get"); 682 return ConstantAggregateZero::get(ST); 683 } 684 685 Constant* ConstantStruct::get(StructType *T, ...) { 686 va_list ap; 687 SmallVector<Constant*, 8> Values; 688 va_start(ap, T); 689 while (Constant *Val = va_arg(ap, llvm::Constant*)) 690 Values.push_back(Val); 691 va_end(ap); 692 return get(T, Values); 693 } 694 695 ConstantVector::ConstantVector(VectorType *T, 696 const std::vector<Constant*> &V) 697 : Constant(T, ConstantVectorVal, 698 OperandTraits<ConstantVector>::op_end(this) - V.size(), 699 V.size()) { 700 Use *OL = OperandList; 701 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end(); 702 I != E; ++I, ++OL) { 703 Constant *C = *I; 704 assert(C->getType() == T->getElementType() && 705 "Initializer for vector element doesn't match vector element type!"); 706 *OL = C; 707 } 708 } 709 710 // ConstantVector accessors. 711 Constant *ConstantVector::get(ArrayRef<Constant*> V) { 712 assert(!V.empty() && "Vectors can't be empty"); 713 VectorType *T = VectorType::get(V.front()->getType(), V.size()); 714 LLVMContextImpl *pImpl = T->getContext().pImpl; 715 716 // If this is an all-undef or all-zero vector, return a 717 // ConstantAggregateZero or UndefValue. 718 Constant *C = V[0]; 719 bool isZero = C->isNullValue(); 720 bool isUndef = isa<UndefValue>(C); 721 722 if (isZero || isUndef) { 723 for (unsigned i = 1, e = V.size(); i != e; ++i) 724 if (V[i] != C) { 725 isZero = isUndef = false; 726 break; 727 } 728 } 729 730 if (isZero) 731 return ConstantAggregateZero::get(T); 732 if (isUndef) 733 return UndefValue::get(T); 734 735 return pImpl->VectorConstants.getOrCreate(T, V); 736 } 737 738 // Utility function for determining if a ConstantExpr is a CastOp or not. This 739 // can't be inline because we don't want to #include Instruction.h into 740 // Constant.h 741 bool ConstantExpr::isCast() const { 742 return Instruction::isCast(getOpcode()); 743 } 744 745 bool ConstantExpr::isCompare() const { 746 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp; 747 } 748 749 bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const { 750 if (getOpcode() != Instruction::GetElementPtr) return false; 751 752 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this); 753 User::const_op_iterator OI = llvm::next(this->op_begin()); 754 755 // Skip the first index, as it has no static limit. 756 ++GEPI; 757 ++OI; 758 759 // The remaining indices must be compile-time known integers within the 760 // bounds of the corresponding notional static array types. 761 for (; GEPI != E; ++GEPI, ++OI) { 762 ConstantInt *CI = dyn_cast<ConstantInt>(*OI); 763 if (!CI) return false; 764 if (ArrayType *ATy = dyn_cast<ArrayType>(*GEPI)) 765 if (CI->getValue().getActiveBits() > 64 || 766 CI->getZExtValue() >= ATy->getNumElements()) 767 return false; 768 } 769 770 // All the indices checked out. 771 return true; 772 } 773 774 bool ConstantExpr::hasIndices() const { 775 return getOpcode() == Instruction::ExtractValue || 776 getOpcode() == Instruction::InsertValue; 777 } 778 779 ArrayRef<unsigned> ConstantExpr::getIndices() const { 780 if (const ExtractValueConstantExpr *EVCE = 781 dyn_cast<ExtractValueConstantExpr>(this)) 782 return EVCE->Indices; 783 784 return cast<InsertValueConstantExpr>(this)->Indices; 785 } 786 787 unsigned ConstantExpr::getPredicate() const { 788 assert(isCompare()); 789 return ((const CompareConstantExpr*)this)->predicate; 790 } 791 792 /// getWithOperandReplaced - Return a constant expression identical to this 793 /// one, but with the specified operand set to the specified value. 794 Constant * 795 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const { 796 assert(OpNo < getNumOperands() && "Operand num is out of range!"); 797 assert(Op->getType() == getOperand(OpNo)->getType() && 798 "Replacing operand with value of different type!"); 799 if (getOperand(OpNo) == Op) 800 return const_cast<ConstantExpr*>(this); 801 802 Constant *Op0, *Op1, *Op2; 803 switch (getOpcode()) { 804 case Instruction::Trunc: 805 case Instruction::ZExt: 806 case Instruction::SExt: 807 case Instruction::FPTrunc: 808 case Instruction::FPExt: 809 case Instruction::UIToFP: 810 case Instruction::SIToFP: 811 case Instruction::FPToUI: 812 case Instruction::FPToSI: 813 case Instruction::PtrToInt: 814 case Instruction::IntToPtr: 815 case Instruction::BitCast: 816 return ConstantExpr::getCast(getOpcode(), Op, getType()); 817 case Instruction::Select: 818 Op0 = (OpNo == 0) ? Op : getOperand(0); 819 Op1 = (OpNo == 1) ? Op : getOperand(1); 820 Op2 = (OpNo == 2) ? Op : getOperand(2); 821 return ConstantExpr::getSelect(Op0, Op1, Op2); 822 case Instruction::InsertElement: 823 Op0 = (OpNo == 0) ? Op : getOperand(0); 824 Op1 = (OpNo == 1) ? Op : getOperand(1); 825 Op2 = (OpNo == 2) ? Op : getOperand(2); 826 return ConstantExpr::getInsertElement(Op0, Op1, Op2); 827 case Instruction::ExtractElement: 828 Op0 = (OpNo == 0) ? Op : getOperand(0); 829 Op1 = (OpNo == 1) ? Op : getOperand(1); 830 return ConstantExpr::getExtractElement(Op0, Op1); 831 case Instruction::ShuffleVector: 832 Op0 = (OpNo == 0) ? Op : getOperand(0); 833 Op1 = (OpNo == 1) ? Op : getOperand(1); 834 Op2 = (OpNo == 2) ? Op : getOperand(2); 835 return ConstantExpr::getShuffleVector(Op0, Op1, Op2); 836 case Instruction::GetElementPtr: { 837 SmallVector<Constant*, 8> Ops; 838 Ops.resize(getNumOperands()-1); 839 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) 840 Ops[i-1] = getOperand(i); 841 if (OpNo == 0) 842 return cast<GEPOperator>(this)->isInBounds() ? 843 ConstantExpr::getInBoundsGetElementPtr(Op, &Ops[0], Ops.size()) : 844 ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size()); 845 Ops[OpNo-1] = Op; 846 return cast<GEPOperator>(this)->isInBounds() ? 847 ConstantExpr::getInBoundsGetElementPtr(getOperand(0), &Ops[0],Ops.size()): 848 ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size()); 849 } 850 default: 851 assert(getNumOperands() == 2 && "Must be binary operator?"); 852 Op0 = (OpNo == 0) ? Op : getOperand(0); 853 Op1 = (OpNo == 1) ? Op : getOperand(1); 854 return ConstantExpr::get(getOpcode(), Op0, Op1, SubclassOptionalData); 855 } 856 } 857 858 /// getWithOperands - This returns the current constant expression with the 859 /// operands replaced with the specified values. The specified array must 860 /// have the same number of operands as our current one. 861 Constant *ConstantExpr:: 862 getWithOperands(ArrayRef<Constant*> Ops, Type *Ty) const { 863 assert(Ops.size() == getNumOperands() && "Operand count mismatch!"); 864 bool AnyChange = Ty != getType(); 865 for (unsigned i = 0; i != Ops.size(); ++i) 866 AnyChange |= Ops[i] != getOperand(i); 867 868 if (!AnyChange) // No operands changed, return self. 869 return const_cast<ConstantExpr*>(this); 870 871 switch (getOpcode()) { 872 case Instruction::Trunc: 873 case Instruction::ZExt: 874 case Instruction::SExt: 875 case Instruction::FPTrunc: 876 case Instruction::FPExt: 877 case Instruction::UIToFP: 878 case Instruction::SIToFP: 879 case Instruction::FPToUI: 880 case Instruction::FPToSI: 881 case Instruction::PtrToInt: 882 case Instruction::IntToPtr: 883 case Instruction::BitCast: 884 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty); 885 case Instruction::Select: 886 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]); 887 case Instruction::InsertElement: 888 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]); 889 case Instruction::ExtractElement: 890 return ConstantExpr::getExtractElement(Ops[0], Ops[1]); 891 case Instruction::ShuffleVector: 892 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]); 893 case Instruction::GetElementPtr: 894 return cast<GEPOperator>(this)->isInBounds() ? 895 ConstantExpr::getInBoundsGetElementPtr(Ops[0], &Ops[1], Ops.size()-1) : 896 ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], Ops.size()-1); 897 case Instruction::ICmp: 898 case Instruction::FCmp: 899 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]); 900 default: 901 assert(getNumOperands() == 2 && "Must be binary operator?"); 902 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData); 903 } 904 } 905 906 907 //===----------------------------------------------------------------------===// 908 // isValueValidForType implementations 909 910 bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) { 911 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay 912 if (Ty == Type::getInt1Ty(Ty->getContext())) 913 return Val == 0 || Val == 1; 914 if (NumBits >= 64) 915 return true; // always true, has to fit in largest type 916 uint64_t Max = (1ll << NumBits) - 1; 917 return Val <= Max; 918 } 919 920 bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) { 921 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay 922 if (Ty == Type::getInt1Ty(Ty->getContext())) 923 return Val == 0 || Val == 1 || Val == -1; 924 if (NumBits >= 64) 925 return true; // always true, has to fit in largest type 926 int64_t Min = -(1ll << (NumBits-1)); 927 int64_t Max = (1ll << (NumBits-1)) - 1; 928 return (Val >= Min && Val <= Max); 929 } 930 931 bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) { 932 // convert modifies in place, so make a copy. 933 APFloat Val2 = APFloat(Val); 934 bool losesInfo; 935 switch (Ty->getTypeID()) { 936 default: 937 return false; // These can't be represented as floating point! 938 939 // FIXME rounding mode needs to be more flexible 940 case Type::FloatTyID: { 941 if (&Val2.getSemantics() == &APFloat::IEEEsingle) 942 return true; 943 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo); 944 return !losesInfo; 945 } 946 case Type::DoubleTyID: { 947 if (&Val2.getSemantics() == &APFloat::IEEEsingle || 948 &Val2.getSemantics() == &APFloat::IEEEdouble) 949 return true; 950 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo); 951 return !losesInfo; 952 } 953 case Type::X86_FP80TyID: 954 return &Val2.getSemantics() == &APFloat::IEEEsingle || 955 &Val2.getSemantics() == &APFloat::IEEEdouble || 956 &Val2.getSemantics() == &APFloat::x87DoubleExtended; 957 case Type::FP128TyID: 958 return &Val2.getSemantics() == &APFloat::IEEEsingle || 959 &Val2.getSemantics() == &APFloat::IEEEdouble || 960 &Val2.getSemantics() == &APFloat::IEEEquad; 961 case Type::PPC_FP128TyID: 962 return &Val2.getSemantics() == &APFloat::IEEEsingle || 963 &Val2.getSemantics() == &APFloat::IEEEdouble || 964 &Val2.getSemantics() == &APFloat::PPCDoubleDouble; 965 } 966 } 967 968 //===----------------------------------------------------------------------===// 969 // Factory Function Implementation 970 971 ConstantAggregateZero* ConstantAggregateZero::get(Type* Ty) { 972 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) && 973 "Cannot create an aggregate zero of non-aggregate type!"); 974 975 LLVMContextImpl *pImpl = Ty->getContext().pImpl; 976 return pImpl->AggZeroConstants.getOrCreate(Ty, 0); 977 } 978 979 /// destroyConstant - Remove the constant from the constant table... 980 /// 981 void ConstantAggregateZero::destroyConstant() { 982 getType()->getContext().pImpl->AggZeroConstants.remove(this); 983 destroyConstantImpl(); 984 } 985 986 /// destroyConstant - Remove the constant from the constant table... 987 /// 988 void ConstantArray::destroyConstant() { 989 getType()->getContext().pImpl->ArrayConstants.remove(this); 990 destroyConstantImpl(); 991 } 992 993 /// isString - This method returns true if the array is an array of i8, and 994 /// if the elements of the array are all ConstantInt's. 995 bool ConstantArray::isString() const { 996 // Check the element type for i8... 997 if (!getType()->getElementType()->isIntegerTy(8)) 998 return false; 999 // Check the elements to make sure they are all integers, not constant 1000 // expressions. 1001 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) 1002 if (!isa<ConstantInt>(getOperand(i))) 1003 return false; 1004 return true; 1005 } 1006 1007 /// isCString - This method returns true if the array is a string (see 1008 /// isString) and it ends in a null byte \\0 and does not contains any other 1009 /// null bytes except its terminator. 1010 bool ConstantArray::isCString() const { 1011 // Check the element type for i8... 1012 if (!getType()->getElementType()->isIntegerTy(8)) 1013 return false; 1014 1015 // Last element must be a null. 1016 if (!getOperand(getNumOperands()-1)->isNullValue()) 1017 return false; 1018 // Other elements must be non-null integers. 1019 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) { 1020 if (!isa<ConstantInt>(getOperand(i))) 1021 return false; 1022 if (getOperand(i)->isNullValue()) 1023 return false; 1024 } 1025 return true; 1026 } 1027 1028 1029 /// convertToString - Helper function for getAsString() and getAsCString(). 1030 static std::string convertToString(const User *U, unsigned len) { 1031 std::string Result; 1032 Result.reserve(len); 1033 for (unsigned i = 0; i != len; ++i) 1034 Result.push_back((char)cast<ConstantInt>(U->getOperand(i))->getZExtValue()); 1035 return Result; 1036 } 1037 1038 /// getAsString - If this array is isString(), then this method converts the 1039 /// array to an std::string and returns it. Otherwise, it asserts out. 1040 /// 1041 std::string ConstantArray::getAsString() const { 1042 assert(isString() && "Not a string!"); 1043 return convertToString(this, getNumOperands()); 1044 } 1045 1046 1047 /// getAsCString - If this array is isCString(), then this method converts the 1048 /// array (without the trailing null byte) to an std::string and returns it. 1049 /// Otherwise, it asserts out. 1050 /// 1051 std::string ConstantArray::getAsCString() const { 1052 assert(isCString() && "Not a string!"); 1053 return convertToString(this, getNumOperands() - 1); 1054 } 1055 1056 1057 //---- ConstantStruct::get() implementation... 1058 // 1059 1060 // destroyConstant - Remove the constant from the constant table... 1061 // 1062 void ConstantStruct::destroyConstant() { 1063 getType()->getContext().pImpl->StructConstants.remove(this); 1064 destroyConstantImpl(); 1065 } 1066 1067 // destroyConstant - Remove the constant from the constant table... 1068 // 1069 void ConstantVector::destroyConstant() { 1070 getType()->getContext().pImpl->VectorConstants.remove(this); 1071 destroyConstantImpl(); 1072 } 1073 1074 /// This function will return true iff every element in this vector constant 1075 /// is set to all ones. 1076 /// @returns true iff this constant's elements are all set to all ones. 1077 /// @brief Determine if the value is all ones. 1078 bool ConstantVector::isAllOnesValue() const { 1079 // Check out first element. 1080 const Constant *Elt = getOperand(0); 1081 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt); 1082 if (!CI || !CI->isAllOnesValue()) return false; 1083 // Then make sure all remaining elements point to the same value. 1084 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) 1085 if (getOperand(I) != Elt) 1086 return false; 1087 1088 return true; 1089 } 1090 1091 /// getSplatValue - If this is a splat constant, where all of the 1092 /// elements have the same value, return that value. Otherwise return null. 1093 Constant *ConstantVector::getSplatValue() const { 1094 // Check out first element. 1095 Constant *Elt = getOperand(0); 1096 // Then make sure all remaining elements point to the same value. 1097 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) 1098 if (getOperand(I) != Elt) 1099 return 0; 1100 return Elt; 1101 } 1102 1103 //---- ConstantPointerNull::get() implementation. 1104 // 1105 1106 ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) { 1107 return Ty->getContext().pImpl->NullPtrConstants.getOrCreate(Ty, 0); 1108 } 1109 1110 // destroyConstant - Remove the constant from the constant table... 1111 // 1112 void ConstantPointerNull::destroyConstant() { 1113 getType()->getContext().pImpl->NullPtrConstants.remove(this); 1114 destroyConstantImpl(); 1115 } 1116 1117 1118 //---- UndefValue::get() implementation. 1119 // 1120 1121 UndefValue *UndefValue::get(Type *Ty) { 1122 return Ty->getContext().pImpl->UndefValueConstants.getOrCreate(Ty, 0); 1123 } 1124 1125 // destroyConstant - Remove the constant from the constant table. 1126 // 1127 void UndefValue::destroyConstant() { 1128 getType()->getContext().pImpl->UndefValueConstants.remove(this); 1129 destroyConstantImpl(); 1130 } 1131 1132 //---- BlockAddress::get() implementation. 1133 // 1134 1135 BlockAddress *BlockAddress::get(BasicBlock *BB) { 1136 assert(BB->getParent() != 0 && "Block must have a parent"); 1137 return get(BB->getParent(), BB); 1138 } 1139 1140 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) { 1141 BlockAddress *&BA = 1142 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)]; 1143 if (BA == 0) 1144 BA = new BlockAddress(F, BB); 1145 1146 assert(BA->getFunction() == F && "Basic block moved between functions"); 1147 return BA; 1148 } 1149 1150 BlockAddress::BlockAddress(Function *F, BasicBlock *BB) 1151 : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal, 1152 &Op<0>(), 2) { 1153 setOperand(0, F); 1154 setOperand(1, BB); 1155 BB->AdjustBlockAddressRefCount(1); 1156 } 1157 1158 1159 // destroyConstant - Remove the constant from the constant table. 1160 // 1161 void BlockAddress::destroyConstant() { 1162 getFunction()->getType()->getContext().pImpl 1163 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock())); 1164 getBasicBlock()->AdjustBlockAddressRefCount(-1); 1165 destroyConstantImpl(); 1166 } 1167 1168 void BlockAddress::replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) { 1169 // This could be replacing either the Basic Block or the Function. In either 1170 // case, we have to remove the map entry. 1171 Function *NewF = getFunction(); 1172 BasicBlock *NewBB = getBasicBlock(); 1173 1174 if (U == &Op<0>()) 1175 NewF = cast<Function>(To); 1176 else 1177 NewBB = cast<BasicBlock>(To); 1178 1179 // See if the 'new' entry already exists, if not, just update this in place 1180 // and return early. 1181 BlockAddress *&NewBA = 1182 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)]; 1183 if (NewBA == 0) { 1184 getBasicBlock()->AdjustBlockAddressRefCount(-1); 1185 1186 // Remove the old entry, this can't cause the map to rehash (just a 1187 // tombstone will get added). 1188 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(), 1189 getBasicBlock())); 1190 NewBA = this; 1191 setOperand(0, NewF); 1192 setOperand(1, NewBB); 1193 getBasicBlock()->AdjustBlockAddressRefCount(1); 1194 return; 1195 } 1196 1197 // Otherwise, I do need to replace this with an existing value. 1198 assert(NewBA != this && "I didn't contain From!"); 1199 1200 // Everyone using this now uses the replacement. 1201 replaceAllUsesWith(NewBA); 1202 1203 destroyConstant(); 1204 } 1205 1206 //---- ConstantExpr::get() implementations. 1207 // 1208 1209 /// This is a utility function to handle folding of casts and lookup of the 1210 /// cast in the ExprConstants map. It is used by the various get* methods below. 1211 static inline Constant *getFoldedCast( 1212 Instruction::CastOps opc, Constant *C, Type *Ty) { 1213 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!"); 1214 // Fold a few common cases 1215 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty)) 1216 return FC; 1217 1218 LLVMContextImpl *pImpl = Ty->getContext().pImpl; 1219 1220 // Look up the constant in the table first to ensure uniqueness 1221 std::vector<Constant*> argVec(1, C); 1222 ExprMapKeyType Key(opc, argVec); 1223 1224 return pImpl->ExprConstants.getOrCreate(Ty, Key); 1225 } 1226 1227 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty) { 1228 Instruction::CastOps opc = Instruction::CastOps(oc); 1229 assert(Instruction::isCast(opc) && "opcode out of range"); 1230 assert(C && Ty && "Null arguments to getCast"); 1231 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!"); 1232 1233 switch (opc) { 1234 default: 1235 llvm_unreachable("Invalid cast opcode"); 1236 break; 1237 case Instruction::Trunc: return getTrunc(C, Ty); 1238 case Instruction::ZExt: return getZExt(C, Ty); 1239 case Instruction::SExt: return getSExt(C, Ty); 1240 case Instruction::FPTrunc: return getFPTrunc(C, Ty); 1241 case Instruction::FPExt: return getFPExtend(C, Ty); 1242 case Instruction::UIToFP: return getUIToFP(C, Ty); 1243 case Instruction::SIToFP: return getSIToFP(C, Ty); 1244 case Instruction::FPToUI: return getFPToUI(C, Ty); 1245 case Instruction::FPToSI: return getFPToSI(C, Ty); 1246 case Instruction::PtrToInt: return getPtrToInt(C, Ty); 1247 case Instruction::IntToPtr: return getIntToPtr(C, Ty); 1248 case Instruction::BitCast: return getBitCast(C, Ty); 1249 } 1250 return 0; 1251 } 1252 1253 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) { 1254 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 1255 return getBitCast(C, Ty); 1256 return getZExt(C, Ty); 1257 } 1258 1259 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) { 1260 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 1261 return getBitCast(C, Ty); 1262 return getSExt(C, Ty); 1263 } 1264 1265 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) { 1266 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 1267 return getBitCast(C, Ty); 1268 return getTrunc(C, Ty); 1269 } 1270 1271 Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) { 1272 assert(S->getType()->isPointerTy() && "Invalid cast"); 1273 assert((Ty->isIntegerTy() || Ty->isPointerTy()) && "Invalid cast"); 1274 1275 if (Ty->isIntegerTy()) 1276 return getPtrToInt(S, Ty); 1277 return getBitCast(S, Ty); 1278 } 1279 1280 Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty, 1281 bool isSigned) { 1282 assert(C->getType()->isIntOrIntVectorTy() && 1283 Ty->isIntOrIntVectorTy() && "Invalid cast"); 1284 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 1285 unsigned DstBits = Ty->getScalarSizeInBits(); 1286 Instruction::CastOps opcode = 1287 (SrcBits == DstBits ? Instruction::BitCast : 1288 (SrcBits > DstBits ? Instruction::Trunc : 1289 (isSigned ? Instruction::SExt : Instruction::ZExt))); 1290 return getCast(opcode, C, Ty); 1291 } 1292 1293 Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) { 1294 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() && 1295 "Invalid cast"); 1296 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 1297 unsigned DstBits = Ty->getScalarSizeInBits(); 1298 if (SrcBits == DstBits) 1299 return C; // Avoid a useless cast 1300 Instruction::CastOps opcode = 1301 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt); 1302 return getCast(opcode, C, Ty); 1303 } 1304 1305 Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty) { 1306 #ifndef NDEBUG 1307 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID; 1308 bool toVec = Ty->getTypeID() == Type::VectorTyID; 1309 #endif 1310 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 1311 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer"); 1312 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral"); 1313 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&& 1314 "SrcTy must be larger than DestTy for Trunc!"); 1315 1316 return getFoldedCast(Instruction::Trunc, C, Ty); 1317 } 1318 1319 Constant *ConstantExpr::getSExt(Constant *C, Type *Ty) { 1320 #ifndef NDEBUG 1321 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID; 1322 bool toVec = Ty->getTypeID() == Type::VectorTyID; 1323 #endif 1324 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 1325 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral"); 1326 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer"); 1327 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&& 1328 "SrcTy must be smaller than DestTy for SExt!"); 1329 1330 return getFoldedCast(Instruction::SExt, C, Ty); 1331 } 1332 1333 Constant *ConstantExpr::getZExt(Constant *C, Type *Ty) { 1334 #ifndef NDEBUG 1335 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID; 1336 bool toVec = Ty->getTypeID() == Type::VectorTyID; 1337 #endif 1338 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 1339 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral"); 1340 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer"); 1341 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&& 1342 "SrcTy must be smaller than DestTy for ZExt!"); 1343 1344 return getFoldedCast(Instruction::ZExt, C, Ty); 1345 } 1346 1347 Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty) { 1348 #ifndef NDEBUG 1349 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID; 1350 bool toVec = Ty->getTypeID() == Type::VectorTyID; 1351 #endif 1352 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 1353 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() && 1354 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&& 1355 "This is an illegal floating point truncation!"); 1356 return getFoldedCast(Instruction::FPTrunc, C, Ty); 1357 } 1358 1359 Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty) { 1360 #ifndef NDEBUG 1361 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID; 1362 bool toVec = Ty->getTypeID() == Type::VectorTyID; 1363 #endif 1364 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 1365 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() && 1366 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&& 1367 "This is an illegal floating point extension!"); 1368 return getFoldedCast(Instruction::FPExt, C, Ty); 1369 } 1370 1371 Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty) { 1372 #ifndef NDEBUG 1373 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID; 1374 bool toVec = Ty->getTypeID() == Type::VectorTyID; 1375 #endif 1376 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 1377 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() && 1378 "This is an illegal uint to floating point cast!"); 1379 return getFoldedCast(Instruction::UIToFP, C, Ty); 1380 } 1381 1382 Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty) { 1383 #ifndef NDEBUG 1384 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID; 1385 bool toVec = Ty->getTypeID() == Type::VectorTyID; 1386 #endif 1387 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 1388 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() && 1389 "This is an illegal sint to floating point cast!"); 1390 return getFoldedCast(Instruction::SIToFP, C, Ty); 1391 } 1392 1393 Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty) { 1394 #ifndef NDEBUG 1395 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID; 1396 bool toVec = Ty->getTypeID() == Type::VectorTyID; 1397 #endif 1398 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 1399 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() && 1400 "This is an illegal floating point to uint cast!"); 1401 return getFoldedCast(Instruction::FPToUI, C, Ty); 1402 } 1403 1404 Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty) { 1405 #ifndef NDEBUG 1406 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID; 1407 bool toVec = Ty->getTypeID() == Type::VectorTyID; 1408 #endif 1409 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 1410 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() && 1411 "This is an illegal floating point to sint cast!"); 1412 return getFoldedCast(Instruction::FPToSI, C, Ty); 1413 } 1414 1415 Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy) { 1416 assert(C->getType()->isPointerTy() && "PtrToInt source must be pointer"); 1417 assert(DstTy->isIntegerTy() && "PtrToInt destination must be integral"); 1418 return getFoldedCast(Instruction::PtrToInt, C, DstTy); 1419 } 1420 1421 Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy) { 1422 assert(C->getType()->isIntegerTy() && "IntToPtr source must be integral"); 1423 assert(DstTy->isPointerTy() && "IntToPtr destination must be a pointer"); 1424 return getFoldedCast(Instruction::IntToPtr, C, DstTy); 1425 } 1426 1427 Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy) { 1428 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) && 1429 "Invalid constantexpr bitcast!"); 1430 1431 // It is common to ask for a bitcast of a value to its own type, handle this 1432 // speedily. 1433 if (C->getType() == DstTy) return C; 1434 1435 return getFoldedCast(Instruction::BitCast, C, DstTy); 1436 } 1437 1438 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2, 1439 unsigned Flags) { 1440 // Check the operands for consistency first. 1441 assert(Opcode >= Instruction::BinaryOpsBegin && 1442 Opcode < Instruction::BinaryOpsEnd && 1443 "Invalid opcode in binary constant expression"); 1444 assert(C1->getType() == C2->getType() && 1445 "Operand types in binary constant expression should match"); 1446 1447 #ifndef NDEBUG 1448 switch (Opcode) { 1449 case Instruction::Add: 1450 case Instruction::Sub: 1451 case Instruction::Mul: 1452 assert(C1->getType() == C2->getType() && "Op types should be identical!"); 1453 assert(C1->getType()->isIntOrIntVectorTy() && 1454 "Tried to create an integer operation on a non-integer type!"); 1455 break; 1456 case Instruction::FAdd: 1457 case Instruction::FSub: 1458 case Instruction::FMul: 1459 assert(C1->getType() == C2->getType() && "Op types should be identical!"); 1460 assert(C1->getType()->isFPOrFPVectorTy() && 1461 "Tried to create a floating-point operation on a " 1462 "non-floating-point type!"); 1463 break; 1464 case Instruction::UDiv: 1465 case Instruction::SDiv: 1466 assert(C1->getType() == C2->getType() && "Op types should be identical!"); 1467 assert(C1->getType()->isIntOrIntVectorTy() && 1468 "Tried to create an arithmetic operation on a non-arithmetic type!"); 1469 break; 1470 case Instruction::FDiv: 1471 assert(C1->getType() == C2->getType() && "Op types should be identical!"); 1472 assert(C1->getType()->isFPOrFPVectorTy() && 1473 "Tried to create an arithmetic operation on a non-arithmetic type!"); 1474 break; 1475 case Instruction::URem: 1476 case Instruction::SRem: 1477 assert(C1->getType() == C2->getType() && "Op types should be identical!"); 1478 assert(C1->getType()->isIntOrIntVectorTy() && 1479 "Tried to create an arithmetic operation on a non-arithmetic type!"); 1480 break; 1481 case Instruction::FRem: 1482 assert(C1->getType() == C2->getType() && "Op types should be identical!"); 1483 assert(C1->getType()->isFPOrFPVectorTy() && 1484 "Tried to create an arithmetic operation on a non-arithmetic type!"); 1485 break; 1486 case Instruction::And: 1487 case Instruction::Or: 1488 case Instruction::Xor: 1489 assert(C1->getType() == C2->getType() && "Op types should be identical!"); 1490 assert(C1->getType()->isIntOrIntVectorTy() && 1491 "Tried to create a logical operation on a non-integral type!"); 1492 break; 1493 case Instruction::Shl: 1494 case Instruction::LShr: 1495 case Instruction::AShr: 1496 assert(C1->getType() == C2->getType() && "Op types should be identical!"); 1497 assert(C1->getType()->isIntOrIntVectorTy() && 1498 "Tried to create a shift operation on a non-integer type!"); 1499 break; 1500 default: 1501 break; 1502 } 1503 #endif 1504 1505 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2)) 1506 return FC; // Fold a few common cases. 1507 1508 std::vector<Constant*> argVec(1, C1); 1509 argVec.push_back(C2); 1510 ExprMapKeyType Key(Opcode, argVec, 0, Flags); 1511 1512 LLVMContextImpl *pImpl = C1->getContext().pImpl; 1513 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key); 1514 } 1515 1516 Constant *ConstantExpr::getSizeOf(Type* Ty) { 1517 // sizeof is implemented as: (i64) gep (Ty*)null, 1 1518 // Note that a non-inbounds gep is used, as null isn't within any object. 1519 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1); 1520 Constant *GEP = getGetElementPtr( 1521 Constant::getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1); 1522 return getPtrToInt(GEP, 1523 Type::getInt64Ty(Ty->getContext())); 1524 } 1525 1526 Constant *ConstantExpr::getAlignOf(Type* Ty) { 1527 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1 1528 // Note that a non-inbounds gep is used, as null isn't within any object. 1529 Type *AligningTy = 1530 StructType::get(Type::getInt1Ty(Ty->getContext()), Ty, NULL); 1531 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo()); 1532 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0); 1533 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1); 1534 Constant *Indices[2] = { Zero, One }; 1535 Constant *GEP = getGetElementPtr(NullPtr, Indices, 2); 1536 return getPtrToInt(GEP, 1537 Type::getInt64Ty(Ty->getContext())); 1538 } 1539 1540 Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) { 1541 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()), 1542 FieldNo)); 1543 } 1544 1545 Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) { 1546 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo 1547 // Note that a non-inbounds gep is used, as null isn't within any object. 1548 Constant *GEPIdx[] = { 1549 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0), 1550 FieldNo 1551 }; 1552 Constant *GEP = getGetElementPtr( 1553 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx, 2); 1554 return getPtrToInt(GEP, 1555 Type::getInt64Ty(Ty->getContext())); 1556 } 1557 1558 Constant *ConstantExpr::getCompare(unsigned short Predicate, 1559 Constant *C1, Constant *C2) { 1560 assert(C1->getType() == C2->getType() && "Op types should be identical!"); 1561 1562 switch (Predicate) { 1563 default: llvm_unreachable("Invalid CmpInst predicate"); 1564 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT: 1565 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE: 1566 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO: 1567 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE: 1568 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE: 1569 case CmpInst::FCMP_TRUE: 1570 return getFCmp(Predicate, C1, C2); 1571 1572 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT: 1573 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE: 1574 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT: 1575 case CmpInst::ICMP_SLE: 1576 return getICmp(Predicate, C1, C2); 1577 } 1578 } 1579 1580 Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2) { 1581 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands"); 1582 1583 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2)) 1584 return SC; // Fold common cases 1585 1586 std::vector<Constant*> argVec(3, C); 1587 argVec[1] = V1; 1588 argVec[2] = V2; 1589 ExprMapKeyType Key(Instruction::Select, argVec); 1590 1591 LLVMContextImpl *pImpl = C->getContext().pImpl; 1592 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key); 1593 } 1594 1595 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs, 1596 unsigned NumIdx, bool InBounds) { 1597 if (Constant *FC = ConstantFoldGetElementPtr(C, InBounds, 1598 makeArrayRef(Idxs, NumIdx))) 1599 return FC; // Fold a few common cases. 1600 1601 // Get the result type of the getelementptr! 1602 Type *Ty = 1603 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx); 1604 assert(Ty && "GEP indices invalid!"); 1605 unsigned AS = cast<PointerType>(C->getType())->getAddressSpace(); 1606 Type *ReqTy = Ty->getPointerTo(AS); 1607 1608 assert(C->getType()->isPointerTy() && 1609 "Non-pointer type for constant GetElementPtr expression"); 1610 // Look up the constant in the table first to ensure uniqueness 1611 std::vector<Constant*> ArgVec; 1612 ArgVec.reserve(NumIdx+1); 1613 ArgVec.push_back(C); 1614 for (unsigned i = 0; i != NumIdx; ++i) 1615 ArgVec.push_back(cast<Constant>(Idxs[i])); 1616 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec, 0, 1617 InBounds ? GEPOperator::IsInBounds : 0); 1618 1619 LLVMContextImpl *pImpl = C->getContext().pImpl; 1620 return pImpl->ExprConstants.getOrCreate(ReqTy, Key); 1621 } 1622 1623 Constant * 1624 ConstantExpr::getICmp(unsigned short pred, Constant *LHS, Constant *RHS) { 1625 assert(LHS->getType() == RHS->getType()); 1626 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE && 1627 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate"); 1628 1629 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS)) 1630 return FC; // Fold a few common cases... 1631 1632 // Look up the constant in the table first to ensure uniqueness 1633 std::vector<Constant*> ArgVec; 1634 ArgVec.push_back(LHS); 1635 ArgVec.push_back(RHS); 1636 // Get the key type with both the opcode and predicate 1637 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred); 1638 1639 Type *ResultTy = Type::getInt1Ty(LHS->getContext()); 1640 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType())) 1641 ResultTy = VectorType::get(ResultTy, VT->getNumElements()); 1642 1643 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl; 1644 return pImpl->ExprConstants.getOrCreate(ResultTy, Key); 1645 } 1646 1647 Constant * 1648 ConstantExpr::getFCmp(unsigned short pred, Constant *LHS, Constant *RHS) { 1649 assert(LHS->getType() == RHS->getType()); 1650 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate"); 1651 1652 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS)) 1653 return FC; // Fold a few common cases... 1654 1655 // Look up the constant in the table first to ensure uniqueness 1656 std::vector<Constant*> ArgVec; 1657 ArgVec.push_back(LHS); 1658 ArgVec.push_back(RHS); 1659 // Get the key type with both the opcode and predicate 1660 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred); 1661 1662 Type *ResultTy = Type::getInt1Ty(LHS->getContext()); 1663 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType())) 1664 ResultTy = VectorType::get(ResultTy, VT->getNumElements()); 1665 1666 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl; 1667 return pImpl->ExprConstants.getOrCreate(ResultTy, Key); 1668 } 1669 1670 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) { 1671 assert(Val->getType()->isVectorTy() && 1672 "Tried to create extractelement operation on non-vector type!"); 1673 assert(Idx->getType()->isIntegerTy(32) && 1674 "Extractelement index must be i32 type!"); 1675 1676 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx)) 1677 return FC; // Fold a few common cases. 1678 1679 // Look up the constant in the table first to ensure uniqueness 1680 std::vector<Constant*> ArgVec(1, Val); 1681 ArgVec.push_back(Idx); 1682 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec); 1683 1684 LLVMContextImpl *pImpl = Val->getContext().pImpl; 1685 Type *ReqTy = cast<VectorType>(Val->getType())->getElementType(); 1686 return pImpl->ExprConstants.getOrCreate(ReqTy, Key); 1687 } 1688 1689 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt, 1690 Constant *Idx) { 1691 assert(Val->getType()->isVectorTy() && 1692 "Tried to create insertelement operation on non-vector type!"); 1693 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType() 1694 && "Insertelement types must match!"); 1695 assert(Idx->getType()->isIntegerTy(32) && 1696 "Insertelement index must be i32 type!"); 1697 1698 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx)) 1699 return FC; // Fold a few common cases. 1700 // Look up the constant in the table first to ensure uniqueness 1701 std::vector<Constant*> ArgVec(1, Val); 1702 ArgVec.push_back(Elt); 1703 ArgVec.push_back(Idx); 1704 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec); 1705 1706 LLVMContextImpl *pImpl = Val->getContext().pImpl; 1707 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key); 1708 } 1709 1710 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2, 1711 Constant *Mask) { 1712 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) && 1713 "Invalid shuffle vector constant expr operands!"); 1714 1715 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask)) 1716 return FC; // Fold a few common cases. 1717 1718 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements(); 1719 Type *EltTy = cast<VectorType>(V1->getType())->getElementType(); 1720 Type *ShufTy = VectorType::get(EltTy, NElts); 1721 1722 // Look up the constant in the table first to ensure uniqueness 1723 std::vector<Constant*> ArgVec(1, V1); 1724 ArgVec.push_back(V2); 1725 ArgVec.push_back(Mask); 1726 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec); 1727 1728 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl; 1729 return pImpl->ExprConstants.getOrCreate(ShufTy, Key); 1730 } 1731 1732 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val, 1733 ArrayRef<unsigned> Idxs) { 1734 assert(ExtractValueInst::getIndexedType(Agg->getType(), 1735 Idxs) == Val->getType() && 1736 "insertvalue indices invalid!"); 1737 assert(Agg->getType()->isFirstClassType() && 1738 "Non-first-class type for constant insertvalue expression"); 1739 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs); 1740 assert(FC && "insertvalue constant expr couldn't be folded!"); 1741 return FC; 1742 } 1743 1744 Constant *ConstantExpr::getExtractValue(Constant *Agg, 1745 ArrayRef<unsigned> Idxs) { 1746 assert(Agg->getType()->isFirstClassType() && 1747 "Tried to create extractelement operation on non-first-class type!"); 1748 1749 Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs); 1750 (void)ReqTy; 1751 assert(ReqTy && "extractvalue indices invalid!"); 1752 1753 assert(Agg->getType()->isFirstClassType() && 1754 "Non-first-class type for constant extractvalue expression"); 1755 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs); 1756 assert(FC && "ExtractValue constant expr couldn't be folded!"); 1757 return FC; 1758 } 1759 1760 Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) { 1761 assert(C->getType()->isIntOrIntVectorTy() && 1762 "Cannot NEG a nonintegral value!"); 1763 return getSub(ConstantFP::getZeroValueForNegation(C->getType()), 1764 C, HasNUW, HasNSW); 1765 } 1766 1767 Constant *ConstantExpr::getFNeg(Constant *C) { 1768 assert(C->getType()->isFPOrFPVectorTy() && 1769 "Cannot FNEG a non-floating-point value!"); 1770 return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C); 1771 } 1772 1773 Constant *ConstantExpr::getNot(Constant *C) { 1774 assert(C->getType()->isIntOrIntVectorTy() && 1775 "Cannot NOT a nonintegral value!"); 1776 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType())); 1777 } 1778 1779 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2, 1780 bool HasNUW, bool HasNSW) { 1781 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) | 1782 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0); 1783 return get(Instruction::Add, C1, C2, Flags); 1784 } 1785 1786 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) { 1787 return get(Instruction::FAdd, C1, C2); 1788 } 1789 1790 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2, 1791 bool HasNUW, bool HasNSW) { 1792 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) | 1793 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0); 1794 return get(Instruction::Sub, C1, C2, Flags); 1795 } 1796 1797 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) { 1798 return get(Instruction::FSub, C1, C2); 1799 } 1800 1801 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2, 1802 bool HasNUW, bool HasNSW) { 1803 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) | 1804 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0); 1805 return get(Instruction::Mul, C1, C2, Flags); 1806 } 1807 1808 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) { 1809 return get(Instruction::FMul, C1, C2); 1810 } 1811 1812 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) { 1813 return get(Instruction::UDiv, C1, C2, 1814 isExact ? PossiblyExactOperator::IsExact : 0); 1815 } 1816 1817 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) { 1818 return get(Instruction::SDiv, C1, C2, 1819 isExact ? PossiblyExactOperator::IsExact : 0); 1820 } 1821 1822 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) { 1823 return get(Instruction::FDiv, C1, C2); 1824 } 1825 1826 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) { 1827 return get(Instruction::URem, C1, C2); 1828 } 1829 1830 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) { 1831 return get(Instruction::SRem, C1, C2); 1832 } 1833 1834 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) { 1835 return get(Instruction::FRem, C1, C2); 1836 } 1837 1838 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) { 1839 return get(Instruction::And, C1, C2); 1840 } 1841 1842 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) { 1843 return get(Instruction::Or, C1, C2); 1844 } 1845 1846 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) { 1847 return get(Instruction::Xor, C1, C2); 1848 } 1849 1850 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2, 1851 bool HasNUW, bool HasNSW) { 1852 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) | 1853 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0); 1854 return get(Instruction::Shl, C1, C2, Flags); 1855 } 1856 1857 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) { 1858 return get(Instruction::LShr, C1, C2, 1859 isExact ? PossiblyExactOperator::IsExact : 0); 1860 } 1861 1862 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) { 1863 return get(Instruction::AShr, C1, C2, 1864 isExact ? PossiblyExactOperator::IsExact : 0); 1865 } 1866 1867 // destroyConstant - Remove the constant from the constant table... 1868 // 1869 void ConstantExpr::destroyConstant() { 1870 getType()->getContext().pImpl->ExprConstants.remove(this); 1871 destroyConstantImpl(); 1872 } 1873 1874 const char *ConstantExpr::getOpcodeName() const { 1875 return Instruction::getOpcodeName(getOpcode()); 1876 } 1877 1878 1879 1880 GetElementPtrConstantExpr:: 1881 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList, 1882 Type *DestTy) 1883 : ConstantExpr(DestTy, Instruction::GetElementPtr, 1884 OperandTraits<GetElementPtrConstantExpr>::op_end(this) 1885 - (IdxList.size()+1), IdxList.size()+1) { 1886 OperandList[0] = C; 1887 for (unsigned i = 0, E = IdxList.size(); i != E; ++i) 1888 OperandList[i+1] = IdxList[i]; 1889 } 1890 1891 1892 //===----------------------------------------------------------------------===// 1893 // replaceUsesOfWithOnConstant implementations 1894 1895 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of 1896 /// 'From' to be uses of 'To'. This must update the uniquing data structures 1897 /// etc. 1898 /// 1899 /// Note that we intentionally replace all uses of From with To here. Consider 1900 /// a large array that uses 'From' 1000 times. By handling this case all here, 1901 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that 1902 /// single invocation handles all 1000 uses. Handling them one at a time would 1903 /// work, but would be really slow because it would have to unique each updated 1904 /// array instance. 1905 /// 1906 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To, 1907 Use *U) { 1908 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!"); 1909 Constant *ToC = cast<Constant>(To); 1910 1911 LLVMContextImpl *pImpl = getType()->getContext().pImpl; 1912 1913 std::pair<LLVMContextImpl::ArrayConstantsTy::MapKey, ConstantArray*> Lookup; 1914 Lookup.first.first = cast<ArrayType>(getType()); 1915 Lookup.second = this; 1916 1917 std::vector<Constant*> &Values = Lookup.first.second; 1918 Values.reserve(getNumOperands()); // Build replacement array. 1919 1920 // Fill values with the modified operands of the constant array. Also, 1921 // compute whether this turns into an all-zeros array. 1922 bool isAllZeros = false; 1923 unsigned NumUpdated = 0; 1924 if (!ToC->isNullValue()) { 1925 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) { 1926 Constant *Val = cast<Constant>(O->get()); 1927 if (Val == From) { 1928 Val = ToC; 1929 ++NumUpdated; 1930 } 1931 Values.push_back(Val); 1932 } 1933 } else { 1934 isAllZeros = true; 1935 for (Use *O = OperandList, *E = OperandList+getNumOperands();O != E; ++O) { 1936 Constant *Val = cast<Constant>(O->get()); 1937 if (Val == From) { 1938 Val = ToC; 1939 ++NumUpdated; 1940 } 1941 Values.push_back(Val); 1942 if (isAllZeros) isAllZeros = Val->isNullValue(); 1943 } 1944 } 1945 1946 Constant *Replacement = 0; 1947 if (isAllZeros) { 1948 Replacement = ConstantAggregateZero::get(getType()); 1949 } else { 1950 // Check to see if we have this array type already. 1951 bool Exists; 1952 LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I = 1953 pImpl->ArrayConstants.InsertOrGetItem(Lookup, Exists); 1954 1955 if (Exists) { 1956 Replacement = I->second; 1957 } else { 1958 // Okay, the new shape doesn't exist in the system yet. Instead of 1959 // creating a new constant array, inserting it, replaceallusesof'ing the 1960 // old with the new, then deleting the old... just update the current one 1961 // in place! 1962 pImpl->ArrayConstants.MoveConstantToNewSlot(this, I); 1963 1964 // Update to the new value. Optimize for the case when we have a single 1965 // operand that we're changing, but handle bulk updates efficiently. 1966 if (NumUpdated == 1) { 1967 unsigned OperandToUpdate = U - OperandList; 1968 assert(getOperand(OperandToUpdate) == From && 1969 "ReplaceAllUsesWith broken!"); 1970 setOperand(OperandToUpdate, ToC); 1971 } else { 1972 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) 1973 if (getOperand(i) == From) 1974 setOperand(i, ToC); 1975 } 1976 return; 1977 } 1978 } 1979 1980 // Otherwise, I do need to replace this with an existing value. 1981 assert(Replacement != this && "I didn't contain From!"); 1982 1983 // Everyone using this now uses the replacement. 1984 replaceAllUsesWith(Replacement); 1985 1986 // Delete the old constant! 1987 destroyConstant(); 1988 } 1989 1990 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To, 1991 Use *U) { 1992 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!"); 1993 Constant *ToC = cast<Constant>(To); 1994 1995 unsigned OperandToUpdate = U-OperandList; 1996 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!"); 1997 1998 std::pair<LLVMContextImpl::StructConstantsTy::MapKey, ConstantStruct*> Lookup; 1999 Lookup.first.first = cast<StructType>(getType()); 2000 Lookup.second = this; 2001 std::vector<Constant*> &Values = Lookup.first.second; 2002 Values.reserve(getNumOperands()); // Build replacement struct. 2003 2004 2005 // Fill values with the modified operands of the constant struct. Also, 2006 // compute whether this turns into an all-zeros struct. 2007 bool isAllZeros = false; 2008 if (!ToC->isNullValue()) { 2009 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) 2010 Values.push_back(cast<Constant>(O->get())); 2011 } else { 2012 isAllZeros = true; 2013 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) { 2014 Constant *Val = cast<Constant>(O->get()); 2015 Values.push_back(Val); 2016 if (isAllZeros) isAllZeros = Val->isNullValue(); 2017 } 2018 } 2019 Values[OperandToUpdate] = ToC; 2020 2021 LLVMContextImpl *pImpl = getContext().pImpl; 2022 2023 Constant *Replacement = 0; 2024 if (isAllZeros) { 2025 Replacement = ConstantAggregateZero::get(getType()); 2026 } else { 2027 // Check to see if we have this struct type already. 2028 bool Exists; 2029 LLVMContextImpl::StructConstantsTy::MapTy::iterator I = 2030 pImpl->StructConstants.InsertOrGetItem(Lookup, Exists); 2031 2032 if (Exists) { 2033 Replacement = I->second; 2034 } else { 2035 // Okay, the new shape doesn't exist in the system yet. Instead of 2036 // creating a new constant struct, inserting it, replaceallusesof'ing the 2037 // old with the new, then deleting the old... just update the current one 2038 // in place! 2039 pImpl->StructConstants.MoveConstantToNewSlot(this, I); 2040 2041 // Update to the new value. 2042 setOperand(OperandToUpdate, ToC); 2043 return; 2044 } 2045 } 2046 2047 assert(Replacement != this && "I didn't contain From!"); 2048 2049 // Everyone using this now uses the replacement. 2050 replaceAllUsesWith(Replacement); 2051 2052 // Delete the old constant! 2053 destroyConstant(); 2054 } 2055 2056 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To, 2057 Use *U) { 2058 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!"); 2059 2060 std::vector<Constant*> Values; 2061 Values.reserve(getNumOperands()); // Build replacement array... 2062 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 2063 Constant *Val = getOperand(i); 2064 if (Val == From) Val = cast<Constant>(To); 2065 Values.push_back(Val); 2066 } 2067 2068 Constant *Replacement = get(Values); 2069 assert(Replacement != this && "I didn't contain From!"); 2070 2071 // Everyone using this now uses the replacement. 2072 replaceAllUsesWith(Replacement); 2073 2074 // Delete the old constant! 2075 destroyConstant(); 2076 } 2077 2078 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV, 2079 Use *U) { 2080 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!"); 2081 Constant *To = cast<Constant>(ToV); 2082 2083 Constant *Replacement = 0; 2084 if (getOpcode() == Instruction::GetElementPtr) { 2085 SmallVector<Constant*, 8> Indices; 2086 Constant *Pointer = getOperand(0); 2087 Indices.reserve(getNumOperands()-1); 2088 if (Pointer == From) Pointer = To; 2089 2090 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 2091 Constant *Val = getOperand(i); 2092 if (Val == From) Val = To; 2093 Indices.push_back(Val); 2094 } 2095 Replacement = ConstantExpr::getGetElementPtr(Pointer, 2096 &Indices[0], Indices.size(), 2097 cast<GEPOperator>(this)->isInBounds()); 2098 } else if (getOpcode() == Instruction::ExtractValue) { 2099 Constant *Agg = getOperand(0); 2100 if (Agg == From) Agg = To; 2101 2102 ArrayRef<unsigned> Indices = getIndices(); 2103 Replacement = ConstantExpr::getExtractValue(Agg, Indices); 2104 } else if (getOpcode() == Instruction::InsertValue) { 2105 Constant *Agg = getOperand(0); 2106 Constant *Val = getOperand(1); 2107 if (Agg == From) Agg = To; 2108 if (Val == From) Val = To; 2109 2110 ArrayRef<unsigned> Indices = getIndices(); 2111 Replacement = ConstantExpr::getInsertValue(Agg, Val, Indices); 2112 } else if (isCast()) { 2113 assert(getOperand(0) == From && "Cast only has one use!"); 2114 Replacement = ConstantExpr::getCast(getOpcode(), To, getType()); 2115 } else if (getOpcode() == Instruction::Select) { 2116 Constant *C1 = getOperand(0); 2117 Constant *C2 = getOperand(1); 2118 Constant *C3 = getOperand(2); 2119 if (C1 == From) C1 = To; 2120 if (C2 == From) C2 = To; 2121 if (C3 == From) C3 = To; 2122 Replacement = ConstantExpr::getSelect(C1, C2, C3); 2123 } else if (getOpcode() == Instruction::ExtractElement) { 2124 Constant *C1 = getOperand(0); 2125 Constant *C2 = getOperand(1); 2126 if (C1 == From) C1 = To; 2127 if (C2 == From) C2 = To; 2128 Replacement = ConstantExpr::getExtractElement(C1, C2); 2129 } else if (getOpcode() == Instruction::InsertElement) { 2130 Constant *C1 = getOperand(0); 2131 Constant *C2 = getOperand(1); 2132 Constant *C3 = getOperand(1); 2133 if (C1 == From) C1 = To; 2134 if (C2 == From) C2 = To; 2135 if (C3 == From) C3 = To; 2136 Replacement = ConstantExpr::getInsertElement(C1, C2, C3); 2137 } else if (getOpcode() == Instruction::ShuffleVector) { 2138 Constant *C1 = getOperand(0); 2139 Constant *C2 = getOperand(1); 2140 Constant *C3 = getOperand(2); 2141 if (C1 == From) C1 = To; 2142 if (C2 == From) C2 = To; 2143 if (C3 == From) C3 = To; 2144 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3); 2145 } else if (isCompare()) { 2146 Constant *C1 = getOperand(0); 2147 Constant *C2 = getOperand(1); 2148 if (C1 == From) C1 = To; 2149 if (C2 == From) C2 = To; 2150 if (getOpcode() == Instruction::ICmp) 2151 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2); 2152 else { 2153 assert(getOpcode() == Instruction::FCmp); 2154 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2); 2155 } 2156 } else if (getNumOperands() == 2) { 2157 Constant *C1 = getOperand(0); 2158 Constant *C2 = getOperand(1); 2159 if (C1 == From) C1 = To; 2160 if (C2 == From) C2 = To; 2161 Replacement = ConstantExpr::get(getOpcode(), C1, C2, SubclassOptionalData); 2162 } else { 2163 llvm_unreachable("Unknown ConstantExpr type!"); 2164 return; 2165 } 2166 2167 assert(Replacement != this && "I didn't contain From!"); 2168 2169 // Everyone using this now uses the replacement. 2170 replaceAllUsesWith(Replacement); 2171 2172 // Delete the old constant! 2173 destroyConstant(); 2174 } 2175