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