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