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