1 //===-- Instructions.cpp - Implement the LLVM instructions ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements all of the non-inline methods for the LLVM instruction
13 //===----------------------------------------------------------------------===//
15 #include "LLVMContextImpl.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/Operator.h"
22 #include "llvm/Analysis/Dominators.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/CallSite.h"
25 #include "llvm/Support/ConstantRange.h"
26 #include "llvm/Support/MathExtras.h"
29 //===----------------------------------------------------------------------===//
31 //===----------------------------------------------------------------------===//
33 #define CALLSITE_DELEGATE_GETTER(METHOD) \
34 Instruction *II = getInstruction(); \
36 ? cast<CallInst>(II)->METHOD \
37 : cast<InvokeInst>(II)->METHOD
39 #define CALLSITE_DELEGATE_SETTER(METHOD) \
40 Instruction *II = getInstruction(); \
42 cast<CallInst>(II)->METHOD; \
44 cast<InvokeInst>(II)->METHOD
46 CallingConv::ID CallSite::getCallingConv() const {
47 CALLSITE_DELEGATE_GETTER(getCallingConv());
49 void CallSite::setCallingConv(CallingConv::ID CC) {
50 CALLSITE_DELEGATE_SETTER(setCallingConv(CC));
52 const AttrListPtr &CallSite::getAttributes() const {
53 CALLSITE_DELEGATE_GETTER(getAttributes());
55 void CallSite::setAttributes(const AttrListPtr &PAL) {
56 CALLSITE_DELEGATE_SETTER(setAttributes(PAL));
58 bool CallSite::paramHasAttr(uint16_t i, Attributes attr) const {
59 CALLSITE_DELEGATE_GETTER(paramHasAttr(i, attr));
61 uint16_t CallSite::getParamAlignment(uint16_t i) const {
62 CALLSITE_DELEGATE_GETTER(getParamAlignment(i));
65 /// @brief Return true if the call should not be inlined.
66 bool CallSite::isNoInline() const {
67 CALLSITE_DELEGATE_GETTER(isNoInline());
70 void CallSite::setIsNoInline(bool Value) {
71 CALLSITE_DELEGATE_GETTER(setIsNoInline(Value));
75 bool CallSite::doesNotAccessMemory() const {
76 CALLSITE_DELEGATE_GETTER(doesNotAccessMemory());
78 void CallSite::setDoesNotAccessMemory(bool doesNotAccessMemory) {
79 CALLSITE_DELEGATE_SETTER(setDoesNotAccessMemory(doesNotAccessMemory));
81 bool CallSite::onlyReadsMemory() const {
82 CALLSITE_DELEGATE_GETTER(onlyReadsMemory());
84 void CallSite::setOnlyReadsMemory(bool onlyReadsMemory) {
85 CALLSITE_DELEGATE_SETTER(setOnlyReadsMemory(onlyReadsMemory));
87 bool CallSite::doesNotReturn() const {
88 CALLSITE_DELEGATE_GETTER(doesNotReturn());
90 void CallSite::setDoesNotReturn(bool doesNotReturn) {
91 CALLSITE_DELEGATE_SETTER(setDoesNotReturn(doesNotReturn));
93 bool CallSite::doesNotThrow() const {
94 CALLSITE_DELEGATE_GETTER(doesNotThrow());
96 void CallSite::setDoesNotThrow(bool doesNotThrow) {
97 CALLSITE_DELEGATE_SETTER(setDoesNotThrow(doesNotThrow));
100 bool CallSite::hasArgument(const Value *Arg) const {
101 for (arg_iterator AI = this->arg_begin(), E = this->arg_end(); AI != E; ++AI)
102 if (AI->get() == Arg)
107 User::op_iterator CallSite::getCallee() const {
108 Instruction *II(getInstruction());
110 ? cast<CallInst>(II)->op_begin()
111 : cast<InvokeInst>(II)->op_end() - 3; // Skip BB, BB, Function
114 #undef CALLSITE_DELEGATE_GETTER
115 #undef CALLSITE_DELEGATE_SETTER
117 //===----------------------------------------------------------------------===//
118 // TerminatorInst Class
119 //===----------------------------------------------------------------------===//
121 // Out of line virtual method, so the vtable, etc has a home.
122 TerminatorInst::~TerminatorInst() {
125 //===----------------------------------------------------------------------===//
126 // UnaryInstruction Class
127 //===----------------------------------------------------------------------===//
129 // Out of line virtual method, so the vtable, etc has a home.
130 UnaryInstruction::~UnaryInstruction() {
133 //===----------------------------------------------------------------------===//
135 //===----------------------------------------------------------------------===//
137 /// areInvalidOperands - Return a string if the specified operands are invalid
138 /// for a select operation, otherwise return null.
139 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
140 if (Op1->getType() != Op2->getType())
141 return "both values to select must have same type";
143 if (const VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
145 if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
146 return "vector select condition element type must be i1";
147 const VectorType *ET = dyn_cast<VectorType>(Op1->getType());
149 return "selected values for vector select must be vectors";
150 if (ET->getNumElements() != VT->getNumElements())
151 return "vector select requires selected vectors to have "
152 "the same vector length as select condition";
153 } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
154 return "select condition must be i1 or <n x i1>";
160 //===----------------------------------------------------------------------===//
162 //===----------------------------------------------------------------------===//
164 PHINode::PHINode(const PHINode &PN)
165 : Instruction(PN.getType(), Instruction::PHI,
166 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
167 ReservedSpace(PN.getNumOperands()) {
168 Use *OL = OperandList;
169 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
170 OL[i] = PN.getOperand(i);
171 OL[i+1] = PN.getOperand(i+1);
173 SubclassOptionalData = PN.SubclassOptionalData;
176 PHINode::~PHINode() {
178 dropHungoffUses(OperandList);
181 // removeIncomingValue - Remove an incoming value. This is useful if a
182 // predecessor basic block is deleted.
183 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
184 unsigned NumOps = getNumOperands();
185 Use *OL = OperandList;
186 assert(Idx*2 < NumOps && "BB not in PHI node!");
187 Value *Removed = OL[Idx*2];
189 // Move everything after this operand down.
191 // FIXME: we could just swap with the end of the list, then erase. However,
192 // client might not expect this to happen. The code as it is thrashes the
193 // use/def lists, which is kinda lame.
194 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
199 // Nuke the last value.
201 OL[NumOps-2+1].set(0);
202 NumOperands = NumOps-2;
204 // If the PHI node is dead, because it has zero entries, nuke it now.
205 if (NumOps == 2 && DeletePHIIfEmpty) {
206 // If anyone is using this PHI, make them use a dummy value instead...
207 replaceAllUsesWith(UndefValue::get(getType()));
213 /// resizeOperands - resize operands - This adjusts the length of the operands
214 /// list according to the following behavior:
215 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
216 /// of operation. This grows the number of ops by 1.5 times.
217 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
218 /// 3. If NumOps == NumOperands, trim the reserved space.
220 void PHINode::resizeOperands(unsigned NumOps) {
221 unsigned e = getNumOperands();
224 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
225 } else if (NumOps*2 > NumOperands) {
227 if (ReservedSpace >= NumOps) return;
228 } else if (NumOps == NumOperands) {
229 if (ReservedSpace == NumOps) return;
234 ReservedSpace = NumOps;
235 Use *OldOps = OperandList;
236 Use *NewOps = allocHungoffUses(NumOps);
237 std::copy(OldOps, OldOps + e, NewOps);
238 OperandList = NewOps;
239 if (OldOps) Use::zap(OldOps, OldOps + e, true);
242 /// hasConstantValue - If the specified PHI node always merges together the same
243 /// value, return the value, otherwise return null.
245 /// If the PHI has undef operands, but all the rest of the operands are
246 /// some unique value, return that value if it can be proved that the
247 /// value dominates the PHI. If DT is null, use a conservative check,
248 /// otherwise use DT to test for dominance.
250 Value *PHINode::hasConstantValue(DominatorTree *DT) const {
251 // If the PHI node only has one incoming value, eliminate the PHI node.
252 if (getNumIncomingValues() == 1) {
253 if (getIncomingValue(0) != this) // not X = phi X
254 return getIncomingValue(0);
255 return UndefValue::get(getType()); // Self cycle is dead.
258 // Otherwise if all of the incoming values are the same for the PHI, replace
259 // the PHI node with the incoming value.
262 bool HasUndefInput = false;
263 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
264 if (isa<UndefValue>(getIncomingValue(i))) {
265 HasUndefInput = true;
266 } else if (getIncomingValue(i) != this) { // Not the PHI node itself...
267 if (InVal && getIncomingValue(i) != InVal)
268 return 0; // Not the same, bail out.
269 InVal = getIncomingValue(i);
272 // The only case that could cause InVal to be null is if we have a PHI node
273 // that only has entries for itself. In this case, there is no entry into the
274 // loop, so kill the PHI.
276 if (InVal == 0) InVal = UndefValue::get(getType());
278 // If we have a PHI node like phi(X, undef, X), where X is defined by some
279 // instruction, we cannot always return X as the result of the PHI node. Only
280 // do this if X is not an instruction (thus it must dominate the PHI block),
281 // or if the client is prepared to deal with this possibility.
282 if (!HasUndefInput || !isa<Instruction>(InVal))
285 Instruction *IV = cast<Instruction>(InVal);
287 // We have a DominatorTree. Do a precise test.
288 if (!DT->dominates(IV, this))
291 // If it is in the entry block, it obviously dominates everything.
292 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
294 return 0; // Cannot guarantee that InVal dominates this PHINode.
297 // All of the incoming values are the same, return the value now.
302 //===----------------------------------------------------------------------===//
303 // CallInst Implementation
304 //===----------------------------------------------------------------------===//
306 CallInst::~CallInst() {
309 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
310 assert(NumOperands == NumParams+1 && "NumOperands not set up?");
311 Use *OL = OperandList;
314 const FunctionType *FTy =
315 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
316 FTy = FTy; // silence warning.
318 assert((NumParams == FTy->getNumParams() ||
319 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
320 "Calling a function with bad signature!");
321 for (unsigned i = 0; i != NumParams; ++i) {
322 assert((i >= FTy->getNumParams() ||
323 FTy->getParamType(i) == Params[i]->getType()) &&
324 "Calling a function with a bad signature!");
329 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
330 assert(NumOperands == 3 && "NumOperands not set up?");
331 Use *OL = OperandList;
336 const FunctionType *FTy =
337 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
338 FTy = FTy; // silence warning.
340 assert((FTy->getNumParams() == 2 ||
341 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
342 "Calling a function with bad signature");
343 assert((0 >= FTy->getNumParams() ||
344 FTy->getParamType(0) == Actual1->getType()) &&
345 "Calling a function with a bad signature!");
346 assert((1 >= FTy->getNumParams() ||
347 FTy->getParamType(1) == Actual2->getType()) &&
348 "Calling a function with a bad signature!");
351 void CallInst::init(Value *Func, Value *Actual) {
352 assert(NumOperands == 2 && "NumOperands not set up?");
353 Use *OL = OperandList;
357 const FunctionType *FTy =
358 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
359 FTy = FTy; // silence warning.
361 assert((FTy->getNumParams() == 1 ||
362 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
363 "Calling a function with bad signature");
364 assert((0 == FTy->getNumParams() ||
365 FTy->getParamType(0) == Actual->getType()) &&
366 "Calling a function with a bad signature!");
369 void CallInst::init(Value *Func) {
370 assert(NumOperands == 1 && "NumOperands not set up?");
371 Use *OL = OperandList;
374 const FunctionType *FTy =
375 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
376 FTy = FTy; // silence warning.
378 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
381 CallInst::CallInst(Value *Func, Value* Actual, const Twine &Name,
382 Instruction *InsertBefore)
383 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
384 ->getElementType())->getReturnType(),
386 OperandTraits<CallInst>::op_end(this) - 2,
392 CallInst::CallInst(Value *Func, Value* Actual, const Twine &Name,
393 BasicBlock *InsertAtEnd)
394 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
395 ->getElementType())->getReturnType(),
397 OperandTraits<CallInst>::op_end(this) - 2,
402 CallInst::CallInst(Value *Func, const Twine &Name,
403 Instruction *InsertBefore)
404 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
405 ->getElementType())->getReturnType(),
407 OperandTraits<CallInst>::op_end(this) - 1,
413 CallInst::CallInst(Value *Func, const Twine &Name,
414 BasicBlock *InsertAtEnd)
415 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
416 ->getElementType())->getReturnType(),
418 OperandTraits<CallInst>::op_end(this) - 1,
424 CallInst::CallInst(const CallInst &CI)
425 : Instruction(CI.getType(), Instruction::Call,
426 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
427 CI.getNumOperands()) {
428 setAttributes(CI.getAttributes());
429 setTailCall(CI.isTailCall());
430 setCallingConv(CI.getCallingConv());
432 Use *OL = OperandList;
433 Use *InOL = CI.OperandList;
434 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
436 SubclassOptionalData = CI.SubclassOptionalData;
439 void CallInst::addAttribute(unsigned i, Attributes attr) {
440 AttrListPtr PAL = getAttributes();
441 PAL = PAL.addAttr(i, attr);
445 void CallInst::removeAttribute(unsigned i, Attributes attr) {
446 AttrListPtr PAL = getAttributes();
447 PAL = PAL.removeAttr(i, attr);
451 bool CallInst::paramHasAttr(unsigned i, Attributes attr) const {
452 if (AttributeList.paramHasAttr(i, attr))
454 if (const Function *F = getCalledFunction())
455 return F->paramHasAttr(i, attr);
459 /// IsConstantOne - Return true only if val is constant int 1
460 static bool IsConstantOne(Value *val) {
461 assert(val && "IsConstantOne does not work with NULL val");
462 return isa<ConstantInt>(val) && cast<ConstantInt>(val)->isOne();
465 static Instruction *createMalloc(Instruction *InsertBefore,
466 BasicBlock *InsertAtEnd, const Type *IntPtrTy,
467 const Type *AllocTy, Value *AllocSize,
468 Value *ArraySize, Function *MallocF,
470 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
471 "createMalloc needs either InsertBefore or InsertAtEnd");
473 // malloc(type) becomes:
474 // bitcast (i8* malloc(typeSize)) to type*
475 // malloc(type, arraySize) becomes:
476 // bitcast (i8 *malloc(typeSize*arraySize)) to type*
478 ArraySize = ConstantInt::get(IntPtrTy, 1);
479 else if (ArraySize->getType() != IntPtrTy) {
481 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
484 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
488 if (!IsConstantOne(ArraySize)) {
489 if (IsConstantOne(AllocSize)) {
490 AllocSize = ArraySize; // Operand * 1 = Operand
491 } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
492 Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
494 // Malloc arg is constant product of type size and array size
495 AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
497 // Multiply type size by the array size...
499 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
500 "mallocsize", InsertBefore);
502 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
503 "mallocsize", InsertAtEnd);
507 assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
508 // Create the call to Malloc.
509 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
510 Module* M = BB->getParent()->getParent();
511 const Type *BPTy = Type::getInt8PtrTy(BB->getContext());
512 Value *MallocFunc = MallocF;
514 // prototype malloc as "void *malloc(size_t)"
515 MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy, NULL);
516 const PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
517 CallInst *MCall = NULL;
518 Instruction *Result = NULL;
520 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall", InsertBefore);
522 if (Result->getType() != AllocPtrType)
523 // Create a cast instruction to convert to the right type...
524 Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
526 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall");
528 if (Result->getType() != AllocPtrType) {
529 InsertAtEnd->getInstList().push_back(MCall);
530 // Create a cast instruction to convert to the right type...
531 Result = new BitCastInst(MCall, AllocPtrType, Name);
534 MCall->setTailCall();
535 if (Function *F = dyn_cast<Function>(MallocFunc)) {
536 MCall->setCallingConv(F->getCallingConv());
537 if (!F->doesNotAlias(0)) F->setDoesNotAlias(0);
539 assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
544 /// CreateMalloc - Generate the IR for a call to malloc:
545 /// 1. Compute the malloc call's argument as the specified type's size,
546 /// possibly multiplied by the array size if the array size is not
548 /// 2. Call malloc with that argument.
549 /// 3. Bitcast the result of the malloc call to the specified type.
550 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
551 const Type *IntPtrTy, const Type *AllocTy,
552 Value *AllocSize, Value *ArraySize,
554 return createMalloc(InsertBefore, NULL, IntPtrTy, AllocTy, AllocSize,
555 ArraySize, NULL, Name);
558 /// CreateMalloc - Generate the IR for a call to malloc:
559 /// 1. Compute the malloc call's argument as the specified type's size,
560 /// possibly multiplied by the array size if the array size is not
562 /// 2. Call malloc with that argument.
563 /// 3. Bitcast the result of the malloc call to the specified type.
564 /// Note: This function does not add the bitcast to the basic block, that is the
565 /// responsibility of the caller.
566 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
567 const Type *IntPtrTy, const Type *AllocTy,
568 Value *AllocSize, Value *ArraySize,
569 Function *MallocF, const Twine &Name) {
570 return createMalloc(NULL, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
571 ArraySize, MallocF, Name);
574 static Instruction* createFree(Value* Source, Instruction *InsertBefore,
575 BasicBlock *InsertAtEnd) {
576 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
577 "createFree needs either InsertBefore or InsertAtEnd");
578 assert(Source->getType()->isPointerTy() &&
579 "Can not free something of nonpointer type!");
581 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
582 Module* M = BB->getParent()->getParent();
584 const Type *VoidTy = Type::getVoidTy(M->getContext());
585 const Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
586 // prototype free as "void free(void*)"
587 Value *FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy, NULL);
588 CallInst* Result = NULL;
589 Value *PtrCast = Source;
591 if (Source->getType() != IntPtrTy)
592 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
593 Result = CallInst::Create(FreeFunc, PtrCast, "", InsertBefore);
595 if (Source->getType() != IntPtrTy)
596 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
597 Result = CallInst::Create(FreeFunc, PtrCast, "");
599 Result->setTailCall();
600 if (Function *F = dyn_cast<Function>(FreeFunc))
601 Result->setCallingConv(F->getCallingConv());
606 /// CreateFree - Generate the IR for a call to the builtin free function.
607 void CallInst::CreateFree(Value* Source, Instruction *InsertBefore) {
608 createFree(Source, InsertBefore, NULL);
611 /// CreateFree - Generate the IR for a call to the builtin free function.
612 /// Note: This function does not add the call to the basic block, that is the
613 /// responsibility of the caller.
614 Instruction* CallInst::CreateFree(Value* Source, BasicBlock *InsertAtEnd) {
615 Instruction* FreeCall = createFree(Source, NULL, InsertAtEnd);
616 assert(FreeCall && "CreateFree did not create a CallInst");
620 //===----------------------------------------------------------------------===//
621 // InvokeInst Implementation
622 //===----------------------------------------------------------------------===//
624 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
625 Value* const *Args, unsigned NumArgs) {
626 assert(NumOperands == 3+NumArgs && "NumOperands not set up?");
629 Op<-1>() = IfException;
630 const FunctionType *FTy =
631 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
632 FTy = FTy; // silence warning.
634 assert(((NumArgs == FTy->getNumParams()) ||
635 (FTy->isVarArg() && NumArgs > FTy->getNumParams())) &&
636 "Invoking a function with bad signature");
638 Use *OL = OperandList;
639 for (unsigned i = 0, e = NumArgs; i != e; i++) {
640 assert((i >= FTy->getNumParams() ||
641 FTy->getParamType(i) == Args[i]->getType()) &&
642 "Invoking a function with a bad signature!");
648 InvokeInst::InvokeInst(const InvokeInst &II)
649 : TerminatorInst(II.getType(), Instruction::Invoke,
650 OperandTraits<InvokeInst>::op_end(this)
651 - II.getNumOperands(),
652 II.getNumOperands()) {
653 setAttributes(II.getAttributes());
654 setCallingConv(II.getCallingConv());
655 Use *OL = OperandList, *InOL = II.OperandList;
656 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
658 SubclassOptionalData = II.SubclassOptionalData;
661 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
662 return getSuccessor(idx);
664 unsigned InvokeInst::getNumSuccessorsV() const {
665 return getNumSuccessors();
667 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
668 return setSuccessor(idx, B);
671 bool InvokeInst::paramHasAttr(unsigned i, Attributes attr) const {
672 if (AttributeList.paramHasAttr(i, attr))
674 if (const Function *F = getCalledFunction())
675 return F->paramHasAttr(i, attr);
679 void InvokeInst::addAttribute(unsigned i, Attributes attr) {
680 AttrListPtr PAL = getAttributes();
681 PAL = PAL.addAttr(i, attr);
685 void InvokeInst::removeAttribute(unsigned i, Attributes attr) {
686 AttrListPtr PAL = getAttributes();
687 PAL = PAL.removeAttr(i, attr);
692 //===----------------------------------------------------------------------===//
693 // ReturnInst Implementation
694 //===----------------------------------------------------------------------===//
696 ReturnInst::ReturnInst(const ReturnInst &RI)
697 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret,
698 OperandTraits<ReturnInst>::op_end(this) -
700 RI.getNumOperands()) {
701 if (RI.getNumOperands())
702 Op<0>() = RI.Op<0>();
703 SubclassOptionalData = RI.SubclassOptionalData;
706 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
707 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
708 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
713 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
714 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
715 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
720 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
721 : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret,
722 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
725 unsigned ReturnInst::getNumSuccessorsV() const {
726 return getNumSuccessors();
729 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
730 /// emit the vtable for the class in this translation unit.
731 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
732 llvm_unreachable("ReturnInst has no successors!");
735 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
736 llvm_unreachable("ReturnInst has no successors!");
740 ReturnInst::~ReturnInst() {
743 //===----------------------------------------------------------------------===//
744 // UnwindInst Implementation
745 //===----------------------------------------------------------------------===//
747 UnwindInst::UnwindInst(LLVMContext &Context, Instruction *InsertBefore)
748 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind,
749 0, 0, InsertBefore) {
751 UnwindInst::UnwindInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
752 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind,
757 unsigned UnwindInst::getNumSuccessorsV() const {
758 return getNumSuccessors();
761 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
762 llvm_unreachable("UnwindInst has no successors!");
765 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
766 llvm_unreachable("UnwindInst has no successors!");
770 //===----------------------------------------------------------------------===//
771 // UnreachableInst Implementation
772 //===----------------------------------------------------------------------===//
774 UnreachableInst::UnreachableInst(LLVMContext &Context,
775 Instruction *InsertBefore)
776 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
777 0, 0, InsertBefore) {
779 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
780 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
784 unsigned UnreachableInst::getNumSuccessorsV() const {
785 return getNumSuccessors();
788 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
789 llvm_unreachable("UnwindInst has no successors!");
792 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
793 llvm_unreachable("UnwindInst has no successors!");
797 //===----------------------------------------------------------------------===//
798 // BranchInst Implementation
799 //===----------------------------------------------------------------------===//
801 void BranchInst::AssertOK() {
803 assert(getCondition()->getType()->isIntegerTy(1) &&
804 "May only branch on boolean predicates!");
807 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
808 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
809 OperandTraits<BranchInst>::op_end(this) - 1,
811 assert(IfTrue != 0 && "Branch destination may not be null!");
814 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
815 Instruction *InsertBefore)
816 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
817 OperandTraits<BranchInst>::op_end(this) - 3,
827 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
828 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
829 OperandTraits<BranchInst>::op_end(this) - 1,
831 assert(IfTrue != 0 && "Branch destination may not be null!");
835 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
836 BasicBlock *InsertAtEnd)
837 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
838 OperandTraits<BranchInst>::op_end(this) - 3,
849 BranchInst::BranchInst(const BranchInst &BI) :
850 TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br,
851 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
852 BI.getNumOperands()) {
853 Op<-1>() = BI.Op<-1>();
854 if (BI.getNumOperands() != 1) {
855 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
856 Op<-3>() = BI.Op<-3>();
857 Op<-2>() = BI.Op<-2>();
859 SubclassOptionalData = BI.SubclassOptionalData;
863 Use* Use::getPrefix() {
864 PointerIntPair<Use**, 2, PrevPtrTag> &PotentialPrefix(this[-1].Prev);
865 if (PotentialPrefix.getOpaqueValue())
868 return reinterpret_cast<Use*>((char*)&PotentialPrefix + 1);
871 BranchInst::~BranchInst() {
872 if (NumOperands == 1) {
873 if (Use *Prefix = OperandList->getPrefix()) {
876 // mark OperandList to have a special value for scrutiny
877 // by baseclass destructors and operator delete
878 OperandList = Prefix;
881 OperandList = op_begin();
887 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
888 return getSuccessor(idx);
890 unsigned BranchInst::getNumSuccessorsV() const {
891 return getNumSuccessors();
893 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
894 setSuccessor(idx, B);
898 //===----------------------------------------------------------------------===//
899 // AllocaInst Implementation
900 //===----------------------------------------------------------------------===//
902 static Value *getAISize(LLVMContext &Context, Value *Amt) {
904 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
906 assert(!isa<BasicBlock>(Amt) &&
907 "Passed basic block into allocation size parameter! Use other ctor");
908 assert(Amt->getType()->isIntegerTy(32) &&
909 "Allocation array size is not a 32-bit integer!");
914 AllocaInst::AllocaInst(const Type *Ty, Value *ArraySize,
915 const Twine &Name, Instruction *InsertBefore)
916 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
917 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
919 assert(!Ty->isVoidTy() && "Cannot allocate void!");
923 AllocaInst::AllocaInst(const Type *Ty, Value *ArraySize,
924 const Twine &Name, BasicBlock *InsertAtEnd)
925 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
926 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
928 assert(!Ty->isVoidTy() && "Cannot allocate void!");
932 AllocaInst::AllocaInst(const Type *Ty, const Twine &Name,
933 Instruction *InsertBefore)
934 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
935 getAISize(Ty->getContext(), 0), InsertBefore) {
937 assert(!Ty->isVoidTy() && "Cannot allocate void!");
941 AllocaInst::AllocaInst(const Type *Ty, const Twine &Name,
942 BasicBlock *InsertAtEnd)
943 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
944 getAISize(Ty->getContext(), 0), InsertAtEnd) {
946 assert(!Ty->isVoidTy() && "Cannot allocate void!");
950 AllocaInst::AllocaInst(const Type *Ty, Value *ArraySize, unsigned Align,
951 const Twine &Name, Instruction *InsertBefore)
952 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
953 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
955 assert(!Ty->isVoidTy() && "Cannot allocate void!");
959 AllocaInst::AllocaInst(const Type *Ty, Value *ArraySize, unsigned Align,
960 const Twine &Name, BasicBlock *InsertAtEnd)
961 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
962 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
964 assert(!Ty->isVoidTy() && "Cannot allocate void!");
968 // Out of line virtual method, so the vtable, etc has a home.
969 AllocaInst::~AllocaInst() {
972 void AllocaInst::setAlignment(unsigned Align) {
973 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
974 setInstructionSubclassData(Log2_32(Align) + 1);
975 assert(getAlignment() == Align && "Alignment representation error!");
978 bool AllocaInst::isArrayAllocation() const {
979 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
980 return CI->getZExtValue() != 1;
984 const Type *AllocaInst::getAllocatedType() const {
985 return getType()->getElementType();
988 /// isStaticAlloca - Return true if this alloca is in the entry block of the
989 /// function and is a constant size. If so, the code generator will fold it
990 /// into the prolog/epilog code, so it is basically free.
991 bool AllocaInst::isStaticAlloca() const {
992 // Must be constant size.
993 if (!isa<ConstantInt>(getArraySize())) return false;
995 // Must be in the entry block.
996 const BasicBlock *Parent = getParent();
997 return Parent == &Parent->getParent()->front();
1000 //===----------------------------------------------------------------------===//
1001 // LoadInst Implementation
1002 //===----------------------------------------------------------------------===//
1004 void LoadInst::AssertOK() {
1005 assert(getOperand(0)->getType()->isPointerTy() &&
1006 "Ptr must have pointer type.");
1009 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
1010 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1011 Load, Ptr, InsertBef) {
1018 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
1019 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1020 Load, Ptr, InsertAE) {
1027 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1028 Instruction *InsertBef)
1029 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1030 Load, Ptr, InsertBef) {
1031 setVolatile(isVolatile);
1037 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1038 unsigned Align, Instruction *InsertBef)
1039 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1040 Load, Ptr, InsertBef) {
1041 setVolatile(isVolatile);
1042 setAlignment(Align);
1047 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1048 unsigned Align, BasicBlock *InsertAE)
1049 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1050 Load, Ptr, InsertAE) {
1051 setVolatile(isVolatile);
1052 setAlignment(Align);
1057 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1058 BasicBlock *InsertAE)
1059 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1060 Load, Ptr, InsertAE) {
1061 setVolatile(isVolatile);
1069 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
1070 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1071 Load, Ptr, InsertBef) {
1075 if (Name && Name[0]) setName(Name);
1078 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
1079 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1080 Load, Ptr, InsertAE) {
1084 if (Name && Name[0]) setName(Name);
1087 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1088 Instruction *InsertBef)
1089 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1090 Load, Ptr, InsertBef) {
1091 setVolatile(isVolatile);
1094 if (Name && Name[0]) setName(Name);
1097 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1098 BasicBlock *InsertAE)
1099 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1100 Load, Ptr, InsertAE) {
1101 setVolatile(isVolatile);
1104 if (Name && Name[0]) setName(Name);
1107 void LoadInst::setAlignment(unsigned Align) {
1108 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1109 setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
1110 ((Log2_32(Align)+1)<<1));
1113 //===----------------------------------------------------------------------===//
1114 // StoreInst Implementation
1115 //===----------------------------------------------------------------------===//
1117 void StoreInst::AssertOK() {
1118 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1119 assert(getOperand(1)->getType()->isPointerTy() &&
1120 "Ptr must have pointer type!");
1121 assert(getOperand(0)->getType() ==
1122 cast<PointerType>(getOperand(1)->getType())->getElementType()
1123 && "Ptr must be a pointer to Val type!");
1127 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
1128 : Instruction(Type::getVoidTy(val->getContext()), Store,
1129 OperandTraits<StoreInst>::op_begin(this),
1130 OperandTraits<StoreInst>::operands(this),
1139 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
1140 : Instruction(Type::getVoidTy(val->getContext()), Store,
1141 OperandTraits<StoreInst>::op_begin(this),
1142 OperandTraits<StoreInst>::operands(this),
1151 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1152 Instruction *InsertBefore)
1153 : Instruction(Type::getVoidTy(val->getContext()), Store,
1154 OperandTraits<StoreInst>::op_begin(this),
1155 OperandTraits<StoreInst>::operands(this),
1159 setVolatile(isVolatile);
1164 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1165 unsigned Align, Instruction *InsertBefore)
1166 : Instruction(Type::getVoidTy(val->getContext()), Store,
1167 OperandTraits<StoreInst>::op_begin(this),
1168 OperandTraits<StoreInst>::operands(this),
1172 setVolatile(isVolatile);
1173 setAlignment(Align);
1177 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1178 unsigned Align, BasicBlock *InsertAtEnd)
1179 : Instruction(Type::getVoidTy(val->getContext()), Store,
1180 OperandTraits<StoreInst>::op_begin(this),
1181 OperandTraits<StoreInst>::operands(this),
1185 setVolatile(isVolatile);
1186 setAlignment(Align);
1190 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1191 BasicBlock *InsertAtEnd)
1192 : Instruction(Type::getVoidTy(val->getContext()), Store,
1193 OperandTraits<StoreInst>::op_begin(this),
1194 OperandTraits<StoreInst>::operands(this),
1198 setVolatile(isVolatile);
1203 void StoreInst::setAlignment(unsigned Align) {
1204 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1205 setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
1206 ((Log2_32(Align)+1) << 1));
1209 //===----------------------------------------------------------------------===//
1210 // GetElementPtrInst Implementation
1211 //===----------------------------------------------------------------------===//
1213 static unsigned retrieveAddrSpace(const Value *Val) {
1214 return cast<PointerType>(Val->getType())->getAddressSpace();
1217 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx,
1218 const Twine &Name) {
1219 assert(NumOperands == 1+NumIdx && "NumOperands not initialized?");
1220 Use *OL = OperandList;
1223 for (unsigned i = 0; i != NumIdx; ++i)
1229 void GetElementPtrInst::init(Value *Ptr, Value *Idx, const Twine &Name) {
1230 assert(NumOperands == 2 && "NumOperands not initialized?");
1231 Use *OL = OperandList;
1238 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1239 : Instruction(GEPI.getType(), GetElementPtr,
1240 OperandTraits<GetElementPtrInst>::op_end(this)
1241 - GEPI.getNumOperands(),
1242 GEPI.getNumOperands()) {
1243 Use *OL = OperandList;
1244 Use *GEPIOL = GEPI.OperandList;
1245 for (unsigned i = 0, E = NumOperands; i != E; ++i)
1247 SubclassOptionalData = GEPI.SubclassOptionalData;
1250 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1251 const Twine &Name, Instruction *InBe)
1252 : Instruction(PointerType::get(
1253 checkType(getIndexedType(Ptr->getType(),Idx)), retrieveAddrSpace(Ptr)),
1255 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1257 init(Ptr, Idx, Name);
1260 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1261 const Twine &Name, BasicBlock *IAE)
1262 : Instruction(PointerType::get(
1263 checkType(getIndexedType(Ptr->getType(),Idx)),
1264 retrieveAddrSpace(Ptr)),
1266 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1268 init(Ptr, Idx, Name);
1271 /// getIndexedType - Returns the type of the element that would be accessed with
1272 /// a gep instruction with the specified parameters.
1274 /// The Idxs pointer should point to a continuous piece of memory containing the
1275 /// indices, either as Value* or uint64_t.
1277 /// A null type is returned if the indices are invalid for the specified
1280 template <typename IndexTy>
1281 static const Type* getIndexedTypeInternal(const Type *Ptr, IndexTy const *Idxs,
1283 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1284 if (!PTy) return 0; // Type isn't a pointer type!
1285 const Type *Agg = PTy->getElementType();
1287 // Handle the special case of the empty set index set, which is always valid.
1291 // If there is at least one index, the top level type must be sized, otherwise
1292 // it cannot be 'stepped over'. We explicitly allow abstract types (those
1293 // that contain opaque types) under the assumption that it will be resolved to
1294 // a sane type later.
1295 if (!Agg->isSized() && !Agg->isAbstract())
1298 unsigned CurIdx = 1;
1299 for (; CurIdx != NumIdx; ++CurIdx) {
1300 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1301 if (!CT || CT->isPointerTy()) return 0;
1302 IndexTy Index = Idxs[CurIdx];
1303 if (!CT->indexValid(Index)) return 0;
1304 Agg = CT->getTypeAtIndex(Index);
1306 // If the new type forwards to another type, then it is in the middle
1307 // of being refined to another type (and hence, may have dropped all
1308 // references to what it was using before). So, use the new forwarded
1310 if (const Type *Ty = Agg->getForwardedType())
1313 return CurIdx == NumIdx ? Agg : 0;
1316 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1319 return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1322 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1323 uint64_t const *Idxs,
1325 return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1328 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1329 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1330 if (!PTy) return 0; // Type isn't a pointer type!
1332 // Check the pointer index.
1333 if (!PTy->indexValid(Idx)) return 0;
1335 return PTy->getElementType();
1339 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1340 /// zeros. If so, the result pointer and the first operand have the same
1341 /// value, just potentially different types.
1342 bool GetElementPtrInst::hasAllZeroIndices() const {
1343 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1344 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1345 if (!CI->isZero()) return false;
1353 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1354 /// constant integers. If so, the result pointer and the first operand have
1355 /// a constant offset between them.
1356 bool GetElementPtrInst::hasAllConstantIndices() const {
1357 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1358 if (!isa<ConstantInt>(getOperand(i)))
1364 void GetElementPtrInst::setIsInBounds(bool B) {
1365 cast<GEPOperator>(this)->setIsInBounds(B);
1368 bool GetElementPtrInst::isInBounds() const {
1369 return cast<GEPOperator>(this)->isInBounds();
1372 //===----------------------------------------------------------------------===//
1373 // ExtractElementInst Implementation
1374 //===----------------------------------------------------------------------===//
1376 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1378 Instruction *InsertBef)
1379 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1381 OperandTraits<ExtractElementInst>::op_begin(this),
1383 assert(isValidOperands(Val, Index) &&
1384 "Invalid extractelement instruction operands!");
1390 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1392 BasicBlock *InsertAE)
1393 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1395 OperandTraits<ExtractElementInst>::op_begin(this),
1397 assert(isValidOperands(Val, Index) &&
1398 "Invalid extractelement instruction operands!");
1406 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1407 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy(32))
1413 //===----------------------------------------------------------------------===//
1414 // InsertElementInst Implementation
1415 //===----------------------------------------------------------------------===//
1417 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1419 Instruction *InsertBef)
1420 : Instruction(Vec->getType(), InsertElement,
1421 OperandTraits<InsertElementInst>::op_begin(this),
1423 assert(isValidOperands(Vec, Elt, Index) &&
1424 "Invalid insertelement instruction operands!");
1431 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1433 BasicBlock *InsertAE)
1434 : Instruction(Vec->getType(), InsertElement,
1435 OperandTraits<InsertElementInst>::op_begin(this),
1437 assert(isValidOperands(Vec, Elt, Index) &&
1438 "Invalid insertelement instruction operands!");
1446 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1447 const Value *Index) {
1448 if (!Vec->getType()->isVectorTy())
1449 return false; // First operand of insertelement must be vector type.
1451 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1452 return false;// Second operand of insertelement must be vector element type.
1454 if (!Index->getType()->isIntegerTy(32))
1455 return false; // Third operand of insertelement must be i32.
1460 //===----------------------------------------------------------------------===//
1461 // ShuffleVectorInst Implementation
1462 //===----------------------------------------------------------------------===//
1464 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1466 Instruction *InsertBefore)
1467 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1468 cast<VectorType>(Mask->getType())->getNumElements()),
1470 OperandTraits<ShuffleVectorInst>::op_begin(this),
1471 OperandTraits<ShuffleVectorInst>::operands(this),
1473 assert(isValidOperands(V1, V2, Mask) &&
1474 "Invalid shuffle vector instruction operands!");
1481 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1483 BasicBlock *InsertAtEnd)
1484 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1485 cast<VectorType>(Mask->getType())->getNumElements()),
1487 OperandTraits<ShuffleVectorInst>::op_begin(this),
1488 OperandTraits<ShuffleVectorInst>::operands(this),
1490 assert(isValidOperands(V1, V2, Mask) &&
1491 "Invalid shuffle vector instruction operands!");
1499 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1500 const Value *Mask) {
1501 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
1504 const VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1505 if (!isa<Constant>(Mask) || MaskTy == 0 ||
1506 !MaskTy->getElementType()->isIntegerTy(32))
1511 /// getMaskValue - Return the index from the shuffle mask for the specified
1512 /// output result. This is either -1 if the element is undef or a number less
1513 /// than 2*numelements.
1514 int ShuffleVectorInst::getMaskValue(unsigned i) const {
1515 const Constant *Mask = cast<Constant>(getOperand(2));
1516 if (isa<UndefValue>(Mask)) return -1;
1517 if (isa<ConstantAggregateZero>(Mask)) return 0;
1518 const ConstantVector *MaskCV = cast<ConstantVector>(Mask);
1519 assert(i < MaskCV->getNumOperands() && "Index out of range");
1521 if (isa<UndefValue>(MaskCV->getOperand(i)))
1523 return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
1526 //===----------------------------------------------------------------------===//
1527 // InsertValueInst Class
1528 //===----------------------------------------------------------------------===//
1530 void InsertValueInst::init(Value *Agg, Value *Val, const unsigned *Idx,
1531 unsigned NumIdx, const Twine &Name) {
1532 assert(NumOperands == 2 && "NumOperands not initialized?");
1536 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1540 void InsertValueInst::init(Value *Agg, Value *Val, unsigned Idx,
1541 const Twine &Name) {
1542 assert(NumOperands == 2 && "NumOperands not initialized?");
1546 Indices.push_back(Idx);
1550 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1551 : Instruction(IVI.getType(), InsertValue,
1552 OperandTraits<InsertValueInst>::op_begin(this), 2),
1553 Indices(IVI.Indices) {
1554 Op<0>() = IVI.getOperand(0);
1555 Op<1>() = IVI.getOperand(1);
1556 SubclassOptionalData = IVI.SubclassOptionalData;
1559 InsertValueInst::InsertValueInst(Value *Agg,
1563 Instruction *InsertBefore)
1564 : Instruction(Agg->getType(), InsertValue,
1565 OperandTraits<InsertValueInst>::op_begin(this),
1567 init(Agg, Val, Idx, Name);
1570 InsertValueInst::InsertValueInst(Value *Agg,
1574 BasicBlock *InsertAtEnd)
1575 : Instruction(Agg->getType(), InsertValue,
1576 OperandTraits<InsertValueInst>::op_begin(this),
1578 init(Agg, Val, Idx, Name);
1581 //===----------------------------------------------------------------------===//
1582 // ExtractValueInst Class
1583 //===----------------------------------------------------------------------===//
1585 void ExtractValueInst::init(const unsigned *Idx, unsigned NumIdx,
1586 const Twine &Name) {
1587 assert(NumOperands == 1 && "NumOperands not initialized?");
1589 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1593 void ExtractValueInst::init(unsigned Idx, const Twine &Name) {
1594 assert(NumOperands == 1 && "NumOperands not initialized?");
1596 Indices.push_back(Idx);
1600 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1601 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1602 Indices(EVI.Indices) {
1603 SubclassOptionalData = EVI.SubclassOptionalData;
1606 // getIndexedType - Returns the type of the element that would be extracted
1607 // with an extractvalue instruction with the specified parameters.
1609 // A null type is returned if the indices are invalid for the specified
1612 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1613 const unsigned *Idxs,
1615 unsigned CurIdx = 0;
1616 for (; CurIdx != NumIdx; ++CurIdx) {
1617 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1618 if (!CT || CT->isPointerTy() || CT->isVectorTy()) return 0;
1619 unsigned Index = Idxs[CurIdx];
1620 if (!CT->indexValid(Index)) return 0;
1621 Agg = CT->getTypeAtIndex(Index);
1623 // If the new type forwards to another type, then it is in the middle
1624 // of being refined to another type (and hence, may have dropped all
1625 // references to what it was using before). So, use the new forwarded
1627 if (const Type *Ty = Agg->getForwardedType())
1630 return CurIdx == NumIdx ? Agg : 0;
1633 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1635 return getIndexedType(Agg, &Idx, 1);
1638 //===----------------------------------------------------------------------===//
1639 // BinaryOperator Class
1640 //===----------------------------------------------------------------------===//
1642 /// AdjustIType - Map Add, Sub, and Mul to FAdd, FSub, and FMul when the
1643 /// type is floating-point, to help provide compatibility with an older API.
1645 static BinaryOperator::BinaryOps AdjustIType(BinaryOperator::BinaryOps iType,
1647 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1648 if (Ty->isFPOrFPVectorTy()) {
1649 if (iType == BinaryOperator::Add) iType = BinaryOperator::FAdd;
1650 else if (iType == BinaryOperator::Sub) iType = BinaryOperator::FSub;
1651 else if (iType == BinaryOperator::Mul) iType = BinaryOperator::FMul;
1656 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1657 const Type *Ty, const Twine &Name,
1658 Instruction *InsertBefore)
1659 : Instruction(Ty, AdjustIType(iType, Ty),
1660 OperandTraits<BinaryOperator>::op_begin(this),
1661 OperandTraits<BinaryOperator>::operands(this),
1665 init(AdjustIType(iType, Ty));
1669 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1670 const Type *Ty, const Twine &Name,
1671 BasicBlock *InsertAtEnd)
1672 : Instruction(Ty, AdjustIType(iType, Ty),
1673 OperandTraits<BinaryOperator>::op_begin(this),
1674 OperandTraits<BinaryOperator>::operands(this),
1678 init(AdjustIType(iType, Ty));
1683 void BinaryOperator::init(BinaryOps iType) {
1684 Value *LHS = getOperand(0), *RHS = getOperand(1);
1685 LHS = LHS; RHS = RHS; // Silence warnings.
1686 assert(LHS->getType() == RHS->getType() &&
1687 "Binary operator operand types must match!");
1692 assert(getType() == LHS->getType() &&
1693 "Arithmetic operation should return same type as operands!");
1694 assert(getType()->isIntOrIntVectorTy() &&
1695 "Tried to create an integer operation on a non-integer type!");
1697 case FAdd: case FSub:
1699 assert(getType() == LHS->getType() &&
1700 "Arithmetic operation should return same type as operands!");
1701 assert(getType()->isFPOrFPVectorTy() &&
1702 "Tried to create a floating-point operation on a "
1703 "non-floating-point type!");
1707 assert(getType() == LHS->getType() &&
1708 "Arithmetic operation should return same type as operands!");
1709 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1710 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1711 "Incorrect operand type (not integer) for S/UDIV");
1714 assert(getType() == LHS->getType() &&
1715 "Arithmetic operation should return same type as operands!");
1716 assert(getType()->isFPOrFPVectorTy() &&
1717 "Incorrect operand type (not floating point) for FDIV");
1721 assert(getType() == LHS->getType() &&
1722 "Arithmetic operation should return same type as operands!");
1723 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1724 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1725 "Incorrect operand type (not integer) for S/UREM");
1728 assert(getType() == LHS->getType() &&
1729 "Arithmetic operation should return same type as operands!");
1730 assert(getType()->isFPOrFPVectorTy() &&
1731 "Incorrect operand type (not floating point) for FREM");
1736 assert(getType() == LHS->getType() &&
1737 "Shift operation should return same type as operands!");
1738 assert((getType()->isIntegerTy() ||
1739 (getType()->isVectorTy() &&
1740 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1741 "Tried to create a shift operation on a non-integral type!");
1745 assert(getType() == LHS->getType() &&
1746 "Logical operation should return same type as operands!");
1747 assert((getType()->isIntegerTy() ||
1748 (getType()->isVectorTy() &&
1749 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1750 "Tried to create a logical operation on a non-integral type!");
1758 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1760 Instruction *InsertBefore) {
1761 assert(S1->getType() == S2->getType() &&
1762 "Cannot create binary operator with two operands of differing type!");
1763 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1766 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1768 BasicBlock *InsertAtEnd) {
1769 BinaryOperator *Res = Create(Op, S1, S2, Name);
1770 InsertAtEnd->getInstList().push_back(Res);
1774 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1775 Instruction *InsertBefore) {
1776 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1777 return new BinaryOperator(Instruction::Sub,
1779 Op->getType(), Name, InsertBefore);
1782 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1783 BasicBlock *InsertAtEnd) {
1784 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1785 return new BinaryOperator(Instruction::Sub,
1787 Op->getType(), Name, InsertAtEnd);
1790 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1791 Instruction *InsertBefore) {
1792 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1793 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
1796 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1797 BasicBlock *InsertAtEnd) {
1798 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1799 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
1802 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1803 Instruction *InsertBefore) {
1804 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1805 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
1808 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1809 BasicBlock *InsertAtEnd) {
1810 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1811 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
1814 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1815 Instruction *InsertBefore) {
1816 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1817 return new BinaryOperator(Instruction::FSub,
1819 Op->getType(), Name, InsertBefore);
1822 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1823 BasicBlock *InsertAtEnd) {
1824 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1825 return new BinaryOperator(Instruction::FSub,
1827 Op->getType(), Name, InsertAtEnd);
1830 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1831 Instruction *InsertBefore) {
1833 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1834 C = Constant::getAllOnesValue(PTy->getElementType());
1835 C = ConstantVector::get(
1836 std::vector<Constant*>(PTy->getNumElements(), C));
1838 C = Constant::getAllOnesValue(Op->getType());
1841 return new BinaryOperator(Instruction::Xor, Op, C,
1842 Op->getType(), Name, InsertBefore);
1845 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1846 BasicBlock *InsertAtEnd) {
1848 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1849 // Create a vector of all ones values.
1850 Constant *Elt = Constant::getAllOnesValue(PTy->getElementType());
1851 AllOnes = ConstantVector::get(
1852 std::vector<Constant*>(PTy->getNumElements(), Elt));
1854 AllOnes = Constant::getAllOnesValue(Op->getType());
1857 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1858 Op->getType(), Name, InsertAtEnd);
1862 // isConstantAllOnes - Helper function for several functions below
1863 static inline bool isConstantAllOnes(const Value *V) {
1864 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1865 return CI->isAllOnesValue();
1866 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1867 return CV->isAllOnesValue();
1871 bool BinaryOperator::isNeg(const Value *V) {
1872 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1873 if (Bop->getOpcode() == Instruction::Sub)
1874 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1875 return C->isNegativeZeroValue();
1879 bool BinaryOperator::isFNeg(const Value *V) {
1880 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1881 if (Bop->getOpcode() == Instruction::FSub)
1882 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1883 return C->isNegativeZeroValue();
1887 bool BinaryOperator::isNot(const Value *V) {
1888 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1889 return (Bop->getOpcode() == Instruction::Xor &&
1890 (isConstantAllOnes(Bop->getOperand(1)) ||
1891 isConstantAllOnes(Bop->getOperand(0))));
1895 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1896 return cast<BinaryOperator>(BinOp)->getOperand(1);
1899 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1900 return getNegArgument(const_cast<Value*>(BinOp));
1903 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
1904 return cast<BinaryOperator>(BinOp)->getOperand(1);
1907 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
1908 return getFNegArgument(const_cast<Value*>(BinOp));
1911 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1912 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1913 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1914 Value *Op0 = BO->getOperand(0);
1915 Value *Op1 = BO->getOperand(1);
1916 if (isConstantAllOnes(Op0)) return Op1;
1918 assert(isConstantAllOnes(Op1));
1922 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1923 return getNotArgument(const_cast<Value*>(BinOp));
1927 // swapOperands - Exchange the two operands to this instruction. This
1928 // instruction is safe to use on any binary instruction and does not
1929 // modify the semantics of the instruction. If the instruction is
1930 // order dependent (SetLT f.e.) the opcode is changed.
1932 bool BinaryOperator::swapOperands() {
1933 if (!isCommutative())
1934 return true; // Can't commute operands
1935 Op<0>().swap(Op<1>());
1939 void BinaryOperator::setHasNoUnsignedWrap(bool b) {
1940 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
1943 void BinaryOperator::setHasNoSignedWrap(bool b) {
1944 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
1947 void BinaryOperator::setIsExact(bool b) {
1948 cast<SDivOperator>(this)->setIsExact(b);
1951 bool BinaryOperator::hasNoUnsignedWrap() const {
1952 return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap();
1955 bool BinaryOperator::hasNoSignedWrap() const {
1956 return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap();
1959 bool BinaryOperator::isExact() const {
1960 return cast<SDivOperator>(this)->isExact();
1963 //===----------------------------------------------------------------------===//
1965 //===----------------------------------------------------------------------===//
1967 // Just determine if this cast only deals with integral->integral conversion.
1968 bool CastInst::isIntegerCast() const {
1969 switch (getOpcode()) {
1970 default: return false;
1971 case Instruction::ZExt:
1972 case Instruction::SExt:
1973 case Instruction::Trunc:
1975 case Instruction::BitCast:
1976 return getOperand(0)->getType()->isIntegerTy() &&
1977 getType()->isIntegerTy();
1981 bool CastInst::isLosslessCast() const {
1982 // Only BitCast can be lossless, exit fast if we're not BitCast
1983 if (getOpcode() != Instruction::BitCast)
1986 // Identity cast is always lossless
1987 const Type* SrcTy = getOperand(0)->getType();
1988 const Type* DstTy = getType();
1992 // Pointer to pointer is always lossless.
1993 if (SrcTy->isPointerTy())
1994 return DstTy->isPointerTy();
1995 return false; // Other types have no identity values
1998 /// This function determines if the CastInst does not require any bits to be
1999 /// changed in order to effect the cast. Essentially, it identifies cases where
2000 /// no code gen is necessary for the cast, hence the name no-op cast. For
2001 /// example, the following are all no-op casts:
2002 /// # bitcast i32* %x to i8*
2003 /// # bitcast <2 x i32> %x to <4 x i16>
2004 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
2005 /// @brief Determine if a cast is a no-op.
2006 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
2007 switch (getOpcode()) {
2009 assert(!"Invalid CastOp");
2010 case Instruction::Trunc:
2011 case Instruction::ZExt:
2012 case Instruction::SExt:
2013 case Instruction::FPTrunc:
2014 case Instruction::FPExt:
2015 case Instruction::UIToFP:
2016 case Instruction::SIToFP:
2017 case Instruction::FPToUI:
2018 case Instruction::FPToSI:
2019 return false; // These always modify bits
2020 case Instruction::BitCast:
2021 return true; // BitCast never modifies bits.
2022 case Instruction::PtrToInt:
2023 return IntPtrTy->getScalarSizeInBits() ==
2024 getType()->getScalarSizeInBits();
2025 case Instruction::IntToPtr:
2026 return IntPtrTy->getScalarSizeInBits() ==
2027 getOperand(0)->getType()->getScalarSizeInBits();
2031 /// This function determines if a pair of casts can be eliminated and what
2032 /// opcode should be used in the elimination. This assumes that there are two
2033 /// instructions like this:
2034 /// * %F = firstOpcode SrcTy %x to MidTy
2035 /// * %S = secondOpcode MidTy %F to DstTy
2036 /// The function returns a resultOpcode so these two casts can be replaced with:
2037 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
2038 /// If no such cast is permited, the function returns 0.
2039 unsigned CastInst::isEliminableCastPair(
2040 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
2041 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
2043 // Define the 144 possibilities for these two cast instructions. The values
2044 // in this matrix determine what to do in a given situation and select the
2045 // case in the switch below. The rows correspond to firstOp, the columns
2046 // correspond to secondOp. In looking at the table below, keep in mind
2047 // the following cast properties:
2049 // Size Compare Source Destination
2050 // Operator Src ? Size Type Sign Type Sign
2051 // -------- ------------ ------------------- ---------------------
2052 // TRUNC > Integer Any Integral Any
2053 // ZEXT < Integral Unsigned Integer Any
2054 // SEXT < Integral Signed Integer Any
2055 // FPTOUI n/a FloatPt n/a Integral Unsigned
2056 // FPTOSI n/a FloatPt n/a Integral Signed
2057 // UITOFP n/a Integral Unsigned FloatPt n/a
2058 // SITOFP n/a Integral Signed FloatPt n/a
2059 // FPTRUNC > FloatPt n/a FloatPt n/a
2060 // FPEXT < FloatPt n/a FloatPt n/a
2061 // PTRTOINT n/a Pointer n/a Integral Unsigned
2062 // INTTOPTR n/a Integral Unsigned Pointer n/a
2063 // BITCAST = FirstClass n/a FirstClass n/a
2065 // NOTE: some transforms are safe, but we consider them to be non-profitable.
2066 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2067 // into "fptoui double to i64", but this loses information about the range
2068 // of the produced value (we no longer know the top-part is all zeros).
2069 // Further this conversion is often much more expensive for typical hardware,
2070 // and causes issues when building libgcc. We disallow fptosi+sext for the
2072 const unsigned numCastOps =
2073 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
2074 static const uint8_t CastResults[numCastOps][numCastOps] = {
2075 // T F F U S F F P I B -+
2076 // R Z S P P I I T P 2 N T |
2077 // U E E 2 2 2 2 R E I T C +- secondOp
2078 // N X X U S F F N X N 2 V |
2079 // C T T I I P P C T T P T -+
2080 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
2081 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
2082 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
2083 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
2084 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
2085 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
2086 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
2087 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
2088 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
2089 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
2090 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
2091 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
2094 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
2095 [secondOp-Instruction::CastOpsBegin];
2098 // categorically disallowed
2101 // allowed, use first cast's opcode
2104 // allowed, use second cast's opcode
2107 // no-op cast in second op implies firstOp as long as the DestTy
2108 // is integer and we are not converting between a vector and a
2110 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
2114 // no-op cast in second op implies firstOp as long as the DestTy
2115 // is floating point.
2116 if (DstTy->isFloatingPointTy())
2120 // no-op cast in first op implies secondOp as long as the SrcTy
2122 if (SrcTy->isIntegerTy())
2126 // no-op cast in first op implies secondOp as long as the SrcTy
2127 // is a floating point.
2128 if (SrcTy->isFloatingPointTy())
2132 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
2135 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2136 unsigned MidSize = MidTy->getScalarSizeInBits();
2137 if (MidSize >= PtrSize)
2138 return Instruction::BitCast;
2142 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
2143 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
2144 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
2145 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2146 unsigned DstSize = DstTy->getScalarSizeInBits();
2147 if (SrcSize == DstSize)
2148 return Instruction::BitCast;
2149 else if (SrcSize < DstSize)
2153 case 9: // zext, sext -> zext, because sext can't sign extend after zext
2154 return Instruction::ZExt;
2156 // fpext followed by ftrunc is allowed if the bit size returned to is
2157 // the same as the original, in which case its just a bitcast
2159 return Instruction::BitCast;
2160 return 0; // If the types are not the same we can't eliminate it.
2162 // bitcast followed by ptrtoint is allowed as long as the bitcast
2163 // is a pointer to pointer cast.
2164 if (SrcTy->isPointerTy() && MidTy->isPointerTy())
2168 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
2169 if (MidTy->isPointerTy() && DstTy->isPointerTy())
2173 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2176 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2177 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2178 unsigned DstSize = DstTy->getScalarSizeInBits();
2179 if (SrcSize <= PtrSize && SrcSize == DstSize)
2180 return Instruction::BitCast;
2184 // cast combination can't happen (error in input). This is for all cases
2185 // where the MidTy is not the same for the two cast instructions.
2186 assert(!"Invalid Cast Combination");
2189 assert(!"Error in CastResults table!!!");
2195 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
2196 const Twine &Name, Instruction *InsertBefore) {
2197 // Construct and return the appropriate CastInst subclass
2199 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
2200 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
2201 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
2202 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
2203 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
2204 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
2205 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
2206 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
2207 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
2208 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
2209 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
2210 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
2212 assert(!"Invalid opcode provided");
2217 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
2218 const Twine &Name, BasicBlock *InsertAtEnd) {
2219 // Construct and return the appropriate CastInst subclass
2221 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
2222 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
2223 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
2224 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
2225 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
2226 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
2227 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
2228 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
2229 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
2230 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
2231 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
2232 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
2234 assert(!"Invalid opcode provided");
2239 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
2241 Instruction *InsertBefore) {
2242 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2243 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2244 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2247 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
2249 BasicBlock *InsertAtEnd) {
2250 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2251 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2252 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2255 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
2257 Instruction *InsertBefore) {
2258 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2259 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2260 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2263 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
2265 BasicBlock *InsertAtEnd) {
2266 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2267 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2268 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2271 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2273 Instruction *InsertBefore) {
2274 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2275 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2276 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2279 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2281 BasicBlock *InsertAtEnd) {
2282 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2283 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2284 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2287 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2289 BasicBlock *InsertAtEnd) {
2290 assert(S->getType()->isPointerTy() && "Invalid cast");
2291 assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2294 if (Ty->isIntegerTy())
2295 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2296 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2299 /// @brief Create a BitCast or a PtrToInt cast instruction
2300 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2302 Instruction *InsertBefore) {
2303 assert(S->getType()->isPointerTy() && "Invalid cast");
2304 assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2307 if (Ty->isIntegerTy())
2308 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2309 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2312 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2313 bool isSigned, const Twine &Name,
2314 Instruction *InsertBefore) {
2315 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2316 "Invalid integer cast");
2317 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2318 unsigned DstBits = Ty->getScalarSizeInBits();
2319 Instruction::CastOps opcode =
2320 (SrcBits == DstBits ? Instruction::BitCast :
2321 (SrcBits > DstBits ? Instruction::Trunc :
2322 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2323 return Create(opcode, C, Ty, Name, InsertBefore);
2326 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2327 bool isSigned, const Twine &Name,
2328 BasicBlock *InsertAtEnd) {
2329 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2331 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2332 unsigned DstBits = Ty->getScalarSizeInBits();
2333 Instruction::CastOps opcode =
2334 (SrcBits == DstBits ? Instruction::BitCast :
2335 (SrcBits > DstBits ? Instruction::Trunc :
2336 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2337 return Create(opcode, C, Ty, Name, InsertAtEnd);
2340 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2342 Instruction *InsertBefore) {
2343 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2345 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2346 unsigned DstBits = Ty->getScalarSizeInBits();
2347 Instruction::CastOps opcode =
2348 (SrcBits == DstBits ? Instruction::BitCast :
2349 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2350 return Create(opcode, C, Ty, Name, InsertBefore);
2353 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2355 BasicBlock *InsertAtEnd) {
2356 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2358 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2359 unsigned DstBits = Ty->getScalarSizeInBits();
2360 Instruction::CastOps opcode =
2361 (SrcBits == DstBits ? Instruction::BitCast :
2362 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2363 return Create(opcode, C, Ty, Name, InsertAtEnd);
2366 // Check whether it is valid to call getCastOpcode for these types.
2367 // This routine must be kept in sync with getCastOpcode.
2368 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
2369 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2372 if (SrcTy == DestTy)
2375 // Get the bit sizes, we'll need these
2376 unsigned SrcBits = SrcTy->getScalarSizeInBits(); // 0 for ptr
2377 unsigned DestBits = DestTy->getScalarSizeInBits(); // 0 for ptr
2379 // Run through the possibilities ...
2380 if (DestTy->isIntegerTy()) { // Casting to integral
2381 if (SrcTy->isIntegerTy()) { // Casting from integral
2383 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2385 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2386 // Casting from vector
2387 return DestBits == PTy->getBitWidth();
2388 } else { // Casting from something else
2389 return SrcTy->isPointerTy();
2391 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2392 if (SrcTy->isIntegerTy()) { // Casting from integral
2394 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2396 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2397 // Casting from vector
2398 return DestBits == PTy->getBitWidth();
2399 } else { // Casting from something else
2402 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2403 // Casting to vector
2404 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2405 // Casting from vector
2406 return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
2407 } else { // Casting from something else
2408 return DestPTy->getBitWidth() == SrcBits;
2410 } else if (DestTy->isPointerTy()) { // Casting to pointer
2411 if (SrcTy->isPointerTy()) { // Casting from pointer
2413 } else if (SrcTy->isIntegerTy()) { // Casting from integral
2415 } else { // Casting from something else
2418 } else { // Casting to something else
2423 // Provide a way to get a "cast" where the cast opcode is inferred from the
2424 // types and size of the operand. This, basically, is a parallel of the
2425 // logic in the castIsValid function below. This axiom should hold:
2426 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2427 // should not assert in castIsValid. In other words, this produces a "correct"
2428 // casting opcode for the arguments passed to it.
2429 // This routine must be kept in sync with isCastable.
2430 Instruction::CastOps
2431 CastInst::getCastOpcode(
2432 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
2433 // Get the bit sizes, we'll need these
2434 const Type *SrcTy = Src->getType();
2435 unsigned SrcBits = SrcTy->getScalarSizeInBits(); // 0 for ptr
2436 unsigned DestBits = DestTy->getScalarSizeInBits(); // 0 for ptr
2438 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2439 "Only first class types are castable!");
2441 // Run through the possibilities ...
2442 if (DestTy->isIntegerTy()) { // Casting to integral
2443 if (SrcTy->isIntegerTy()) { // Casting from integral
2444 if (DestBits < SrcBits)
2445 return Trunc; // int -> smaller int
2446 else if (DestBits > SrcBits) { // its an extension
2448 return SExt; // signed -> SEXT
2450 return ZExt; // unsigned -> ZEXT
2452 return BitCast; // Same size, No-op cast
2454 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2456 return FPToSI; // FP -> sint
2458 return FPToUI; // FP -> uint
2459 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2460 assert(DestBits == PTy->getBitWidth() &&
2461 "Casting vector to integer of different width");
2463 return BitCast; // Same size, no-op cast
2465 assert(SrcTy->isPointerTy() &&
2466 "Casting from a value that is not first-class type");
2467 return PtrToInt; // ptr -> int
2469 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2470 if (SrcTy->isIntegerTy()) { // Casting from integral
2472 return SIToFP; // sint -> FP
2474 return UIToFP; // uint -> FP
2475 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2476 if (DestBits < SrcBits) {
2477 return FPTrunc; // FP -> smaller FP
2478 } else if (DestBits > SrcBits) {
2479 return FPExt; // FP -> larger FP
2481 return BitCast; // same size, no-op cast
2483 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2484 assert(DestBits == PTy->getBitWidth() &&
2485 "Casting vector to floating point of different width");
2487 return BitCast; // same size, no-op cast
2489 llvm_unreachable("Casting pointer or non-first class to float");
2491 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2492 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2493 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2494 "Casting vector to vector of different widths");
2496 return BitCast; // vector -> vector
2497 } else if (DestPTy->getBitWidth() == SrcBits) {
2498 return BitCast; // float/int -> vector
2500 assert(!"Illegal cast to vector (wrong type or size)");
2502 } else if (DestTy->isPointerTy()) {
2503 if (SrcTy->isPointerTy()) {
2504 return BitCast; // ptr -> ptr
2505 } else if (SrcTy->isIntegerTy()) {
2506 return IntToPtr; // int -> ptr
2508 assert(!"Casting pointer to other than pointer or int");
2511 assert(!"Casting to type that is not first-class");
2514 // If we fall through to here we probably hit an assertion cast above
2515 // and assertions are not turned on. Anything we return is an error, so
2516 // BitCast is as good a choice as any.
2520 //===----------------------------------------------------------------------===//
2521 // CastInst SubClass Constructors
2522 //===----------------------------------------------------------------------===//
2524 /// Check that the construction parameters for a CastInst are correct. This
2525 /// could be broken out into the separate constructors but it is useful to have
2526 /// it in one place and to eliminate the redundant code for getting the sizes
2527 /// of the types involved.
2529 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2531 // Check for type sanity on the arguments
2532 const Type *SrcTy = S->getType();
2533 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
2534 SrcTy->isAggregateType() || DstTy->isAggregateType())
2537 // Get the size of the types in bits, we'll need this later
2538 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2539 unsigned DstBitSize = DstTy->getScalarSizeInBits();
2541 // Switch on the opcode provided
2543 default: return false; // This is an input error
2544 case Instruction::Trunc:
2545 return SrcTy->isIntOrIntVectorTy() &&
2546 DstTy->isIntOrIntVectorTy()&& SrcBitSize > DstBitSize;
2547 case Instruction::ZExt:
2548 return SrcTy->isIntOrIntVectorTy() &&
2549 DstTy->isIntOrIntVectorTy()&& SrcBitSize < DstBitSize;
2550 case Instruction::SExt:
2551 return SrcTy->isIntOrIntVectorTy() &&
2552 DstTy->isIntOrIntVectorTy()&& SrcBitSize < DstBitSize;
2553 case Instruction::FPTrunc:
2554 return SrcTy->isFPOrFPVectorTy() &&
2555 DstTy->isFPOrFPVectorTy() &&
2556 SrcBitSize > DstBitSize;
2557 case Instruction::FPExt:
2558 return SrcTy->isFPOrFPVectorTy() &&
2559 DstTy->isFPOrFPVectorTy() &&
2560 SrcBitSize < DstBitSize;
2561 case Instruction::UIToFP:
2562 case Instruction::SIToFP:
2563 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2564 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2565 return SVTy->getElementType()->isIntOrIntVectorTy() &&
2566 DVTy->getElementType()->isFPOrFPVectorTy() &&
2567 SVTy->getNumElements() == DVTy->getNumElements();
2570 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy();
2571 case Instruction::FPToUI:
2572 case Instruction::FPToSI:
2573 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2574 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2575 return SVTy->getElementType()->isFPOrFPVectorTy() &&
2576 DVTy->getElementType()->isIntOrIntVectorTy() &&
2577 SVTy->getNumElements() == DVTy->getNumElements();
2580 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy();
2581 case Instruction::PtrToInt:
2582 return SrcTy->isPointerTy() && DstTy->isIntegerTy();
2583 case Instruction::IntToPtr:
2584 return SrcTy->isIntegerTy() && DstTy->isPointerTy();
2585 case Instruction::BitCast:
2586 // BitCast implies a no-op cast of type only. No bits change.
2587 // However, you can't cast pointers to anything but pointers.
2588 if (SrcTy->isPointerTy() != DstTy->isPointerTy())
2591 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2592 // these cases, the cast is okay if the source and destination bit widths
2594 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
2598 TruncInst::TruncInst(
2599 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2600 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2601 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2604 TruncInst::TruncInst(
2605 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2606 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2607 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2611 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2612 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2613 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2617 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2618 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2619 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2622 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2623 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2624 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2628 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2629 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2630 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2633 FPTruncInst::FPTruncInst(
2634 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2635 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2636 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2639 FPTruncInst::FPTruncInst(
2640 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2641 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2642 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2645 FPExtInst::FPExtInst(
2646 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2647 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2648 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2651 FPExtInst::FPExtInst(
2652 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2653 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2654 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2657 UIToFPInst::UIToFPInst(
2658 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2659 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2660 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2663 UIToFPInst::UIToFPInst(
2664 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2665 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2666 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2669 SIToFPInst::SIToFPInst(
2670 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2671 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2672 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2675 SIToFPInst::SIToFPInst(
2676 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2677 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2678 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2681 FPToUIInst::FPToUIInst(
2682 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2683 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2684 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2687 FPToUIInst::FPToUIInst(
2688 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2689 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2690 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2693 FPToSIInst::FPToSIInst(
2694 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2695 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2696 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2699 FPToSIInst::FPToSIInst(
2700 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2701 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2702 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2705 PtrToIntInst::PtrToIntInst(
2706 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2707 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2708 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2711 PtrToIntInst::PtrToIntInst(
2712 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2713 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2714 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2717 IntToPtrInst::IntToPtrInst(
2718 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2719 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2720 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2723 IntToPtrInst::IntToPtrInst(
2724 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2725 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2726 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2729 BitCastInst::BitCastInst(
2730 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2731 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2732 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2735 BitCastInst::BitCastInst(
2736 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2737 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2738 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2741 //===----------------------------------------------------------------------===//
2743 //===----------------------------------------------------------------------===//
2745 void CmpInst::Anchor() const {}
2747 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2748 Value *LHS, Value *RHS, const Twine &Name,
2749 Instruction *InsertBefore)
2750 : Instruction(ty, op,
2751 OperandTraits<CmpInst>::op_begin(this),
2752 OperandTraits<CmpInst>::operands(this),
2756 setPredicate((Predicate)predicate);
2760 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2761 Value *LHS, Value *RHS, const Twine &Name,
2762 BasicBlock *InsertAtEnd)
2763 : Instruction(ty, op,
2764 OperandTraits<CmpInst>::op_begin(this),
2765 OperandTraits<CmpInst>::operands(this),
2769 setPredicate((Predicate)predicate);
2774 CmpInst::Create(OtherOps Op, unsigned short predicate,
2775 Value *S1, Value *S2,
2776 const Twine &Name, Instruction *InsertBefore) {
2777 if (Op == Instruction::ICmp) {
2779 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
2782 return new ICmpInst(CmpInst::Predicate(predicate),
2787 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
2790 return new FCmpInst(CmpInst::Predicate(predicate),
2795 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2796 const Twine &Name, BasicBlock *InsertAtEnd) {
2797 if (Op == Instruction::ICmp) {
2798 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2801 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2805 void CmpInst::swapOperands() {
2806 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2809 cast<FCmpInst>(this)->swapOperands();
2812 bool CmpInst::isCommutative() {
2813 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2814 return IC->isCommutative();
2815 return cast<FCmpInst>(this)->isCommutative();
2818 bool CmpInst::isEquality() {
2819 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2820 return IC->isEquality();
2821 return cast<FCmpInst>(this)->isEquality();
2825 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
2827 default: assert(!"Unknown cmp predicate!");
2828 case ICMP_EQ: return ICMP_NE;
2829 case ICMP_NE: return ICMP_EQ;
2830 case ICMP_UGT: return ICMP_ULE;
2831 case ICMP_ULT: return ICMP_UGE;
2832 case ICMP_UGE: return ICMP_ULT;
2833 case ICMP_ULE: return ICMP_UGT;
2834 case ICMP_SGT: return ICMP_SLE;
2835 case ICMP_SLT: return ICMP_SGE;
2836 case ICMP_SGE: return ICMP_SLT;
2837 case ICMP_SLE: return ICMP_SGT;
2839 case FCMP_OEQ: return FCMP_UNE;
2840 case FCMP_ONE: return FCMP_UEQ;
2841 case FCMP_OGT: return FCMP_ULE;
2842 case FCMP_OLT: return FCMP_UGE;
2843 case FCMP_OGE: return FCMP_ULT;
2844 case FCMP_OLE: return FCMP_UGT;
2845 case FCMP_UEQ: return FCMP_ONE;
2846 case FCMP_UNE: return FCMP_OEQ;
2847 case FCMP_UGT: return FCMP_OLE;
2848 case FCMP_ULT: return FCMP_OGE;
2849 case FCMP_UGE: return FCMP_OLT;
2850 case FCMP_ULE: return FCMP_OGT;
2851 case FCMP_ORD: return FCMP_UNO;
2852 case FCMP_UNO: return FCMP_ORD;
2853 case FCMP_TRUE: return FCMP_FALSE;
2854 case FCMP_FALSE: return FCMP_TRUE;
2858 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2860 default: assert(! "Unknown icmp predicate!");
2861 case ICMP_EQ: case ICMP_NE:
2862 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2864 case ICMP_UGT: return ICMP_SGT;
2865 case ICMP_ULT: return ICMP_SLT;
2866 case ICMP_UGE: return ICMP_SGE;
2867 case ICMP_ULE: return ICMP_SLE;
2871 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2873 default: assert(! "Unknown icmp predicate!");
2874 case ICMP_EQ: case ICMP_NE:
2875 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2877 case ICMP_SGT: return ICMP_UGT;
2878 case ICMP_SLT: return ICMP_ULT;
2879 case ICMP_SGE: return ICMP_UGE;
2880 case ICMP_SLE: return ICMP_ULE;
2884 /// Initialize a set of values that all satisfy the condition with C.
2887 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2890 uint32_t BitWidth = C.getBitWidth();
2892 default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
2893 case ICmpInst::ICMP_EQ: Upper++; break;
2894 case ICmpInst::ICMP_NE: Lower++; break;
2895 case ICmpInst::ICMP_ULT:
2896 Lower = APInt::getMinValue(BitWidth);
2897 // Check for an empty-set condition.
2899 return ConstantRange(BitWidth, /*isFullSet=*/false);
2901 case ICmpInst::ICMP_SLT:
2902 Lower = APInt::getSignedMinValue(BitWidth);
2903 // Check for an empty-set condition.
2905 return ConstantRange(BitWidth, /*isFullSet=*/false);
2907 case ICmpInst::ICMP_UGT:
2908 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2909 // Check for an empty-set condition.
2911 return ConstantRange(BitWidth, /*isFullSet=*/false);
2913 case ICmpInst::ICMP_SGT:
2914 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2915 // Check for an empty-set condition.
2917 return ConstantRange(BitWidth, /*isFullSet=*/false);
2919 case ICmpInst::ICMP_ULE:
2920 Lower = APInt::getMinValue(BitWidth); Upper++;
2921 // Check for a full-set condition.
2923 return ConstantRange(BitWidth, /*isFullSet=*/true);
2925 case ICmpInst::ICMP_SLE:
2926 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2927 // Check for a full-set condition.
2929 return ConstantRange(BitWidth, /*isFullSet=*/true);
2931 case ICmpInst::ICMP_UGE:
2932 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2933 // Check for a full-set condition.
2935 return ConstantRange(BitWidth, /*isFullSet=*/true);
2937 case ICmpInst::ICMP_SGE:
2938 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2939 // Check for a full-set condition.
2941 return ConstantRange(BitWidth, /*isFullSet=*/true);
2944 return ConstantRange(Lower, Upper);
2947 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
2949 default: assert(!"Unknown cmp predicate!");
2950 case ICMP_EQ: case ICMP_NE:
2952 case ICMP_SGT: return ICMP_SLT;
2953 case ICMP_SLT: return ICMP_SGT;
2954 case ICMP_SGE: return ICMP_SLE;
2955 case ICMP_SLE: return ICMP_SGE;
2956 case ICMP_UGT: return ICMP_ULT;
2957 case ICMP_ULT: return ICMP_UGT;
2958 case ICMP_UGE: return ICMP_ULE;
2959 case ICMP_ULE: return ICMP_UGE;
2961 case FCMP_FALSE: case FCMP_TRUE:
2962 case FCMP_OEQ: case FCMP_ONE:
2963 case FCMP_UEQ: case FCMP_UNE:
2964 case FCMP_ORD: case FCMP_UNO:
2966 case FCMP_OGT: return FCMP_OLT;
2967 case FCMP_OLT: return FCMP_OGT;
2968 case FCMP_OGE: return FCMP_OLE;
2969 case FCMP_OLE: return FCMP_OGE;
2970 case FCMP_UGT: return FCMP_ULT;
2971 case FCMP_ULT: return FCMP_UGT;
2972 case FCMP_UGE: return FCMP_ULE;
2973 case FCMP_ULE: return FCMP_UGE;
2977 bool CmpInst::isUnsigned(unsigned short predicate) {
2978 switch (predicate) {
2979 default: return false;
2980 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2981 case ICmpInst::ICMP_UGE: return true;
2985 bool CmpInst::isSigned(unsigned short predicate) {
2986 switch (predicate) {
2987 default: return false;
2988 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2989 case ICmpInst::ICMP_SGE: return true;
2993 bool CmpInst::isOrdered(unsigned short predicate) {
2994 switch (predicate) {
2995 default: return false;
2996 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2997 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2998 case FCmpInst::FCMP_ORD: return true;
3002 bool CmpInst::isUnordered(unsigned short predicate) {
3003 switch (predicate) {
3004 default: return false;
3005 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
3006 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
3007 case FCmpInst::FCMP_UNO: return true;
3011 bool CmpInst::isTrueWhenEqual(unsigned short predicate) {
3013 default: return false;
3014 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
3015 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
3019 bool CmpInst::isFalseWhenEqual(unsigned short predicate) {
3021 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
3022 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
3023 default: return false;
3028 //===----------------------------------------------------------------------===//
3029 // SwitchInst Implementation
3030 //===----------------------------------------------------------------------===//
3032 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
3033 assert(Value && Default);
3034 ReservedSpace = 2+NumCases*2;
3036 OperandList = allocHungoffUses(ReservedSpace);
3038 OperandList[0] = Value;
3039 OperandList[1] = Default;
3042 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3043 /// switch on and a default destination. The number of additional cases can
3044 /// be specified here to make memory allocation more efficient. This
3045 /// constructor can also autoinsert before another instruction.
3046 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3047 Instruction *InsertBefore)
3048 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3049 0, 0, InsertBefore) {
3050 init(Value, Default, NumCases);
3053 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3054 /// switch on and a default destination. The number of additional cases can
3055 /// be specified here to make memory allocation more efficient. This
3056 /// constructor also autoinserts at the end of the specified BasicBlock.
3057 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3058 BasicBlock *InsertAtEnd)
3059 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3060 0, 0, InsertAtEnd) {
3061 init(Value, Default, NumCases);
3064 SwitchInst::SwitchInst(const SwitchInst &SI)
3065 : TerminatorInst(Type::getVoidTy(SI.getContext()), Instruction::Switch,
3066 allocHungoffUses(SI.getNumOperands()), SI.getNumOperands()) {
3067 Use *OL = OperandList, *InOL = SI.OperandList;
3068 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
3070 OL[i+1] = InOL[i+1];
3072 SubclassOptionalData = SI.SubclassOptionalData;
3075 SwitchInst::~SwitchInst() {
3076 dropHungoffUses(OperandList);
3080 /// addCase - Add an entry to the switch instruction...
3082 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
3083 unsigned OpNo = NumOperands;
3084 if (OpNo+2 > ReservedSpace)
3085 resizeOperands(0); // Get more space!
3086 // Initialize some new operands.
3087 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
3088 NumOperands = OpNo+2;
3089 OperandList[OpNo] = OnVal;
3090 OperandList[OpNo+1] = Dest;
3093 /// removeCase - This method removes the specified successor from the switch
3094 /// instruction. Note that this cannot be used to remove the default
3095 /// destination (successor #0).
3097 void SwitchInst::removeCase(unsigned idx) {
3098 assert(idx != 0 && "Cannot remove the default case!");
3099 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
3101 unsigned NumOps = getNumOperands();
3102 Use *OL = OperandList;
3104 // Move everything after this operand down.
3106 // FIXME: we could just swap with the end of the list, then erase. However,
3107 // client might not expect this to happen. The code as it is thrashes the
3108 // use/def lists, which is kinda lame.
3109 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
3111 OL[i-2+1] = OL[i+1];
3114 // Nuke the last value.
3115 OL[NumOps-2].set(0);
3116 OL[NumOps-2+1].set(0);
3117 NumOperands = NumOps-2;
3120 /// resizeOperands - resize operands - This adjusts the length of the operands
3121 /// list according to the following behavior:
3122 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
3123 /// of operation. This grows the number of ops by 3 times.
3124 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
3125 /// 3. If NumOps == NumOperands, trim the reserved space.
3127 void SwitchInst::resizeOperands(unsigned NumOps) {
3128 unsigned e = getNumOperands();
3131 } else if (NumOps*2 > NumOperands) {
3132 // No resize needed.
3133 if (ReservedSpace >= NumOps) return;
3134 } else if (NumOps == NumOperands) {
3135 if (ReservedSpace == NumOps) return;
3140 ReservedSpace = NumOps;
3141 Use *NewOps = allocHungoffUses(NumOps);
3142 Use *OldOps = OperandList;
3143 for (unsigned i = 0; i != e; ++i) {
3144 NewOps[i] = OldOps[i];
3146 OperandList = NewOps;
3147 if (OldOps) Use::zap(OldOps, OldOps + e, true);
3151 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
3152 return getSuccessor(idx);
3154 unsigned SwitchInst::getNumSuccessorsV() const {
3155 return getNumSuccessors();
3157 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3158 setSuccessor(idx, B);
3161 //===----------------------------------------------------------------------===//
3162 // SwitchInst Implementation
3163 //===----------------------------------------------------------------------===//
3165 void IndirectBrInst::init(Value *Address, unsigned NumDests) {
3166 assert(Address && Address->getType()->isPointerTy() &&
3167 "Address of indirectbr must be a pointer");
3168 ReservedSpace = 1+NumDests;
3170 OperandList = allocHungoffUses(ReservedSpace);
3172 OperandList[0] = Address;
3176 /// resizeOperands - resize operands - This adjusts the length of the operands
3177 /// list according to the following behavior:
3178 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
3179 /// of operation. This grows the number of ops by 2 times.
3180 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
3181 /// 3. If NumOps == NumOperands, trim the reserved space.
3183 void IndirectBrInst::resizeOperands(unsigned NumOps) {
3184 unsigned e = getNumOperands();
3187 } else if (NumOps*2 > NumOperands) {
3188 // No resize needed.
3189 if (ReservedSpace >= NumOps) return;
3190 } else if (NumOps == NumOperands) {
3191 if (ReservedSpace == NumOps) return;
3196 ReservedSpace = NumOps;
3197 Use *NewOps = allocHungoffUses(NumOps);
3198 Use *OldOps = OperandList;
3199 for (unsigned i = 0; i != e; ++i)
3200 NewOps[i] = OldOps[i];
3201 OperandList = NewOps;
3202 if (OldOps) Use::zap(OldOps, OldOps + e, true);
3205 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3206 Instruction *InsertBefore)
3207 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3208 0, 0, InsertBefore) {
3209 init(Address, NumCases);
3212 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3213 BasicBlock *InsertAtEnd)
3214 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3215 0, 0, InsertAtEnd) {
3216 init(Address, NumCases);
3219 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
3220 : TerminatorInst(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
3221 allocHungoffUses(IBI.getNumOperands()),
3222 IBI.getNumOperands()) {
3223 Use *OL = OperandList, *InOL = IBI.OperandList;
3224 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
3226 SubclassOptionalData = IBI.SubclassOptionalData;
3229 IndirectBrInst::~IndirectBrInst() {
3230 dropHungoffUses(OperandList);
3233 /// addDestination - Add a destination.
3235 void IndirectBrInst::addDestination(BasicBlock *DestBB) {
3236 unsigned OpNo = NumOperands;
3237 if (OpNo+1 > ReservedSpace)
3238 resizeOperands(0); // Get more space!
3239 // Initialize some new operands.
3240 assert(OpNo < ReservedSpace && "Growing didn't work!");
3241 NumOperands = OpNo+1;
3242 OperandList[OpNo] = DestBB;
3245 /// removeDestination - This method removes the specified successor from the
3246 /// indirectbr instruction.
3247 void IndirectBrInst::removeDestination(unsigned idx) {
3248 assert(idx < getNumOperands()-1 && "Successor index out of range!");
3250 unsigned NumOps = getNumOperands();
3251 Use *OL = OperandList;
3253 // Replace this value with the last one.
3254 OL[idx+1] = OL[NumOps-1];
3256 // Nuke the last value.
3257 OL[NumOps-1].set(0);
3258 NumOperands = NumOps-1;
3261 BasicBlock *IndirectBrInst::getSuccessorV(unsigned idx) const {
3262 return getSuccessor(idx);
3264 unsigned IndirectBrInst::getNumSuccessorsV() const {
3265 return getNumSuccessors();
3267 void IndirectBrInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3268 setSuccessor(idx, B);
3271 //===----------------------------------------------------------------------===//
3272 // clone_impl() implementations
3273 //===----------------------------------------------------------------------===//
3275 // Define these methods here so vtables don't get emitted into every translation
3276 // unit that uses these classes.
3278 GetElementPtrInst *GetElementPtrInst::clone_impl() const {
3279 return new (getNumOperands()) GetElementPtrInst(*this);
3282 BinaryOperator *BinaryOperator::clone_impl() const {
3283 return Create(getOpcode(), Op<0>(), Op<1>());
3286 FCmpInst* FCmpInst::clone_impl() const {
3287 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
3290 ICmpInst* ICmpInst::clone_impl() const {
3291 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
3294 ExtractValueInst *ExtractValueInst::clone_impl() const {
3295 return new ExtractValueInst(*this);
3298 InsertValueInst *InsertValueInst::clone_impl() const {
3299 return new InsertValueInst(*this);
3302 AllocaInst *AllocaInst::clone_impl() const {
3303 return new AllocaInst(getAllocatedType(),
3304 (Value*)getOperand(0),
3308 LoadInst *LoadInst::clone_impl() const {
3309 return new LoadInst(getOperand(0),
3310 Twine(), isVolatile(),
3314 StoreInst *StoreInst::clone_impl() const {
3315 return new StoreInst(getOperand(0), getOperand(1),
3316 isVolatile(), getAlignment());
3319 TruncInst *TruncInst::clone_impl() const {
3320 return new TruncInst(getOperand(0), getType());
3323 ZExtInst *ZExtInst::clone_impl() const {
3324 return new ZExtInst(getOperand(0), getType());
3327 SExtInst *SExtInst::clone_impl() const {
3328 return new SExtInst(getOperand(0), getType());
3331 FPTruncInst *FPTruncInst::clone_impl() const {
3332 return new FPTruncInst(getOperand(0), getType());
3335 FPExtInst *FPExtInst::clone_impl() const {
3336 return new FPExtInst(getOperand(0), getType());
3339 UIToFPInst *UIToFPInst::clone_impl() const {
3340 return new UIToFPInst(getOperand(0), getType());
3343 SIToFPInst *SIToFPInst::clone_impl() const {
3344 return new SIToFPInst(getOperand(0), getType());
3347 FPToUIInst *FPToUIInst::clone_impl() const {
3348 return new FPToUIInst(getOperand(0), getType());
3351 FPToSIInst *FPToSIInst::clone_impl() const {
3352 return new FPToSIInst(getOperand(0), getType());
3355 PtrToIntInst *PtrToIntInst::clone_impl() const {
3356 return new PtrToIntInst(getOperand(0), getType());
3359 IntToPtrInst *IntToPtrInst::clone_impl() const {
3360 return new IntToPtrInst(getOperand(0), getType());
3363 BitCastInst *BitCastInst::clone_impl() const {
3364 return new BitCastInst(getOperand(0), getType());
3367 CallInst *CallInst::clone_impl() const {
3368 return new(getNumOperands()) CallInst(*this);
3371 SelectInst *SelectInst::clone_impl() const {
3372 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
3375 VAArgInst *VAArgInst::clone_impl() const {
3376 return new VAArgInst(getOperand(0), getType());
3379 ExtractElementInst *ExtractElementInst::clone_impl() const {
3380 return ExtractElementInst::Create(getOperand(0), getOperand(1));
3383 InsertElementInst *InsertElementInst::clone_impl() const {
3384 return InsertElementInst::Create(getOperand(0),
3389 ShuffleVectorInst *ShuffleVectorInst::clone_impl() const {
3390 return new ShuffleVectorInst(getOperand(0),
3395 PHINode *PHINode::clone_impl() const {
3396 return new PHINode(*this);
3399 ReturnInst *ReturnInst::clone_impl() const {
3400 return new(getNumOperands()) ReturnInst(*this);
3403 BranchInst *BranchInst::clone_impl() const {
3404 unsigned Ops(getNumOperands());
3405 return new(Ops, Ops == 1) BranchInst(*this);
3408 SwitchInst *SwitchInst::clone_impl() const {
3409 return new SwitchInst(*this);
3412 IndirectBrInst *IndirectBrInst::clone_impl() const {
3413 return new IndirectBrInst(*this);
3417 InvokeInst *InvokeInst::clone_impl() const {
3418 return new(getNumOperands()) InvokeInst(*this);
3421 UnwindInst *UnwindInst::clone_impl() const {
3422 LLVMContext &Context = getContext();
3423 return new UnwindInst(Context);
3426 UnreachableInst *UnreachableInst::clone_impl() const {
3427 LLVMContext &Context = getContext();
3428 return new UnreachableInst(Context);