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