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