1 //===- Instructions.cpp - Implement the LLVM instructions -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements all of the non-inline methods for the LLVM instruction 10 // classes. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/IR/Instructions.h" 15 #include "LLVMContextImpl.h" 16 #include "llvm/ADT/None.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/ADT/Twine.h" 19 #include "llvm/IR/Attributes.h" 20 #include "llvm/IR/BasicBlock.h" 21 #include "llvm/IR/Constant.h" 22 #include "llvm/IR/Constants.h" 23 #include "llvm/IR/DataLayout.h" 24 #include "llvm/IR/DerivedTypes.h" 25 #include "llvm/IR/Function.h" 26 #include "llvm/IR/InstrTypes.h" 27 #include "llvm/IR/Instruction.h" 28 #include "llvm/IR/Intrinsics.h" 29 #include "llvm/IR/LLVMContext.h" 30 #include "llvm/IR/MDBuilder.h" 31 #include "llvm/IR/Metadata.h" 32 #include "llvm/IR/Module.h" 33 #include "llvm/IR/Operator.h" 34 #include "llvm/IR/Type.h" 35 #include "llvm/IR/Value.h" 36 #include "llvm/Support/AtomicOrdering.h" 37 #include "llvm/Support/Casting.h" 38 #include "llvm/Support/ErrorHandling.h" 39 #include "llvm/Support/MathExtras.h" 40 #include "llvm/Support/TypeSize.h" 41 #include <algorithm> 42 #include <cassert> 43 #include <cstdint> 44 #include <vector> 45 46 using namespace llvm; 47 48 //===----------------------------------------------------------------------===// 49 // AllocaInst Class 50 //===----------------------------------------------------------------------===// 51 52 Optional<uint64_t> 53 AllocaInst::getAllocationSizeInBits(const DataLayout &DL) const { 54 uint64_t Size = DL.getTypeAllocSizeInBits(getAllocatedType()); 55 if (isArrayAllocation()) { 56 auto C = dyn_cast<ConstantInt>(getArraySize()); 57 if (!C) 58 return None; 59 Size *= C->getZExtValue(); 60 } 61 return Size; 62 } 63 64 //===----------------------------------------------------------------------===// 65 // SelectInst Class 66 //===----------------------------------------------------------------------===// 67 68 /// areInvalidOperands - Return a string if the specified operands are invalid 69 /// for a select operation, otherwise return null. 70 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) { 71 if (Op1->getType() != Op2->getType()) 72 return "both values to select must have same type"; 73 74 if (Op1->getType()->isTokenTy()) 75 return "select values cannot have token type"; 76 77 if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) { 78 // Vector select. 79 if (VT->getElementType() != Type::getInt1Ty(Op0->getContext())) 80 return "vector select condition element type must be i1"; 81 VectorType *ET = dyn_cast<VectorType>(Op1->getType()); 82 if (!ET) 83 return "selected values for vector select must be vectors"; 84 if (ET->getNumElements() != VT->getNumElements()) 85 return "vector select requires selected vectors to have " 86 "the same vector length as select condition"; 87 } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) { 88 return "select condition must be i1 or <n x i1>"; 89 } 90 return nullptr; 91 } 92 93 //===----------------------------------------------------------------------===// 94 // PHINode Class 95 //===----------------------------------------------------------------------===// 96 97 PHINode::PHINode(const PHINode &PN) 98 : Instruction(PN.getType(), Instruction::PHI, nullptr, PN.getNumOperands()), 99 ReservedSpace(PN.getNumOperands()) { 100 allocHungoffUses(PN.getNumOperands()); 101 std::copy(PN.op_begin(), PN.op_end(), op_begin()); 102 std::copy(PN.block_begin(), PN.block_end(), block_begin()); 103 SubclassOptionalData = PN.SubclassOptionalData; 104 } 105 106 // removeIncomingValue - Remove an incoming value. This is useful if a 107 // predecessor basic block is deleted. 108 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) { 109 Value *Removed = getIncomingValue(Idx); 110 111 // Move everything after this operand down. 112 // 113 // FIXME: we could just swap with the end of the list, then erase. However, 114 // clients might not expect this to happen. The code as it is thrashes the 115 // use/def lists, which is kinda lame. 116 std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx); 117 std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx); 118 119 // Nuke the last value. 120 Op<-1>().set(nullptr); 121 setNumHungOffUseOperands(getNumOperands() - 1); 122 123 // If the PHI node is dead, because it has zero entries, nuke it now. 124 if (getNumOperands() == 0 && DeletePHIIfEmpty) { 125 // If anyone is using this PHI, make them use a dummy value instead... 126 replaceAllUsesWith(UndefValue::get(getType())); 127 eraseFromParent(); 128 } 129 return Removed; 130 } 131 132 /// growOperands - grow operands - This grows the operand list in response 133 /// to a push_back style of operation. This grows the number of ops by 1.5 134 /// times. 135 /// 136 void PHINode::growOperands() { 137 unsigned e = getNumOperands(); 138 unsigned NumOps = e + e / 2; 139 if (NumOps < 2) NumOps = 2; // 2 op PHI nodes are VERY common. 140 141 ReservedSpace = NumOps; 142 growHungoffUses(ReservedSpace, /* IsPhi */ true); 143 } 144 145 /// hasConstantValue - If the specified PHI node always merges together the same 146 /// value, return the value, otherwise return null. 147 Value *PHINode::hasConstantValue() const { 148 // Exploit the fact that phi nodes always have at least one entry. 149 Value *ConstantValue = getIncomingValue(0); 150 for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i) 151 if (getIncomingValue(i) != ConstantValue && getIncomingValue(i) != this) { 152 if (ConstantValue != this) 153 return nullptr; // Incoming values not all the same. 154 // The case where the first value is this PHI. 155 ConstantValue = getIncomingValue(i); 156 } 157 if (ConstantValue == this) 158 return UndefValue::get(getType()); 159 return ConstantValue; 160 } 161 162 /// hasConstantOrUndefValue - Whether the specified PHI node always merges 163 /// together the same value, assuming that undefs result in the same value as 164 /// non-undefs. 165 /// Unlike \ref hasConstantValue, this does not return a value because the 166 /// unique non-undef incoming value need not dominate the PHI node. 167 bool PHINode::hasConstantOrUndefValue() const { 168 Value *ConstantValue = nullptr; 169 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i) { 170 Value *Incoming = getIncomingValue(i); 171 if (Incoming != this && !isa<UndefValue>(Incoming)) { 172 if (ConstantValue && ConstantValue != Incoming) 173 return false; 174 ConstantValue = Incoming; 175 } 176 } 177 return true; 178 } 179 180 //===----------------------------------------------------------------------===// 181 // LandingPadInst Implementation 182 //===----------------------------------------------------------------------===// 183 184 LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues, 185 const Twine &NameStr, Instruction *InsertBefore) 186 : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertBefore) { 187 init(NumReservedValues, NameStr); 188 } 189 190 LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues, 191 const Twine &NameStr, BasicBlock *InsertAtEnd) 192 : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertAtEnd) { 193 init(NumReservedValues, NameStr); 194 } 195 196 LandingPadInst::LandingPadInst(const LandingPadInst &LP) 197 : Instruction(LP.getType(), Instruction::LandingPad, nullptr, 198 LP.getNumOperands()), 199 ReservedSpace(LP.getNumOperands()) { 200 allocHungoffUses(LP.getNumOperands()); 201 Use *OL = getOperandList(); 202 const Use *InOL = LP.getOperandList(); 203 for (unsigned I = 0, E = ReservedSpace; I != E; ++I) 204 OL[I] = InOL[I]; 205 206 setCleanup(LP.isCleanup()); 207 } 208 209 LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses, 210 const Twine &NameStr, 211 Instruction *InsertBefore) { 212 return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertBefore); 213 } 214 215 LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses, 216 const Twine &NameStr, 217 BasicBlock *InsertAtEnd) { 218 return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertAtEnd); 219 } 220 221 void LandingPadInst::init(unsigned NumReservedValues, const Twine &NameStr) { 222 ReservedSpace = NumReservedValues; 223 setNumHungOffUseOperands(0); 224 allocHungoffUses(ReservedSpace); 225 setName(NameStr); 226 setCleanup(false); 227 } 228 229 /// growOperands - grow operands - This grows the operand list in response to a 230 /// push_back style of operation. This grows the number of ops by 2 times. 231 void LandingPadInst::growOperands(unsigned Size) { 232 unsigned e = getNumOperands(); 233 if (ReservedSpace >= e + Size) return; 234 ReservedSpace = (std::max(e, 1U) + Size / 2) * 2; 235 growHungoffUses(ReservedSpace); 236 } 237 238 void LandingPadInst::addClause(Constant *Val) { 239 unsigned OpNo = getNumOperands(); 240 growOperands(1); 241 assert(OpNo < ReservedSpace && "Growing didn't work!"); 242 setNumHungOffUseOperands(getNumOperands() + 1); 243 getOperandList()[OpNo] = Val; 244 } 245 246 //===----------------------------------------------------------------------===// 247 // CallBase Implementation 248 //===----------------------------------------------------------------------===// 249 250 Function *CallBase::getCaller() { return getParent()->getParent(); } 251 252 unsigned CallBase::getNumSubclassExtraOperandsDynamic() const { 253 assert(getOpcode() == Instruction::CallBr && "Unexpected opcode!"); 254 return cast<CallBrInst>(this)->getNumIndirectDests() + 1; 255 } 256 257 bool CallBase::isIndirectCall() const { 258 const Value *V = 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 assert((UsesLHS ^ UsesRHS) && "Should have selected from exactly 1 source"); 2057 return true; 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 int NumOpElts = cast<VectorType>(Op<0>()->getType())->getNumElements(); 2186 int NumMaskElts = cast<VectorType>(getType())->getNumElements(); 2187 if (NumMaskElts <= NumOpElts) 2188 return false; 2189 2190 // The first part of the mask must choose elements from exactly 1 source op. 2191 ArrayRef<int> Mask = getShuffleMask(); 2192 if (!isIdentityMaskImpl(Mask, NumOpElts)) 2193 return false; 2194 2195 // All extending must be with undef elements. 2196 for (int i = NumOpElts; i < NumMaskElts; ++i) 2197 if (Mask[i] != -1) 2198 return false; 2199 2200 return true; 2201 } 2202 2203 bool ShuffleVectorInst::isIdentityWithExtract() const { 2204 int NumOpElts = cast<VectorType>(Op<0>()->getType())->getNumElements(); 2205 int NumMaskElts = getType()->getNumElements(); 2206 if (NumMaskElts >= NumOpElts) 2207 return false; 2208 2209 return isIdentityMaskImpl(getShuffleMask(), NumOpElts); 2210 } 2211 2212 bool ShuffleVectorInst::isConcat() const { 2213 // Vector concatenation is differentiated from identity with padding. 2214 if (isa<UndefValue>(Op<0>()) || isa<UndefValue>(Op<1>())) 2215 return false; 2216 2217 int NumOpElts = cast<VectorType>(Op<0>()->getType())->getNumElements(); 2218 int NumMaskElts = getType()->getNumElements(); 2219 if (NumMaskElts != NumOpElts * 2) 2220 return false; 2221 2222 // Use the mask length rather than the operands' vector lengths here. We 2223 // already know that the shuffle returns a vector twice as long as the inputs, 2224 // and neither of the inputs are undef vectors. If the mask picks consecutive 2225 // elements from both inputs, then this is a concatenation of the inputs. 2226 return isIdentityMaskImpl(getShuffleMask(), NumMaskElts); 2227 } 2228 2229 //===----------------------------------------------------------------------===// 2230 // InsertValueInst Class 2231 //===----------------------------------------------------------------------===// 2232 2233 void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, 2234 const Twine &Name) { 2235 assert(getNumOperands() == 2 && "NumOperands not initialized?"); 2236 2237 // There's no fundamental reason why we require at least one index 2238 // (other than weirdness with &*IdxBegin being invalid; see 2239 // getelementptr's init routine for example). But there's no 2240 // present need to support it. 2241 assert(!Idxs.empty() && "InsertValueInst must have at least one index"); 2242 2243 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) == 2244 Val->getType() && "Inserted value must match indexed type!"); 2245 Op<0>() = Agg; 2246 Op<1>() = Val; 2247 2248 Indices.append(Idxs.begin(), Idxs.end()); 2249 setName(Name); 2250 } 2251 2252 InsertValueInst::InsertValueInst(const InsertValueInst &IVI) 2253 : Instruction(IVI.getType(), InsertValue, 2254 OperandTraits<InsertValueInst>::op_begin(this), 2), 2255 Indices(IVI.Indices) { 2256 Op<0>() = IVI.getOperand(0); 2257 Op<1>() = IVI.getOperand(1); 2258 SubclassOptionalData = IVI.SubclassOptionalData; 2259 } 2260 2261 //===----------------------------------------------------------------------===// 2262 // ExtractValueInst Class 2263 //===----------------------------------------------------------------------===// 2264 2265 void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) { 2266 assert(getNumOperands() == 1 && "NumOperands not initialized?"); 2267 2268 // There's no fundamental reason why we require at least one index. 2269 // But there's no present need to support it. 2270 assert(!Idxs.empty() && "ExtractValueInst must have at least one index"); 2271 2272 Indices.append(Idxs.begin(), Idxs.end()); 2273 setName(Name); 2274 } 2275 2276 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI) 2277 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)), 2278 Indices(EVI.Indices) { 2279 SubclassOptionalData = EVI.SubclassOptionalData; 2280 } 2281 2282 // getIndexedType - Returns the type of the element that would be extracted 2283 // with an extractvalue instruction with the specified parameters. 2284 // 2285 // A null type is returned if the indices are invalid for the specified 2286 // pointer type. 2287 // 2288 Type *ExtractValueInst::getIndexedType(Type *Agg, 2289 ArrayRef<unsigned> Idxs) { 2290 for (unsigned Index : Idxs) { 2291 // We can't use CompositeType::indexValid(Index) here. 2292 // indexValid() always returns true for arrays because getelementptr allows 2293 // out-of-bounds indices. Since we don't allow those for extractvalue and 2294 // insertvalue we need to check array indexing manually. 2295 // Since the only other types we can index into are struct types it's just 2296 // as easy to check those manually as well. 2297 if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) { 2298 if (Index >= AT->getNumElements()) 2299 return nullptr; 2300 Agg = AT->getElementType(); 2301 } else if (StructType *ST = dyn_cast<StructType>(Agg)) { 2302 if (Index >= ST->getNumElements()) 2303 return nullptr; 2304 Agg = ST->getElementType(Index); 2305 } else { 2306 // Not a valid type to index into. 2307 return nullptr; 2308 } 2309 } 2310 return const_cast<Type*>(Agg); 2311 } 2312 2313 //===----------------------------------------------------------------------===// 2314 // UnaryOperator Class 2315 //===----------------------------------------------------------------------===// 2316 2317 UnaryOperator::UnaryOperator(UnaryOps iType, Value *S, 2318 Type *Ty, const Twine &Name, 2319 Instruction *InsertBefore) 2320 : UnaryInstruction(Ty, iType, S, InsertBefore) { 2321 Op<0>() = S; 2322 setName(Name); 2323 AssertOK(); 2324 } 2325 2326 UnaryOperator::UnaryOperator(UnaryOps iType, Value *S, 2327 Type *Ty, const Twine &Name, 2328 BasicBlock *InsertAtEnd) 2329 : UnaryInstruction(Ty, iType, S, InsertAtEnd) { 2330 Op<0>() = S; 2331 setName(Name); 2332 AssertOK(); 2333 } 2334 2335 UnaryOperator *UnaryOperator::Create(UnaryOps Op, Value *S, 2336 const Twine &Name, 2337 Instruction *InsertBefore) { 2338 return new UnaryOperator(Op, S, S->getType(), Name, InsertBefore); 2339 } 2340 2341 UnaryOperator *UnaryOperator::Create(UnaryOps Op, Value *S, 2342 const Twine &Name, 2343 BasicBlock *InsertAtEnd) { 2344 UnaryOperator *Res = Create(Op, S, Name); 2345 InsertAtEnd->getInstList().push_back(Res); 2346 return Res; 2347 } 2348 2349 void UnaryOperator::AssertOK() { 2350 Value *LHS = getOperand(0); 2351 (void)LHS; // Silence warnings. 2352 #ifndef NDEBUG 2353 switch (getOpcode()) { 2354 case FNeg: 2355 assert(getType() == LHS->getType() && 2356 "Unary operation should return same type as operand!"); 2357 assert(getType()->isFPOrFPVectorTy() && 2358 "Tried to create a floating-point operation on a " 2359 "non-floating-point type!"); 2360 break; 2361 default: llvm_unreachable("Invalid opcode provided"); 2362 } 2363 #endif 2364 } 2365 2366 //===----------------------------------------------------------------------===// 2367 // BinaryOperator Class 2368 //===----------------------------------------------------------------------===// 2369 2370 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2, 2371 Type *Ty, const Twine &Name, 2372 Instruction *InsertBefore) 2373 : Instruction(Ty, iType, 2374 OperandTraits<BinaryOperator>::op_begin(this), 2375 OperandTraits<BinaryOperator>::operands(this), 2376 InsertBefore) { 2377 Op<0>() = S1; 2378 Op<1>() = S2; 2379 setName(Name); 2380 AssertOK(); 2381 } 2382 2383 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2, 2384 Type *Ty, const Twine &Name, 2385 BasicBlock *InsertAtEnd) 2386 : Instruction(Ty, iType, 2387 OperandTraits<BinaryOperator>::op_begin(this), 2388 OperandTraits<BinaryOperator>::operands(this), 2389 InsertAtEnd) { 2390 Op<0>() = S1; 2391 Op<1>() = S2; 2392 setName(Name); 2393 AssertOK(); 2394 } 2395 2396 void BinaryOperator::AssertOK() { 2397 Value *LHS = getOperand(0), *RHS = getOperand(1); 2398 (void)LHS; (void)RHS; // Silence warnings. 2399 assert(LHS->getType() == RHS->getType() && 2400 "Binary operator operand types must match!"); 2401 #ifndef NDEBUG 2402 switch (getOpcode()) { 2403 case Add: case Sub: 2404 case Mul: 2405 assert(getType() == LHS->getType() && 2406 "Arithmetic operation should return same type as operands!"); 2407 assert(getType()->isIntOrIntVectorTy() && 2408 "Tried to create an integer operation on a non-integer type!"); 2409 break; 2410 case FAdd: case FSub: 2411 case FMul: 2412 assert(getType() == LHS->getType() && 2413 "Arithmetic operation should return same type as operands!"); 2414 assert(getType()->isFPOrFPVectorTy() && 2415 "Tried to create a floating-point operation on a " 2416 "non-floating-point type!"); 2417 break; 2418 case UDiv: 2419 case SDiv: 2420 assert(getType() == LHS->getType() && 2421 "Arithmetic operation should return same type as operands!"); 2422 assert(getType()->isIntOrIntVectorTy() && 2423 "Incorrect operand type (not integer) for S/UDIV"); 2424 break; 2425 case FDiv: 2426 assert(getType() == LHS->getType() && 2427 "Arithmetic operation should return same type as operands!"); 2428 assert(getType()->isFPOrFPVectorTy() && 2429 "Incorrect operand type (not floating point) for FDIV"); 2430 break; 2431 case URem: 2432 case SRem: 2433 assert(getType() == LHS->getType() && 2434 "Arithmetic operation should return same type as operands!"); 2435 assert(getType()->isIntOrIntVectorTy() && 2436 "Incorrect operand type (not integer) for S/UREM"); 2437 break; 2438 case FRem: 2439 assert(getType() == LHS->getType() && 2440 "Arithmetic operation should return same type as operands!"); 2441 assert(getType()->isFPOrFPVectorTy() && 2442 "Incorrect operand type (not floating point) for FREM"); 2443 break; 2444 case Shl: 2445 case LShr: 2446 case AShr: 2447 assert(getType() == LHS->getType() && 2448 "Shift operation should return same type as operands!"); 2449 assert(getType()->isIntOrIntVectorTy() && 2450 "Tried to create a shift operation on a non-integral type!"); 2451 break; 2452 case And: case Or: 2453 case Xor: 2454 assert(getType() == LHS->getType() && 2455 "Logical operation should return same type as operands!"); 2456 assert(getType()->isIntOrIntVectorTy() && 2457 "Tried to create a logical operation on a non-integral type!"); 2458 break; 2459 default: llvm_unreachable("Invalid opcode provided"); 2460 } 2461 #endif 2462 } 2463 2464 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2, 2465 const Twine &Name, 2466 Instruction *InsertBefore) { 2467 assert(S1->getType() == S2->getType() && 2468 "Cannot create binary operator with two operands of differing type!"); 2469 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore); 2470 } 2471 2472 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2, 2473 const Twine &Name, 2474 BasicBlock *InsertAtEnd) { 2475 BinaryOperator *Res = Create(Op, S1, S2, Name); 2476 InsertAtEnd->getInstList().push_back(Res); 2477 return Res; 2478 } 2479 2480 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name, 2481 Instruction *InsertBefore) { 2482 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2483 return new BinaryOperator(Instruction::Sub, 2484 zero, Op, 2485 Op->getType(), Name, InsertBefore); 2486 } 2487 2488 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name, 2489 BasicBlock *InsertAtEnd) { 2490 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2491 return new BinaryOperator(Instruction::Sub, 2492 zero, Op, 2493 Op->getType(), Name, InsertAtEnd); 2494 } 2495 2496 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name, 2497 Instruction *InsertBefore) { 2498 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2499 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore); 2500 } 2501 2502 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name, 2503 BasicBlock *InsertAtEnd) { 2504 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2505 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd); 2506 } 2507 2508 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name, 2509 Instruction *InsertBefore) { 2510 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2511 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore); 2512 } 2513 2514 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name, 2515 BasicBlock *InsertAtEnd) { 2516 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2517 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd); 2518 } 2519 2520 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name, 2521 Instruction *InsertBefore) { 2522 Constant *C = Constant::getAllOnesValue(Op->getType()); 2523 return new BinaryOperator(Instruction::Xor, Op, C, 2524 Op->getType(), Name, InsertBefore); 2525 } 2526 2527 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name, 2528 BasicBlock *InsertAtEnd) { 2529 Constant *AllOnes = Constant::getAllOnesValue(Op->getType()); 2530 return new BinaryOperator(Instruction::Xor, Op, AllOnes, 2531 Op->getType(), Name, InsertAtEnd); 2532 } 2533 2534 // Exchange the two operands to this instruction. This instruction is safe to 2535 // use on any binary instruction and does not modify the semantics of the 2536 // instruction. If the instruction is order-dependent (SetLT f.e.), the opcode 2537 // is changed. 2538 bool BinaryOperator::swapOperands() { 2539 if (!isCommutative()) 2540 return true; // Can't commute operands 2541 Op<0>().swap(Op<1>()); 2542 return false; 2543 } 2544 2545 //===----------------------------------------------------------------------===// 2546 // FPMathOperator Class 2547 //===----------------------------------------------------------------------===// 2548 2549 float FPMathOperator::getFPAccuracy() const { 2550 const MDNode *MD = 2551 cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath); 2552 if (!MD) 2553 return 0.0; 2554 ConstantFP *Accuracy = mdconst::extract<ConstantFP>(MD->getOperand(0)); 2555 return Accuracy->getValueAPF().convertToFloat(); 2556 } 2557 2558 //===----------------------------------------------------------------------===// 2559 // CastInst Class 2560 //===----------------------------------------------------------------------===// 2561 2562 // Just determine if this cast only deals with integral->integral conversion. 2563 bool CastInst::isIntegerCast() const { 2564 switch (getOpcode()) { 2565 default: return false; 2566 case Instruction::ZExt: 2567 case Instruction::SExt: 2568 case Instruction::Trunc: 2569 return true; 2570 case Instruction::BitCast: 2571 return getOperand(0)->getType()->isIntegerTy() && 2572 getType()->isIntegerTy(); 2573 } 2574 } 2575 2576 bool CastInst::isLosslessCast() const { 2577 // Only BitCast can be lossless, exit fast if we're not BitCast 2578 if (getOpcode() != Instruction::BitCast) 2579 return false; 2580 2581 // Identity cast is always lossless 2582 Type *SrcTy = getOperand(0)->getType(); 2583 Type *DstTy = getType(); 2584 if (SrcTy == DstTy) 2585 return true; 2586 2587 // Pointer to pointer is always lossless. 2588 if (SrcTy->isPointerTy()) 2589 return DstTy->isPointerTy(); 2590 return false; // Other types have no identity values 2591 } 2592 2593 /// This function determines if the CastInst does not require any bits to be 2594 /// changed in order to effect the cast. Essentially, it identifies cases where 2595 /// no code gen is necessary for the cast, hence the name no-op cast. For 2596 /// example, the following are all no-op casts: 2597 /// # bitcast i32* %x to i8* 2598 /// # bitcast <2 x i32> %x to <4 x i16> 2599 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only 2600 /// Determine if the described cast is a no-op. 2601 bool CastInst::isNoopCast(Instruction::CastOps Opcode, 2602 Type *SrcTy, 2603 Type *DestTy, 2604 const DataLayout &DL) { 2605 switch (Opcode) { 2606 default: llvm_unreachable("Invalid CastOp"); 2607 case Instruction::Trunc: 2608 case Instruction::ZExt: 2609 case Instruction::SExt: 2610 case Instruction::FPTrunc: 2611 case Instruction::FPExt: 2612 case Instruction::UIToFP: 2613 case Instruction::SIToFP: 2614 case Instruction::FPToUI: 2615 case Instruction::FPToSI: 2616 case Instruction::AddrSpaceCast: 2617 // TODO: Target informations may give a more accurate answer here. 2618 return false; 2619 case Instruction::BitCast: 2620 return true; // BitCast never modifies bits. 2621 case Instruction::PtrToInt: 2622 return DL.getIntPtrType(SrcTy)->getScalarSizeInBits() == 2623 DestTy->getScalarSizeInBits(); 2624 case Instruction::IntToPtr: 2625 return DL.getIntPtrType(DestTy)->getScalarSizeInBits() == 2626 SrcTy->getScalarSizeInBits(); 2627 } 2628 } 2629 2630 bool CastInst::isNoopCast(const DataLayout &DL) const { 2631 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), DL); 2632 } 2633 2634 /// This function determines if a pair of casts can be eliminated and what 2635 /// opcode should be used in the elimination. This assumes that there are two 2636 /// instructions like this: 2637 /// * %F = firstOpcode SrcTy %x to MidTy 2638 /// * %S = secondOpcode MidTy %F to DstTy 2639 /// The function returns a resultOpcode so these two casts can be replaced with: 2640 /// * %Replacement = resultOpcode %SrcTy %x to DstTy 2641 /// If no such cast is permitted, the function returns 0. 2642 unsigned CastInst::isEliminableCastPair( 2643 Instruction::CastOps firstOp, Instruction::CastOps secondOp, 2644 Type *SrcTy, Type *MidTy, Type *DstTy, Type *SrcIntPtrTy, Type *MidIntPtrTy, 2645 Type *DstIntPtrTy) { 2646 // Define the 144 possibilities for these two cast instructions. The values 2647 // in this matrix determine what to do in a given situation and select the 2648 // case in the switch below. The rows correspond to firstOp, the columns 2649 // correspond to secondOp. In looking at the table below, keep in mind 2650 // the following cast properties: 2651 // 2652 // Size Compare Source Destination 2653 // Operator Src ? Size Type Sign Type Sign 2654 // -------- ------------ ------------------- --------------------- 2655 // TRUNC > Integer Any Integral Any 2656 // ZEXT < Integral Unsigned Integer Any 2657 // SEXT < Integral Signed Integer Any 2658 // FPTOUI n/a FloatPt n/a Integral Unsigned 2659 // FPTOSI n/a FloatPt n/a Integral Signed 2660 // UITOFP n/a Integral Unsigned FloatPt n/a 2661 // SITOFP n/a Integral Signed FloatPt n/a 2662 // FPTRUNC > FloatPt n/a FloatPt n/a 2663 // FPEXT < FloatPt n/a FloatPt n/a 2664 // PTRTOINT n/a Pointer n/a Integral Unsigned 2665 // INTTOPTR n/a Integral Unsigned Pointer n/a 2666 // BITCAST = FirstClass n/a FirstClass n/a 2667 // ADDRSPCST n/a Pointer n/a Pointer n/a 2668 // 2669 // NOTE: some transforms are safe, but we consider them to be non-profitable. 2670 // For example, we could merge "fptoui double to i32" + "zext i32 to i64", 2671 // into "fptoui double to i64", but this loses information about the range 2672 // of the produced value (we no longer know the top-part is all zeros). 2673 // Further this conversion is often much more expensive for typical hardware, 2674 // and causes issues when building libgcc. We disallow fptosi+sext for the 2675 // same reason. 2676 const unsigned numCastOps = 2677 Instruction::CastOpsEnd - Instruction::CastOpsBegin; 2678 static const uint8_t CastResults[numCastOps][numCastOps] = { 2679 // T F F U S F F P I B A -+ 2680 // R Z S P P I I T P 2 N T S | 2681 // U E E 2 2 2 2 R E I T C C +- secondOp 2682 // N X X U S F F N X N 2 V V | 2683 // C T T I I P P C T T P T T -+ 2684 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // Trunc -+ 2685 { 8, 1, 9,99,99, 2,17,99,99,99, 2, 3, 0}, // ZExt | 2686 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3, 0}, // SExt | 2687 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToUI | 2688 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToSI | 2689 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // UIToFP +- firstOp 2690 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // SIToFP | 2691 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // FPTrunc | 2692 { 99,99,99, 2, 2,99,99, 8, 2,99,99, 4, 0}, // FPExt | 2693 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3, 0}, // PtrToInt | 2694 { 99,99,99,99,99,99,99,99,99,11,99,15, 0}, // IntToPtr | 2695 { 5, 5, 5, 6, 6, 5, 5, 6, 6,16, 5, 1,14}, // BitCast | 2696 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+ 2697 }; 2698 2699 // TODO: This logic could be encoded into the table above and handled in the 2700 // switch below. 2701 // If either of the casts are a bitcast from scalar to vector, disallow the 2702 // merging. However, any pair of bitcasts are allowed. 2703 bool IsFirstBitcast = (firstOp == Instruction::BitCast); 2704 bool IsSecondBitcast = (secondOp == Instruction::BitCast); 2705 bool AreBothBitcasts = IsFirstBitcast && IsSecondBitcast; 2706 2707 // Check if any of the casts convert scalars <-> vectors. 2708 if ((IsFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) || 2709 (IsSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy))) 2710 if (!AreBothBitcasts) 2711 return 0; 2712 2713 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin] 2714 [secondOp-Instruction::CastOpsBegin]; 2715 switch (ElimCase) { 2716 case 0: 2717 // Categorically disallowed. 2718 return 0; 2719 case 1: 2720 // Allowed, use first cast's opcode. 2721 return firstOp; 2722 case 2: 2723 // Allowed, use second cast's opcode. 2724 return secondOp; 2725 case 3: 2726 // No-op cast in second op implies firstOp as long as the DestTy 2727 // is integer and we are not converting between a vector and a 2728 // non-vector type. 2729 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy()) 2730 return firstOp; 2731 return 0; 2732 case 4: 2733 // No-op cast in second op implies firstOp as long as the DestTy 2734 // is floating point. 2735 if (DstTy->isFloatingPointTy()) 2736 return firstOp; 2737 return 0; 2738 case 5: 2739 // No-op cast in first op implies secondOp as long as the SrcTy 2740 // is an integer. 2741 if (SrcTy->isIntegerTy()) 2742 return secondOp; 2743 return 0; 2744 case 6: 2745 // No-op cast in first op implies secondOp as long as the SrcTy 2746 // is a floating point. 2747 if (SrcTy->isFloatingPointTy()) 2748 return secondOp; 2749 return 0; 2750 case 7: { 2751 // Cannot simplify if address spaces are different! 2752 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) 2753 return 0; 2754 2755 unsigned MidSize = MidTy->getScalarSizeInBits(); 2756 // We can still fold this without knowing the actual sizes as long we 2757 // know that the intermediate pointer is the largest possible 2758 // pointer size. 2759 // FIXME: Is this always true? 2760 if (MidSize == 64) 2761 return Instruction::BitCast; 2762 2763 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size. 2764 if (!SrcIntPtrTy || DstIntPtrTy != SrcIntPtrTy) 2765 return 0; 2766 unsigned PtrSize = SrcIntPtrTy->getScalarSizeInBits(); 2767 if (MidSize >= PtrSize) 2768 return Instruction::BitCast; 2769 return 0; 2770 } 2771 case 8: { 2772 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size 2773 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy) 2774 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy) 2775 unsigned SrcSize = SrcTy->getScalarSizeInBits(); 2776 unsigned DstSize = DstTy->getScalarSizeInBits(); 2777 if (SrcSize == DstSize) 2778 return Instruction::BitCast; 2779 else if (SrcSize < DstSize) 2780 return firstOp; 2781 return secondOp; 2782 } 2783 case 9: 2784 // zext, sext -> zext, because sext can't sign extend after zext 2785 return Instruction::ZExt; 2786 case 11: { 2787 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize 2788 if (!MidIntPtrTy) 2789 return 0; 2790 unsigned PtrSize = MidIntPtrTy->getScalarSizeInBits(); 2791 unsigned SrcSize = SrcTy->getScalarSizeInBits(); 2792 unsigned DstSize = DstTy->getScalarSizeInBits(); 2793 if (SrcSize <= PtrSize && SrcSize == DstSize) 2794 return Instruction::BitCast; 2795 return 0; 2796 } 2797 case 12: 2798 // addrspacecast, addrspacecast -> bitcast, if SrcAS == DstAS 2799 // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS 2800 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) 2801 return Instruction::AddrSpaceCast; 2802 return Instruction::BitCast; 2803 case 13: 2804 // FIXME: this state can be merged with (1), but the following assert 2805 // is useful to check the correcteness of the sequence due to semantic 2806 // change of bitcast. 2807 assert( 2808 SrcTy->isPtrOrPtrVectorTy() && 2809 MidTy->isPtrOrPtrVectorTy() && 2810 DstTy->isPtrOrPtrVectorTy() && 2811 SrcTy->getPointerAddressSpace() != MidTy->getPointerAddressSpace() && 2812 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() && 2813 "Illegal addrspacecast, bitcast sequence!"); 2814 // Allowed, use first cast's opcode 2815 return firstOp; 2816 case 14: 2817 // bitcast, addrspacecast -> addrspacecast if the element type of 2818 // bitcast's source is the same as that of addrspacecast's destination. 2819 if (SrcTy->getScalarType()->getPointerElementType() == 2820 DstTy->getScalarType()->getPointerElementType()) 2821 return Instruction::AddrSpaceCast; 2822 return 0; 2823 case 15: 2824 // FIXME: this state can be merged with (1), but the following assert 2825 // is useful to check the correcteness of the sequence due to semantic 2826 // change of bitcast. 2827 assert( 2828 SrcTy->isIntOrIntVectorTy() && 2829 MidTy->isPtrOrPtrVectorTy() && 2830 DstTy->isPtrOrPtrVectorTy() && 2831 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() && 2832 "Illegal inttoptr, bitcast sequence!"); 2833 // Allowed, use first cast's opcode 2834 return firstOp; 2835 case 16: 2836 // FIXME: this state can be merged with (2), but the following assert 2837 // is useful to check the correcteness of the sequence due to semantic 2838 // change of bitcast. 2839 assert( 2840 SrcTy->isPtrOrPtrVectorTy() && 2841 MidTy->isPtrOrPtrVectorTy() && 2842 DstTy->isIntOrIntVectorTy() && 2843 SrcTy->getPointerAddressSpace() == MidTy->getPointerAddressSpace() && 2844 "Illegal bitcast, ptrtoint sequence!"); 2845 // Allowed, use second cast's opcode 2846 return secondOp; 2847 case 17: 2848 // (sitofp (zext x)) -> (uitofp x) 2849 return Instruction::UIToFP; 2850 case 99: 2851 // Cast combination can't happen (error in input). This is for all cases 2852 // where the MidTy is not the same for the two cast instructions. 2853 llvm_unreachable("Invalid Cast Combination"); 2854 default: 2855 llvm_unreachable("Error in CastResults table!!!"); 2856 } 2857 } 2858 2859 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty, 2860 const Twine &Name, Instruction *InsertBefore) { 2861 assert(castIsValid(op, S, Ty) && "Invalid cast!"); 2862 // Construct and return the appropriate CastInst subclass 2863 switch (op) { 2864 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore); 2865 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore); 2866 case SExt: return new SExtInst (S, Ty, Name, InsertBefore); 2867 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore); 2868 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore); 2869 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore); 2870 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore); 2871 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore); 2872 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore); 2873 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore); 2874 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore); 2875 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore); 2876 case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertBefore); 2877 default: llvm_unreachable("Invalid opcode provided"); 2878 } 2879 } 2880 2881 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty, 2882 const Twine &Name, BasicBlock *InsertAtEnd) { 2883 assert(castIsValid(op, S, Ty) && "Invalid cast!"); 2884 // Construct and return the appropriate CastInst subclass 2885 switch (op) { 2886 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd); 2887 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd); 2888 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd); 2889 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd); 2890 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd); 2891 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd); 2892 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd); 2893 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd); 2894 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd); 2895 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd); 2896 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd); 2897 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd); 2898 case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertAtEnd); 2899 default: llvm_unreachable("Invalid opcode provided"); 2900 } 2901 } 2902 2903 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty, 2904 const Twine &Name, 2905 Instruction *InsertBefore) { 2906 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2907 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 2908 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore); 2909 } 2910 2911 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty, 2912 const Twine &Name, 2913 BasicBlock *InsertAtEnd) { 2914 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2915 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 2916 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd); 2917 } 2918 2919 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty, 2920 const Twine &Name, 2921 Instruction *InsertBefore) { 2922 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2923 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 2924 return Create(Instruction::SExt, S, Ty, Name, InsertBefore); 2925 } 2926 2927 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty, 2928 const Twine &Name, 2929 BasicBlock *InsertAtEnd) { 2930 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2931 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 2932 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd); 2933 } 2934 2935 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty, 2936 const Twine &Name, 2937 Instruction *InsertBefore) { 2938 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2939 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 2940 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore); 2941 } 2942 2943 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty, 2944 const Twine &Name, 2945 BasicBlock *InsertAtEnd) { 2946 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2947 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 2948 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd); 2949 } 2950 2951 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty, 2952 const Twine &Name, 2953 BasicBlock *InsertAtEnd) { 2954 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); 2955 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) && 2956 "Invalid cast"); 2957 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast"); 2958 assert((!Ty->isVectorTy() || 2959 cast<VectorType>(Ty)->getNumElements() == 2960 cast<VectorType>(S->getType())->getNumElements()) && 2961 "Invalid cast"); 2962 2963 if (Ty->isIntOrIntVectorTy()) 2964 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd); 2965 2966 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertAtEnd); 2967 } 2968 2969 /// Create a BitCast or a PtrToInt cast instruction 2970 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty, 2971 const Twine &Name, 2972 Instruction *InsertBefore) { 2973 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); 2974 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) && 2975 "Invalid cast"); 2976 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast"); 2977 assert((!Ty->isVectorTy() || 2978 cast<VectorType>(Ty)->getNumElements() == 2979 cast<VectorType>(S->getType())->getNumElements()) && 2980 "Invalid cast"); 2981 2982 if (Ty->isIntOrIntVectorTy()) 2983 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore); 2984 2985 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertBefore); 2986 } 2987 2988 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast( 2989 Value *S, Type *Ty, 2990 const Twine &Name, 2991 BasicBlock *InsertAtEnd) { 2992 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); 2993 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast"); 2994 2995 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace()) 2996 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertAtEnd); 2997 2998 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 2999 } 3000 3001 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast( 3002 Value *S, Type *Ty, 3003 const Twine &Name, 3004 Instruction *InsertBefore) { 3005 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); 3006 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast"); 3007 3008 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace()) 3009 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertBefore); 3010 3011 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 3012 } 3013 3014 CastInst *CastInst::CreateBitOrPointerCast(Value *S, Type *Ty, 3015 const Twine &Name, 3016 Instruction *InsertBefore) { 3017 if (S->getType()->isPointerTy() && Ty->isIntegerTy()) 3018 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore); 3019 if (S->getType()->isIntegerTy() && Ty->isPointerTy()) 3020 return Create(Instruction::IntToPtr, S, Ty, Name, InsertBefore); 3021 3022 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 3023 } 3024 3025 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty, 3026 bool isSigned, const Twine &Name, 3027 Instruction *InsertBefore) { 3028 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() && 3029 "Invalid integer cast"); 3030 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 3031 unsigned DstBits = Ty->getScalarSizeInBits(); 3032 Instruction::CastOps opcode = 3033 (SrcBits == DstBits ? Instruction::BitCast : 3034 (SrcBits > DstBits ? Instruction::Trunc : 3035 (isSigned ? Instruction::SExt : Instruction::ZExt))); 3036 return Create(opcode, C, Ty, Name, InsertBefore); 3037 } 3038 3039 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty, 3040 bool isSigned, const Twine &Name, 3041 BasicBlock *InsertAtEnd) { 3042 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() && 3043 "Invalid cast"); 3044 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 3045 unsigned DstBits = Ty->getScalarSizeInBits(); 3046 Instruction::CastOps opcode = 3047 (SrcBits == DstBits ? Instruction::BitCast : 3048 (SrcBits > DstBits ? Instruction::Trunc : 3049 (isSigned ? Instruction::SExt : Instruction::ZExt))); 3050 return Create(opcode, C, Ty, Name, InsertAtEnd); 3051 } 3052 3053 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty, 3054 const Twine &Name, 3055 Instruction *InsertBefore) { 3056 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() && 3057 "Invalid cast"); 3058 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 3059 unsigned DstBits = Ty->getScalarSizeInBits(); 3060 Instruction::CastOps opcode = 3061 (SrcBits == DstBits ? Instruction::BitCast : 3062 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt)); 3063 return Create(opcode, C, Ty, Name, InsertBefore); 3064 } 3065 3066 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty, 3067 const Twine &Name, 3068 BasicBlock *InsertAtEnd) { 3069 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() && 3070 "Invalid cast"); 3071 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 3072 unsigned DstBits = Ty->getScalarSizeInBits(); 3073 Instruction::CastOps opcode = 3074 (SrcBits == DstBits ? Instruction::BitCast : 3075 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt)); 3076 return Create(opcode, C, Ty, Name, InsertAtEnd); 3077 } 3078 3079 // Check whether it is valid to call getCastOpcode for these types. 3080 // This routine must be kept in sync with getCastOpcode. 3081 bool CastInst::isCastable(Type *SrcTy, Type *DestTy) { 3082 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType()) 3083 return false; 3084 3085 if (SrcTy == DestTy) 3086 return true; 3087 3088 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) 3089 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) 3090 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) { 3091 // An element by element cast. Valid if casting the elements is valid. 3092 SrcTy = SrcVecTy->getElementType(); 3093 DestTy = DestVecTy->getElementType(); 3094 } 3095 3096 // Get the bit sizes, we'll need these 3097 TypeSize SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr 3098 TypeSize DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr 3099 3100 // Run through the possibilities ... 3101 if (DestTy->isIntegerTy()) { // Casting to integral 3102 if (SrcTy->isIntegerTy()) // Casting from integral 3103 return true; 3104 if (SrcTy->isFloatingPointTy()) // Casting from floating pt 3105 return true; 3106 if (SrcTy->isVectorTy()) // Casting from vector 3107 return DestBits == SrcBits; 3108 // Casting from something else 3109 return SrcTy->isPointerTy(); 3110 } 3111 if (DestTy->isFloatingPointTy()) { // Casting to floating pt 3112 if (SrcTy->isIntegerTy()) // Casting from integral 3113 return true; 3114 if (SrcTy->isFloatingPointTy()) // Casting from floating pt 3115 return true; 3116 if (SrcTy->isVectorTy()) // Casting from vector 3117 return DestBits == SrcBits; 3118 // Casting from something else 3119 return false; 3120 } 3121 if (DestTy->isVectorTy()) // Casting to vector 3122 return DestBits == SrcBits; 3123 if (DestTy->isPointerTy()) { // Casting to pointer 3124 if (SrcTy->isPointerTy()) // Casting from pointer 3125 return true; 3126 return SrcTy->isIntegerTy(); // Casting from integral 3127 } 3128 if (DestTy->isX86_MMXTy()) { 3129 if (SrcTy->isVectorTy()) 3130 return DestBits == SrcBits; // 64-bit vector to MMX 3131 return false; 3132 } // Casting to something else 3133 return false; 3134 } 3135 3136 bool CastInst::isBitCastable(Type *SrcTy, Type *DestTy) { 3137 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType()) 3138 return false; 3139 3140 if (SrcTy == DestTy) 3141 return true; 3142 3143 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) { 3144 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) { 3145 if (SrcVecTy->getElementCount() == DestVecTy->getElementCount()) { 3146 // An element by element cast. Valid if casting the elements is valid. 3147 SrcTy = SrcVecTy->getElementType(); 3148 DestTy = DestVecTy->getElementType(); 3149 } 3150 } 3151 } 3152 3153 if (PointerType *DestPtrTy = dyn_cast<PointerType>(DestTy)) { 3154 if (PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy)) { 3155 return SrcPtrTy->getAddressSpace() == DestPtrTy->getAddressSpace(); 3156 } 3157 } 3158 3159 TypeSize SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr 3160 TypeSize DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr 3161 3162 // Could still have vectors of pointers if the number of elements doesn't 3163 // match 3164 if (SrcBits.getKnownMinSize() == 0 || DestBits.getKnownMinSize() == 0) 3165 return false; 3166 3167 if (SrcBits != DestBits) 3168 return false; 3169 3170 if (DestTy->isX86_MMXTy() || SrcTy->isX86_MMXTy()) 3171 return false; 3172 3173 return true; 3174 } 3175 3176 bool CastInst::isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy, 3177 const DataLayout &DL) { 3178 // ptrtoint and inttoptr are not allowed on non-integral pointers 3179 if (auto *PtrTy = dyn_cast<PointerType>(SrcTy)) 3180 if (auto *IntTy = dyn_cast<IntegerType>(DestTy)) 3181 return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) && 3182 !DL.isNonIntegralPointerType(PtrTy)); 3183 if (auto *PtrTy = dyn_cast<PointerType>(DestTy)) 3184 if (auto *IntTy = dyn_cast<IntegerType>(SrcTy)) 3185 return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) && 3186 !DL.isNonIntegralPointerType(PtrTy)); 3187 3188 return isBitCastable(SrcTy, DestTy); 3189 } 3190 3191 // Provide a way to get a "cast" where the cast opcode is inferred from the 3192 // types and size of the operand. This, basically, is a parallel of the 3193 // logic in the castIsValid function below. This axiom should hold: 3194 // castIsValid( getCastOpcode(Val, Ty), Val, Ty) 3195 // should not assert in castIsValid. In other words, this produces a "correct" 3196 // casting opcode for the arguments passed to it. 3197 // This routine must be kept in sync with isCastable. 3198 Instruction::CastOps 3199 CastInst::getCastOpcode( 3200 const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) { 3201 Type *SrcTy = Src->getType(); 3202 3203 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() && 3204 "Only first class types are castable!"); 3205 3206 if (SrcTy == DestTy) 3207 return BitCast; 3208 3209 // FIXME: Check address space sizes here 3210 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) 3211 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) 3212 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) { 3213 // An element by element cast. Find the appropriate opcode based on the 3214 // element types. 3215 SrcTy = SrcVecTy->getElementType(); 3216 DestTy = DestVecTy->getElementType(); 3217 } 3218 3219 // Get the bit sizes, we'll need these 3220 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr 3221 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr 3222 3223 // Run through the possibilities ... 3224 if (DestTy->isIntegerTy()) { // Casting to integral 3225 if (SrcTy->isIntegerTy()) { // Casting from integral 3226 if (DestBits < SrcBits) 3227 return Trunc; // int -> smaller int 3228 else if (DestBits > SrcBits) { // its an extension 3229 if (SrcIsSigned) 3230 return SExt; // signed -> SEXT 3231 else 3232 return ZExt; // unsigned -> ZEXT 3233 } else { 3234 return BitCast; // Same size, No-op cast 3235 } 3236 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt 3237 if (DestIsSigned) 3238 return FPToSI; // FP -> sint 3239 else 3240 return FPToUI; // FP -> uint 3241 } else if (SrcTy->isVectorTy()) { 3242 assert(DestBits == SrcBits && 3243 "Casting vector to integer of different width"); 3244 return BitCast; // Same size, no-op cast 3245 } else { 3246 assert(SrcTy->isPointerTy() && 3247 "Casting from a value that is not first-class type"); 3248 return PtrToInt; // ptr -> int 3249 } 3250 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt 3251 if (SrcTy->isIntegerTy()) { // Casting from integral 3252 if (SrcIsSigned) 3253 return SIToFP; // sint -> FP 3254 else 3255 return UIToFP; // uint -> FP 3256 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt 3257 if (DestBits < SrcBits) { 3258 return FPTrunc; // FP -> smaller FP 3259 } else if (DestBits > SrcBits) { 3260 return FPExt; // FP -> larger FP 3261 } else { 3262 return BitCast; // same size, no-op cast 3263 } 3264 } else if (SrcTy->isVectorTy()) { 3265 assert(DestBits == SrcBits && 3266 "Casting vector to floating point of different width"); 3267 return BitCast; // same size, no-op cast 3268 } 3269 llvm_unreachable("Casting pointer or non-first class to float"); 3270 } else if (DestTy->isVectorTy()) { 3271 assert(DestBits == SrcBits && 3272 "Illegal cast to vector (wrong type or size)"); 3273 return BitCast; 3274 } else if (DestTy->isPointerTy()) { 3275 if (SrcTy->isPointerTy()) { 3276 if (DestTy->getPointerAddressSpace() != SrcTy->getPointerAddressSpace()) 3277 return AddrSpaceCast; 3278 return BitCast; // ptr -> ptr 3279 } else if (SrcTy->isIntegerTy()) { 3280 return IntToPtr; // int -> ptr 3281 } 3282 llvm_unreachable("Casting pointer to other than pointer or int"); 3283 } else if (DestTy->isX86_MMXTy()) { 3284 if (SrcTy->isVectorTy()) { 3285 assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX"); 3286 return BitCast; // 64-bit vector to MMX 3287 } 3288 llvm_unreachable("Illegal cast to X86_MMX"); 3289 } 3290 llvm_unreachable("Casting to type that is not first-class"); 3291 } 3292 3293 //===----------------------------------------------------------------------===// 3294 // CastInst SubClass Constructors 3295 //===----------------------------------------------------------------------===// 3296 3297 /// Check that the construction parameters for a CastInst are correct. This 3298 /// could be broken out into the separate constructors but it is useful to have 3299 /// it in one place and to eliminate the redundant code for getting the sizes 3300 /// of the types involved. 3301 bool 3302 CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) { 3303 // Check for type sanity on the arguments 3304 Type *SrcTy = S->getType(); 3305 3306 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() || 3307 SrcTy->isAggregateType() || DstTy->isAggregateType()) 3308 return false; 3309 3310 // Get the size of the types in bits, and whether we are dealing 3311 // with vector types, we'll need this later. 3312 bool SrcIsVec = isa<VectorType>(SrcTy); 3313 bool DstIsVec = isa<VectorType>(DstTy); 3314 unsigned SrcScalarBitSize = SrcTy->getScalarSizeInBits(); 3315 unsigned DstScalarBitSize = DstTy->getScalarSizeInBits(); 3316 3317 // If these are vector types, get the lengths of the vectors (using zero for 3318 // scalar types means that checking that vector lengths match also checks that 3319 // scalars are not being converted to vectors or vectors to scalars). 3320 ElementCount SrcEC = SrcIsVec ? cast<VectorType>(SrcTy)->getElementCount() 3321 : ElementCount(0, false); 3322 ElementCount DstEC = DstIsVec ? cast<VectorType>(DstTy)->getElementCount() 3323 : ElementCount(0, false); 3324 3325 // Switch on the opcode provided 3326 switch (op) { 3327 default: return false; // This is an input error 3328 case Instruction::Trunc: 3329 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() && 3330 SrcEC == DstEC && SrcScalarBitSize > DstScalarBitSize; 3331 case Instruction::ZExt: 3332 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() && 3333 SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize; 3334 case Instruction::SExt: 3335 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() && 3336 SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize; 3337 case Instruction::FPTrunc: 3338 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() && 3339 SrcEC == DstEC && SrcScalarBitSize > DstScalarBitSize; 3340 case Instruction::FPExt: 3341 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() && 3342 SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize; 3343 case Instruction::UIToFP: 3344 case Instruction::SIToFP: 3345 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() && 3346 SrcEC == DstEC; 3347 case Instruction::FPToUI: 3348 case Instruction::FPToSI: 3349 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() && 3350 SrcEC == DstEC; 3351 case Instruction::PtrToInt: 3352 if (SrcEC != DstEC) 3353 return false; 3354 return SrcTy->isPtrOrPtrVectorTy() && DstTy->isIntOrIntVectorTy(); 3355 case Instruction::IntToPtr: 3356 if (SrcEC != DstEC) 3357 return false; 3358 return SrcTy->isIntOrIntVectorTy() && DstTy->isPtrOrPtrVectorTy(); 3359 case Instruction::BitCast: { 3360 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType()); 3361 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType()); 3362 3363 // BitCast implies a no-op cast of type only. No bits change. 3364 // However, you can't cast pointers to anything but pointers. 3365 if (!SrcPtrTy != !DstPtrTy) 3366 return false; 3367 3368 // For non-pointer cases, the cast is okay if the source and destination bit 3369 // widths are identical. 3370 if (!SrcPtrTy) 3371 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits(); 3372 3373 // If both are pointers then the address spaces must match. 3374 if (SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace()) 3375 return false; 3376 3377 // A vector of pointers must have the same number of elements. 3378 if (SrcIsVec && DstIsVec) 3379 return SrcEC == DstEC; 3380 if (SrcIsVec) 3381 return SrcEC == ElementCount(1, false); 3382 if (DstIsVec) 3383 return DstEC == ElementCount(1, false); 3384 3385 return true; 3386 } 3387 case Instruction::AddrSpaceCast: { 3388 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType()); 3389 if (!SrcPtrTy) 3390 return false; 3391 3392 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType()); 3393 if (!DstPtrTy) 3394 return false; 3395 3396 if (SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace()) 3397 return false; 3398 3399 return SrcEC == DstEC; 3400 } 3401 } 3402 } 3403 3404 TruncInst::TruncInst( 3405 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3406 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) { 3407 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc"); 3408 } 3409 3410 TruncInst::TruncInst( 3411 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3412 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) { 3413 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc"); 3414 } 3415 3416 ZExtInst::ZExtInst( 3417 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3418 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) { 3419 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt"); 3420 } 3421 3422 ZExtInst::ZExtInst( 3423 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3424 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) { 3425 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt"); 3426 } 3427 SExtInst::SExtInst( 3428 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3429 ) : CastInst(Ty, SExt, S, Name, InsertBefore) { 3430 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt"); 3431 } 3432 3433 SExtInst::SExtInst( 3434 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3435 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) { 3436 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt"); 3437 } 3438 3439 FPTruncInst::FPTruncInst( 3440 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3441 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) { 3442 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc"); 3443 } 3444 3445 FPTruncInst::FPTruncInst( 3446 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3447 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) { 3448 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc"); 3449 } 3450 3451 FPExtInst::FPExtInst( 3452 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3453 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) { 3454 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt"); 3455 } 3456 3457 FPExtInst::FPExtInst( 3458 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3459 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) { 3460 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt"); 3461 } 3462 3463 UIToFPInst::UIToFPInst( 3464 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3465 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) { 3466 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP"); 3467 } 3468 3469 UIToFPInst::UIToFPInst( 3470 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3471 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) { 3472 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP"); 3473 } 3474 3475 SIToFPInst::SIToFPInst( 3476 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3477 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) { 3478 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP"); 3479 } 3480 3481 SIToFPInst::SIToFPInst( 3482 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3483 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) { 3484 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP"); 3485 } 3486 3487 FPToUIInst::FPToUIInst( 3488 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3489 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) { 3490 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI"); 3491 } 3492 3493 FPToUIInst::FPToUIInst( 3494 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3495 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) { 3496 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI"); 3497 } 3498 3499 FPToSIInst::FPToSIInst( 3500 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3501 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) { 3502 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI"); 3503 } 3504 3505 FPToSIInst::FPToSIInst( 3506 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3507 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) { 3508 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI"); 3509 } 3510 3511 PtrToIntInst::PtrToIntInst( 3512 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3513 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) { 3514 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt"); 3515 } 3516 3517 PtrToIntInst::PtrToIntInst( 3518 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3519 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) { 3520 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt"); 3521 } 3522 3523 IntToPtrInst::IntToPtrInst( 3524 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3525 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) { 3526 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr"); 3527 } 3528 3529 IntToPtrInst::IntToPtrInst( 3530 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3531 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) { 3532 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr"); 3533 } 3534 3535 BitCastInst::BitCastInst( 3536 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3537 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) { 3538 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast"); 3539 } 3540 3541 BitCastInst::BitCastInst( 3542 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3543 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) { 3544 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast"); 3545 } 3546 3547 AddrSpaceCastInst::AddrSpaceCastInst( 3548 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3549 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertBefore) { 3550 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast"); 3551 } 3552 3553 AddrSpaceCastInst::AddrSpaceCastInst( 3554 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3555 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertAtEnd) { 3556 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast"); 3557 } 3558 3559 //===----------------------------------------------------------------------===// 3560 // CmpInst Classes 3561 //===----------------------------------------------------------------------===// 3562 3563 CmpInst::CmpInst(Type *ty, OtherOps op, Predicate predicate, Value *LHS, 3564 Value *RHS, const Twine &Name, Instruction *InsertBefore, 3565 Instruction *FlagsSource) 3566 : Instruction(ty, op, 3567 OperandTraits<CmpInst>::op_begin(this), 3568 OperandTraits<CmpInst>::operands(this), 3569 InsertBefore) { 3570 Op<0>() = LHS; 3571 Op<1>() = RHS; 3572 setPredicate((Predicate)predicate); 3573 setName(Name); 3574 if (FlagsSource) 3575 copyIRFlags(FlagsSource); 3576 } 3577 3578 CmpInst::CmpInst(Type *ty, OtherOps op, Predicate predicate, Value *LHS, 3579 Value *RHS, const Twine &Name, BasicBlock *InsertAtEnd) 3580 : Instruction(ty, op, 3581 OperandTraits<CmpInst>::op_begin(this), 3582 OperandTraits<CmpInst>::operands(this), 3583 InsertAtEnd) { 3584 Op<0>() = LHS; 3585 Op<1>() = RHS; 3586 setPredicate((Predicate)predicate); 3587 setName(Name); 3588 } 3589 3590 CmpInst * 3591 CmpInst::Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2, 3592 const Twine &Name, Instruction *InsertBefore) { 3593 if (Op == Instruction::ICmp) { 3594 if (InsertBefore) 3595 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate), 3596 S1, S2, Name); 3597 else 3598 return new ICmpInst(CmpInst::Predicate(predicate), 3599 S1, S2, Name); 3600 } 3601 3602 if (InsertBefore) 3603 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate), 3604 S1, S2, Name); 3605 else 3606 return new FCmpInst(CmpInst::Predicate(predicate), 3607 S1, S2, Name); 3608 } 3609 3610 CmpInst * 3611 CmpInst::Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2, 3612 const Twine &Name, BasicBlock *InsertAtEnd) { 3613 if (Op == Instruction::ICmp) { 3614 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate), 3615 S1, S2, Name); 3616 } 3617 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate), 3618 S1, S2, Name); 3619 } 3620 3621 void CmpInst::swapOperands() { 3622 if (ICmpInst *IC = dyn_cast<ICmpInst>(this)) 3623 IC->swapOperands(); 3624 else 3625 cast<FCmpInst>(this)->swapOperands(); 3626 } 3627 3628 bool CmpInst::isCommutative() const { 3629 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this)) 3630 return IC->isCommutative(); 3631 return cast<FCmpInst>(this)->isCommutative(); 3632 } 3633 3634 bool CmpInst::isEquality() const { 3635 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this)) 3636 return IC->isEquality(); 3637 return cast<FCmpInst>(this)->isEquality(); 3638 } 3639 3640 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) { 3641 switch (pred) { 3642 default: llvm_unreachable("Unknown cmp predicate!"); 3643 case ICMP_EQ: return ICMP_NE; 3644 case ICMP_NE: return ICMP_EQ; 3645 case ICMP_UGT: return ICMP_ULE; 3646 case ICMP_ULT: return ICMP_UGE; 3647 case ICMP_UGE: return ICMP_ULT; 3648 case ICMP_ULE: return ICMP_UGT; 3649 case ICMP_SGT: return ICMP_SLE; 3650 case ICMP_SLT: return ICMP_SGE; 3651 case ICMP_SGE: return ICMP_SLT; 3652 case ICMP_SLE: return ICMP_SGT; 3653 3654 case FCMP_OEQ: return FCMP_UNE; 3655 case FCMP_ONE: return FCMP_UEQ; 3656 case FCMP_OGT: return FCMP_ULE; 3657 case FCMP_OLT: return FCMP_UGE; 3658 case FCMP_OGE: return FCMP_ULT; 3659 case FCMP_OLE: return FCMP_UGT; 3660 case FCMP_UEQ: return FCMP_ONE; 3661 case FCMP_UNE: return FCMP_OEQ; 3662 case FCMP_UGT: return FCMP_OLE; 3663 case FCMP_ULT: return FCMP_OGE; 3664 case FCMP_UGE: return FCMP_OLT; 3665 case FCMP_ULE: return FCMP_OGT; 3666 case FCMP_ORD: return FCMP_UNO; 3667 case FCMP_UNO: return FCMP_ORD; 3668 case FCMP_TRUE: return FCMP_FALSE; 3669 case FCMP_FALSE: return FCMP_TRUE; 3670 } 3671 } 3672 3673 StringRef CmpInst::getPredicateName(Predicate Pred) { 3674 switch (Pred) { 3675 default: return "unknown"; 3676 case FCmpInst::FCMP_FALSE: return "false"; 3677 case FCmpInst::FCMP_OEQ: return "oeq"; 3678 case FCmpInst::FCMP_OGT: return "ogt"; 3679 case FCmpInst::FCMP_OGE: return "oge"; 3680 case FCmpInst::FCMP_OLT: return "olt"; 3681 case FCmpInst::FCMP_OLE: return "ole"; 3682 case FCmpInst::FCMP_ONE: return "one"; 3683 case FCmpInst::FCMP_ORD: return "ord"; 3684 case FCmpInst::FCMP_UNO: return "uno"; 3685 case FCmpInst::FCMP_UEQ: return "ueq"; 3686 case FCmpInst::FCMP_UGT: return "ugt"; 3687 case FCmpInst::FCMP_UGE: return "uge"; 3688 case FCmpInst::FCMP_ULT: return "ult"; 3689 case FCmpInst::FCMP_ULE: return "ule"; 3690 case FCmpInst::FCMP_UNE: return "une"; 3691 case FCmpInst::FCMP_TRUE: return "true"; 3692 case ICmpInst::ICMP_EQ: return "eq"; 3693 case ICmpInst::ICMP_NE: return "ne"; 3694 case ICmpInst::ICMP_SGT: return "sgt"; 3695 case ICmpInst::ICMP_SGE: return "sge"; 3696 case ICmpInst::ICMP_SLT: return "slt"; 3697 case ICmpInst::ICMP_SLE: return "sle"; 3698 case ICmpInst::ICMP_UGT: return "ugt"; 3699 case ICmpInst::ICMP_UGE: return "uge"; 3700 case ICmpInst::ICMP_ULT: return "ult"; 3701 case ICmpInst::ICMP_ULE: return "ule"; 3702 } 3703 } 3704 3705 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) { 3706 switch (pred) { 3707 default: llvm_unreachable("Unknown icmp predicate!"); 3708 case ICMP_EQ: case ICMP_NE: 3709 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE: 3710 return pred; 3711 case ICMP_UGT: return ICMP_SGT; 3712 case ICMP_ULT: return ICMP_SLT; 3713 case ICMP_UGE: return ICMP_SGE; 3714 case ICMP_ULE: return ICMP_SLE; 3715 } 3716 } 3717 3718 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) { 3719 switch (pred) { 3720 default: llvm_unreachable("Unknown icmp predicate!"); 3721 case ICMP_EQ: case ICMP_NE: 3722 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE: 3723 return pred; 3724 case ICMP_SGT: return ICMP_UGT; 3725 case ICMP_SLT: return ICMP_ULT; 3726 case ICMP_SGE: return ICMP_UGE; 3727 case ICMP_SLE: return ICMP_ULE; 3728 } 3729 } 3730 3731 CmpInst::Predicate CmpInst::getFlippedStrictnessPredicate(Predicate pred) { 3732 switch (pred) { 3733 default: llvm_unreachable("Unknown or unsupported cmp predicate!"); 3734 case ICMP_SGT: return ICMP_SGE; 3735 case ICMP_SLT: return ICMP_SLE; 3736 case ICMP_SGE: return ICMP_SGT; 3737 case ICMP_SLE: return ICMP_SLT; 3738 case ICMP_UGT: return ICMP_UGE; 3739 case ICMP_ULT: return ICMP_ULE; 3740 case ICMP_UGE: return ICMP_UGT; 3741 case ICMP_ULE: return ICMP_ULT; 3742 3743 case FCMP_OGT: return FCMP_OGE; 3744 case FCMP_OLT: return FCMP_OLE; 3745 case FCMP_OGE: return FCMP_OGT; 3746 case FCMP_OLE: return FCMP_OLT; 3747 case FCMP_UGT: return FCMP_UGE; 3748 case FCMP_ULT: return FCMP_ULE; 3749 case FCMP_UGE: return FCMP_UGT; 3750 case FCMP_ULE: return FCMP_ULT; 3751 } 3752 } 3753 3754 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) { 3755 switch (pred) { 3756 default: llvm_unreachable("Unknown cmp predicate!"); 3757 case ICMP_EQ: case ICMP_NE: 3758 return pred; 3759 case ICMP_SGT: return ICMP_SLT; 3760 case ICMP_SLT: return ICMP_SGT; 3761 case ICMP_SGE: return ICMP_SLE; 3762 case ICMP_SLE: return ICMP_SGE; 3763 case ICMP_UGT: return ICMP_ULT; 3764 case ICMP_ULT: return ICMP_UGT; 3765 case ICMP_UGE: return ICMP_ULE; 3766 case ICMP_ULE: return ICMP_UGE; 3767 3768 case FCMP_FALSE: case FCMP_TRUE: 3769 case FCMP_OEQ: case FCMP_ONE: 3770 case FCMP_UEQ: case FCMP_UNE: 3771 case FCMP_ORD: case FCMP_UNO: 3772 return pred; 3773 case FCMP_OGT: return FCMP_OLT; 3774 case FCMP_OLT: return FCMP_OGT; 3775 case FCMP_OGE: return FCMP_OLE; 3776 case FCMP_OLE: return FCMP_OGE; 3777 case FCMP_UGT: return FCMP_ULT; 3778 case FCMP_ULT: return FCMP_UGT; 3779 case FCMP_UGE: return FCMP_ULE; 3780 case FCMP_ULE: return FCMP_UGE; 3781 } 3782 } 3783 3784 CmpInst::Predicate CmpInst::getNonStrictPredicate(Predicate pred) { 3785 switch (pred) { 3786 case ICMP_SGT: return ICMP_SGE; 3787 case ICMP_SLT: return ICMP_SLE; 3788 case ICMP_UGT: return ICMP_UGE; 3789 case ICMP_ULT: return ICMP_ULE; 3790 case FCMP_OGT: return FCMP_OGE; 3791 case FCMP_OLT: return FCMP_OLE; 3792 case FCMP_UGT: return FCMP_UGE; 3793 case FCMP_ULT: return FCMP_ULE; 3794 default: return pred; 3795 } 3796 } 3797 3798 CmpInst::Predicate CmpInst::getSignedPredicate(Predicate pred) { 3799 assert(CmpInst::isUnsigned(pred) && "Call only with signed predicates!"); 3800 3801 switch (pred) { 3802 default: 3803 llvm_unreachable("Unknown predicate!"); 3804 case CmpInst::ICMP_ULT: 3805 return CmpInst::ICMP_SLT; 3806 case CmpInst::ICMP_ULE: 3807 return CmpInst::ICMP_SLE; 3808 case CmpInst::ICMP_UGT: 3809 return CmpInst::ICMP_SGT; 3810 case CmpInst::ICMP_UGE: 3811 return CmpInst::ICMP_SGE; 3812 } 3813 } 3814 3815 bool CmpInst::isUnsigned(Predicate predicate) { 3816 switch (predicate) { 3817 default: return false; 3818 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT: 3819 case ICmpInst::ICMP_UGE: return true; 3820 } 3821 } 3822 3823 bool CmpInst::isSigned(Predicate predicate) { 3824 switch (predicate) { 3825 default: return false; 3826 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT: 3827 case ICmpInst::ICMP_SGE: return true; 3828 } 3829 } 3830 3831 bool CmpInst::isOrdered(Predicate predicate) { 3832 switch (predicate) { 3833 default: return false; 3834 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT: 3835 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE: 3836 case FCmpInst::FCMP_ORD: return true; 3837 } 3838 } 3839 3840 bool CmpInst::isUnordered(Predicate predicate) { 3841 switch (predicate) { 3842 default: return false; 3843 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT: 3844 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE: 3845 case FCmpInst::FCMP_UNO: return true; 3846 } 3847 } 3848 3849 bool CmpInst::isTrueWhenEqual(Predicate predicate) { 3850 switch(predicate) { 3851 default: return false; 3852 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE: 3853 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true; 3854 } 3855 } 3856 3857 bool CmpInst::isFalseWhenEqual(Predicate predicate) { 3858 switch(predicate) { 3859 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT: 3860 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true; 3861 default: return false; 3862 } 3863 } 3864 3865 bool CmpInst::isImpliedTrueByMatchingCmp(Predicate Pred1, Predicate Pred2) { 3866 // If the predicates match, then we know the first condition implies the 3867 // second is true. 3868 if (Pred1 == Pred2) 3869 return true; 3870 3871 switch (Pred1) { 3872 default: 3873 break; 3874 case ICMP_EQ: 3875 // A == B implies A >=u B, A <=u B, A >=s B, and A <=s B are true. 3876 return Pred2 == ICMP_UGE || Pred2 == ICMP_ULE || Pred2 == ICMP_SGE || 3877 Pred2 == ICMP_SLE; 3878 case ICMP_UGT: // A >u B implies A != B and A >=u B are true. 3879 return Pred2 == ICMP_NE || Pred2 == ICMP_UGE; 3880 case ICMP_ULT: // A <u B implies A != B and A <=u B are true. 3881 return Pred2 == ICMP_NE || Pred2 == ICMP_ULE; 3882 case ICMP_SGT: // A >s B implies A != B and A >=s B are true. 3883 return Pred2 == ICMP_NE || Pred2 == ICMP_SGE; 3884 case ICMP_SLT: // A <s B implies A != B and A <=s B are true. 3885 return Pred2 == ICMP_NE || Pred2 == ICMP_SLE; 3886 } 3887 return false; 3888 } 3889 3890 bool CmpInst::isImpliedFalseByMatchingCmp(Predicate Pred1, Predicate Pred2) { 3891 return isImpliedTrueByMatchingCmp(Pred1, getInversePredicate(Pred2)); 3892 } 3893 3894 //===----------------------------------------------------------------------===// 3895 // SwitchInst Implementation 3896 //===----------------------------------------------------------------------===// 3897 3898 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) { 3899 assert(Value && Default && NumReserved); 3900 ReservedSpace = NumReserved; 3901 setNumHungOffUseOperands(2); 3902 allocHungoffUses(ReservedSpace); 3903 3904 Op<0>() = Value; 3905 Op<1>() = Default; 3906 } 3907 3908 /// SwitchInst ctor - Create a new switch instruction, specifying a value to 3909 /// switch on and a default destination. The number of additional cases can 3910 /// be specified here to make memory allocation more efficient. This 3911 /// constructor can also autoinsert before another instruction. 3912 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases, 3913 Instruction *InsertBefore) 3914 : Instruction(Type::getVoidTy(Value->getContext()), Instruction::Switch, 3915 nullptr, 0, InsertBefore) { 3916 init(Value, Default, 2+NumCases*2); 3917 } 3918 3919 /// SwitchInst ctor - Create a new switch instruction, specifying a value to 3920 /// switch on and a default destination. The number of additional cases can 3921 /// be specified here to make memory allocation more efficient. This 3922 /// constructor also autoinserts at the end of the specified BasicBlock. 3923 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases, 3924 BasicBlock *InsertAtEnd) 3925 : Instruction(Type::getVoidTy(Value->getContext()), Instruction::Switch, 3926 nullptr, 0, InsertAtEnd) { 3927 init(Value, Default, 2+NumCases*2); 3928 } 3929 3930 SwitchInst::SwitchInst(const SwitchInst &SI) 3931 : Instruction(SI.getType(), Instruction::Switch, nullptr, 0) { 3932 init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands()); 3933 setNumHungOffUseOperands(SI.getNumOperands()); 3934 Use *OL = getOperandList(); 3935 const Use *InOL = SI.getOperandList(); 3936 for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) { 3937 OL[i] = InOL[i]; 3938 OL[i+1] = InOL[i+1]; 3939 } 3940 SubclassOptionalData = SI.SubclassOptionalData; 3941 } 3942 3943 /// addCase - Add an entry to the switch instruction... 3944 /// 3945 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) { 3946 unsigned NewCaseIdx = getNumCases(); 3947 unsigned OpNo = getNumOperands(); 3948 if (OpNo+2 > ReservedSpace) 3949 growOperands(); // Get more space! 3950 // Initialize some new operands. 3951 assert(OpNo+1 < ReservedSpace && "Growing didn't work!"); 3952 setNumHungOffUseOperands(OpNo+2); 3953 CaseHandle Case(this, NewCaseIdx); 3954 Case.setValue(OnVal); 3955 Case.setSuccessor(Dest); 3956 } 3957 3958 /// removeCase - This method removes the specified case and its successor 3959 /// from the switch instruction. 3960 SwitchInst::CaseIt SwitchInst::removeCase(CaseIt I) { 3961 unsigned idx = I->getCaseIndex(); 3962 3963 assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!"); 3964 3965 unsigned NumOps = getNumOperands(); 3966 Use *OL = getOperandList(); 3967 3968 // Overwrite this case with the end of the list. 3969 if (2 + (idx + 1) * 2 != NumOps) { 3970 OL[2 + idx * 2] = OL[NumOps - 2]; 3971 OL[2 + idx * 2 + 1] = OL[NumOps - 1]; 3972 } 3973 3974 // Nuke the last value. 3975 OL[NumOps-2].set(nullptr); 3976 OL[NumOps-2+1].set(nullptr); 3977 setNumHungOffUseOperands(NumOps-2); 3978 3979 return CaseIt(this, idx); 3980 } 3981 3982 /// growOperands - grow operands - This grows the operand list in response 3983 /// to a push_back style of operation. This grows the number of ops by 3 times. 3984 /// 3985 void SwitchInst::growOperands() { 3986 unsigned e = getNumOperands(); 3987 unsigned NumOps = e*3; 3988 3989 ReservedSpace = NumOps; 3990 growHungoffUses(ReservedSpace); 3991 } 3992 3993 MDNode * 3994 SwitchInstProfUpdateWrapper::getProfBranchWeightsMD(const SwitchInst &SI) { 3995 if (MDNode *ProfileData = SI.getMetadata(LLVMContext::MD_prof)) 3996 if (auto *MDName = dyn_cast<MDString>(ProfileData->getOperand(0))) 3997 if (MDName->getString() == "branch_weights") 3998 return ProfileData; 3999 return nullptr; 4000 } 4001 4002 MDNode *SwitchInstProfUpdateWrapper::buildProfBranchWeightsMD() { 4003 assert(Changed && "called only if metadata has changed"); 4004 4005 if (!Weights) 4006 return nullptr; 4007 4008 assert(SI.getNumSuccessors() == Weights->size() && 4009 "num of prof branch_weights must accord with num of successors"); 4010 4011 bool AllZeroes = 4012 all_of(Weights.getValue(), [](uint32_t W) { return W == 0; }); 4013 4014 if (AllZeroes || Weights.getValue().size() < 2) 4015 return nullptr; 4016 4017 return MDBuilder(SI.getParent()->getContext()).createBranchWeights(*Weights); 4018 } 4019 4020 void SwitchInstProfUpdateWrapper::init() { 4021 MDNode *ProfileData = getProfBranchWeightsMD(SI); 4022 if (!ProfileData) 4023 return; 4024 4025 if (ProfileData->getNumOperands() != SI.getNumSuccessors() + 1) { 4026 llvm_unreachable("number of prof branch_weights metadata operands does " 4027 "not correspond to number of succesors"); 4028 } 4029 4030 SmallVector<uint32_t, 8> Weights; 4031 for (unsigned CI = 1, CE = SI.getNumSuccessors(); CI <= CE; ++CI) { 4032 ConstantInt *C = mdconst::extract<ConstantInt>(ProfileData->getOperand(CI)); 4033 uint32_t CW = C->getValue().getZExtValue(); 4034 Weights.push_back(CW); 4035 } 4036 this->Weights = std::move(Weights); 4037 } 4038 4039 SwitchInst::CaseIt 4040 SwitchInstProfUpdateWrapper::removeCase(SwitchInst::CaseIt I) { 4041 if (Weights) { 4042 assert(SI.getNumSuccessors() == Weights->size() && 4043 "num of prof branch_weights must accord with num of successors"); 4044 Changed = true; 4045 // Copy the last case to the place of the removed one and shrink. 4046 // This is tightly coupled with the way SwitchInst::removeCase() removes 4047 // the cases in SwitchInst::removeCase(CaseIt). 4048 Weights.getValue()[I->getCaseIndex() + 1] = Weights.getValue().back(); 4049 Weights.getValue().pop_back(); 4050 } 4051 return SI.removeCase(I); 4052 } 4053 4054 void SwitchInstProfUpdateWrapper::addCase( 4055 ConstantInt *OnVal, BasicBlock *Dest, 4056 SwitchInstProfUpdateWrapper::CaseWeightOpt W) { 4057 SI.addCase(OnVal, Dest); 4058 4059 if (!Weights && W && *W) { 4060 Changed = true; 4061 Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0); 4062 Weights.getValue()[SI.getNumSuccessors() - 1] = *W; 4063 } else if (Weights) { 4064 Changed = true; 4065 Weights.getValue().push_back(W ? *W : 0); 4066 } 4067 if (Weights) 4068 assert(SI.getNumSuccessors() == Weights->size() && 4069 "num of prof branch_weights must accord with num of successors"); 4070 } 4071 4072 SymbolTableList<Instruction>::iterator 4073 SwitchInstProfUpdateWrapper::eraseFromParent() { 4074 // Instruction is erased. Mark as unchanged to not touch it in the destructor. 4075 Changed = false; 4076 if (Weights) 4077 Weights->resize(0); 4078 return SI.eraseFromParent(); 4079 } 4080 4081 SwitchInstProfUpdateWrapper::CaseWeightOpt 4082 SwitchInstProfUpdateWrapper::getSuccessorWeight(unsigned idx) { 4083 if (!Weights) 4084 return None; 4085 return Weights.getValue()[idx]; 4086 } 4087 4088 void SwitchInstProfUpdateWrapper::setSuccessorWeight( 4089 unsigned idx, SwitchInstProfUpdateWrapper::CaseWeightOpt W) { 4090 if (!W) 4091 return; 4092 4093 if (!Weights && *W) 4094 Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0); 4095 4096 if (Weights) { 4097 auto &OldW = Weights.getValue()[idx]; 4098 if (*W != OldW) { 4099 Changed = true; 4100 OldW = *W; 4101 } 4102 } 4103 } 4104 4105 SwitchInstProfUpdateWrapper::CaseWeightOpt 4106 SwitchInstProfUpdateWrapper::getSuccessorWeight(const SwitchInst &SI, 4107 unsigned idx) { 4108 if (MDNode *ProfileData = getProfBranchWeightsMD(SI)) 4109 if (ProfileData->getNumOperands() == SI.getNumSuccessors() + 1) 4110 return mdconst::extract<ConstantInt>(ProfileData->getOperand(idx + 1)) 4111 ->getValue() 4112 .getZExtValue(); 4113 4114 return None; 4115 } 4116 4117 //===----------------------------------------------------------------------===// 4118 // IndirectBrInst Implementation 4119 //===----------------------------------------------------------------------===// 4120 4121 void IndirectBrInst::init(Value *Address, unsigned NumDests) { 4122 assert(Address && Address->getType()->isPointerTy() && 4123 "Address of indirectbr must be a pointer"); 4124 ReservedSpace = 1+NumDests; 4125 setNumHungOffUseOperands(1); 4126 allocHungoffUses(ReservedSpace); 4127 4128 Op<0>() = Address; 4129 } 4130 4131 4132 /// growOperands - grow operands - This grows the operand list in response 4133 /// to a push_back style of operation. This grows the number of ops by 2 times. 4134 /// 4135 void IndirectBrInst::growOperands() { 4136 unsigned e = getNumOperands(); 4137 unsigned NumOps = e*2; 4138 4139 ReservedSpace = NumOps; 4140 growHungoffUses(ReservedSpace); 4141 } 4142 4143 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases, 4144 Instruction *InsertBefore) 4145 : Instruction(Type::getVoidTy(Address->getContext()), 4146 Instruction::IndirectBr, nullptr, 0, InsertBefore) { 4147 init(Address, NumCases); 4148 } 4149 4150 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases, 4151 BasicBlock *InsertAtEnd) 4152 : Instruction(Type::getVoidTy(Address->getContext()), 4153 Instruction::IndirectBr, nullptr, 0, InsertAtEnd) { 4154 init(Address, NumCases); 4155 } 4156 4157 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI) 4158 : Instruction(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr, 4159 nullptr, IBI.getNumOperands()) { 4160 allocHungoffUses(IBI.getNumOperands()); 4161 Use *OL = getOperandList(); 4162 const Use *InOL = IBI.getOperandList(); 4163 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i) 4164 OL[i] = InOL[i]; 4165 SubclassOptionalData = IBI.SubclassOptionalData; 4166 } 4167 4168 /// addDestination - Add a destination. 4169 /// 4170 void IndirectBrInst::addDestination(BasicBlock *DestBB) { 4171 unsigned OpNo = getNumOperands(); 4172 if (OpNo+1 > ReservedSpace) 4173 growOperands(); // Get more space! 4174 // Initialize some new operands. 4175 assert(OpNo < ReservedSpace && "Growing didn't work!"); 4176 setNumHungOffUseOperands(OpNo+1); 4177 getOperandList()[OpNo] = DestBB; 4178 } 4179 4180 /// removeDestination - This method removes the specified successor from the 4181 /// indirectbr instruction. 4182 void IndirectBrInst::removeDestination(unsigned idx) { 4183 assert(idx < getNumOperands()-1 && "Successor index out of range!"); 4184 4185 unsigned NumOps = getNumOperands(); 4186 Use *OL = getOperandList(); 4187 4188 // Replace this value with the last one. 4189 OL[idx+1] = OL[NumOps-1]; 4190 4191 // Nuke the last value. 4192 OL[NumOps-1].set(nullptr); 4193 setNumHungOffUseOperands(NumOps-1); 4194 } 4195 4196 //===----------------------------------------------------------------------===// 4197 // FreezeInst Implementation 4198 //===----------------------------------------------------------------------===// 4199 4200 FreezeInst::FreezeInst(Value *S, 4201 const Twine &Name, Instruction *InsertBefore) 4202 : UnaryInstruction(S->getType(), Freeze, S, InsertBefore) { 4203 setName(Name); 4204 } 4205 4206 FreezeInst::FreezeInst(Value *S, 4207 const Twine &Name, BasicBlock *InsertAtEnd) 4208 : UnaryInstruction(S->getType(), Freeze, S, InsertAtEnd) { 4209 setName(Name); 4210 } 4211 4212 //===----------------------------------------------------------------------===// 4213 // cloneImpl() implementations 4214 //===----------------------------------------------------------------------===// 4215 4216 // Define these methods here so vtables don't get emitted into every translation 4217 // unit that uses these classes. 4218 4219 GetElementPtrInst *GetElementPtrInst::cloneImpl() const { 4220 return new (getNumOperands()) GetElementPtrInst(*this); 4221 } 4222 4223 UnaryOperator *UnaryOperator::cloneImpl() const { 4224 return Create(getOpcode(), Op<0>()); 4225 } 4226 4227 BinaryOperator *BinaryOperator::cloneImpl() const { 4228 return Create(getOpcode(), Op<0>(), Op<1>()); 4229 } 4230 4231 FCmpInst *FCmpInst::cloneImpl() const { 4232 return new FCmpInst(getPredicate(), Op<0>(), Op<1>()); 4233 } 4234 4235 ICmpInst *ICmpInst::cloneImpl() const { 4236 return new ICmpInst(getPredicate(), Op<0>(), Op<1>()); 4237 } 4238 4239 ExtractValueInst *ExtractValueInst::cloneImpl() const { 4240 return new ExtractValueInst(*this); 4241 } 4242 4243 InsertValueInst *InsertValueInst::cloneImpl() const { 4244 return new InsertValueInst(*this); 4245 } 4246 4247 AllocaInst *AllocaInst::cloneImpl() const { 4248 AllocaInst *Result = 4249 new AllocaInst(getAllocatedType(), getType()->getAddressSpace(), 4250 getOperand(0), getAlign()); 4251 Result->setUsedWithInAlloca(isUsedWithInAlloca()); 4252 Result->setSwiftError(isSwiftError()); 4253 return Result; 4254 } 4255 4256 LoadInst *LoadInst::cloneImpl() const { 4257 return new LoadInst(getType(), getOperand(0), Twine(), isVolatile(), 4258 getAlign(), getOrdering(), getSyncScopeID()); 4259 } 4260 4261 StoreInst *StoreInst::cloneImpl() const { 4262 return new StoreInst(getOperand(0), getOperand(1), isVolatile(), getAlign(), 4263 getOrdering(), getSyncScopeID()); 4264 } 4265 4266 AtomicCmpXchgInst *AtomicCmpXchgInst::cloneImpl() const { 4267 AtomicCmpXchgInst *Result = 4268 new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2), 4269 getSuccessOrdering(), getFailureOrdering(), 4270 getSyncScopeID()); 4271 Result->setVolatile(isVolatile()); 4272 Result->setWeak(isWeak()); 4273 return Result; 4274 } 4275 4276 AtomicRMWInst *AtomicRMWInst::cloneImpl() const { 4277 AtomicRMWInst *Result = 4278 new AtomicRMWInst(getOperation(), getOperand(0), getOperand(1), 4279 getOrdering(), getSyncScopeID()); 4280 Result->setVolatile(isVolatile()); 4281 return Result; 4282 } 4283 4284 FenceInst *FenceInst::cloneImpl() const { 4285 return new FenceInst(getContext(), getOrdering(), getSyncScopeID()); 4286 } 4287 4288 TruncInst *TruncInst::cloneImpl() const { 4289 return new TruncInst(getOperand(0), getType()); 4290 } 4291 4292 ZExtInst *ZExtInst::cloneImpl() const { 4293 return new ZExtInst(getOperand(0), getType()); 4294 } 4295 4296 SExtInst *SExtInst::cloneImpl() const { 4297 return new SExtInst(getOperand(0), getType()); 4298 } 4299 4300 FPTruncInst *FPTruncInst::cloneImpl() const { 4301 return new FPTruncInst(getOperand(0), getType()); 4302 } 4303 4304 FPExtInst *FPExtInst::cloneImpl() const { 4305 return new FPExtInst(getOperand(0), getType()); 4306 } 4307 4308 UIToFPInst *UIToFPInst::cloneImpl() const { 4309 return new UIToFPInst(getOperand(0), getType()); 4310 } 4311 4312 SIToFPInst *SIToFPInst::cloneImpl() const { 4313 return new SIToFPInst(getOperand(0), getType()); 4314 } 4315 4316 FPToUIInst *FPToUIInst::cloneImpl() const { 4317 return new FPToUIInst(getOperand(0), getType()); 4318 } 4319 4320 FPToSIInst *FPToSIInst::cloneImpl() const { 4321 return new FPToSIInst(getOperand(0), getType()); 4322 } 4323 4324 PtrToIntInst *PtrToIntInst::cloneImpl() const { 4325 return new PtrToIntInst(getOperand(0), getType()); 4326 } 4327 4328 IntToPtrInst *IntToPtrInst::cloneImpl() const { 4329 return new IntToPtrInst(getOperand(0), getType()); 4330 } 4331 4332 BitCastInst *BitCastInst::cloneImpl() const { 4333 return new BitCastInst(getOperand(0), getType()); 4334 } 4335 4336 AddrSpaceCastInst *AddrSpaceCastInst::cloneImpl() const { 4337 return new AddrSpaceCastInst(getOperand(0), getType()); 4338 } 4339 4340 CallInst *CallInst::cloneImpl() const { 4341 if (hasOperandBundles()) { 4342 unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo); 4343 return new(getNumOperands(), DescriptorBytes) CallInst(*this); 4344 } 4345 return new(getNumOperands()) CallInst(*this); 4346 } 4347 4348 SelectInst *SelectInst::cloneImpl() const { 4349 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2)); 4350 } 4351 4352 VAArgInst *VAArgInst::cloneImpl() const { 4353 return new VAArgInst(getOperand(0), getType()); 4354 } 4355 4356 ExtractElementInst *ExtractElementInst::cloneImpl() const { 4357 return ExtractElementInst::Create(getOperand(0), getOperand(1)); 4358 } 4359 4360 InsertElementInst *InsertElementInst::cloneImpl() const { 4361 return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2)); 4362 } 4363 4364 ShuffleVectorInst *ShuffleVectorInst::cloneImpl() const { 4365 return new ShuffleVectorInst(getOperand(0), getOperand(1), getShuffleMask()); 4366 } 4367 4368 PHINode *PHINode::cloneImpl() const { return new PHINode(*this); } 4369 4370 LandingPadInst *LandingPadInst::cloneImpl() const { 4371 return new LandingPadInst(*this); 4372 } 4373 4374 ReturnInst *ReturnInst::cloneImpl() const { 4375 return new(getNumOperands()) ReturnInst(*this); 4376 } 4377 4378 BranchInst *BranchInst::cloneImpl() const { 4379 return new(getNumOperands()) BranchInst(*this); 4380 } 4381 4382 SwitchInst *SwitchInst::cloneImpl() const { return new SwitchInst(*this); } 4383 4384 IndirectBrInst *IndirectBrInst::cloneImpl() const { 4385 return new IndirectBrInst(*this); 4386 } 4387 4388 InvokeInst *InvokeInst::cloneImpl() const { 4389 if (hasOperandBundles()) { 4390 unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo); 4391 return new(getNumOperands(), DescriptorBytes) InvokeInst(*this); 4392 } 4393 return new(getNumOperands()) InvokeInst(*this); 4394 } 4395 4396 CallBrInst *CallBrInst::cloneImpl() const { 4397 if (hasOperandBundles()) { 4398 unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo); 4399 return new (getNumOperands(), DescriptorBytes) CallBrInst(*this); 4400 } 4401 return new (getNumOperands()) CallBrInst(*this); 4402 } 4403 4404 ResumeInst *ResumeInst::cloneImpl() const { return new (1) ResumeInst(*this); } 4405 4406 CleanupReturnInst *CleanupReturnInst::cloneImpl() const { 4407 return new (getNumOperands()) CleanupReturnInst(*this); 4408 } 4409 4410 CatchReturnInst *CatchReturnInst::cloneImpl() const { 4411 return new (getNumOperands()) CatchReturnInst(*this); 4412 } 4413 4414 CatchSwitchInst *CatchSwitchInst::cloneImpl() const { 4415 return new CatchSwitchInst(*this); 4416 } 4417 4418 FuncletPadInst *FuncletPadInst::cloneImpl() const { 4419 return new (getNumOperands()) FuncletPadInst(*this); 4420 } 4421 4422 UnreachableInst *UnreachableInst::cloneImpl() const { 4423 LLVMContext &Context = getContext(); 4424 return new UnreachableInst(Context); 4425 } 4426 4427 FreezeInst *FreezeInst::cloneImpl() const { 4428 return new FreezeInst(getOperand(0)); 4429 } 4430