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