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