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 "llvm/Constants.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Function.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Support/CallSite.h"
20 #include "llvm/Support/ConstantRange.h"
21 #include "llvm/Support/MathExtras.h"
24 //===----------------------------------------------------------------------===//
26 //===----------------------------------------------------------------------===//
28 CallSite::CallSite(Instruction *C) {
29 assert((isa<CallInst>(C) || isa<InvokeInst>(C)) && "Not a call!");
32 unsigned CallSite::getCallingConv() const {
33 if (CallInst *CI = dyn_cast<CallInst>(I))
34 return CI->getCallingConv();
36 return cast<InvokeInst>(I)->getCallingConv();
38 void CallSite::setCallingConv(unsigned CC) {
39 if (CallInst *CI = dyn_cast<CallInst>(I))
40 CI->setCallingConv(CC);
42 cast<InvokeInst>(I)->setCallingConv(CC);
44 const PAListPtr &CallSite::getParamAttrs() const {
45 if (CallInst *CI = dyn_cast<CallInst>(I))
46 return CI->getParamAttrs();
48 return cast<InvokeInst>(I)->getParamAttrs();
50 void CallSite::setParamAttrs(const PAListPtr &PAL) {
51 if (CallInst *CI = dyn_cast<CallInst>(I))
52 CI->setParamAttrs(PAL);
54 cast<InvokeInst>(I)->setParamAttrs(PAL);
56 bool CallSite::paramHasAttr(uint16_t i, ParameterAttributes attr) const {
57 if (CallInst *CI = dyn_cast<CallInst>(I))
58 return CI->paramHasAttr(i, attr);
60 return cast<InvokeInst>(I)->paramHasAttr(i, attr);
62 uint16_t CallSite::getParamAlignment(uint16_t i) const {
63 if (CallInst *CI = dyn_cast<CallInst>(I))
64 return CI->getParamAlignment(i);
66 return cast<InvokeInst>(I)->getParamAlignment(i);
69 bool CallSite::doesNotAccessMemory() const {
70 if (CallInst *CI = dyn_cast<CallInst>(I))
71 return CI->doesNotAccessMemory();
73 return cast<InvokeInst>(I)->doesNotAccessMemory();
75 bool CallSite::onlyReadsMemory() const {
76 if (CallInst *CI = dyn_cast<CallInst>(I))
77 return CI->onlyReadsMemory();
79 return cast<InvokeInst>(I)->onlyReadsMemory();
81 bool CallSite::doesNotThrow() const {
82 if (CallInst *CI = dyn_cast<CallInst>(I))
83 return CI->doesNotThrow();
85 return cast<InvokeInst>(I)->doesNotThrow();
87 void CallSite::setDoesNotThrow(bool doesNotThrow) {
88 if (CallInst *CI = dyn_cast<CallInst>(I))
89 CI->setDoesNotThrow(doesNotThrow);
91 cast<InvokeInst>(I)->setDoesNotThrow(doesNotThrow);
94 bool CallSite::hasArgument(const Value *Arg) const {
95 for (arg_iterator AI = this->arg_begin(), E = this->arg_end(); AI != E; ++AI)
101 //===----------------------------------------------------------------------===//
102 // TerminatorInst Class
103 //===----------------------------------------------------------------------===//
105 // Out of line virtual method, so the vtable, etc has a home.
106 TerminatorInst::~TerminatorInst() {
109 //===----------------------------------------------------------------------===//
110 // UnaryInstruction Class
111 //===----------------------------------------------------------------------===//
113 // Out of line virtual method, so the vtable, etc has a home.
114 UnaryInstruction::~UnaryInstruction() {
117 //===----------------------------------------------------------------------===//
119 //===----------------------------------------------------------------------===//
121 PHINode::PHINode(const PHINode &PN)
122 : Instruction(PN.getType(), Instruction::PHI,
123 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
124 ReservedSpace(PN.getNumOperands()) {
125 Use *OL = OperandList;
126 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
127 OL[i] = PN.getOperand(i);
128 OL[i+1] = PN.getOperand(i+1);
132 PHINode::~PHINode() {
134 dropHungoffUses(OperandList);
137 // removeIncomingValue - Remove an incoming value. This is useful if a
138 // predecessor basic block is deleted.
139 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
140 unsigned NumOps = getNumOperands();
141 Use *OL = OperandList;
142 assert(Idx*2 < NumOps && "BB not in PHI node!");
143 Value *Removed = OL[Idx*2];
145 // Move everything after this operand down.
147 // FIXME: we could just swap with the end of the list, then erase. However,
148 // client might not expect this to happen. The code as it is thrashes the
149 // use/def lists, which is kinda lame.
150 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
155 // Nuke the last value.
157 OL[NumOps-2+1].set(0);
158 NumOperands = NumOps-2;
160 // If the PHI node is dead, because it has zero entries, nuke it now.
161 if (NumOps == 2 && DeletePHIIfEmpty) {
162 // If anyone is using this PHI, make them use a dummy value instead...
163 replaceAllUsesWith(UndefValue::get(getType()));
169 /// resizeOperands - resize operands - This adjusts the length of the operands
170 /// list according to the following behavior:
171 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
172 /// of operation. This grows the number of ops by 1.5 times.
173 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
174 /// 3. If NumOps == NumOperands, trim the reserved space.
176 void PHINode::resizeOperands(unsigned NumOps) {
177 unsigned e = getNumOperands();
180 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
181 } else if (NumOps*2 > NumOperands) {
183 if (ReservedSpace >= NumOps) return;
184 } else if (NumOps == NumOperands) {
185 if (ReservedSpace == NumOps) return;
190 ReservedSpace = NumOps;
191 Use *OldOps = OperandList;
192 Use *NewOps = allocHungoffUses(NumOps);
193 for (unsigned i = 0; i != e; ++i) {
194 NewOps[i] = OldOps[i];
196 OperandList = NewOps;
197 if (OldOps) Use::zap(OldOps, OldOps + e, true);
200 /// hasConstantValue - If the specified PHI node always merges together the same
201 /// value, return the value, otherwise return null.
203 Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) const {
204 // If the PHI node only has one incoming value, eliminate the PHI node...
205 if (getNumIncomingValues() == 1) {
206 if (getIncomingValue(0) != this) // not X = phi X
207 return getIncomingValue(0);
209 return UndefValue::get(getType()); // Self cycle is dead.
212 // Otherwise if all of the incoming values are the same for the PHI, replace
213 // the PHI node with the incoming value.
216 bool HasUndefInput = false;
217 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
218 if (isa<UndefValue>(getIncomingValue(i))) {
219 HasUndefInput = true;
220 } else if (getIncomingValue(i) != this) { // Not the PHI node itself...
221 if (InVal && getIncomingValue(i) != InVal)
222 return 0; // Not the same, bail out.
224 InVal = getIncomingValue(i);
227 // The only case that could cause InVal to be null is if we have a PHI node
228 // that only has entries for itself. In this case, there is no entry into the
229 // loop, so kill the PHI.
231 if (InVal == 0) InVal = UndefValue::get(getType());
233 // If we have a PHI node like phi(X, undef, X), where X is defined by some
234 // instruction, we cannot always return X as the result of the PHI node. Only
235 // do this if X is not an instruction (thus it must dominate the PHI block),
236 // or if the client is prepared to deal with this possibility.
237 if (HasUndefInput && !AllowNonDominatingInstruction)
238 if (Instruction *IV = dyn_cast<Instruction>(InVal))
239 // If it's in the entry block, it dominates everything.
240 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
242 return 0; // Cannot guarantee that InVal dominates this PHINode.
244 // All of the incoming values are the same, return the value now.
249 //===----------------------------------------------------------------------===//
250 // CallInst Implementation
251 //===----------------------------------------------------------------------===//
253 CallInst::~CallInst() {
256 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
257 assert(NumOperands == NumParams+1 && "NumOperands not set up?");
258 Use *OL = OperandList;
261 const FunctionType *FTy =
262 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
263 FTy = FTy; // silence warning.
265 assert((NumParams == FTy->getNumParams() ||
266 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
267 "Calling a function with bad signature!");
268 for (unsigned i = 0; i != NumParams; ++i) {
269 assert((i >= FTy->getNumParams() ||
270 FTy->getParamType(i) == Params[i]->getType()) &&
271 "Calling a function with a bad signature!");
276 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
277 assert(NumOperands == 3 && "NumOperands not set up?");
278 Use *OL = OperandList;
283 const FunctionType *FTy =
284 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
285 FTy = FTy; // silence warning.
287 assert((FTy->getNumParams() == 2 ||
288 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
289 "Calling a function with bad signature");
290 assert((0 >= FTy->getNumParams() ||
291 FTy->getParamType(0) == Actual1->getType()) &&
292 "Calling a function with a bad signature!");
293 assert((1 >= FTy->getNumParams() ||
294 FTy->getParamType(1) == Actual2->getType()) &&
295 "Calling a function with a bad signature!");
298 void CallInst::init(Value *Func, Value *Actual) {
299 assert(NumOperands == 2 && "NumOperands not set up?");
300 Use *OL = OperandList;
304 const FunctionType *FTy =
305 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
306 FTy = FTy; // silence warning.
308 assert((FTy->getNumParams() == 1 ||
309 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
310 "Calling a function with bad signature");
311 assert((0 == FTy->getNumParams() ||
312 FTy->getParamType(0) == Actual->getType()) &&
313 "Calling a function with a bad signature!");
316 void CallInst::init(Value *Func) {
317 assert(NumOperands == 1 && "NumOperands not set up?");
318 Use *OL = OperandList;
321 const FunctionType *FTy =
322 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
323 FTy = FTy; // silence warning.
325 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
328 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
329 Instruction *InsertBefore)
330 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
331 ->getElementType())->getReturnType(),
333 OperandTraits<CallInst>::op_end(this) - 2,
339 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
340 BasicBlock *InsertAtEnd)
341 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
342 ->getElementType())->getReturnType(),
344 OperandTraits<CallInst>::op_end(this) - 2,
349 CallInst::CallInst(Value *Func, const std::string &Name,
350 Instruction *InsertBefore)
351 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
352 ->getElementType())->getReturnType(),
354 OperandTraits<CallInst>::op_end(this) - 1,
360 CallInst::CallInst(Value *Func, const std::string &Name,
361 BasicBlock *InsertAtEnd)
362 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
363 ->getElementType())->getReturnType(),
365 OperandTraits<CallInst>::op_end(this) - 1,
371 CallInst::CallInst(const CallInst &CI)
372 : Instruction(CI.getType(), Instruction::Call,
373 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
374 CI.getNumOperands()) {
375 setParamAttrs(CI.getParamAttrs());
376 SubclassData = CI.SubclassData;
377 Use *OL = OperandList;
378 Use *InOL = CI.OperandList;
379 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
383 void CallInst::addParamAttr(unsigned i, ParameterAttributes attr) {
384 PAListPtr PAL = getParamAttrs();
385 PAL = PAL.addAttr(i, attr);
389 bool CallInst::paramHasAttr(unsigned i, ParameterAttributes attr) const {
390 if (ParamAttrs.paramHasAttr(i, attr))
392 if (const Function *F = getCalledFunction())
393 return F->paramHasAttr(i, attr);
397 void CallInst::setDoesNotThrow(bool doesNotThrow) {
398 PAListPtr PAL = getParamAttrs();
400 PAL = PAL.addAttr(0, ParamAttr::NoUnwind);
402 PAL = PAL.removeAttr(0, ParamAttr::NoUnwind);
407 //===----------------------------------------------------------------------===//
408 // InvokeInst Implementation
409 //===----------------------------------------------------------------------===//
411 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
412 Value* const *Args, unsigned NumArgs) {
413 assert(NumOperands == 3+NumArgs && "NumOperands not set up?");
414 Use *OL = OperandList;
418 const FunctionType *FTy =
419 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
420 FTy = FTy; // silence warning.
422 assert(((NumArgs == FTy->getNumParams()) ||
423 (FTy->isVarArg() && NumArgs > FTy->getNumParams())) &&
424 "Calling a function with bad signature");
426 for (unsigned i = 0, e = NumArgs; i != e; i++) {
427 assert((i >= FTy->getNumParams() ||
428 FTy->getParamType(i) == Args[i]->getType()) &&
429 "Invoking a function with a bad signature!");
435 InvokeInst::InvokeInst(const InvokeInst &II)
436 : TerminatorInst(II.getType(), Instruction::Invoke,
437 OperandTraits<InvokeInst>::op_end(this)
438 - II.getNumOperands(),
439 II.getNumOperands()) {
440 setParamAttrs(II.getParamAttrs());
441 SubclassData = II.SubclassData;
442 Use *OL = OperandList, *InOL = II.OperandList;
443 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
447 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
448 return getSuccessor(idx);
450 unsigned InvokeInst::getNumSuccessorsV() const {
451 return getNumSuccessors();
453 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
454 return setSuccessor(idx, B);
457 bool InvokeInst::paramHasAttr(unsigned i, ParameterAttributes attr) const {
458 if (ParamAttrs.paramHasAttr(i, attr))
460 if (const Function *F = getCalledFunction())
461 return F->paramHasAttr(i, attr);
465 void InvokeInst::addParamAttr(unsigned i, ParameterAttributes attr) {
466 PAListPtr PAL = getParamAttrs();
467 PAL = PAL.addAttr(i, attr);
471 void InvokeInst::setDoesNotThrow(bool doesNotThrow) {
472 PAListPtr PAL = getParamAttrs();
474 PAL = PAL.addAttr(0, ParamAttr::NoUnwind);
476 PAL = PAL.removeAttr(0, ParamAttr::NoUnwind);
481 //===----------------------------------------------------------------------===//
482 // ReturnInst Implementation
483 //===----------------------------------------------------------------------===//
485 ReturnInst::ReturnInst(const ReturnInst &RI)
486 : TerminatorInst(Type::VoidTy, Instruction::Ret,
487 OperandTraits<ReturnInst>::op_end(this)
488 - RI.getNumOperands(),
489 RI.getNumOperands()) {
490 unsigned N = RI.getNumOperands();
492 Op<0>() = RI.Op<0>();
494 Use *OL = OperandList;
495 for (unsigned i = 0; i < N; ++i)
496 OL[i] = RI.getOperand(i);
500 ReturnInst::ReturnInst(Value *retVal, Instruction *InsertBefore)
501 : TerminatorInst(Type::VoidTy, Instruction::Ret,
502 OperandTraits<ReturnInst>::op_end(this) - (retVal != 0),
503 retVal != 0, InsertBefore) {
507 ReturnInst::ReturnInst(Value *retVal, BasicBlock *InsertAtEnd)
508 : TerminatorInst(Type::VoidTy, Instruction::Ret,
509 OperandTraits<ReturnInst>::op_end(this) - (retVal != 0),
510 retVal != 0, InsertAtEnd) {
514 ReturnInst::ReturnInst(BasicBlock *InsertAtEnd)
515 : TerminatorInst(Type::VoidTy, Instruction::Ret,
516 OperandTraits<ReturnInst>::op_end(this),
520 ReturnInst::ReturnInst(Value * const* retVals, unsigned N,
521 Instruction *InsertBefore)
522 : TerminatorInst(Type::VoidTy, Instruction::Ret,
523 OperandTraits<ReturnInst>::op_end(this) - N,
528 ReturnInst::ReturnInst(Value * const* retVals, unsigned N,
529 BasicBlock *InsertAtEnd)
530 : TerminatorInst(Type::VoidTy, Instruction::Ret,
531 OperandTraits<ReturnInst>::op_end(this) - N,
537 void ReturnInst::init(Value * const* retVals, unsigned N) {
538 assert (N > 0 && "Invalid operands numbers in ReturnInst init");
541 if (NumOperands == 1) {
543 if (V->getType() == Type::VoidTy)
549 Use *OL = OperandList;
550 for (unsigned i = 0; i < NumOperands; ++i) {
551 Value *V = *retVals++;
552 assert(!isa<BasicBlock>(V) &&
553 "Cannot return basic block. Probably using the incorrect ctor");
558 unsigned ReturnInst::getNumSuccessorsV() const {
559 return getNumSuccessors();
562 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
563 /// emit the vtable for the class in this translation unit.
564 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
565 assert(0 && "ReturnInst has no successors!");
568 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
569 assert(0 && "ReturnInst has no successors!");
574 ReturnInst::~ReturnInst() {
577 //===----------------------------------------------------------------------===//
578 // UnwindInst Implementation
579 //===----------------------------------------------------------------------===//
581 UnwindInst::UnwindInst(Instruction *InsertBefore)
582 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertBefore) {
584 UnwindInst::UnwindInst(BasicBlock *InsertAtEnd)
585 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertAtEnd) {
589 unsigned UnwindInst::getNumSuccessorsV() const {
590 return getNumSuccessors();
593 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
594 assert(0 && "UnwindInst has no successors!");
597 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
598 assert(0 && "UnwindInst has no successors!");
603 //===----------------------------------------------------------------------===//
604 // UnreachableInst Implementation
605 //===----------------------------------------------------------------------===//
607 UnreachableInst::UnreachableInst(Instruction *InsertBefore)
608 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertBefore) {
610 UnreachableInst::UnreachableInst(BasicBlock *InsertAtEnd)
611 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertAtEnd) {
614 unsigned UnreachableInst::getNumSuccessorsV() const {
615 return getNumSuccessors();
618 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
619 assert(0 && "UnwindInst has no successors!");
622 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
623 assert(0 && "UnwindInst has no successors!");
628 //===----------------------------------------------------------------------===//
629 // BranchInst Implementation
630 //===----------------------------------------------------------------------===//
632 void BranchInst::AssertOK() {
634 assert(getCondition()->getType() == Type::Int1Ty &&
635 "May only branch on boolean predicates!");
638 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
639 : TerminatorInst(Type::VoidTy, Instruction::Br,
640 OperandTraits<BranchInst>::op_end(this) - 1,
642 assert(IfTrue != 0 && "Branch destination may not be null!");
645 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
646 Instruction *InsertBefore)
647 : TerminatorInst(Type::VoidTy, Instruction::Br,
648 OperandTraits<BranchInst>::op_end(this) - 3,
658 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
659 : TerminatorInst(Type::VoidTy, Instruction::Br,
660 OperandTraits<BranchInst>::op_end(this) - 1,
662 assert(IfTrue != 0 && "Branch destination may not be null!");
666 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
667 BasicBlock *InsertAtEnd)
668 : TerminatorInst(Type::VoidTy, Instruction::Br,
669 OperandTraits<BranchInst>::op_end(this) - 3,
680 BranchInst::BranchInst(const BranchInst &BI) :
681 TerminatorInst(Type::VoidTy, Instruction::Br,
682 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
683 BI.getNumOperands()) {
684 OperandList[0] = BI.getOperand(0);
685 if (BI.getNumOperands() != 1) {
686 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
687 OperandList[1] = BI.getOperand(1);
688 OperandList[2] = BI.getOperand(2);
692 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
693 return getSuccessor(idx);
695 unsigned BranchInst::getNumSuccessorsV() const {
696 return getNumSuccessors();
698 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
699 setSuccessor(idx, B);
703 //===----------------------------------------------------------------------===//
704 // AllocationInst Implementation
705 //===----------------------------------------------------------------------===//
707 static Value *getAISize(Value *Amt) {
709 Amt = ConstantInt::get(Type::Int32Ty, 1);
711 assert(!isa<BasicBlock>(Amt) &&
712 "Passed basic block into allocation size parameter! Use other ctor");
713 assert(Amt->getType() == Type::Int32Ty &&
714 "Malloc/Allocation array size is not a 32-bit integer!");
719 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
720 unsigned Align, const std::string &Name,
721 Instruction *InsertBefore)
722 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
725 assert(Ty != Type::VoidTy && "Cannot allocate void!");
729 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
730 unsigned Align, const std::string &Name,
731 BasicBlock *InsertAtEnd)
732 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
735 assert(Ty != Type::VoidTy && "Cannot allocate void!");
739 // Out of line virtual method, so the vtable, etc has a home.
740 AllocationInst::~AllocationInst() {
743 void AllocationInst::setAlignment(unsigned Align) {
744 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
745 SubclassData = Log2_32(Align) + 1;
746 assert(getAlignment() == Align && "Alignment representation error!");
749 bool AllocationInst::isArrayAllocation() const {
750 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
751 return CI->getZExtValue() != 1;
755 const Type *AllocationInst::getAllocatedType() const {
756 return getType()->getElementType();
759 AllocaInst::AllocaInst(const AllocaInst &AI)
760 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
761 Instruction::Alloca, AI.getAlignment()) {
764 MallocInst::MallocInst(const MallocInst &MI)
765 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
766 Instruction::Malloc, MI.getAlignment()) {
769 //===----------------------------------------------------------------------===//
770 // FreeInst Implementation
771 //===----------------------------------------------------------------------===//
773 void FreeInst::AssertOK() {
774 assert(isa<PointerType>(getOperand(0)->getType()) &&
775 "Can not free something of nonpointer type!");
778 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
779 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertBefore) {
783 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
784 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertAtEnd) {
789 //===----------------------------------------------------------------------===//
790 // LoadInst Implementation
791 //===----------------------------------------------------------------------===//
793 void LoadInst::AssertOK() {
794 assert(isa<PointerType>(getOperand(0)->getType()) &&
795 "Ptr must have pointer type.");
798 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
799 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
800 Load, Ptr, InsertBef) {
807 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
808 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
809 Load, Ptr, InsertAE) {
816 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
817 Instruction *InsertBef)
818 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
819 Load, Ptr, InsertBef) {
820 setVolatile(isVolatile);
826 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
827 unsigned Align, Instruction *InsertBef)
828 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
829 Load, Ptr, InsertBef) {
830 setVolatile(isVolatile);
836 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
837 unsigned Align, BasicBlock *InsertAE)
838 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
839 Load, Ptr, InsertAE) {
840 setVolatile(isVolatile);
846 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
847 BasicBlock *InsertAE)
848 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
849 Load, Ptr, InsertAE) {
850 setVolatile(isVolatile);
858 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
859 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
860 Load, Ptr, InsertBef) {
864 if (Name && Name[0]) setName(Name);
867 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
868 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
869 Load, Ptr, InsertAE) {
873 if (Name && Name[0]) setName(Name);
876 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
877 Instruction *InsertBef)
878 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
879 Load, Ptr, InsertBef) {
880 setVolatile(isVolatile);
883 if (Name && Name[0]) setName(Name);
886 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
887 BasicBlock *InsertAE)
888 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
889 Load, Ptr, InsertAE) {
890 setVolatile(isVolatile);
893 if (Name && Name[0]) setName(Name);
896 void LoadInst::setAlignment(unsigned Align) {
897 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
898 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
901 //===----------------------------------------------------------------------===//
902 // StoreInst Implementation
903 //===----------------------------------------------------------------------===//
905 void StoreInst::AssertOK() {
906 assert(isa<PointerType>(getOperand(1)->getType()) &&
907 "Ptr must have pointer type!");
908 assert(getOperand(0)->getType() ==
909 cast<PointerType>(getOperand(1)->getType())->getElementType()
910 && "Ptr must be a pointer to Val type!");
914 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
915 : Instruction(Type::VoidTy, Store,
916 OperandTraits<StoreInst>::op_begin(this),
917 OperandTraits<StoreInst>::operands(this),
926 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
927 : Instruction(Type::VoidTy, Store,
928 OperandTraits<StoreInst>::op_begin(this),
929 OperandTraits<StoreInst>::operands(this),
938 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
939 Instruction *InsertBefore)
940 : Instruction(Type::VoidTy, Store,
941 OperandTraits<StoreInst>::op_begin(this),
942 OperandTraits<StoreInst>::operands(this),
946 setVolatile(isVolatile);
951 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
952 unsigned Align, Instruction *InsertBefore)
953 : Instruction(Type::VoidTy, Store,
954 OperandTraits<StoreInst>::op_begin(this),
955 OperandTraits<StoreInst>::operands(this),
959 setVolatile(isVolatile);
964 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
965 unsigned Align, BasicBlock *InsertAtEnd)
966 : Instruction(Type::VoidTy, Store,
967 OperandTraits<StoreInst>::op_begin(this),
968 OperandTraits<StoreInst>::operands(this),
972 setVolatile(isVolatile);
977 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
978 BasicBlock *InsertAtEnd)
979 : Instruction(Type::VoidTy, Store,
980 OperandTraits<StoreInst>::op_begin(this),
981 OperandTraits<StoreInst>::operands(this),
985 setVolatile(isVolatile);
990 void StoreInst::setAlignment(unsigned Align) {
991 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
992 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
995 //===----------------------------------------------------------------------===//
996 // GetElementPtrInst Implementation
997 //===----------------------------------------------------------------------===//
999 static unsigned retrieveAddrSpace(const Value *Val) {
1000 return cast<PointerType>(Val->getType())->getAddressSpace();
1003 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx,
1004 const std::string &Name) {
1005 assert(NumOperands == 1+NumIdx && "NumOperands not initialized?");
1006 Use *OL = OperandList;
1009 for (unsigned i = 0; i != NumIdx; ++i)
1015 void GetElementPtrInst::init(Value *Ptr, Value *Idx, const std::string &Name) {
1016 assert(NumOperands == 2 && "NumOperands not initialized?");
1017 Use *OL = OperandList;
1024 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1025 : Instruction(GEPI.getType(), GetElementPtr,
1026 OperandTraits<GetElementPtrInst>::op_end(this)
1027 - GEPI.getNumOperands(),
1028 GEPI.getNumOperands()) {
1029 Use *OL = OperandList;
1030 Use *GEPIOL = GEPI.OperandList;
1031 for (unsigned i = 0, E = NumOperands; i != E; ++i)
1035 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1036 const std::string &Name, Instruction *InBe)
1037 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1038 retrieveAddrSpace(Ptr)),
1040 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1042 init(Ptr, Idx, Name);
1045 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1046 const std::string &Name, BasicBlock *IAE)
1047 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1048 retrieveAddrSpace(Ptr)),
1050 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1052 init(Ptr, Idx, Name);
1055 // getIndexedType - Returns the type of the element that would be loaded with
1056 // a load instruction with the specified parameters.
1058 // A null type is returned if the indices are invalid for the specified
1061 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1064 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1065 if (!PTy) return 0; // Type isn't a pointer type!
1066 const Type *Agg = PTy->getElementType();
1068 // Handle the special case of the empty set index set...
1072 unsigned CurIdx = 1;
1073 for (; CurIdx != NumIdx; ++CurIdx) {
1074 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1075 if (!CT || isa<PointerType>(CT)) return 0;
1076 Value *Index = Idxs[CurIdx];
1077 if (!CT->indexValid(Index)) return 0;
1078 Agg = CT->getTypeAtIndex(Index);
1080 // If the new type forwards to another type, then it is in the middle
1081 // of being refined to another type (and hence, may have dropped all
1082 // references to what it was using before). So, use the new forwarded
1084 if (const Type *Ty = Agg->getForwardedType())
1087 return CurIdx == NumIdx ? Agg : 0;
1090 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1091 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1092 if (!PTy) return 0; // Type isn't a pointer type!
1094 // Check the pointer index.
1095 if (!PTy->indexValid(Idx)) return 0;
1097 return PTy->getElementType();
1101 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1102 /// zeros. If so, the result pointer and the first operand have the same
1103 /// value, just potentially different types.
1104 bool GetElementPtrInst::hasAllZeroIndices() const {
1105 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1106 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1107 if (!CI->isZero()) return false;
1115 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1116 /// constant integers. If so, the result pointer and the first operand have
1117 /// a constant offset between them.
1118 bool GetElementPtrInst::hasAllConstantIndices() const {
1119 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1120 if (!isa<ConstantInt>(getOperand(i)))
1127 //===----------------------------------------------------------------------===//
1128 // ExtractElementInst Implementation
1129 //===----------------------------------------------------------------------===//
1131 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1132 const std::string &Name,
1133 Instruction *InsertBef)
1134 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1136 OperandTraits<ExtractElementInst>::op_begin(this),
1138 assert(isValidOperands(Val, Index) &&
1139 "Invalid extractelement instruction operands!");
1145 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1146 const std::string &Name,
1147 Instruction *InsertBef)
1148 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1150 OperandTraits<ExtractElementInst>::op_begin(this),
1152 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1153 assert(isValidOperands(Val, Index) &&
1154 "Invalid extractelement instruction operands!");
1161 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1162 const std::string &Name,
1163 BasicBlock *InsertAE)
1164 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1166 OperandTraits<ExtractElementInst>::op_begin(this),
1168 assert(isValidOperands(Val, Index) &&
1169 "Invalid extractelement instruction operands!");
1176 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1177 const std::string &Name,
1178 BasicBlock *InsertAE)
1179 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1181 OperandTraits<ExtractElementInst>::op_begin(this),
1183 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1184 assert(isValidOperands(Val, Index) &&
1185 "Invalid extractelement instruction operands!");
1193 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1194 if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty)
1200 //===----------------------------------------------------------------------===//
1201 // InsertElementInst Implementation
1202 //===----------------------------------------------------------------------===//
1204 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
1205 : Instruction(IE.getType(), InsertElement,
1206 OperandTraits<InsertElementInst>::op_begin(this), 3) {
1207 Op<0>() = IE.Op<0>();
1208 Op<1>() = IE.Op<1>();
1209 Op<2>() = IE.Op<2>();
1211 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1212 const std::string &Name,
1213 Instruction *InsertBef)
1214 : Instruction(Vec->getType(), InsertElement,
1215 OperandTraits<InsertElementInst>::op_begin(this),
1217 assert(isValidOperands(Vec, Elt, Index) &&
1218 "Invalid insertelement instruction operands!");
1225 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1226 const std::string &Name,
1227 Instruction *InsertBef)
1228 : Instruction(Vec->getType(), InsertElement,
1229 OperandTraits<InsertElementInst>::op_begin(this),
1231 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1232 assert(isValidOperands(Vec, Elt, Index) &&
1233 "Invalid insertelement instruction operands!");
1241 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1242 const std::string &Name,
1243 BasicBlock *InsertAE)
1244 : Instruction(Vec->getType(), InsertElement,
1245 OperandTraits<InsertElementInst>::op_begin(this),
1247 assert(isValidOperands(Vec, Elt, Index) &&
1248 "Invalid insertelement instruction operands!");
1256 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1257 const std::string &Name,
1258 BasicBlock *InsertAE)
1259 : Instruction(Vec->getType(), InsertElement,
1260 OperandTraits<InsertElementInst>::op_begin(this),
1262 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1263 assert(isValidOperands(Vec, Elt, Index) &&
1264 "Invalid insertelement instruction operands!");
1272 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1273 const Value *Index) {
1274 if (!isa<VectorType>(Vec->getType()))
1275 return false; // First operand of insertelement must be vector type.
1277 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1278 return false;// Second operand of insertelement must be vector element type.
1280 if (Index->getType() != Type::Int32Ty)
1281 return false; // Third operand of insertelement must be uint.
1286 //===----------------------------------------------------------------------===//
1287 // ShuffleVectorInst Implementation
1288 //===----------------------------------------------------------------------===//
1290 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
1291 : Instruction(SV.getType(), ShuffleVector,
1292 OperandTraits<ShuffleVectorInst>::op_begin(this),
1293 OperandTraits<ShuffleVectorInst>::operands(this)) {
1294 Op<0>() = SV.Op<0>();
1295 Op<1>() = SV.Op<1>();
1296 Op<2>() = SV.Op<2>();
1299 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1300 const std::string &Name,
1301 Instruction *InsertBefore)
1302 : Instruction(V1->getType(), ShuffleVector,
1303 OperandTraits<ShuffleVectorInst>::op_begin(this),
1304 OperandTraits<ShuffleVectorInst>::operands(this),
1306 assert(isValidOperands(V1, V2, Mask) &&
1307 "Invalid shuffle vector instruction operands!");
1314 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1315 const std::string &Name,
1316 BasicBlock *InsertAtEnd)
1317 : Instruction(V1->getType(), ShuffleVector,
1318 OperandTraits<ShuffleVectorInst>::op_begin(this),
1319 OperandTraits<ShuffleVectorInst>::operands(this),
1321 assert(isValidOperands(V1, V2, Mask) &&
1322 "Invalid shuffle vector instruction operands!");
1330 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1331 const Value *Mask) {
1332 if (!isa<VectorType>(V1->getType()) ||
1333 V1->getType() != V2->getType())
1336 const VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1337 if (!isa<Constant>(Mask) || MaskTy == 0 ||
1338 MaskTy->getElementType() != Type::Int32Ty ||
1339 MaskTy->getNumElements() !=
1340 cast<VectorType>(V1->getType())->getNumElements())
1345 /// getMaskValue - Return the index from the shuffle mask for the specified
1346 /// output result. This is either -1 if the element is undef or a number less
1347 /// than 2*numelements.
1348 int ShuffleVectorInst::getMaskValue(unsigned i) const {
1349 const Constant *Mask = cast<Constant>(getOperand(2));
1350 if (isa<UndefValue>(Mask)) return -1;
1351 if (isa<ConstantAggregateZero>(Mask)) return 0;
1352 const ConstantVector *MaskCV = cast<ConstantVector>(Mask);
1353 assert(i < MaskCV->getNumOperands() && "Index out of range");
1355 if (isa<UndefValue>(MaskCV->getOperand(i)))
1357 return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
1360 //===----------------------------------------------------------------------===//
1361 // InsertValueInst Class
1362 //===----------------------------------------------------------------------===//
1364 void InsertValueInst::init(Value *Agg, Value *Val, const unsigned *Idx,
1365 unsigned NumIdx, const std::string &Name) {
1366 assert(NumOperands == 2 && "NumOperands not initialized?");
1370 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1374 void InsertValueInst::init(Value *Agg, Value *Val, unsigned Idx,
1375 const std::string &Name) {
1376 assert(NumOperands == 2 && "NumOperands not initialized?");
1380 Indices.push_back(Idx);
1384 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1385 : Instruction(IVI.getType(), InsertValue,
1386 OperandTraits<InsertValueInst>::op_begin(this), 2),
1387 Indices(IVI.Indices) {
1388 Op<0>() = IVI.getOperand(0);
1389 Op<1>() = IVI.getOperand(1);
1392 InsertValueInst::InsertValueInst(Value *Agg,
1395 const std::string &Name,
1396 Instruction *InsertBefore)
1397 : Instruction(Agg->getType(), InsertValue,
1398 OperandTraits<InsertValueInst>::op_begin(this),
1400 init(Agg, Val, Idx, Name);
1403 InsertValueInst::InsertValueInst(Value *Agg,
1406 const std::string &Name,
1407 BasicBlock *InsertAtEnd)
1408 : Instruction(Agg->getType(), InsertValue,
1409 OperandTraits<InsertValueInst>::op_begin(this),
1411 init(Agg, Val, Idx, Name);
1414 //===----------------------------------------------------------------------===//
1415 // ExtractValueInst Class
1416 //===----------------------------------------------------------------------===//
1418 void ExtractValueInst::init(const unsigned *Idx, unsigned NumIdx,
1419 const std::string &Name) {
1420 assert(NumOperands == 1 && "NumOperands not initialized?");
1422 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1426 void ExtractValueInst::init(unsigned Idx, const std::string &Name) {
1427 assert(NumOperands == 1 && "NumOperands not initialized?");
1429 Indices.push_back(Idx);
1433 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1434 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1435 Indices(EVI.Indices) {
1438 // getIndexedType - Returns the type of the element that would be extracted
1439 // with an extractvalue instruction with the specified parameters.
1441 // A null type is returned if the indices are invalid for the specified
1444 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1445 const unsigned *Idxs,
1447 unsigned CurIdx = 0;
1448 for (; CurIdx != NumIdx; ++CurIdx) {
1449 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1450 if (!CT || isa<PointerType>(CT) || isa<VectorType>(CT)) return 0;
1451 unsigned Index = Idxs[CurIdx];
1452 if (!CT->indexValid(Index)) return 0;
1453 Agg = CT->getTypeAtIndex(Index);
1455 // If the new type forwards to another type, then it is in the middle
1456 // of being refined to another type (and hence, may have dropped all
1457 // references to what it was using before). So, use the new forwarded
1459 if (const Type *Ty = Agg->getForwardedType())
1462 return CurIdx == NumIdx ? Agg : 0;
1465 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1466 const unsigned Idx) {
1467 const unsigned Idxs[1] = { Idx };
1468 return getIndexedType(Agg, &Idxs[0], 1);
1471 ExtractValueInst::ExtractValueInst(Value *Agg,
1473 const std::string &Name,
1474 BasicBlock *InsertAtEnd)
1475 : UnaryInstruction(checkType(getIndexedType(Agg->getType(), &Idx, 1)),
1476 ExtractValue, Agg, InsertAtEnd) {
1480 ExtractValueInst::ExtractValueInst(Value *Agg,
1482 const std::string &Name,
1483 Instruction *InsertBefore)
1484 : UnaryInstruction(checkType(getIndexedType(Agg->getType(), &Idx, 1)),
1485 ExtractValue, Agg, InsertBefore) {
1489 //===----------------------------------------------------------------------===//
1490 // BinaryOperator Class
1491 //===----------------------------------------------------------------------===//
1493 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1494 const Type *Ty, const std::string &Name,
1495 Instruction *InsertBefore)
1496 : Instruction(Ty, iType,
1497 OperandTraits<BinaryOperator>::op_begin(this),
1498 OperandTraits<BinaryOperator>::operands(this),
1506 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1507 const Type *Ty, const std::string &Name,
1508 BasicBlock *InsertAtEnd)
1509 : Instruction(Ty, iType,
1510 OperandTraits<BinaryOperator>::op_begin(this),
1511 OperandTraits<BinaryOperator>::operands(this),
1520 void BinaryOperator::init(BinaryOps iType) {
1521 Value *LHS = getOperand(0), *RHS = getOperand(1);
1522 LHS = LHS; RHS = RHS; // Silence warnings.
1523 assert(LHS->getType() == RHS->getType() &&
1524 "Binary operator operand types must match!");
1529 assert(getType() == LHS->getType() &&
1530 "Arithmetic operation should return same type as operands!");
1531 assert((getType()->isInteger() || getType()->isFloatingPoint() ||
1532 isa<VectorType>(getType())) &&
1533 "Tried to create an arithmetic operation on a non-arithmetic type!");
1537 assert(getType() == LHS->getType() &&
1538 "Arithmetic operation should return same type as operands!");
1539 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1540 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1541 "Incorrect operand type (not integer) for S/UDIV");
1544 assert(getType() == LHS->getType() &&
1545 "Arithmetic operation should return same type as operands!");
1546 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1547 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1548 && "Incorrect operand type (not floating point) for FDIV");
1552 assert(getType() == LHS->getType() &&
1553 "Arithmetic operation should return same type as operands!");
1554 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1555 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1556 "Incorrect operand type (not integer) for S/UREM");
1559 assert(getType() == LHS->getType() &&
1560 "Arithmetic operation should return same type as operands!");
1561 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1562 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1563 && "Incorrect operand type (not floating point) for FREM");
1568 assert(getType() == LHS->getType() &&
1569 "Shift operation should return same type as operands!");
1570 assert(getType()->isInteger() &&
1571 "Shift operation requires integer operands");
1575 assert(getType() == LHS->getType() &&
1576 "Logical operation should return same type as operands!");
1577 assert((getType()->isInteger() ||
1578 (isa<VectorType>(getType()) &&
1579 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1580 "Tried to create a logical operation on a non-integral type!");
1588 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1589 const std::string &Name,
1590 Instruction *InsertBefore) {
1591 assert(S1->getType() == S2->getType() &&
1592 "Cannot create binary operator with two operands of differing type!");
1593 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1596 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1597 const std::string &Name,
1598 BasicBlock *InsertAtEnd) {
1599 BinaryOperator *Res = Create(Op, S1, S2, Name);
1600 InsertAtEnd->getInstList().push_back(Res);
1604 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const std::string &Name,
1605 Instruction *InsertBefore) {
1606 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1607 return new BinaryOperator(Instruction::Sub,
1609 Op->getType(), Name, InsertBefore);
1612 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const std::string &Name,
1613 BasicBlock *InsertAtEnd) {
1614 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1615 return new BinaryOperator(Instruction::Sub,
1617 Op->getType(), Name, InsertAtEnd);
1620 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const std::string &Name,
1621 Instruction *InsertBefore) {
1623 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1624 C = ConstantInt::getAllOnesValue(PTy->getElementType());
1625 C = ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), C));
1627 C = ConstantInt::getAllOnesValue(Op->getType());
1630 return new BinaryOperator(Instruction::Xor, Op, C,
1631 Op->getType(), Name, InsertBefore);
1634 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const std::string &Name,
1635 BasicBlock *InsertAtEnd) {
1637 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1638 // Create a vector of all ones values.
1639 Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType());
1641 ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1643 AllOnes = ConstantInt::getAllOnesValue(Op->getType());
1646 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1647 Op->getType(), Name, InsertAtEnd);
1651 // isConstantAllOnes - Helper function for several functions below
1652 static inline bool isConstantAllOnes(const Value *V) {
1653 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1654 return CI->isAllOnesValue();
1655 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1656 return CV->isAllOnesValue();
1660 bool BinaryOperator::isNeg(const Value *V) {
1661 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1662 if (Bop->getOpcode() == Instruction::Sub)
1663 return Bop->getOperand(0) ==
1664 ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1668 bool BinaryOperator::isNot(const Value *V) {
1669 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1670 return (Bop->getOpcode() == Instruction::Xor &&
1671 (isConstantAllOnes(Bop->getOperand(1)) ||
1672 isConstantAllOnes(Bop->getOperand(0))));
1676 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1677 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1678 return cast<BinaryOperator>(BinOp)->getOperand(1);
1681 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1682 return getNegArgument(const_cast<Value*>(BinOp));
1685 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1686 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1687 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1688 Value *Op0 = BO->getOperand(0);
1689 Value *Op1 = BO->getOperand(1);
1690 if (isConstantAllOnes(Op0)) return Op1;
1692 assert(isConstantAllOnes(Op1));
1696 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1697 return getNotArgument(const_cast<Value*>(BinOp));
1701 // swapOperands - Exchange the two operands to this instruction. This
1702 // instruction is safe to use on any binary instruction and does not
1703 // modify the semantics of the instruction. If the instruction is
1704 // order dependent (SetLT f.e.) the opcode is changed.
1706 bool BinaryOperator::swapOperands() {
1707 if (!isCommutative())
1708 return true; // Can't commute operands
1709 Op<0>().swap(Op<1>());
1713 //===----------------------------------------------------------------------===//
1715 //===----------------------------------------------------------------------===//
1717 // Just determine if this cast only deals with integral->integral conversion.
1718 bool CastInst::isIntegerCast() const {
1719 switch (getOpcode()) {
1720 default: return false;
1721 case Instruction::ZExt:
1722 case Instruction::SExt:
1723 case Instruction::Trunc:
1725 case Instruction::BitCast:
1726 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1730 bool CastInst::isLosslessCast() const {
1731 // Only BitCast can be lossless, exit fast if we're not BitCast
1732 if (getOpcode() != Instruction::BitCast)
1735 // Identity cast is always lossless
1736 const Type* SrcTy = getOperand(0)->getType();
1737 const Type* DstTy = getType();
1741 // Pointer to pointer is always lossless.
1742 if (isa<PointerType>(SrcTy))
1743 return isa<PointerType>(DstTy);
1744 return false; // Other types have no identity values
1747 /// This function determines if the CastInst does not require any bits to be
1748 /// changed in order to effect the cast. Essentially, it identifies cases where
1749 /// no code gen is necessary for the cast, hence the name no-op cast. For
1750 /// example, the following are all no-op casts:
1751 /// # bitcast i32* %x to i8*
1752 /// # bitcast <2 x i32> %x to <4 x i16>
1753 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
1754 /// @brief Determine if a cast is a no-op.
1755 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1756 switch (getOpcode()) {
1758 assert(!"Invalid CastOp");
1759 case Instruction::Trunc:
1760 case Instruction::ZExt:
1761 case Instruction::SExt:
1762 case Instruction::FPTrunc:
1763 case Instruction::FPExt:
1764 case Instruction::UIToFP:
1765 case Instruction::SIToFP:
1766 case Instruction::FPToUI:
1767 case Instruction::FPToSI:
1768 return false; // These always modify bits
1769 case Instruction::BitCast:
1770 return true; // BitCast never modifies bits.
1771 case Instruction::PtrToInt:
1772 return IntPtrTy->getPrimitiveSizeInBits() ==
1773 getType()->getPrimitiveSizeInBits();
1774 case Instruction::IntToPtr:
1775 return IntPtrTy->getPrimitiveSizeInBits() ==
1776 getOperand(0)->getType()->getPrimitiveSizeInBits();
1780 /// This function determines if a pair of casts can be eliminated and what
1781 /// opcode should be used in the elimination. This assumes that there are two
1782 /// instructions like this:
1783 /// * %F = firstOpcode SrcTy %x to MidTy
1784 /// * %S = secondOpcode MidTy %F to DstTy
1785 /// The function returns a resultOpcode so these two casts can be replaced with:
1786 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1787 /// If no such cast is permited, the function returns 0.
1788 unsigned CastInst::isEliminableCastPair(
1789 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1790 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1792 // Define the 144 possibilities for these two cast instructions. The values
1793 // in this matrix determine what to do in a given situation and select the
1794 // case in the switch below. The rows correspond to firstOp, the columns
1795 // correspond to secondOp. In looking at the table below, keep in mind
1796 // the following cast properties:
1798 // Size Compare Source Destination
1799 // Operator Src ? Size Type Sign Type Sign
1800 // -------- ------------ ------------------- ---------------------
1801 // TRUNC > Integer Any Integral Any
1802 // ZEXT < Integral Unsigned Integer Any
1803 // SEXT < Integral Signed Integer Any
1804 // FPTOUI n/a FloatPt n/a Integral Unsigned
1805 // FPTOSI n/a FloatPt n/a Integral Signed
1806 // UITOFP n/a Integral Unsigned FloatPt n/a
1807 // SITOFP n/a Integral Signed FloatPt n/a
1808 // FPTRUNC > FloatPt n/a FloatPt n/a
1809 // FPEXT < FloatPt n/a FloatPt n/a
1810 // PTRTOINT n/a Pointer n/a Integral Unsigned
1811 // INTTOPTR n/a Integral Unsigned Pointer n/a
1812 // BITCONVERT = FirstClass n/a FirstClass n/a
1814 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1815 // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
1816 // into "fptoui double to ulong", but this loses information about the range
1817 // of the produced value (we no longer know the top-part is all zeros).
1818 // Further this conversion is often much more expensive for typical hardware,
1819 // and causes issues when building libgcc. We disallow fptosi+sext for the
1821 const unsigned numCastOps =
1822 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1823 static const uint8_t CastResults[numCastOps][numCastOps] = {
1824 // T F F U S F F P I B -+
1825 // R Z S P P I I T P 2 N T |
1826 // U E E 2 2 2 2 R E I T C +- secondOp
1827 // N X X U S F F N X N 2 V |
1828 // C T T I I P P C T T P T -+
1829 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1830 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1831 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1832 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1833 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1834 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1835 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1836 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1837 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1838 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1839 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1840 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1843 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1844 [secondOp-Instruction::CastOpsBegin];
1847 // categorically disallowed
1850 // allowed, use first cast's opcode
1853 // allowed, use second cast's opcode
1856 // no-op cast in second op implies firstOp as long as the DestTy
1858 if (DstTy->isInteger())
1862 // no-op cast in second op implies firstOp as long as the DestTy
1863 // is floating point
1864 if (DstTy->isFloatingPoint())
1868 // no-op cast in first op implies secondOp as long as the SrcTy
1870 if (SrcTy->isInteger())
1874 // no-op cast in first op implies secondOp as long as the SrcTy
1875 // is a floating point
1876 if (SrcTy->isFloatingPoint())
1880 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1881 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1882 unsigned MidSize = MidTy->getPrimitiveSizeInBits();
1883 if (MidSize >= PtrSize)
1884 return Instruction::BitCast;
1888 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1889 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1890 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1891 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1892 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1893 if (SrcSize == DstSize)
1894 return Instruction::BitCast;
1895 else if (SrcSize < DstSize)
1899 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1900 return Instruction::ZExt;
1902 // fpext followed by ftrunc is allowed if the bit size returned to is
1903 // the same as the original, in which case its just a bitcast
1905 return Instruction::BitCast;
1906 return 0; // If the types are not the same we can't eliminate it.
1908 // bitcast followed by ptrtoint is allowed as long as the bitcast
1909 // is a pointer to pointer cast.
1910 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1914 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1915 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1919 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1920 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1921 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1922 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1923 if (SrcSize <= PtrSize && SrcSize == DstSize)
1924 return Instruction::BitCast;
1928 // cast combination can't happen (error in input). This is for all cases
1929 // where the MidTy is not the same for the two cast instructions.
1930 assert(!"Invalid Cast Combination");
1933 assert(!"Error in CastResults table!!!");
1939 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
1940 const std::string &Name, Instruction *InsertBefore) {
1941 // Construct and return the appropriate CastInst subclass
1943 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1944 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1945 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1946 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1947 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1948 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1949 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1950 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1951 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1952 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1953 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1954 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1956 assert(!"Invalid opcode provided");
1961 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
1962 const std::string &Name, BasicBlock *InsertAtEnd) {
1963 // Construct and return the appropriate CastInst subclass
1965 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1966 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1967 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1968 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1969 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1970 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1971 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1972 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1973 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1974 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1975 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1976 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1978 assert(!"Invalid opcode provided");
1983 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
1984 const std::string &Name,
1985 Instruction *InsertBefore) {
1986 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1987 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1988 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
1991 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
1992 const std::string &Name,
1993 BasicBlock *InsertAtEnd) {
1994 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1995 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1996 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
1999 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
2000 const std::string &Name,
2001 Instruction *InsertBefore) {
2002 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
2003 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2004 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2007 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
2008 const std::string &Name,
2009 BasicBlock *InsertAtEnd) {
2010 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
2011 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2012 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2015 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2016 const std::string &Name,
2017 Instruction *InsertBefore) {
2018 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
2019 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2020 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2023 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2024 const std::string &Name,
2025 BasicBlock *InsertAtEnd) {
2026 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
2027 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2028 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2031 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2032 const std::string &Name,
2033 BasicBlock *InsertAtEnd) {
2034 assert(isa<PointerType>(S->getType()) && "Invalid cast");
2035 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
2038 if (Ty->isInteger())
2039 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2040 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2043 /// @brief Create a BitCast or a PtrToInt cast instruction
2044 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2045 const std::string &Name,
2046 Instruction *InsertBefore) {
2047 assert(isa<PointerType>(S->getType()) && "Invalid cast");
2048 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
2051 if (Ty->isInteger())
2052 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2053 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2056 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2057 bool isSigned, const std::string &Name,
2058 Instruction *InsertBefore) {
2059 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
2060 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
2061 unsigned DstBits = Ty->getPrimitiveSizeInBits();
2062 Instruction::CastOps opcode =
2063 (SrcBits == DstBits ? Instruction::BitCast :
2064 (SrcBits > DstBits ? Instruction::Trunc :
2065 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2066 return Create(opcode, C, Ty, Name, InsertBefore);
2069 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2070 bool isSigned, const std::string &Name,
2071 BasicBlock *InsertAtEnd) {
2072 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
2073 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
2074 unsigned DstBits = Ty->getPrimitiveSizeInBits();
2075 Instruction::CastOps opcode =
2076 (SrcBits == DstBits ? Instruction::BitCast :
2077 (SrcBits > DstBits ? Instruction::Trunc :
2078 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2079 return Create(opcode, C, Ty, Name, InsertAtEnd);
2082 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2083 const std::string &Name,
2084 Instruction *InsertBefore) {
2085 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
2087 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
2088 unsigned DstBits = Ty->getPrimitiveSizeInBits();
2089 Instruction::CastOps opcode =
2090 (SrcBits == DstBits ? Instruction::BitCast :
2091 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2092 return Create(opcode, C, Ty, Name, InsertBefore);
2095 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2096 const std::string &Name,
2097 BasicBlock *InsertAtEnd) {
2098 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
2100 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
2101 unsigned DstBits = Ty->getPrimitiveSizeInBits();
2102 Instruction::CastOps opcode =
2103 (SrcBits == DstBits ? Instruction::BitCast :
2104 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2105 return Create(opcode, C, Ty, Name, InsertAtEnd);
2108 // Check whether it is valid to call getCastOpcode for these types.
2109 // This routine must be kept in sync with getCastOpcode.
2110 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
2111 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2114 if (SrcTy == DestTy)
2117 // Get the bit sizes, we'll need these
2118 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2119 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2121 // Run through the possibilities ...
2122 if (DestTy->isInteger()) { // Casting to integral
2123 if (SrcTy->isInteger()) { // Casting from integral
2125 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2127 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2128 // Casting from vector
2129 return DestBits == PTy->getBitWidth();
2130 } else { // Casting from something else
2131 return isa<PointerType>(SrcTy);
2133 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2134 if (SrcTy->isInteger()) { // Casting from integral
2136 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2138 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2139 // Casting from vector
2140 return DestBits == PTy->getBitWidth();
2141 } else { // Casting from something else
2144 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2145 // Casting to vector
2146 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2147 // Casting from vector
2148 return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
2149 } else { // Casting from something else
2150 return DestPTy->getBitWidth() == SrcBits;
2152 } else if (isa<PointerType>(DestTy)) { // Casting to pointer
2153 if (isa<PointerType>(SrcTy)) { // Casting from pointer
2155 } else if (SrcTy->isInteger()) { // Casting from integral
2157 } else { // Casting from something else
2160 } else { // Casting to something else
2165 // Provide a way to get a "cast" where the cast opcode is inferred from the
2166 // types and size of the operand. This, basically, is a parallel of the
2167 // logic in the castIsValid function below. This axiom should hold:
2168 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2169 // should not assert in castIsValid. In other words, this produces a "correct"
2170 // casting opcode for the arguments passed to it.
2171 // This routine must be kept in sync with isCastable.
2172 Instruction::CastOps
2173 CastInst::getCastOpcode(
2174 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
2175 // Get the bit sizes, we'll need these
2176 const Type *SrcTy = Src->getType();
2177 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2178 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2180 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2181 "Only first class types are castable!");
2183 // Run through the possibilities ...
2184 if (DestTy->isInteger()) { // Casting to integral
2185 if (SrcTy->isInteger()) { // Casting from integral
2186 if (DestBits < SrcBits)
2187 return Trunc; // int -> smaller int
2188 else if (DestBits > SrcBits) { // its an extension
2190 return SExt; // signed -> SEXT
2192 return ZExt; // unsigned -> ZEXT
2194 return BitCast; // Same size, No-op cast
2196 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2198 return FPToSI; // FP -> sint
2200 return FPToUI; // FP -> uint
2201 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2202 assert(DestBits == PTy->getBitWidth() &&
2203 "Casting vector to integer of different width");
2204 return BitCast; // Same size, no-op cast
2206 assert(isa<PointerType>(SrcTy) &&
2207 "Casting from a value that is not first-class type");
2208 return PtrToInt; // ptr -> int
2210 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2211 if (SrcTy->isInteger()) { // Casting from integral
2213 return SIToFP; // sint -> FP
2215 return UIToFP; // uint -> FP
2216 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2217 if (DestBits < SrcBits) {
2218 return FPTrunc; // FP -> smaller FP
2219 } else if (DestBits > SrcBits) {
2220 return FPExt; // FP -> larger FP
2222 return BitCast; // same size, no-op cast
2224 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2225 assert(DestBits == PTy->getBitWidth() &&
2226 "Casting vector to floating point of different width");
2227 return BitCast; // same size, no-op cast
2229 assert(0 && "Casting pointer or non-first class to float");
2231 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2232 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2233 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2234 "Casting vector to vector of different widths");
2235 return BitCast; // vector -> vector
2236 } else if (DestPTy->getBitWidth() == SrcBits) {
2237 return BitCast; // float/int -> vector
2239 assert(!"Illegal cast to vector (wrong type or size)");
2241 } else if (isa<PointerType>(DestTy)) {
2242 if (isa<PointerType>(SrcTy)) {
2243 return BitCast; // ptr -> ptr
2244 } else if (SrcTy->isInteger()) {
2245 return IntToPtr; // int -> ptr
2247 assert(!"Casting pointer to other than pointer or int");
2250 assert(!"Casting to type that is not first-class");
2253 // If we fall through to here we probably hit an assertion cast above
2254 // and assertions are not turned on. Anything we return is an error, so
2255 // BitCast is as good a choice as any.
2259 //===----------------------------------------------------------------------===//
2260 // CastInst SubClass Constructors
2261 //===----------------------------------------------------------------------===//
2263 /// Check that the construction parameters for a CastInst are correct. This
2264 /// could be broken out into the separate constructors but it is useful to have
2265 /// it in one place and to eliminate the redundant code for getting the sizes
2266 /// of the types involved.
2268 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2270 // Check for type sanity on the arguments
2271 const Type *SrcTy = S->getType();
2272 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
2275 // Get the size of the types in bits, we'll need this later
2276 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2277 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2279 // Switch on the opcode provided
2281 default: return false; // This is an input error
2282 case Instruction::Trunc:
2283 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize > DstBitSize;
2284 case Instruction::ZExt:
2285 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2286 case Instruction::SExt:
2287 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2288 case Instruction::FPTrunc:
2289 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2290 SrcBitSize > DstBitSize;
2291 case Instruction::FPExt:
2292 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2293 SrcBitSize < DstBitSize;
2294 case Instruction::UIToFP:
2295 case Instruction::SIToFP:
2296 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2297 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2298 return SVTy->getElementType()->isInteger() &&
2299 DVTy->getElementType()->isFloatingPoint() &&
2300 SVTy->getNumElements() == DVTy->getNumElements();
2303 return SrcTy->isInteger() && DstTy->isFloatingPoint();
2304 case Instruction::FPToUI:
2305 case Instruction::FPToSI:
2306 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2307 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2308 return SVTy->getElementType()->isFloatingPoint() &&
2309 DVTy->getElementType()->isInteger() &&
2310 SVTy->getNumElements() == DVTy->getNumElements();
2313 return SrcTy->isFloatingPoint() && DstTy->isInteger();
2314 case Instruction::PtrToInt:
2315 return isa<PointerType>(SrcTy) && DstTy->isInteger();
2316 case Instruction::IntToPtr:
2317 return SrcTy->isInteger() && isa<PointerType>(DstTy);
2318 case Instruction::BitCast:
2319 // BitCast implies a no-op cast of type only. No bits change.
2320 // However, you can't cast pointers to anything but pointers.
2321 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2324 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2325 // these cases, the cast is okay if the source and destination bit widths
2327 return SrcBitSize == DstBitSize;
2331 TruncInst::TruncInst(
2332 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2333 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2334 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2337 TruncInst::TruncInst(
2338 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2339 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2340 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2344 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2345 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2346 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2350 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2351 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2352 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2355 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2356 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2357 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2361 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2362 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2363 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2366 FPTruncInst::FPTruncInst(
2367 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2368 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2369 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2372 FPTruncInst::FPTruncInst(
2373 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2374 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2375 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2378 FPExtInst::FPExtInst(
2379 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2380 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2381 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2384 FPExtInst::FPExtInst(
2385 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2386 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2387 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2390 UIToFPInst::UIToFPInst(
2391 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2392 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2393 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2396 UIToFPInst::UIToFPInst(
2397 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2398 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2399 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2402 SIToFPInst::SIToFPInst(
2403 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2404 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2405 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2408 SIToFPInst::SIToFPInst(
2409 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2410 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2411 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2414 FPToUIInst::FPToUIInst(
2415 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2416 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2417 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2420 FPToUIInst::FPToUIInst(
2421 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2422 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2423 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2426 FPToSIInst::FPToSIInst(
2427 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2428 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2429 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2432 FPToSIInst::FPToSIInst(
2433 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2434 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2435 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2438 PtrToIntInst::PtrToIntInst(
2439 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2440 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2441 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2444 PtrToIntInst::PtrToIntInst(
2445 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2446 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2447 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2450 IntToPtrInst::IntToPtrInst(
2451 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2452 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2453 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2456 IntToPtrInst::IntToPtrInst(
2457 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2458 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2459 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2462 BitCastInst::BitCastInst(
2463 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2464 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2465 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2468 BitCastInst::BitCastInst(
2469 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2470 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2471 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2474 //===----------------------------------------------------------------------===//
2476 //===----------------------------------------------------------------------===//
2478 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2479 Value *LHS, Value *RHS, const std::string &Name,
2480 Instruction *InsertBefore)
2481 : Instruction(ty, op,
2482 OperandTraits<CmpInst>::op_begin(this),
2483 OperandTraits<CmpInst>::operands(this),
2487 SubclassData = predicate;
2491 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2492 Value *LHS, Value *RHS, const std::string &Name,
2493 BasicBlock *InsertAtEnd)
2494 : Instruction(ty, op,
2495 OperandTraits<CmpInst>::op_begin(this),
2496 OperandTraits<CmpInst>::operands(this),
2500 SubclassData = predicate;
2505 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2506 const std::string &Name, Instruction *InsertBefore) {
2507 if (Op == Instruction::ICmp) {
2508 return new ICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2511 if (Op == Instruction::FCmp) {
2512 return new FCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2515 if (Op == Instruction::VICmp) {
2516 return new VICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2519 return new VFCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2524 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2525 const std::string &Name, BasicBlock *InsertAtEnd) {
2526 if (Op == Instruction::ICmp) {
2527 return new ICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2530 if (Op == Instruction::FCmp) {
2531 return new FCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2534 if (Op == Instruction::VICmp) {
2535 return new VICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2538 return new VFCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2542 void CmpInst::swapOperands() {
2543 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2546 cast<FCmpInst>(this)->swapOperands();
2549 bool CmpInst::isCommutative() {
2550 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2551 return IC->isCommutative();
2552 return cast<FCmpInst>(this)->isCommutative();
2555 bool CmpInst::isEquality() {
2556 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2557 return IC->isEquality();
2558 return cast<FCmpInst>(this)->isEquality();
2562 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
2564 default: assert(!"Unknown cmp predicate!");
2565 case ICMP_EQ: return ICMP_NE;
2566 case ICMP_NE: return ICMP_EQ;
2567 case ICMP_UGT: return ICMP_ULE;
2568 case ICMP_ULT: return ICMP_UGE;
2569 case ICMP_UGE: return ICMP_ULT;
2570 case ICMP_ULE: return ICMP_UGT;
2571 case ICMP_SGT: return ICMP_SLE;
2572 case ICMP_SLT: return ICMP_SGE;
2573 case ICMP_SGE: return ICMP_SLT;
2574 case ICMP_SLE: return ICMP_SGT;
2576 case FCMP_OEQ: return FCMP_UNE;
2577 case FCMP_ONE: return FCMP_UEQ;
2578 case FCMP_OGT: return FCMP_ULE;
2579 case FCMP_OLT: return FCMP_UGE;
2580 case FCMP_OGE: return FCMP_ULT;
2581 case FCMP_OLE: return FCMP_UGT;
2582 case FCMP_UEQ: return FCMP_ONE;
2583 case FCMP_UNE: return FCMP_OEQ;
2584 case FCMP_UGT: return FCMP_OLE;
2585 case FCMP_ULT: return FCMP_OGE;
2586 case FCMP_UGE: return FCMP_OLT;
2587 case FCMP_ULE: return FCMP_OGT;
2588 case FCMP_ORD: return FCMP_UNO;
2589 case FCMP_UNO: return FCMP_ORD;
2590 case FCMP_TRUE: return FCMP_FALSE;
2591 case FCMP_FALSE: return FCMP_TRUE;
2595 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2597 default: assert(! "Unknown icmp predicate!");
2598 case ICMP_EQ: case ICMP_NE:
2599 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2601 case ICMP_UGT: return ICMP_SGT;
2602 case ICMP_ULT: return ICMP_SLT;
2603 case ICMP_UGE: return ICMP_SGE;
2604 case ICMP_ULE: return ICMP_SLE;
2608 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2610 default: assert(! "Unknown icmp predicate!");
2611 case ICMP_EQ: case ICMP_NE:
2612 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2614 case ICMP_SGT: return ICMP_UGT;
2615 case ICMP_SLT: return ICMP_ULT;
2616 case ICMP_SGE: return ICMP_UGE;
2617 case ICMP_SLE: return ICMP_ULE;
2621 bool ICmpInst::isSignedPredicate(Predicate pred) {
2623 default: assert(! "Unknown icmp predicate!");
2624 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2626 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2627 case ICMP_UGE: case ICMP_ULE:
2632 /// Initialize a set of values that all satisfy the condition with C.
2635 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2638 uint32_t BitWidth = C.getBitWidth();
2640 default: assert(0 && "Invalid ICmp opcode to ConstantRange ctor!");
2641 case ICmpInst::ICMP_EQ: Upper++; break;
2642 case ICmpInst::ICMP_NE: Lower++; break;
2643 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2644 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2645 case ICmpInst::ICMP_UGT:
2646 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2648 case ICmpInst::ICMP_SGT:
2649 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2651 case ICmpInst::ICMP_ULE:
2652 Lower = APInt::getMinValue(BitWidth); Upper++;
2654 case ICmpInst::ICMP_SLE:
2655 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2657 case ICmpInst::ICMP_UGE:
2658 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2660 case ICmpInst::ICMP_SGE:
2661 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2664 return ConstantRange(Lower, Upper);
2667 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
2669 default: assert(!"Unknown cmp predicate!");
2670 case ICMP_EQ: case ICMP_NE:
2672 case ICMP_SGT: return ICMP_SLT;
2673 case ICMP_SLT: return ICMP_SGT;
2674 case ICMP_SGE: return ICMP_SLE;
2675 case ICMP_SLE: return ICMP_SGE;
2676 case ICMP_UGT: return ICMP_ULT;
2677 case ICMP_ULT: return ICMP_UGT;
2678 case ICMP_UGE: return ICMP_ULE;
2679 case ICMP_ULE: return ICMP_UGE;
2681 case FCMP_FALSE: case FCMP_TRUE:
2682 case FCMP_OEQ: case FCMP_ONE:
2683 case FCMP_UEQ: case FCMP_UNE:
2684 case FCMP_ORD: case FCMP_UNO:
2686 case FCMP_OGT: return FCMP_OLT;
2687 case FCMP_OLT: return FCMP_OGT;
2688 case FCMP_OGE: return FCMP_OLE;
2689 case FCMP_OLE: return FCMP_OGE;
2690 case FCMP_UGT: return FCMP_ULT;
2691 case FCMP_ULT: return FCMP_UGT;
2692 case FCMP_UGE: return FCMP_ULE;
2693 case FCMP_ULE: return FCMP_UGE;
2697 bool CmpInst::isUnsigned(unsigned short predicate) {
2698 switch (predicate) {
2699 default: return false;
2700 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2701 case ICmpInst::ICMP_UGE: return true;
2705 bool CmpInst::isSigned(unsigned short predicate){
2706 switch (predicate) {
2707 default: return false;
2708 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2709 case ICmpInst::ICMP_SGE: return true;
2713 bool CmpInst::isOrdered(unsigned short predicate) {
2714 switch (predicate) {
2715 default: return false;
2716 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2717 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2718 case FCmpInst::FCMP_ORD: return true;
2722 bool CmpInst::isUnordered(unsigned short predicate) {
2723 switch (predicate) {
2724 default: return false;
2725 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2726 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2727 case FCmpInst::FCMP_UNO: return true;
2731 //===----------------------------------------------------------------------===//
2732 // SwitchInst Implementation
2733 //===----------------------------------------------------------------------===//
2735 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2736 assert(Value && Default);
2737 ReservedSpace = 2+NumCases*2;
2739 OperandList = allocHungoffUses(ReservedSpace);
2741 OperandList[0] = Value;
2742 OperandList[1] = Default;
2745 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2746 /// switch on and a default destination. The number of additional cases can
2747 /// be specified here to make memory allocation more efficient. This
2748 /// constructor can also autoinsert before another instruction.
2749 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2750 Instruction *InsertBefore)
2751 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) {
2752 init(Value, Default, NumCases);
2755 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2756 /// switch on and a default destination. The number of additional cases can
2757 /// be specified here to make memory allocation more efficient. This
2758 /// constructor also autoinserts at the end of the specified BasicBlock.
2759 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2760 BasicBlock *InsertAtEnd)
2761 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) {
2762 init(Value, Default, NumCases);
2765 SwitchInst::SwitchInst(const SwitchInst &SI)
2766 : TerminatorInst(Type::VoidTy, Instruction::Switch,
2767 allocHungoffUses(SI.getNumOperands()), SI.getNumOperands()) {
2768 Use *OL = OperandList, *InOL = SI.OperandList;
2769 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2771 OL[i+1] = InOL[i+1];
2775 SwitchInst::~SwitchInst() {
2776 dropHungoffUses(OperandList);
2780 /// addCase - Add an entry to the switch instruction...
2782 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2783 unsigned OpNo = NumOperands;
2784 if (OpNo+2 > ReservedSpace)
2785 resizeOperands(0); // Get more space!
2786 // Initialize some new operands.
2787 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2788 NumOperands = OpNo+2;
2789 OperandList[OpNo] = OnVal;
2790 OperandList[OpNo+1] = Dest;
2793 /// removeCase - This method removes the specified successor from the switch
2794 /// instruction. Note that this cannot be used to remove the default
2795 /// destination (successor #0).
2797 void SwitchInst::removeCase(unsigned idx) {
2798 assert(idx != 0 && "Cannot remove the default case!");
2799 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2801 unsigned NumOps = getNumOperands();
2802 Use *OL = OperandList;
2804 // Move everything after this operand down.
2806 // FIXME: we could just swap with the end of the list, then erase. However,
2807 // client might not expect this to happen. The code as it is thrashes the
2808 // use/def lists, which is kinda lame.
2809 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2811 OL[i-2+1] = OL[i+1];
2814 // Nuke the last value.
2815 OL[NumOps-2].set(0);
2816 OL[NumOps-2+1].set(0);
2817 NumOperands = NumOps-2;
2820 /// resizeOperands - resize operands - This adjusts the length of the operands
2821 /// list according to the following behavior:
2822 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2823 /// of operation. This grows the number of ops by 3 times.
2824 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2825 /// 3. If NumOps == NumOperands, trim the reserved space.
2827 void SwitchInst::resizeOperands(unsigned NumOps) {
2828 unsigned e = getNumOperands();
2831 } else if (NumOps*2 > NumOperands) {
2832 // No resize needed.
2833 if (ReservedSpace >= NumOps) return;
2834 } else if (NumOps == NumOperands) {
2835 if (ReservedSpace == NumOps) return;
2840 ReservedSpace = NumOps;
2841 Use *NewOps = allocHungoffUses(NumOps);
2842 Use *OldOps = OperandList;
2843 for (unsigned i = 0; i != e; ++i) {
2844 NewOps[i] = OldOps[i];
2846 OperandList = NewOps;
2847 if (OldOps) Use::zap(OldOps, OldOps + e, true);
2851 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2852 return getSuccessor(idx);
2854 unsigned SwitchInst::getNumSuccessorsV() const {
2855 return getNumSuccessors();
2857 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2858 setSuccessor(idx, B);
2861 //===----------------------------------------------------------------------===//
2862 // GetResultInst Implementation
2863 //===----------------------------------------------------------------------===//
2865 GetResultInst::GetResultInst(Value *Aggregate, unsigned Index,
2866 const std::string &Name,
2867 Instruction *InsertBef)
2868 : UnaryInstruction(cast<StructType>(Aggregate->getType())
2869 ->getElementType(Index),
2870 GetResult, Aggregate, InsertBef),
2872 assert(isValidOperands(Aggregate, Index)
2873 && "Invalid GetResultInst operands!");
2877 bool GetResultInst::isValidOperands(const Value *Aggregate, unsigned Index) {
2881 if (const StructType *STy = dyn_cast<StructType>(Aggregate->getType())) {
2882 unsigned NumElements = STy->getNumElements();
2883 if (Index >= NumElements || NumElements == 0)
2886 // getresult aggregate value's element types are restricted to
2887 // avoid nested aggregates.
2888 for (unsigned i = 0; i < NumElements; ++i)
2889 if (!STy->getElementType(i)->isFirstClassType())
2892 // Otherwise, Aggregate is valid.
2898 // Define these methods here so vtables don't get emitted into every translation
2899 // unit that uses these classes.
2901 GetElementPtrInst *GetElementPtrInst::clone() const {
2902 return new(getNumOperands()) GetElementPtrInst(*this);
2905 BinaryOperator *BinaryOperator::clone() const {
2906 return Create(getOpcode(), Op<0>(), Op<1>());
2909 FCmpInst* FCmpInst::clone() const {
2910 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
2912 ICmpInst* ICmpInst::clone() const {
2913 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
2916 VFCmpInst* VFCmpInst::clone() const {
2917 return new VFCmpInst(getPredicate(), Op<0>(), Op<1>());
2919 VICmpInst* VICmpInst::clone() const {
2920 return new VICmpInst(getPredicate(), Op<0>(), Op<1>());
2923 ExtractValueInst *ExtractValueInst::clone() const {
2924 return new ExtractValueInst(*this);
2926 InsertValueInst *InsertValueInst::clone() const {
2927 return new InsertValueInst(*this);
2931 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
2932 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
2933 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
2934 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
2935 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
2936 CastInst *TruncInst::clone() const { return new TruncInst(*this); }
2937 CastInst *ZExtInst::clone() const { return new ZExtInst(*this); }
2938 CastInst *SExtInst::clone() const { return new SExtInst(*this); }
2939 CastInst *FPTruncInst::clone() const { return new FPTruncInst(*this); }
2940 CastInst *FPExtInst::clone() const { return new FPExtInst(*this); }
2941 CastInst *UIToFPInst::clone() const { return new UIToFPInst(*this); }
2942 CastInst *SIToFPInst::clone() const { return new SIToFPInst(*this); }
2943 CastInst *FPToUIInst::clone() const { return new FPToUIInst(*this); }
2944 CastInst *FPToSIInst::clone() const { return new FPToSIInst(*this); }
2945 CastInst *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
2946 CastInst *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
2947 CastInst *BitCastInst::clone() const { return new BitCastInst(*this); }
2948 CallInst *CallInst::clone() const {
2949 return new(getNumOperands()) CallInst(*this);
2951 SelectInst *SelectInst::clone() const {
2952 return new(getNumOperands()) SelectInst(*this);
2954 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
2956 ExtractElementInst *ExtractElementInst::clone() const {
2957 return new ExtractElementInst(*this);
2959 InsertElementInst *InsertElementInst::clone() const {
2960 return InsertElementInst::Create(*this);
2962 ShuffleVectorInst *ShuffleVectorInst::clone() const {
2963 return new ShuffleVectorInst(*this);
2965 PHINode *PHINode::clone() const { return new PHINode(*this); }
2966 ReturnInst *ReturnInst::clone() const {
2967 return new(getNumOperands()) ReturnInst(*this);
2969 BranchInst *BranchInst::clone() const {
2970 return new(getNumOperands()) BranchInst(*this);
2972 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
2973 InvokeInst *InvokeInst::clone() const {
2974 return new(getNumOperands()) InvokeInst(*this);
2976 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
2977 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}
2978 GetResultInst *GetResultInst::clone() const { return new GetResultInst(*this); }