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