1 //===- Instructions.cpp - Implement the LLVM instructions -----------------===// 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 all of the non-inline methods for the LLVM instruction 10 // classes. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/IR/Instructions.h" 15 #include "LLVMContextImpl.h" 16 #include "llvm/ADT/None.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/ADT/Twine.h" 19 #include "llvm/IR/Attributes.h" 20 #include "llvm/IR/BasicBlock.h" 21 #include "llvm/IR/Constant.h" 22 #include "llvm/IR/Constants.h" 23 #include "llvm/IR/DataLayout.h" 24 #include "llvm/IR/DerivedTypes.h" 25 #include "llvm/IR/Function.h" 26 #include "llvm/IR/InstrTypes.h" 27 #include "llvm/IR/Instruction.h" 28 #include "llvm/IR/Intrinsics.h" 29 #include "llvm/IR/LLVMContext.h" 30 #include "llvm/IR/MDBuilder.h" 31 #include "llvm/IR/Metadata.h" 32 #include "llvm/IR/Module.h" 33 #include "llvm/IR/Operator.h" 34 #include "llvm/IR/Type.h" 35 #include "llvm/IR/Value.h" 36 #include "llvm/Support/AtomicOrdering.h" 37 #include "llvm/Support/Casting.h" 38 #include "llvm/Support/ErrorHandling.h" 39 #include "llvm/Support/MathExtras.h" 40 #include "llvm/Support/TypeSize.h" 41 #include <algorithm> 42 #include <cassert> 43 #include <cstdint> 44 #include <vector> 45 46 using namespace llvm; 47 48 static cl::opt<bool> DisableI2pP2iOpt( 49 "disable-i2p-p2i-opt", cl::init(false), 50 cl::desc("Disables inttoptr/ptrtoint roundtrip optimization")); 51 52 //===----------------------------------------------------------------------===// 53 // AllocaInst Class 54 //===----------------------------------------------------------------------===// 55 56 Optional<TypeSize> 57 AllocaInst::getAllocationSizeInBits(const DataLayout &DL) const { 58 TypeSize Size = DL.getTypeAllocSizeInBits(getAllocatedType()); 59 if (isArrayAllocation()) { 60 auto *C = dyn_cast<ConstantInt>(getArraySize()); 61 if (!C) 62 return None; 63 assert(!Size.isScalable() && "Array elements cannot have a scalable size"); 64 Size *= C->getZExtValue(); 65 } 66 return Size; 67 } 68 69 //===----------------------------------------------------------------------===// 70 // SelectInst Class 71 //===----------------------------------------------------------------------===// 72 73 /// areInvalidOperands - Return a string if the specified operands are invalid 74 /// for a select operation, otherwise return null. 75 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) { 76 if (Op1->getType() != Op2->getType()) 77 return "both values to select must have same type"; 78 79 if (Op1->getType()->isTokenTy()) 80 return "select values cannot have token type"; 81 82 if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) { 83 // Vector select. 84 if (VT->getElementType() != Type::getInt1Ty(Op0->getContext())) 85 return "vector select condition element type must be i1"; 86 VectorType *ET = dyn_cast<VectorType>(Op1->getType()); 87 if (!ET) 88 return "selected values for vector select must be vectors"; 89 if (ET->getElementCount() != VT->getElementCount()) 90 return "vector select requires selected vectors to have " 91 "the same vector length as select condition"; 92 } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) { 93 return "select condition must be i1 or <n x i1>"; 94 } 95 return nullptr; 96 } 97 98 //===----------------------------------------------------------------------===// 99 // PHINode Class 100 //===----------------------------------------------------------------------===// 101 102 PHINode::PHINode(const PHINode &PN) 103 : Instruction(PN.getType(), Instruction::PHI, nullptr, PN.getNumOperands()), 104 ReservedSpace(PN.getNumOperands()) { 105 allocHungoffUses(PN.getNumOperands()); 106 std::copy(PN.op_begin(), PN.op_end(), op_begin()); 107 std::copy(PN.block_begin(), PN.block_end(), block_begin()); 108 SubclassOptionalData = PN.SubclassOptionalData; 109 } 110 111 // removeIncomingValue - Remove an incoming value. This is useful if a 112 // predecessor basic block is deleted. 113 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) { 114 Value *Removed = getIncomingValue(Idx); 115 116 // Move everything after this operand down. 117 // 118 // FIXME: we could just swap with the end of the list, then erase. However, 119 // clients might not expect this to happen. The code as it is thrashes the 120 // use/def lists, which is kinda lame. 121 std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx); 122 std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx); 123 124 // Nuke the last value. 125 Op<-1>().set(nullptr); 126 setNumHungOffUseOperands(getNumOperands() - 1); 127 128 // If the PHI node is dead, because it has zero entries, nuke it now. 129 if (getNumOperands() == 0 && DeletePHIIfEmpty) { 130 // If anyone is using this PHI, make them use a dummy value instead... 131 replaceAllUsesWith(UndefValue::get(getType())); 132 eraseFromParent(); 133 } 134 return Removed; 135 } 136 137 /// growOperands - grow operands - This grows the operand list in response 138 /// to a push_back style of operation. This grows the number of ops by 1.5 139 /// times. 140 /// 141 void PHINode::growOperands() { 142 unsigned e = getNumOperands(); 143 unsigned NumOps = e + e / 2; 144 if (NumOps < 2) NumOps = 2; // 2 op PHI nodes are VERY common. 145 146 ReservedSpace = NumOps; 147 growHungoffUses(ReservedSpace, /* IsPhi */ true); 148 } 149 150 /// hasConstantValue - If the specified PHI node always merges together the same 151 /// value, return the value, otherwise return null. 152 Value *PHINode::hasConstantValue() const { 153 // Exploit the fact that phi nodes always have at least one entry. 154 Value *ConstantValue = getIncomingValue(0); 155 for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i) 156 if (getIncomingValue(i) != ConstantValue && getIncomingValue(i) != this) { 157 if (ConstantValue != this) 158 return nullptr; // Incoming values not all the same. 159 // The case where the first value is this PHI. 160 ConstantValue = getIncomingValue(i); 161 } 162 if (ConstantValue == this) 163 return UndefValue::get(getType()); 164 return ConstantValue; 165 } 166 167 /// hasConstantOrUndefValue - Whether the specified PHI node always merges 168 /// together the same value, assuming that undefs result in the same value as 169 /// non-undefs. 170 /// Unlike \ref hasConstantValue, this does not return a value because the 171 /// unique non-undef incoming value need not dominate the PHI node. 172 bool PHINode::hasConstantOrUndefValue() const { 173 Value *ConstantValue = nullptr; 174 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i) { 175 Value *Incoming = getIncomingValue(i); 176 if (Incoming != this && !isa<UndefValue>(Incoming)) { 177 if (ConstantValue && ConstantValue != Incoming) 178 return false; 179 ConstantValue = Incoming; 180 } 181 } 182 return true; 183 } 184 185 //===----------------------------------------------------------------------===// 186 // LandingPadInst Implementation 187 //===----------------------------------------------------------------------===// 188 189 LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues, 190 const Twine &NameStr, Instruction *InsertBefore) 191 : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertBefore) { 192 init(NumReservedValues, NameStr); 193 } 194 195 LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues, 196 const Twine &NameStr, BasicBlock *InsertAtEnd) 197 : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertAtEnd) { 198 init(NumReservedValues, NameStr); 199 } 200 201 LandingPadInst::LandingPadInst(const LandingPadInst &LP) 202 : Instruction(LP.getType(), Instruction::LandingPad, nullptr, 203 LP.getNumOperands()), 204 ReservedSpace(LP.getNumOperands()) { 205 allocHungoffUses(LP.getNumOperands()); 206 Use *OL = getOperandList(); 207 const Use *InOL = LP.getOperandList(); 208 for (unsigned I = 0, E = ReservedSpace; I != E; ++I) 209 OL[I] = InOL[I]; 210 211 setCleanup(LP.isCleanup()); 212 } 213 214 LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses, 215 const Twine &NameStr, 216 Instruction *InsertBefore) { 217 return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertBefore); 218 } 219 220 LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses, 221 const Twine &NameStr, 222 BasicBlock *InsertAtEnd) { 223 return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertAtEnd); 224 } 225 226 void LandingPadInst::init(unsigned NumReservedValues, const Twine &NameStr) { 227 ReservedSpace = NumReservedValues; 228 setNumHungOffUseOperands(0); 229 allocHungoffUses(ReservedSpace); 230 setName(NameStr); 231 setCleanup(false); 232 } 233 234 /// growOperands - grow operands - This grows the operand list in response to a 235 /// push_back style of operation. This grows the number of ops by 2 times. 236 void LandingPadInst::growOperands(unsigned Size) { 237 unsigned e = getNumOperands(); 238 if (ReservedSpace >= e + Size) return; 239 ReservedSpace = (std::max(e, 1U) + Size / 2) * 2; 240 growHungoffUses(ReservedSpace); 241 } 242 243 void LandingPadInst::addClause(Constant *Val) { 244 unsigned OpNo = getNumOperands(); 245 growOperands(1); 246 assert(OpNo < ReservedSpace && "Growing didn't work!"); 247 setNumHungOffUseOperands(getNumOperands() + 1); 248 getOperandList()[OpNo] = Val; 249 } 250 251 //===----------------------------------------------------------------------===// 252 // CallBase Implementation 253 //===----------------------------------------------------------------------===// 254 255 CallBase *CallBase::Create(CallBase *CB, ArrayRef<OperandBundleDef> Bundles, 256 Instruction *InsertPt) { 257 switch (CB->getOpcode()) { 258 case Instruction::Call: 259 return CallInst::Create(cast<CallInst>(CB), Bundles, InsertPt); 260 case Instruction::Invoke: 261 return InvokeInst::Create(cast<InvokeInst>(CB), Bundles, InsertPt); 262 case Instruction::CallBr: 263 return CallBrInst::Create(cast<CallBrInst>(CB), Bundles, InsertPt); 264 default: 265 llvm_unreachable("Unknown CallBase sub-class!"); 266 } 267 } 268 269 CallBase *CallBase::Create(CallBase *CI, OperandBundleDef OpB, 270 Instruction *InsertPt) { 271 SmallVector<OperandBundleDef, 2> OpDefs; 272 for (unsigned i = 0, e = CI->getNumOperandBundles(); i < e; ++i) { 273 auto ChildOB = CI->getOperandBundleAt(i); 274 if (ChildOB.getTagName() != OpB.getTag()) 275 OpDefs.emplace_back(ChildOB); 276 } 277 OpDefs.emplace_back(OpB); 278 return CallBase::Create(CI, OpDefs, InsertPt); 279 } 280 281 282 Function *CallBase::getCaller() { return getParent()->getParent(); } 283 284 unsigned CallBase::getNumSubclassExtraOperandsDynamic() const { 285 assert(getOpcode() == Instruction::CallBr && "Unexpected opcode!"); 286 return cast<CallBrInst>(this)->getNumIndirectDests() + 1; 287 } 288 289 bool CallBase::isIndirectCall() const { 290 const Value *V = getCalledOperand(); 291 if (isa<Function>(V) || isa<Constant>(V)) 292 return false; 293 return !isInlineAsm(); 294 } 295 296 /// Tests if this call site must be tail call optimized. Only a CallInst can 297 /// be tail call optimized. 298 bool CallBase::isMustTailCall() const { 299 if (auto *CI = dyn_cast<CallInst>(this)) 300 return CI->isMustTailCall(); 301 return false; 302 } 303 304 /// Tests if this call site is marked as a tail call. 305 bool CallBase::isTailCall() const { 306 if (auto *CI = dyn_cast<CallInst>(this)) 307 return CI->isTailCall(); 308 return false; 309 } 310 311 Intrinsic::ID CallBase::getIntrinsicID() const { 312 if (auto *F = getCalledFunction()) 313 return F->getIntrinsicID(); 314 return Intrinsic::not_intrinsic; 315 } 316 317 bool CallBase::isReturnNonNull() const { 318 if (hasRetAttr(Attribute::NonNull)) 319 return true; 320 321 if (getRetDereferenceableBytes() > 0 && 322 !NullPointerIsDefined(getCaller(), getType()->getPointerAddressSpace())) 323 return true; 324 325 return false; 326 } 327 328 Value *CallBase::getReturnedArgOperand() const { 329 unsigned Index; 330 331 if (Attrs.hasAttrSomewhere(Attribute::Returned, &Index)) 332 return getArgOperand(Index - AttributeList::FirstArgIndex); 333 if (const Function *F = getCalledFunction()) 334 if (F->getAttributes().hasAttrSomewhere(Attribute::Returned, &Index)) 335 return getArgOperand(Index - AttributeList::FirstArgIndex); 336 337 return nullptr; 338 } 339 340 /// Determine whether the argument or parameter has the given attribute. 341 bool CallBase::paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const { 342 assert(ArgNo < arg_size() && "Param index out of bounds!"); 343 344 if (Attrs.hasParamAttr(ArgNo, Kind)) 345 return true; 346 if (const Function *F = getCalledFunction()) 347 return F->getAttributes().hasParamAttr(ArgNo, Kind); 348 return false; 349 } 350 351 bool CallBase::hasFnAttrOnCalledFunction(Attribute::AttrKind Kind) const { 352 Value *V = getCalledOperand(); 353 if (auto *CE = dyn_cast<ConstantExpr>(V)) 354 if (CE->getOpcode() == BitCast) 355 V = CE->getOperand(0); 356 357 if (auto *F = dyn_cast<Function>(V)) 358 return F->getAttributes().hasFnAttr(Kind); 359 360 return false; 361 } 362 363 bool CallBase::hasFnAttrOnCalledFunction(StringRef Kind) const { 364 Value *V = getCalledOperand(); 365 if (auto *CE = dyn_cast<ConstantExpr>(V)) 366 if (CE->getOpcode() == BitCast) 367 V = CE->getOperand(0); 368 369 if (auto *F = dyn_cast<Function>(V)) 370 return F->getAttributes().hasFnAttr(Kind); 371 372 return false; 373 } 374 375 void CallBase::getOperandBundlesAsDefs( 376 SmallVectorImpl<OperandBundleDef> &Defs) const { 377 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) 378 Defs.emplace_back(getOperandBundleAt(i)); 379 } 380 381 CallBase::op_iterator 382 CallBase::populateBundleOperandInfos(ArrayRef<OperandBundleDef> Bundles, 383 const unsigned BeginIndex) { 384 auto It = op_begin() + BeginIndex; 385 for (auto &B : Bundles) 386 It = std::copy(B.input_begin(), B.input_end(), It); 387 388 auto *ContextImpl = getContext().pImpl; 389 auto BI = Bundles.begin(); 390 unsigned CurrentIndex = BeginIndex; 391 392 for (auto &BOI : bundle_op_infos()) { 393 assert(BI != Bundles.end() && "Incorrect allocation?"); 394 395 BOI.Tag = ContextImpl->getOrInsertBundleTag(BI->getTag()); 396 BOI.Begin = CurrentIndex; 397 BOI.End = CurrentIndex + BI->input_size(); 398 CurrentIndex = BOI.End; 399 BI++; 400 } 401 402 assert(BI == Bundles.end() && "Incorrect allocation?"); 403 404 return It; 405 } 406 407 CallBase::BundleOpInfo &CallBase::getBundleOpInfoForOperand(unsigned OpIdx) { 408 /// When there isn't many bundles, we do a simple linear search. 409 /// Else fallback to a binary-search that use the fact that bundles usually 410 /// have similar number of argument to get faster convergence. 411 if (bundle_op_info_end() - bundle_op_info_begin() < 8) { 412 for (auto &BOI : bundle_op_infos()) 413 if (BOI.Begin <= OpIdx && OpIdx < BOI.End) 414 return BOI; 415 416 llvm_unreachable("Did not find operand bundle for operand!"); 417 } 418 419 assert(OpIdx >= arg_size() && "the Idx is not in the operand bundles"); 420 assert(bundle_op_info_end() - bundle_op_info_begin() > 0 && 421 OpIdx < std::prev(bundle_op_info_end())->End && 422 "The Idx isn't in the operand bundle"); 423 424 /// We need a decimal number below and to prevent using floating point numbers 425 /// we use an intergal value multiplied by this constant. 426 constexpr unsigned NumberScaling = 1024; 427 428 bundle_op_iterator Begin = bundle_op_info_begin(); 429 bundle_op_iterator End = bundle_op_info_end(); 430 bundle_op_iterator Current = Begin; 431 432 while (Begin != End) { 433 unsigned ScaledOperandPerBundle = 434 NumberScaling * (std::prev(End)->End - Begin->Begin) / (End - Begin); 435 Current = Begin + (((OpIdx - Begin->Begin) * NumberScaling) / 436 ScaledOperandPerBundle); 437 if (Current >= End) 438 Current = std::prev(End); 439 assert(Current < End && Current >= Begin && 440 "the operand bundle doesn't cover every value in the range"); 441 if (OpIdx >= Current->Begin && OpIdx < Current->End) 442 break; 443 if (OpIdx >= Current->End) 444 Begin = Current + 1; 445 else 446 End = Current; 447 } 448 449 assert(OpIdx >= Current->Begin && OpIdx < Current->End && 450 "the operand bundle doesn't cover every value in the range"); 451 return *Current; 452 } 453 454 CallBase *CallBase::addOperandBundle(CallBase *CB, uint32_t ID, 455 OperandBundleDef OB, 456 Instruction *InsertPt) { 457 if (CB->getOperandBundle(ID)) 458 return CB; 459 460 SmallVector<OperandBundleDef, 1> Bundles; 461 CB->getOperandBundlesAsDefs(Bundles); 462 Bundles.push_back(OB); 463 return Create(CB, Bundles, InsertPt); 464 } 465 466 CallBase *CallBase::removeOperandBundle(CallBase *CB, uint32_t ID, 467 Instruction *InsertPt) { 468 SmallVector<OperandBundleDef, 1> Bundles; 469 bool CreateNew = false; 470 471 for (unsigned I = 0, E = CB->getNumOperandBundles(); I != E; ++I) { 472 auto Bundle = CB->getOperandBundleAt(I); 473 if (Bundle.getTagID() == ID) { 474 CreateNew = true; 475 continue; 476 } 477 Bundles.emplace_back(Bundle); 478 } 479 480 return CreateNew ? Create(CB, Bundles, InsertPt) : CB; 481 } 482 483 bool CallBase::hasReadingOperandBundles() const { 484 // Implementation note: this is a conservative implementation of operand 485 // bundle semantics, where *any* non-assume operand bundle (other than 486 // ptrauth) forces a callsite to be at least readonly. 487 return hasOperandBundlesOtherThan(LLVMContext::OB_ptrauth) && 488 getIntrinsicID() != Intrinsic::assume; 489 } 490 491 //===----------------------------------------------------------------------===// 492 // CallInst Implementation 493 //===----------------------------------------------------------------------===// 494 495 void CallInst::init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args, 496 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr) { 497 this->FTy = FTy; 498 assert(getNumOperands() == Args.size() + CountBundleInputs(Bundles) + 1 && 499 "NumOperands not set up?"); 500 501 #ifndef NDEBUG 502 assert((Args.size() == FTy->getNumParams() || 503 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) && 504 "Calling a function with bad signature!"); 505 506 for (unsigned i = 0; i != Args.size(); ++i) 507 assert((i >= FTy->getNumParams() || 508 FTy->getParamType(i) == Args[i]->getType()) && 509 "Calling a function with a bad signature!"); 510 #endif 511 512 // Set operands in order of their index to match use-list-order 513 // prediction. 514 llvm::copy(Args, op_begin()); 515 setCalledOperand(Func); 516 517 auto It = populateBundleOperandInfos(Bundles, Args.size()); 518 (void)It; 519 assert(It + 1 == op_end() && "Should add up!"); 520 521 setName(NameStr); 522 } 523 524 void CallInst::init(FunctionType *FTy, Value *Func, const Twine &NameStr) { 525 this->FTy = FTy; 526 assert(getNumOperands() == 1 && "NumOperands not set up?"); 527 setCalledOperand(Func); 528 529 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature"); 530 531 setName(NameStr); 532 } 533 534 CallInst::CallInst(FunctionType *Ty, Value *Func, const Twine &Name, 535 Instruction *InsertBefore) 536 : CallBase(Ty->getReturnType(), Instruction::Call, 537 OperandTraits<CallBase>::op_end(this) - 1, 1, InsertBefore) { 538 init(Ty, Func, Name); 539 } 540 541 CallInst::CallInst(FunctionType *Ty, Value *Func, const Twine &Name, 542 BasicBlock *InsertAtEnd) 543 : CallBase(Ty->getReturnType(), Instruction::Call, 544 OperandTraits<CallBase>::op_end(this) - 1, 1, InsertAtEnd) { 545 init(Ty, Func, Name); 546 } 547 548 CallInst::CallInst(const CallInst &CI) 549 : CallBase(CI.Attrs, CI.FTy, CI.getType(), Instruction::Call, 550 OperandTraits<CallBase>::op_end(this) - CI.getNumOperands(), 551 CI.getNumOperands()) { 552 setTailCallKind(CI.getTailCallKind()); 553 setCallingConv(CI.getCallingConv()); 554 555 std::copy(CI.op_begin(), CI.op_end(), op_begin()); 556 std::copy(CI.bundle_op_info_begin(), CI.bundle_op_info_end(), 557 bundle_op_info_begin()); 558 SubclassOptionalData = CI.SubclassOptionalData; 559 } 560 561 CallInst *CallInst::Create(CallInst *CI, ArrayRef<OperandBundleDef> OpB, 562 Instruction *InsertPt) { 563 std::vector<Value *> Args(CI->arg_begin(), CI->arg_end()); 564 565 auto *NewCI = CallInst::Create(CI->getFunctionType(), CI->getCalledOperand(), 566 Args, OpB, CI->getName(), InsertPt); 567 NewCI->setTailCallKind(CI->getTailCallKind()); 568 NewCI->setCallingConv(CI->getCallingConv()); 569 NewCI->SubclassOptionalData = CI->SubclassOptionalData; 570 NewCI->setAttributes(CI->getAttributes()); 571 NewCI->setDebugLoc(CI->getDebugLoc()); 572 return NewCI; 573 } 574 575 // Update profile weight for call instruction by scaling it using the ratio 576 // of S/T. The meaning of "branch_weights" meta data for call instruction is 577 // transfered to represent call count. 578 void CallInst::updateProfWeight(uint64_t S, uint64_t T) { 579 auto *ProfileData = getMetadata(LLVMContext::MD_prof); 580 if (ProfileData == nullptr) 581 return; 582 583 auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0)); 584 if (!ProfDataName || (!ProfDataName->getString().equals("branch_weights") && 585 !ProfDataName->getString().equals("VP"))) 586 return; 587 588 if (T == 0) { 589 LLVM_DEBUG(dbgs() << "Attempting to update profile weights will result in " 590 "div by 0. Ignoring. Likely the function " 591 << getParent()->getParent()->getName() 592 << " has 0 entry count, and contains call instructions " 593 "with non-zero prof info."); 594 return; 595 } 596 597 MDBuilder MDB(getContext()); 598 SmallVector<Metadata *, 3> Vals; 599 Vals.push_back(ProfileData->getOperand(0)); 600 APInt APS(128, S), APT(128, T); 601 if (ProfDataName->getString().equals("branch_weights") && 602 ProfileData->getNumOperands() > 0) { 603 // Using APInt::div may be expensive, but most cases should fit 64 bits. 604 APInt Val(128, mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1)) 605 ->getValue() 606 .getZExtValue()); 607 Val *= APS; 608 Vals.push_back(MDB.createConstant( 609 ConstantInt::get(Type::getInt32Ty(getContext()), 610 Val.udiv(APT).getLimitedValue(UINT32_MAX)))); 611 } else if (ProfDataName->getString().equals("VP")) 612 for (unsigned i = 1; i < ProfileData->getNumOperands(); i += 2) { 613 // The first value is the key of the value profile, which will not change. 614 Vals.push_back(ProfileData->getOperand(i)); 615 uint64_t Count = 616 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(i + 1)) 617 ->getValue() 618 .getZExtValue(); 619 // Don't scale the magic number. 620 if (Count == NOMORE_ICP_MAGICNUM) { 621 Vals.push_back(ProfileData->getOperand(i + 1)); 622 continue; 623 } 624 // Using APInt::div may be expensive, but most cases should fit 64 bits. 625 APInt Val(128, Count); 626 Val *= APS; 627 Vals.push_back(MDB.createConstant( 628 ConstantInt::get(Type::getInt64Ty(getContext()), 629 Val.udiv(APT).getLimitedValue()))); 630 } 631 setMetadata(LLVMContext::MD_prof, MDNode::get(getContext(), Vals)); 632 } 633 634 /// IsConstantOne - Return true only if val is constant int 1 635 static bool IsConstantOne(Value *val) { 636 assert(val && "IsConstantOne does not work with nullptr val"); 637 const ConstantInt *CVal = dyn_cast<ConstantInt>(val); 638 return CVal && CVal->isOne(); 639 } 640 641 static Instruction *createMalloc(Instruction *InsertBefore, 642 BasicBlock *InsertAtEnd, Type *IntPtrTy, 643 Type *AllocTy, Value *AllocSize, 644 Value *ArraySize, 645 ArrayRef<OperandBundleDef> OpB, 646 Function *MallocF, const Twine &Name) { 647 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) && 648 "createMalloc needs either InsertBefore or InsertAtEnd"); 649 650 // malloc(type) becomes: 651 // bitcast (i8* malloc(typeSize)) to type* 652 // malloc(type, arraySize) becomes: 653 // bitcast (i8* malloc(typeSize*arraySize)) to type* 654 if (!ArraySize) 655 ArraySize = ConstantInt::get(IntPtrTy, 1); 656 else if (ArraySize->getType() != IntPtrTy) { 657 if (InsertBefore) 658 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false, 659 "", InsertBefore); 660 else 661 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false, 662 "", InsertAtEnd); 663 } 664 665 if (!IsConstantOne(ArraySize)) { 666 if (IsConstantOne(AllocSize)) { 667 AllocSize = ArraySize; // Operand * 1 = Operand 668 } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) { 669 Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy, 670 false /*ZExt*/); 671 // Malloc arg is constant product of type size and array size 672 AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize)); 673 } else { 674 // Multiply type size by the array size... 675 if (InsertBefore) 676 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize, 677 "mallocsize", InsertBefore); 678 else 679 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize, 680 "mallocsize", InsertAtEnd); 681 } 682 } 683 684 assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size"); 685 // Create the call to Malloc. 686 BasicBlock *BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd; 687 Module *M = BB->getParent()->getParent(); 688 Type *BPTy = Type::getInt8PtrTy(BB->getContext()); 689 FunctionCallee MallocFunc = MallocF; 690 if (!MallocFunc) 691 // prototype malloc as "void *malloc(size_t)" 692 MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy); 693 PointerType *AllocPtrType = PointerType::getUnqual(AllocTy); 694 CallInst *MCall = nullptr; 695 Instruction *Result = nullptr; 696 if (InsertBefore) { 697 MCall = CallInst::Create(MallocFunc, AllocSize, OpB, "malloccall", 698 InsertBefore); 699 Result = MCall; 700 if (Result->getType() != AllocPtrType) 701 // Create a cast instruction to convert to the right type... 702 Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore); 703 } else { 704 MCall = CallInst::Create(MallocFunc, AllocSize, OpB, "malloccall"); 705 Result = MCall; 706 if (Result->getType() != AllocPtrType) { 707 InsertAtEnd->getInstList().push_back(MCall); 708 // Create a cast instruction to convert to the right type... 709 Result = new BitCastInst(MCall, AllocPtrType, Name); 710 } 711 } 712 MCall->setTailCall(); 713 if (Function *F = dyn_cast<Function>(MallocFunc.getCallee())) { 714 MCall->setCallingConv(F->getCallingConv()); 715 if (!F->returnDoesNotAlias()) 716 F->setReturnDoesNotAlias(); 717 } 718 assert(!MCall->getType()->isVoidTy() && "Malloc has void return type"); 719 720 return Result; 721 } 722 723 /// CreateMalloc - Generate the IR for a call to malloc: 724 /// 1. Compute the malloc call's argument as the specified type's size, 725 /// possibly multiplied by the array size if the array size is not 726 /// constant 1. 727 /// 2. Call malloc with that argument. 728 /// 3. Bitcast the result of the malloc call to the specified type. 729 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore, 730 Type *IntPtrTy, Type *AllocTy, 731 Value *AllocSize, Value *ArraySize, 732 Function *MallocF, 733 const Twine &Name) { 734 return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize, 735 ArraySize, None, MallocF, Name); 736 } 737 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore, 738 Type *IntPtrTy, Type *AllocTy, 739 Value *AllocSize, Value *ArraySize, 740 ArrayRef<OperandBundleDef> OpB, 741 Function *MallocF, 742 const Twine &Name) { 743 return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize, 744 ArraySize, OpB, MallocF, Name); 745 } 746 747 /// CreateMalloc - Generate the IR for a call to malloc: 748 /// 1. Compute the malloc call's argument as the specified type's size, 749 /// possibly multiplied by the array size if the array size is not 750 /// constant 1. 751 /// 2. Call malloc with that argument. 752 /// 3. Bitcast the result of the malloc call to the specified type. 753 /// Note: This function does not add the bitcast to the basic block, that is the 754 /// responsibility of the caller. 755 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd, 756 Type *IntPtrTy, Type *AllocTy, 757 Value *AllocSize, Value *ArraySize, 758 Function *MallocF, const Twine &Name) { 759 return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize, 760 ArraySize, None, MallocF, Name); 761 } 762 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd, 763 Type *IntPtrTy, Type *AllocTy, 764 Value *AllocSize, Value *ArraySize, 765 ArrayRef<OperandBundleDef> OpB, 766 Function *MallocF, const Twine &Name) { 767 return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize, 768 ArraySize, OpB, MallocF, Name); 769 } 770 771 static Instruction *createFree(Value *Source, 772 ArrayRef<OperandBundleDef> Bundles, 773 Instruction *InsertBefore, 774 BasicBlock *InsertAtEnd) { 775 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) && 776 "createFree needs either InsertBefore or InsertAtEnd"); 777 assert(Source->getType()->isPointerTy() && 778 "Can not free something of nonpointer type!"); 779 780 BasicBlock *BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd; 781 Module *M = BB->getParent()->getParent(); 782 783 Type *VoidTy = Type::getVoidTy(M->getContext()); 784 Type *IntPtrTy = Type::getInt8PtrTy(M->getContext()); 785 // prototype free as "void free(void*)" 786 FunctionCallee FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy); 787 CallInst *Result = nullptr; 788 Value *PtrCast = Source; 789 if (InsertBefore) { 790 if (Source->getType() != IntPtrTy) 791 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore); 792 Result = CallInst::Create(FreeFunc, PtrCast, Bundles, "", InsertBefore); 793 } else { 794 if (Source->getType() != IntPtrTy) 795 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd); 796 Result = CallInst::Create(FreeFunc, PtrCast, Bundles, ""); 797 } 798 Result->setTailCall(); 799 if (Function *F = dyn_cast<Function>(FreeFunc.getCallee())) 800 Result->setCallingConv(F->getCallingConv()); 801 802 return Result; 803 } 804 805 /// CreateFree - Generate the IR for a call to the builtin free function. 806 Instruction *CallInst::CreateFree(Value *Source, Instruction *InsertBefore) { 807 return createFree(Source, None, InsertBefore, nullptr); 808 } 809 Instruction *CallInst::CreateFree(Value *Source, 810 ArrayRef<OperandBundleDef> Bundles, 811 Instruction *InsertBefore) { 812 return createFree(Source, Bundles, InsertBefore, nullptr); 813 } 814 815 /// CreateFree - Generate the IR for a call to the builtin free function. 816 /// Note: This function does not add the call to the basic block, that is the 817 /// responsibility of the caller. 818 Instruction *CallInst::CreateFree(Value *Source, BasicBlock *InsertAtEnd) { 819 Instruction *FreeCall = createFree(Source, None, nullptr, InsertAtEnd); 820 assert(FreeCall && "CreateFree did not create a CallInst"); 821 return FreeCall; 822 } 823 Instruction *CallInst::CreateFree(Value *Source, 824 ArrayRef<OperandBundleDef> Bundles, 825 BasicBlock *InsertAtEnd) { 826 Instruction *FreeCall = createFree(Source, Bundles, nullptr, InsertAtEnd); 827 assert(FreeCall && "CreateFree did not create a CallInst"); 828 return FreeCall; 829 } 830 831 //===----------------------------------------------------------------------===// 832 // InvokeInst Implementation 833 //===----------------------------------------------------------------------===// 834 835 void InvokeInst::init(FunctionType *FTy, Value *Fn, BasicBlock *IfNormal, 836 BasicBlock *IfException, ArrayRef<Value *> Args, 837 ArrayRef<OperandBundleDef> Bundles, 838 const Twine &NameStr) { 839 this->FTy = FTy; 840 841 assert((int)getNumOperands() == 842 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)) && 843 "NumOperands not set up?"); 844 845 #ifndef NDEBUG 846 assert(((Args.size() == FTy->getNumParams()) || 847 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) && 848 "Invoking a function with bad signature"); 849 850 for (unsigned i = 0, e = Args.size(); i != e; i++) 851 assert((i >= FTy->getNumParams() || 852 FTy->getParamType(i) == Args[i]->getType()) && 853 "Invoking a function with a bad signature!"); 854 #endif 855 856 // Set operands in order of their index to match use-list-order 857 // prediction. 858 llvm::copy(Args, op_begin()); 859 setNormalDest(IfNormal); 860 setUnwindDest(IfException); 861 setCalledOperand(Fn); 862 863 auto It = populateBundleOperandInfos(Bundles, Args.size()); 864 (void)It; 865 assert(It + 3 == op_end() && "Should add up!"); 866 867 setName(NameStr); 868 } 869 870 InvokeInst::InvokeInst(const InvokeInst &II) 871 : CallBase(II.Attrs, II.FTy, II.getType(), Instruction::Invoke, 872 OperandTraits<CallBase>::op_end(this) - II.getNumOperands(), 873 II.getNumOperands()) { 874 setCallingConv(II.getCallingConv()); 875 std::copy(II.op_begin(), II.op_end(), op_begin()); 876 std::copy(II.bundle_op_info_begin(), II.bundle_op_info_end(), 877 bundle_op_info_begin()); 878 SubclassOptionalData = II.SubclassOptionalData; 879 } 880 881 InvokeInst *InvokeInst::Create(InvokeInst *II, ArrayRef<OperandBundleDef> OpB, 882 Instruction *InsertPt) { 883 std::vector<Value *> Args(II->arg_begin(), II->arg_end()); 884 885 auto *NewII = InvokeInst::Create( 886 II->getFunctionType(), II->getCalledOperand(), II->getNormalDest(), 887 II->getUnwindDest(), Args, OpB, II->getName(), InsertPt); 888 NewII->setCallingConv(II->getCallingConv()); 889 NewII->SubclassOptionalData = II->SubclassOptionalData; 890 NewII->setAttributes(II->getAttributes()); 891 NewII->setDebugLoc(II->getDebugLoc()); 892 return NewII; 893 } 894 895 LandingPadInst *InvokeInst::getLandingPadInst() const { 896 return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI()); 897 } 898 899 //===----------------------------------------------------------------------===// 900 // CallBrInst Implementation 901 //===----------------------------------------------------------------------===// 902 903 void CallBrInst::init(FunctionType *FTy, Value *Fn, BasicBlock *Fallthrough, 904 ArrayRef<BasicBlock *> IndirectDests, 905 ArrayRef<Value *> Args, 906 ArrayRef<OperandBundleDef> Bundles, 907 const Twine &NameStr) { 908 this->FTy = FTy; 909 910 assert((int)getNumOperands() == 911 ComputeNumOperands(Args.size(), IndirectDests.size(), 912 CountBundleInputs(Bundles)) && 913 "NumOperands not set up?"); 914 915 #ifndef NDEBUG 916 assert(((Args.size() == FTy->getNumParams()) || 917 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) && 918 "Calling a function with bad signature"); 919 920 for (unsigned i = 0, e = Args.size(); i != e; i++) 921 assert((i >= FTy->getNumParams() || 922 FTy->getParamType(i) == Args[i]->getType()) && 923 "Calling a function with a bad signature!"); 924 #endif 925 926 // Set operands in order of their index to match use-list-order 927 // prediction. 928 std::copy(Args.begin(), Args.end(), op_begin()); 929 NumIndirectDests = IndirectDests.size(); 930 setDefaultDest(Fallthrough); 931 for (unsigned i = 0; i != NumIndirectDests; ++i) 932 setIndirectDest(i, IndirectDests[i]); 933 setCalledOperand(Fn); 934 935 auto It = populateBundleOperandInfos(Bundles, Args.size()); 936 (void)It; 937 assert(It + 2 + IndirectDests.size() == op_end() && "Should add up!"); 938 939 setName(NameStr); 940 } 941 942 void CallBrInst::updateArgBlockAddresses(unsigned i, BasicBlock *B) { 943 assert(getNumIndirectDests() > i && "IndirectDest # out of range for callbr"); 944 if (BasicBlock *OldBB = getIndirectDest(i)) { 945 BlockAddress *Old = BlockAddress::get(OldBB); 946 BlockAddress *New = BlockAddress::get(B); 947 for (unsigned ArgNo = 0, e = arg_size(); ArgNo != e; ++ArgNo) 948 if (dyn_cast<BlockAddress>(getArgOperand(ArgNo)) == Old) 949 setArgOperand(ArgNo, New); 950 } 951 } 952 953 CallBrInst::CallBrInst(const CallBrInst &CBI) 954 : CallBase(CBI.Attrs, CBI.FTy, CBI.getType(), Instruction::CallBr, 955 OperandTraits<CallBase>::op_end(this) - CBI.getNumOperands(), 956 CBI.getNumOperands()) { 957 setCallingConv(CBI.getCallingConv()); 958 std::copy(CBI.op_begin(), CBI.op_end(), op_begin()); 959 std::copy(CBI.bundle_op_info_begin(), CBI.bundle_op_info_end(), 960 bundle_op_info_begin()); 961 SubclassOptionalData = CBI.SubclassOptionalData; 962 NumIndirectDests = CBI.NumIndirectDests; 963 } 964 965 CallBrInst *CallBrInst::Create(CallBrInst *CBI, ArrayRef<OperandBundleDef> OpB, 966 Instruction *InsertPt) { 967 std::vector<Value *> Args(CBI->arg_begin(), CBI->arg_end()); 968 969 auto *NewCBI = CallBrInst::Create( 970 CBI->getFunctionType(), CBI->getCalledOperand(), CBI->getDefaultDest(), 971 CBI->getIndirectDests(), Args, OpB, CBI->getName(), InsertPt); 972 NewCBI->setCallingConv(CBI->getCallingConv()); 973 NewCBI->SubclassOptionalData = CBI->SubclassOptionalData; 974 NewCBI->setAttributes(CBI->getAttributes()); 975 NewCBI->setDebugLoc(CBI->getDebugLoc()); 976 NewCBI->NumIndirectDests = CBI->NumIndirectDests; 977 return NewCBI; 978 } 979 980 //===----------------------------------------------------------------------===// 981 // ReturnInst Implementation 982 //===----------------------------------------------------------------------===// 983 984 ReturnInst::ReturnInst(const ReturnInst &RI) 985 : Instruction(Type::getVoidTy(RI.getContext()), Instruction::Ret, 986 OperandTraits<ReturnInst>::op_end(this) - RI.getNumOperands(), 987 RI.getNumOperands()) { 988 if (RI.getNumOperands()) 989 Op<0>() = RI.Op<0>(); 990 SubclassOptionalData = RI.SubclassOptionalData; 991 } 992 993 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore) 994 : Instruction(Type::getVoidTy(C), Instruction::Ret, 995 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal, 996 InsertBefore) { 997 if (retVal) 998 Op<0>() = retVal; 999 } 1000 1001 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd) 1002 : Instruction(Type::getVoidTy(C), Instruction::Ret, 1003 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal, 1004 InsertAtEnd) { 1005 if (retVal) 1006 Op<0>() = retVal; 1007 } 1008 1009 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd) 1010 : Instruction(Type::getVoidTy(Context), Instruction::Ret, 1011 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {} 1012 1013 //===----------------------------------------------------------------------===// 1014 // ResumeInst Implementation 1015 //===----------------------------------------------------------------------===// 1016 1017 ResumeInst::ResumeInst(const ResumeInst &RI) 1018 : Instruction(Type::getVoidTy(RI.getContext()), Instruction::Resume, 1019 OperandTraits<ResumeInst>::op_begin(this), 1) { 1020 Op<0>() = RI.Op<0>(); 1021 } 1022 1023 ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore) 1024 : Instruction(Type::getVoidTy(Exn->getContext()), Instruction::Resume, 1025 OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) { 1026 Op<0>() = Exn; 1027 } 1028 1029 ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd) 1030 : Instruction(Type::getVoidTy(Exn->getContext()), Instruction::Resume, 1031 OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) { 1032 Op<0>() = Exn; 1033 } 1034 1035 //===----------------------------------------------------------------------===// 1036 // CleanupReturnInst Implementation 1037 //===----------------------------------------------------------------------===// 1038 1039 CleanupReturnInst::CleanupReturnInst(const CleanupReturnInst &CRI) 1040 : Instruction(CRI.getType(), Instruction::CleanupRet, 1041 OperandTraits<CleanupReturnInst>::op_end(this) - 1042 CRI.getNumOperands(), 1043 CRI.getNumOperands()) { 1044 setSubclassData<Instruction::OpaqueField>( 1045 CRI.getSubclassData<Instruction::OpaqueField>()); 1046 Op<0>() = CRI.Op<0>(); 1047 if (CRI.hasUnwindDest()) 1048 Op<1>() = CRI.Op<1>(); 1049 } 1050 1051 void CleanupReturnInst::init(Value *CleanupPad, BasicBlock *UnwindBB) { 1052 if (UnwindBB) 1053 setSubclassData<UnwindDestField>(true); 1054 1055 Op<0>() = CleanupPad; 1056 if (UnwindBB) 1057 Op<1>() = UnwindBB; 1058 } 1059 1060 CleanupReturnInst::CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, 1061 unsigned Values, Instruction *InsertBefore) 1062 : Instruction(Type::getVoidTy(CleanupPad->getContext()), 1063 Instruction::CleanupRet, 1064 OperandTraits<CleanupReturnInst>::op_end(this) - Values, 1065 Values, InsertBefore) { 1066 init(CleanupPad, UnwindBB); 1067 } 1068 1069 CleanupReturnInst::CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, 1070 unsigned Values, BasicBlock *InsertAtEnd) 1071 : Instruction(Type::getVoidTy(CleanupPad->getContext()), 1072 Instruction::CleanupRet, 1073 OperandTraits<CleanupReturnInst>::op_end(this) - Values, 1074 Values, InsertAtEnd) { 1075 init(CleanupPad, UnwindBB); 1076 } 1077 1078 //===----------------------------------------------------------------------===// 1079 // CatchReturnInst Implementation 1080 //===----------------------------------------------------------------------===// 1081 void CatchReturnInst::init(Value *CatchPad, BasicBlock *BB) { 1082 Op<0>() = CatchPad; 1083 Op<1>() = BB; 1084 } 1085 1086 CatchReturnInst::CatchReturnInst(const CatchReturnInst &CRI) 1087 : Instruction(Type::getVoidTy(CRI.getContext()), Instruction::CatchRet, 1088 OperandTraits<CatchReturnInst>::op_begin(this), 2) { 1089 Op<0>() = CRI.Op<0>(); 1090 Op<1>() = CRI.Op<1>(); 1091 } 1092 1093 CatchReturnInst::CatchReturnInst(Value *CatchPad, BasicBlock *BB, 1094 Instruction *InsertBefore) 1095 : Instruction(Type::getVoidTy(BB->getContext()), Instruction::CatchRet, 1096 OperandTraits<CatchReturnInst>::op_begin(this), 2, 1097 InsertBefore) { 1098 init(CatchPad, BB); 1099 } 1100 1101 CatchReturnInst::CatchReturnInst(Value *CatchPad, BasicBlock *BB, 1102 BasicBlock *InsertAtEnd) 1103 : Instruction(Type::getVoidTy(BB->getContext()), Instruction::CatchRet, 1104 OperandTraits<CatchReturnInst>::op_begin(this), 2, 1105 InsertAtEnd) { 1106 init(CatchPad, BB); 1107 } 1108 1109 //===----------------------------------------------------------------------===// 1110 // CatchSwitchInst Implementation 1111 //===----------------------------------------------------------------------===// 1112 1113 CatchSwitchInst::CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest, 1114 unsigned NumReservedValues, 1115 const Twine &NameStr, 1116 Instruction *InsertBefore) 1117 : Instruction(ParentPad->getType(), Instruction::CatchSwitch, nullptr, 0, 1118 InsertBefore) { 1119 if (UnwindDest) 1120 ++NumReservedValues; 1121 init(ParentPad, UnwindDest, NumReservedValues + 1); 1122 setName(NameStr); 1123 } 1124 1125 CatchSwitchInst::CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest, 1126 unsigned NumReservedValues, 1127 const Twine &NameStr, BasicBlock *InsertAtEnd) 1128 : Instruction(ParentPad->getType(), Instruction::CatchSwitch, nullptr, 0, 1129 InsertAtEnd) { 1130 if (UnwindDest) 1131 ++NumReservedValues; 1132 init(ParentPad, UnwindDest, NumReservedValues + 1); 1133 setName(NameStr); 1134 } 1135 1136 CatchSwitchInst::CatchSwitchInst(const CatchSwitchInst &CSI) 1137 : Instruction(CSI.getType(), Instruction::CatchSwitch, nullptr, 1138 CSI.getNumOperands()) { 1139 init(CSI.getParentPad(), CSI.getUnwindDest(), CSI.getNumOperands()); 1140 setNumHungOffUseOperands(ReservedSpace); 1141 Use *OL = getOperandList(); 1142 const Use *InOL = CSI.getOperandList(); 1143 for (unsigned I = 1, E = ReservedSpace; I != E; ++I) 1144 OL[I] = InOL[I]; 1145 } 1146 1147 void CatchSwitchInst::init(Value *ParentPad, BasicBlock *UnwindDest, 1148 unsigned NumReservedValues) { 1149 assert(ParentPad && NumReservedValues); 1150 1151 ReservedSpace = NumReservedValues; 1152 setNumHungOffUseOperands(UnwindDest ? 2 : 1); 1153 allocHungoffUses(ReservedSpace); 1154 1155 Op<0>() = ParentPad; 1156 if (UnwindDest) { 1157 setSubclassData<UnwindDestField>(true); 1158 setUnwindDest(UnwindDest); 1159 } 1160 } 1161 1162 /// growOperands - grow operands - This grows the operand list in response to a 1163 /// push_back style of operation. This grows the number of ops by 2 times. 1164 void CatchSwitchInst::growOperands(unsigned Size) { 1165 unsigned NumOperands = getNumOperands(); 1166 assert(NumOperands >= 1); 1167 if (ReservedSpace >= NumOperands + Size) 1168 return; 1169 ReservedSpace = (NumOperands + Size / 2) * 2; 1170 growHungoffUses(ReservedSpace); 1171 } 1172 1173 void CatchSwitchInst::addHandler(BasicBlock *Handler) { 1174 unsigned OpNo = getNumOperands(); 1175 growOperands(1); 1176 assert(OpNo < ReservedSpace && "Growing didn't work!"); 1177 setNumHungOffUseOperands(getNumOperands() + 1); 1178 getOperandList()[OpNo] = Handler; 1179 } 1180 1181 void CatchSwitchInst::removeHandler(handler_iterator HI) { 1182 // Move all subsequent handlers up one. 1183 Use *EndDst = op_end() - 1; 1184 for (Use *CurDst = HI.getCurrent(); CurDst != EndDst; ++CurDst) 1185 *CurDst = *(CurDst + 1); 1186 // Null out the last handler use. 1187 *EndDst = nullptr; 1188 1189 setNumHungOffUseOperands(getNumOperands() - 1); 1190 } 1191 1192 //===----------------------------------------------------------------------===// 1193 // FuncletPadInst Implementation 1194 //===----------------------------------------------------------------------===// 1195 void FuncletPadInst::init(Value *ParentPad, ArrayRef<Value *> Args, 1196 const Twine &NameStr) { 1197 assert(getNumOperands() == 1 + Args.size() && "NumOperands not set up?"); 1198 llvm::copy(Args, op_begin()); 1199 setParentPad(ParentPad); 1200 setName(NameStr); 1201 } 1202 1203 FuncletPadInst::FuncletPadInst(const FuncletPadInst &FPI) 1204 : Instruction(FPI.getType(), FPI.getOpcode(), 1205 OperandTraits<FuncletPadInst>::op_end(this) - 1206 FPI.getNumOperands(), 1207 FPI.getNumOperands()) { 1208 std::copy(FPI.op_begin(), FPI.op_end(), op_begin()); 1209 setParentPad(FPI.getParentPad()); 1210 } 1211 1212 FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad, 1213 ArrayRef<Value *> Args, unsigned Values, 1214 const Twine &NameStr, Instruction *InsertBefore) 1215 : Instruction(ParentPad->getType(), Op, 1216 OperandTraits<FuncletPadInst>::op_end(this) - Values, Values, 1217 InsertBefore) { 1218 init(ParentPad, Args, NameStr); 1219 } 1220 1221 FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad, 1222 ArrayRef<Value *> Args, unsigned Values, 1223 const Twine &NameStr, BasicBlock *InsertAtEnd) 1224 : Instruction(ParentPad->getType(), Op, 1225 OperandTraits<FuncletPadInst>::op_end(this) - Values, Values, 1226 InsertAtEnd) { 1227 init(ParentPad, Args, NameStr); 1228 } 1229 1230 //===----------------------------------------------------------------------===// 1231 // UnreachableInst Implementation 1232 //===----------------------------------------------------------------------===// 1233 1234 UnreachableInst::UnreachableInst(LLVMContext &Context, 1235 Instruction *InsertBefore) 1236 : Instruction(Type::getVoidTy(Context), Instruction::Unreachable, nullptr, 1237 0, InsertBefore) {} 1238 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd) 1239 : Instruction(Type::getVoidTy(Context), Instruction::Unreachable, nullptr, 1240 0, InsertAtEnd) {} 1241 1242 //===----------------------------------------------------------------------===// 1243 // BranchInst Implementation 1244 //===----------------------------------------------------------------------===// 1245 1246 void BranchInst::AssertOK() { 1247 if (isConditional()) 1248 assert(getCondition()->getType()->isIntegerTy(1) && 1249 "May only branch on boolean predicates!"); 1250 } 1251 1252 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore) 1253 : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br, 1254 OperandTraits<BranchInst>::op_end(this) - 1, 1, 1255 InsertBefore) { 1256 assert(IfTrue && "Branch destination may not be null!"); 1257 Op<-1>() = IfTrue; 1258 } 1259 1260 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond, 1261 Instruction *InsertBefore) 1262 : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br, 1263 OperandTraits<BranchInst>::op_end(this) - 3, 3, 1264 InsertBefore) { 1265 // Assign in order of operand index to make use-list order predictable. 1266 Op<-3>() = Cond; 1267 Op<-2>() = IfFalse; 1268 Op<-1>() = IfTrue; 1269 #ifndef NDEBUG 1270 AssertOK(); 1271 #endif 1272 } 1273 1274 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) 1275 : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br, 1276 OperandTraits<BranchInst>::op_end(this) - 1, 1, InsertAtEnd) { 1277 assert(IfTrue && "Branch destination may not be null!"); 1278 Op<-1>() = IfTrue; 1279 } 1280 1281 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond, 1282 BasicBlock *InsertAtEnd) 1283 : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br, 1284 OperandTraits<BranchInst>::op_end(this) - 3, 3, InsertAtEnd) { 1285 // Assign in order of operand index to make use-list order predictable. 1286 Op<-3>() = Cond; 1287 Op<-2>() = IfFalse; 1288 Op<-1>() = IfTrue; 1289 #ifndef NDEBUG 1290 AssertOK(); 1291 #endif 1292 } 1293 1294 BranchInst::BranchInst(const BranchInst &BI) 1295 : Instruction(Type::getVoidTy(BI.getContext()), Instruction::Br, 1296 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(), 1297 BI.getNumOperands()) { 1298 // Assign in order of operand index to make use-list order predictable. 1299 if (BI.getNumOperands() != 1) { 1300 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!"); 1301 Op<-3>() = BI.Op<-3>(); 1302 Op<-2>() = BI.Op<-2>(); 1303 } 1304 Op<-1>() = BI.Op<-1>(); 1305 SubclassOptionalData = BI.SubclassOptionalData; 1306 } 1307 1308 void BranchInst::swapSuccessors() { 1309 assert(isConditional() && 1310 "Cannot swap successors of an unconditional branch"); 1311 Op<-1>().swap(Op<-2>()); 1312 1313 // Update profile metadata if present and it matches our structural 1314 // expectations. 1315 swapProfMetadata(); 1316 } 1317 1318 //===----------------------------------------------------------------------===// 1319 // AllocaInst Implementation 1320 //===----------------------------------------------------------------------===// 1321 1322 static Value *getAISize(LLVMContext &Context, Value *Amt) { 1323 if (!Amt) 1324 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1); 1325 else { 1326 assert(!isa<BasicBlock>(Amt) && 1327 "Passed basic block into allocation size parameter! Use other ctor"); 1328 assert(Amt->getType()->isIntegerTy() && 1329 "Allocation array size is not an integer!"); 1330 } 1331 return Amt; 1332 } 1333 1334 static Align computeAllocaDefaultAlign(Type *Ty, BasicBlock *BB) { 1335 assert(BB && "Insertion BB cannot be null when alignment not provided!"); 1336 assert(BB->getParent() && 1337 "BB must be in a Function when alignment not provided!"); 1338 const DataLayout &DL = BB->getModule()->getDataLayout(); 1339 return DL.getPrefTypeAlign(Ty); 1340 } 1341 1342 static Align computeAllocaDefaultAlign(Type *Ty, Instruction *I) { 1343 assert(I && "Insertion position cannot be null when alignment not provided!"); 1344 return computeAllocaDefaultAlign(Ty, I->getParent()); 1345 } 1346 1347 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name, 1348 Instruction *InsertBefore) 1349 : AllocaInst(Ty, AddrSpace, /*ArraySize=*/nullptr, Name, InsertBefore) {} 1350 1351 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name, 1352 BasicBlock *InsertAtEnd) 1353 : AllocaInst(Ty, AddrSpace, /*ArraySize=*/nullptr, Name, InsertAtEnd) {} 1354 1355 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, 1356 const Twine &Name, Instruction *InsertBefore) 1357 : AllocaInst(Ty, AddrSpace, ArraySize, 1358 computeAllocaDefaultAlign(Ty, InsertBefore), Name, 1359 InsertBefore) {} 1360 1361 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, 1362 const Twine &Name, BasicBlock *InsertAtEnd) 1363 : AllocaInst(Ty, AddrSpace, ArraySize, 1364 computeAllocaDefaultAlign(Ty, InsertAtEnd), Name, 1365 InsertAtEnd) {} 1366 1367 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, 1368 Align Align, const Twine &Name, 1369 Instruction *InsertBefore) 1370 : UnaryInstruction(PointerType::get(Ty, AddrSpace), Alloca, 1371 getAISize(Ty->getContext(), ArraySize), InsertBefore), 1372 AllocatedType(Ty) { 1373 setAlignment(Align); 1374 assert(!Ty->isVoidTy() && "Cannot allocate void!"); 1375 setName(Name); 1376 } 1377 1378 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, 1379 Align Align, const Twine &Name, BasicBlock *InsertAtEnd) 1380 : UnaryInstruction(PointerType::get(Ty, AddrSpace), Alloca, 1381 getAISize(Ty->getContext(), ArraySize), InsertAtEnd), 1382 AllocatedType(Ty) { 1383 setAlignment(Align); 1384 assert(!Ty->isVoidTy() && "Cannot allocate void!"); 1385 setName(Name); 1386 } 1387 1388 1389 bool AllocaInst::isArrayAllocation() const { 1390 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0))) 1391 return !CI->isOne(); 1392 return true; 1393 } 1394 1395 /// isStaticAlloca - Return true if this alloca is in the entry block of the 1396 /// function and is a constant size. If so, the code generator will fold it 1397 /// into the prolog/epilog code, so it is basically free. 1398 bool AllocaInst::isStaticAlloca() const { 1399 // Must be constant size. 1400 if (!isa<ConstantInt>(getArraySize())) return false; 1401 1402 // Must be in the entry block. 1403 const BasicBlock *Parent = getParent(); 1404 return Parent == &Parent->getParent()->front() && !isUsedWithInAlloca(); 1405 } 1406 1407 //===----------------------------------------------------------------------===// 1408 // LoadInst Implementation 1409 //===----------------------------------------------------------------------===// 1410 1411 void LoadInst::AssertOK() { 1412 assert(getOperand(0)->getType()->isPointerTy() && 1413 "Ptr must have pointer type."); 1414 } 1415 1416 static Align computeLoadStoreDefaultAlign(Type *Ty, BasicBlock *BB) { 1417 assert(BB && "Insertion BB cannot be null when alignment not provided!"); 1418 assert(BB->getParent() && 1419 "BB must be in a Function when alignment not provided!"); 1420 const DataLayout &DL = BB->getModule()->getDataLayout(); 1421 return DL.getABITypeAlign(Ty); 1422 } 1423 1424 static Align computeLoadStoreDefaultAlign(Type *Ty, Instruction *I) { 1425 assert(I && "Insertion position cannot be null when alignment not provided!"); 1426 return computeLoadStoreDefaultAlign(Ty, I->getParent()); 1427 } 1428 1429 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, 1430 Instruction *InsertBef) 1431 : LoadInst(Ty, Ptr, Name, /*isVolatile=*/false, InsertBef) {} 1432 1433 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, 1434 BasicBlock *InsertAE) 1435 : LoadInst(Ty, Ptr, Name, /*isVolatile=*/false, InsertAE) {} 1436 1437 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, 1438 Instruction *InsertBef) 1439 : LoadInst(Ty, Ptr, Name, isVolatile, 1440 computeLoadStoreDefaultAlign(Ty, InsertBef), InsertBef) {} 1441 1442 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, 1443 BasicBlock *InsertAE) 1444 : LoadInst(Ty, Ptr, Name, isVolatile, 1445 computeLoadStoreDefaultAlign(Ty, InsertAE), InsertAE) {} 1446 1447 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, 1448 Align Align, Instruction *InsertBef) 1449 : LoadInst(Ty, Ptr, Name, isVolatile, Align, AtomicOrdering::NotAtomic, 1450 SyncScope::System, InsertBef) {} 1451 1452 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, 1453 Align Align, BasicBlock *InsertAE) 1454 : LoadInst(Ty, Ptr, Name, isVolatile, Align, AtomicOrdering::NotAtomic, 1455 SyncScope::System, InsertAE) {} 1456 1457 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, 1458 Align Align, AtomicOrdering Order, SyncScope::ID SSID, 1459 Instruction *InsertBef) 1460 : UnaryInstruction(Ty, Load, Ptr, InsertBef) { 1461 assert(cast<PointerType>(Ptr->getType())->isOpaqueOrPointeeTypeMatches(Ty)); 1462 setVolatile(isVolatile); 1463 setAlignment(Align); 1464 setAtomic(Order, SSID); 1465 AssertOK(); 1466 setName(Name); 1467 } 1468 1469 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, 1470 Align Align, AtomicOrdering Order, SyncScope::ID SSID, 1471 BasicBlock *InsertAE) 1472 : UnaryInstruction(Ty, Load, Ptr, InsertAE) { 1473 assert(cast<PointerType>(Ptr->getType())->isOpaqueOrPointeeTypeMatches(Ty)); 1474 setVolatile(isVolatile); 1475 setAlignment(Align); 1476 setAtomic(Order, SSID); 1477 AssertOK(); 1478 setName(Name); 1479 } 1480 1481 //===----------------------------------------------------------------------===// 1482 // StoreInst Implementation 1483 //===----------------------------------------------------------------------===// 1484 1485 void StoreInst::AssertOK() { 1486 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!"); 1487 assert(getOperand(1)->getType()->isPointerTy() && 1488 "Ptr must have pointer type!"); 1489 assert(cast<PointerType>(getOperand(1)->getType()) 1490 ->isOpaqueOrPointeeTypeMatches(getOperand(0)->getType()) && 1491 "Ptr must be a pointer to Val type!"); 1492 } 1493 1494 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore) 1495 : StoreInst(val, addr, /*isVolatile=*/false, InsertBefore) {} 1496 1497 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd) 1498 : StoreInst(val, addr, /*isVolatile=*/false, InsertAtEnd) {} 1499 1500 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, 1501 Instruction *InsertBefore) 1502 : StoreInst(val, addr, isVolatile, 1503 computeLoadStoreDefaultAlign(val->getType(), InsertBefore), 1504 InsertBefore) {} 1505 1506 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, 1507 BasicBlock *InsertAtEnd) 1508 : StoreInst(val, addr, isVolatile, 1509 computeLoadStoreDefaultAlign(val->getType(), InsertAtEnd), 1510 InsertAtEnd) {} 1511 1512 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align, 1513 Instruction *InsertBefore) 1514 : StoreInst(val, addr, isVolatile, Align, AtomicOrdering::NotAtomic, 1515 SyncScope::System, InsertBefore) {} 1516 1517 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align, 1518 BasicBlock *InsertAtEnd) 1519 : StoreInst(val, addr, isVolatile, Align, AtomicOrdering::NotAtomic, 1520 SyncScope::System, InsertAtEnd) {} 1521 1522 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align, 1523 AtomicOrdering Order, SyncScope::ID SSID, 1524 Instruction *InsertBefore) 1525 : Instruction(Type::getVoidTy(val->getContext()), Store, 1526 OperandTraits<StoreInst>::op_begin(this), 1527 OperandTraits<StoreInst>::operands(this), InsertBefore) { 1528 Op<0>() = val; 1529 Op<1>() = addr; 1530 setVolatile(isVolatile); 1531 setAlignment(Align); 1532 setAtomic(Order, SSID); 1533 AssertOK(); 1534 } 1535 1536 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align, 1537 AtomicOrdering Order, SyncScope::ID SSID, 1538 BasicBlock *InsertAtEnd) 1539 : Instruction(Type::getVoidTy(val->getContext()), Store, 1540 OperandTraits<StoreInst>::op_begin(this), 1541 OperandTraits<StoreInst>::operands(this), InsertAtEnd) { 1542 Op<0>() = val; 1543 Op<1>() = addr; 1544 setVolatile(isVolatile); 1545 setAlignment(Align); 1546 setAtomic(Order, SSID); 1547 AssertOK(); 1548 } 1549 1550 1551 //===----------------------------------------------------------------------===// 1552 // AtomicCmpXchgInst Implementation 1553 //===----------------------------------------------------------------------===// 1554 1555 void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal, 1556 Align Alignment, AtomicOrdering SuccessOrdering, 1557 AtomicOrdering FailureOrdering, 1558 SyncScope::ID SSID) { 1559 Op<0>() = Ptr; 1560 Op<1>() = Cmp; 1561 Op<2>() = NewVal; 1562 setSuccessOrdering(SuccessOrdering); 1563 setFailureOrdering(FailureOrdering); 1564 setSyncScopeID(SSID); 1565 setAlignment(Alignment); 1566 1567 assert(getOperand(0) && getOperand(1) && getOperand(2) && 1568 "All operands must be non-null!"); 1569 assert(getOperand(0)->getType()->isPointerTy() && 1570 "Ptr must have pointer type!"); 1571 assert(cast<PointerType>(getOperand(0)->getType()) 1572 ->isOpaqueOrPointeeTypeMatches(getOperand(1)->getType()) && 1573 "Ptr must be a pointer to Cmp type!"); 1574 assert(cast<PointerType>(getOperand(0)->getType()) 1575 ->isOpaqueOrPointeeTypeMatches(getOperand(2)->getType()) && 1576 "Ptr must be a pointer to NewVal type!"); 1577 assert(getOperand(1)->getType() == getOperand(2)->getType() && 1578 "Cmp type and NewVal type must be same!"); 1579 } 1580 1581 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, 1582 Align Alignment, 1583 AtomicOrdering SuccessOrdering, 1584 AtomicOrdering FailureOrdering, 1585 SyncScope::ID SSID, 1586 Instruction *InsertBefore) 1587 : Instruction( 1588 StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext())), 1589 AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this), 1590 OperandTraits<AtomicCmpXchgInst>::operands(this), InsertBefore) { 1591 Init(Ptr, Cmp, NewVal, Alignment, SuccessOrdering, FailureOrdering, SSID); 1592 } 1593 1594 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, 1595 Align Alignment, 1596 AtomicOrdering SuccessOrdering, 1597 AtomicOrdering FailureOrdering, 1598 SyncScope::ID SSID, 1599 BasicBlock *InsertAtEnd) 1600 : Instruction( 1601 StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext())), 1602 AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this), 1603 OperandTraits<AtomicCmpXchgInst>::operands(this), InsertAtEnd) { 1604 Init(Ptr, Cmp, NewVal, Alignment, SuccessOrdering, FailureOrdering, SSID); 1605 } 1606 1607 //===----------------------------------------------------------------------===// 1608 // AtomicRMWInst Implementation 1609 //===----------------------------------------------------------------------===// 1610 1611 void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val, 1612 Align Alignment, AtomicOrdering Ordering, 1613 SyncScope::ID SSID) { 1614 Op<0>() = Ptr; 1615 Op<1>() = Val; 1616 setOperation(Operation); 1617 setOrdering(Ordering); 1618 setSyncScopeID(SSID); 1619 setAlignment(Alignment); 1620 1621 assert(getOperand(0) && getOperand(1) && 1622 "All operands must be non-null!"); 1623 assert(getOperand(0)->getType()->isPointerTy() && 1624 "Ptr must have pointer type!"); 1625 assert(cast<PointerType>(getOperand(0)->getType()) 1626 ->isOpaqueOrPointeeTypeMatches(getOperand(1)->getType()) && 1627 "Ptr must be a pointer to Val type!"); 1628 assert(Ordering != AtomicOrdering::NotAtomic && 1629 "AtomicRMW instructions must be atomic!"); 1630 } 1631 1632 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, 1633 Align Alignment, AtomicOrdering Ordering, 1634 SyncScope::ID SSID, Instruction *InsertBefore) 1635 : Instruction(Val->getType(), AtomicRMW, 1636 OperandTraits<AtomicRMWInst>::op_begin(this), 1637 OperandTraits<AtomicRMWInst>::operands(this), InsertBefore) { 1638 Init(Operation, Ptr, Val, Alignment, Ordering, SSID); 1639 } 1640 1641 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, 1642 Align Alignment, AtomicOrdering Ordering, 1643 SyncScope::ID SSID, BasicBlock *InsertAtEnd) 1644 : Instruction(Val->getType(), AtomicRMW, 1645 OperandTraits<AtomicRMWInst>::op_begin(this), 1646 OperandTraits<AtomicRMWInst>::operands(this), InsertAtEnd) { 1647 Init(Operation, Ptr, Val, Alignment, Ordering, SSID); 1648 } 1649 1650 StringRef AtomicRMWInst::getOperationName(BinOp Op) { 1651 switch (Op) { 1652 case AtomicRMWInst::Xchg: 1653 return "xchg"; 1654 case AtomicRMWInst::Add: 1655 return "add"; 1656 case AtomicRMWInst::Sub: 1657 return "sub"; 1658 case AtomicRMWInst::And: 1659 return "and"; 1660 case AtomicRMWInst::Nand: 1661 return "nand"; 1662 case AtomicRMWInst::Or: 1663 return "or"; 1664 case AtomicRMWInst::Xor: 1665 return "xor"; 1666 case AtomicRMWInst::Max: 1667 return "max"; 1668 case AtomicRMWInst::Min: 1669 return "min"; 1670 case AtomicRMWInst::UMax: 1671 return "umax"; 1672 case AtomicRMWInst::UMin: 1673 return "umin"; 1674 case AtomicRMWInst::FAdd: 1675 return "fadd"; 1676 case AtomicRMWInst::FSub: 1677 return "fsub"; 1678 case AtomicRMWInst::BAD_BINOP: 1679 return "<invalid operation>"; 1680 } 1681 1682 llvm_unreachable("invalid atomicrmw operation"); 1683 } 1684 1685 //===----------------------------------------------------------------------===// 1686 // FenceInst Implementation 1687 //===----------------------------------------------------------------------===// 1688 1689 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering, 1690 SyncScope::ID SSID, 1691 Instruction *InsertBefore) 1692 : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertBefore) { 1693 setOrdering(Ordering); 1694 setSyncScopeID(SSID); 1695 } 1696 1697 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering, 1698 SyncScope::ID SSID, 1699 BasicBlock *InsertAtEnd) 1700 : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertAtEnd) { 1701 setOrdering(Ordering); 1702 setSyncScopeID(SSID); 1703 } 1704 1705 //===----------------------------------------------------------------------===// 1706 // GetElementPtrInst Implementation 1707 //===----------------------------------------------------------------------===// 1708 1709 void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList, 1710 const Twine &Name) { 1711 assert(getNumOperands() == 1 + IdxList.size() && 1712 "NumOperands not initialized?"); 1713 Op<0>() = Ptr; 1714 llvm::copy(IdxList, op_begin() + 1); 1715 setName(Name); 1716 } 1717 1718 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI) 1719 : Instruction(GEPI.getType(), GetElementPtr, 1720 OperandTraits<GetElementPtrInst>::op_end(this) - 1721 GEPI.getNumOperands(), 1722 GEPI.getNumOperands()), 1723 SourceElementType(GEPI.SourceElementType), 1724 ResultElementType(GEPI.ResultElementType) { 1725 std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin()); 1726 SubclassOptionalData = GEPI.SubclassOptionalData; 1727 } 1728 1729 Type *GetElementPtrInst::getTypeAtIndex(Type *Ty, Value *Idx) { 1730 if (auto *Struct = dyn_cast<StructType>(Ty)) { 1731 if (!Struct->indexValid(Idx)) 1732 return nullptr; 1733 return Struct->getTypeAtIndex(Idx); 1734 } 1735 if (!Idx->getType()->isIntOrIntVectorTy()) 1736 return nullptr; 1737 if (auto *Array = dyn_cast<ArrayType>(Ty)) 1738 return Array->getElementType(); 1739 if (auto *Vector = dyn_cast<VectorType>(Ty)) 1740 return Vector->getElementType(); 1741 return nullptr; 1742 } 1743 1744 Type *GetElementPtrInst::getTypeAtIndex(Type *Ty, uint64_t Idx) { 1745 if (auto *Struct = dyn_cast<StructType>(Ty)) { 1746 if (Idx >= Struct->getNumElements()) 1747 return nullptr; 1748 return Struct->getElementType(Idx); 1749 } 1750 if (auto *Array = dyn_cast<ArrayType>(Ty)) 1751 return Array->getElementType(); 1752 if (auto *Vector = dyn_cast<VectorType>(Ty)) 1753 return Vector->getElementType(); 1754 return nullptr; 1755 } 1756 1757 template <typename IndexTy> 1758 static Type *getIndexedTypeInternal(Type *Ty, ArrayRef<IndexTy> IdxList) { 1759 if (IdxList.empty()) 1760 return Ty; 1761 for (IndexTy V : IdxList.slice(1)) { 1762 Ty = GetElementPtrInst::getTypeAtIndex(Ty, V); 1763 if (!Ty) 1764 return Ty; 1765 } 1766 return Ty; 1767 } 1768 1769 Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<Value *> IdxList) { 1770 return getIndexedTypeInternal(Ty, IdxList); 1771 } 1772 1773 Type *GetElementPtrInst::getIndexedType(Type *Ty, 1774 ArrayRef<Constant *> IdxList) { 1775 return getIndexedTypeInternal(Ty, IdxList); 1776 } 1777 1778 Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList) { 1779 return getIndexedTypeInternal(Ty, IdxList); 1780 } 1781 1782 /// hasAllZeroIndices - Return true if all of the indices of this GEP are 1783 /// zeros. If so, the result pointer and the first operand have the same 1784 /// value, just potentially different types. 1785 bool GetElementPtrInst::hasAllZeroIndices() const { 1786 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1787 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) { 1788 if (!CI->isZero()) return false; 1789 } else { 1790 return false; 1791 } 1792 } 1793 return true; 1794 } 1795 1796 /// hasAllConstantIndices - Return true if all of the indices of this GEP are 1797 /// constant integers. If so, the result pointer and the first operand have 1798 /// a constant offset between them. 1799 bool GetElementPtrInst::hasAllConstantIndices() const { 1800 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1801 if (!isa<ConstantInt>(getOperand(i))) 1802 return false; 1803 } 1804 return true; 1805 } 1806 1807 void GetElementPtrInst::setIsInBounds(bool B) { 1808 cast<GEPOperator>(this)->setIsInBounds(B); 1809 } 1810 1811 bool GetElementPtrInst::isInBounds() const { 1812 return cast<GEPOperator>(this)->isInBounds(); 1813 } 1814 1815 bool GetElementPtrInst::accumulateConstantOffset(const DataLayout &DL, 1816 APInt &Offset) const { 1817 // Delegate to the generic GEPOperator implementation. 1818 return cast<GEPOperator>(this)->accumulateConstantOffset(DL, Offset); 1819 } 1820 1821 bool GetElementPtrInst::collectOffset( 1822 const DataLayout &DL, unsigned BitWidth, 1823 MapVector<Value *, APInt> &VariableOffsets, 1824 APInt &ConstantOffset) const { 1825 // Delegate to the generic GEPOperator implementation. 1826 return cast<GEPOperator>(this)->collectOffset(DL, BitWidth, VariableOffsets, 1827 ConstantOffset); 1828 } 1829 1830 //===----------------------------------------------------------------------===// 1831 // ExtractElementInst Implementation 1832 //===----------------------------------------------------------------------===// 1833 1834 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index, 1835 const Twine &Name, 1836 Instruction *InsertBef) 1837 : Instruction(cast<VectorType>(Val->getType())->getElementType(), 1838 ExtractElement, 1839 OperandTraits<ExtractElementInst>::op_begin(this), 1840 2, InsertBef) { 1841 assert(isValidOperands(Val, Index) && 1842 "Invalid extractelement instruction operands!"); 1843 Op<0>() = Val; 1844 Op<1>() = Index; 1845 setName(Name); 1846 } 1847 1848 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index, 1849 const Twine &Name, 1850 BasicBlock *InsertAE) 1851 : Instruction(cast<VectorType>(Val->getType())->getElementType(), 1852 ExtractElement, 1853 OperandTraits<ExtractElementInst>::op_begin(this), 1854 2, InsertAE) { 1855 assert(isValidOperands(Val, Index) && 1856 "Invalid extractelement instruction operands!"); 1857 1858 Op<0>() = Val; 1859 Op<1>() = Index; 1860 setName(Name); 1861 } 1862 1863 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) { 1864 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy()) 1865 return false; 1866 return true; 1867 } 1868 1869 //===----------------------------------------------------------------------===// 1870 // InsertElementInst Implementation 1871 //===----------------------------------------------------------------------===// 1872 1873 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index, 1874 const Twine &Name, 1875 Instruction *InsertBef) 1876 : Instruction(Vec->getType(), InsertElement, 1877 OperandTraits<InsertElementInst>::op_begin(this), 1878 3, InsertBef) { 1879 assert(isValidOperands(Vec, Elt, Index) && 1880 "Invalid insertelement instruction operands!"); 1881 Op<0>() = Vec; 1882 Op<1>() = Elt; 1883 Op<2>() = Index; 1884 setName(Name); 1885 } 1886 1887 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index, 1888 const Twine &Name, 1889 BasicBlock *InsertAE) 1890 : Instruction(Vec->getType(), InsertElement, 1891 OperandTraits<InsertElementInst>::op_begin(this), 1892 3, InsertAE) { 1893 assert(isValidOperands(Vec, Elt, Index) && 1894 "Invalid insertelement instruction operands!"); 1895 1896 Op<0>() = Vec; 1897 Op<1>() = Elt; 1898 Op<2>() = Index; 1899 setName(Name); 1900 } 1901 1902 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt, 1903 const Value *Index) { 1904 if (!Vec->getType()->isVectorTy()) 1905 return false; // First operand of insertelement must be vector type. 1906 1907 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType()) 1908 return false;// Second operand of insertelement must be vector element type. 1909 1910 if (!Index->getType()->isIntegerTy()) 1911 return false; // Third operand of insertelement must be i32. 1912 return true; 1913 } 1914 1915 //===----------------------------------------------------------------------===// 1916 // ShuffleVectorInst Implementation 1917 //===----------------------------------------------------------------------===// 1918 1919 static Value *createPlaceholderForShuffleVector(Value *V) { 1920 assert(V && "Cannot create placeholder of nullptr V"); 1921 return PoisonValue::get(V->getType()); 1922 } 1923 1924 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *Mask, const Twine &Name, 1925 Instruction *InsertBefore) 1926 : ShuffleVectorInst(V1, createPlaceholderForShuffleVector(V1), Mask, Name, 1927 InsertBefore) {} 1928 1929 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *Mask, const Twine &Name, 1930 BasicBlock *InsertAtEnd) 1931 : ShuffleVectorInst(V1, createPlaceholderForShuffleVector(V1), Mask, Name, 1932 InsertAtEnd) {} 1933 1934 ShuffleVectorInst::ShuffleVectorInst(Value *V1, ArrayRef<int> Mask, 1935 const Twine &Name, 1936 Instruction *InsertBefore) 1937 : ShuffleVectorInst(V1, createPlaceholderForShuffleVector(V1), Mask, Name, 1938 InsertBefore) {} 1939 1940 ShuffleVectorInst::ShuffleVectorInst(Value *V1, ArrayRef<int> Mask, 1941 const Twine &Name, BasicBlock *InsertAtEnd) 1942 : ShuffleVectorInst(V1, createPlaceholderForShuffleVector(V1), Mask, Name, 1943 InsertAtEnd) {} 1944 1945 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask, 1946 const Twine &Name, 1947 Instruction *InsertBefore) 1948 : Instruction( 1949 VectorType::get(cast<VectorType>(V1->getType())->getElementType(), 1950 cast<VectorType>(Mask->getType())->getElementCount()), 1951 ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this), 1952 OperandTraits<ShuffleVectorInst>::operands(this), InsertBefore) { 1953 assert(isValidOperands(V1, V2, Mask) && 1954 "Invalid shuffle vector instruction operands!"); 1955 1956 Op<0>() = V1; 1957 Op<1>() = V2; 1958 SmallVector<int, 16> MaskArr; 1959 getShuffleMask(cast<Constant>(Mask), MaskArr); 1960 setShuffleMask(MaskArr); 1961 setName(Name); 1962 } 1963 1964 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask, 1965 const Twine &Name, BasicBlock *InsertAtEnd) 1966 : Instruction( 1967 VectorType::get(cast<VectorType>(V1->getType())->getElementType(), 1968 cast<VectorType>(Mask->getType())->getElementCount()), 1969 ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this), 1970 OperandTraits<ShuffleVectorInst>::operands(this), InsertAtEnd) { 1971 assert(isValidOperands(V1, V2, Mask) && 1972 "Invalid shuffle vector instruction operands!"); 1973 1974 Op<0>() = V1; 1975 Op<1>() = V2; 1976 SmallVector<int, 16> MaskArr; 1977 getShuffleMask(cast<Constant>(Mask), MaskArr); 1978 setShuffleMask(MaskArr); 1979 setName(Name); 1980 } 1981 1982 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask, 1983 const Twine &Name, 1984 Instruction *InsertBefore) 1985 : Instruction( 1986 VectorType::get(cast<VectorType>(V1->getType())->getElementType(), 1987 Mask.size(), isa<ScalableVectorType>(V1->getType())), 1988 ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this), 1989 OperandTraits<ShuffleVectorInst>::operands(this), InsertBefore) { 1990 assert(isValidOperands(V1, V2, Mask) && 1991 "Invalid shuffle vector instruction operands!"); 1992 Op<0>() = V1; 1993 Op<1>() = V2; 1994 setShuffleMask(Mask); 1995 setName(Name); 1996 } 1997 1998 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask, 1999 const Twine &Name, BasicBlock *InsertAtEnd) 2000 : Instruction( 2001 VectorType::get(cast<VectorType>(V1->getType())->getElementType(), 2002 Mask.size(), isa<ScalableVectorType>(V1->getType())), 2003 ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this), 2004 OperandTraits<ShuffleVectorInst>::operands(this), InsertAtEnd) { 2005 assert(isValidOperands(V1, V2, Mask) && 2006 "Invalid shuffle vector instruction operands!"); 2007 2008 Op<0>() = V1; 2009 Op<1>() = V2; 2010 setShuffleMask(Mask); 2011 setName(Name); 2012 } 2013 2014 void ShuffleVectorInst::commute() { 2015 int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements(); 2016 int NumMaskElts = ShuffleMask.size(); 2017 SmallVector<int, 16> NewMask(NumMaskElts); 2018 for (int i = 0; i != NumMaskElts; ++i) { 2019 int MaskElt = getMaskValue(i); 2020 if (MaskElt == UndefMaskElem) { 2021 NewMask[i] = UndefMaskElem; 2022 continue; 2023 } 2024 assert(MaskElt >= 0 && MaskElt < 2 * NumOpElts && "Out-of-range mask"); 2025 MaskElt = (MaskElt < NumOpElts) ? MaskElt + NumOpElts : MaskElt - NumOpElts; 2026 NewMask[i] = MaskElt; 2027 } 2028 setShuffleMask(NewMask); 2029 Op<0>().swap(Op<1>()); 2030 } 2031 2032 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2, 2033 ArrayRef<int> Mask) { 2034 // V1 and V2 must be vectors of the same type. 2035 if (!isa<VectorType>(V1->getType()) || V1->getType() != V2->getType()) 2036 return false; 2037 2038 // Make sure the mask elements make sense. 2039 int V1Size = 2040 cast<VectorType>(V1->getType())->getElementCount().getKnownMinValue(); 2041 for (int Elem : Mask) 2042 if (Elem != UndefMaskElem && Elem >= V1Size * 2) 2043 return false; 2044 2045 if (isa<ScalableVectorType>(V1->getType())) 2046 if ((Mask[0] != 0 && Mask[0] != UndefMaskElem) || !is_splat(Mask)) 2047 return false; 2048 2049 return true; 2050 } 2051 2052 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2, 2053 const Value *Mask) { 2054 // V1 and V2 must be vectors of the same type. 2055 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType()) 2056 return false; 2057 2058 // Mask must be vector of i32, and must be the same kind of vector as the 2059 // input vectors 2060 auto *MaskTy = dyn_cast<VectorType>(Mask->getType()); 2061 if (!MaskTy || !MaskTy->getElementType()->isIntegerTy(32) || 2062 isa<ScalableVectorType>(MaskTy) != isa<ScalableVectorType>(V1->getType())) 2063 return false; 2064 2065 // Check to see if Mask is valid. 2066 if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask)) 2067 return true; 2068 2069 if (const auto *MV = dyn_cast<ConstantVector>(Mask)) { 2070 unsigned V1Size = cast<FixedVectorType>(V1->getType())->getNumElements(); 2071 for (Value *Op : MV->operands()) { 2072 if (auto *CI = dyn_cast<ConstantInt>(Op)) { 2073 if (CI->uge(V1Size*2)) 2074 return false; 2075 } else if (!isa<UndefValue>(Op)) { 2076 return false; 2077 } 2078 } 2079 return true; 2080 } 2081 2082 if (const auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) { 2083 unsigned V1Size = cast<FixedVectorType>(V1->getType())->getNumElements(); 2084 for (unsigned i = 0, e = cast<FixedVectorType>(MaskTy)->getNumElements(); 2085 i != e; ++i) 2086 if (CDS->getElementAsInteger(i) >= V1Size*2) 2087 return false; 2088 return true; 2089 } 2090 2091 return false; 2092 } 2093 2094 void ShuffleVectorInst::getShuffleMask(const Constant *Mask, 2095 SmallVectorImpl<int> &Result) { 2096 ElementCount EC = cast<VectorType>(Mask->getType())->getElementCount(); 2097 2098 if (isa<ConstantAggregateZero>(Mask)) { 2099 Result.resize(EC.getKnownMinValue(), 0); 2100 return; 2101 } 2102 2103 Result.reserve(EC.getKnownMinValue()); 2104 2105 if (EC.isScalable()) { 2106 assert((isa<ConstantAggregateZero>(Mask) || isa<UndefValue>(Mask)) && 2107 "Scalable vector shuffle mask must be undef or zeroinitializer"); 2108 int MaskVal = isa<UndefValue>(Mask) ? -1 : 0; 2109 for (unsigned I = 0; I < EC.getKnownMinValue(); ++I) 2110 Result.emplace_back(MaskVal); 2111 return; 2112 } 2113 2114 unsigned NumElts = EC.getKnownMinValue(); 2115 2116 if (auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) { 2117 for (unsigned i = 0; i != NumElts; ++i) 2118 Result.push_back(CDS->getElementAsInteger(i)); 2119 return; 2120 } 2121 for (unsigned i = 0; i != NumElts; ++i) { 2122 Constant *C = Mask->getAggregateElement(i); 2123 Result.push_back(isa<UndefValue>(C) ? -1 : 2124 cast<ConstantInt>(C)->getZExtValue()); 2125 } 2126 } 2127 2128 void ShuffleVectorInst::setShuffleMask(ArrayRef<int> Mask) { 2129 ShuffleMask.assign(Mask.begin(), Mask.end()); 2130 ShuffleMaskForBitcode = convertShuffleMaskForBitcode(Mask, getType()); 2131 } 2132 2133 Constant *ShuffleVectorInst::convertShuffleMaskForBitcode(ArrayRef<int> Mask, 2134 Type *ResultTy) { 2135 Type *Int32Ty = Type::getInt32Ty(ResultTy->getContext()); 2136 if (isa<ScalableVectorType>(ResultTy)) { 2137 assert(is_splat(Mask) && "Unexpected shuffle"); 2138 Type *VecTy = VectorType::get(Int32Ty, Mask.size(), true); 2139 if (Mask[0] == 0) 2140 return Constant::getNullValue(VecTy); 2141 return UndefValue::get(VecTy); 2142 } 2143 SmallVector<Constant *, 16> MaskConst; 2144 for (int Elem : Mask) { 2145 if (Elem == UndefMaskElem) 2146 MaskConst.push_back(UndefValue::get(Int32Ty)); 2147 else 2148 MaskConst.push_back(ConstantInt::get(Int32Ty, Elem)); 2149 } 2150 return ConstantVector::get(MaskConst); 2151 } 2152 2153 static bool isSingleSourceMaskImpl(ArrayRef<int> Mask, int NumOpElts) { 2154 assert(!Mask.empty() && "Shuffle mask must contain elements"); 2155 bool UsesLHS = false; 2156 bool UsesRHS = false; 2157 for (int I : Mask) { 2158 if (I == -1) 2159 continue; 2160 assert(I >= 0 && I < (NumOpElts * 2) && 2161 "Out-of-bounds shuffle mask element"); 2162 UsesLHS |= (I < NumOpElts); 2163 UsesRHS |= (I >= NumOpElts); 2164 if (UsesLHS && UsesRHS) 2165 return false; 2166 } 2167 // Allow for degenerate case: completely undef mask means neither source is used. 2168 return UsesLHS || UsesRHS; 2169 } 2170 2171 bool ShuffleVectorInst::isSingleSourceMask(ArrayRef<int> Mask) { 2172 // We don't have vector operand size information, so assume operands are the 2173 // same size as the mask. 2174 return isSingleSourceMaskImpl(Mask, Mask.size()); 2175 } 2176 2177 static bool isIdentityMaskImpl(ArrayRef<int> Mask, int NumOpElts) { 2178 if (!isSingleSourceMaskImpl(Mask, NumOpElts)) 2179 return false; 2180 for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) { 2181 if (Mask[i] == -1) 2182 continue; 2183 if (Mask[i] != i && Mask[i] != (NumOpElts + i)) 2184 return false; 2185 } 2186 return true; 2187 } 2188 2189 bool ShuffleVectorInst::isIdentityMask(ArrayRef<int> Mask) { 2190 // We don't have vector operand size information, so assume operands are the 2191 // same size as the mask. 2192 return isIdentityMaskImpl(Mask, Mask.size()); 2193 } 2194 2195 bool ShuffleVectorInst::isReverseMask(ArrayRef<int> Mask) { 2196 if (!isSingleSourceMask(Mask)) 2197 return false; 2198 for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) { 2199 if (Mask[i] == -1) 2200 continue; 2201 if (Mask[i] != (NumElts - 1 - i) && Mask[i] != (NumElts + NumElts - 1 - i)) 2202 return false; 2203 } 2204 return true; 2205 } 2206 2207 bool ShuffleVectorInst::isZeroEltSplatMask(ArrayRef<int> Mask) { 2208 if (!isSingleSourceMask(Mask)) 2209 return false; 2210 for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) { 2211 if (Mask[i] == -1) 2212 continue; 2213 if (Mask[i] != 0 && Mask[i] != NumElts) 2214 return false; 2215 } 2216 return true; 2217 } 2218 2219 bool ShuffleVectorInst::isSelectMask(ArrayRef<int> Mask) { 2220 // Select is differentiated from identity. It requires using both sources. 2221 if (isSingleSourceMask(Mask)) 2222 return false; 2223 for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) { 2224 if (Mask[i] == -1) 2225 continue; 2226 if (Mask[i] != i && Mask[i] != (NumElts + i)) 2227 return false; 2228 } 2229 return true; 2230 } 2231 2232 bool ShuffleVectorInst::isTransposeMask(ArrayRef<int> Mask) { 2233 // Example masks that will return true: 2234 // v1 = <a, b, c, d> 2235 // v2 = <e, f, g, h> 2236 // trn1 = shufflevector v1, v2 <0, 4, 2, 6> = <a, e, c, g> 2237 // trn2 = shufflevector v1, v2 <1, 5, 3, 7> = <b, f, d, h> 2238 2239 // 1. The number of elements in the mask must be a power-of-2 and at least 2. 2240 int NumElts = Mask.size(); 2241 if (NumElts < 2 || !isPowerOf2_32(NumElts)) 2242 return false; 2243 2244 // 2. The first element of the mask must be either a 0 or a 1. 2245 if (Mask[0] != 0 && Mask[0] != 1) 2246 return false; 2247 2248 // 3. The difference between the first 2 elements must be equal to the 2249 // number of elements in the mask. 2250 if ((Mask[1] - Mask[0]) != NumElts) 2251 return false; 2252 2253 // 4. The difference between consecutive even-numbered and odd-numbered 2254 // elements must be equal to 2. 2255 for (int i = 2; i < NumElts; ++i) { 2256 int MaskEltVal = Mask[i]; 2257 if (MaskEltVal == -1) 2258 return false; 2259 int MaskEltPrevVal = Mask[i - 2]; 2260 if (MaskEltVal - MaskEltPrevVal != 2) 2261 return false; 2262 } 2263 return true; 2264 } 2265 2266 bool ShuffleVectorInst::isExtractSubvectorMask(ArrayRef<int> Mask, 2267 int NumSrcElts, int &Index) { 2268 // Must extract from a single source. 2269 if (!isSingleSourceMaskImpl(Mask, NumSrcElts)) 2270 return false; 2271 2272 // Must be smaller (else this is an Identity shuffle). 2273 if (NumSrcElts <= (int)Mask.size()) 2274 return false; 2275 2276 // Find start of extraction, accounting that we may start with an UNDEF. 2277 int SubIndex = -1; 2278 for (int i = 0, e = Mask.size(); i != e; ++i) { 2279 int M = Mask[i]; 2280 if (M < 0) 2281 continue; 2282 int Offset = (M % NumSrcElts) - i; 2283 if (0 <= SubIndex && SubIndex != Offset) 2284 return false; 2285 SubIndex = Offset; 2286 } 2287 2288 if (0 <= SubIndex && SubIndex + (int)Mask.size() <= NumSrcElts) { 2289 Index = SubIndex; 2290 return true; 2291 } 2292 return false; 2293 } 2294 2295 bool ShuffleVectorInst::isInsertSubvectorMask(ArrayRef<int> Mask, 2296 int NumSrcElts, int &NumSubElts, 2297 int &Index) { 2298 int NumMaskElts = Mask.size(); 2299 2300 // Don't try to match if we're shuffling to a smaller size. 2301 if (NumMaskElts < NumSrcElts) 2302 return false; 2303 2304 // TODO: We don't recognize self-insertion/widening. 2305 if (isSingleSourceMaskImpl(Mask, NumSrcElts)) 2306 return false; 2307 2308 // Determine which mask elements are attributed to which source. 2309 APInt UndefElts = APInt::getZero(NumMaskElts); 2310 APInt Src0Elts = APInt::getZero(NumMaskElts); 2311 APInt Src1Elts = APInt::getZero(NumMaskElts); 2312 bool Src0Identity = true; 2313 bool Src1Identity = true; 2314 2315 for (int i = 0; i != NumMaskElts; ++i) { 2316 int M = Mask[i]; 2317 if (M < 0) { 2318 UndefElts.setBit(i); 2319 continue; 2320 } 2321 if (M < NumSrcElts) { 2322 Src0Elts.setBit(i); 2323 Src0Identity &= (M == i); 2324 continue; 2325 } 2326 Src1Elts.setBit(i); 2327 Src1Identity &= (M == (i + NumSrcElts)); 2328 } 2329 assert((Src0Elts | Src1Elts | UndefElts).isAllOnes() && 2330 "unknown shuffle elements"); 2331 assert(!Src0Elts.isZero() && !Src1Elts.isZero() && 2332 "2-source shuffle not found"); 2333 2334 // Determine lo/hi span ranges. 2335 // TODO: How should we handle undefs at the start of subvector insertions? 2336 int Src0Lo = Src0Elts.countTrailingZeros(); 2337 int Src1Lo = Src1Elts.countTrailingZeros(); 2338 int Src0Hi = NumMaskElts - Src0Elts.countLeadingZeros(); 2339 int Src1Hi = NumMaskElts - Src1Elts.countLeadingZeros(); 2340 2341 // If src0 is in place, see if the src1 elements is inplace within its own 2342 // span. 2343 if (Src0Identity) { 2344 int NumSub1Elts = Src1Hi - Src1Lo; 2345 ArrayRef<int> Sub1Mask = Mask.slice(Src1Lo, NumSub1Elts); 2346 if (isIdentityMaskImpl(Sub1Mask, NumSrcElts)) { 2347 NumSubElts = NumSub1Elts; 2348 Index = Src1Lo; 2349 return true; 2350 } 2351 } 2352 2353 // If src1 is in place, see if the src0 elements is inplace within its own 2354 // span. 2355 if (Src1Identity) { 2356 int NumSub0Elts = Src0Hi - Src0Lo; 2357 ArrayRef<int> Sub0Mask = Mask.slice(Src0Lo, NumSub0Elts); 2358 if (isIdentityMaskImpl(Sub0Mask, NumSrcElts)) { 2359 NumSubElts = NumSub0Elts; 2360 Index = Src0Lo; 2361 return true; 2362 } 2363 } 2364 2365 return false; 2366 } 2367 2368 bool ShuffleVectorInst::isIdentityWithPadding() const { 2369 if (isa<UndefValue>(Op<2>())) 2370 return false; 2371 2372 // FIXME: Not currently possible to express a shuffle mask for a scalable 2373 // vector for this case. 2374 if (isa<ScalableVectorType>(getType())) 2375 return false; 2376 2377 int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements(); 2378 int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements(); 2379 if (NumMaskElts <= NumOpElts) 2380 return false; 2381 2382 // The first part of the mask must choose elements from exactly 1 source op. 2383 ArrayRef<int> Mask = getShuffleMask(); 2384 if (!isIdentityMaskImpl(Mask, NumOpElts)) 2385 return false; 2386 2387 // All extending must be with undef elements. 2388 for (int i = NumOpElts; i < NumMaskElts; ++i) 2389 if (Mask[i] != -1) 2390 return false; 2391 2392 return true; 2393 } 2394 2395 bool ShuffleVectorInst::isIdentityWithExtract() const { 2396 if (isa<UndefValue>(Op<2>())) 2397 return false; 2398 2399 // FIXME: Not currently possible to express a shuffle mask for a scalable 2400 // vector for this case. 2401 if (isa<ScalableVectorType>(getType())) 2402 return false; 2403 2404 int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements(); 2405 int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements(); 2406 if (NumMaskElts >= NumOpElts) 2407 return false; 2408 2409 return isIdentityMaskImpl(getShuffleMask(), NumOpElts); 2410 } 2411 2412 bool ShuffleVectorInst::isConcat() const { 2413 // Vector concatenation is differentiated from identity with padding. 2414 if (isa<UndefValue>(Op<0>()) || isa<UndefValue>(Op<1>()) || 2415 isa<UndefValue>(Op<2>())) 2416 return false; 2417 2418 // FIXME: Not currently possible to express a shuffle mask for a scalable 2419 // vector for this case. 2420 if (isa<ScalableVectorType>(getType())) 2421 return false; 2422 2423 int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements(); 2424 int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements(); 2425 if (NumMaskElts != NumOpElts * 2) 2426 return false; 2427 2428 // Use the mask length rather than the operands' vector lengths here. We 2429 // already know that the shuffle returns a vector twice as long as the inputs, 2430 // and neither of the inputs are undef vectors. If the mask picks consecutive 2431 // elements from both inputs, then this is a concatenation of the inputs. 2432 return isIdentityMaskImpl(getShuffleMask(), NumMaskElts); 2433 } 2434 2435 static bool isReplicationMaskWithParams(ArrayRef<int> Mask, 2436 int ReplicationFactor, int VF) { 2437 assert(Mask.size() == (unsigned)ReplicationFactor * VF && 2438 "Unexpected mask size."); 2439 2440 for (int CurrElt : seq(0, VF)) { 2441 ArrayRef<int> CurrSubMask = Mask.take_front(ReplicationFactor); 2442 assert(CurrSubMask.size() == (unsigned)ReplicationFactor && 2443 "Run out of mask?"); 2444 Mask = Mask.drop_front(ReplicationFactor); 2445 if (!all_of(CurrSubMask, [CurrElt](int MaskElt) { 2446 return MaskElt == UndefMaskElem || MaskElt == CurrElt; 2447 })) 2448 return false; 2449 } 2450 assert(Mask.empty() && "Did not consume the whole mask?"); 2451 2452 return true; 2453 } 2454 2455 bool ShuffleVectorInst::isReplicationMask(ArrayRef<int> Mask, 2456 int &ReplicationFactor, int &VF) { 2457 // undef-less case is trivial. 2458 if (none_of(Mask, [](int MaskElt) { return MaskElt == UndefMaskElem; })) { 2459 ReplicationFactor = 2460 Mask.take_while([](int MaskElt) { return MaskElt == 0; }).size(); 2461 if (ReplicationFactor == 0 || Mask.size() % ReplicationFactor != 0) 2462 return false; 2463 VF = Mask.size() / ReplicationFactor; 2464 return isReplicationMaskWithParams(Mask, ReplicationFactor, VF); 2465 } 2466 2467 // However, if the mask contains undef's, we have to enumerate possible tuples 2468 // and pick one. There are bounds on replication factor: [1, mask size] 2469 // (where RF=1 is an identity shuffle, RF=mask size is a broadcast shuffle) 2470 // Additionally, mask size is a replication factor multiplied by vector size, 2471 // which further significantly reduces the search space. 2472 2473 // Before doing that, let's perform basic correctness checking first. 2474 int Largest = -1; 2475 for (int MaskElt : Mask) { 2476 if (MaskElt == UndefMaskElem) 2477 continue; 2478 // Elements must be in non-decreasing order. 2479 if (MaskElt < Largest) 2480 return false; 2481 Largest = std::max(Largest, MaskElt); 2482 } 2483 2484 // Prefer larger replication factor if all else equal. 2485 for (int PossibleReplicationFactor : 2486 reverse(seq_inclusive<unsigned>(1, Mask.size()))) { 2487 if (Mask.size() % PossibleReplicationFactor != 0) 2488 continue; 2489 int PossibleVF = Mask.size() / PossibleReplicationFactor; 2490 if (!isReplicationMaskWithParams(Mask, PossibleReplicationFactor, 2491 PossibleVF)) 2492 continue; 2493 ReplicationFactor = PossibleReplicationFactor; 2494 VF = PossibleVF; 2495 return true; 2496 } 2497 2498 return false; 2499 } 2500 2501 bool ShuffleVectorInst::isReplicationMask(int &ReplicationFactor, 2502 int &VF) const { 2503 // Not possible to express a shuffle mask for a scalable vector for this 2504 // case. 2505 if (isa<ScalableVectorType>(getType())) 2506 return false; 2507 2508 VF = cast<FixedVectorType>(Op<0>()->getType())->getNumElements(); 2509 if (ShuffleMask.size() % VF != 0) 2510 return false; 2511 ReplicationFactor = ShuffleMask.size() / VF; 2512 2513 return isReplicationMaskWithParams(ShuffleMask, ReplicationFactor, VF); 2514 } 2515 2516 //===----------------------------------------------------------------------===// 2517 // InsertValueInst Class 2518 //===----------------------------------------------------------------------===// 2519 2520 void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, 2521 const Twine &Name) { 2522 assert(getNumOperands() == 2 && "NumOperands not initialized?"); 2523 2524 // There's no fundamental reason why we require at least one index 2525 // (other than weirdness with &*IdxBegin being invalid; see 2526 // getelementptr's init routine for example). But there's no 2527 // present need to support it. 2528 assert(!Idxs.empty() && "InsertValueInst must have at least one index"); 2529 2530 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) == 2531 Val->getType() && "Inserted value must match indexed type!"); 2532 Op<0>() = Agg; 2533 Op<1>() = Val; 2534 2535 Indices.append(Idxs.begin(), Idxs.end()); 2536 setName(Name); 2537 } 2538 2539 InsertValueInst::InsertValueInst(const InsertValueInst &IVI) 2540 : Instruction(IVI.getType(), InsertValue, 2541 OperandTraits<InsertValueInst>::op_begin(this), 2), 2542 Indices(IVI.Indices) { 2543 Op<0>() = IVI.getOperand(0); 2544 Op<1>() = IVI.getOperand(1); 2545 SubclassOptionalData = IVI.SubclassOptionalData; 2546 } 2547 2548 //===----------------------------------------------------------------------===// 2549 // ExtractValueInst Class 2550 //===----------------------------------------------------------------------===// 2551 2552 void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) { 2553 assert(getNumOperands() == 1 && "NumOperands not initialized?"); 2554 2555 // There's no fundamental reason why we require at least one index. 2556 // But there's no present need to support it. 2557 assert(!Idxs.empty() && "ExtractValueInst must have at least one index"); 2558 2559 Indices.append(Idxs.begin(), Idxs.end()); 2560 setName(Name); 2561 } 2562 2563 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI) 2564 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)), 2565 Indices(EVI.Indices) { 2566 SubclassOptionalData = EVI.SubclassOptionalData; 2567 } 2568 2569 // getIndexedType - Returns the type of the element that would be extracted 2570 // with an extractvalue instruction with the specified parameters. 2571 // 2572 // A null type is returned if the indices are invalid for the specified 2573 // pointer type. 2574 // 2575 Type *ExtractValueInst::getIndexedType(Type *Agg, 2576 ArrayRef<unsigned> Idxs) { 2577 for (unsigned Index : Idxs) { 2578 // We can't use CompositeType::indexValid(Index) here. 2579 // indexValid() always returns true for arrays because getelementptr allows 2580 // out-of-bounds indices. Since we don't allow those for extractvalue and 2581 // insertvalue we need to check array indexing manually. 2582 // Since the only other types we can index into are struct types it's just 2583 // as easy to check those manually as well. 2584 if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) { 2585 if (Index >= AT->getNumElements()) 2586 return nullptr; 2587 Agg = AT->getElementType(); 2588 } else if (StructType *ST = dyn_cast<StructType>(Agg)) { 2589 if (Index >= ST->getNumElements()) 2590 return nullptr; 2591 Agg = ST->getElementType(Index); 2592 } else { 2593 // Not a valid type to index into. 2594 return nullptr; 2595 } 2596 } 2597 return const_cast<Type*>(Agg); 2598 } 2599 2600 //===----------------------------------------------------------------------===// 2601 // UnaryOperator Class 2602 //===----------------------------------------------------------------------===// 2603 2604 UnaryOperator::UnaryOperator(UnaryOps iType, Value *S, 2605 Type *Ty, const Twine &Name, 2606 Instruction *InsertBefore) 2607 : UnaryInstruction(Ty, iType, S, InsertBefore) { 2608 Op<0>() = S; 2609 setName(Name); 2610 AssertOK(); 2611 } 2612 2613 UnaryOperator::UnaryOperator(UnaryOps iType, Value *S, 2614 Type *Ty, const Twine &Name, 2615 BasicBlock *InsertAtEnd) 2616 : UnaryInstruction(Ty, iType, S, InsertAtEnd) { 2617 Op<0>() = S; 2618 setName(Name); 2619 AssertOK(); 2620 } 2621 2622 UnaryOperator *UnaryOperator::Create(UnaryOps Op, Value *S, 2623 const Twine &Name, 2624 Instruction *InsertBefore) { 2625 return new UnaryOperator(Op, S, S->getType(), Name, InsertBefore); 2626 } 2627 2628 UnaryOperator *UnaryOperator::Create(UnaryOps Op, Value *S, 2629 const Twine &Name, 2630 BasicBlock *InsertAtEnd) { 2631 UnaryOperator *Res = Create(Op, S, Name); 2632 InsertAtEnd->getInstList().push_back(Res); 2633 return Res; 2634 } 2635 2636 void UnaryOperator::AssertOK() { 2637 Value *LHS = getOperand(0); 2638 (void)LHS; // Silence warnings. 2639 #ifndef NDEBUG 2640 switch (getOpcode()) { 2641 case FNeg: 2642 assert(getType() == LHS->getType() && 2643 "Unary operation should return same type as operand!"); 2644 assert(getType()->isFPOrFPVectorTy() && 2645 "Tried to create a floating-point operation on a " 2646 "non-floating-point type!"); 2647 break; 2648 default: llvm_unreachable("Invalid opcode provided"); 2649 } 2650 #endif 2651 } 2652 2653 //===----------------------------------------------------------------------===// 2654 // BinaryOperator Class 2655 //===----------------------------------------------------------------------===// 2656 2657 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2, 2658 Type *Ty, const Twine &Name, 2659 Instruction *InsertBefore) 2660 : Instruction(Ty, iType, 2661 OperandTraits<BinaryOperator>::op_begin(this), 2662 OperandTraits<BinaryOperator>::operands(this), 2663 InsertBefore) { 2664 Op<0>() = S1; 2665 Op<1>() = S2; 2666 setName(Name); 2667 AssertOK(); 2668 } 2669 2670 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2, 2671 Type *Ty, const Twine &Name, 2672 BasicBlock *InsertAtEnd) 2673 : Instruction(Ty, iType, 2674 OperandTraits<BinaryOperator>::op_begin(this), 2675 OperandTraits<BinaryOperator>::operands(this), 2676 InsertAtEnd) { 2677 Op<0>() = S1; 2678 Op<1>() = S2; 2679 setName(Name); 2680 AssertOK(); 2681 } 2682 2683 void BinaryOperator::AssertOK() { 2684 Value *LHS = getOperand(0), *RHS = getOperand(1); 2685 (void)LHS; (void)RHS; // Silence warnings. 2686 assert(LHS->getType() == RHS->getType() && 2687 "Binary operator operand types must match!"); 2688 #ifndef NDEBUG 2689 switch (getOpcode()) { 2690 case Add: case Sub: 2691 case Mul: 2692 assert(getType() == LHS->getType() && 2693 "Arithmetic operation should return same type as operands!"); 2694 assert(getType()->isIntOrIntVectorTy() && 2695 "Tried to create an integer operation on a non-integer type!"); 2696 break; 2697 case FAdd: case FSub: 2698 case FMul: 2699 assert(getType() == LHS->getType() && 2700 "Arithmetic operation should return same type as operands!"); 2701 assert(getType()->isFPOrFPVectorTy() && 2702 "Tried to create a floating-point operation on a " 2703 "non-floating-point type!"); 2704 break; 2705 case UDiv: 2706 case SDiv: 2707 assert(getType() == LHS->getType() && 2708 "Arithmetic operation should return same type as operands!"); 2709 assert(getType()->isIntOrIntVectorTy() && 2710 "Incorrect operand type (not integer) for S/UDIV"); 2711 break; 2712 case FDiv: 2713 assert(getType() == LHS->getType() && 2714 "Arithmetic operation should return same type as operands!"); 2715 assert(getType()->isFPOrFPVectorTy() && 2716 "Incorrect operand type (not floating point) for FDIV"); 2717 break; 2718 case URem: 2719 case SRem: 2720 assert(getType() == LHS->getType() && 2721 "Arithmetic operation should return same type as operands!"); 2722 assert(getType()->isIntOrIntVectorTy() && 2723 "Incorrect operand type (not integer) for S/UREM"); 2724 break; 2725 case FRem: 2726 assert(getType() == LHS->getType() && 2727 "Arithmetic operation should return same type as operands!"); 2728 assert(getType()->isFPOrFPVectorTy() && 2729 "Incorrect operand type (not floating point) for FREM"); 2730 break; 2731 case Shl: 2732 case LShr: 2733 case AShr: 2734 assert(getType() == LHS->getType() && 2735 "Shift operation should return same type as operands!"); 2736 assert(getType()->isIntOrIntVectorTy() && 2737 "Tried to create a shift operation on a non-integral type!"); 2738 break; 2739 case And: case Or: 2740 case Xor: 2741 assert(getType() == LHS->getType() && 2742 "Logical operation should return same type as operands!"); 2743 assert(getType()->isIntOrIntVectorTy() && 2744 "Tried to create a logical operation on a non-integral type!"); 2745 break; 2746 default: llvm_unreachable("Invalid opcode provided"); 2747 } 2748 #endif 2749 } 2750 2751 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2, 2752 const Twine &Name, 2753 Instruction *InsertBefore) { 2754 assert(S1->getType() == S2->getType() && 2755 "Cannot create binary operator with two operands of differing type!"); 2756 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore); 2757 } 2758 2759 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2, 2760 const Twine &Name, 2761 BasicBlock *InsertAtEnd) { 2762 BinaryOperator *Res = Create(Op, S1, S2, Name); 2763 InsertAtEnd->getInstList().push_back(Res); 2764 return Res; 2765 } 2766 2767 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name, 2768 Instruction *InsertBefore) { 2769 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2770 return new BinaryOperator(Instruction::Sub, 2771 zero, Op, 2772 Op->getType(), Name, InsertBefore); 2773 } 2774 2775 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name, 2776 BasicBlock *InsertAtEnd) { 2777 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2778 return new BinaryOperator(Instruction::Sub, 2779 zero, Op, 2780 Op->getType(), Name, InsertAtEnd); 2781 } 2782 2783 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name, 2784 Instruction *InsertBefore) { 2785 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2786 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore); 2787 } 2788 2789 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name, 2790 BasicBlock *InsertAtEnd) { 2791 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2792 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd); 2793 } 2794 2795 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name, 2796 Instruction *InsertBefore) { 2797 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2798 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore); 2799 } 2800 2801 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name, 2802 BasicBlock *InsertAtEnd) { 2803 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2804 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd); 2805 } 2806 2807 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name, 2808 Instruction *InsertBefore) { 2809 Constant *C = Constant::getAllOnesValue(Op->getType()); 2810 return new BinaryOperator(Instruction::Xor, Op, C, 2811 Op->getType(), Name, InsertBefore); 2812 } 2813 2814 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name, 2815 BasicBlock *InsertAtEnd) { 2816 Constant *AllOnes = Constant::getAllOnesValue(Op->getType()); 2817 return new BinaryOperator(Instruction::Xor, Op, AllOnes, 2818 Op->getType(), Name, InsertAtEnd); 2819 } 2820 2821 // Exchange the two operands to this instruction. This instruction is safe to 2822 // use on any binary instruction and does not modify the semantics of the 2823 // instruction. If the instruction is order-dependent (SetLT f.e.), the opcode 2824 // is changed. 2825 bool BinaryOperator::swapOperands() { 2826 if (!isCommutative()) 2827 return true; // Can't commute operands 2828 Op<0>().swap(Op<1>()); 2829 return false; 2830 } 2831 2832 //===----------------------------------------------------------------------===// 2833 // FPMathOperator Class 2834 //===----------------------------------------------------------------------===// 2835 2836 float FPMathOperator::getFPAccuracy() const { 2837 const MDNode *MD = 2838 cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath); 2839 if (!MD) 2840 return 0.0; 2841 ConstantFP *Accuracy = mdconst::extract<ConstantFP>(MD->getOperand(0)); 2842 return Accuracy->getValueAPF().convertToFloat(); 2843 } 2844 2845 //===----------------------------------------------------------------------===// 2846 // CastInst Class 2847 //===----------------------------------------------------------------------===// 2848 2849 // Just determine if this cast only deals with integral->integral conversion. 2850 bool CastInst::isIntegerCast() const { 2851 switch (getOpcode()) { 2852 default: return false; 2853 case Instruction::ZExt: 2854 case Instruction::SExt: 2855 case Instruction::Trunc: 2856 return true; 2857 case Instruction::BitCast: 2858 return getOperand(0)->getType()->isIntegerTy() && 2859 getType()->isIntegerTy(); 2860 } 2861 } 2862 2863 bool CastInst::isLosslessCast() const { 2864 // Only BitCast can be lossless, exit fast if we're not BitCast 2865 if (getOpcode() != Instruction::BitCast) 2866 return false; 2867 2868 // Identity cast is always lossless 2869 Type *SrcTy = getOperand(0)->getType(); 2870 Type *DstTy = getType(); 2871 if (SrcTy == DstTy) 2872 return true; 2873 2874 // Pointer to pointer is always lossless. 2875 if (SrcTy->isPointerTy()) 2876 return DstTy->isPointerTy(); 2877 return false; // Other types have no identity values 2878 } 2879 2880 /// This function determines if the CastInst does not require any bits to be 2881 /// changed in order to effect the cast. Essentially, it identifies cases where 2882 /// no code gen is necessary for the cast, hence the name no-op cast. For 2883 /// example, the following are all no-op casts: 2884 /// # bitcast i32* %x to i8* 2885 /// # bitcast <2 x i32> %x to <4 x i16> 2886 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only 2887 /// Determine if the described cast is a no-op. 2888 bool CastInst::isNoopCast(Instruction::CastOps Opcode, 2889 Type *SrcTy, 2890 Type *DestTy, 2891 const DataLayout &DL) { 2892 assert(castIsValid(Opcode, SrcTy, DestTy) && "method precondition"); 2893 switch (Opcode) { 2894 default: llvm_unreachable("Invalid CastOp"); 2895 case Instruction::Trunc: 2896 case Instruction::ZExt: 2897 case Instruction::SExt: 2898 case Instruction::FPTrunc: 2899 case Instruction::FPExt: 2900 case Instruction::UIToFP: 2901 case Instruction::SIToFP: 2902 case Instruction::FPToUI: 2903 case Instruction::FPToSI: 2904 case Instruction::AddrSpaceCast: 2905 // TODO: Target informations may give a more accurate answer here. 2906 return false; 2907 case Instruction::BitCast: 2908 return true; // BitCast never modifies bits. 2909 case Instruction::PtrToInt: 2910 return DL.getIntPtrType(SrcTy)->getScalarSizeInBits() == 2911 DestTy->getScalarSizeInBits(); 2912 case Instruction::IntToPtr: 2913 return DL.getIntPtrType(DestTy)->getScalarSizeInBits() == 2914 SrcTy->getScalarSizeInBits(); 2915 } 2916 } 2917 2918 bool CastInst::isNoopCast(const DataLayout &DL) const { 2919 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), DL); 2920 } 2921 2922 /// This function determines if a pair of casts can be eliminated and what 2923 /// opcode should be used in the elimination. This assumes that there are two 2924 /// instructions like this: 2925 /// * %F = firstOpcode SrcTy %x to MidTy 2926 /// * %S = secondOpcode MidTy %F to DstTy 2927 /// The function returns a resultOpcode so these two casts can be replaced with: 2928 /// * %Replacement = resultOpcode %SrcTy %x to DstTy 2929 /// If no such cast is permitted, the function returns 0. 2930 unsigned CastInst::isEliminableCastPair( 2931 Instruction::CastOps firstOp, Instruction::CastOps secondOp, 2932 Type *SrcTy, Type *MidTy, Type *DstTy, Type *SrcIntPtrTy, Type *MidIntPtrTy, 2933 Type *DstIntPtrTy) { 2934 // Define the 144 possibilities for these two cast instructions. The values 2935 // in this matrix determine what to do in a given situation and select the 2936 // case in the switch below. The rows correspond to firstOp, the columns 2937 // correspond to secondOp. In looking at the table below, keep in mind 2938 // the following cast properties: 2939 // 2940 // Size Compare Source Destination 2941 // Operator Src ? Size Type Sign Type Sign 2942 // -------- ------------ ------------------- --------------------- 2943 // TRUNC > Integer Any Integral Any 2944 // ZEXT < Integral Unsigned Integer Any 2945 // SEXT < Integral Signed Integer Any 2946 // FPTOUI n/a FloatPt n/a Integral Unsigned 2947 // FPTOSI n/a FloatPt n/a Integral Signed 2948 // UITOFP n/a Integral Unsigned FloatPt n/a 2949 // SITOFP n/a Integral Signed FloatPt n/a 2950 // FPTRUNC > FloatPt n/a FloatPt n/a 2951 // FPEXT < FloatPt n/a FloatPt n/a 2952 // PTRTOINT n/a Pointer n/a Integral Unsigned 2953 // INTTOPTR n/a Integral Unsigned Pointer n/a 2954 // BITCAST = FirstClass n/a FirstClass n/a 2955 // ADDRSPCST n/a Pointer n/a Pointer n/a 2956 // 2957 // NOTE: some transforms are safe, but we consider them to be non-profitable. 2958 // For example, we could merge "fptoui double to i32" + "zext i32 to i64", 2959 // into "fptoui double to i64", but this loses information about the range 2960 // of the produced value (we no longer know the top-part is all zeros). 2961 // Further this conversion is often much more expensive for typical hardware, 2962 // and causes issues when building libgcc. We disallow fptosi+sext for the 2963 // same reason. 2964 const unsigned numCastOps = 2965 Instruction::CastOpsEnd - Instruction::CastOpsBegin; 2966 static const uint8_t CastResults[numCastOps][numCastOps] = { 2967 // T F F U S F F P I B A -+ 2968 // R Z S P P I I T P 2 N T S | 2969 // U E E 2 2 2 2 R E I T C C +- secondOp 2970 // N X X U S F F N X N 2 V V | 2971 // C T T I I P P C T T P T T -+ 2972 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // Trunc -+ 2973 { 8, 1, 9,99,99, 2,17,99,99,99, 2, 3, 0}, // ZExt | 2974 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3, 0}, // SExt | 2975 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToUI | 2976 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToSI | 2977 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // UIToFP +- firstOp 2978 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // SIToFP | 2979 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // FPTrunc | 2980 { 99,99,99, 2, 2,99,99, 8, 2,99,99, 4, 0}, // FPExt | 2981 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3, 0}, // PtrToInt | 2982 { 99,99,99,99,99,99,99,99,99,11,99,15, 0}, // IntToPtr | 2983 { 5, 5, 5, 6, 6, 5, 5, 6, 6,16, 5, 1,14}, // BitCast | 2984 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+ 2985 }; 2986 2987 // TODO: This logic could be encoded into the table above and handled in the 2988 // switch below. 2989 // If either of the casts are a bitcast from scalar to vector, disallow the 2990 // merging. However, any pair of bitcasts are allowed. 2991 bool IsFirstBitcast = (firstOp == Instruction::BitCast); 2992 bool IsSecondBitcast = (secondOp == Instruction::BitCast); 2993 bool AreBothBitcasts = IsFirstBitcast && IsSecondBitcast; 2994 2995 // Check if any of the casts convert scalars <-> vectors. 2996 if ((IsFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) || 2997 (IsSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy))) 2998 if (!AreBothBitcasts) 2999 return 0; 3000 3001 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin] 3002 [secondOp-Instruction::CastOpsBegin]; 3003 switch (ElimCase) { 3004 case 0: 3005 // Categorically disallowed. 3006 return 0; 3007 case 1: 3008 // Allowed, use first cast's opcode. 3009 return firstOp; 3010 case 2: 3011 // Allowed, use second cast's opcode. 3012 return secondOp; 3013 case 3: 3014 // No-op cast in second op implies firstOp as long as the DestTy 3015 // is integer and we are not converting between a vector and a 3016 // non-vector type. 3017 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy()) 3018 return firstOp; 3019 return 0; 3020 case 4: 3021 // No-op cast in second op implies firstOp as long as the DestTy 3022 // is floating point. 3023 if (DstTy->isFloatingPointTy()) 3024 return firstOp; 3025 return 0; 3026 case 5: 3027 // No-op cast in first op implies secondOp as long as the SrcTy 3028 // is an integer. 3029 if (SrcTy->isIntegerTy()) 3030 return secondOp; 3031 return 0; 3032 case 6: 3033 // No-op cast in first op implies secondOp as long as the SrcTy 3034 // is a floating point. 3035 if (SrcTy->isFloatingPointTy()) 3036 return secondOp; 3037 return 0; 3038 case 7: { 3039 // Disable inttoptr/ptrtoint optimization if enabled. 3040 if (DisableI2pP2iOpt) 3041 return 0; 3042 3043 // Cannot simplify if address spaces are different! 3044 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) 3045 return 0; 3046 3047 unsigned MidSize = MidTy->getScalarSizeInBits(); 3048 // We can still fold this without knowing the actual sizes as long we 3049 // know that the intermediate pointer is the largest possible 3050 // pointer size. 3051 // FIXME: Is this always true? 3052 if (MidSize == 64) 3053 return Instruction::BitCast; 3054 3055 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size. 3056 if (!SrcIntPtrTy || DstIntPtrTy != SrcIntPtrTy) 3057 return 0; 3058 unsigned PtrSize = SrcIntPtrTy->getScalarSizeInBits(); 3059 if (MidSize >= PtrSize) 3060 return Instruction::BitCast; 3061 return 0; 3062 } 3063 case 8: { 3064 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size 3065 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy) 3066 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy) 3067 unsigned SrcSize = SrcTy->getScalarSizeInBits(); 3068 unsigned DstSize = DstTy->getScalarSizeInBits(); 3069 if (SrcSize == DstSize) 3070 return Instruction::BitCast; 3071 else if (SrcSize < DstSize) 3072 return firstOp; 3073 return secondOp; 3074 } 3075 case 9: 3076 // zext, sext -> zext, because sext can't sign extend after zext 3077 return Instruction::ZExt; 3078 case 11: { 3079 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize 3080 if (!MidIntPtrTy) 3081 return 0; 3082 unsigned PtrSize = MidIntPtrTy->getScalarSizeInBits(); 3083 unsigned SrcSize = SrcTy->getScalarSizeInBits(); 3084 unsigned DstSize = DstTy->getScalarSizeInBits(); 3085 if (SrcSize <= PtrSize && SrcSize == DstSize) 3086 return Instruction::BitCast; 3087 return 0; 3088 } 3089 case 12: 3090 // addrspacecast, addrspacecast -> bitcast, if SrcAS == DstAS 3091 // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS 3092 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) 3093 return Instruction::AddrSpaceCast; 3094 return Instruction::BitCast; 3095 case 13: 3096 // FIXME: this state can be merged with (1), but the following assert 3097 // is useful to check the correcteness of the sequence due to semantic 3098 // change of bitcast. 3099 assert( 3100 SrcTy->isPtrOrPtrVectorTy() && 3101 MidTy->isPtrOrPtrVectorTy() && 3102 DstTy->isPtrOrPtrVectorTy() && 3103 SrcTy->getPointerAddressSpace() != MidTy->getPointerAddressSpace() && 3104 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() && 3105 "Illegal addrspacecast, bitcast sequence!"); 3106 // Allowed, use first cast's opcode 3107 return firstOp; 3108 case 14: { 3109 // bitcast, addrspacecast -> addrspacecast if the element type of 3110 // bitcast's source is the same as that of addrspacecast's destination. 3111 PointerType *SrcPtrTy = cast<PointerType>(SrcTy->getScalarType()); 3112 PointerType *DstPtrTy = cast<PointerType>(DstTy->getScalarType()); 3113 if (SrcPtrTy->hasSameElementTypeAs(DstPtrTy)) 3114 return Instruction::AddrSpaceCast; 3115 return 0; 3116 } 3117 case 15: 3118 // FIXME: this state can be merged with (1), but the following assert 3119 // is useful to check the correcteness of the sequence due to semantic 3120 // change of bitcast. 3121 assert( 3122 SrcTy->isIntOrIntVectorTy() && 3123 MidTy->isPtrOrPtrVectorTy() && 3124 DstTy->isPtrOrPtrVectorTy() && 3125 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() && 3126 "Illegal inttoptr, bitcast sequence!"); 3127 // Allowed, use first cast's opcode 3128 return firstOp; 3129 case 16: 3130 // FIXME: this state can be merged with (2), but the following assert 3131 // is useful to check the correcteness of the sequence due to semantic 3132 // change of bitcast. 3133 assert( 3134 SrcTy->isPtrOrPtrVectorTy() && 3135 MidTy->isPtrOrPtrVectorTy() && 3136 DstTy->isIntOrIntVectorTy() && 3137 SrcTy->getPointerAddressSpace() == MidTy->getPointerAddressSpace() && 3138 "Illegal bitcast, ptrtoint sequence!"); 3139 // Allowed, use second cast's opcode 3140 return secondOp; 3141 case 17: 3142 // (sitofp (zext x)) -> (uitofp x) 3143 return Instruction::UIToFP; 3144 case 99: 3145 // Cast combination can't happen (error in input). This is for all cases 3146 // where the MidTy is not the same for the two cast instructions. 3147 llvm_unreachable("Invalid Cast Combination"); 3148 default: 3149 llvm_unreachable("Error in CastResults table!!!"); 3150 } 3151 } 3152 3153 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty, 3154 const Twine &Name, Instruction *InsertBefore) { 3155 assert(castIsValid(op, S, Ty) && "Invalid cast!"); 3156 // Construct and return the appropriate CastInst subclass 3157 switch (op) { 3158 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore); 3159 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore); 3160 case SExt: return new SExtInst (S, Ty, Name, InsertBefore); 3161 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore); 3162 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore); 3163 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore); 3164 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore); 3165 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore); 3166 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore); 3167 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore); 3168 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore); 3169 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore); 3170 case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertBefore); 3171 default: llvm_unreachable("Invalid opcode provided"); 3172 } 3173 } 3174 3175 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty, 3176 const Twine &Name, BasicBlock *InsertAtEnd) { 3177 assert(castIsValid(op, S, Ty) && "Invalid cast!"); 3178 // Construct and return the appropriate CastInst subclass 3179 switch (op) { 3180 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd); 3181 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd); 3182 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd); 3183 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd); 3184 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd); 3185 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd); 3186 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd); 3187 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd); 3188 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd); 3189 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd); 3190 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd); 3191 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd); 3192 case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertAtEnd); 3193 default: llvm_unreachable("Invalid opcode provided"); 3194 } 3195 } 3196 3197 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty, 3198 const Twine &Name, 3199 Instruction *InsertBefore) { 3200 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 3201 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 3202 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore); 3203 } 3204 3205 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty, 3206 const Twine &Name, 3207 BasicBlock *InsertAtEnd) { 3208 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 3209 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 3210 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd); 3211 } 3212 3213 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty, 3214 const Twine &Name, 3215 Instruction *InsertBefore) { 3216 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 3217 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 3218 return Create(Instruction::SExt, S, Ty, Name, InsertBefore); 3219 } 3220 3221 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty, 3222 const Twine &Name, 3223 BasicBlock *InsertAtEnd) { 3224 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 3225 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 3226 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd); 3227 } 3228 3229 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty, 3230 const Twine &Name, 3231 Instruction *InsertBefore) { 3232 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 3233 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 3234 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore); 3235 } 3236 3237 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty, 3238 const Twine &Name, 3239 BasicBlock *InsertAtEnd) { 3240 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 3241 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 3242 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd); 3243 } 3244 3245 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty, 3246 const Twine &Name, 3247 BasicBlock *InsertAtEnd) { 3248 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); 3249 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) && 3250 "Invalid cast"); 3251 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast"); 3252 assert((!Ty->isVectorTy() || 3253 cast<VectorType>(Ty)->getElementCount() == 3254 cast<VectorType>(S->getType())->getElementCount()) && 3255 "Invalid cast"); 3256 3257 if (Ty->isIntOrIntVectorTy()) 3258 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd); 3259 3260 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertAtEnd); 3261 } 3262 3263 /// Create a BitCast or a PtrToInt cast instruction 3264 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty, 3265 const Twine &Name, 3266 Instruction *InsertBefore) { 3267 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); 3268 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) && 3269 "Invalid cast"); 3270 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast"); 3271 assert((!Ty->isVectorTy() || 3272 cast<VectorType>(Ty)->getElementCount() == 3273 cast<VectorType>(S->getType())->getElementCount()) && 3274 "Invalid cast"); 3275 3276 if (Ty->isIntOrIntVectorTy()) 3277 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore); 3278 3279 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertBefore); 3280 } 3281 3282 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast( 3283 Value *S, Type *Ty, 3284 const Twine &Name, 3285 BasicBlock *InsertAtEnd) { 3286 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); 3287 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast"); 3288 3289 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace()) 3290 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertAtEnd); 3291 3292 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 3293 } 3294 3295 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast( 3296 Value *S, Type *Ty, 3297 const Twine &Name, 3298 Instruction *InsertBefore) { 3299 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); 3300 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast"); 3301 3302 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace()) 3303 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertBefore); 3304 3305 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 3306 } 3307 3308 CastInst *CastInst::CreateBitOrPointerCast(Value *S, Type *Ty, 3309 const Twine &Name, 3310 Instruction *InsertBefore) { 3311 if (S->getType()->isPointerTy() && Ty->isIntegerTy()) 3312 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore); 3313 if (S->getType()->isIntegerTy() && Ty->isPointerTy()) 3314 return Create(Instruction::IntToPtr, S, Ty, Name, InsertBefore); 3315 3316 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 3317 } 3318 3319 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty, 3320 bool isSigned, const Twine &Name, 3321 Instruction *InsertBefore) { 3322 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() && 3323 "Invalid integer cast"); 3324 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 3325 unsigned DstBits = Ty->getScalarSizeInBits(); 3326 Instruction::CastOps opcode = 3327 (SrcBits == DstBits ? Instruction::BitCast : 3328 (SrcBits > DstBits ? Instruction::Trunc : 3329 (isSigned ? Instruction::SExt : Instruction::ZExt))); 3330 return Create(opcode, C, Ty, Name, InsertBefore); 3331 } 3332 3333 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty, 3334 bool isSigned, const Twine &Name, 3335 BasicBlock *InsertAtEnd) { 3336 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() && 3337 "Invalid cast"); 3338 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 3339 unsigned DstBits = Ty->getScalarSizeInBits(); 3340 Instruction::CastOps opcode = 3341 (SrcBits == DstBits ? Instruction::BitCast : 3342 (SrcBits > DstBits ? Instruction::Trunc : 3343 (isSigned ? Instruction::SExt : Instruction::ZExt))); 3344 return Create(opcode, C, Ty, Name, InsertAtEnd); 3345 } 3346 3347 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty, 3348 const Twine &Name, 3349 Instruction *InsertBefore) { 3350 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() && 3351 "Invalid cast"); 3352 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 3353 unsigned DstBits = Ty->getScalarSizeInBits(); 3354 Instruction::CastOps opcode = 3355 (SrcBits == DstBits ? Instruction::BitCast : 3356 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt)); 3357 return Create(opcode, C, Ty, Name, InsertBefore); 3358 } 3359 3360 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty, 3361 const Twine &Name, 3362 BasicBlock *InsertAtEnd) { 3363 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() && 3364 "Invalid cast"); 3365 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 3366 unsigned DstBits = Ty->getScalarSizeInBits(); 3367 Instruction::CastOps opcode = 3368 (SrcBits == DstBits ? Instruction::BitCast : 3369 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt)); 3370 return Create(opcode, C, Ty, Name, InsertAtEnd); 3371 } 3372 3373 bool CastInst::isBitCastable(Type *SrcTy, Type *DestTy) { 3374 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType()) 3375 return false; 3376 3377 if (SrcTy == DestTy) 3378 return true; 3379 3380 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) { 3381 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) { 3382 if (SrcVecTy->getElementCount() == DestVecTy->getElementCount()) { 3383 // An element by element cast. Valid if casting the elements is valid. 3384 SrcTy = SrcVecTy->getElementType(); 3385 DestTy = DestVecTy->getElementType(); 3386 } 3387 } 3388 } 3389 3390 if (PointerType *DestPtrTy = dyn_cast<PointerType>(DestTy)) { 3391 if (PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy)) { 3392 return SrcPtrTy->getAddressSpace() == DestPtrTy->getAddressSpace(); 3393 } 3394 } 3395 3396 TypeSize SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr 3397 TypeSize DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr 3398 3399 // Could still have vectors of pointers if the number of elements doesn't 3400 // match 3401 if (SrcBits.getKnownMinSize() == 0 || DestBits.getKnownMinSize() == 0) 3402 return false; 3403 3404 if (SrcBits != DestBits) 3405 return false; 3406 3407 if (DestTy->isX86_MMXTy() || SrcTy->isX86_MMXTy()) 3408 return false; 3409 3410 return true; 3411 } 3412 3413 bool CastInst::isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy, 3414 const DataLayout &DL) { 3415 // ptrtoint and inttoptr are not allowed on non-integral pointers 3416 if (auto *PtrTy = dyn_cast<PointerType>(SrcTy)) 3417 if (auto *IntTy = dyn_cast<IntegerType>(DestTy)) 3418 return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) && 3419 !DL.isNonIntegralPointerType(PtrTy)); 3420 if (auto *PtrTy = dyn_cast<PointerType>(DestTy)) 3421 if (auto *IntTy = dyn_cast<IntegerType>(SrcTy)) 3422 return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) && 3423 !DL.isNonIntegralPointerType(PtrTy)); 3424 3425 return isBitCastable(SrcTy, DestTy); 3426 } 3427 3428 // Provide a way to get a "cast" where the cast opcode is inferred from the 3429 // types and size of the operand. This, basically, is a parallel of the 3430 // logic in the castIsValid function below. This axiom should hold: 3431 // castIsValid( getCastOpcode(Val, Ty), Val, Ty) 3432 // should not assert in castIsValid. In other words, this produces a "correct" 3433 // casting opcode for the arguments passed to it. 3434 Instruction::CastOps 3435 CastInst::getCastOpcode( 3436 const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) { 3437 Type *SrcTy = Src->getType(); 3438 3439 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() && 3440 "Only first class types are castable!"); 3441 3442 if (SrcTy == DestTy) 3443 return BitCast; 3444 3445 // FIXME: Check address space sizes here 3446 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) 3447 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) 3448 if (SrcVecTy->getElementCount() == DestVecTy->getElementCount()) { 3449 // An element by element cast. Find the appropriate opcode based on the 3450 // element types. 3451 SrcTy = SrcVecTy->getElementType(); 3452 DestTy = DestVecTy->getElementType(); 3453 } 3454 3455 // Get the bit sizes, we'll need these 3456 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr 3457 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr 3458 3459 // Run through the possibilities ... 3460 if (DestTy->isIntegerTy()) { // Casting to integral 3461 if (SrcTy->isIntegerTy()) { // Casting from integral 3462 if (DestBits < SrcBits) 3463 return Trunc; // int -> smaller int 3464 else if (DestBits > SrcBits) { // its an extension 3465 if (SrcIsSigned) 3466 return SExt; // signed -> SEXT 3467 else 3468 return ZExt; // unsigned -> ZEXT 3469 } else { 3470 return BitCast; // Same size, No-op cast 3471 } 3472 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt 3473 if (DestIsSigned) 3474 return FPToSI; // FP -> sint 3475 else 3476 return FPToUI; // FP -> uint 3477 } else if (SrcTy->isVectorTy()) { 3478 assert(DestBits == SrcBits && 3479 "Casting vector to integer of different width"); 3480 return BitCast; // Same size, no-op cast 3481 } else { 3482 assert(SrcTy->isPointerTy() && 3483 "Casting from a value that is not first-class type"); 3484 return PtrToInt; // ptr -> int 3485 } 3486 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt 3487 if (SrcTy->isIntegerTy()) { // Casting from integral 3488 if (SrcIsSigned) 3489 return SIToFP; // sint -> FP 3490 else 3491 return UIToFP; // uint -> FP 3492 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt 3493 if (DestBits < SrcBits) { 3494 return FPTrunc; // FP -> smaller FP 3495 } else if (DestBits > SrcBits) { 3496 return FPExt; // FP -> larger FP 3497 } else { 3498 return BitCast; // same size, no-op cast 3499 } 3500 } else if (SrcTy->isVectorTy()) { 3501 assert(DestBits == SrcBits && 3502 "Casting vector to floating point of different width"); 3503 return BitCast; // same size, no-op cast 3504 } 3505 llvm_unreachable("Casting pointer or non-first class to float"); 3506 } else if (DestTy->isVectorTy()) { 3507 assert(DestBits == SrcBits && 3508 "Illegal cast to vector (wrong type or size)"); 3509 return BitCast; 3510 } else if (DestTy->isPointerTy()) { 3511 if (SrcTy->isPointerTy()) { 3512 if (DestTy->getPointerAddressSpace() != SrcTy->getPointerAddressSpace()) 3513 return AddrSpaceCast; 3514 return BitCast; // ptr -> ptr 3515 } else if (SrcTy->isIntegerTy()) { 3516 return IntToPtr; // int -> ptr 3517 } 3518 llvm_unreachable("Casting pointer to other than pointer or int"); 3519 } else if (DestTy->isX86_MMXTy()) { 3520 if (SrcTy->isVectorTy()) { 3521 assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX"); 3522 return BitCast; // 64-bit vector to MMX 3523 } 3524 llvm_unreachable("Illegal cast to X86_MMX"); 3525 } 3526 llvm_unreachable("Casting to type that is not first-class"); 3527 } 3528 3529 //===----------------------------------------------------------------------===// 3530 // CastInst SubClass Constructors 3531 //===----------------------------------------------------------------------===// 3532 3533 /// Check that the construction parameters for a CastInst are correct. This 3534 /// could be broken out into the separate constructors but it is useful to have 3535 /// it in one place and to eliminate the redundant code for getting the sizes 3536 /// of the types involved. 3537 bool 3538 CastInst::castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy) { 3539 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() || 3540 SrcTy->isAggregateType() || DstTy->isAggregateType()) 3541 return false; 3542 3543 // Get the size of the types in bits, and whether we are dealing 3544 // with vector types, we'll need this later. 3545 bool SrcIsVec = isa<VectorType>(SrcTy); 3546 bool DstIsVec = isa<VectorType>(DstTy); 3547 unsigned SrcScalarBitSize = SrcTy->getScalarSizeInBits(); 3548 unsigned DstScalarBitSize = DstTy->getScalarSizeInBits(); 3549 3550 // If these are vector types, get the lengths of the vectors (using zero for 3551 // scalar types means that checking that vector lengths match also checks that 3552 // scalars are not being converted to vectors or vectors to scalars). 3553 ElementCount SrcEC = SrcIsVec ? cast<VectorType>(SrcTy)->getElementCount() 3554 : ElementCount::getFixed(0); 3555 ElementCount DstEC = DstIsVec ? cast<VectorType>(DstTy)->getElementCount() 3556 : ElementCount::getFixed(0); 3557 3558 // Switch on the opcode provided 3559 switch (op) { 3560 default: return false; // This is an input error 3561 case Instruction::Trunc: 3562 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() && 3563 SrcEC == DstEC && SrcScalarBitSize > DstScalarBitSize; 3564 case Instruction::ZExt: 3565 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() && 3566 SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize; 3567 case Instruction::SExt: 3568 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() && 3569 SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize; 3570 case Instruction::FPTrunc: 3571 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() && 3572 SrcEC == DstEC && SrcScalarBitSize > DstScalarBitSize; 3573 case Instruction::FPExt: 3574 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() && 3575 SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize; 3576 case Instruction::UIToFP: 3577 case Instruction::SIToFP: 3578 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() && 3579 SrcEC == DstEC; 3580 case Instruction::FPToUI: 3581 case Instruction::FPToSI: 3582 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() && 3583 SrcEC == DstEC; 3584 case Instruction::PtrToInt: 3585 if (SrcEC != DstEC) 3586 return false; 3587 return SrcTy->isPtrOrPtrVectorTy() && DstTy->isIntOrIntVectorTy(); 3588 case Instruction::IntToPtr: 3589 if (SrcEC != DstEC) 3590 return false; 3591 return SrcTy->isIntOrIntVectorTy() && DstTy->isPtrOrPtrVectorTy(); 3592 case Instruction::BitCast: { 3593 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType()); 3594 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType()); 3595 3596 // BitCast implies a no-op cast of type only. No bits change. 3597 // However, you can't cast pointers to anything but pointers. 3598 if (!SrcPtrTy != !DstPtrTy) 3599 return false; 3600 3601 // For non-pointer cases, the cast is okay if the source and destination bit 3602 // widths are identical. 3603 if (!SrcPtrTy) 3604 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits(); 3605 3606 // If both are pointers then the address spaces must match. 3607 if (SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace()) 3608 return false; 3609 3610 // A vector of pointers must have the same number of elements. 3611 if (SrcIsVec && DstIsVec) 3612 return SrcEC == DstEC; 3613 if (SrcIsVec) 3614 return SrcEC == ElementCount::getFixed(1); 3615 if (DstIsVec) 3616 return DstEC == ElementCount::getFixed(1); 3617 3618 return true; 3619 } 3620 case Instruction::AddrSpaceCast: { 3621 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType()); 3622 if (!SrcPtrTy) 3623 return false; 3624 3625 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType()); 3626 if (!DstPtrTy) 3627 return false; 3628 3629 if (SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace()) 3630 return false; 3631 3632 return SrcEC == DstEC; 3633 } 3634 } 3635 } 3636 3637 TruncInst::TruncInst( 3638 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3639 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) { 3640 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc"); 3641 } 3642 3643 TruncInst::TruncInst( 3644 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3645 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) { 3646 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc"); 3647 } 3648 3649 ZExtInst::ZExtInst( 3650 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3651 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) { 3652 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt"); 3653 } 3654 3655 ZExtInst::ZExtInst( 3656 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3657 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) { 3658 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt"); 3659 } 3660 SExtInst::SExtInst( 3661 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3662 ) : CastInst(Ty, SExt, S, Name, InsertBefore) { 3663 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt"); 3664 } 3665 3666 SExtInst::SExtInst( 3667 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3668 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) { 3669 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt"); 3670 } 3671 3672 FPTruncInst::FPTruncInst( 3673 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3674 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) { 3675 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc"); 3676 } 3677 3678 FPTruncInst::FPTruncInst( 3679 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3680 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) { 3681 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc"); 3682 } 3683 3684 FPExtInst::FPExtInst( 3685 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3686 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) { 3687 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt"); 3688 } 3689 3690 FPExtInst::FPExtInst( 3691 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3692 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) { 3693 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt"); 3694 } 3695 3696 UIToFPInst::UIToFPInst( 3697 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3698 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) { 3699 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP"); 3700 } 3701 3702 UIToFPInst::UIToFPInst( 3703 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3704 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) { 3705 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP"); 3706 } 3707 3708 SIToFPInst::SIToFPInst( 3709 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3710 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) { 3711 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP"); 3712 } 3713 3714 SIToFPInst::SIToFPInst( 3715 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3716 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) { 3717 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP"); 3718 } 3719 3720 FPToUIInst::FPToUIInst( 3721 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3722 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) { 3723 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI"); 3724 } 3725 3726 FPToUIInst::FPToUIInst( 3727 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3728 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) { 3729 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI"); 3730 } 3731 3732 FPToSIInst::FPToSIInst( 3733 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3734 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) { 3735 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI"); 3736 } 3737 3738 FPToSIInst::FPToSIInst( 3739 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3740 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) { 3741 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI"); 3742 } 3743 3744 PtrToIntInst::PtrToIntInst( 3745 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3746 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) { 3747 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt"); 3748 } 3749 3750 PtrToIntInst::PtrToIntInst( 3751 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3752 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) { 3753 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt"); 3754 } 3755 3756 IntToPtrInst::IntToPtrInst( 3757 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3758 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) { 3759 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr"); 3760 } 3761 3762 IntToPtrInst::IntToPtrInst( 3763 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3764 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) { 3765 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr"); 3766 } 3767 3768 BitCastInst::BitCastInst( 3769 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3770 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) { 3771 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast"); 3772 } 3773 3774 BitCastInst::BitCastInst( 3775 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3776 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) { 3777 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast"); 3778 } 3779 3780 AddrSpaceCastInst::AddrSpaceCastInst( 3781 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3782 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertBefore) { 3783 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast"); 3784 } 3785 3786 AddrSpaceCastInst::AddrSpaceCastInst( 3787 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3788 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertAtEnd) { 3789 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast"); 3790 } 3791 3792 //===----------------------------------------------------------------------===// 3793 // CmpInst Classes 3794 //===----------------------------------------------------------------------===// 3795 3796 CmpInst::CmpInst(Type *ty, OtherOps op, Predicate predicate, Value *LHS, 3797 Value *RHS, const Twine &Name, Instruction *InsertBefore, 3798 Instruction *FlagsSource) 3799 : Instruction(ty, op, 3800 OperandTraits<CmpInst>::op_begin(this), 3801 OperandTraits<CmpInst>::operands(this), 3802 InsertBefore) { 3803 Op<0>() = LHS; 3804 Op<1>() = RHS; 3805 setPredicate((Predicate)predicate); 3806 setName(Name); 3807 if (FlagsSource) 3808 copyIRFlags(FlagsSource); 3809 } 3810 3811 CmpInst::CmpInst(Type *ty, OtherOps op, Predicate predicate, Value *LHS, 3812 Value *RHS, const Twine &Name, BasicBlock *InsertAtEnd) 3813 : Instruction(ty, op, 3814 OperandTraits<CmpInst>::op_begin(this), 3815 OperandTraits<CmpInst>::operands(this), 3816 InsertAtEnd) { 3817 Op<0>() = LHS; 3818 Op<1>() = RHS; 3819 setPredicate((Predicate)predicate); 3820 setName(Name); 3821 } 3822 3823 CmpInst * 3824 CmpInst::Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2, 3825 const Twine &Name, Instruction *InsertBefore) { 3826 if (Op == Instruction::ICmp) { 3827 if (InsertBefore) 3828 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate), 3829 S1, S2, Name); 3830 else 3831 return new ICmpInst(CmpInst::Predicate(predicate), 3832 S1, S2, Name); 3833 } 3834 3835 if (InsertBefore) 3836 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate), 3837 S1, S2, Name); 3838 else 3839 return new FCmpInst(CmpInst::Predicate(predicate), 3840 S1, S2, Name); 3841 } 3842 3843 CmpInst * 3844 CmpInst::Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2, 3845 const Twine &Name, BasicBlock *InsertAtEnd) { 3846 if (Op == Instruction::ICmp) { 3847 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate), 3848 S1, S2, Name); 3849 } 3850 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate), 3851 S1, S2, Name); 3852 } 3853 3854 void CmpInst::swapOperands() { 3855 if (ICmpInst *IC = dyn_cast<ICmpInst>(this)) 3856 IC->swapOperands(); 3857 else 3858 cast<FCmpInst>(this)->swapOperands(); 3859 } 3860 3861 bool CmpInst::isCommutative() const { 3862 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this)) 3863 return IC->isCommutative(); 3864 return cast<FCmpInst>(this)->isCommutative(); 3865 } 3866 3867 bool CmpInst::isEquality(Predicate P) { 3868 if (ICmpInst::isIntPredicate(P)) 3869 return ICmpInst::isEquality(P); 3870 if (FCmpInst::isFPPredicate(P)) 3871 return FCmpInst::isEquality(P); 3872 llvm_unreachable("Unsupported predicate kind"); 3873 } 3874 3875 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) { 3876 switch (pred) { 3877 default: llvm_unreachable("Unknown cmp predicate!"); 3878 case ICMP_EQ: return ICMP_NE; 3879 case ICMP_NE: return ICMP_EQ; 3880 case ICMP_UGT: return ICMP_ULE; 3881 case ICMP_ULT: return ICMP_UGE; 3882 case ICMP_UGE: return ICMP_ULT; 3883 case ICMP_ULE: return ICMP_UGT; 3884 case ICMP_SGT: return ICMP_SLE; 3885 case ICMP_SLT: return ICMP_SGE; 3886 case ICMP_SGE: return ICMP_SLT; 3887 case ICMP_SLE: return ICMP_SGT; 3888 3889 case FCMP_OEQ: return FCMP_UNE; 3890 case FCMP_ONE: return FCMP_UEQ; 3891 case FCMP_OGT: return FCMP_ULE; 3892 case FCMP_OLT: return FCMP_UGE; 3893 case FCMP_OGE: return FCMP_ULT; 3894 case FCMP_OLE: return FCMP_UGT; 3895 case FCMP_UEQ: return FCMP_ONE; 3896 case FCMP_UNE: return FCMP_OEQ; 3897 case FCMP_UGT: return FCMP_OLE; 3898 case FCMP_ULT: return FCMP_OGE; 3899 case FCMP_UGE: return FCMP_OLT; 3900 case FCMP_ULE: return FCMP_OGT; 3901 case FCMP_ORD: return FCMP_UNO; 3902 case FCMP_UNO: return FCMP_ORD; 3903 case FCMP_TRUE: return FCMP_FALSE; 3904 case FCMP_FALSE: return FCMP_TRUE; 3905 } 3906 } 3907 3908 StringRef CmpInst::getPredicateName(Predicate Pred) { 3909 switch (Pred) { 3910 default: return "unknown"; 3911 case FCmpInst::FCMP_FALSE: return "false"; 3912 case FCmpInst::FCMP_OEQ: return "oeq"; 3913 case FCmpInst::FCMP_OGT: return "ogt"; 3914 case FCmpInst::FCMP_OGE: return "oge"; 3915 case FCmpInst::FCMP_OLT: return "olt"; 3916 case FCmpInst::FCMP_OLE: return "ole"; 3917 case FCmpInst::FCMP_ONE: return "one"; 3918 case FCmpInst::FCMP_ORD: return "ord"; 3919 case FCmpInst::FCMP_UNO: return "uno"; 3920 case FCmpInst::FCMP_UEQ: return "ueq"; 3921 case FCmpInst::FCMP_UGT: return "ugt"; 3922 case FCmpInst::FCMP_UGE: return "uge"; 3923 case FCmpInst::FCMP_ULT: return "ult"; 3924 case FCmpInst::FCMP_ULE: return "ule"; 3925 case FCmpInst::FCMP_UNE: return "une"; 3926 case FCmpInst::FCMP_TRUE: return "true"; 3927 case ICmpInst::ICMP_EQ: return "eq"; 3928 case ICmpInst::ICMP_NE: return "ne"; 3929 case ICmpInst::ICMP_SGT: return "sgt"; 3930 case ICmpInst::ICMP_SGE: return "sge"; 3931 case ICmpInst::ICMP_SLT: return "slt"; 3932 case ICmpInst::ICMP_SLE: return "sle"; 3933 case ICmpInst::ICMP_UGT: return "ugt"; 3934 case ICmpInst::ICMP_UGE: return "uge"; 3935 case ICmpInst::ICMP_ULT: return "ult"; 3936 case ICmpInst::ICMP_ULE: return "ule"; 3937 } 3938 } 3939 3940 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) { 3941 switch (pred) { 3942 default: llvm_unreachable("Unknown icmp predicate!"); 3943 case ICMP_EQ: case ICMP_NE: 3944 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE: 3945 return pred; 3946 case ICMP_UGT: return ICMP_SGT; 3947 case ICMP_ULT: return ICMP_SLT; 3948 case ICMP_UGE: return ICMP_SGE; 3949 case ICMP_ULE: return ICMP_SLE; 3950 } 3951 } 3952 3953 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) { 3954 switch (pred) { 3955 default: llvm_unreachable("Unknown icmp predicate!"); 3956 case ICMP_EQ: case ICMP_NE: 3957 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE: 3958 return pred; 3959 case ICMP_SGT: return ICMP_UGT; 3960 case ICMP_SLT: return ICMP_ULT; 3961 case ICMP_SGE: return ICMP_UGE; 3962 case ICMP_SLE: return ICMP_ULE; 3963 } 3964 } 3965 3966 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) { 3967 switch (pred) { 3968 default: llvm_unreachable("Unknown cmp predicate!"); 3969 case ICMP_EQ: case ICMP_NE: 3970 return pred; 3971 case ICMP_SGT: return ICMP_SLT; 3972 case ICMP_SLT: return ICMP_SGT; 3973 case ICMP_SGE: return ICMP_SLE; 3974 case ICMP_SLE: return ICMP_SGE; 3975 case ICMP_UGT: return ICMP_ULT; 3976 case ICMP_ULT: return ICMP_UGT; 3977 case ICMP_UGE: return ICMP_ULE; 3978 case ICMP_ULE: return ICMP_UGE; 3979 3980 case FCMP_FALSE: case FCMP_TRUE: 3981 case FCMP_OEQ: case FCMP_ONE: 3982 case FCMP_UEQ: case FCMP_UNE: 3983 case FCMP_ORD: case FCMP_UNO: 3984 return pred; 3985 case FCMP_OGT: return FCMP_OLT; 3986 case FCMP_OLT: return FCMP_OGT; 3987 case FCMP_OGE: return FCMP_OLE; 3988 case FCMP_OLE: return FCMP_OGE; 3989 case FCMP_UGT: return FCMP_ULT; 3990 case FCMP_ULT: return FCMP_UGT; 3991 case FCMP_UGE: return FCMP_ULE; 3992 case FCMP_ULE: return FCMP_UGE; 3993 } 3994 } 3995 3996 bool CmpInst::isNonStrictPredicate(Predicate pred) { 3997 switch (pred) { 3998 case ICMP_SGE: 3999 case ICMP_SLE: 4000 case ICMP_UGE: 4001 case ICMP_ULE: 4002 case FCMP_OGE: 4003 case FCMP_OLE: 4004 case FCMP_UGE: 4005 case FCMP_ULE: 4006 return true; 4007 default: 4008 return false; 4009 } 4010 } 4011 4012 bool CmpInst::isStrictPredicate(Predicate pred) { 4013 switch (pred) { 4014 case ICMP_SGT: 4015 case ICMP_SLT: 4016 case ICMP_UGT: 4017 case ICMP_ULT: 4018 case FCMP_OGT: 4019 case FCMP_OLT: 4020 case FCMP_UGT: 4021 case FCMP_ULT: 4022 return true; 4023 default: 4024 return false; 4025 } 4026 } 4027 4028 CmpInst::Predicate CmpInst::getStrictPredicate(Predicate pred) { 4029 switch (pred) { 4030 case ICMP_SGE: 4031 return ICMP_SGT; 4032 case ICMP_SLE: 4033 return ICMP_SLT; 4034 case ICMP_UGE: 4035 return ICMP_UGT; 4036 case ICMP_ULE: 4037 return ICMP_ULT; 4038 case FCMP_OGE: 4039 return FCMP_OGT; 4040 case FCMP_OLE: 4041 return FCMP_OLT; 4042 case FCMP_UGE: 4043 return FCMP_UGT; 4044 case FCMP_ULE: 4045 return FCMP_ULT; 4046 default: 4047 return pred; 4048 } 4049 } 4050 4051 CmpInst::Predicate CmpInst::getNonStrictPredicate(Predicate pred) { 4052 switch (pred) { 4053 case ICMP_SGT: 4054 return ICMP_SGE; 4055 case ICMP_SLT: 4056 return ICMP_SLE; 4057 case ICMP_UGT: 4058 return ICMP_UGE; 4059 case ICMP_ULT: 4060 return ICMP_ULE; 4061 case FCMP_OGT: 4062 return FCMP_OGE; 4063 case FCMP_OLT: 4064 return FCMP_OLE; 4065 case FCMP_UGT: 4066 return FCMP_UGE; 4067 case FCMP_ULT: 4068 return FCMP_ULE; 4069 default: 4070 return pred; 4071 } 4072 } 4073 4074 CmpInst::Predicate CmpInst::getFlippedStrictnessPredicate(Predicate pred) { 4075 assert(CmpInst::isRelational(pred) && "Call only with relational predicate!"); 4076 4077 if (isStrictPredicate(pred)) 4078 return getNonStrictPredicate(pred); 4079 if (isNonStrictPredicate(pred)) 4080 return getStrictPredicate(pred); 4081 4082 llvm_unreachable("Unknown predicate!"); 4083 } 4084 4085 CmpInst::Predicate CmpInst::getSignedPredicate(Predicate pred) { 4086 assert(CmpInst::isUnsigned(pred) && "Call only with unsigned predicates!"); 4087 4088 switch (pred) { 4089 default: 4090 llvm_unreachable("Unknown predicate!"); 4091 case CmpInst::ICMP_ULT: 4092 return CmpInst::ICMP_SLT; 4093 case CmpInst::ICMP_ULE: 4094 return CmpInst::ICMP_SLE; 4095 case CmpInst::ICMP_UGT: 4096 return CmpInst::ICMP_SGT; 4097 case CmpInst::ICMP_UGE: 4098 return CmpInst::ICMP_SGE; 4099 } 4100 } 4101 4102 CmpInst::Predicate CmpInst::getUnsignedPredicate(Predicate pred) { 4103 assert(CmpInst::isSigned(pred) && "Call only with signed predicates!"); 4104 4105 switch (pred) { 4106 default: 4107 llvm_unreachable("Unknown predicate!"); 4108 case CmpInst::ICMP_SLT: 4109 return CmpInst::ICMP_ULT; 4110 case CmpInst::ICMP_SLE: 4111 return CmpInst::ICMP_ULE; 4112 case CmpInst::ICMP_SGT: 4113 return CmpInst::ICMP_UGT; 4114 case CmpInst::ICMP_SGE: 4115 return CmpInst::ICMP_UGE; 4116 } 4117 } 4118 4119 bool CmpInst::isUnsigned(Predicate predicate) { 4120 switch (predicate) { 4121 default: return false; 4122 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT: 4123 case ICmpInst::ICMP_UGE: return true; 4124 } 4125 } 4126 4127 bool CmpInst::isSigned(Predicate predicate) { 4128 switch (predicate) { 4129 default: return false; 4130 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT: 4131 case ICmpInst::ICMP_SGE: return true; 4132 } 4133 } 4134 4135 bool ICmpInst::compare(const APInt &LHS, const APInt &RHS, 4136 ICmpInst::Predicate Pred) { 4137 assert(ICmpInst::isIntPredicate(Pred) && "Only for integer predicates!"); 4138 switch (Pred) { 4139 case ICmpInst::Predicate::ICMP_EQ: 4140 return LHS.eq(RHS); 4141 case ICmpInst::Predicate::ICMP_NE: 4142 return LHS.ne(RHS); 4143 case ICmpInst::Predicate::ICMP_UGT: 4144 return LHS.ugt(RHS); 4145 case ICmpInst::Predicate::ICMP_UGE: 4146 return LHS.uge(RHS); 4147 case ICmpInst::Predicate::ICMP_ULT: 4148 return LHS.ult(RHS); 4149 case ICmpInst::Predicate::ICMP_ULE: 4150 return LHS.ule(RHS); 4151 case ICmpInst::Predicate::ICMP_SGT: 4152 return LHS.sgt(RHS); 4153 case ICmpInst::Predicate::ICMP_SGE: 4154 return LHS.sge(RHS); 4155 case ICmpInst::Predicate::ICMP_SLT: 4156 return LHS.slt(RHS); 4157 case ICmpInst::Predicate::ICMP_SLE: 4158 return LHS.sle(RHS); 4159 default: 4160 llvm_unreachable("Unexpected non-integer predicate."); 4161 }; 4162 } 4163 4164 bool FCmpInst::compare(const APFloat &LHS, const APFloat &RHS, 4165 FCmpInst::Predicate Pred) { 4166 APFloat::cmpResult R = LHS.compare(RHS); 4167 switch (Pred) { 4168 default: 4169 llvm_unreachable("Invalid FCmp Predicate"); 4170 case FCmpInst::FCMP_FALSE: 4171 return false; 4172 case FCmpInst::FCMP_TRUE: 4173 return true; 4174 case FCmpInst::FCMP_UNO: 4175 return R == APFloat::cmpUnordered; 4176 case FCmpInst::FCMP_ORD: 4177 return R != APFloat::cmpUnordered; 4178 case FCmpInst::FCMP_UEQ: 4179 return R == APFloat::cmpUnordered || R == APFloat::cmpEqual; 4180 case FCmpInst::FCMP_OEQ: 4181 return R == APFloat::cmpEqual; 4182 case FCmpInst::FCMP_UNE: 4183 return R != APFloat::cmpEqual; 4184 case FCmpInst::FCMP_ONE: 4185 return R == APFloat::cmpLessThan || R == APFloat::cmpGreaterThan; 4186 case FCmpInst::FCMP_ULT: 4187 return R == APFloat::cmpUnordered || R == APFloat::cmpLessThan; 4188 case FCmpInst::FCMP_OLT: 4189 return R == APFloat::cmpLessThan; 4190 case FCmpInst::FCMP_UGT: 4191 return R == APFloat::cmpUnordered || R == APFloat::cmpGreaterThan; 4192 case FCmpInst::FCMP_OGT: 4193 return R == APFloat::cmpGreaterThan; 4194 case FCmpInst::FCMP_ULE: 4195 return R != APFloat::cmpGreaterThan; 4196 case FCmpInst::FCMP_OLE: 4197 return R == APFloat::cmpLessThan || R == APFloat::cmpEqual; 4198 case FCmpInst::FCMP_UGE: 4199 return R != APFloat::cmpLessThan; 4200 case FCmpInst::FCMP_OGE: 4201 return R == APFloat::cmpGreaterThan || R == APFloat::cmpEqual; 4202 } 4203 } 4204 4205 CmpInst::Predicate CmpInst::getFlippedSignednessPredicate(Predicate pred) { 4206 assert(CmpInst::isRelational(pred) && 4207 "Call only with non-equality predicates!"); 4208 4209 if (isSigned(pred)) 4210 return getUnsignedPredicate(pred); 4211 if (isUnsigned(pred)) 4212 return getSignedPredicate(pred); 4213 4214 llvm_unreachable("Unknown predicate!"); 4215 } 4216 4217 bool CmpInst::isOrdered(Predicate predicate) { 4218 switch (predicate) { 4219 default: return false; 4220 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT: 4221 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE: 4222 case FCmpInst::FCMP_ORD: return true; 4223 } 4224 } 4225 4226 bool CmpInst::isUnordered(Predicate predicate) { 4227 switch (predicate) { 4228 default: return false; 4229 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT: 4230 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE: 4231 case FCmpInst::FCMP_UNO: return true; 4232 } 4233 } 4234 4235 bool CmpInst::isTrueWhenEqual(Predicate predicate) { 4236 switch(predicate) { 4237 default: return false; 4238 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE: 4239 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true; 4240 } 4241 } 4242 4243 bool CmpInst::isFalseWhenEqual(Predicate predicate) { 4244 switch(predicate) { 4245 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT: 4246 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true; 4247 default: return false; 4248 } 4249 } 4250 4251 bool CmpInst::isImpliedTrueByMatchingCmp(Predicate Pred1, Predicate Pred2) { 4252 // If the predicates match, then we know the first condition implies the 4253 // second is true. 4254 if (Pred1 == Pred2) 4255 return true; 4256 4257 switch (Pred1) { 4258 default: 4259 break; 4260 case ICMP_EQ: 4261 // A == B implies A >=u B, A <=u B, A >=s B, and A <=s B are true. 4262 return Pred2 == ICMP_UGE || Pred2 == ICMP_ULE || Pred2 == ICMP_SGE || 4263 Pred2 == ICMP_SLE; 4264 case ICMP_UGT: // A >u B implies A != B and A >=u B are true. 4265 return Pred2 == ICMP_NE || Pred2 == ICMP_UGE; 4266 case ICMP_ULT: // A <u B implies A != B and A <=u B are true. 4267 return Pred2 == ICMP_NE || Pred2 == ICMP_ULE; 4268 case ICMP_SGT: // A >s B implies A != B and A >=s B are true. 4269 return Pred2 == ICMP_NE || Pred2 == ICMP_SGE; 4270 case ICMP_SLT: // A <s B implies A != B and A <=s B are true. 4271 return Pred2 == ICMP_NE || Pred2 == ICMP_SLE; 4272 } 4273 return false; 4274 } 4275 4276 bool CmpInst::isImpliedFalseByMatchingCmp(Predicate Pred1, Predicate Pred2) { 4277 return isImpliedTrueByMatchingCmp(Pred1, getInversePredicate(Pred2)); 4278 } 4279 4280 //===----------------------------------------------------------------------===// 4281 // SwitchInst Implementation 4282 //===----------------------------------------------------------------------===// 4283 4284 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) { 4285 assert(Value && Default && NumReserved); 4286 ReservedSpace = NumReserved; 4287 setNumHungOffUseOperands(2); 4288 allocHungoffUses(ReservedSpace); 4289 4290 Op<0>() = Value; 4291 Op<1>() = Default; 4292 } 4293 4294 /// SwitchInst ctor - Create a new switch instruction, specifying a value to 4295 /// switch on and a default destination. The number of additional cases can 4296 /// be specified here to make memory allocation more efficient. This 4297 /// constructor can also autoinsert before another instruction. 4298 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases, 4299 Instruction *InsertBefore) 4300 : Instruction(Type::getVoidTy(Value->getContext()), Instruction::Switch, 4301 nullptr, 0, InsertBefore) { 4302 init(Value, Default, 2+NumCases*2); 4303 } 4304 4305 /// SwitchInst ctor - Create a new switch instruction, specifying a value to 4306 /// switch on and a default destination. The number of additional cases can 4307 /// be specified here to make memory allocation more efficient. This 4308 /// constructor also autoinserts at the end of the specified BasicBlock. 4309 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases, 4310 BasicBlock *InsertAtEnd) 4311 : Instruction(Type::getVoidTy(Value->getContext()), Instruction::Switch, 4312 nullptr, 0, InsertAtEnd) { 4313 init(Value, Default, 2+NumCases*2); 4314 } 4315 4316 SwitchInst::SwitchInst(const SwitchInst &SI) 4317 : Instruction(SI.getType(), Instruction::Switch, nullptr, 0) { 4318 init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands()); 4319 setNumHungOffUseOperands(SI.getNumOperands()); 4320 Use *OL = getOperandList(); 4321 const Use *InOL = SI.getOperandList(); 4322 for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) { 4323 OL[i] = InOL[i]; 4324 OL[i+1] = InOL[i+1]; 4325 } 4326 SubclassOptionalData = SI.SubclassOptionalData; 4327 } 4328 4329 /// addCase - Add an entry to the switch instruction... 4330 /// 4331 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) { 4332 unsigned NewCaseIdx = getNumCases(); 4333 unsigned OpNo = getNumOperands(); 4334 if (OpNo+2 > ReservedSpace) 4335 growOperands(); // Get more space! 4336 // Initialize some new operands. 4337 assert(OpNo+1 < ReservedSpace && "Growing didn't work!"); 4338 setNumHungOffUseOperands(OpNo+2); 4339 CaseHandle Case(this, NewCaseIdx); 4340 Case.setValue(OnVal); 4341 Case.setSuccessor(Dest); 4342 } 4343 4344 /// removeCase - This method removes the specified case and its successor 4345 /// from the switch instruction. 4346 SwitchInst::CaseIt SwitchInst::removeCase(CaseIt I) { 4347 unsigned idx = I->getCaseIndex(); 4348 4349 assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!"); 4350 4351 unsigned NumOps = getNumOperands(); 4352 Use *OL = getOperandList(); 4353 4354 // Overwrite this case with the end of the list. 4355 if (2 + (idx + 1) * 2 != NumOps) { 4356 OL[2 + idx * 2] = OL[NumOps - 2]; 4357 OL[2 + idx * 2 + 1] = OL[NumOps - 1]; 4358 } 4359 4360 // Nuke the last value. 4361 OL[NumOps-2].set(nullptr); 4362 OL[NumOps-2+1].set(nullptr); 4363 setNumHungOffUseOperands(NumOps-2); 4364 4365 return CaseIt(this, idx); 4366 } 4367 4368 /// growOperands - grow operands - This grows the operand list in response 4369 /// to a push_back style of operation. This grows the number of ops by 3 times. 4370 /// 4371 void SwitchInst::growOperands() { 4372 unsigned e = getNumOperands(); 4373 unsigned NumOps = e*3; 4374 4375 ReservedSpace = NumOps; 4376 growHungoffUses(ReservedSpace); 4377 } 4378 4379 MDNode * 4380 SwitchInstProfUpdateWrapper::getProfBranchWeightsMD(const SwitchInst &SI) { 4381 if (MDNode *ProfileData = SI.getMetadata(LLVMContext::MD_prof)) 4382 if (auto *MDName = dyn_cast<MDString>(ProfileData->getOperand(0))) 4383 if (MDName->getString() == "branch_weights") 4384 return ProfileData; 4385 return nullptr; 4386 } 4387 4388 MDNode *SwitchInstProfUpdateWrapper::buildProfBranchWeightsMD() { 4389 assert(Changed && "called only if metadata has changed"); 4390 4391 if (!Weights) 4392 return nullptr; 4393 4394 assert(SI.getNumSuccessors() == Weights->size() && 4395 "num of prof branch_weights must accord with num of successors"); 4396 4397 bool AllZeroes = 4398 all_of(Weights.getValue(), [](uint32_t W) { return W == 0; }); 4399 4400 if (AllZeroes || Weights.getValue().size() < 2) 4401 return nullptr; 4402 4403 return MDBuilder(SI.getParent()->getContext()).createBranchWeights(*Weights); 4404 } 4405 4406 void SwitchInstProfUpdateWrapper::init() { 4407 MDNode *ProfileData = getProfBranchWeightsMD(SI); 4408 if (!ProfileData) 4409 return; 4410 4411 if (ProfileData->getNumOperands() != SI.getNumSuccessors() + 1) { 4412 llvm_unreachable("number of prof branch_weights metadata operands does " 4413 "not correspond to number of succesors"); 4414 } 4415 4416 SmallVector<uint32_t, 8> Weights; 4417 for (unsigned CI = 1, CE = SI.getNumSuccessors(); CI <= CE; ++CI) { 4418 ConstantInt *C = mdconst::extract<ConstantInt>(ProfileData->getOperand(CI)); 4419 uint32_t CW = C->getValue().getZExtValue(); 4420 Weights.push_back(CW); 4421 } 4422 this->Weights = std::move(Weights); 4423 } 4424 4425 SwitchInst::CaseIt 4426 SwitchInstProfUpdateWrapper::removeCase(SwitchInst::CaseIt I) { 4427 if (Weights) { 4428 assert(SI.getNumSuccessors() == Weights->size() && 4429 "num of prof branch_weights must accord with num of successors"); 4430 Changed = true; 4431 // Copy the last case to the place of the removed one and shrink. 4432 // This is tightly coupled with the way SwitchInst::removeCase() removes 4433 // the cases in SwitchInst::removeCase(CaseIt). 4434 Weights.getValue()[I->getCaseIndex() + 1] = Weights.getValue().back(); 4435 Weights.getValue().pop_back(); 4436 } 4437 return SI.removeCase(I); 4438 } 4439 4440 void SwitchInstProfUpdateWrapper::addCase( 4441 ConstantInt *OnVal, BasicBlock *Dest, 4442 SwitchInstProfUpdateWrapper::CaseWeightOpt W) { 4443 SI.addCase(OnVal, Dest); 4444 4445 if (!Weights && W && *W) { 4446 Changed = true; 4447 Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0); 4448 Weights.getValue()[SI.getNumSuccessors() - 1] = *W; 4449 } else if (Weights) { 4450 Changed = true; 4451 Weights.getValue().push_back(W.getValueOr(0)); 4452 } 4453 if (Weights) 4454 assert(SI.getNumSuccessors() == Weights->size() && 4455 "num of prof branch_weights must accord with num of successors"); 4456 } 4457 4458 SymbolTableList<Instruction>::iterator 4459 SwitchInstProfUpdateWrapper::eraseFromParent() { 4460 // Instruction is erased. Mark as unchanged to not touch it in the destructor. 4461 Changed = false; 4462 if (Weights) 4463 Weights->resize(0); 4464 return SI.eraseFromParent(); 4465 } 4466 4467 SwitchInstProfUpdateWrapper::CaseWeightOpt 4468 SwitchInstProfUpdateWrapper::getSuccessorWeight(unsigned idx) { 4469 if (!Weights) 4470 return None; 4471 return Weights.getValue()[idx]; 4472 } 4473 4474 void SwitchInstProfUpdateWrapper::setSuccessorWeight( 4475 unsigned idx, SwitchInstProfUpdateWrapper::CaseWeightOpt W) { 4476 if (!W) 4477 return; 4478 4479 if (!Weights && *W) 4480 Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0); 4481 4482 if (Weights) { 4483 auto &OldW = Weights.getValue()[idx]; 4484 if (*W != OldW) { 4485 Changed = true; 4486 OldW = *W; 4487 } 4488 } 4489 } 4490 4491 SwitchInstProfUpdateWrapper::CaseWeightOpt 4492 SwitchInstProfUpdateWrapper::getSuccessorWeight(const SwitchInst &SI, 4493 unsigned idx) { 4494 if (MDNode *ProfileData = getProfBranchWeightsMD(SI)) 4495 if (ProfileData->getNumOperands() == SI.getNumSuccessors() + 1) 4496 return mdconst::extract<ConstantInt>(ProfileData->getOperand(idx + 1)) 4497 ->getValue() 4498 .getZExtValue(); 4499 4500 return None; 4501 } 4502 4503 //===----------------------------------------------------------------------===// 4504 // IndirectBrInst Implementation 4505 //===----------------------------------------------------------------------===// 4506 4507 void IndirectBrInst::init(Value *Address, unsigned NumDests) { 4508 assert(Address && Address->getType()->isPointerTy() && 4509 "Address of indirectbr must be a pointer"); 4510 ReservedSpace = 1+NumDests; 4511 setNumHungOffUseOperands(1); 4512 allocHungoffUses(ReservedSpace); 4513 4514 Op<0>() = Address; 4515 } 4516 4517 4518 /// growOperands - grow operands - This grows the operand list in response 4519 /// to a push_back style of operation. This grows the number of ops by 2 times. 4520 /// 4521 void IndirectBrInst::growOperands() { 4522 unsigned e = getNumOperands(); 4523 unsigned NumOps = e*2; 4524 4525 ReservedSpace = NumOps; 4526 growHungoffUses(ReservedSpace); 4527 } 4528 4529 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases, 4530 Instruction *InsertBefore) 4531 : Instruction(Type::getVoidTy(Address->getContext()), 4532 Instruction::IndirectBr, nullptr, 0, InsertBefore) { 4533 init(Address, NumCases); 4534 } 4535 4536 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases, 4537 BasicBlock *InsertAtEnd) 4538 : Instruction(Type::getVoidTy(Address->getContext()), 4539 Instruction::IndirectBr, nullptr, 0, InsertAtEnd) { 4540 init(Address, NumCases); 4541 } 4542 4543 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI) 4544 : Instruction(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr, 4545 nullptr, IBI.getNumOperands()) { 4546 allocHungoffUses(IBI.getNumOperands()); 4547 Use *OL = getOperandList(); 4548 const Use *InOL = IBI.getOperandList(); 4549 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i) 4550 OL[i] = InOL[i]; 4551 SubclassOptionalData = IBI.SubclassOptionalData; 4552 } 4553 4554 /// addDestination - Add a destination. 4555 /// 4556 void IndirectBrInst::addDestination(BasicBlock *DestBB) { 4557 unsigned OpNo = getNumOperands(); 4558 if (OpNo+1 > ReservedSpace) 4559 growOperands(); // Get more space! 4560 // Initialize some new operands. 4561 assert(OpNo < ReservedSpace && "Growing didn't work!"); 4562 setNumHungOffUseOperands(OpNo+1); 4563 getOperandList()[OpNo] = DestBB; 4564 } 4565 4566 /// removeDestination - This method removes the specified successor from the 4567 /// indirectbr instruction. 4568 void IndirectBrInst::removeDestination(unsigned idx) { 4569 assert(idx < getNumOperands()-1 && "Successor index out of range!"); 4570 4571 unsigned NumOps = getNumOperands(); 4572 Use *OL = getOperandList(); 4573 4574 // Replace this value with the last one. 4575 OL[idx+1] = OL[NumOps-1]; 4576 4577 // Nuke the last value. 4578 OL[NumOps-1].set(nullptr); 4579 setNumHungOffUseOperands(NumOps-1); 4580 } 4581 4582 //===----------------------------------------------------------------------===// 4583 // FreezeInst Implementation 4584 //===----------------------------------------------------------------------===// 4585 4586 FreezeInst::FreezeInst(Value *S, 4587 const Twine &Name, Instruction *InsertBefore) 4588 : UnaryInstruction(S->getType(), Freeze, S, InsertBefore) { 4589 setName(Name); 4590 } 4591 4592 FreezeInst::FreezeInst(Value *S, 4593 const Twine &Name, BasicBlock *InsertAtEnd) 4594 : UnaryInstruction(S->getType(), Freeze, S, InsertAtEnd) { 4595 setName(Name); 4596 } 4597 4598 //===----------------------------------------------------------------------===// 4599 // cloneImpl() implementations 4600 //===----------------------------------------------------------------------===// 4601 4602 // Define these methods here so vtables don't get emitted into every translation 4603 // unit that uses these classes. 4604 4605 GetElementPtrInst *GetElementPtrInst::cloneImpl() const { 4606 return new (getNumOperands()) GetElementPtrInst(*this); 4607 } 4608 4609 UnaryOperator *UnaryOperator::cloneImpl() const { 4610 return Create(getOpcode(), Op<0>()); 4611 } 4612 4613 BinaryOperator *BinaryOperator::cloneImpl() const { 4614 return Create(getOpcode(), Op<0>(), Op<1>()); 4615 } 4616 4617 FCmpInst *FCmpInst::cloneImpl() const { 4618 return new FCmpInst(getPredicate(), Op<0>(), Op<1>()); 4619 } 4620 4621 ICmpInst *ICmpInst::cloneImpl() const { 4622 return new ICmpInst(getPredicate(), Op<0>(), Op<1>()); 4623 } 4624 4625 ExtractValueInst *ExtractValueInst::cloneImpl() const { 4626 return new ExtractValueInst(*this); 4627 } 4628 4629 InsertValueInst *InsertValueInst::cloneImpl() const { 4630 return new InsertValueInst(*this); 4631 } 4632 4633 AllocaInst *AllocaInst::cloneImpl() const { 4634 AllocaInst *Result = 4635 new AllocaInst(getAllocatedType(), getType()->getAddressSpace(), 4636 getOperand(0), getAlign()); 4637 Result->setUsedWithInAlloca(isUsedWithInAlloca()); 4638 Result->setSwiftError(isSwiftError()); 4639 return Result; 4640 } 4641 4642 LoadInst *LoadInst::cloneImpl() const { 4643 return new LoadInst(getType(), getOperand(0), Twine(), isVolatile(), 4644 getAlign(), getOrdering(), getSyncScopeID()); 4645 } 4646 4647 StoreInst *StoreInst::cloneImpl() const { 4648 return new StoreInst(getOperand(0), getOperand(1), isVolatile(), getAlign(), 4649 getOrdering(), getSyncScopeID()); 4650 } 4651 4652 AtomicCmpXchgInst *AtomicCmpXchgInst::cloneImpl() const { 4653 AtomicCmpXchgInst *Result = new AtomicCmpXchgInst( 4654 getOperand(0), getOperand(1), getOperand(2), getAlign(), 4655 getSuccessOrdering(), getFailureOrdering(), getSyncScopeID()); 4656 Result->setVolatile(isVolatile()); 4657 Result->setWeak(isWeak()); 4658 return Result; 4659 } 4660 4661 AtomicRMWInst *AtomicRMWInst::cloneImpl() const { 4662 AtomicRMWInst *Result = 4663 new AtomicRMWInst(getOperation(), getOperand(0), getOperand(1), 4664 getAlign(), getOrdering(), getSyncScopeID()); 4665 Result->setVolatile(isVolatile()); 4666 return Result; 4667 } 4668 4669 FenceInst *FenceInst::cloneImpl() const { 4670 return new FenceInst(getContext(), getOrdering(), getSyncScopeID()); 4671 } 4672 4673 TruncInst *TruncInst::cloneImpl() const { 4674 return new TruncInst(getOperand(0), getType()); 4675 } 4676 4677 ZExtInst *ZExtInst::cloneImpl() const { 4678 return new ZExtInst(getOperand(0), getType()); 4679 } 4680 4681 SExtInst *SExtInst::cloneImpl() const { 4682 return new SExtInst(getOperand(0), getType()); 4683 } 4684 4685 FPTruncInst *FPTruncInst::cloneImpl() const { 4686 return new FPTruncInst(getOperand(0), getType()); 4687 } 4688 4689 FPExtInst *FPExtInst::cloneImpl() const { 4690 return new FPExtInst(getOperand(0), getType()); 4691 } 4692 4693 UIToFPInst *UIToFPInst::cloneImpl() const { 4694 return new UIToFPInst(getOperand(0), getType()); 4695 } 4696 4697 SIToFPInst *SIToFPInst::cloneImpl() const { 4698 return new SIToFPInst(getOperand(0), getType()); 4699 } 4700 4701 FPToUIInst *FPToUIInst::cloneImpl() const { 4702 return new FPToUIInst(getOperand(0), getType()); 4703 } 4704 4705 FPToSIInst *FPToSIInst::cloneImpl() const { 4706 return new FPToSIInst(getOperand(0), getType()); 4707 } 4708 4709 PtrToIntInst *PtrToIntInst::cloneImpl() const { 4710 return new PtrToIntInst(getOperand(0), getType()); 4711 } 4712 4713 IntToPtrInst *IntToPtrInst::cloneImpl() const { 4714 return new IntToPtrInst(getOperand(0), getType()); 4715 } 4716 4717 BitCastInst *BitCastInst::cloneImpl() const { 4718 return new BitCastInst(getOperand(0), getType()); 4719 } 4720 4721 AddrSpaceCastInst *AddrSpaceCastInst::cloneImpl() const { 4722 return new AddrSpaceCastInst(getOperand(0), getType()); 4723 } 4724 4725 CallInst *CallInst::cloneImpl() const { 4726 if (hasOperandBundles()) { 4727 unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo); 4728 return new(getNumOperands(), DescriptorBytes) CallInst(*this); 4729 } 4730 return new(getNumOperands()) CallInst(*this); 4731 } 4732 4733 SelectInst *SelectInst::cloneImpl() const { 4734 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2)); 4735 } 4736 4737 VAArgInst *VAArgInst::cloneImpl() const { 4738 return new VAArgInst(getOperand(0), getType()); 4739 } 4740 4741 ExtractElementInst *ExtractElementInst::cloneImpl() const { 4742 return ExtractElementInst::Create(getOperand(0), getOperand(1)); 4743 } 4744 4745 InsertElementInst *InsertElementInst::cloneImpl() const { 4746 return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2)); 4747 } 4748 4749 ShuffleVectorInst *ShuffleVectorInst::cloneImpl() const { 4750 return new ShuffleVectorInst(getOperand(0), getOperand(1), getShuffleMask()); 4751 } 4752 4753 PHINode *PHINode::cloneImpl() const { return new PHINode(*this); } 4754 4755 LandingPadInst *LandingPadInst::cloneImpl() const { 4756 return new LandingPadInst(*this); 4757 } 4758 4759 ReturnInst *ReturnInst::cloneImpl() const { 4760 return new(getNumOperands()) ReturnInst(*this); 4761 } 4762 4763 BranchInst *BranchInst::cloneImpl() const { 4764 return new(getNumOperands()) BranchInst(*this); 4765 } 4766 4767 SwitchInst *SwitchInst::cloneImpl() const { return new SwitchInst(*this); } 4768 4769 IndirectBrInst *IndirectBrInst::cloneImpl() const { 4770 return new IndirectBrInst(*this); 4771 } 4772 4773 InvokeInst *InvokeInst::cloneImpl() const { 4774 if (hasOperandBundles()) { 4775 unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo); 4776 return new(getNumOperands(), DescriptorBytes) InvokeInst(*this); 4777 } 4778 return new(getNumOperands()) InvokeInst(*this); 4779 } 4780 4781 CallBrInst *CallBrInst::cloneImpl() const { 4782 if (hasOperandBundles()) { 4783 unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo); 4784 return new (getNumOperands(), DescriptorBytes) CallBrInst(*this); 4785 } 4786 return new (getNumOperands()) CallBrInst(*this); 4787 } 4788 4789 ResumeInst *ResumeInst::cloneImpl() const { return new (1) ResumeInst(*this); } 4790 4791 CleanupReturnInst *CleanupReturnInst::cloneImpl() const { 4792 return new (getNumOperands()) CleanupReturnInst(*this); 4793 } 4794 4795 CatchReturnInst *CatchReturnInst::cloneImpl() const { 4796 return new (getNumOperands()) CatchReturnInst(*this); 4797 } 4798 4799 CatchSwitchInst *CatchSwitchInst::cloneImpl() const { 4800 return new CatchSwitchInst(*this); 4801 } 4802 4803 FuncletPadInst *FuncletPadInst::cloneImpl() const { 4804 return new (getNumOperands()) FuncletPadInst(*this); 4805 } 4806 4807 UnreachableInst *UnreachableInst::cloneImpl() const { 4808 LLVMContext &Context = getContext(); 4809 return new UnreachableInst(Context); 4810 } 4811 4812 FreezeInst *FreezeInst::cloneImpl() const { 4813 return new FreezeInst(getOperand(0)); 4814 } 4815