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