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