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