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