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/BasicBlock.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/ParamAttrsList.h"
21 #include "llvm/Support/CallSite.h"
22 #include "llvm/Support/ConstantRange.h"
23 #include "llvm/Support/MathExtras.h"
26 //===----------------------------------------------------------------------===//
28 //===----------------------------------------------------------------------===//
30 CallSite::CallSite(Instruction *C) {
31 assert((isa<CallInst>(C) || isa<InvokeInst>(C)) && "Not a call!");
34 unsigned CallSite::getCallingConv() const {
35 if (CallInst *CI = dyn_cast<CallInst>(I))
36 return CI->getCallingConv();
38 return cast<InvokeInst>(I)->getCallingConv();
40 void CallSite::setCallingConv(unsigned CC) {
41 if (CallInst *CI = dyn_cast<CallInst>(I))
42 CI->setCallingConv(CC);
44 cast<InvokeInst>(I)->setCallingConv(CC);
46 const ParamAttrsList* CallSite::getParamAttrs() const {
47 if (CallInst *CI = dyn_cast<CallInst>(I))
48 return CI->getParamAttrs();
50 return cast<InvokeInst>(I)->getParamAttrs();
52 void CallSite::setParamAttrs(const ParamAttrsList *PAL) {
53 if (CallInst *CI = dyn_cast<CallInst>(I))
54 CI->setParamAttrs(PAL);
56 cast<InvokeInst>(I)->setParamAttrs(PAL);
58 bool CallSite::paramHasAttr(uint16_t i, ParameterAttributes attr) const {
59 if (CallInst *CI = dyn_cast<CallInst>(I))
60 return CI->paramHasAttr(i, attr);
62 return cast<InvokeInst>(I)->paramHasAttr(i, attr);
64 uint16_t CallSite::getParamAlignment(uint16_t i) const {
65 if (CallInst *CI = dyn_cast<CallInst>(I))
66 return CI->getParamAlignment(i);
68 return cast<InvokeInst>(I)->getParamAlignment(i);
71 bool CallSite::doesNotAccessMemory() const {
72 if (CallInst *CI = dyn_cast<CallInst>(I))
73 return CI->doesNotAccessMemory();
75 return cast<InvokeInst>(I)->doesNotAccessMemory();
77 bool CallSite::onlyReadsMemory() const {
78 if (CallInst *CI = dyn_cast<CallInst>(I))
79 return CI->onlyReadsMemory();
81 return cast<InvokeInst>(I)->onlyReadsMemory();
83 bool CallSite::doesNotThrow() const {
84 if (CallInst *CI = dyn_cast<CallInst>(I))
85 return CI->doesNotThrow();
87 return cast<InvokeInst>(I)->doesNotThrow();
89 void CallSite::setDoesNotThrow(bool doesNotThrow) {
90 if (CallInst *CI = dyn_cast<CallInst>(I))
91 CI->setDoesNotThrow(doesNotThrow);
93 cast<InvokeInst>(I)->setDoesNotThrow(doesNotThrow);
96 //===----------------------------------------------------------------------===//
97 // TerminatorInst Class
98 //===----------------------------------------------------------------------===//
100 // Out of line virtual method, so the vtable, etc has a home.
101 TerminatorInst::~TerminatorInst() {
104 // Out of line virtual method, so the vtable, etc has a home.
105 UnaryInstruction::~UnaryInstruction() {
109 //===----------------------------------------------------------------------===//
111 //===----------------------------------------------------------------------===//
113 PHINode::PHINode(const PHINode &PN)
114 : Instruction(PN.getType(), Instruction::PHI,
115 new Use[PN.getNumOperands()], PN.getNumOperands()),
116 ReservedSpace(PN.getNumOperands()) {
117 Use *OL = OperandList;
118 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
119 OL[i].init(PN.getOperand(i), this);
120 OL[i+1].init(PN.getOperand(i+1), this);
124 PHINode::~PHINode() {
125 delete [] OperandList;
128 // removeIncomingValue - Remove an incoming value. This is useful if a
129 // predecessor basic block is deleted.
130 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
131 unsigned NumOps = getNumOperands();
132 Use *OL = OperandList;
133 assert(Idx*2 < NumOps && "BB not in PHI node!");
134 Value *Removed = OL[Idx*2];
136 // Move everything after this operand down.
138 // FIXME: we could just swap with the end of the list, then erase. However,
139 // client might not expect this to happen. The code as it is thrashes the
140 // use/def lists, which is kinda lame.
141 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
146 // Nuke the last value.
148 OL[NumOps-2+1].set(0);
149 NumOperands = NumOps-2;
151 // If the PHI node is dead, because it has zero entries, nuke it now.
152 if (NumOps == 2 && DeletePHIIfEmpty) {
153 // If anyone is using this PHI, make them use a dummy value instead...
154 replaceAllUsesWith(UndefValue::get(getType()));
160 /// resizeOperands - resize operands - This adjusts the length of the operands
161 /// list according to the following behavior:
162 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
163 /// of operation. This grows the number of ops by 1.5 times.
164 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
165 /// 3. If NumOps == NumOperands, trim the reserved space.
167 void PHINode::resizeOperands(unsigned NumOps) {
169 NumOps = (getNumOperands())*3/2;
170 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
171 } else if (NumOps*2 > NumOperands) {
173 if (ReservedSpace >= NumOps) return;
174 } else if (NumOps == NumOperands) {
175 if (ReservedSpace == NumOps) return;
180 ReservedSpace = NumOps;
181 Use *NewOps = new Use[NumOps];
182 Use *OldOps = OperandList;
183 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
184 NewOps[i].init(OldOps[i], this);
188 OperandList = NewOps;
191 /// hasConstantValue - If the specified PHI node always merges together the same
192 /// value, return the value, otherwise return null.
194 Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) const {
195 // If the PHI node only has one incoming value, eliminate the PHI node...
196 if (getNumIncomingValues() == 1) {
197 if (getIncomingValue(0) != this) // not X = phi X
198 return getIncomingValue(0);
200 return UndefValue::get(getType()); // Self cycle is dead.
203 // Otherwise if all of the incoming values are the same for the PHI, replace
204 // the PHI node with the incoming value.
207 bool HasUndefInput = false;
208 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
209 if (isa<UndefValue>(getIncomingValue(i))) {
210 HasUndefInput = true;
211 } else if (getIncomingValue(i) != this) { // Not the PHI node itself...
212 if (InVal && getIncomingValue(i) != InVal)
213 return 0; // Not the same, bail out.
215 InVal = getIncomingValue(i);
218 // The only case that could cause InVal to be null is if we have a PHI node
219 // that only has entries for itself. In this case, there is no entry into the
220 // loop, so kill the PHI.
222 if (InVal == 0) InVal = UndefValue::get(getType());
224 // If we have a PHI node like phi(X, undef, X), where X is defined by some
225 // instruction, we cannot always return X as the result of the PHI node. Only
226 // do this if X is not an instruction (thus it must dominate the PHI block),
227 // or if the client is prepared to deal with this possibility.
228 if (HasUndefInput && !AllowNonDominatingInstruction)
229 if (Instruction *IV = dyn_cast<Instruction>(InVal))
230 // If it's in the entry block, it dominates everything.
231 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
233 return 0; // Cannot guarantee that InVal dominates this PHINode.
235 // All of the incoming values are the same, return the value now.
240 //===----------------------------------------------------------------------===//
241 // CallInst Implementation
242 //===----------------------------------------------------------------------===//
244 CallInst::~CallInst() {
245 delete [] OperandList;
247 ParamAttrs->dropRef();
250 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
252 NumOperands = NumParams+1;
253 Use *OL = OperandList = new Use[NumParams+1];
254 OL[0].init(Func, this);
256 const FunctionType *FTy =
257 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
258 FTy = FTy; // silence warning.
260 assert((NumParams == FTy->getNumParams() ||
261 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
262 "Calling a function with bad signature!");
263 for (unsigned i = 0; i != NumParams; ++i) {
264 assert((i >= FTy->getNumParams() ||
265 FTy->getParamType(i) == Params[i]->getType()) &&
266 "Calling a function with a bad signature!");
267 OL[i+1].init(Params[i], this);
271 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
274 Use *OL = OperandList = new Use[3];
275 OL[0].init(Func, this);
276 OL[1].init(Actual1, this);
277 OL[2].init(Actual2, this);
279 const FunctionType *FTy =
280 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
281 FTy = FTy; // silence warning.
283 assert((FTy->getNumParams() == 2 ||
284 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
285 "Calling a function with bad signature");
286 assert((0 >= FTy->getNumParams() ||
287 FTy->getParamType(0) == Actual1->getType()) &&
288 "Calling a function with a bad signature!");
289 assert((1 >= FTy->getNumParams() ||
290 FTy->getParamType(1) == Actual2->getType()) &&
291 "Calling a function with a bad signature!");
294 void CallInst::init(Value *Func, Value *Actual) {
297 Use *OL = OperandList = new Use[2];
298 OL[0].init(Func, this);
299 OL[1].init(Actual, this);
301 const FunctionType *FTy =
302 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
303 FTy = FTy; // silence warning.
305 assert((FTy->getNumParams() == 1 ||
306 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
307 "Calling a function with bad signature");
308 assert((0 == FTy->getNumParams() ||
309 FTy->getParamType(0) == Actual->getType()) &&
310 "Calling a function with a bad signature!");
313 void CallInst::init(Value *Func) {
316 Use *OL = OperandList = new Use[1];
317 OL[0].init(Func, this);
319 const FunctionType *FTy =
320 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
321 FTy = FTy; // silence warning.
323 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
326 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
327 Instruction *InsertBefore)
328 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
329 ->getElementType())->getReturnType(),
330 Instruction::Call, 0, 0, InsertBefore) {
335 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
336 BasicBlock *InsertAtEnd)
337 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
338 ->getElementType())->getReturnType(),
339 Instruction::Call, 0, 0, InsertAtEnd) {
343 CallInst::CallInst(Value *Func, const std::string &Name,
344 Instruction *InsertBefore)
345 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
346 ->getElementType())->getReturnType(),
347 Instruction::Call, 0, 0, InsertBefore) {
352 CallInst::CallInst(Value *Func, const std::string &Name,
353 BasicBlock *InsertAtEnd)
354 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
355 ->getElementType())->getReturnType(),
356 Instruction::Call, 0, 0, InsertAtEnd) {
361 CallInst::CallInst(const CallInst &CI)
362 : Instruction(CI.getType(), Instruction::Call, new Use[CI.getNumOperands()],
363 CI.getNumOperands()),
365 setParamAttrs(CI.getParamAttrs());
366 SubclassData = CI.SubclassData;
367 Use *OL = OperandList;
368 Use *InOL = CI.OperandList;
369 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
370 OL[i].init(InOL[i], this);
373 void CallInst::setParamAttrs(const ParamAttrsList *newAttrs) {
374 if (ParamAttrs == newAttrs)
378 ParamAttrs->dropRef();
383 ParamAttrs = newAttrs;
386 bool CallInst::paramHasAttr(uint16_t i, ParameterAttributes attr) const {
387 if (ParamAttrs && ParamAttrs->paramHasAttr(i, attr))
389 if (const Function *F = getCalledFunction())
390 return F->paramHasAttr(i, attr);
394 uint16_t CallInst::getParamAlignment(uint16_t i) const {
395 if (ParamAttrs && ParamAttrs->getParamAlignment(i))
396 return ParamAttrs->getParamAlignment(i);
397 if (const Function *F = getCalledFunction())
398 return F->getParamAlignment(i);
402 /// @brief Determine if the call does not access memory.
403 bool CallInst::doesNotAccessMemory() const {
404 return paramHasAttr(0, ParamAttr::ReadNone);
407 /// @brief Determine if the call does not access or only reads memory.
408 bool CallInst::onlyReadsMemory() const {
409 return doesNotAccessMemory() || paramHasAttr(0, ParamAttr::ReadOnly);
412 /// @brief Determine if the call cannot return.
413 bool CallInst::doesNotReturn() const {
414 return paramHasAttr(0, ParamAttr::NoReturn);
417 /// @brief Determine if the call cannot unwind.
418 bool CallInst::doesNotThrow() const {
419 return paramHasAttr(0, ParamAttr::NoUnwind);
422 /// @brief Determine if the call returns a structure.
423 bool CallInst::isStructReturn() const {
424 // Be friendly and also check the callee.
425 return paramHasAttr(1, ParamAttr::StructRet);
428 /// @brief Determine if any call argument is an aggregate passed by value.
429 bool CallInst::hasByValArgument() const {
430 if (ParamAttrs && ParamAttrs->hasAttrSomewhere(ParamAttr::ByVal))
432 // Be consistent with other methods and check the callee too.
433 if (const Function *F = getCalledFunction())
434 if (const ParamAttrsList *PAL = F->getParamAttrs())
435 return PAL->hasAttrSomewhere(ParamAttr::ByVal);
439 void CallInst::setDoesNotThrow(bool doesNotThrow) {
440 const ParamAttrsList *PAL = getParamAttrs();
442 PAL = ParamAttrsList::includeAttrs(PAL, 0, ParamAttr::NoUnwind);
444 PAL = ParamAttrsList::excludeAttrs(PAL, 0, ParamAttr::NoUnwind);
449 //===----------------------------------------------------------------------===//
450 // InvokeInst Implementation
451 //===----------------------------------------------------------------------===//
453 InvokeInst::~InvokeInst() {
454 delete [] OperandList;
456 ParamAttrs->dropRef();
459 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
460 Value* const *Args, unsigned NumArgs) {
462 NumOperands = 3+NumArgs;
463 Use *OL = OperandList = new Use[3+NumArgs];
464 OL[0].init(Fn, this);
465 OL[1].init(IfNormal, this);
466 OL[2].init(IfException, this);
467 const FunctionType *FTy =
468 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
469 FTy = FTy; // silence warning.
471 assert(((NumArgs == FTy->getNumParams()) ||
472 (FTy->isVarArg() && NumArgs > FTy->getNumParams())) &&
473 "Calling a function with bad signature");
475 for (unsigned i = 0, e = NumArgs; i != e; i++) {
476 assert((i >= FTy->getNumParams() ||
477 FTy->getParamType(i) == Args[i]->getType()) &&
478 "Invoking a function with a bad signature!");
480 OL[i+3].init(Args[i], this);
484 InvokeInst::InvokeInst(const InvokeInst &II)
485 : TerminatorInst(II.getType(), Instruction::Invoke,
486 new Use[II.getNumOperands()], II.getNumOperands()),
488 setParamAttrs(II.getParamAttrs());
489 SubclassData = II.SubclassData;
490 Use *OL = OperandList, *InOL = II.OperandList;
491 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
492 OL[i].init(InOL[i], this);
495 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
496 return getSuccessor(idx);
498 unsigned InvokeInst::getNumSuccessorsV() const {
499 return getNumSuccessors();
501 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
502 return setSuccessor(idx, B);
505 void InvokeInst::setParamAttrs(const ParamAttrsList *newAttrs) {
506 if (ParamAttrs == newAttrs)
510 ParamAttrs->dropRef();
515 ParamAttrs = newAttrs;
518 bool InvokeInst::paramHasAttr(uint16_t i, ParameterAttributes attr) const {
519 if (ParamAttrs && ParamAttrs->paramHasAttr(i, attr))
521 if (const Function *F = getCalledFunction())
522 return F->paramHasAttr(i, attr);
526 uint16_t InvokeInst::getParamAlignment(uint16_t i) const {
527 if (ParamAttrs && ParamAttrs->getParamAlignment(i))
528 return ParamAttrs->getParamAlignment(i);
529 if (const Function *F = getCalledFunction())
530 return F->getParamAlignment(i);
534 /// @brief Determine if the call does not access memory.
535 bool InvokeInst::doesNotAccessMemory() const {
536 return paramHasAttr(0, ParamAttr::ReadNone);
539 /// @brief Determine if the call does not access or only reads memory.
540 bool InvokeInst::onlyReadsMemory() const {
541 return doesNotAccessMemory() || paramHasAttr(0, ParamAttr::ReadOnly);
544 /// @brief Determine if the call cannot return.
545 bool InvokeInst::doesNotReturn() const {
546 return paramHasAttr(0, ParamAttr::NoReturn);
549 /// @brief Determine if the call cannot unwind.
550 bool InvokeInst::doesNotThrow() const {
551 return paramHasAttr(0, ParamAttr::NoUnwind);
554 void InvokeInst::setDoesNotThrow(bool doesNotThrow) {
555 const ParamAttrsList *PAL = getParamAttrs();
557 PAL = ParamAttrsList::includeAttrs(PAL, 0, ParamAttr::NoUnwind);
559 PAL = ParamAttrsList::excludeAttrs(PAL, 0, ParamAttr::NoUnwind);
563 /// @brief Determine if the call returns a structure.
564 bool InvokeInst::isStructReturn() const {
565 // Be friendly and also check the callee.
566 return paramHasAttr(1, ParamAttr::StructRet);
570 //===----------------------------------------------------------------------===//
571 // ReturnInst Implementation
572 //===----------------------------------------------------------------------===//
574 ReturnInst::ReturnInst(const ReturnInst &RI)
575 : TerminatorInst(Type::VoidTy, Instruction::Ret,
576 &RetVal, RI.getNumOperands()) {
577 unsigned N = RI.getNumOperands();
579 RetVal.init(RI.RetVal, this);
581 Use *OL = OperandList = new Use[N];
582 for (unsigned i = 0; i < N; ++i)
583 OL[i].init(RI.getOperand(i), this);
587 ReturnInst::ReturnInst(Value *retVal, Instruction *InsertBefore)
588 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertBefore) {
592 ReturnInst::ReturnInst(Value *retVal, BasicBlock *InsertAtEnd)
593 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertAtEnd) {
597 ReturnInst::ReturnInst(BasicBlock *InsertAtEnd)
598 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertAtEnd) {
601 ReturnInst::ReturnInst(Value * const* retVals, unsigned N,
602 Instruction *InsertBefore)
603 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, N, InsertBefore) {
607 ReturnInst::ReturnInst(Value * const* retVals, unsigned N,
608 BasicBlock *InsertAtEnd)
609 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, N, InsertAtEnd) {
613 ReturnInst::ReturnInst(Value * const* retVals, unsigned N)
614 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, N) {
619 void ReturnInst::init(Value * const* retVals, unsigned N) {
620 assert (N > 0 && "Invalid operands numbers in ReturnInst init");
623 if (NumOperands == 1) {
625 if (V->getType() == Type::VoidTy)
627 RetVal.init(V, this);
631 Use *OL = OperandList = new Use[NumOperands];
632 for (unsigned i = 0; i < NumOperands; ++i) {
633 Value *V = *retVals++;
634 assert(!isa<BasicBlock>(V) &&
635 "Cannot return basic block. Probably using the incorrect ctor");
640 unsigned ReturnInst::getNumSuccessorsV() const {
641 return getNumSuccessors();
644 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
645 /// emit the vtable for the class in this translation unit.
646 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
647 assert(0 && "ReturnInst has no successors!");
650 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
651 assert(0 && "ReturnInst has no successors!");
656 ReturnInst::~ReturnInst() {
658 delete [] OperandList;
661 //===----------------------------------------------------------------------===//
662 // UnwindInst Implementation
663 //===----------------------------------------------------------------------===//
665 UnwindInst::UnwindInst(Instruction *InsertBefore)
666 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertBefore) {
668 UnwindInst::UnwindInst(BasicBlock *InsertAtEnd)
669 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertAtEnd) {
673 unsigned UnwindInst::getNumSuccessorsV() const {
674 return getNumSuccessors();
677 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
678 assert(0 && "UnwindInst has no successors!");
681 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
682 assert(0 && "UnwindInst has no successors!");
687 //===----------------------------------------------------------------------===//
688 // UnreachableInst Implementation
689 //===----------------------------------------------------------------------===//
691 UnreachableInst::UnreachableInst(Instruction *InsertBefore)
692 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertBefore) {
694 UnreachableInst::UnreachableInst(BasicBlock *InsertAtEnd)
695 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertAtEnd) {
698 unsigned UnreachableInst::getNumSuccessorsV() const {
699 return getNumSuccessors();
702 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
703 assert(0 && "UnwindInst has no successors!");
706 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
707 assert(0 && "UnwindInst has no successors!");
712 //===----------------------------------------------------------------------===//
713 // BranchInst Implementation
714 //===----------------------------------------------------------------------===//
716 void BranchInst::AssertOK() {
718 assert(getCondition()->getType() == Type::Int1Ty &&
719 "May only branch on boolean predicates!");
722 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
723 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 1, InsertBefore) {
724 assert(IfTrue != 0 && "Branch destination may not be null!");
725 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
727 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
728 Instruction *InsertBefore)
729 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 3, InsertBefore) {
730 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
731 Ops[1].init(reinterpret_cast<Value*>(IfFalse), this);
732 Ops[2].init(Cond, this);
738 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
739 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 1, InsertAtEnd) {
740 assert(IfTrue != 0 && "Branch destination may not be null!");
741 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
744 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
745 BasicBlock *InsertAtEnd)
746 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 3, InsertAtEnd) {
747 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
748 Ops[1].init(reinterpret_cast<Value*>(IfFalse), this);
749 Ops[2].init(Cond, this);
756 BranchInst::BranchInst(const BranchInst &BI) :
757 TerminatorInst(Type::VoidTy, Instruction::Br, Ops, BI.getNumOperands()) {
758 OperandList[0].init(BI.getOperand(0), this);
759 if (BI.getNumOperands() != 1) {
760 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
761 OperandList[1].init(BI.getOperand(1), this);
762 OperandList[2].init(BI.getOperand(2), this);
766 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
767 return getSuccessor(idx);
769 unsigned BranchInst::getNumSuccessorsV() const {
770 return getNumSuccessors();
772 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
773 setSuccessor(idx, B);
777 //===----------------------------------------------------------------------===//
778 // AllocationInst Implementation
779 //===----------------------------------------------------------------------===//
781 static Value *getAISize(Value *Amt) {
783 Amt = ConstantInt::get(Type::Int32Ty, 1);
785 assert(!isa<BasicBlock>(Amt) &&
786 "Passed basic block into allocation size parameter! Use other ctor");
787 assert(Amt->getType() == Type::Int32Ty &&
788 "Malloc/Allocation array size is not a 32-bit integer!");
793 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
794 unsigned Align, const std::string &Name,
795 Instruction *InsertBefore)
796 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
797 InsertBefore), Alignment(Align) {
798 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
799 assert(Ty != Type::VoidTy && "Cannot allocate void!");
803 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
804 unsigned Align, const std::string &Name,
805 BasicBlock *InsertAtEnd)
806 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
807 InsertAtEnd), Alignment(Align) {
808 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
809 assert(Ty != Type::VoidTy && "Cannot allocate void!");
813 // Out of line virtual method, so the vtable, etc has a home.
814 AllocationInst::~AllocationInst() {
817 bool AllocationInst::isArrayAllocation() const {
818 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
819 return CI->getZExtValue() != 1;
823 const Type *AllocationInst::getAllocatedType() const {
824 return getType()->getElementType();
827 AllocaInst::AllocaInst(const AllocaInst &AI)
828 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
829 Instruction::Alloca, AI.getAlignment()) {
832 MallocInst::MallocInst(const MallocInst &MI)
833 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
834 Instruction::Malloc, MI.getAlignment()) {
837 //===----------------------------------------------------------------------===//
838 // FreeInst Implementation
839 //===----------------------------------------------------------------------===//
841 void FreeInst::AssertOK() {
842 assert(isa<PointerType>(getOperand(0)->getType()) &&
843 "Can not free something of nonpointer type!");
846 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
847 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertBefore) {
851 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
852 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertAtEnd) {
857 //===----------------------------------------------------------------------===//
858 // LoadInst Implementation
859 //===----------------------------------------------------------------------===//
861 void LoadInst::AssertOK() {
862 assert(isa<PointerType>(getOperand(0)->getType()) &&
863 "Ptr must have pointer type.");
866 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
867 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
868 Load, Ptr, InsertBef) {
875 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
876 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
877 Load, Ptr, InsertAE) {
884 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
885 Instruction *InsertBef)
886 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
887 Load, Ptr, InsertBef) {
888 setVolatile(isVolatile);
894 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
895 unsigned Align, Instruction *InsertBef)
896 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
897 Load, Ptr, InsertBef) {
898 setVolatile(isVolatile);
904 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
905 unsigned Align, BasicBlock *InsertAE)
906 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
907 Load, Ptr, InsertAE) {
908 setVolatile(isVolatile);
914 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
915 BasicBlock *InsertAE)
916 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
917 Load, Ptr, InsertAE) {
918 setVolatile(isVolatile);
926 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
927 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
928 Load, Ptr, InsertBef) {
932 if (Name && Name[0]) setName(Name);
935 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
936 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
937 Load, Ptr, InsertAE) {
941 if (Name && Name[0]) setName(Name);
944 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
945 Instruction *InsertBef)
946 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
947 Load, Ptr, InsertBef) {
948 setVolatile(isVolatile);
951 if (Name && Name[0]) setName(Name);
954 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
955 BasicBlock *InsertAE)
956 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
957 Load, Ptr, InsertAE) {
958 setVolatile(isVolatile);
961 if (Name && Name[0]) setName(Name);
964 void LoadInst::setAlignment(unsigned Align) {
965 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
966 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
969 //===----------------------------------------------------------------------===//
970 // StoreInst Implementation
971 //===----------------------------------------------------------------------===//
973 void StoreInst::AssertOK() {
974 assert(isa<PointerType>(getOperand(1)->getType()) &&
975 "Ptr must have pointer type!");
976 assert(getOperand(0)->getType() ==
977 cast<PointerType>(getOperand(1)->getType())->getElementType()
978 && "Ptr must be a pointer to Val type!");
982 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
983 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
984 Ops[0].init(val, this);
985 Ops[1].init(addr, this);
991 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
992 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
993 Ops[0].init(val, this);
994 Ops[1].init(addr, this);
1000 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1001 Instruction *InsertBefore)
1002 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
1003 Ops[0].init(val, this);
1004 Ops[1].init(addr, this);
1005 setVolatile(isVolatile);
1010 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1011 unsigned Align, Instruction *InsertBefore)
1012 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
1013 Ops[0].init(val, this);
1014 Ops[1].init(addr, this);
1015 setVolatile(isVolatile);
1016 setAlignment(Align);
1020 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1021 unsigned Align, BasicBlock *InsertAtEnd)
1022 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
1023 Ops[0].init(val, this);
1024 Ops[1].init(addr, this);
1025 setVolatile(isVolatile);
1026 setAlignment(Align);
1030 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1031 BasicBlock *InsertAtEnd)
1032 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
1033 Ops[0].init(val, this);
1034 Ops[1].init(addr, this);
1035 setVolatile(isVolatile);
1040 void StoreInst::setAlignment(unsigned Align) {
1041 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1042 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
1045 //===----------------------------------------------------------------------===//
1046 // GetElementPtrInst Implementation
1047 //===----------------------------------------------------------------------===//
1049 static unsigned retrieveAddrSpace(const Value *Val) {
1050 return cast<PointerType>(Val->getType())->getAddressSpace();
1053 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx) {
1054 NumOperands = 1+NumIdx;
1055 Use *OL = OperandList = new Use[NumOperands];
1056 OL[0].init(Ptr, this);
1058 for (unsigned i = 0; i != NumIdx; ++i)
1059 OL[i+1].init(Idx[i], this);
1062 void GetElementPtrInst::init(Value *Ptr, Value *Idx) {
1064 Use *OL = OperandList = new Use[2];
1065 OL[0].init(Ptr, this);
1066 OL[1].init(Idx, this);
1069 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1070 const std::string &Name, Instruction *InBe)
1071 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1072 retrieveAddrSpace(Ptr)),
1073 GetElementPtr, 0, 0, InBe) {
1078 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1079 const std::string &Name, BasicBlock *IAE)
1080 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1081 retrieveAddrSpace(Ptr)),
1082 GetElementPtr, 0, 0, IAE) {
1087 GetElementPtrInst::~GetElementPtrInst() {
1088 delete[] OperandList;
1091 // getIndexedType - Returns the type of the element that would be loaded with
1092 // a load instruction with the specified parameters.
1094 // A null type is returned if the indices are invalid for the specified
1097 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1100 bool AllowCompositeLeaf) {
1101 if (!isa<PointerType>(Ptr)) return 0; // Type isn't a pointer type!
1103 // Handle the special case of the empty set index set...
1105 if (AllowCompositeLeaf ||
1106 cast<PointerType>(Ptr)->getElementType()->isFirstClassType())
1107 return cast<PointerType>(Ptr)->getElementType();
1112 unsigned CurIdx = 0;
1113 while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
1114 if (NumIdx == CurIdx) {
1115 if (AllowCompositeLeaf || CT->isFirstClassType()) return Ptr;
1116 return 0; // Can't load a whole structure or array!?!?
1119 Value *Index = Idxs[CurIdx++];
1120 if (isa<PointerType>(CT) && CurIdx != 1)
1121 return 0; // Can only index into pointer types at the first index!
1122 if (!CT->indexValid(Index)) return 0;
1123 Ptr = CT->getTypeAtIndex(Index);
1125 // If the new type forwards to another type, then it is in the middle
1126 // of being refined to another type (and hence, may have dropped all
1127 // references to what it was using before). So, use the new forwarded
1129 if (const Type * Ty = Ptr->getForwardedType()) {
1133 return CurIdx == NumIdx ? Ptr : 0;
1136 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1137 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1138 if (!PTy) return 0; // Type isn't a pointer type!
1140 // Check the pointer index.
1141 if (!PTy->indexValid(Idx)) return 0;
1143 return PTy->getElementType();
1147 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1148 /// zeros. If so, the result pointer and the first operand have the same
1149 /// value, just potentially different types.
1150 bool GetElementPtrInst::hasAllZeroIndices() const {
1151 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1152 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1153 if (!CI->isZero()) return false;
1161 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1162 /// constant integers. If so, the result pointer and the first operand have
1163 /// a constant offset between them.
1164 bool GetElementPtrInst::hasAllConstantIndices() const {
1165 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1166 if (!isa<ConstantInt>(getOperand(i)))
1173 //===----------------------------------------------------------------------===//
1174 // ExtractElementInst Implementation
1175 //===----------------------------------------------------------------------===//
1177 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1178 const std::string &Name,
1179 Instruction *InsertBef)
1180 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1181 ExtractElement, Ops, 2, InsertBef) {
1182 assert(isValidOperands(Val, Index) &&
1183 "Invalid extractelement instruction operands!");
1184 Ops[0].init(Val, this);
1185 Ops[1].init(Index, this);
1189 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1190 const std::string &Name,
1191 Instruction *InsertBef)
1192 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1193 ExtractElement, Ops, 2, InsertBef) {
1194 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1195 assert(isValidOperands(Val, Index) &&
1196 "Invalid extractelement instruction operands!");
1197 Ops[0].init(Val, this);
1198 Ops[1].init(Index, this);
1203 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1204 const std::string &Name,
1205 BasicBlock *InsertAE)
1206 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1207 ExtractElement, Ops, 2, InsertAE) {
1208 assert(isValidOperands(Val, Index) &&
1209 "Invalid extractelement instruction operands!");
1211 Ops[0].init(Val, this);
1212 Ops[1].init(Index, this);
1216 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1217 const std::string &Name,
1218 BasicBlock *InsertAE)
1219 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1220 ExtractElement, Ops, 2, InsertAE) {
1221 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1222 assert(isValidOperands(Val, Index) &&
1223 "Invalid extractelement instruction operands!");
1225 Ops[0].init(Val, this);
1226 Ops[1].init(Index, this);
1231 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1232 if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty)
1238 //===----------------------------------------------------------------------===//
1239 // InsertElementInst Implementation
1240 //===----------------------------------------------------------------------===//
1242 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
1243 : Instruction(IE.getType(), InsertElement, Ops, 3) {
1244 Ops[0].init(IE.Ops[0], this);
1245 Ops[1].init(IE.Ops[1], this);
1246 Ops[2].init(IE.Ops[2], this);
1248 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1249 const std::string &Name,
1250 Instruction *InsertBef)
1251 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertBef) {
1252 assert(isValidOperands(Vec, Elt, Index) &&
1253 "Invalid insertelement instruction operands!");
1254 Ops[0].init(Vec, this);
1255 Ops[1].init(Elt, this);
1256 Ops[2].init(Index, this);
1260 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1261 const std::string &Name,
1262 Instruction *InsertBef)
1263 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertBef) {
1264 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1265 assert(isValidOperands(Vec, Elt, Index) &&
1266 "Invalid insertelement instruction operands!");
1267 Ops[0].init(Vec, this);
1268 Ops[1].init(Elt, this);
1269 Ops[2].init(Index, this);
1274 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1275 const std::string &Name,
1276 BasicBlock *InsertAE)
1277 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertAE) {
1278 assert(isValidOperands(Vec, Elt, Index) &&
1279 "Invalid insertelement instruction operands!");
1281 Ops[0].init(Vec, this);
1282 Ops[1].init(Elt, this);
1283 Ops[2].init(Index, this);
1287 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1288 const std::string &Name,
1289 BasicBlock *InsertAE)
1290 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertAE) {
1291 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1292 assert(isValidOperands(Vec, Elt, Index) &&
1293 "Invalid insertelement instruction operands!");
1295 Ops[0].init(Vec, this);
1296 Ops[1].init(Elt, this);
1297 Ops[2].init(Index, this);
1301 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1302 const Value *Index) {
1303 if (!isa<VectorType>(Vec->getType()))
1304 return false; // First operand of insertelement must be vector type.
1306 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1307 return false;// Second operand of insertelement must be vector element type.
1309 if (Index->getType() != Type::Int32Ty)
1310 return false; // Third operand of insertelement must be uint.
1315 //===----------------------------------------------------------------------===//
1316 // ShuffleVectorInst Implementation
1317 //===----------------------------------------------------------------------===//
1319 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
1320 : Instruction(SV.getType(), ShuffleVector, Ops, 3) {
1321 Ops[0].init(SV.Ops[0], this);
1322 Ops[1].init(SV.Ops[1], this);
1323 Ops[2].init(SV.Ops[2], this);
1326 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1327 const std::string &Name,
1328 Instruction *InsertBefore)
1329 : Instruction(V1->getType(), ShuffleVector, Ops, 3, InsertBefore) {
1330 assert(isValidOperands(V1, V2, Mask) &&
1331 "Invalid shuffle vector instruction operands!");
1332 Ops[0].init(V1, this);
1333 Ops[1].init(V2, this);
1334 Ops[2].init(Mask, this);
1338 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1339 const std::string &Name,
1340 BasicBlock *InsertAtEnd)
1341 : Instruction(V1->getType(), ShuffleVector, Ops, 3, InsertAtEnd) {
1342 assert(isValidOperands(V1, V2, Mask) &&
1343 "Invalid shuffle vector instruction operands!");
1345 Ops[0].init(V1, this);
1346 Ops[1].init(V2, this);
1347 Ops[2].init(Mask, this);
1351 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1352 const Value *Mask) {
1353 if (!isa<VectorType>(V1->getType())) return false;
1354 if (V1->getType() != V2->getType()) return false;
1355 if (!isa<VectorType>(Mask->getType()) ||
1356 cast<VectorType>(Mask->getType())->getElementType() != Type::Int32Ty ||
1357 cast<VectorType>(Mask->getType())->getNumElements() !=
1358 cast<VectorType>(V1->getType())->getNumElements())
1364 //===----------------------------------------------------------------------===//
1365 // BinaryOperator Class
1366 //===----------------------------------------------------------------------===//
1368 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1369 const Type *Ty, const std::string &Name,
1370 Instruction *InsertBefore)
1371 : Instruction(Ty, iType, Ops, 2, InsertBefore) {
1372 Ops[0].init(S1, this);
1373 Ops[1].init(S2, this);
1378 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1379 const Type *Ty, const std::string &Name,
1380 BasicBlock *InsertAtEnd)
1381 : Instruction(Ty, iType, Ops, 2, InsertAtEnd) {
1382 Ops[0].init(S1, this);
1383 Ops[1].init(S2, this);
1389 void BinaryOperator::init(BinaryOps iType) {
1390 Value *LHS = getOperand(0), *RHS = getOperand(1);
1391 LHS = LHS; RHS = RHS; // Silence warnings.
1392 assert(LHS->getType() == RHS->getType() &&
1393 "Binary operator operand types must match!");
1398 assert(getType() == LHS->getType() &&
1399 "Arithmetic operation should return same type as operands!");
1400 assert((getType()->isInteger() || getType()->isFloatingPoint() ||
1401 isa<VectorType>(getType())) &&
1402 "Tried to create an arithmetic operation on a non-arithmetic type!");
1406 assert(getType() == LHS->getType() &&
1407 "Arithmetic operation should return same type as operands!");
1408 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1409 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1410 "Incorrect operand type (not integer) for S/UDIV");
1413 assert(getType() == LHS->getType() &&
1414 "Arithmetic operation should return same type as operands!");
1415 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1416 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1417 && "Incorrect operand type (not floating point) for FDIV");
1421 assert(getType() == LHS->getType() &&
1422 "Arithmetic operation should return same type as operands!");
1423 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1424 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1425 "Incorrect operand type (not integer) for S/UREM");
1428 assert(getType() == LHS->getType() &&
1429 "Arithmetic operation should return same type as operands!");
1430 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1431 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1432 && "Incorrect operand type (not floating point) for FREM");
1437 assert(getType() == LHS->getType() &&
1438 "Shift operation should return same type as operands!");
1439 assert(getType()->isInteger() &&
1440 "Shift operation requires integer operands");
1444 assert(getType() == LHS->getType() &&
1445 "Logical operation should return same type as operands!");
1446 assert((getType()->isInteger() ||
1447 (isa<VectorType>(getType()) &&
1448 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1449 "Tried to create a logical operation on a non-integral type!");
1457 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1458 const std::string &Name,
1459 Instruction *InsertBefore) {
1460 assert(S1->getType() == S2->getType() &&
1461 "Cannot create binary operator with two operands of differing type!");
1462 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1465 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1466 const std::string &Name,
1467 BasicBlock *InsertAtEnd) {
1468 BinaryOperator *Res = create(Op, S1, S2, Name);
1469 InsertAtEnd->getInstList().push_back(Res);
1473 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1474 Instruction *InsertBefore) {
1475 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1476 return new BinaryOperator(Instruction::Sub,
1478 Op->getType(), Name, InsertBefore);
1481 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1482 BasicBlock *InsertAtEnd) {
1483 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1484 return new BinaryOperator(Instruction::Sub,
1486 Op->getType(), Name, InsertAtEnd);
1489 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1490 Instruction *InsertBefore) {
1492 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1493 C = ConstantInt::getAllOnesValue(PTy->getElementType());
1494 C = ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), C));
1496 C = ConstantInt::getAllOnesValue(Op->getType());
1499 return new BinaryOperator(Instruction::Xor, Op, C,
1500 Op->getType(), Name, InsertBefore);
1503 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1504 BasicBlock *InsertAtEnd) {
1506 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1507 // Create a vector of all ones values.
1508 Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType());
1510 ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1512 AllOnes = ConstantInt::getAllOnesValue(Op->getType());
1515 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1516 Op->getType(), Name, InsertAtEnd);
1520 // isConstantAllOnes - Helper function for several functions below
1521 static inline bool isConstantAllOnes(const Value *V) {
1522 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1523 return CI->isAllOnesValue();
1524 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1525 return CV->isAllOnesValue();
1529 bool BinaryOperator::isNeg(const Value *V) {
1530 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1531 if (Bop->getOpcode() == Instruction::Sub)
1532 return Bop->getOperand(0) ==
1533 ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1537 bool BinaryOperator::isNot(const Value *V) {
1538 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1539 return (Bop->getOpcode() == Instruction::Xor &&
1540 (isConstantAllOnes(Bop->getOperand(1)) ||
1541 isConstantAllOnes(Bop->getOperand(0))));
1545 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1546 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1547 return cast<BinaryOperator>(BinOp)->getOperand(1);
1550 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1551 return getNegArgument(const_cast<Value*>(BinOp));
1554 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1555 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1556 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1557 Value *Op0 = BO->getOperand(0);
1558 Value *Op1 = BO->getOperand(1);
1559 if (isConstantAllOnes(Op0)) return Op1;
1561 assert(isConstantAllOnes(Op1));
1565 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1566 return getNotArgument(const_cast<Value*>(BinOp));
1570 // swapOperands - Exchange the two operands to this instruction. This
1571 // instruction is safe to use on any binary instruction and does not
1572 // modify the semantics of the instruction. If the instruction is
1573 // order dependent (SetLT f.e.) the opcode is changed.
1575 bool BinaryOperator::swapOperands() {
1576 if (!isCommutative())
1577 return true; // Can't commute operands
1578 std::swap(Ops[0], Ops[1]);
1582 //===----------------------------------------------------------------------===//
1584 //===----------------------------------------------------------------------===//
1586 // Just determine if this cast only deals with integral->integral conversion.
1587 bool CastInst::isIntegerCast() const {
1588 switch (getOpcode()) {
1589 default: return false;
1590 case Instruction::ZExt:
1591 case Instruction::SExt:
1592 case Instruction::Trunc:
1594 case Instruction::BitCast:
1595 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1599 bool CastInst::isLosslessCast() const {
1600 // Only BitCast can be lossless, exit fast if we're not BitCast
1601 if (getOpcode() != Instruction::BitCast)
1604 // Identity cast is always lossless
1605 const Type* SrcTy = getOperand(0)->getType();
1606 const Type* DstTy = getType();
1610 // Pointer to pointer is always lossless.
1611 if (isa<PointerType>(SrcTy))
1612 return isa<PointerType>(DstTy);
1613 return false; // Other types have no identity values
1616 /// This function determines if the CastInst does not require any bits to be
1617 /// changed in order to effect the cast. Essentially, it identifies cases where
1618 /// no code gen is necessary for the cast, hence the name no-op cast. For
1619 /// example, the following are all no-op casts:
1620 /// # bitcast uint %X, int
1621 /// # bitcast uint* %x, sbyte*
1622 /// # bitcast vector< 2 x int > %x, vector< 4 x short>
1623 /// # ptrtoint uint* %x, uint ; on 32-bit plaforms only
1624 /// @brief Determine if a cast is a no-op.
1625 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1626 switch (getOpcode()) {
1628 assert(!"Invalid CastOp");
1629 case Instruction::Trunc:
1630 case Instruction::ZExt:
1631 case Instruction::SExt:
1632 case Instruction::FPTrunc:
1633 case Instruction::FPExt:
1634 case Instruction::UIToFP:
1635 case Instruction::SIToFP:
1636 case Instruction::FPToUI:
1637 case Instruction::FPToSI:
1638 return false; // These always modify bits
1639 case Instruction::BitCast:
1640 return true; // BitCast never modifies bits.
1641 case Instruction::PtrToInt:
1642 return IntPtrTy->getPrimitiveSizeInBits() ==
1643 getType()->getPrimitiveSizeInBits();
1644 case Instruction::IntToPtr:
1645 return IntPtrTy->getPrimitiveSizeInBits() ==
1646 getOperand(0)->getType()->getPrimitiveSizeInBits();
1650 /// This function determines if a pair of casts can be eliminated and what
1651 /// opcode should be used in the elimination. This assumes that there are two
1652 /// instructions like this:
1653 /// * %F = firstOpcode SrcTy %x to MidTy
1654 /// * %S = secondOpcode MidTy %F to DstTy
1655 /// The function returns a resultOpcode so these two casts can be replaced with:
1656 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1657 /// If no such cast is permited, the function returns 0.
1658 unsigned CastInst::isEliminableCastPair(
1659 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1660 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1662 // Define the 144 possibilities for these two cast instructions. The values
1663 // in this matrix determine what to do in a given situation and select the
1664 // case in the switch below. The rows correspond to firstOp, the columns
1665 // correspond to secondOp. In looking at the table below, keep in mind
1666 // the following cast properties:
1668 // Size Compare Source Destination
1669 // Operator Src ? Size Type Sign Type Sign
1670 // -------- ------------ ------------------- ---------------------
1671 // TRUNC > Integer Any Integral Any
1672 // ZEXT < Integral Unsigned Integer Any
1673 // SEXT < Integral Signed Integer Any
1674 // FPTOUI n/a FloatPt n/a Integral Unsigned
1675 // FPTOSI n/a FloatPt n/a Integral Signed
1676 // UITOFP n/a Integral Unsigned FloatPt n/a
1677 // SITOFP n/a Integral Signed FloatPt n/a
1678 // FPTRUNC > FloatPt n/a FloatPt n/a
1679 // FPEXT < FloatPt n/a FloatPt n/a
1680 // PTRTOINT n/a Pointer n/a Integral Unsigned
1681 // INTTOPTR n/a Integral Unsigned Pointer n/a
1682 // BITCONVERT = FirstClass n/a FirstClass n/a
1684 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1685 // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
1686 // into "fptoui double to ulong", but this loses information about the range
1687 // of the produced value (we no longer know the top-part is all zeros).
1688 // Further this conversion is often much more expensive for typical hardware,
1689 // and causes issues when building libgcc. We disallow fptosi+sext for the
1691 const unsigned numCastOps =
1692 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1693 static const uint8_t CastResults[numCastOps][numCastOps] = {
1694 // T F F U S F F P I B -+
1695 // R Z S P P I I T P 2 N T |
1696 // U E E 2 2 2 2 R E I T C +- secondOp
1697 // N X X U S F F N X N 2 V |
1698 // C T T I I P P C T T P T -+
1699 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1700 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1701 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1702 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1703 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1704 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1705 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1706 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1707 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1708 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1709 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1710 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1713 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1714 [secondOp-Instruction::CastOpsBegin];
1717 // categorically disallowed
1720 // allowed, use first cast's opcode
1723 // allowed, use second cast's opcode
1726 // no-op cast in second op implies firstOp as long as the DestTy
1728 if (DstTy->isInteger())
1732 // no-op cast in second op implies firstOp as long as the DestTy
1733 // is floating point
1734 if (DstTy->isFloatingPoint())
1738 // no-op cast in first op implies secondOp as long as the SrcTy
1740 if (SrcTy->isInteger())
1744 // no-op cast in first op implies secondOp as long as the SrcTy
1745 // is a floating point
1746 if (SrcTy->isFloatingPoint())
1750 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1751 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1752 unsigned MidSize = MidTy->getPrimitiveSizeInBits();
1753 if (MidSize >= PtrSize)
1754 return Instruction::BitCast;
1758 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1759 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1760 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1761 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1762 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1763 if (SrcSize == DstSize)
1764 return Instruction::BitCast;
1765 else if (SrcSize < DstSize)
1769 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1770 return Instruction::ZExt;
1772 // fpext followed by ftrunc is allowed if the bit size returned to is
1773 // the same as the original, in which case its just a bitcast
1775 return Instruction::BitCast;
1776 return 0; // If the types are not the same we can't eliminate it.
1778 // bitcast followed by ptrtoint is allowed as long as the bitcast
1779 // is a pointer to pointer cast.
1780 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1784 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1785 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1789 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1790 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1791 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1792 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1793 if (SrcSize <= PtrSize && SrcSize == DstSize)
1794 return Instruction::BitCast;
1798 // cast combination can't happen (error in input). This is for all cases
1799 // where the MidTy is not the same for the two cast instructions.
1800 assert(!"Invalid Cast Combination");
1803 assert(!"Error in CastResults table!!!");
1809 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1810 const std::string &Name, Instruction *InsertBefore) {
1811 // Construct and return the appropriate CastInst subclass
1813 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1814 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1815 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1816 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1817 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1818 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1819 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1820 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1821 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1822 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1823 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1824 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1826 assert(!"Invalid opcode provided");
1831 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1832 const std::string &Name, BasicBlock *InsertAtEnd) {
1833 // Construct and return the appropriate CastInst subclass
1835 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1836 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1837 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1838 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1839 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1840 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1841 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1842 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1843 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1844 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1845 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1846 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1848 assert(!"Invalid opcode provided");
1853 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1854 const std::string &Name,
1855 Instruction *InsertBefore) {
1856 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1857 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1858 return create(Instruction::ZExt, S, Ty, Name, InsertBefore);
1861 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1862 const std::string &Name,
1863 BasicBlock *InsertAtEnd) {
1864 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1865 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1866 return create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
1869 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1870 const std::string &Name,
1871 Instruction *InsertBefore) {
1872 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1873 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1874 return create(Instruction::SExt, S, Ty, Name, InsertBefore);
1877 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1878 const std::string &Name,
1879 BasicBlock *InsertAtEnd) {
1880 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1881 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1882 return create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
1885 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1886 const std::string &Name,
1887 Instruction *InsertBefore) {
1888 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1889 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1890 return create(Instruction::Trunc, S, Ty, Name, InsertBefore);
1893 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1894 const std::string &Name,
1895 BasicBlock *InsertAtEnd) {
1896 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1897 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1898 return create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
1901 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1902 const std::string &Name,
1903 BasicBlock *InsertAtEnd) {
1904 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1905 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1908 if (Ty->isInteger())
1909 return create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
1910 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1913 /// @brief Create a BitCast or a PtrToInt cast instruction
1914 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1915 const std::string &Name,
1916 Instruction *InsertBefore) {
1917 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1918 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1921 if (Ty->isInteger())
1922 return create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
1923 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1926 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1927 bool isSigned, const std::string &Name,
1928 Instruction *InsertBefore) {
1929 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1930 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1931 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1932 Instruction::CastOps opcode =
1933 (SrcBits == DstBits ? Instruction::BitCast :
1934 (SrcBits > DstBits ? Instruction::Trunc :
1935 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1936 return create(opcode, C, Ty, Name, InsertBefore);
1939 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1940 bool isSigned, const std::string &Name,
1941 BasicBlock *InsertAtEnd) {
1942 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1943 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1944 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1945 Instruction::CastOps opcode =
1946 (SrcBits == DstBits ? Instruction::BitCast :
1947 (SrcBits > DstBits ? Instruction::Trunc :
1948 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1949 return create(opcode, C, Ty, Name, InsertAtEnd);
1952 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1953 const std::string &Name,
1954 Instruction *InsertBefore) {
1955 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1957 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1958 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1959 Instruction::CastOps opcode =
1960 (SrcBits == DstBits ? Instruction::BitCast :
1961 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1962 return create(opcode, C, Ty, Name, InsertBefore);
1965 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1966 const std::string &Name,
1967 BasicBlock *InsertAtEnd) {
1968 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1970 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1971 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1972 Instruction::CastOps opcode =
1973 (SrcBits == DstBits ? Instruction::BitCast :
1974 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1975 return create(opcode, C, Ty, Name, InsertAtEnd);
1978 // Check whether it is valid to call getCastOpcode for these types.
1979 // This routine must be kept in sync with getCastOpcode.
1980 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
1981 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
1984 if (SrcTy == DestTy)
1987 // Get the bit sizes, we'll need these
1988 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1989 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1991 // Run through the possibilities ...
1992 if (DestTy->isInteger()) { // Casting to integral
1993 if (SrcTy->isInteger()) { // Casting from integral
1995 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1997 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1998 // Casting from vector
1999 return DestBits == PTy->getBitWidth();
2000 } else { // Casting from something else
2001 return isa<PointerType>(SrcTy);
2003 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2004 if (SrcTy->isInteger()) { // Casting from integral
2006 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2008 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2009 // Casting from vector
2010 return DestBits == PTy->getBitWidth();
2011 } else { // Casting from something else
2014 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2015 // Casting to vector
2016 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2017 // Casting from vector
2018 return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
2019 } else { // Casting from something else
2020 return DestPTy->getBitWidth() == SrcBits;
2022 } else if (isa<PointerType>(DestTy)) { // Casting to pointer
2023 if (isa<PointerType>(SrcTy)) { // Casting from pointer
2025 } else if (SrcTy->isInteger()) { // Casting from integral
2027 } else { // Casting from something else
2030 } else { // Casting to something else
2035 // Provide a way to get a "cast" where the cast opcode is inferred from the
2036 // types and size of the operand. This, basically, is a parallel of the
2037 // logic in the castIsValid function below. This axiom should hold:
2038 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2039 // should not assert in castIsValid. In other words, this produces a "correct"
2040 // casting opcode for the arguments passed to it.
2041 // This routine must be kept in sync with isCastable.
2042 Instruction::CastOps
2043 CastInst::getCastOpcode(
2044 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
2045 // Get the bit sizes, we'll need these
2046 const Type *SrcTy = Src->getType();
2047 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2048 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2050 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2051 "Only first class types are castable!");
2053 // Run through the possibilities ...
2054 if (DestTy->isInteger()) { // Casting to integral
2055 if (SrcTy->isInteger()) { // Casting from integral
2056 if (DestBits < SrcBits)
2057 return Trunc; // int -> smaller int
2058 else if (DestBits > SrcBits) { // its an extension
2060 return SExt; // signed -> SEXT
2062 return ZExt; // unsigned -> ZEXT
2064 return BitCast; // Same size, No-op cast
2066 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2068 return FPToSI; // FP -> sint
2070 return FPToUI; // FP -> uint
2071 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2072 assert(DestBits == PTy->getBitWidth() &&
2073 "Casting vector to integer of different width");
2074 return BitCast; // Same size, no-op cast
2076 assert(isa<PointerType>(SrcTy) &&
2077 "Casting from a value that is not first-class type");
2078 return PtrToInt; // ptr -> int
2080 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2081 if (SrcTy->isInteger()) { // Casting from integral
2083 return SIToFP; // sint -> FP
2085 return UIToFP; // uint -> FP
2086 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2087 if (DestBits < SrcBits) {
2088 return FPTrunc; // FP -> smaller FP
2089 } else if (DestBits > SrcBits) {
2090 return FPExt; // FP -> larger FP
2092 return BitCast; // same size, no-op cast
2094 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2095 assert(DestBits == PTy->getBitWidth() &&
2096 "Casting vector to floating point of different width");
2097 return BitCast; // same size, no-op cast
2099 assert(0 && "Casting pointer or non-first class to float");
2101 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2102 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2103 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2104 "Casting vector to vector of different widths");
2105 return BitCast; // vector -> vector
2106 } else if (DestPTy->getBitWidth() == SrcBits) {
2107 return BitCast; // float/int -> vector
2109 assert(!"Illegal cast to vector (wrong type or size)");
2111 } else if (isa<PointerType>(DestTy)) {
2112 if (isa<PointerType>(SrcTy)) {
2113 return BitCast; // ptr -> ptr
2114 } else if (SrcTy->isInteger()) {
2115 return IntToPtr; // int -> ptr
2117 assert(!"Casting pointer to other than pointer or int");
2120 assert(!"Casting to type that is not first-class");
2123 // If we fall through to here we probably hit an assertion cast above
2124 // and assertions are not turned on. Anything we return is an error, so
2125 // BitCast is as good a choice as any.
2129 //===----------------------------------------------------------------------===//
2130 // CastInst SubClass Constructors
2131 //===----------------------------------------------------------------------===//
2133 /// Check that the construction parameters for a CastInst are correct. This
2134 /// could be broken out into the separate constructors but it is useful to have
2135 /// it in one place and to eliminate the redundant code for getting the sizes
2136 /// of the types involved.
2138 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2140 // Check for type sanity on the arguments
2141 const Type *SrcTy = S->getType();
2142 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
2145 // Get the size of the types in bits, we'll need this later
2146 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2147 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2149 // Switch on the opcode provided
2151 default: return false; // This is an input error
2152 case Instruction::Trunc:
2153 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize > DstBitSize;
2154 case Instruction::ZExt:
2155 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2156 case Instruction::SExt:
2157 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2158 case Instruction::FPTrunc:
2159 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2160 SrcBitSize > DstBitSize;
2161 case Instruction::FPExt:
2162 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2163 SrcBitSize < DstBitSize;
2164 case Instruction::UIToFP:
2165 case Instruction::SIToFP:
2166 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2167 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2168 return SVTy->getElementType()->isInteger() &&
2169 DVTy->getElementType()->isFloatingPoint() &&
2170 SVTy->getNumElements() == DVTy->getNumElements();
2173 return SrcTy->isInteger() && DstTy->isFloatingPoint();
2174 case Instruction::FPToUI:
2175 case Instruction::FPToSI:
2176 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2177 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2178 return SVTy->getElementType()->isFloatingPoint() &&
2179 DVTy->getElementType()->isInteger() &&
2180 SVTy->getNumElements() == DVTy->getNumElements();
2183 return SrcTy->isFloatingPoint() && DstTy->isInteger();
2184 case Instruction::PtrToInt:
2185 return isa<PointerType>(SrcTy) && DstTy->isInteger();
2186 case Instruction::IntToPtr:
2187 return SrcTy->isInteger() && isa<PointerType>(DstTy);
2188 case Instruction::BitCast:
2189 // BitCast implies a no-op cast of type only. No bits change.
2190 // However, you can't cast pointers to anything but pointers.
2191 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2194 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2195 // these cases, the cast is okay if the source and destination bit widths
2197 return SrcBitSize == DstBitSize;
2201 TruncInst::TruncInst(
2202 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2203 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2204 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2207 TruncInst::TruncInst(
2208 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2209 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2210 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2214 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2215 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2216 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2220 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2221 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2222 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2225 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2226 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2227 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2231 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2232 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2233 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2236 FPTruncInst::FPTruncInst(
2237 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2238 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2239 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2242 FPTruncInst::FPTruncInst(
2243 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2244 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2245 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2248 FPExtInst::FPExtInst(
2249 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2250 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2251 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2254 FPExtInst::FPExtInst(
2255 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2256 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2257 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2260 UIToFPInst::UIToFPInst(
2261 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2262 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2263 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2266 UIToFPInst::UIToFPInst(
2267 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2268 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2269 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2272 SIToFPInst::SIToFPInst(
2273 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2274 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2275 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2278 SIToFPInst::SIToFPInst(
2279 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2280 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2281 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2284 FPToUIInst::FPToUIInst(
2285 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2286 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2287 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2290 FPToUIInst::FPToUIInst(
2291 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2292 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2293 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2296 FPToSIInst::FPToSIInst(
2297 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2298 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2299 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2302 FPToSIInst::FPToSIInst(
2303 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2304 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2305 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2308 PtrToIntInst::PtrToIntInst(
2309 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2310 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2311 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2314 PtrToIntInst::PtrToIntInst(
2315 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2316 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2317 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2320 IntToPtrInst::IntToPtrInst(
2321 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2322 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2323 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2326 IntToPtrInst::IntToPtrInst(
2327 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2328 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2329 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2332 BitCastInst::BitCastInst(
2333 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2334 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2335 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2338 BitCastInst::BitCastInst(
2339 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2340 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2341 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2344 //===----------------------------------------------------------------------===//
2346 //===----------------------------------------------------------------------===//
2348 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2349 const std::string &Name, Instruction *InsertBefore)
2350 : Instruction(Type::Int1Ty, op, Ops, 2, InsertBefore) {
2351 Ops[0].init(LHS, this);
2352 Ops[1].init(RHS, this);
2353 SubclassData = predicate;
2355 if (op == Instruction::ICmp) {
2356 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2357 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2358 "Invalid ICmp predicate value");
2359 const Type* Op0Ty = getOperand(0)->getType();
2360 const Type* Op1Ty = getOperand(1)->getType();
2361 assert(Op0Ty == Op1Ty &&
2362 "Both operands to ICmp instruction are not of the same type!");
2363 // Check that the operands are the right type
2364 assert((Op0Ty->isInteger() || isa<PointerType>(Op0Ty)) &&
2365 "Invalid operand types for ICmp instruction");
2368 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2369 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2370 "Invalid FCmp predicate value");
2371 const Type* Op0Ty = getOperand(0)->getType();
2372 const Type* Op1Ty = getOperand(1)->getType();
2373 assert(Op0Ty == Op1Ty &&
2374 "Both operands to FCmp instruction are not of the same type!");
2375 // Check that the operands are the right type
2376 assert(Op0Ty->isFloatingPoint() &&
2377 "Invalid operand types for FCmp instruction");
2380 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2381 const std::string &Name, BasicBlock *InsertAtEnd)
2382 : Instruction(Type::Int1Ty, op, Ops, 2, InsertAtEnd) {
2383 Ops[0].init(LHS, this);
2384 Ops[1].init(RHS, this);
2385 SubclassData = predicate;
2387 if (op == Instruction::ICmp) {
2388 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2389 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2390 "Invalid ICmp predicate value");
2392 const Type* Op0Ty = getOperand(0)->getType();
2393 const Type* Op1Ty = getOperand(1)->getType();
2394 assert(Op0Ty == Op1Ty &&
2395 "Both operands to ICmp instruction are not of the same type!");
2396 // Check that the operands are the right type
2397 assert((Op0Ty->isInteger() || isa<PointerType>(Op0Ty)) &&
2398 "Invalid operand types for ICmp instruction");
2401 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2402 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2403 "Invalid FCmp predicate value");
2404 const Type* Op0Ty = getOperand(0)->getType();
2405 const Type* Op1Ty = getOperand(1)->getType();
2406 assert(Op0Ty == Op1Ty &&
2407 "Both operands to FCmp instruction are not of the same type!");
2408 // Check that the operands are the right type
2409 assert(Op0Ty->isFloatingPoint() &&
2410 "Invalid operand types for FCmp instruction");
2414 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2415 const std::string &Name, Instruction *InsertBefore) {
2416 if (Op == Instruction::ICmp) {
2417 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2420 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2425 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2426 const std::string &Name, BasicBlock *InsertAtEnd) {
2427 if (Op == Instruction::ICmp) {
2428 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2431 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2435 void CmpInst::swapOperands() {
2436 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2439 cast<FCmpInst>(this)->swapOperands();
2442 bool CmpInst::isCommutative() {
2443 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2444 return IC->isCommutative();
2445 return cast<FCmpInst>(this)->isCommutative();
2448 bool CmpInst::isEquality() {
2449 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2450 return IC->isEquality();
2451 return cast<FCmpInst>(this)->isEquality();
2455 ICmpInst::Predicate ICmpInst::getInversePredicate(Predicate pred) {
2458 assert(!"Unknown icmp predicate!");
2459 case ICMP_EQ: return ICMP_NE;
2460 case ICMP_NE: return ICMP_EQ;
2461 case ICMP_UGT: return ICMP_ULE;
2462 case ICMP_ULT: return ICMP_UGE;
2463 case ICMP_UGE: return ICMP_ULT;
2464 case ICMP_ULE: return ICMP_UGT;
2465 case ICMP_SGT: return ICMP_SLE;
2466 case ICMP_SLT: return ICMP_SGE;
2467 case ICMP_SGE: return ICMP_SLT;
2468 case ICMP_SLE: return ICMP_SGT;
2472 ICmpInst::Predicate ICmpInst::getSwappedPredicate(Predicate pred) {
2474 default: assert(! "Unknown icmp predicate!");
2475 case ICMP_EQ: case ICMP_NE:
2477 case ICMP_SGT: return ICMP_SLT;
2478 case ICMP_SLT: return ICMP_SGT;
2479 case ICMP_SGE: return ICMP_SLE;
2480 case ICMP_SLE: return ICMP_SGE;
2481 case ICMP_UGT: return ICMP_ULT;
2482 case ICMP_ULT: return ICMP_UGT;
2483 case ICMP_UGE: return ICMP_ULE;
2484 case ICMP_ULE: return ICMP_UGE;
2488 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2490 default: assert(! "Unknown icmp predicate!");
2491 case ICMP_EQ: case ICMP_NE:
2492 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2494 case ICMP_UGT: return ICMP_SGT;
2495 case ICMP_ULT: return ICMP_SLT;
2496 case ICMP_UGE: return ICMP_SGE;
2497 case ICMP_ULE: return ICMP_SLE;
2501 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2503 default: assert(! "Unknown icmp predicate!");
2504 case ICMP_EQ: case ICMP_NE:
2505 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2507 case ICMP_SGT: return ICMP_UGT;
2508 case ICMP_SLT: return ICMP_ULT;
2509 case ICMP_SGE: return ICMP_UGE;
2510 case ICMP_SLE: return ICMP_ULE;
2514 bool ICmpInst::isSignedPredicate(Predicate pred) {
2516 default: assert(! "Unknown icmp predicate!");
2517 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2519 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2520 case ICMP_UGE: case ICMP_ULE:
2525 /// Initialize a set of values that all satisfy the condition with C.
2528 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2531 uint32_t BitWidth = C.getBitWidth();
2533 default: assert(0 && "Invalid ICmp opcode to ConstantRange ctor!");
2534 case ICmpInst::ICMP_EQ: Upper++; break;
2535 case ICmpInst::ICMP_NE: Lower++; break;
2536 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2537 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2538 case ICmpInst::ICMP_UGT:
2539 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2541 case ICmpInst::ICMP_SGT:
2542 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2544 case ICmpInst::ICMP_ULE:
2545 Lower = APInt::getMinValue(BitWidth); Upper++;
2547 case ICmpInst::ICMP_SLE:
2548 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2550 case ICmpInst::ICMP_UGE:
2551 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2553 case ICmpInst::ICMP_SGE:
2554 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2557 return ConstantRange(Lower, Upper);
2560 FCmpInst::Predicate FCmpInst::getInversePredicate(Predicate pred) {
2563 assert(!"Unknown icmp predicate!");
2564 case FCMP_OEQ: return FCMP_UNE;
2565 case FCMP_ONE: return FCMP_UEQ;
2566 case FCMP_OGT: return FCMP_ULE;
2567 case FCMP_OLT: return FCMP_UGE;
2568 case FCMP_OGE: return FCMP_ULT;
2569 case FCMP_OLE: return FCMP_UGT;
2570 case FCMP_UEQ: return FCMP_ONE;
2571 case FCMP_UNE: return FCMP_OEQ;
2572 case FCMP_UGT: return FCMP_OLE;
2573 case FCMP_ULT: return FCMP_OGE;
2574 case FCMP_UGE: return FCMP_OLT;
2575 case FCMP_ULE: return FCMP_OGT;
2576 case FCMP_ORD: return FCMP_UNO;
2577 case FCMP_UNO: return FCMP_ORD;
2578 case FCMP_TRUE: return FCMP_FALSE;
2579 case FCMP_FALSE: return FCMP_TRUE;
2583 FCmpInst::Predicate FCmpInst::getSwappedPredicate(Predicate pred) {
2585 default: assert(!"Unknown fcmp predicate!");
2586 case FCMP_FALSE: case FCMP_TRUE:
2587 case FCMP_OEQ: case FCMP_ONE:
2588 case FCMP_UEQ: case FCMP_UNE:
2589 case FCMP_ORD: case FCMP_UNO:
2591 case FCMP_OGT: return FCMP_OLT;
2592 case FCMP_OLT: return FCMP_OGT;
2593 case FCMP_OGE: return FCMP_OLE;
2594 case FCMP_OLE: return FCMP_OGE;
2595 case FCMP_UGT: return FCMP_ULT;
2596 case FCMP_ULT: return FCMP_UGT;
2597 case FCMP_UGE: return FCMP_ULE;
2598 case FCMP_ULE: return FCMP_UGE;
2602 bool CmpInst::isUnsigned(unsigned short predicate) {
2603 switch (predicate) {
2604 default: return false;
2605 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2606 case ICmpInst::ICMP_UGE: return true;
2610 bool CmpInst::isSigned(unsigned short predicate){
2611 switch (predicate) {
2612 default: return false;
2613 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2614 case ICmpInst::ICMP_SGE: return true;
2618 bool CmpInst::isOrdered(unsigned short predicate) {
2619 switch (predicate) {
2620 default: return false;
2621 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2622 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2623 case FCmpInst::FCMP_ORD: return true;
2627 bool CmpInst::isUnordered(unsigned short predicate) {
2628 switch (predicate) {
2629 default: return false;
2630 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2631 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2632 case FCmpInst::FCMP_UNO: return true;
2636 //===----------------------------------------------------------------------===//
2637 // SwitchInst Implementation
2638 //===----------------------------------------------------------------------===//
2640 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2641 assert(Value && Default);
2642 ReservedSpace = 2+NumCases*2;
2644 OperandList = new Use[ReservedSpace];
2646 OperandList[0].init(Value, this);
2647 OperandList[1].init(Default, this);
2650 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2651 /// switch on and a default destination. The number of additional cases can
2652 /// be specified here to make memory allocation more efficient. This
2653 /// constructor can also autoinsert before another instruction.
2654 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2655 Instruction *InsertBefore)
2656 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) {
2657 init(Value, Default, NumCases);
2660 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2661 /// switch on and a default destination. The number of additional cases can
2662 /// be specified here to make memory allocation more efficient. This
2663 /// constructor also autoinserts at the end of the specified BasicBlock.
2664 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2665 BasicBlock *InsertAtEnd)
2666 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) {
2667 init(Value, Default, NumCases);
2670 SwitchInst::SwitchInst(const SwitchInst &SI)
2671 : TerminatorInst(Type::VoidTy, Instruction::Switch,
2672 new Use[SI.getNumOperands()], SI.getNumOperands()) {
2673 Use *OL = OperandList, *InOL = SI.OperandList;
2674 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2675 OL[i].init(InOL[i], this);
2676 OL[i+1].init(InOL[i+1], this);
2680 SwitchInst::~SwitchInst() {
2681 delete [] OperandList;
2685 /// addCase - Add an entry to the switch instruction...
2687 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2688 unsigned OpNo = NumOperands;
2689 if (OpNo+2 > ReservedSpace)
2690 resizeOperands(0); // Get more space!
2691 // Initialize some new operands.
2692 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2693 NumOperands = OpNo+2;
2694 OperandList[OpNo].init(OnVal, this);
2695 OperandList[OpNo+1].init(Dest, this);
2698 /// removeCase - This method removes the specified successor from the switch
2699 /// instruction. Note that this cannot be used to remove the default
2700 /// destination (successor #0).
2702 void SwitchInst::removeCase(unsigned idx) {
2703 assert(idx != 0 && "Cannot remove the default case!");
2704 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2706 unsigned NumOps = getNumOperands();
2707 Use *OL = OperandList;
2709 // Move everything after this operand down.
2711 // FIXME: we could just swap with the end of the list, then erase. However,
2712 // client might not expect this to happen. The code as it is thrashes the
2713 // use/def lists, which is kinda lame.
2714 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2716 OL[i-2+1] = OL[i+1];
2719 // Nuke the last value.
2720 OL[NumOps-2].set(0);
2721 OL[NumOps-2+1].set(0);
2722 NumOperands = NumOps-2;
2725 /// resizeOperands - resize operands - This adjusts the length of the operands
2726 /// list according to the following behavior:
2727 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2728 /// of operation. This grows the number of ops by 1.5 times.
2729 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2730 /// 3. If NumOps == NumOperands, trim the reserved space.
2732 void SwitchInst::resizeOperands(unsigned NumOps) {
2734 NumOps = getNumOperands()/2*6;
2735 } else if (NumOps*2 > NumOperands) {
2736 // No resize needed.
2737 if (ReservedSpace >= NumOps) return;
2738 } else if (NumOps == NumOperands) {
2739 if (ReservedSpace == NumOps) return;
2744 ReservedSpace = NumOps;
2745 Use *NewOps = new Use[NumOps];
2746 Use *OldOps = OperandList;
2747 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2748 NewOps[i].init(OldOps[i], this);
2752 OperandList = NewOps;
2756 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2757 return getSuccessor(idx);
2759 unsigned SwitchInst::getNumSuccessorsV() const {
2760 return getNumSuccessors();
2762 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2763 setSuccessor(idx, B);
2766 //===----------------------------------------------------------------------===//
2767 // GetResultInst Implementation
2768 //===----------------------------------------------------------------------===//
2770 GetResultInst::GetResultInst(Value *Aggregate, unsigned Index,
2771 const std::string &Name,
2772 Instruction *InsertBef)
2773 : Instruction(cast<StructType>(Aggregate->getType())->getElementType(Index),
2774 GetResult, &Aggr, 1, InsertBef) {
2775 assert(isValidOperands(Aggregate, Index) && "Invalid GetResultInst operands!");
2776 Aggr.init(Aggregate, this);
2781 bool GetResultInst::isValidOperands(const Value *Aggregate, unsigned Index) {
2785 if (const StructType *STy = dyn_cast<StructType>(Aggregate->getType())) {
2786 unsigned NumElements = STy->getNumElements();
2787 if (Index >= NumElements)
2790 // getresult aggregate value's element types are restricted to
2791 // avoid nested aggregates.
2792 for (unsigned i = 0; i < NumElements; ++i)
2793 if (!STy->getElementType(i)->isFirstClassType())
2796 // Otherwise, Aggregate is valid.
2802 // Define these methods here so vtables don't get emitted into every translation
2803 // unit that uses these classes.
2805 GetElementPtrInst *GetElementPtrInst::clone() const {
2806 return new GetElementPtrInst(*this);
2809 BinaryOperator *BinaryOperator::clone() const {
2810 return create(getOpcode(), Ops[0], Ops[1]);
2813 FCmpInst* FCmpInst::clone() const {
2814 return new FCmpInst(getPredicate(), Ops[0], Ops[1]);
2816 ICmpInst* ICmpInst::clone() const {
2817 return new ICmpInst(getPredicate(), Ops[0], Ops[1]);
2820 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
2821 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
2822 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
2823 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
2824 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
2825 CastInst *TruncInst::clone() const { return new TruncInst(*this); }
2826 CastInst *ZExtInst::clone() const { return new ZExtInst(*this); }
2827 CastInst *SExtInst::clone() const { return new SExtInst(*this); }
2828 CastInst *FPTruncInst::clone() const { return new FPTruncInst(*this); }
2829 CastInst *FPExtInst::clone() const { return new FPExtInst(*this); }
2830 CastInst *UIToFPInst::clone() const { return new UIToFPInst(*this); }
2831 CastInst *SIToFPInst::clone() const { return new SIToFPInst(*this); }
2832 CastInst *FPToUIInst::clone() const { return new FPToUIInst(*this); }
2833 CastInst *FPToSIInst::clone() const { return new FPToSIInst(*this); }
2834 CastInst *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
2835 CastInst *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
2836 CastInst *BitCastInst::clone() const { return new BitCastInst(*this); }
2837 CallInst *CallInst::clone() const { return new CallInst(*this); }
2838 SelectInst *SelectInst::clone() const { return new SelectInst(*this); }
2839 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
2841 ExtractElementInst *ExtractElementInst::clone() const {
2842 return new ExtractElementInst(*this);
2844 InsertElementInst *InsertElementInst::clone() const {
2845 return new InsertElementInst(*this);
2847 ShuffleVectorInst *ShuffleVectorInst::clone() const {
2848 return new ShuffleVectorInst(*this);
2850 PHINode *PHINode::clone() const { return new PHINode(*this); }
2851 ReturnInst *ReturnInst::clone() const { return new ReturnInst(*this); }
2852 BranchInst *BranchInst::clone() const { return new BranchInst(*this); }
2853 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
2854 InvokeInst *InvokeInst::clone() const { return new InvokeInst(*this); }
2855 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
2856 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}
2857 GetResultInst *GetResultInst::clone() const { return new GetResultInst(*this); }