Instructions.cpp revision 0a5372ed3e8cda10d724feda3c1a1c998db05ca0
1//===-- Instructions.cpp - Implement the LLVM instructions ----------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements all of the non-inline methods for the LLVM instruction 11// classes. 12// 13//===----------------------------------------------------------------------===// 14 15#include "llvm/Constants.h" 16#include "llvm/DerivedTypes.h" 17#include "llvm/Function.h" 18#include "llvm/Instructions.h" 19#include "llvm/Support/ErrorHandling.h" 20#include "llvm/Support/CallSite.h" 21#include "llvm/Support/ConstantRange.h" 22#include "llvm/Support/MathExtras.h" 23#include "llvm/Support/Streams.h" 24using namespace llvm; 25 26//===----------------------------------------------------------------------===// 27// CallSite Class 28//===----------------------------------------------------------------------===// 29 30#define CALLSITE_DELEGATE_GETTER(METHOD) \ 31 Instruction *II(getInstruction()); \ 32 return isCall() \ 33 ? cast<CallInst>(II)->METHOD \ 34 : cast<InvokeInst>(II)->METHOD 35 36#define CALLSITE_DELEGATE_SETTER(METHOD) \ 37 Instruction *II(getInstruction()); \ 38 if (isCall()) \ 39 cast<CallInst>(II)->METHOD; \ 40 else \ 41 cast<InvokeInst>(II)->METHOD 42 43CallSite::CallSite(Instruction *C) { 44 assert((isa<CallInst>(C) || isa<InvokeInst>(C)) && "Not a call!"); 45 I.setPointer(C); 46 I.setInt(isa<CallInst>(C)); 47} 48unsigned CallSite::getCallingConv() const { 49 CALLSITE_DELEGATE_GETTER(getCallingConv()); 50} 51void CallSite::setCallingConv(unsigned CC) { 52 CALLSITE_DELEGATE_SETTER(setCallingConv(CC)); 53} 54const AttrListPtr &CallSite::getAttributes() const { 55 CALLSITE_DELEGATE_GETTER(getAttributes()); 56} 57void CallSite::setAttributes(const AttrListPtr &PAL) { 58 CALLSITE_DELEGATE_SETTER(setAttributes(PAL)); 59} 60bool CallSite::paramHasAttr(uint16_t i, Attributes attr) const { 61 CALLSITE_DELEGATE_GETTER(paramHasAttr(i, attr)); 62} 63uint16_t CallSite::getParamAlignment(uint16_t i) const { 64 CALLSITE_DELEGATE_GETTER(getParamAlignment(i)); 65} 66bool CallSite::doesNotAccessMemory() const { 67 CALLSITE_DELEGATE_GETTER(doesNotAccessMemory()); 68} 69void CallSite::setDoesNotAccessMemory(bool doesNotAccessMemory) { 70 CALLSITE_DELEGATE_SETTER(setDoesNotAccessMemory(doesNotAccessMemory)); 71} 72bool CallSite::onlyReadsMemory() const { 73 CALLSITE_DELEGATE_GETTER(onlyReadsMemory()); 74} 75void CallSite::setOnlyReadsMemory(bool onlyReadsMemory) { 76 CALLSITE_DELEGATE_SETTER(setOnlyReadsMemory(onlyReadsMemory)); 77} 78bool CallSite::doesNotReturn() const { 79 CALLSITE_DELEGATE_GETTER(doesNotReturn()); 80} 81void CallSite::setDoesNotReturn(bool doesNotReturn) { 82 CALLSITE_DELEGATE_SETTER(setDoesNotReturn(doesNotReturn)); 83} 84bool CallSite::doesNotThrow() const { 85 CALLSITE_DELEGATE_GETTER(doesNotThrow()); 86} 87void CallSite::setDoesNotThrow(bool doesNotThrow) { 88 CALLSITE_DELEGATE_SETTER(setDoesNotThrow(doesNotThrow)); 89} 90 91bool CallSite::hasArgument(const Value *Arg) const { 92 for (arg_iterator AI = this->arg_begin(), E = this->arg_end(); AI != E; ++AI) 93 if (AI->get() == Arg) 94 return true; 95 return false; 96} 97 98#undef CALLSITE_DELEGATE_GETTER 99#undef CALLSITE_DELEGATE_SETTER 100 101//===----------------------------------------------------------------------===// 102// TerminatorInst Class 103//===----------------------------------------------------------------------===// 104 105// Out of line virtual method, so the vtable, etc has a home. 106TerminatorInst::~TerminatorInst() { 107} 108 109//===----------------------------------------------------------------------===// 110// UnaryInstruction Class 111//===----------------------------------------------------------------------===// 112 113// Out of line virtual method, so the vtable, etc has a home. 114UnaryInstruction::~UnaryInstruction() { 115} 116 117//===----------------------------------------------------------------------===// 118// SelectInst Class 119//===----------------------------------------------------------------------===// 120 121/// areInvalidOperands - Return a string if the specified operands are invalid 122/// for a select operation, otherwise return null. 123const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) { 124 if (Op1->getType() != Op2->getType()) 125 return "both values to select must have same type"; 126 127 if (const VectorType *VT = dyn_cast<VectorType>(Op0->getType())) { 128 // Vector select. 129 if (VT->getElementType() != Type::Int1Ty) 130 return "vector select condition element type must be i1"; 131 const VectorType *ET = dyn_cast<VectorType>(Op1->getType()); 132 if (ET == 0) 133 return "selected values for vector select must be vectors"; 134 if (ET->getNumElements() != VT->getNumElements()) 135 return "vector select requires selected vectors to have " 136 "the same vector length as select condition"; 137 } else if (Op0->getType() != Type::Int1Ty) { 138 return "select condition must be i1 or <n x i1>"; 139 } 140 return 0; 141} 142 143 144//===----------------------------------------------------------------------===// 145// PHINode Class 146//===----------------------------------------------------------------------===// 147 148PHINode::PHINode(const PHINode &PN) 149 : Instruction(PN.getType(), Instruction::PHI, 150 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()), 151 ReservedSpace(PN.getNumOperands()) { 152 Use *OL = OperandList; 153 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) { 154 OL[i] = PN.getOperand(i); 155 OL[i+1] = PN.getOperand(i+1); 156 } 157} 158 159PHINode::~PHINode() { 160 if (OperandList) 161 dropHungoffUses(OperandList); 162} 163 164// removeIncomingValue - Remove an incoming value. This is useful if a 165// predecessor basic block is deleted. 166Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) { 167 unsigned NumOps = getNumOperands(); 168 Use *OL = OperandList; 169 assert(Idx*2 < NumOps && "BB not in PHI node!"); 170 Value *Removed = OL[Idx*2]; 171 172 // Move everything after this operand down. 173 // 174 // FIXME: we could just swap with the end of the list, then erase. However, 175 // client might not expect this to happen. The code as it is thrashes the 176 // use/def lists, which is kinda lame. 177 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) { 178 OL[i-2] = OL[i]; 179 OL[i-2+1] = OL[i+1]; 180 } 181 182 // Nuke the last value. 183 OL[NumOps-2].set(0); 184 OL[NumOps-2+1].set(0); 185 NumOperands = NumOps-2; 186 187 // If the PHI node is dead, because it has zero entries, nuke it now. 188 if (NumOps == 2 && DeletePHIIfEmpty) { 189 // If anyone is using this PHI, make them use a dummy value instead... 190 replaceAllUsesWith(UndefValue::get(getType())); 191 eraseFromParent(); 192 } 193 return Removed; 194} 195 196/// resizeOperands - resize operands - This adjusts the length of the operands 197/// list according to the following behavior: 198/// 1. If NumOps == 0, grow the operand list in response to a push_back style 199/// of operation. This grows the number of ops by 1.5 times. 200/// 2. If NumOps > NumOperands, reserve space for NumOps operands. 201/// 3. If NumOps == NumOperands, trim the reserved space. 202/// 203void PHINode::resizeOperands(unsigned NumOps) { 204 unsigned e = getNumOperands(); 205 if (NumOps == 0) { 206 NumOps = e*3/2; 207 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common. 208 } else if (NumOps*2 > NumOperands) { 209 // No resize needed. 210 if (ReservedSpace >= NumOps) return; 211 } else if (NumOps == NumOperands) { 212 if (ReservedSpace == NumOps) return; 213 } else { 214 return; 215 } 216 217 ReservedSpace = NumOps; 218 Use *OldOps = OperandList; 219 Use *NewOps = allocHungoffUses(NumOps); 220 std::copy(OldOps, OldOps + e, NewOps); 221 OperandList = NewOps; 222 if (OldOps) Use::zap(OldOps, OldOps + e, true); 223} 224 225/// hasConstantValue - If the specified PHI node always merges together the same 226/// value, return the value, otherwise return null. 227/// 228Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) const { 229 // If the PHI node only has one incoming value, eliminate the PHI node... 230 if (getNumIncomingValues() == 1) { 231 if (getIncomingValue(0) != this) // not X = phi X 232 return getIncomingValue(0); 233 else 234 return UndefValue::get(getType()); // Self cycle is dead. 235 } 236 237 // Otherwise if all of the incoming values are the same for the PHI, replace 238 // the PHI node with the incoming value. 239 // 240 Value *InVal = 0; 241 bool HasUndefInput = false; 242 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i) 243 if (isa<UndefValue>(getIncomingValue(i))) { 244 HasUndefInput = true; 245 } else if (getIncomingValue(i) != this) { // Not the PHI node itself... 246 if (InVal && getIncomingValue(i) != InVal) 247 return 0; // Not the same, bail out. 248 else 249 InVal = getIncomingValue(i); 250 } 251 252 // The only case that could cause InVal to be null is if we have a PHI node 253 // that only has entries for itself. In this case, there is no entry into the 254 // loop, so kill the PHI. 255 // 256 if (InVal == 0) InVal = UndefValue::get(getType()); 257 258 // If we have a PHI node like phi(X, undef, X), where X is defined by some 259 // instruction, we cannot always return X as the result of the PHI node. Only 260 // do this if X is not an instruction (thus it must dominate the PHI block), 261 // or if the client is prepared to deal with this possibility. 262 if (HasUndefInput && !AllowNonDominatingInstruction) 263 if (Instruction *IV = dyn_cast<Instruction>(InVal)) 264 // If it's in the entry block, it dominates everything. 265 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() || 266 isa<InvokeInst>(IV)) 267 return 0; // Cannot guarantee that InVal dominates this PHINode. 268 269 // All of the incoming values are the same, return the value now. 270 return InVal; 271} 272 273 274//===----------------------------------------------------------------------===// 275// CallInst Implementation 276//===----------------------------------------------------------------------===// 277 278CallInst::~CallInst() { 279} 280 281void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) { 282 assert(NumOperands == NumParams+1 && "NumOperands not set up?"); 283 Use *OL = OperandList; 284 OL[0] = Func; 285 286 const FunctionType *FTy = 287 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType()); 288 FTy = FTy; // silence warning. 289 290 assert((NumParams == FTy->getNumParams() || 291 (FTy->isVarArg() && NumParams > FTy->getNumParams())) && 292 "Calling a function with bad signature!"); 293 for (unsigned i = 0; i != NumParams; ++i) { 294 assert((i >= FTy->getNumParams() || 295 FTy->getParamType(i) == Params[i]->getType()) && 296 "Calling a function with a bad signature!"); 297 OL[i+1] = Params[i]; 298 } 299} 300 301void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) { 302 assert(NumOperands == 3 && "NumOperands not set up?"); 303 Use *OL = OperandList; 304 OL[0] = Func; 305 OL[1] = Actual1; 306 OL[2] = Actual2; 307 308 const FunctionType *FTy = 309 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType()); 310 FTy = FTy; // silence warning. 311 312 assert((FTy->getNumParams() == 2 || 313 (FTy->isVarArg() && FTy->getNumParams() < 2)) && 314 "Calling a function with bad signature"); 315 assert((0 >= FTy->getNumParams() || 316 FTy->getParamType(0) == Actual1->getType()) && 317 "Calling a function with a bad signature!"); 318 assert((1 >= FTy->getNumParams() || 319 FTy->getParamType(1) == Actual2->getType()) && 320 "Calling a function with a bad signature!"); 321} 322 323void CallInst::init(Value *Func, Value *Actual) { 324 assert(NumOperands == 2 && "NumOperands not set up?"); 325 Use *OL = OperandList; 326 OL[0] = Func; 327 OL[1] = Actual; 328 329 const FunctionType *FTy = 330 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType()); 331 FTy = FTy; // silence warning. 332 333 assert((FTy->getNumParams() == 1 || 334 (FTy->isVarArg() && FTy->getNumParams() == 0)) && 335 "Calling a function with bad signature"); 336 assert((0 == FTy->getNumParams() || 337 FTy->getParamType(0) == Actual->getType()) && 338 "Calling a function with a bad signature!"); 339} 340 341void CallInst::init(Value *Func) { 342 assert(NumOperands == 1 && "NumOperands not set up?"); 343 Use *OL = OperandList; 344 OL[0] = Func; 345 346 const FunctionType *FTy = 347 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType()); 348 FTy = FTy; // silence warning. 349 350 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature"); 351} 352 353CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name, 354 Instruction *InsertBefore) 355 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType()) 356 ->getElementType())->getReturnType(), 357 Instruction::Call, 358 OperandTraits<CallInst>::op_end(this) - 2, 359 2, InsertBefore) { 360 init(Func, Actual); 361 setName(Name); 362} 363 364CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name, 365 BasicBlock *InsertAtEnd) 366 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType()) 367 ->getElementType())->getReturnType(), 368 Instruction::Call, 369 OperandTraits<CallInst>::op_end(this) - 2, 370 2, InsertAtEnd) { 371 init(Func, Actual); 372 setName(Name); 373} 374CallInst::CallInst(Value *Func, const std::string &Name, 375 Instruction *InsertBefore) 376 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType()) 377 ->getElementType())->getReturnType(), 378 Instruction::Call, 379 OperandTraits<CallInst>::op_end(this) - 1, 380 1, InsertBefore) { 381 init(Func); 382 setName(Name); 383} 384 385CallInst::CallInst(Value *Func, const std::string &Name, 386 BasicBlock *InsertAtEnd) 387 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType()) 388 ->getElementType())->getReturnType(), 389 Instruction::Call, 390 OperandTraits<CallInst>::op_end(this) - 1, 391 1, InsertAtEnd) { 392 init(Func); 393 setName(Name); 394} 395 396CallInst::CallInst(const CallInst &CI) 397 : Instruction(CI.getType(), Instruction::Call, 398 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(), 399 CI.getNumOperands()) { 400 setAttributes(CI.getAttributes()); 401 SubclassData = CI.SubclassData; 402 Use *OL = OperandList; 403 Use *InOL = CI.OperandList; 404 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i) 405 OL[i] = InOL[i]; 406} 407 408void CallInst::addAttribute(unsigned i, Attributes attr) { 409 AttrListPtr PAL = getAttributes(); 410 PAL = PAL.addAttr(i, attr); 411 setAttributes(PAL); 412} 413 414void CallInst::removeAttribute(unsigned i, Attributes attr) { 415 AttrListPtr PAL = getAttributes(); 416 PAL = PAL.removeAttr(i, attr); 417 setAttributes(PAL); 418} 419 420bool CallInst::paramHasAttr(unsigned i, Attributes attr) const { 421 if (AttributeList.paramHasAttr(i, attr)) 422 return true; 423 if (const Function *F = getCalledFunction()) 424 return F->paramHasAttr(i, attr); 425 return false; 426} 427 428 429//===----------------------------------------------------------------------===// 430// InvokeInst Implementation 431//===----------------------------------------------------------------------===// 432 433void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException, 434 Value* const *Args, unsigned NumArgs) { 435 assert(NumOperands == 3+NumArgs && "NumOperands not set up?"); 436 Use *OL = OperandList; 437 OL[0] = Fn; 438 OL[1] = IfNormal; 439 OL[2] = IfException; 440 const FunctionType *FTy = 441 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType()); 442 FTy = FTy; // silence warning. 443 444 assert(((NumArgs == FTy->getNumParams()) || 445 (FTy->isVarArg() && NumArgs > FTy->getNumParams())) && 446 "Calling a function with bad signature"); 447 448 for (unsigned i = 0, e = NumArgs; i != e; i++) { 449 assert((i >= FTy->getNumParams() || 450 FTy->getParamType(i) == Args[i]->getType()) && 451 "Invoking a function with a bad signature!"); 452 453 OL[i+3] = Args[i]; 454 } 455} 456 457InvokeInst::InvokeInst(const InvokeInst &II) 458 : TerminatorInst(II.getType(), Instruction::Invoke, 459 OperandTraits<InvokeInst>::op_end(this) 460 - II.getNumOperands(), 461 II.getNumOperands()) { 462 setAttributes(II.getAttributes()); 463 SubclassData = II.SubclassData; 464 Use *OL = OperandList, *InOL = II.OperandList; 465 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i) 466 OL[i] = InOL[i]; 467} 468 469BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const { 470 return getSuccessor(idx); 471} 472unsigned InvokeInst::getNumSuccessorsV() const { 473 return getNumSuccessors(); 474} 475void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) { 476 return setSuccessor(idx, B); 477} 478 479bool InvokeInst::paramHasAttr(unsigned i, Attributes attr) const { 480 if (AttributeList.paramHasAttr(i, attr)) 481 return true; 482 if (const Function *F = getCalledFunction()) 483 return F->paramHasAttr(i, attr); 484 return false; 485} 486 487void InvokeInst::addAttribute(unsigned i, Attributes attr) { 488 AttrListPtr PAL = getAttributes(); 489 PAL = PAL.addAttr(i, attr); 490 setAttributes(PAL); 491} 492 493void InvokeInst::removeAttribute(unsigned i, Attributes attr) { 494 AttrListPtr PAL = getAttributes(); 495 PAL = PAL.removeAttr(i, attr); 496 setAttributes(PAL); 497} 498 499 500//===----------------------------------------------------------------------===// 501// ReturnInst Implementation 502//===----------------------------------------------------------------------===// 503 504ReturnInst::ReturnInst(const ReturnInst &RI) 505 : TerminatorInst(Type::VoidTy, Instruction::Ret, 506 OperandTraits<ReturnInst>::op_end(this) - 507 RI.getNumOperands(), 508 RI.getNumOperands()) { 509 if (RI.getNumOperands()) 510 Op<0>() = RI.Op<0>(); 511} 512 513ReturnInst::ReturnInst(Value *retVal, Instruction *InsertBefore) 514 : TerminatorInst(Type::VoidTy, Instruction::Ret, 515 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal, 516 InsertBefore) { 517 if (retVal) 518 Op<0>() = retVal; 519} 520ReturnInst::ReturnInst(Value *retVal, BasicBlock *InsertAtEnd) 521 : TerminatorInst(Type::VoidTy, Instruction::Ret, 522 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal, 523 InsertAtEnd) { 524 if (retVal) 525 Op<0>() = retVal; 526} 527ReturnInst::ReturnInst(BasicBlock *InsertAtEnd) 528 : TerminatorInst(Type::VoidTy, Instruction::Ret, 529 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) { 530} 531 532unsigned ReturnInst::getNumSuccessorsV() const { 533 return getNumSuccessors(); 534} 535 536/// Out-of-line ReturnInst method, put here so the C++ compiler can choose to 537/// emit the vtable for the class in this translation unit. 538void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) { 539 LLVM_UNREACHABLE("ReturnInst has no successors!"); 540} 541 542BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const { 543 LLVM_UNREACHABLE("ReturnInst has no successors!"); 544 return 0; 545} 546 547ReturnInst::~ReturnInst() { 548} 549 550//===----------------------------------------------------------------------===// 551// UnwindInst Implementation 552//===----------------------------------------------------------------------===// 553 554UnwindInst::UnwindInst(Instruction *InsertBefore) 555 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertBefore) { 556} 557UnwindInst::UnwindInst(BasicBlock *InsertAtEnd) 558 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertAtEnd) { 559} 560 561 562unsigned UnwindInst::getNumSuccessorsV() const { 563 return getNumSuccessors(); 564} 565 566void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) { 567 LLVM_UNREACHABLE("UnwindInst has no successors!"); 568} 569 570BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const { 571 LLVM_UNREACHABLE("UnwindInst has no successors!"); 572 return 0; 573} 574 575//===----------------------------------------------------------------------===// 576// UnreachableInst Implementation 577//===----------------------------------------------------------------------===// 578 579UnreachableInst::UnreachableInst(Instruction *InsertBefore) 580 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertBefore) { 581} 582UnreachableInst::UnreachableInst(BasicBlock *InsertAtEnd) 583 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertAtEnd) { 584} 585 586unsigned UnreachableInst::getNumSuccessorsV() const { 587 return getNumSuccessors(); 588} 589 590void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) { 591 LLVM_UNREACHABLE("UnwindInst has no successors!"); 592} 593 594BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const { 595 LLVM_UNREACHABLE("UnwindInst has no successors!"); 596 return 0; 597} 598 599//===----------------------------------------------------------------------===// 600// BranchInst Implementation 601//===----------------------------------------------------------------------===// 602 603void BranchInst::AssertOK() { 604 if (isConditional()) 605 assert(getCondition()->getType() == Type::Int1Ty && 606 "May only branch on boolean predicates!"); 607} 608 609BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore) 610 : TerminatorInst(Type::VoidTy, Instruction::Br, 611 OperandTraits<BranchInst>::op_end(this) - 1, 612 1, InsertBefore) { 613 assert(IfTrue != 0 && "Branch destination may not be null!"); 614 Op<-1>() = IfTrue; 615} 616BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond, 617 Instruction *InsertBefore) 618 : TerminatorInst(Type::VoidTy, Instruction::Br, 619 OperandTraits<BranchInst>::op_end(this) - 3, 620 3, InsertBefore) { 621 Op<-1>() = IfTrue; 622 Op<-2>() = IfFalse; 623 Op<-3>() = Cond; 624#ifndef NDEBUG 625 AssertOK(); 626#endif 627} 628 629BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) 630 : TerminatorInst(Type::VoidTy, Instruction::Br, 631 OperandTraits<BranchInst>::op_end(this) - 1, 632 1, InsertAtEnd) { 633 assert(IfTrue != 0 && "Branch destination may not be null!"); 634 Op<-1>() = IfTrue; 635} 636 637BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond, 638 BasicBlock *InsertAtEnd) 639 : TerminatorInst(Type::VoidTy, Instruction::Br, 640 OperandTraits<BranchInst>::op_end(this) - 3, 641 3, InsertAtEnd) { 642 Op<-1>() = IfTrue; 643 Op<-2>() = IfFalse; 644 Op<-3>() = Cond; 645#ifndef NDEBUG 646 AssertOK(); 647#endif 648} 649 650 651BranchInst::BranchInst(const BranchInst &BI) : 652 TerminatorInst(Type::VoidTy, Instruction::Br, 653 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(), 654 BI.getNumOperands()) { 655 Op<-1>() = BI.Op<-1>(); 656 if (BI.getNumOperands() != 1) { 657 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!"); 658 Op<-3>() = BI.Op<-3>(); 659 Op<-2>() = BI.Op<-2>(); 660 } 661} 662 663 664Use* Use::getPrefix() { 665 PointerIntPair<Use**, 2, PrevPtrTag> &PotentialPrefix(this[-1].Prev); 666 if (PotentialPrefix.getOpaqueValue()) 667 return 0; 668 669 return reinterpret_cast<Use*>((char*)&PotentialPrefix + 1); 670} 671 672BranchInst::~BranchInst() { 673 if (NumOperands == 1) { 674 if (Use *Prefix = OperandList->getPrefix()) { 675 Op<-1>() = 0; 676 // 677 // mark OperandList to have a special value for scrutiny 678 // by baseclass destructors and operator delete 679 OperandList = Prefix; 680 } else { 681 NumOperands = 3; 682 OperandList = op_begin(); 683 } 684 } 685} 686 687 688BasicBlock *BranchInst::getSuccessorV(unsigned idx) const { 689 return getSuccessor(idx); 690} 691unsigned BranchInst::getNumSuccessorsV() const { 692 return getNumSuccessors(); 693} 694void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) { 695 setSuccessor(idx, B); 696} 697 698 699//===----------------------------------------------------------------------===// 700// AllocationInst Implementation 701//===----------------------------------------------------------------------===// 702 703static Value *getAISize(Value *Amt) { 704 if (!Amt) 705 Amt = ConstantInt::get(Type::Int32Ty, 1); 706 else { 707 assert(!isa<BasicBlock>(Amt) && 708 "Passed basic block into allocation size parameter! Use other ctor"); 709 assert(Amt->getType() == Type::Int32Ty && 710 "Malloc/Allocation array size is not a 32-bit integer!"); 711 } 712 return Amt; 713} 714 715AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy, 716 unsigned Align, const std::string &Name, 717 Instruction *InsertBefore) 718 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize), 719 InsertBefore) { 720 setAlignment(Align); 721 assert(Ty != Type::VoidTy && "Cannot allocate void!"); 722 setName(Name); 723} 724 725AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy, 726 unsigned Align, const std::string &Name, 727 BasicBlock *InsertAtEnd) 728 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize), 729 InsertAtEnd) { 730 setAlignment(Align); 731 assert(Ty != Type::VoidTy && "Cannot allocate void!"); 732 setName(Name); 733} 734 735// Out of line virtual method, so the vtable, etc has a home. 736AllocationInst::~AllocationInst() { 737} 738 739void AllocationInst::setAlignment(unsigned Align) { 740 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!"); 741 SubclassData = Log2_32(Align) + 1; 742 assert(getAlignment() == Align && "Alignment representation error!"); 743} 744 745bool AllocationInst::isArrayAllocation() const { 746 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0))) 747 return CI->getZExtValue() != 1; 748 return true; 749} 750 751const Type *AllocationInst::getAllocatedType() const { 752 return getType()->getElementType(); 753} 754 755AllocaInst::AllocaInst(const AllocaInst &AI) 756 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0), 757 Instruction::Alloca, AI.getAlignment()) { 758} 759 760/// isStaticAlloca - Return true if this alloca is in the entry block of the 761/// function and is a constant size. If so, the code generator will fold it 762/// into the prolog/epilog code, so it is basically free. 763bool AllocaInst::isStaticAlloca() const { 764 // Must be constant size. 765 if (!isa<ConstantInt>(getArraySize())) return false; 766 767 // Must be in the entry block. 768 const BasicBlock *Parent = getParent(); 769 return Parent == &Parent->getParent()->front(); 770} 771 772MallocInst::MallocInst(const MallocInst &MI) 773 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0), 774 Instruction::Malloc, MI.getAlignment()) { 775} 776 777//===----------------------------------------------------------------------===// 778// FreeInst Implementation 779//===----------------------------------------------------------------------===// 780 781void FreeInst::AssertOK() { 782 assert(isa<PointerType>(getOperand(0)->getType()) && 783 "Can not free something of nonpointer type!"); 784} 785 786FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore) 787 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertBefore) { 788 AssertOK(); 789} 790 791FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd) 792 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertAtEnd) { 793 AssertOK(); 794} 795 796 797//===----------------------------------------------------------------------===// 798// LoadInst Implementation 799//===----------------------------------------------------------------------===// 800 801void LoadInst::AssertOK() { 802 assert(isa<PointerType>(getOperand(0)->getType()) && 803 "Ptr must have pointer type."); 804} 805 806LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef) 807 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(), 808 Load, Ptr, InsertBef) { 809 setVolatile(false); 810 setAlignment(0); 811 AssertOK(); 812 setName(Name); 813} 814 815LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE) 816 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(), 817 Load, Ptr, InsertAE) { 818 setVolatile(false); 819 setAlignment(0); 820 AssertOK(); 821 setName(Name); 822} 823 824LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile, 825 Instruction *InsertBef) 826 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(), 827 Load, Ptr, InsertBef) { 828 setVolatile(isVolatile); 829 setAlignment(0); 830 AssertOK(); 831 setName(Name); 832} 833 834LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile, 835 unsigned Align, Instruction *InsertBef) 836 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(), 837 Load, Ptr, InsertBef) { 838 setVolatile(isVolatile); 839 setAlignment(Align); 840 AssertOK(); 841 setName(Name); 842} 843 844LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile, 845 unsigned Align, BasicBlock *InsertAE) 846 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(), 847 Load, Ptr, InsertAE) { 848 setVolatile(isVolatile); 849 setAlignment(Align); 850 AssertOK(); 851 setName(Name); 852} 853 854LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile, 855 BasicBlock *InsertAE) 856 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(), 857 Load, Ptr, InsertAE) { 858 setVolatile(isVolatile); 859 setAlignment(0); 860 AssertOK(); 861 setName(Name); 862} 863 864 865 866LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef) 867 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(), 868 Load, Ptr, InsertBef) { 869 setVolatile(false); 870 setAlignment(0); 871 AssertOK(); 872 if (Name && Name[0]) setName(Name); 873} 874 875LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE) 876 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(), 877 Load, Ptr, InsertAE) { 878 setVolatile(false); 879 setAlignment(0); 880 AssertOK(); 881 if (Name && Name[0]) setName(Name); 882} 883 884LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile, 885 Instruction *InsertBef) 886: UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(), 887 Load, Ptr, InsertBef) { 888 setVolatile(isVolatile); 889 setAlignment(0); 890 AssertOK(); 891 if (Name && Name[0]) setName(Name); 892} 893 894LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile, 895 BasicBlock *InsertAE) 896 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(), 897 Load, Ptr, InsertAE) { 898 setVolatile(isVolatile); 899 setAlignment(0); 900 AssertOK(); 901 if (Name && Name[0]) setName(Name); 902} 903 904void LoadInst::setAlignment(unsigned Align) { 905 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!"); 906 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1); 907} 908 909//===----------------------------------------------------------------------===// 910// StoreInst Implementation 911//===----------------------------------------------------------------------===// 912 913void StoreInst::AssertOK() { 914 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!"); 915 assert(isa<PointerType>(getOperand(1)->getType()) && 916 "Ptr must have pointer type!"); 917 assert(getOperand(0)->getType() == 918 cast<PointerType>(getOperand(1)->getType())->getElementType() 919 && "Ptr must be a pointer to Val type!"); 920} 921 922 923StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore) 924 : Instruction(Type::VoidTy, Store, 925 OperandTraits<StoreInst>::op_begin(this), 926 OperandTraits<StoreInst>::operands(this), 927 InsertBefore) { 928 Op<0>() = val; 929 Op<1>() = addr; 930 setVolatile(false); 931 setAlignment(0); 932 AssertOK(); 933} 934 935StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd) 936 : Instruction(Type::VoidTy, Store, 937 OperandTraits<StoreInst>::op_begin(this), 938 OperandTraits<StoreInst>::operands(this), 939 InsertAtEnd) { 940 Op<0>() = val; 941 Op<1>() = addr; 942 setVolatile(false); 943 setAlignment(0); 944 AssertOK(); 945} 946 947StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, 948 Instruction *InsertBefore) 949 : Instruction(Type::VoidTy, Store, 950 OperandTraits<StoreInst>::op_begin(this), 951 OperandTraits<StoreInst>::operands(this), 952 InsertBefore) { 953 Op<0>() = val; 954 Op<1>() = addr; 955 setVolatile(isVolatile); 956 setAlignment(0); 957 AssertOK(); 958} 959 960StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, 961 unsigned Align, Instruction *InsertBefore) 962 : Instruction(Type::VoidTy, Store, 963 OperandTraits<StoreInst>::op_begin(this), 964 OperandTraits<StoreInst>::operands(this), 965 InsertBefore) { 966 Op<0>() = val; 967 Op<1>() = addr; 968 setVolatile(isVolatile); 969 setAlignment(Align); 970 AssertOK(); 971} 972 973StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, 974 unsigned Align, BasicBlock *InsertAtEnd) 975 : Instruction(Type::VoidTy, Store, 976 OperandTraits<StoreInst>::op_begin(this), 977 OperandTraits<StoreInst>::operands(this), 978 InsertAtEnd) { 979 Op<0>() = val; 980 Op<1>() = addr; 981 setVolatile(isVolatile); 982 setAlignment(Align); 983 AssertOK(); 984} 985 986StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, 987 BasicBlock *InsertAtEnd) 988 : Instruction(Type::VoidTy, Store, 989 OperandTraits<StoreInst>::op_begin(this), 990 OperandTraits<StoreInst>::operands(this), 991 InsertAtEnd) { 992 Op<0>() = val; 993 Op<1>() = addr; 994 setVolatile(isVolatile); 995 setAlignment(0); 996 AssertOK(); 997} 998 999void StoreInst::setAlignment(unsigned Align) { 1000 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!"); 1001 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1); 1002} 1003 1004//===----------------------------------------------------------------------===// 1005// GetElementPtrInst Implementation 1006//===----------------------------------------------------------------------===// 1007 1008static unsigned retrieveAddrSpace(const Value *Val) { 1009 return cast<PointerType>(Val->getType())->getAddressSpace(); 1010} 1011 1012void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx, 1013 const std::string &Name) { 1014 assert(NumOperands == 1+NumIdx && "NumOperands not initialized?"); 1015 Use *OL = OperandList; 1016 OL[0] = Ptr; 1017 1018 for (unsigned i = 0; i != NumIdx; ++i) 1019 OL[i+1] = Idx[i]; 1020 1021 setName(Name); 1022} 1023 1024void GetElementPtrInst::init(Value *Ptr, Value *Idx, const std::string &Name) { 1025 assert(NumOperands == 2 && "NumOperands not initialized?"); 1026 Use *OL = OperandList; 1027 OL[0] = Ptr; 1028 OL[1] = Idx; 1029 1030 setName(Name); 1031} 1032 1033GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI) 1034 : Instruction(GEPI.getType(), GetElementPtr, 1035 OperandTraits<GetElementPtrInst>::op_end(this) 1036 - GEPI.getNumOperands(), 1037 GEPI.getNumOperands()) { 1038 Use *OL = OperandList; 1039 Use *GEPIOL = GEPI.OperandList; 1040 for (unsigned i = 0, E = NumOperands; i != E; ++i) 1041 OL[i] = GEPIOL[i]; 1042} 1043 1044GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx, 1045 const std::string &Name, Instruction *InBe) 1046 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)), 1047 retrieveAddrSpace(Ptr)), 1048 GetElementPtr, 1049 OperandTraits<GetElementPtrInst>::op_end(this) - 2, 1050 2, InBe) { 1051 init(Ptr, Idx, Name); 1052} 1053 1054GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx, 1055 const std::string &Name, BasicBlock *IAE) 1056 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)), 1057 retrieveAddrSpace(Ptr)), 1058 GetElementPtr, 1059 OperandTraits<GetElementPtrInst>::op_end(this) - 2, 1060 2, IAE) { 1061 init(Ptr, Idx, Name); 1062} 1063 1064/// getIndexedType - Returns the type of the element that would be accessed with 1065/// a gep instruction with the specified parameters. 1066/// 1067/// The Idxs pointer should point to a continuous piece of memory containing the 1068/// indices, either as Value* or uint64_t. 1069/// 1070/// A null type is returned if the indices are invalid for the specified 1071/// pointer type. 1072/// 1073template <typename IndexTy> 1074static const Type* getIndexedTypeInternal(const Type *Ptr, IndexTy const *Idxs, 1075 unsigned NumIdx) { 1076 const PointerType *PTy = dyn_cast<PointerType>(Ptr); 1077 if (!PTy) return 0; // Type isn't a pointer type! 1078 const Type *Agg = PTy->getElementType(); 1079 1080 // Handle the special case of the empty set index set, which is always valid. 1081 if (NumIdx == 0) 1082 return Agg; 1083 1084 // If there is at least one index, the top level type must be sized, otherwise 1085 // it cannot be 'stepped over'. We explicitly allow abstract types (those 1086 // that contain opaque types) under the assumption that it will be resolved to 1087 // a sane type later. 1088 if (!Agg->isSized() && !Agg->isAbstract()) 1089 return 0; 1090 1091 unsigned CurIdx = 1; 1092 for (; CurIdx != NumIdx; ++CurIdx) { 1093 const CompositeType *CT = dyn_cast<CompositeType>(Agg); 1094 if (!CT || isa<PointerType>(CT)) return 0; 1095 IndexTy Index = Idxs[CurIdx]; 1096 if (!CT->indexValid(Index)) return 0; 1097 Agg = CT->getTypeAtIndex(Index); 1098 1099 // If the new type forwards to another type, then it is in the middle 1100 // of being refined to another type (and hence, may have dropped all 1101 // references to what it was using before). So, use the new forwarded 1102 // type. 1103 if (const Type *Ty = Agg->getForwardedType()) 1104 Agg = Ty; 1105 } 1106 return CurIdx == NumIdx ? Agg : 0; 1107} 1108 1109const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, 1110 Value* const *Idxs, 1111 unsigned NumIdx) { 1112 return getIndexedTypeInternal(Ptr, Idxs, NumIdx); 1113} 1114 1115const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, 1116 uint64_t const *Idxs, 1117 unsigned NumIdx) { 1118 return getIndexedTypeInternal(Ptr, Idxs, NumIdx); 1119} 1120 1121const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) { 1122 const PointerType *PTy = dyn_cast<PointerType>(Ptr); 1123 if (!PTy) return 0; // Type isn't a pointer type! 1124 1125 // Check the pointer index. 1126 if (!PTy->indexValid(Idx)) return 0; 1127 1128 return PTy->getElementType(); 1129} 1130 1131 1132/// hasAllZeroIndices - Return true if all of the indices of this GEP are 1133/// zeros. If so, the result pointer and the first operand have the same 1134/// value, just potentially different types. 1135bool GetElementPtrInst::hasAllZeroIndices() const { 1136 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1137 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) { 1138 if (!CI->isZero()) return false; 1139 } else { 1140 return false; 1141 } 1142 } 1143 return true; 1144} 1145 1146/// hasAllConstantIndices - Return true if all of the indices of this GEP are 1147/// constant integers. If so, the result pointer and the first operand have 1148/// a constant offset between them. 1149bool GetElementPtrInst::hasAllConstantIndices() const { 1150 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1151 if (!isa<ConstantInt>(getOperand(i))) 1152 return false; 1153 } 1154 return true; 1155} 1156 1157 1158//===----------------------------------------------------------------------===// 1159// ExtractElementInst Implementation 1160//===----------------------------------------------------------------------===// 1161 1162ExtractElementInst::ExtractElementInst(Value *Val, Value *Index, 1163 const std::string &Name, 1164 Instruction *InsertBef) 1165 : Instruction(cast<VectorType>(Val->getType())->getElementType(), 1166 ExtractElement, 1167 OperandTraits<ExtractElementInst>::op_begin(this), 1168 2, InsertBef) { 1169 assert(isValidOperands(Val, Index) && 1170 "Invalid extractelement instruction operands!"); 1171 Op<0>() = Val; 1172 Op<1>() = Index; 1173 setName(Name); 1174} 1175 1176ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV, 1177 const std::string &Name, 1178 Instruction *InsertBef) 1179 : Instruction(cast<VectorType>(Val->getType())->getElementType(), 1180 ExtractElement, 1181 OperandTraits<ExtractElementInst>::op_begin(this), 1182 2, InsertBef) { 1183 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV); 1184 assert(isValidOperands(Val, Index) && 1185 "Invalid extractelement instruction operands!"); 1186 Op<0>() = Val; 1187 Op<1>() = Index; 1188 setName(Name); 1189} 1190 1191 1192ExtractElementInst::ExtractElementInst(Value *Val, Value *Index, 1193 const std::string &Name, 1194 BasicBlock *InsertAE) 1195 : Instruction(cast<VectorType>(Val->getType())->getElementType(), 1196 ExtractElement, 1197 OperandTraits<ExtractElementInst>::op_begin(this), 1198 2, InsertAE) { 1199 assert(isValidOperands(Val, Index) && 1200 "Invalid extractelement instruction operands!"); 1201 1202 Op<0>() = Val; 1203 Op<1>() = Index; 1204 setName(Name); 1205} 1206 1207ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV, 1208 const std::string &Name, 1209 BasicBlock *InsertAE) 1210 : Instruction(cast<VectorType>(Val->getType())->getElementType(), 1211 ExtractElement, 1212 OperandTraits<ExtractElementInst>::op_begin(this), 1213 2, InsertAE) { 1214 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV); 1215 assert(isValidOperands(Val, Index) && 1216 "Invalid extractelement instruction operands!"); 1217 1218 Op<0>() = Val; 1219 Op<1>() = Index; 1220 setName(Name); 1221} 1222 1223 1224bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) { 1225 if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty) 1226 return false; 1227 return true; 1228} 1229 1230 1231//===----------------------------------------------------------------------===// 1232// InsertElementInst Implementation 1233//===----------------------------------------------------------------------===// 1234 1235InsertElementInst::InsertElementInst(const InsertElementInst &IE) 1236 : Instruction(IE.getType(), InsertElement, 1237 OperandTraits<InsertElementInst>::op_begin(this), 3) { 1238 Op<0>() = IE.Op<0>(); 1239 Op<1>() = IE.Op<1>(); 1240 Op<2>() = IE.Op<2>(); 1241} 1242InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index, 1243 const std::string &Name, 1244 Instruction *InsertBef) 1245 : Instruction(Vec->getType(), InsertElement, 1246 OperandTraits<InsertElementInst>::op_begin(this), 1247 3, InsertBef) { 1248 assert(isValidOperands(Vec, Elt, Index) && 1249 "Invalid insertelement instruction operands!"); 1250 Op<0>() = Vec; 1251 Op<1>() = Elt; 1252 Op<2>() = Index; 1253 setName(Name); 1254} 1255 1256InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV, 1257 const std::string &Name, 1258 Instruction *InsertBef) 1259 : Instruction(Vec->getType(), InsertElement, 1260 OperandTraits<InsertElementInst>::op_begin(this), 1261 3, InsertBef) { 1262 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV); 1263 assert(isValidOperands(Vec, Elt, Index) && 1264 "Invalid insertelement instruction operands!"); 1265 Op<0>() = Vec; 1266 Op<1>() = Elt; 1267 Op<2>() = Index; 1268 setName(Name); 1269} 1270 1271 1272InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index, 1273 const std::string &Name, 1274 BasicBlock *InsertAE) 1275 : Instruction(Vec->getType(), InsertElement, 1276 OperandTraits<InsertElementInst>::op_begin(this), 1277 3, InsertAE) { 1278 assert(isValidOperands(Vec, Elt, Index) && 1279 "Invalid insertelement instruction operands!"); 1280 1281 Op<0>() = Vec; 1282 Op<1>() = Elt; 1283 Op<2>() = Index; 1284 setName(Name); 1285} 1286 1287InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV, 1288 const std::string &Name, 1289 BasicBlock *InsertAE) 1290: Instruction(Vec->getType(), InsertElement, 1291 OperandTraits<InsertElementInst>::op_begin(this), 1292 3, InsertAE) { 1293 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV); 1294 assert(isValidOperands(Vec, Elt, Index) && 1295 "Invalid insertelement instruction operands!"); 1296 1297 Op<0>() = Vec; 1298 Op<1>() = Elt; 1299 Op<2>() = Index; 1300 setName(Name); 1301} 1302 1303bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt, 1304 const Value *Index) { 1305 if (!isa<VectorType>(Vec->getType())) 1306 return false; // First operand of insertelement must be vector type. 1307 1308 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType()) 1309 return false;// Second operand of insertelement must be vector element type. 1310 1311 if (Index->getType() != Type::Int32Ty) 1312 return false; // Third operand of insertelement must be i32. 1313 return true; 1314} 1315 1316 1317//===----------------------------------------------------------------------===// 1318// ShuffleVectorInst Implementation 1319//===----------------------------------------------------------------------===// 1320 1321ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV) 1322 : Instruction(SV.getType(), ShuffleVector, 1323 OperandTraits<ShuffleVectorInst>::op_begin(this), 1324 OperandTraits<ShuffleVectorInst>::operands(this)) { 1325 Op<0>() = SV.Op<0>(); 1326 Op<1>() = SV.Op<1>(); 1327 Op<2>() = SV.Op<2>(); 1328} 1329 1330ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask, 1331 const std::string &Name, 1332 Instruction *InsertBefore) 1333: Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(), 1334 cast<VectorType>(Mask->getType())->getNumElements()), 1335 ShuffleVector, 1336 OperandTraits<ShuffleVectorInst>::op_begin(this), 1337 OperandTraits<ShuffleVectorInst>::operands(this), 1338 InsertBefore) { 1339 assert(isValidOperands(V1, V2, Mask) && 1340 "Invalid shuffle vector instruction operands!"); 1341 Op<0>() = V1; 1342 Op<1>() = V2; 1343 Op<2>() = Mask; 1344 setName(Name); 1345} 1346 1347ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask, 1348 const std::string &Name, 1349 BasicBlock *InsertAtEnd) 1350 : Instruction(V1->getType(), ShuffleVector, 1351 OperandTraits<ShuffleVectorInst>::op_begin(this), 1352 OperandTraits<ShuffleVectorInst>::operands(this), 1353 InsertAtEnd) { 1354 assert(isValidOperands(V1, V2, Mask) && 1355 "Invalid shuffle vector instruction operands!"); 1356 1357 Op<0>() = V1; 1358 Op<1>() = V2; 1359 Op<2>() = Mask; 1360 setName(Name); 1361} 1362 1363bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2, 1364 const Value *Mask) { 1365 if (!isa<VectorType>(V1->getType()) || V1->getType() != V2->getType()) 1366 return false; 1367 1368 const VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType()); 1369 if (!isa<Constant>(Mask) || MaskTy == 0 || 1370 MaskTy->getElementType() != Type::Int32Ty) 1371 return false; 1372 return true; 1373} 1374 1375/// getMaskValue - Return the index from the shuffle mask for the specified 1376/// output result. This is either -1 if the element is undef or a number less 1377/// than 2*numelements. 1378int ShuffleVectorInst::getMaskValue(unsigned i) const { 1379 const Constant *Mask = cast<Constant>(getOperand(2)); 1380 if (isa<UndefValue>(Mask)) return -1; 1381 if (isa<ConstantAggregateZero>(Mask)) return 0; 1382 const ConstantVector *MaskCV = cast<ConstantVector>(Mask); 1383 assert(i < MaskCV->getNumOperands() && "Index out of range"); 1384 1385 if (isa<UndefValue>(MaskCV->getOperand(i))) 1386 return -1; 1387 return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue(); 1388} 1389 1390//===----------------------------------------------------------------------===// 1391// InsertValueInst Class 1392//===----------------------------------------------------------------------===// 1393 1394void InsertValueInst::init(Value *Agg, Value *Val, const unsigned *Idx, 1395 unsigned NumIdx, const std::string &Name) { 1396 assert(NumOperands == 2 && "NumOperands not initialized?"); 1397 Op<0>() = Agg; 1398 Op<1>() = Val; 1399 1400 Indices.insert(Indices.end(), Idx, Idx + NumIdx); 1401 setName(Name); 1402} 1403 1404void InsertValueInst::init(Value *Agg, Value *Val, unsigned Idx, 1405 const std::string &Name) { 1406 assert(NumOperands == 2 && "NumOperands not initialized?"); 1407 Op<0>() = Agg; 1408 Op<1>() = Val; 1409 1410 Indices.push_back(Idx); 1411 setName(Name); 1412} 1413 1414InsertValueInst::InsertValueInst(const InsertValueInst &IVI) 1415 : Instruction(IVI.getType(), InsertValue, 1416 OperandTraits<InsertValueInst>::op_begin(this), 2), 1417 Indices(IVI.Indices) { 1418 Op<0>() = IVI.getOperand(0); 1419 Op<1>() = IVI.getOperand(1); 1420} 1421 1422InsertValueInst::InsertValueInst(Value *Agg, 1423 Value *Val, 1424 unsigned Idx, 1425 const std::string &Name, 1426 Instruction *InsertBefore) 1427 : Instruction(Agg->getType(), InsertValue, 1428 OperandTraits<InsertValueInst>::op_begin(this), 1429 2, InsertBefore) { 1430 init(Agg, Val, Idx, Name); 1431} 1432 1433InsertValueInst::InsertValueInst(Value *Agg, 1434 Value *Val, 1435 unsigned Idx, 1436 const std::string &Name, 1437 BasicBlock *InsertAtEnd) 1438 : Instruction(Agg->getType(), InsertValue, 1439 OperandTraits<InsertValueInst>::op_begin(this), 1440 2, InsertAtEnd) { 1441 init(Agg, Val, Idx, Name); 1442} 1443 1444//===----------------------------------------------------------------------===// 1445// ExtractValueInst Class 1446//===----------------------------------------------------------------------===// 1447 1448void ExtractValueInst::init(const unsigned *Idx, unsigned NumIdx, 1449 const std::string &Name) { 1450 assert(NumOperands == 1 && "NumOperands not initialized?"); 1451 1452 Indices.insert(Indices.end(), Idx, Idx + NumIdx); 1453 setName(Name); 1454} 1455 1456void ExtractValueInst::init(unsigned Idx, const std::string &Name) { 1457 assert(NumOperands == 1 && "NumOperands not initialized?"); 1458 1459 Indices.push_back(Idx); 1460 setName(Name); 1461} 1462 1463ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI) 1464 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)), 1465 Indices(EVI.Indices) { 1466} 1467 1468// getIndexedType - Returns the type of the element that would be extracted 1469// with an extractvalue instruction with the specified parameters. 1470// 1471// A null type is returned if the indices are invalid for the specified 1472// pointer type. 1473// 1474const Type* ExtractValueInst::getIndexedType(const Type *Agg, 1475 const unsigned *Idxs, 1476 unsigned NumIdx) { 1477 unsigned CurIdx = 0; 1478 for (; CurIdx != NumIdx; ++CurIdx) { 1479 const CompositeType *CT = dyn_cast<CompositeType>(Agg); 1480 if (!CT || isa<PointerType>(CT) || isa<VectorType>(CT)) return 0; 1481 unsigned Index = Idxs[CurIdx]; 1482 if (!CT->indexValid(Index)) return 0; 1483 Agg = CT->getTypeAtIndex(Index); 1484 1485 // If the new type forwards to another type, then it is in the middle 1486 // of being refined to another type (and hence, may have dropped all 1487 // references to what it was using before). So, use the new forwarded 1488 // type. 1489 if (const Type *Ty = Agg->getForwardedType()) 1490 Agg = Ty; 1491 } 1492 return CurIdx == NumIdx ? Agg : 0; 1493} 1494 1495const Type* ExtractValueInst::getIndexedType(const Type *Agg, 1496 unsigned Idx) { 1497 return getIndexedType(Agg, &Idx, 1); 1498} 1499 1500//===----------------------------------------------------------------------===// 1501// BinaryOperator Class 1502//===----------------------------------------------------------------------===// 1503 1504/// AdjustIType - Map Add, Sub, and Mul to FAdd, FSub, and FMul when the 1505/// type is floating-point, to help provide compatibility with an older API. 1506/// 1507static BinaryOperator::BinaryOps AdjustIType(BinaryOperator::BinaryOps iType, 1508 const Type *Ty) { 1509 // API compatibility: Adjust integer opcodes to floating-point opcodes. 1510 if (Ty->isFPOrFPVector()) { 1511 if (iType == BinaryOperator::Add) iType = BinaryOperator::FAdd; 1512 else if (iType == BinaryOperator::Sub) iType = BinaryOperator::FSub; 1513 else if (iType == BinaryOperator::Mul) iType = BinaryOperator::FMul; 1514 } 1515 return iType; 1516} 1517 1518BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2, 1519 const Type *Ty, const std::string &Name, 1520 Instruction *InsertBefore) 1521 : Instruction(Ty, AdjustIType(iType, Ty), 1522 OperandTraits<BinaryOperator>::op_begin(this), 1523 OperandTraits<BinaryOperator>::operands(this), 1524 InsertBefore) { 1525 Op<0>() = S1; 1526 Op<1>() = S2; 1527 init(AdjustIType(iType, Ty)); 1528 setName(Name); 1529} 1530 1531BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2, 1532 const Type *Ty, const std::string &Name, 1533 BasicBlock *InsertAtEnd) 1534 : Instruction(Ty, AdjustIType(iType, Ty), 1535 OperandTraits<BinaryOperator>::op_begin(this), 1536 OperandTraits<BinaryOperator>::operands(this), 1537 InsertAtEnd) { 1538 Op<0>() = S1; 1539 Op<1>() = S2; 1540 init(AdjustIType(iType, Ty)); 1541 setName(Name); 1542} 1543 1544 1545void BinaryOperator::init(BinaryOps iType) { 1546 Value *LHS = getOperand(0), *RHS = getOperand(1); 1547 LHS = LHS; RHS = RHS; // Silence warnings. 1548 assert(LHS->getType() == RHS->getType() && 1549 "Binary operator operand types must match!"); 1550#ifndef NDEBUG 1551 switch (iType) { 1552 case Add: case Sub: 1553 case Mul: 1554 assert(getType() == LHS->getType() && 1555 "Arithmetic operation should return same type as operands!"); 1556 assert(getType()->isIntOrIntVector() && 1557 "Tried to create an integer operation on a non-integer type!"); 1558 break; 1559 case FAdd: case FSub: 1560 case FMul: 1561 assert(getType() == LHS->getType() && 1562 "Arithmetic operation should return same type as operands!"); 1563 assert(getType()->isFPOrFPVector() && 1564 "Tried to create a floating-point operation on a " 1565 "non-floating-point type!"); 1566 break; 1567 case UDiv: 1568 case SDiv: 1569 assert(getType() == LHS->getType() && 1570 "Arithmetic operation should return same type as operands!"); 1571 assert((getType()->isInteger() || (isa<VectorType>(getType()) && 1572 cast<VectorType>(getType())->getElementType()->isInteger())) && 1573 "Incorrect operand type (not integer) for S/UDIV"); 1574 break; 1575 case FDiv: 1576 assert(getType() == LHS->getType() && 1577 "Arithmetic operation should return same type as operands!"); 1578 assert(getType()->isFPOrFPVector() && 1579 "Incorrect operand type (not floating point) for FDIV"); 1580 break; 1581 case URem: 1582 case SRem: 1583 assert(getType() == LHS->getType() && 1584 "Arithmetic operation should return same type as operands!"); 1585 assert((getType()->isInteger() || (isa<VectorType>(getType()) && 1586 cast<VectorType>(getType())->getElementType()->isInteger())) && 1587 "Incorrect operand type (not integer) for S/UREM"); 1588 break; 1589 case FRem: 1590 assert(getType() == LHS->getType() && 1591 "Arithmetic operation should return same type as operands!"); 1592 assert(getType()->isFPOrFPVector() && 1593 "Incorrect operand type (not floating point) for FREM"); 1594 break; 1595 case Shl: 1596 case LShr: 1597 case AShr: 1598 assert(getType() == LHS->getType() && 1599 "Shift operation should return same type as operands!"); 1600 assert((getType()->isInteger() || 1601 (isa<VectorType>(getType()) && 1602 cast<VectorType>(getType())->getElementType()->isInteger())) && 1603 "Tried to create a shift operation on a non-integral type!"); 1604 break; 1605 case And: case Or: 1606 case Xor: 1607 assert(getType() == LHS->getType() && 1608 "Logical operation should return same type as operands!"); 1609 assert((getType()->isInteger() || 1610 (isa<VectorType>(getType()) && 1611 cast<VectorType>(getType())->getElementType()->isInteger())) && 1612 "Tried to create a logical operation on a non-integral type!"); 1613 break; 1614 default: 1615 break; 1616 } 1617#endif 1618} 1619 1620BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2, 1621 const std::string &Name, 1622 Instruction *InsertBefore) { 1623 assert(S1->getType() == S2->getType() && 1624 "Cannot create binary operator with two operands of differing type!"); 1625 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore); 1626} 1627 1628BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2, 1629 const std::string &Name, 1630 BasicBlock *InsertAtEnd) { 1631 BinaryOperator *Res = Create(Op, S1, S2, Name); 1632 InsertAtEnd->getInstList().push_back(Res); 1633 return Res; 1634} 1635 1636BinaryOperator *BinaryOperator::CreateNeg(LLVMContext &Context, 1637 Value *Op, const std::string &Name, 1638 Instruction *InsertBefore) { 1639 Value *zero = Context.getZeroValueForNegation(Op->getType()); 1640 return new BinaryOperator(Instruction::Sub, 1641 zero, Op, 1642 Op->getType(), Name, InsertBefore); 1643} 1644 1645BinaryOperator *BinaryOperator::CreateNeg(LLVMContext &Context, 1646 Value *Op, const std::string &Name, 1647 BasicBlock *InsertAtEnd) { 1648 Value *zero = Context.getZeroValueForNegation(Op->getType()); 1649 return new BinaryOperator(Instruction::Sub, 1650 zero, Op, 1651 Op->getType(), Name, InsertAtEnd); 1652} 1653 1654BinaryOperator *BinaryOperator::CreateFNeg(LLVMContext &Context, 1655 Value *Op, const std::string &Name, 1656 Instruction *InsertBefore) { 1657 Value *zero = Context.getZeroValueForNegation(Op->getType()); 1658 return new BinaryOperator(Instruction::FSub, 1659 zero, Op, 1660 Op->getType(), Name, InsertBefore); 1661} 1662 1663BinaryOperator *BinaryOperator::CreateFNeg(LLVMContext &Context, 1664 Value *Op, const std::string &Name, 1665 BasicBlock *InsertAtEnd) { 1666 Value *zero = Context.getZeroValueForNegation(Op->getType()); 1667 return new BinaryOperator(Instruction::FSub, 1668 zero, Op, 1669 Op->getType(), Name, InsertAtEnd); 1670} 1671 1672BinaryOperator *BinaryOperator::CreateNot(Value *Op, const std::string &Name, 1673 Instruction *InsertBefore) { 1674 Constant *C; 1675 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) { 1676 C = ConstantInt::getAllOnesValue(PTy->getElementType()); 1677 C = ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), C)); 1678 } else { 1679 C = ConstantInt::getAllOnesValue(Op->getType()); 1680 } 1681 1682 return new BinaryOperator(Instruction::Xor, Op, C, 1683 Op->getType(), Name, InsertBefore); 1684} 1685 1686BinaryOperator *BinaryOperator::CreateNot(Value *Op, const std::string &Name, 1687 BasicBlock *InsertAtEnd) { 1688 Constant *AllOnes; 1689 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) { 1690 // Create a vector of all ones values. 1691 Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType()); 1692 AllOnes = 1693 ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), Elt)); 1694 } else { 1695 AllOnes = ConstantInt::getAllOnesValue(Op->getType()); 1696 } 1697 1698 return new BinaryOperator(Instruction::Xor, Op, AllOnes, 1699 Op->getType(), Name, InsertAtEnd); 1700} 1701 1702 1703// isConstantAllOnes - Helper function for several functions below 1704static inline bool isConstantAllOnes(const Value *V) { 1705 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) 1706 return CI->isAllOnesValue(); 1707 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V)) 1708 return CV->isAllOnesValue(); 1709 return false; 1710} 1711 1712bool BinaryOperator::isNeg(LLVMContext &Context, const Value *V) { 1713 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V)) 1714 if (Bop->getOpcode() == Instruction::Sub) 1715 return Bop->getOperand(0) == 1716 Context.getZeroValueForNegation(Bop->getType()); 1717 return false; 1718} 1719 1720bool BinaryOperator::isFNeg(LLVMContext &Context, const Value *V) { 1721 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V)) 1722 if (Bop->getOpcode() == Instruction::FSub) 1723 return Bop->getOperand(0) == 1724 Context.getZeroValueForNegation(Bop->getType()); 1725 return false; 1726} 1727 1728bool BinaryOperator::isNot(const Value *V) { 1729 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V)) 1730 return (Bop->getOpcode() == Instruction::Xor && 1731 (isConstantAllOnes(Bop->getOperand(1)) || 1732 isConstantAllOnes(Bop->getOperand(0)))); 1733 return false; 1734} 1735 1736Value *BinaryOperator::getNegArgument(Value *BinOp) { 1737 return cast<BinaryOperator>(BinOp)->getOperand(1); 1738} 1739 1740const Value *BinaryOperator::getNegArgument(const Value *BinOp) { 1741 return getNegArgument(const_cast<Value*>(BinOp)); 1742} 1743 1744Value *BinaryOperator::getFNegArgument(Value *BinOp) { 1745 return cast<BinaryOperator>(BinOp)->getOperand(1); 1746} 1747 1748const Value *BinaryOperator::getFNegArgument(const Value *BinOp) { 1749 return getFNegArgument(const_cast<Value*>(BinOp)); 1750} 1751 1752Value *BinaryOperator::getNotArgument(Value *BinOp) { 1753 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!"); 1754 BinaryOperator *BO = cast<BinaryOperator>(BinOp); 1755 Value *Op0 = BO->getOperand(0); 1756 Value *Op1 = BO->getOperand(1); 1757 if (isConstantAllOnes(Op0)) return Op1; 1758 1759 assert(isConstantAllOnes(Op1)); 1760 return Op0; 1761} 1762 1763const Value *BinaryOperator::getNotArgument(const Value *BinOp) { 1764 return getNotArgument(const_cast<Value*>(BinOp)); 1765} 1766 1767 1768// swapOperands - Exchange the two operands to this instruction. This 1769// instruction is safe to use on any binary instruction and does not 1770// modify the semantics of the instruction. If the instruction is 1771// order dependent (SetLT f.e.) the opcode is changed. 1772// 1773bool BinaryOperator::swapOperands() { 1774 if (!isCommutative()) 1775 return true; // Can't commute operands 1776 Op<0>().swap(Op<1>()); 1777 return false; 1778} 1779 1780//===----------------------------------------------------------------------===// 1781// CastInst Class 1782//===----------------------------------------------------------------------===// 1783 1784// Just determine if this cast only deals with integral->integral conversion. 1785bool CastInst::isIntegerCast() const { 1786 switch (getOpcode()) { 1787 default: return false; 1788 case Instruction::ZExt: 1789 case Instruction::SExt: 1790 case Instruction::Trunc: 1791 return true; 1792 case Instruction::BitCast: 1793 return getOperand(0)->getType()->isInteger() && getType()->isInteger(); 1794 } 1795} 1796 1797bool CastInst::isLosslessCast() const { 1798 // Only BitCast can be lossless, exit fast if we're not BitCast 1799 if (getOpcode() != Instruction::BitCast) 1800 return false; 1801 1802 // Identity cast is always lossless 1803 const Type* SrcTy = getOperand(0)->getType(); 1804 const Type* DstTy = getType(); 1805 if (SrcTy == DstTy) 1806 return true; 1807 1808 // Pointer to pointer is always lossless. 1809 if (isa<PointerType>(SrcTy)) 1810 return isa<PointerType>(DstTy); 1811 return false; // Other types have no identity values 1812} 1813 1814/// This function determines if the CastInst does not require any bits to be 1815/// changed in order to effect the cast. Essentially, it identifies cases where 1816/// no code gen is necessary for the cast, hence the name no-op cast. For 1817/// example, the following are all no-op casts: 1818/// # bitcast i32* %x to i8* 1819/// # bitcast <2 x i32> %x to <4 x i16> 1820/// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only 1821/// @brief Determine if a cast is a no-op. 1822bool CastInst::isNoopCast(const Type *IntPtrTy) const { 1823 switch (getOpcode()) { 1824 default: 1825 assert(!"Invalid CastOp"); 1826 case Instruction::Trunc: 1827 case Instruction::ZExt: 1828 case Instruction::SExt: 1829 case Instruction::FPTrunc: 1830 case Instruction::FPExt: 1831 case Instruction::UIToFP: 1832 case Instruction::SIToFP: 1833 case Instruction::FPToUI: 1834 case Instruction::FPToSI: 1835 return false; // These always modify bits 1836 case Instruction::BitCast: 1837 return true; // BitCast never modifies bits. 1838 case Instruction::PtrToInt: 1839 return IntPtrTy->getScalarSizeInBits() == 1840 getType()->getScalarSizeInBits(); 1841 case Instruction::IntToPtr: 1842 return IntPtrTy->getScalarSizeInBits() == 1843 getOperand(0)->getType()->getScalarSizeInBits(); 1844 } 1845} 1846 1847/// This function determines if a pair of casts can be eliminated and what 1848/// opcode should be used in the elimination. This assumes that there are two 1849/// instructions like this: 1850/// * %F = firstOpcode SrcTy %x to MidTy 1851/// * %S = secondOpcode MidTy %F to DstTy 1852/// The function returns a resultOpcode so these two casts can be replaced with: 1853/// * %Replacement = resultOpcode %SrcTy %x to DstTy 1854/// If no such cast is permited, the function returns 0. 1855unsigned CastInst::isEliminableCastPair( 1856 Instruction::CastOps firstOp, Instruction::CastOps secondOp, 1857 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy) 1858{ 1859 // Define the 144 possibilities for these two cast instructions. The values 1860 // in this matrix determine what to do in a given situation and select the 1861 // case in the switch below. The rows correspond to firstOp, the columns 1862 // correspond to secondOp. In looking at the table below, keep in mind 1863 // the following cast properties: 1864 // 1865 // Size Compare Source Destination 1866 // Operator Src ? Size Type Sign Type Sign 1867 // -------- ------------ ------------------- --------------------- 1868 // TRUNC > Integer Any Integral Any 1869 // ZEXT < Integral Unsigned Integer Any 1870 // SEXT < Integral Signed Integer Any 1871 // FPTOUI n/a FloatPt n/a Integral Unsigned 1872 // FPTOSI n/a FloatPt n/a Integral Signed 1873 // UITOFP n/a Integral Unsigned FloatPt n/a 1874 // SITOFP n/a Integral Signed FloatPt n/a 1875 // FPTRUNC > FloatPt n/a FloatPt n/a 1876 // FPEXT < FloatPt n/a FloatPt n/a 1877 // PTRTOINT n/a Pointer n/a Integral Unsigned 1878 // INTTOPTR n/a Integral Unsigned Pointer n/a 1879 // BITCONVERT = FirstClass n/a FirstClass n/a 1880 // 1881 // NOTE: some transforms are safe, but we consider them to be non-profitable. 1882 // For example, we could merge "fptoui double to i32" + "zext i32 to i64", 1883 // into "fptoui double to i64", but this loses information about the range 1884 // of the produced value (we no longer know the top-part is all zeros). 1885 // Further this conversion is often much more expensive for typical hardware, 1886 // and causes issues when building libgcc. We disallow fptosi+sext for the 1887 // same reason. 1888 const unsigned numCastOps = 1889 Instruction::CastOpsEnd - Instruction::CastOpsBegin; 1890 static const uint8_t CastResults[numCastOps][numCastOps] = { 1891 // T F F U S F F P I B -+ 1892 // R Z S P P I I T P 2 N T | 1893 // U E E 2 2 2 2 R E I T C +- secondOp 1894 // N X X U S F F N X N 2 V | 1895 // C T T I I P P C T T P T -+ 1896 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+ 1897 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt | 1898 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt | 1899 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI | 1900 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI | 1901 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp 1902 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP | 1903 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc | 1904 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt | 1905 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt | 1906 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr | 1907 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+ 1908 }; 1909 1910 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin] 1911 [secondOp-Instruction::CastOpsBegin]; 1912 switch (ElimCase) { 1913 case 0: 1914 // categorically disallowed 1915 return 0; 1916 case 1: 1917 // allowed, use first cast's opcode 1918 return firstOp; 1919 case 2: 1920 // allowed, use second cast's opcode 1921 return secondOp; 1922 case 3: 1923 // no-op cast in second op implies firstOp as long as the DestTy 1924 // is integer 1925 if (DstTy->isInteger()) 1926 return firstOp; 1927 return 0; 1928 case 4: 1929 // no-op cast in second op implies firstOp as long as the DestTy 1930 // is floating point 1931 if (DstTy->isFloatingPoint()) 1932 return firstOp; 1933 return 0; 1934 case 5: 1935 // no-op cast in first op implies secondOp as long as the SrcTy 1936 // is an integer 1937 if (SrcTy->isInteger()) 1938 return secondOp; 1939 return 0; 1940 case 6: 1941 // no-op cast in first op implies secondOp as long as the SrcTy 1942 // is a floating point 1943 if (SrcTy->isFloatingPoint()) 1944 return secondOp; 1945 return 0; 1946 case 7: { 1947 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size 1948 unsigned PtrSize = IntPtrTy->getScalarSizeInBits(); 1949 unsigned MidSize = MidTy->getScalarSizeInBits(); 1950 if (MidSize >= PtrSize) 1951 return Instruction::BitCast; 1952 return 0; 1953 } 1954 case 8: { 1955 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size 1956 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy) 1957 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy) 1958 unsigned SrcSize = SrcTy->getScalarSizeInBits(); 1959 unsigned DstSize = DstTy->getScalarSizeInBits(); 1960 if (SrcSize == DstSize) 1961 return Instruction::BitCast; 1962 else if (SrcSize < DstSize) 1963 return firstOp; 1964 return secondOp; 1965 } 1966 case 9: // zext, sext -> zext, because sext can't sign extend after zext 1967 return Instruction::ZExt; 1968 case 10: 1969 // fpext followed by ftrunc is allowed if the bit size returned to is 1970 // the same as the original, in which case its just a bitcast 1971 if (SrcTy == DstTy) 1972 return Instruction::BitCast; 1973 return 0; // If the types are not the same we can't eliminate it. 1974 case 11: 1975 // bitcast followed by ptrtoint is allowed as long as the bitcast 1976 // is a pointer to pointer cast. 1977 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy)) 1978 return secondOp; 1979 return 0; 1980 case 12: 1981 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast 1982 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy)) 1983 return firstOp; 1984 return 0; 1985 case 13: { 1986 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize 1987 unsigned PtrSize = IntPtrTy->getScalarSizeInBits(); 1988 unsigned SrcSize = SrcTy->getScalarSizeInBits(); 1989 unsigned DstSize = DstTy->getScalarSizeInBits(); 1990 if (SrcSize <= PtrSize && SrcSize == DstSize) 1991 return Instruction::BitCast; 1992 return 0; 1993 } 1994 case 99: 1995 // cast combination can't happen (error in input). This is for all cases 1996 // where the MidTy is not the same for the two cast instructions. 1997 assert(!"Invalid Cast Combination"); 1998 return 0; 1999 default: 2000 assert(!"Error in CastResults table!!!"); 2001 return 0; 2002 } 2003 return 0; 2004} 2005 2006CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty, 2007 const std::string &Name, Instruction *InsertBefore) { 2008 // Construct and return the appropriate CastInst subclass 2009 switch (op) { 2010 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore); 2011 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore); 2012 case SExt: return new SExtInst (S, Ty, Name, InsertBefore); 2013 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore); 2014 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore); 2015 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore); 2016 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore); 2017 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore); 2018 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore); 2019 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore); 2020 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore); 2021 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore); 2022 default: 2023 assert(!"Invalid opcode provided"); 2024 } 2025 return 0; 2026} 2027 2028CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty, 2029 const std::string &Name, BasicBlock *InsertAtEnd) { 2030 // Construct and return the appropriate CastInst subclass 2031 switch (op) { 2032 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd); 2033 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd); 2034 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd); 2035 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd); 2036 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd); 2037 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd); 2038 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd); 2039 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd); 2040 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd); 2041 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd); 2042 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd); 2043 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd); 2044 default: 2045 assert(!"Invalid opcode provided"); 2046 } 2047 return 0; 2048} 2049 2050CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty, 2051 const std::string &Name, 2052 Instruction *InsertBefore) { 2053 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2054 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 2055 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore); 2056} 2057 2058CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty, 2059 const std::string &Name, 2060 BasicBlock *InsertAtEnd) { 2061 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2062 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 2063 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd); 2064} 2065 2066CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty, 2067 const std::string &Name, 2068 Instruction *InsertBefore) { 2069 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2070 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 2071 return Create(Instruction::SExt, S, Ty, Name, InsertBefore); 2072} 2073 2074CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty, 2075 const std::string &Name, 2076 BasicBlock *InsertAtEnd) { 2077 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2078 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 2079 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd); 2080} 2081 2082CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty, 2083 const std::string &Name, 2084 Instruction *InsertBefore) { 2085 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2086 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 2087 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore); 2088} 2089 2090CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty, 2091 const std::string &Name, 2092 BasicBlock *InsertAtEnd) { 2093 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2094 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 2095 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd); 2096} 2097 2098CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty, 2099 const std::string &Name, 2100 BasicBlock *InsertAtEnd) { 2101 assert(isa<PointerType>(S->getType()) && "Invalid cast"); 2102 assert((Ty->isInteger() || isa<PointerType>(Ty)) && 2103 "Invalid cast"); 2104 2105 if (Ty->isInteger()) 2106 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd); 2107 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 2108} 2109 2110/// @brief Create a BitCast or a PtrToInt cast instruction 2111CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty, 2112 const std::string &Name, 2113 Instruction *InsertBefore) { 2114 assert(isa<PointerType>(S->getType()) && "Invalid cast"); 2115 assert((Ty->isInteger() || isa<PointerType>(Ty)) && 2116 "Invalid cast"); 2117 2118 if (Ty->isInteger()) 2119 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore); 2120 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 2121} 2122 2123CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty, 2124 bool isSigned, const std::string &Name, 2125 Instruction *InsertBefore) { 2126 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast"); 2127 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 2128 unsigned DstBits = Ty->getScalarSizeInBits(); 2129 Instruction::CastOps opcode = 2130 (SrcBits == DstBits ? Instruction::BitCast : 2131 (SrcBits > DstBits ? Instruction::Trunc : 2132 (isSigned ? Instruction::SExt : Instruction::ZExt))); 2133 return Create(opcode, C, Ty, Name, InsertBefore); 2134} 2135 2136CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty, 2137 bool isSigned, const std::string &Name, 2138 BasicBlock *InsertAtEnd) { 2139 assert(C->getType()->isIntOrIntVector() && Ty->isIntOrIntVector() && 2140 "Invalid cast"); 2141 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 2142 unsigned DstBits = Ty->getScalarSizeInBits(); 2143 Instruction::CastOps opcode = 2144 (SrcBits == DstBits ? Instruction::BitCast : 2145 (SrcBits > DstBits ? Instruction::Trunc : 2146 (isSigned ? Instruction::SExt : Instruction::ZExt))); 2147 return Create(opcode, C, Ty, Name, InsertAtEnd); 2148} 2149 2150CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty, 2151 const std::string &Name, 2152 Instruction *InsertBefore) { 2153 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() && 2154 "Invalid cast"); 2155 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 2156 unsigned DstBits = Ty->getScalarSizeInBits(); 2157 Instruction::CastOps opcode = 2158 (SrcBits == DstBits ? Instruction::BitCast : 2159 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt)); 2160 return Create(opcode, C, Ty, Name, InsertBefore); 2161} 2162 2163CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty, 2164 const std::string &Name, 2165 BasicBlock *InsertAtEnd) { 2166 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() && 2167 "Invalid cast"); 2168 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 2169 unsigned DstBits = Ty->getScalarSizeInBits(); 2170 Instruction::CastOps opcode = 2171 (SrcBits == DstBits ? Instruction::BitCast : 2172 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt)); 2173 return Create(opcode, C, Ty, Name, InsertAtEnd); 2174} 2175 2176// Check whether it is valid to call getCastOpcode for these types. 2177// This routine must be kept in sync with getCastOpcode. 2178bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) { 2179 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType()) 2180 return false; 2181 2182 if (SrcTy == DestTy) 2183 return true; 2184 2185 // Get the bit sizes, we'll need these 2186 unsigned SrcBits = SrcTy->getScalarSizeInBits(); // 0 for ptr 2187 unsigned DestBits = DestTy->getScalarSizeInBits(); // 0 for ptr 2188 2189 // Run through the possibilities ... 2190 if (DestTy->isInteger()) { // Casting to integral 2191 if (SrcTy->isInteger()) { // Casting from integral 2192 return true; 2193 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt 2194 return true; 2195 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) { 2196 // Casting from vector 2197 return DestBits == PTy->getBitWidth(); 2198 } else { // Casting from something else 2199 return isa<PointerType>(SrcTy); 2200 } 2201 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt 2202 if (SrcTy->isInteger()) { // Casting from integral 2203 return true; 2204 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt 2205 return true; 2206 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) { 2207 // Casting from vector 2208 return DestBits == PTy->getBitWidth(); 2209 } else { // Casting from something else 2210 return false; 2211 } 2212 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) { 2213 // Casting to vector 2214 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) { 2215 // Casting from vector 2216 return DestPTy->getBitWidth() == SrcPTy->getBitWidth(); 2217 } else { // Casting from something else 2218 return DestPTy->getBitWidth() == SrcBits; 2219 } 2220 } else if (isa<PointerType>(DestTy)) { // Casting to pointer 2221 if (isa<PointerType>(SrcTy)) { // Casting from pointer 2222 return true; 2223 } else if (SrcTy->isInteger()) { // Casting from integral 2224 return true; 2225 } else { // Casting from something else 2226 return false; 2227 } 2228 } else { // Casting to something else 2229 return false; 2230 } 2231} 2232 2233// Provide a way to get a "cast" where the cast opcode is inferred from the 2234// types and size of the operand. This, basically, is a parallel of the 2235// logic in the castIsValid function below. This axiom should hold: 2236// castIsValid( getCastOpcode(Val, Ty), Val, Ty) 2237// should not assert in castIsValid. In other words, this produces a "correct" 2238// casting opcode for the arguments passed to it. 2239// This routine must be kept in sync with isCastable. 2240Instruction::CastOps 2241CastInst::getCastOpcode( 2242 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) { 2243 // Get the bit sizes, we'll need these 2244 const Type *SrcTy = Src->getType(); 2245 unsigned SrcBits = SrcTy->getScalarSizeInBits(); // 0 for ptr 2246 unsigned DestBits = DestTy->getScalarSizeInBits(); // 0 for ptr 2247 2248 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() && 2249 "Only first class types are castable!"); 2250 2251 // Run through the possibilities ... 2252 if (DestTy->isInteger()) { // Casting to integral 2253 if (SrcTy->isInteger()) { // Casting from integral 2254 if (DestBits < SrcBits) 2255 return Trunc; // int -> smaller int 2256 else if (DestBits > SrcBits) { // its an extension 2257 if (SrcIsSigned) 2258 return SExt; // signed -> SEXT 2259 else 2260 return ZExt; // unsigned -> ZEXT 2261 } else { 2262 return BitCast; // Same size, No-op cast 2263 } 2264 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt 2265 if (DestIsSigned) 2266 return FPToSI; // FP -> sint 2267 else 2268 return FPToUI; // FP -> uint 2269 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) { 2270 assert(DestBits == PTy->getBitWidth() && 2271 "Casting vector to integer of different width"); 2272 PTy = NULL; 2273 return BitCast; // Same size, no-op cast 2274 } else { 2275 assert(isa<PointerType>(SrcTy) && 2276 "Casting from a value that is not first-class type"); 2277 return PtrToInt; // ptr -> int 2278 } 2279 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt 2280 if (SrcTy->isInteger()) { // Casting from integral 2281 if (SrcIsSigned) 2282 return SIToFP; // sint -> FP 2283 else 2284 return UIToFP; // uint -> FP 2285 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt 2286 if (DestBits < SrcBits) { 2287 return FPTrunc; // FP -> smaller FP 2288 } else if (DestBits > SrcBits) { 2289 return FPExt; // FP -> larger FP 2290 } else { 2291 return BitCast; // same size, no-op cast 2292 } 2293 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) { 2294 assert(DestBits == PTy->getBitWidth() && 2295 "Casting vector to floating point of different width"); 2296 PTy = NULL; 2297 return BitCast; // same size, no-op cast 2298 } else { 2299 LLVM_UNREACHABLE("Casting pointer or non-first class to float"); 2300 } 2301 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) { 2302 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) { 2303 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() && 2304 "Casting vector to vector of different widths"); 2305 SrcPTy = NULL; 2306 return BitCast; // vector -> vector 2307 } else if (DestPTy->getBitWidth() == SrcBits) { 2308 return BitCast; // float/int -> vector 2309 } else { 2310 assert(!"Illegal cast to vector (wrong type or size)"); 2311 } 2312 } else if (isa<PointerType>(DestTy)) { 2313 if (isa<PointerType>(SrcTy)) { 2314 return BitCast; // ptr -> ptr 2315 } else if (SrcTy->isInteger()) { 2316 return IntToPtr; // int -> ptr 2317 } else { 2318 assert(!"Casting pointer to other than pointer or int"); 2319 } 2320 } else { 2321 assert(!"Casting to type that is not first-class"); 2322 } 2323 2324 // If we fall through to here we probably hit an assertion cast above 2325 // and assertions are not turned on. Anything we return is an error, so 2326 // BitCast is as good a choice as any. 2327 return BitCast; 2328} 2329 2330//===----------------------------------------------------------------------===// 2331// CastInst SubClass Constructors 2332//===----------------------------------------------------------------------===// 2333 2334/// Check that the construction parameters for a CastInst are correct. This 2335/// could be broken out into the separate constructors but it is useful to have 2336/// it in one place and to eliminate the redundant code for getting the sizes 2337/// of the types involved. 2338bool 2339CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) { 2340 2341 // Check for type sanity on the arguments 2342 const Type *SrcTy = S->getType(); 2343 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType()) 2344 return false; 2345 2346 // Get the size of the types in bits, we'll need this later 2347 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2348 unsigned DstBitSize = DstTy->getScalarSizeInBits(); 2349 2350 // Switch on the opcode provided 2351 switch (op) { 2352 default: return false; // This is an input error 2353 case Instruction::Trunc: 2354 return SrcTy->isIntOrIntVector() && 2355 DstTy->isIntOrIntVector()&& SrcBitSize > DstBitSize; 2356 case Instruction::ZExt: 2357 return SrcTy->isIntOrIntVector() && 2358 DstTy->isIntOrIntVector()&& SrcBitSize < DstBitSize; 2359 case Instruction::SExt: 2360 return SrcTy->isIntOrIntVector() && 2361 DstTy->isIntOrIntVector()&& SrcBitSize < DstBitSize; 2362 case Instruction::FPTrunc: 2363 return SrcTy->isFPOrFPVector() && 2364 DstTy->isFPOrFPVector() && 2365 SrcBitSize > DstBitSize; 2366 case Instruction::FPExt: 2367 return SrcTy->isFPOrFPVector() && 2368 DstTy->isFPOrFPVector() && 2369 SrcBitSize < DstBitSize; 2370 case Instruction::UIToFP: 2371 case Instruction::SIToFP: 2372 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) { 2373 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) { 2374 return SVTy->getElementType()->isIntOrIntVector() && 2375 DVTy->getElementType()->isFPOrFPVector() && 2376 SVTy->getNumElements() == DVTy->getNumElements(); 2377 } 2378 } 2379 return SrcTy->isIntOrIntVector() && DstTy->isFPOrFPVector(); 2380 case Instruction::FPToUI: 2381 case Instruction::FPToSI: 2382 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) { 2383 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) { 2384 return SVTy->getElementType()->isFPOrFPVector() && 2385 DVTy->getElementType()->isIntOrIntVector() && 2386 SVTy->getNumElements() == DVTy->getNumElements(); 2387 } 2388 } 2389 return SrcTy->isFPOrFPVector() && DstTy->isIntOrIntVector(); 2390 case Instruction::PtrToInt: 2391 return isa<PointerType>(SrcTy) && DstTy->isInteger(); 2392 case Instruction::IntToPtr: 2393 return SrcTy->isInteger() && isa<PointerType>(DstTy); 2394 case Instruction::BitCast: 2395 // BitCast implies a no-op cast of type only. No bits change. 2396 // However, you can't cast pointers to anything but pointers. 2397 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy)) 2398 return false; 2399 2400 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all 2401 // these cases, the cast is okay if the source and destination bit widths 2402 // are identical. 2403 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits(); 2404 } 2405} 2406 2407TruncInst::TruncInst( 2408 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore 2409) : CastInst(Ty, Trunc, S, Name, InsertBefore) { 2410 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc"); 2411} 2412 2413TruncInst::TruncInst( 2414 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd 2415) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) { 2416 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc"); 2417} 2418 2419ZExtInst::ZExtInst( 2420 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore 2421) : CastInst(Ty, ZExt, S, Name, InsertBefore) { 2422 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt"); 2423} 2424 2425ZExtInst::ZExtInst( 2426 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd 2427) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) { 2428 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt"); 2429} 2430SExtInst::SExtInst( 2431 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore 2432) : CastInst(Ty, SExt, S, Name, InsertBefore) { 2433 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt"); 2434} 2435 2436SExtInst::SExtInst( 2437 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd 2438) : CastInst(Ty, SExt, S, Name, InsertAtEnd) { 2439 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt"); 2440} 2441 2442FPTruncInst::FPTruncInst( 2443 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore 2444) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) { 2445 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc"); 2446} 2447 2448FPTruncInst::FPTruncInst( 2449 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd 2450) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) { 2451 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc"); 2452} 2453 2454FPExtInst::FPExtInst( 2455 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore 2456) : CastInst(Ty, FPExt, S, Name, InsertBefore) { 2457 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt"); 2458} 2459 2460FPExtInst::FPExtInst( 2461 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd 2462) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) { 2463 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt"); 2464} 2465 2466UIToFPInst::UIToFPInst( 2467 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore 2468) : CastInst(Ty, UIToFP, S, Name, InsertBefore) { 2469 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP"); 2470} 2471 2472UIToFPInst::UIToFPInst( 2473 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd 2474) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) { 2475 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP"); 2476} 2477 2478SIToFPInst::SIToFPInst( 2479 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore 2480) : CastInst(Ty, SIToFP, S, Name, InsertBefore) { 2481 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP"); 2482} 2483 2484SIToFPInst::SIToFPInst( 2485 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd 2486) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) { 2487 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP"); 2488} 2489 2490FPToUIInst::FPToUIInst( 2491 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore 2492) : CastInst(Ty, FPToUI, S, Name, InsertBefore) { 2493 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI"); 2494} 2495 2496FPToUIInst::FPToUIInst( 2497 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd 2498) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) { 2499 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI"); 2500} 2501 2502FPToSIInst::FPToSIInst( 2503 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore 2504) : CastInst(Ty, FPToSI, S, Name, InsertBefore) { 2505 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI"); 2506} 2507 2508FPToSIInst::FPToSIInst( 2509 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd 2510) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) { 2511 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI"); 2512} 2513 2514PtrToIntInst::PtrToIntInst( 2515 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore 2516) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) { 2517 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt"); 2518} 2519 2520PtrToIntInst::PtrToIntInst( 2521 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd 2522) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) { 2523 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt"); 2524} 2525 2526IntToPtrInst::IntToPtrInst( 2527 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore 2528) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) { 2529 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr"); 2530} 2531 2532IntToPtrInst::IntToPtrInst( 2533 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd 2534) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) { 2535 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr"); 2536} 2537 2538BitCastInst::BitCastInst( 2539 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore 2540) : CastInst(Ty, BitCast, S, Name, InsertBefore) { 2541 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast"); 2542} 2543 2544BitCastInst::BitCastInst( 2545 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd 2546) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) { 2547 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast"); 2548} 2549 2550//===----------------------------------------------------------------------===// 2551// CmpInst Classes 2552//===----------------------------------------------------------------------===// 2553 2554CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate, 2555 Value *LHS, Value *RHS, const std::string &Name, 2556 Instruction *InsertBefore) 2557 : Instruction(ty, op, 2558 OperandTraits<CmpInst>::op_begin(this), 2559 OperandTraits<CmpInst>::operands(this), 2560 InsertBefore) { 2561 Op<0>() = LHS; 2562 Op<1>() = RHS; 2563 SubclassData = predicate; 2564 setName(Name); 2565} 2566 2567CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate, 2568 Value *LHS, Value *RHS, const std::string &Name, 2569 BasicBlock *InsertAtEnd) 2570 : Instruction(ty, op, 2571 OperandTraits<CmpInst>::op_begin(this), 2572 OperandTraits<CmpInst>::operands(this), 2573 InsertAtEnd) { 2574 Op<0>() = LHS; 2575 Op<1>() = RHS; 2576 SubclassData = predicate; 2577 setName(Name); 2578} 2579 2580CmpInst * 2581CmpInst::Create(LLVMContext &Context, OtherOps Op, unsigned short predicate, 2582 Value *S1, Value *S2, 2583 const std::string &Name, Instruction *InsertBefore) { 2584 if (Op == Instruction::ICmp) { 2585 if (InsertBefore) 2586 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate), 2587 S1, S2, Name); 2588 else 2589 return new ICmpInst(Context, CmpInst::Predicate(predicate), 2590 S1, S2, Name); 2591 } 2592 2593 if (InsertBefore) 2594 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate), 2595 S1, S2, Name); 2596 else 2597 return new FCmpInst(Context, CmpInst::Predicate(predicate), 2598 S1, S2, Name); 2599} 2600 2601CmpInst * 2602CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2, 2603 const std::string &Name, BasicBlock *InsertAtEnd) { 2604 if (Op == Instruction::ICmp) { 2605 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate), 2606 S1, S2, Name); 2607 } 2608 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate), 2609 S1, S2, Name); 2610} 2611 2612void CmpInst::swapOperands() { 2613 if (ICmpInst *IC = dyn_cast<ICmpInst>(this)) 2614 IC->swapOperands(); 2615 else 2616 cast<FCmpInst>(this)->swapOperands(); 2617} 2618 2619bool CmpInst::isCommutative() { 2620 if (ICmpInst *IC = dyn_cast<ICmpInst>(this)) 2621 return IC->isCommutative(); 2622 return cast<FCmpInst>(this)->isCommutative(); 2623} 2624 2625bool CmpInst::isEquality() { 2626 if (ICmpInst *IC = dyn_cast<ICmpInst>(this)) 2627 return IC->isEquality(); 2628 return cast<FCmpInst>(this)->isEquality(); 2629} 2630 2631 2632CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) { 2633 switch (pred) { 2634 default: assert(!"Unknown cmp predicate!"); 2635 case ICMP_EQ: return ICMP_NE; 2636 case ICMP_NE: return ICMP_EQ; 2637 case ICMP_UGT: return ICMP_ULE; 2638 case ICMP_ULT: return ICMP_UGE; 2639 case ICMP_UGE: return ICMP_ULT; 2640 case ICMP_ULE: return ICMP_UGT; 2641 case ICMP_SGT: return ICMP_SLE; 2642 case ICMP_SLT: return ICMP_SGE; 2643 case ICMP_SGE: return ICMP_SLT; 2644 case ICMP_SLE: return ICMP_SGT; 2645 2646 case FCMP_OEQ: return FCMP_UNE; 2647 case FCMP_ONE: return FCMP_UEQ; 2648 case FCMP_OGT: return FCMP_ULE; 2649 case FCMP_OLT: return FCMP_UGE; 2650 case FCMP_OGE: return FCMP_ULT; 2651 case FCMP_OLE: return FCMP_UGT; 2652 case FCMP_UEQ: return FCMP_ONE; 2653 case FCMP_UNE: return FCMP_OEQ; 2654 case FCMP_UGT: return FCMP_OLE; 2655 case FCMP_ULT: return FCMP_OGE; 2656 case FCMP_UGE: return FCMP_OLT; 2657 case FCMP_ULE: return FCMP_OGT; 2658 case FCMP_ORD: return FCMP_UNO; 2659 case FCMP_UNO: return FCMP_ORD; 2660 case FCMP_TRUE: return FCMP_FALSE; 2661 case FCMP_FALSE: return FCMP_TRUE; 2662 } 2663} 2664 2665ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) { 2666 switch (pred) { 2667 default: assert(! "Unknown icmp predicate!"); 2668 case ICMP_EQ: case ICMP_NE: 2669 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE: 2670 return pred; 2671 case ICMP_UGT: return ICMP_SGT; 2672 case ICMP_ULT: return ICMP_SLT; 2673 case ICMP_UGE: return ICMP_SGE; 2674 case ICMP_ULE: return ICMP_SLE; 2675 } 2676} 2677 2678ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) { 2679 switch (pred) { 2680 default: assert(! "Unknown icmp predicate!"); 2681 case ICMP_EQ: case ICMP_NE: 2682 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE: 2683 return pred; 2684 case ICMP_SGT: return ICMP_UGT; 2685 case ICMP_SLT: return ICMP_ULT; 2686 case ICMP_SGE: return ICMP_UGE; 2687 case ICMP_SLE: return ICMP_ULE; 2688 } 2689} 2690 2691bool ICmpInst::isSignedPredicate(Predicate pred) { 2692 switch (pred) { 2693 default: assert(! "Unknown icmp predicate!"); 2694 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE: 2695 return true; 2696 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT: 2697 case ICMP_UGE: case ICMP_ULE: 2698 return false; 2699 } 2700} 2701 2702/// Initialize a set of values that all satisfy the condition with C. 2703/// 2704ConstantRange 2705ICmpInst::makeConstantRange(Predicate pred, const APInt &C) { 2706 APInt Lower(C); 2707 APInt Upper(C); 2708 uint32_t BitWidth = C.getBitWidth(); 2709 switch (pred) { 2710 default: LLVM_UNREACHABLE("Invalid ICmp opcode to ConstantRange ctor!"); 2711 case ICmpInst::ICMP_EQ: Upper++; break; 2712 case ICmpInst::ICMP_NE: Lower++; break; 2713 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break; 2714 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break; 2715 case ICmpInst::ICMP_UGT: 2716 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max) 2717 break; 2718 case ICmpInst::ICMP_SGT: 2719 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max) 2720 break; 2721 case ICmpInst::ICMP_ULE: 2722 Lower = APInt::getMinValue(BitWidth); Upper++; 2723 break; 2724 case ICmpInst::ICMP_SLE: 2725 Lower = APInt::getSignedMinValue(BitWidth); Upper++; 2726 break; 2727 case ICmpInst::ICMP_UGE: 2728 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max) 2729 break; 2730 case ICmpInst::ICMP_SGE: 2731 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max) 2732 break; 2733 } 2734 return ConstantRange(Lower, Upper); 2735} 2736 2737CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) { 2738 switch (pred) { 2739 default: assert(!"Unknown cmp predicate!"); 2740 case ICMP_EQ: case ICMP_NE: 2741 return pred; 2742 case ICMP_SGT: return ICMP_SLT; 2743 case ICMP_SLT: return ICMP_SGT; 2744 case ICMP_SGE: return ICMP_SLE; 2745 case ICMP_SLE: return ICMP_SGE; 2746 case ICMP_UGT: return ICMP_ULT; 2747 case ICMP_ULT: return ICMP_UGT; 2748 case ICMP_UGE: return ICMP_ULE; 2749 case ICMP_ULE: return ICMP_UGE; 2750 2751 case FCMP_FALSE: case FCMP_TRUE: 2752 case FCMP_OEQ: case FCMP_ONE: 2753 case FCMP_UEQ: case FCMP_UNE: 2754 case FCMP_ORD: case FCMP_UNO: 2755 return pred; 2756 case FCMP_OGT: return FCMP_OLT; 2757 case FCMP_OLT: return FCMP_OGT; 2758 case FCMP_OGE: return FCMP_OLE; 2759 case FCMP_OLE: return FCMP_OGE; 2760 case FCMP_UGT: return FCMP_ULT; 2761 case FCMP_ULT: return FCMP_UGT; 2762 case FCMP_UGE: return FCMP_ULE; 2763 case FCMP_ULE: return FCMP_UGE; 2764 } 2765} 2766 2767bool CmpInst::isUnsigned(unsigned short predicate) { 2768 switch (predicate) { 2769 default: return false; 2770 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT: 2771 case ICmpInst::ICMP_UGE: return true; 2772 } 2773} 2774 2775bool CmpInst::isSigned(unsigned short predicate){ 2776 switch (predicate) { 2777 default: return false; 2778 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT: 2779 case ICmpInst::ICMP_SGE: return true; 2780 } 2781} 2782 2783bool CmpInst::isOrdered(unsigned short predicate) { 2784 switch (predicate) { 2785 default: return false; 2786 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT: 2787 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE: 2788 case FCmpInst::FCMP_ORD: return true; 2789 } 2790} 2791 2792bool CmpInst::isUnordered(unsigned short predicate) { 2793 switch (predicate) { 2794 default: return false; 2795 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT: 2796 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE: 2797 case FCmpInst::FCMP_UNO: return true; 2798 } 2799} 2800 2801//===----------------------------------------------------------------------===// 2802// SwitchInst Implementation 2803//===----------------------------------------------------------------------===// 2804 2805void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) { 2806 assert(Value && Default); 2807 ReservedSpace = 2+NumCases*2; 2808 NumOperands = 2; 2809 OperandList = allocHungoffUses(ReservedSpace); 2810 2811 OperandList[0] = Value; 2812 OperandList[1] = Default; 2813} 2814 2815/// SwitchInst ctor - Create a new switch instruction, specifying a value to 2816/// switch on and a default destination. The number of additional cases can 2817/// be specified here to make memory allocation more efficient. This 2818/// constructor can also autoinsert before another instruction. 2819SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases, 2820 Instruction *InsertBefore) 2821 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) { 2822 init(Value, Default, NumCases); 2823} 2824 2825/// SwitchInst ctor - Create a new switch instruction, specifying a value to 2826/// switch on and a default destination. The number of additional cases can 2827/// be specified here to make memory allocation more efficient. This 2828/// constructor also autoinserts at the end of the specified BasicBlock. 2829SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases, 2830 BasicBlock *InsertAtEnd) 2831 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) { 2832 init(Value, Default, NumCases); 2833} 2834 2835SwitchInst::SwitchInst(const SwitchInst &SI) 2836 : TerminatorInst(Type::VoidTy, Instruction::Switch, 2837 allocHungoffUses(SI.getNumOperands()), SI.getNumOperands()) { 2838 Use *OL = OperandList, *InOL = SI.OperandList; 2839 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) { 2840 OL[i] = InOL[i]; 2841 OL[i+1] = InOL[i+1]; 2842 } 2843} 2844 2845SwitchInst::~SwitchInst() { 2846 dropHungoffUses(OperandList); 2847} 2848 2849 2850/// addCase - Add an entry to the switch instruction... 2851/// 2852void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) { 2853 unsigned OpNo = NumOperands; 2854 if (OpNo+2 > ReservedSpace) 2855 resizeOperands(0); // Get more space! 2856 // Initialize some new operands. 2857 assert(OpNo+1 < ReservedSpace && "Growing didn't work!"); 2858 NumOperands = OpNo+2; 2859 OperandList[OpNo] = OnVal; 2860 OperandList[OpNo+1] = Dest; 2861} 2862 2863/// removeCase - This method removes the specified successor from the switch 2864/// instruction. Note that this cannot be used to remove the default 2865/// destination (successor #0). 2866/// 2867void SwitchInst::removeCase(unsigned idx) { 2868 assert(idx != 0 && "Cannot remove the default case!"); 2869 assert(idx*2 < getNumOperands() && "Successor index out of range!!!"); 2870 2871 unsigned NumOps = getNumOperands(); 2872 Use *OL = OperandList; 2873 2874 // Move everything after this operand down. 2875 // 2876 // FIXME: we could just swap with the end of the list, then erase. However, 2877 // client might not expect this to happen. The code as it is thrashes the 2878 // use/def lists, which is kinda lame. 2879 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) { 2880 OL[i-2] = OL[i]; 2881 OL[i-2+1] = OL[i+1]; 2882 } 2883 2884 // Nuke the last value. 2885 OL[NumOps-2].set(0); 2886 OL[NumOps-2+1].set(0); 2887 NumOperands = NumOps-2; 2888} 2889 2890/// resizeOperands - resize operands - This adjusts the length of the operands 2891/// list according to the following behavior: 2892/// 1. If NumOps == 0, grow the operand list in response to a push_back style 2893/// of operation. This grows the number of ops by 3 times. 2894/// 2. If NumOps > NumOperands, reserve space for NumOps operands. 2895/// 3. If NumOps == NumOperands, trim the reserved space. 2896/// 2897void SwitchInst::resizeOperands(unsigned NumOps) { 2898 unsigned e = getNumOperands(); 2899 if (NumOps == 0) { 2900 NumOps = e*3; 2901 } else if (NumOps*2 > NumOperands) { 2902 // No resize needed. 2903 if (ReservedSpace >= NumOps) return; 2904 } else if (NumOps == NumOperands) { 2905 if (ReservedSpace == NumOps) return; 2906 } else { 2907 return; 2908 } 2909 2910 ReservedSpace = NumOps; 2911 Use *NewOps = allocHungoffUses(NumOps); 2912 Use *OldOps = OperandList; 2913 for (unsigned i = 0; i != e; ++i) { 2914 NewOps[i] = OldOps[i]; 2915 } 2916 OperandList = NewOps; 2917 if (OldOps) Use::zap(OldOps, OldOps + e, true); 2918} 2919 2920 2921BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const { 2922 return getSuccessor(idx); 2923} 2924unsigned SwitchInst::getNumSuccessorsV() const { 2925 return getNumSuccessors(); 2926} 2927void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) { 2928 setSuccessor(idx, B); 2929} 2930 2931// Define these methods here so vtables don't get emitted into every translation 2932// unit that uses these classes. 2933 2934GetElementPtrInst *GetElementPtrInst::clone(LLVMContext&) const { 2935 return new(getNumOperands()) GetElementPtrInst(*this); 2936} 2937 2938BinaryOperator *BinaryOperator::clone(LLVMContext&) const { 2939 return Create(getOpcode(), Op<0>(), Op<1>()); 2940} 2941 2942FCmpInst* FCmpInst::clone(LLVMContext &Context) const { 2943 return new FCmpInst(Context, getPredicate(), Op<0>(), Op<1>()); 2944} 2945ICmpInst* ICmpInst::clone(LLVMContext &Context) const { 2946 return new ICmpInst(Context, getPredicate(), Op<0>(), Op<1>()); 2947} 2948 2949ExtractValueInst *ExtractValueInst::clone(LLVMContext&) const { 2950 return new ExtractValueInst(*this); 2951} 2952InsertValueInst *InsertValueInst::clone(LLVMContext&) const { 2953 return new InsertValueInst(*this); 2954} 2955 2956MallocInst *MallocInst::clone(LLVMContext&) const { 2957 return new MallocInst(*this); 2958} 2959 2960AllocaInst *AllocaInst::clone(LLVMContext&) const { 2961 return new AllocaInst(*this); 2962} 2963 2964FreeInst *FreeInst::clone(LLVMContext&) const { 2965 return new FreeInst(getOperand(0)); 2966} 2967 2968LoadInst *LoadInst::clone(LLVMContext&) const { 2969 return new LoadInst(*this); 2970} 2971 2972StoreInst *StoreInst::clone(LLVMContext&) const { 2973 return new StoreInst(*this); 2974} 2975 2976CastInst *TruncInst::clone(LLVMContext&) const { 2977 return new TruncInst(*this); 2978} 2979 2980CastInst *ZExtInst::clone(LLVMContext&) const { 2981 return new ZExtInst(*this); 2982} 2983 2984CastInst *SExtInst::clone(LLVMContext&) const { 2985 return new SExtInst(*this); 2986} 2987 2988CastInst *FPTruncInst::clone(LLVMContext&) const { 2989 return new FPTruncInst(*this); 2990} 2991 2992CastInst *FPExtInst::clone(LLVMContext&) const { 2993 return new FPExtInst(*this); 2994} 2995 2996CastInst *UIToFPInst::clone(LLVMContext&) const { 2997 return new UIToFPInst(*this); 2998} 2999 3000CastInst *SIToFPInst::clone(LLVMContext&) const { 3001 return new SIToFPInst(*this); 3002} 3003 3004CastInst *FPToUIInst::clone(LLVMContext&) const { 3005 return new FPToUIInst(*this); 3006} 3007 3008CastInst *FPToSIInst::clone(LLVMContext&) const { 3009 return new FPToSIInst(*this); 3010} 3011 3012CastInst *PtrToIntInst::clone(LLVMContext&) const { 3013 return new PtrToIntInst(*this); 3014} 3015 3016CastInst *IntToPtrInst::clone(LLVMContext&) const { 3017 return new IntToPtrInst(*this); 3018} 3019 3020CastInst *BitCastInst::clone(LLVMContext&) const { 3021 return new BitCastInst(*this); 3022} 3023 3024CallInst *CallInst::clone(LLVMContext&) const { 3025 return new(getNumOperands()) CallInst(*this); 3026} 3027 3028SelectInst *SelectInst::clone(LLVMContext&) const { 3029 return new(getNumOperands()) SelectInst(*this); 3030} 3031 3032VAArgInst *VAArgInst::clone(LLVMContext&) const { 3033 return new VAArgInst(*this); 3034} 3035 3036ExtractElementInst *ExtractElementInst::clone(LLVMContext&) const { 3037 return new ExtractElementInst(*this); 3038} 3039 3040InsertElementInst *InsertElementInst::clone(LLVMContext&) const { 3041 return InsertElementInst::Create(*this); 3042} 3043 3044ShuffleVectorInst *ShuffleVectorInst::clone(LLVMContext&) const { 3045 return new ShuffleVectorInst(*this); 3046} 3047 3048PHINode *PHINode::clone(LLVMContext&) const { 3049 return new PHINode(*this); 3050} 3051 3052ReturnInst *ReturnInst::clone(LLVMContext&) const { 3053 return new(getNumOperands()) ReturnInst(*this); 3054} 3055 3056BranchInst *BranchInst::clone(LLVMContext&) const { 3057 unsigned Ops(getNumOperands()); 3058 return new(Ops, Ops == 1) BranchInst(*this); 3059} 3060 3061SwitchInst *SwitchInst::clone(LLVMContext&) const { 3062 return new SwitchInst(*this); 3063} 3064 3065InvokeInst *InvokeInst::clone(LLVMContext&) const { 3066 return new(getNumOperands()) InvokeInst(*this); 3067} 3068 3069UnwindInst *UnwindInst::clone(LLVMContext&) const { 3070 return new UnwindInst(); 3071} 3072 3073UnreachableInst *UnreachableInst::clone(LLVMContext&) const { 3074 return new UnreachableInst(); 3075} 3076