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/ParameterAttributes.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 bool CallSite::doesNotAccessMemory() const {
65 if (CallInst *CI = dyn_cast<CallInst>(I))
66 return CI->doesNotAccessMemory();
68 return cast<InvokeInst>(I)->doesNotAccessMemory();
70 bool CallSite::onlyReadsMemory() const {
71 if (CallInst *CI = dyn_cast<CallInst>(I))
72 return CI->onlyReadsMemory();
74 return cast<InvokeInst>(I)->onlyReadsMemory();
76 bool CallSite::doesNotThrow() const {
77 if (CallInst *CI = dyn_cast<CallInst>(I))
78 return CI->doesNotThrow();
80 return cast<InvokeInst>(I)->doesNotThrow();
82 void CallSite::setDoesNotThrow(bool doesNotThrow) {
83 if (CallInst *CI = dyn_cast<CallInst>(I))
84 CI->setDoesNotThrow(doesNotThrow);
86 cast<InvokeInst>(I)->setDoesNotThrow(doesNotThrow);
89 //===----------------------------------------------------------------------===//
90 // TerminatorInst Class
91 //===----------------------------------------------------------------------===//
93 // Out of line virtual method, so the vtable, etc has a home.
94 TerminatorInst::~TerminatorInst() {
97 // Out of line virtual method, so the vtable, etc has a home.
98 UnaryInstruction::~UnaryInstruction() {
102 //===----------------------------------------------------------------------===//
104 //===----------------------------------------------------------------------===//
106 PHINode::PHINode(const PHINode &PN)
107 : Instruction(PN.getType(), Instruction::PHI,
108 new Use[PN.getNumOperands()], PN.getNumOperands()),
109 ReservedSpace(PN.getNumOperands()) {
110 Use *OL = OperandList;
111 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
112 OL[i].init(PN.getOperand(i), this);
113 OL[i+1].init(PN.getOperand(i+1), this);
117 PHINode::~PHINode() {
118 delete [] OperandList;
121 // removeIncomingValue - Remove an incoming value. This is useful if a
122 // predecessor basic block is deleted.
123 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
124 unsigned NumOps = getNumOperands();
125 Use *OL = OperandList;
126 assert(Idx*2 < NumOps && "BB not in PHI node!");
127 Value *Removed = OL[Idx*2];
129 // Move everything after this operand down.
131 // FIXME: we could just swap with the end of the list, then erase. However,
132 // client might not expect this to happen. The code as it is thrashes the
133 // use/def lists, which is kinda lame.
134 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
139 // Nuke the last value.
141 OL[NumOps-2+1].set(0);
142 NumOperands = NumOps-2;
144 // If the PHI node is dead, because it has zero entries, nuke it now.
145 if (NumOps == 2 && DeletePHIIfEmpty) {
146 // If anyone is using this PHI, make them use a dummy value instead...
147 replaceAllUsesWith(UndefValue::get(getType()));
153 /// resizeOperands - resize operands - This adjusts the length of the operands
154 /// list according to the following behavior:
155 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
156 /// of operation. This grows the number of ops by 1.5 times.
157 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
158 /// 3. If NumOps == NumOperands, trim the reserved space.
160 void PHINode::resizeOperands(unsigned NumOps) {
162 NumOps = (getNumOperands())*3/2;
163 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
164 } else if (NumOps*2 > NumOperands) {
166 if (ReservedSpace >= NumOps) return;
167 } else if (NumOps == NumOperands) {
168 if (ReservedSpace == NumOps) return;
173 ReservedSpace = NumOps;
174 Use *NewOps = new Use[NumOps];
175 Use *OldOps = OperandList;
176 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
177 NewOps[i].init(OldOps[i], this);
181 OperandList = NewOps;
184 /// hasConstantValue - If the specified PHI node always merges together the same
185 /// value, return the value, otherwise return null.
187 Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) const {
188 // If the PHI node only has one incoming value, eliminate the PHI node...
189 if (getNumIncomingValues() == 1)
190 if (getIncomingValue(0) != this) // not X = phi X
191 return getIncomingValue(0);
193 return UndefValue::get(getType()); // Self cycle is dead.
195 // Otherwise if all of the incoming values are the same for the PHI, replace
196 // the PHI node with the incoming value.
199 bool HasUndefInput = false;
200 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
201 if (isa<UndefValue>(getIncomingValue(i)))
202 HasUndefInput = true;
203 else if (getIncomingValue(i) != this) // Not the PHI node itself...
204 if (InVal && getIncomingValue(i) != InVal)
205 return 0; // Not the same, bail out.
207 InVal = getIncomingValue(i);
209 // The only case that could cause InVal to be null is if we have a PHI node
210 // that only has entries for itself. In this case, there is no entry into the
211 // loop, so kill the PHI.
213 if (InVal == 0) InVal = UndefValue::get(getType());
215 // If we have a PHI node like phi(X, undef, X), where X is defined by some
216 // instruction, we cannot always return X as the result of the PHI node. Only
217 // do this if X is not an instruction (thus it must dominate the PHI block),
218 // or if the client is prepared to deal with this possibility.
219 if (HasUndefInput && !AllowNonDominatingInstruction)
220 if (Instruction *IV = dyn_cast<Instruction>(InVal))
221 // If it's in the entry block, it dominates everything.
222 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
224 return 0; // Cannot guarantee that InVal dominates this PHINode.
226 // All of the incoming values are the same, return the value now.
231 //===----------------------------------------------------------------------===//
232 // CallInst Implementation
233 //===----------------------------------------------------------------------===//
235 CallInst::~CallInst() {
236 delete [] OperandList;
238 ParamAttrs->dropRef();
241 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
243 NumOperands = NumParams+1;
244 Use *OL = OperandList = new Use[NumParams+1];
245 OL[0].init(Func, this);
247 const FunctionType *FTy =
248 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
249 FTy = FTy; // silence warning.
251 assert((NumParams == FTy->getNumParams() ||
252 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
253 "Calling a function with bad signature!");
254 for (unsigned i = 0; i != NumParams; ++i) {
255 assert((i >= FTy->getNumParams() ||
256 FTy->getParamType(i) == Params[i]->getType()) &&
257 "Calling a function with a bad signature!");
258 OL[i+1].init(Params[i], this);
262 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
265 Use *OL = OperandList = new Use[3];
266 OL[0].init(Func, this);
267 OL[1].init(Actual1, this);
268 OL[2].init(Actual2, this);
270 const FunctionType *FTy =
271 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
272 FTy = FTy; // silence warning.
274 assert((FTy->getNumParams() == 2 ||
275 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
276 "Calling a function with bad signature");
277 assert((0 >= FTy->getNumParams() ||
278 FTy->getParamType(0) == Actual1->getType()) &&
279 "Calling a function with a bad signature!");
280 assert((1 >= FTy->getNumParams() ||
281 FTy->getParamType(1) == Actual2->getType()) &&
282 "Calling a function with a bad signature!");
285 void CallInst::init(Value *Func, Value *Actual) {
288 Use *OL = OperandList = new Use[2];
289 OL[0].init(Func, this);
290 OL[1].init(Actual, this);
292 const FunctionType *FTy =
293 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
294 FTy = FTy; // silence warning.
296 assert((FTy->getNumParams() == 1 ||
297 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
298 "Calling a function with bad signature");
299 assert((0 == FTy->getNumParams() ||
300 FTy->getParamType(0) == Actual->getType()) &&
301 "Calling a function with a bad signature!");
304 void CallInst::init(Value *Func) {
307 Use *OL = OperandList = new Use[1];
308 OL[0].init(Func, this);
310 const FunctionType *FTy =
311 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
312 FTy = FTy; // silence warning.
314 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
317 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
318 Instruction *InsertBefore)
319 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
320 ->getElementType())->getReturnType(),
321 Instruction::Call, 0, 0, InsertBefore) {
326 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
327 BasicBlock *InsertAtEnd)
328 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
329 ->getElementType())->getReturnType(),
330 Instruction::Call, 0, 0, InsertAtEnd) {
334 CallInst::CallInst(Value *Func, const std::string &Name,
335 Instruction *InsertBefore)
336 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
337 ->getElementType())->getReturnType(),
338 Instruction::Call, 0, 0, InsertBefore) {
343 CallInst::CallInst(Value *Func, const std::string &Name,
344 BasicBlock *InsertAtEnd)
345 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
346 ->getElementType())->getReturnType(),
347 Instruction::Call, 0, 0, InsertAtEnd) {
352 CallInst::CallInst(const CallInst &CI)
353 : Instruction(CI.getType(), Instruction::Call, new Use[CI.getNumOperands()],
354 CI.getNumOperands()),
356 setParamAttrs(CI.getParamAttrs());
357 SubclassData = CI.SubclassData;
358 Use *OL = OperandList;
359 Use *InOL = CI.OperandList;
360 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
361 OL[i].init(InOL[i], this);
364 void CallInst::setParamAttrs(const ParamAttrsList *newAttrs) {
365 if (ParamAttrs == newAttrs)
369 ParamAttrs->dropRef();
374 ParamAttrs = newAttrs;
377 bool CallInst::paramHasAttr(uint16_t i, ParameterAttributes attr) const {
378 if (ParamAttrs && ParamAttrs->paramHasAttr(i, attr))
380 if (const Function *F = getCalledFunction())
381 return F->paramHasAttr(i, attr);
385 /// @brief Determine if the call does not access memory.
386 bool CallInst::doesNotAccessMemory() const {
387 return paramHasAttr(0, ParamAttr::ReadNone);
390 /// @brief Determine if the call does not access or only reads memory.
391 bool CallInst::onlyReadsMemory() const {
392 return doesNotAccessMemory() || paramHasAttr(0, ParamAttr::ReadOnly);
395 /// @brief Determine if the call cannot return.
396 bool CallInst::doesNotReturn() const {
397 return paramHasAttr(0, ParamAttr::NoReturn);
400 /// @brief Determine if the call cannot unwind.
401 bool CallInst::doesNotThrow() const {
402 return paramHasAttr(0, ParamAttr::NoUnwind);
405 /// @brief Determine if the call returns a structure.
406 bool CallInst::isStructReturn() const {
407 // Be friendly and also check the callee.
408 return paramHasAttr(1, ParamAttr::StructRet);
411 /// @brief Determine if any call argument is an aggregate passed by value.
412 bool CallInst::hasByValArgument() const {
413 if (ParamAttrs && ParamAttrs->hasAttrSomewhere(ParamAttr::ByVal))
415 // Be consistent with other methods and check the callee too.
416 if (const Function *F = getCalledFunction())
417 if (const ParamAttrsList *PAL = F->getParamAttrs())
418 return PAL->hasAttrSomewhere(ParamAttr::ByVal);
422 void CallInst::setDoesNotThrow(bool doesNotThrow) {
423 const ParamAttrsList *PAL = getParamAttrs();
425 PAL = ParamAttrsList::includeAttrs(PAL, 0, ParamAttr::NoUnwind);
427 PAL = ParamAttrsList::excludeAttrs(PAL, 0, ParamAttr::NoUnwind);
432 //===----------------------------------------------------------------------===//
433 // InvokeInst Implementation
434 //===----------------------------------------------------------------------===//
436 InvokeInst::~InvokeInst() {
437 delete [] OperandList;
439 ParamAttrs->dropRef();
442 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
443 Value* const *Args, unsigned NumArgs) {
445 NumOperands = 3+NumArgs;
446 Use *OL = OperandList = new Use[3+NumArgs];
447 OL[0].init(Fn, this);
448 OL[1].init(IfNormal, this);
449 OL[2].init(IfException, this);
450 const FunctionType *FTy =
451 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
452 FTy = FTy; // silence warning.
454 assert((NumArgs == FTy->getNumParams()) ||
455 (FTy->isVarArg() && NumArgs > FTy->getNumParams()) &&
456 "Calling a function with bad signature");
458 for (unsigned i = 0, e = NumArgs; i != e; i++) {
459 assert((i >= FTy->getNumParams() ||
460 FTy->getParamType(i) == Args[i]->getType()) &&
461 "Invoking a function with a bad signature!");
463 OL[i+3].init(Args[i], this);
467 InvokeInst::InvokeInst(const InvokeInst &II)
468 : TerminatorInst(II.getType(), Instruction::Invoke,
469 new Use[II.getNumOperands()], II.getNumOperands()),
471 setParamAttrs(II.getParamAttrs());
472 SubclassData = II.SubclassData;
473 Use *OL = OperandList, *InOL = II.OperandList;
474 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
475 OL[i].init(InOL[i], this);
478 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
479 return getSuccessor(idx);
481 unsigned InvokeInst::getNumSuccessorsV() const {
482 return getNumSuccessors();
484 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
485 return setSuccessor(idx, B);
488 void InvokeInst::setParamAttrs(const ParamAttrsList *newAttrs) {
489 if (ParamAttrs == newAttrs)
493 ParamAttrs->dropRef();
498 ParamAttrs = newAttrs;
501 bool InvokeInst::paramHasAttr(uint16_t i, ParameterAttributes attr) const {
502 if (ParamAttrs && ParamAttrs->paramHasAttr(i, attr))
504 if (const Function *F = getCalledFunction())
505 return F->paramHasAttr(i, attr);
510 /// @brief Determine if the call does not access memory.
511 bool InvokeInst::doesNotAccessMemory() const {
512 return paramHasAttr(0, ParamAttr::ReadNone);
515 /// @brief Determine if the call does not access or only reads memory.
516 bool InvokeInst::onlyReadsMemory() const {
517 return doesNotAccessMemory() || paramHasAttr(0, ParamAttr::ReadOnly);
520 /// @brief Determine if the call cannot return.
521 bool InvokeInst::doesNotReturn() const {
522 return paramHasAttr(0, ParamAttr::NoReturn);
525 /// @brief Determine if the call cannot unwind.
526 bool InvokeInst::doesNotThrow() const {
527 return paramHasAttr(0, ParamAttr::NoUnwind);
530 void InvokeInst::setDoesNotThrow(bool doesNotThrow) {
531 const ParamAttrsList *PAL = getParamAttrs();
533 PAL = ParamAttrsList::includeAttrs(PAL, 0, ParamAttr::NoUnwind);
535 PAL = ParamAttrsList::excludeAttrs(PAL, 0, ParamAttr::NoUnwind);
539 /// @brief Determine if the call returns a structure.
540 bool InvokeInst::isStructReturn() const {
541 // Be friendly and also check the callee.
542 return paramHasAttr(1, ParamAttr::StructRet);
546 //===----------------------------------------------------------------------===//
547 // ReturnInst Implementation
548 //===----------------------------------------------------------------------===//
550 ReturnInst::ReturnInst(const ReturnInst &RI)
551 : TerminatorInst(Type::VoidTy, Instruction::Ret,
552 &RetVal, RI.getNumOperands()) {
553 if (RI.getNumOperands())
554 RetVal.init(RI.RetVal, this);
557 ReturnInst::ReturnInst(Value *retVal, Instruction *InsertBefore)
558 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertBefore) {
561 ReturnInst::ReturnInst(Value *retVal, BasicBlock *InsertAtEnd)
562 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertAtEnd) {
565 ReturnInst::ReturnInst(BasicBlock *InsertAtEnd)
566 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertAtEnd) {
571 void ReturnInst::init(Value *retVal) {
572 if (retVal && retVal->getType() != Type::VoidTy) {
573 assert(!isa<BasicBlock>(retVal) &&
574 "Cannot return basic block. Probably using the incorrect ctor");
576 RetVal.init(retVal, this);
580 unsigned ReturnInst::getNumSuccessorsV() const {
581 return getNumSuccessors();
584 // Out-of-line ReturnInst method, put here so the C++ compiler can choose to
585 // emit the vtable for the class in this translation unit.
586 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
587 assert(0 && "ReturnInst has no successors!");
590 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
591 assert(0 && "ReturnInst has no successors!");
597 //===----------------------------------------------------------------------===//
598 // UnwindInst Implementation
599 //===----------------------------------------------------------------------===//
601 UnwindInst::UnwindInst(Instruction *InsertBefore)
602 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertBefore) {
604 UnwindInst::UnwindInst(BasicBlock *InsertAtEnd)
605 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertAtEnd) {
609 unsigned UnwindInst::getNumSuccessorsV() const {
610 return getNumSuccessors();
613 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
614 assert(0 && "UnwindInst has no successors!");
617 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
618 assert(0 && "UnwindInst has no successors!");
623 //===----------------------------------------------------------------------===//
624 // UnreachableInst Implementation
625 //===----------------------------------------------------------------------===//
627 UnreachableInst::UnreachableInst(Instruction *InsertBefore)
628 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertBefore) {
630 UnreachableInst::UnreachableInst(BasicBlock *InsertAtEnd)
631 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertAtEnd) {
634 unsigned UnreachableInst::getNumSuccessorsV() const {
635 return getNumSuccessors();
638 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
639 assert(0 && "UnwindInst has no successors!");
642 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
643 assert(0 && "UnwindInst has no successors!");
648 //===----------------------------------------------------------------------===//
649 // BranchInst Implementation
650 //===----------------------------------------------------------------------===//
652 void BranchInst::AssertOK() {
654 assert(getCondition()->getType() == Type::Int1Ty &&
655 "May only branch on boolean predicates!");
658 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
659 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 1, InsertBefore) {
660 assert(IfTrue != 0 && "Branch destination may not be null!");
661 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
663 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
664 Instruction *InsertBefore)
665 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 3, InsertBefore) {
666 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
667 Ops[1].init(reinterpret_cast<Value*>(IfFalse), this);
668 Ops[2].init(Cond, this);
674 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
675 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 1, InsertAtEnd) {
676 assert(IfTrue != 0 && "Branch destination may not be null!");
677 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
680 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
681 BasicBlock *InsertAtEnd)
682 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 3, InsertAtEnd) {
683 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
684 Ops[1].init(reinterpret_cast<Value*>(IfFalse), this);
685 Ops[2].init(Cond, this);
692 BranchInst::BranchInst(const BranchInst &BI) :
693 TerminatorInst(Type::VoidTy, Instruction::Br, Ops, BI.getNumOperands()) {
694 OperandList[0].init(BI.getOperand(0), this);
695 if (BI.getNumOperands() != 1) {
696 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
697 OperandList[1].init(BI.getOperand(1), this);
698 OperandList[2].init(BI.getOperand(2), this);
702 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
703 return getSuccessor(idx);
705 unsigned BranchInst::getNumSuccessorsV() const {
706 return getNumSuccessors();
708 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
709 setSuccessor(idx, B);
713 //===----------------------------------------------------------------------===//
714 // AllocationInst Implementation
715 //===----------------------------------------------------------------------===//
717 static Value *getAISize(Value *Amt) {
719 Amt = ConstantInt::get(Type::Int32Ty, 1);
721 assert(!isa<BasicBlock>(Amt) &&
722 "Passed basic block into allocation size parameter! Use other ctor");
723 assert(Amt->getType() == Type::Int32Ty &&
724 "Malloc/Allocation array size is not a 32-bit integer!");
729 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
730 unsigned Align, const std::string &Name,
731 Instruction *InsertBefore)
732 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
733 InsertBefore), Alignment(Align) {
734 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
735 assert(Ty != Type::VoidTy && "Cannot allocate void!");
739 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
740 unsigned Align, const std::string &Name,
741 BasicBlock *InsertAtEnd)
742 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
743 InsertAtEnd), Alignment(Align) {
744 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
745 assert(Ty != Type::VoidTy && "Cannot allocate void!");
749 // Out of line virtual method, so the vtable, etc has a home.
750 AllocationInst::~AllocationInst() {
753 bool AllocationInst::isArrayAllocation() const {
754 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
755 return CI->getZExtValue() != 1;
759 const Type *AllocationInst::getAllocatedType() const {
760 return getType()->getElementType();
763 AllocaInst::AllocaInst(const AllocaInst &AI)
764 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
765 Instruction::Alloca, AI.getAlignment()) {
768 MallocInst::MallocInst(const MallocInst &MI)
769 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
770 Instruction::Malloc, MI.getAlignment()) {
773 //===----------------------------------------------------------------------===//
774 // FreeInst Implementation
775 //===----------------------------------------------------------------------===//
777 void FreeInst::AssertOK() {
778 assert(isa<PointerType>(getOperand(0)->getType()) &&
779 "Can not free something of nonpointer type!");
782 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
783 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertBefore) {
787 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
788 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertAtEnd) {
793 //===----------------------------------------------------------------------===//
794 // LoadInst Implementation
795 //===----------------------------------------------------------------------===//
797 void LoadInst::AssertOK() {
798 assert(isa<PointerType>(getOperand(0)->getType()) &&
799 "Ptr must have pointer type.");
802 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
803 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
804 Load, Ptr, InsertBef) {
811 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
812 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
813 Load, Ptr, InsertAE) {
820 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
821 Instruction *InsertBef)
822 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
823 Load, Ptr, InsertBef) {
824 setVolatile(isVolatile);
830 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
831 unsigned Align, Instruction *InsertBef)
832 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
833 Load, Ptr, InsertBef) {
834 setVolatile(isVolatile);
840 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
841 unsigned Align, BasicBlock *InsertAE)
842 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
843 Load, Ptr, InsertAE) {
844 setVolatile(isVolatile);
850 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
851 BasicBlock *InsertAE)
852 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
853 Load, Ptr, InsertAE) {
854 setVolatile(isVolatile);
862 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
863 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
864 Load, Ptr, InsertBef) {
868 if (Name && Name[0]) setName(Name);
871 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
872 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
873 Load, Ptr, InsertAE) {
877 if (Name && Name[0]) setName(Name);
880 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
881 Instruction *InsertBef)
882 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
883 Load, Ptr, InsertBef) {
884 setVolatile(isVolatile);
887 if (Name && Name[0]) setName(Name);
890 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
891 BasicBlock *InsertAE)
892 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
893 Load, Ptr, InsertAE) {
894 setVolatile(isVolatile);
897 if (Name && Name[0]) setName(Name);
900 void LoadInst::setAlignment(unsigned Align) {
901 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
902 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
905 //===----------------------------------------------------------------------===//
906 // StoreInst Implementation
907 //===----------------------------------------------------------------------===//
909 void StoreInst::AssertOK() {
910 assert(isa<PointerType>(getOperand(1)->getType()) &&
911 "Ptr must have pointer type!");
912 assert(getOperand(0)->getType() ==
913 cast<PointerType>(getOperand(1)->getType())->getElementType()
914 && "Ptr must be a pointer to Val type!");
918 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
919 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
920 Ops[0].init(val, this);
921 Ops[1].init(addr, this);
927 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
928 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
929 Ops[0].init(val, this);
930 Ops[1].init(addr, this);
936 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
937 Instruction *InsertBefore)
938 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
939 Ops[0].init(val, this);
940 Ops[1].init(addr, this);
941 setVolatile(isVolatile);
946 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
947 unsigned Align, Instruction *InsertBefore)
948 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
949 Ops[0].init(val, this);
950 Ops[1].init(addr, this);
951 setVolatile(isVolatile);
956 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
957 unsigned Align, BasicBlock *InsertAtEnd)
958 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
959 Ops[0].init(val, this);
960 Ops[1].init(addr, this);
961 setVolatile(isVolatile);
966 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
967 BasicBlock *InsertAtEnd)
968 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
969 Ops[0].init(val, this);
970 Ops[1].init(addr, this);
971 setVolatile(isVolatile);
976 void StoreInst::setAlignment(unsigned Align) {
977 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
978 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
981 //===----------------------------------------------------------------------===//
982 // GetElementPtrInst Implementation
983 //===----------------------------------------------------------------------===//
985 static unsigned retrieveAddrSpace(const Value *Val) {
986 return cast<PointerType>(Val->getType())->getAddressSpace();
989 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx) {
990 NumOperands = 1+NumIdx;
991 Use *OL = OperandList = new Use[NumOperands];
992 OL[0].init(Ptr, this);
994 for (unsigned i = 0; i != NumIdx; ++i)
995 OL[i+1].init(Idx[i], this);
998 void GetElementPtrInst::init(Value *Ptr, Value *Idx) {
1000 Use *OL = OperandList = new Use[2];
1001 OL[0].init(Ptr, this);
1002 OL[1].init(Idx, this);
1005 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1006 const std::string &Name, Instruction *InBe)
1007 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1008 retrieveAddrSpace(Ptr)),
1009 GetElementPtr, 0, 0, InBe) {
1014 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1015 const std::string &Name, BasicBlock *IAE)
1016 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1017 retrieveAddrSpace(Ptr)),
1018 GetElementPtr, 0, 0, IAE) {
1023 GetElementPtrInst::~GetElementPtrInst() {
1024 delete[] OperandList;
1027 // getIndexedType - Returns the type of the element that would be loaded with
1028 // a load instruction with the specified parameters.
1030 // A null type is returned if the indices are invalid for the specified
1033 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1036 bool AllowCompositeLeaf) {
1037 if (!isa<PointerType>(Ptr)) return 0; // Type isn't a pointer type!
1039 // Handle the special case of the empty set index set...
1041 if (AllowCompositeLeaf ||
1042 cast<PointerType>(Ptr)->getElementType()->isFirstClassType())
1043 return cast<PointerType>(Ptr)->getElementType();
1047 unsigned CurIdx = 0;
1048 while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
1049 if (NumIdx == CurIdx) {
1050 if (AllowCompositeLeaf || CT->isFirstClassType()) return Ptr;
1051 return 0; // Can't load a whole structure or array!?!?
1054 Value *Index = Idxs[CurIdx++];
1055 if (isa<PointerType>(CT) && CurIdx != 1)
1056 return 0; // Can only index into pointer types at the first index!
1057 if (!CT->indexValid(Index)) return 0;
1058 Ptr = CT->getTypeAtIndex(Index);
1060 // If the new type forwards to another type, then it is in the middle
1061 // of being refined to another type (and hence, may have dropped all
1062 // references to what it was using before). So, use the new forwarded
1064 if (const Type * Ty = Ptr->getForwardedType()) {
1068 return CurIdx == NumIdx ? Ptr : 0;
1071 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1072 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1073 if (!PTy) return 0; // Type isn't a pointer type!
1075 // Check the pointer index.
1076 if (!PTy->indexValid(Idx)) return 0;
1078 return PTy->getElementType();
1082 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1083 /// zeros. If so, the result pointer and the first operand have the same
1084 /// value, just potentially different types.
1085 bool GetElementPtrInst::hasAllZeroIndices() const {
1086 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1087 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1088 if (!CI->isZero()) return false;
1096 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1097 /// constant integers. If so, the result pointer and the first operand have
1098 /// a constant offset between them.
1099 bool GetElementPtrInst::hasAllConstantIndices() const {
1100 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1101 if (!isa<ConstantInt>(getOperand(i)))
1108 //===----------------------------------------------------------------------===//
1109 // ExtractElementInst Implementation
1110 //===----------------------------------------------------------------------===//
1112 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1113 const std::string &Name,
1114 Instruction *InsertBef)
1115 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1116 ExtractElement, Ops, 2, InsertBef) {
1117 assert(isValidOperands(Val, Index) &&
1118 "Invalid extractelement instruction operands!");
1119 Ops[0].init(Val, this);
1120 Ops[1].init(Index, this);
1124 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1125 const std::string &Name,
1126 Instruction *InsertBef)
1127 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1128 ExtractElement, Ops, 2, InsertBef) {
1129 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1130 assert(isValidOperands(Val, Index) &&
1131 "Invalid extractelement instruction operands!");
1132 Ops[0].init(Val, this);
1133 Ops[1].init(Index, this);
1138 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1139 const std::string &Name,
1140 BasicBlock *InsertAE)
1141 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1142 ExtractElement, Ops, 2, InsertAE) {
1143 assert(isValidOperands(Val, Index) &&
1144 "Invalid extractelement instruction operands!");
1146 Ops[0].init(Val, this);
1147 Ops[1].init(Index, this);
1151 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1152 const std::string &Name,
1153 BasicBlock *InsertAE)
1154 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1155 ExtractElement, Ops, 2, InsertAE) {
1156 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1157 assert(isValidOperands(Val, Index) &&
1158 "Invalid extractelement instruction operands!");
1160 Ops[0].init(Val, this);
1161 Ops[1].init(Index, this);
1166 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1167 if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty)
1173 //===----------------------------------------------------------------------===//
1174 // InsertElementInst Implementation
1175 //===----------------------------------------------------------------------===//
1177 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
1178 : Instruction(IE.getType(), InsertElement, Ops, 3) {
1179 Ops[0].init(IE.Ops[0], this);
1180 Ops[1].init(IE.Ops[1], this);
1181 Ops[2].init(IE.Ops[2], this);
1183 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1184 const std::string &Name,
1185 Instruction *InsertBef)
1186 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertBef) {
1187 assert(isValidOperands(Vec, Elt, Index) &&
1188 "Invalid insertelement instruction operands!");
1189 Ops[0].init(Vec, this);
1190 Ops[1].init(Elt, this);
1191 Ops[2].init(Index, this);
1195 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1196 const std::string &Name,
1197 Instruction *InsertBef)
1198 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertBef) {
1199 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1200 assert(isValidOperands(Vec, Elt, Index) &&
1201 "Invalid insertelement instruction operands!");
1202 Ops[0].init(Vec, this);
1203 Ops[1].init(Elt, this);
1204 Ops[2].init(Index, this);
1209 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1210 const std::string &Name,
1211 BasicBlock *InsertAE)
1212 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertAE) {
1213 assert(isValidOperands(Vec, Elt, Index) &&
1214 "Invalid insertelement instruction operands!");
1216 Ops[0].init(Vec, this);
1217 Ops[1].init(Elt, this);
1218 Ops[2].init(Index, this);
1222 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1223 const std::string &Name,
1224 BasicBlock *InsertAE)
1225 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertAE) {
1226 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1227 assert(isValidOperands(Vec, Elt, Index) &&
1228 "Invalid insertelement instruction operands!");
1230 Ops[0].init(Vec, this);
1231 Ops[1].init(Elt, this);
1232 Ops[2].init(Index, this);
1236 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1237 const Value *Index) {
1238 if (!isa<VectorType>(Vec->getType()))
1239 return false; // First operand of insertelement must be vector type.
1241 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1242 return false;// Second operand of insertelement must be vector element type.
1244 if (Index->getType() != Type::Int32Ty)
1245 return false; // Third operand of insertelement must be uint.
1250 //===----------------------------------------------------------------------===//
1251 // ShuffleVectorInst Implementation
1252 //===----------------------------------------------------------------------===//
1254 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
1255 : Instruction(SV.getType(), ShuffleVector, Ops, 3) {
1256 Ops[0].init(SV.Ops[0], this);
1257 Ops[1].init(SV.Ops[1], this);
1258 Ops[2].init(SV.Ops[2], this);
1261 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1262 const std::string &Name,
1263 Instruction *InsertBefore)
1264 : Instruction(V1->getType(), ShuffleVector, Ops, 3, InsertBefore) {
1265 assert(isValidOperands(V1, V2, Mask) &&
1266 "Invalid shuffle vector instruction operands!");
1267 Ops[0].init(V1, this);
1268 Ops[1].init(V2, this);
1269 Ops[2].init(Mask, this);
1273 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1274 const std::string &Name,
1275 BasicBlock *InsertAtEnd)
1276 : Instruction(V1->getType(), ShuffleVector, Ops, 3, InsertAtEnd) {
1277 assert(isValidOperands(V1, V2, Mask) &&
1278 "Invalid shuffle vector instruction operands!");
1280 Ops[0].init(V1, this);
1281 Ops[1].init(V2, this);
1282 Ops[2].init(Mask, this);
1286 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1287 const Value *Mask) {
1288 if (!isa<VectorType>(V1->getType())) return false;
1289 if (V1->getType() != V2->getType()) return false;
1290 if (!isa<VectorType>(Mask->getType()) ||
1291 cast<VectorType>(Mask->getType())->getElementType() != Type::Int32Ty ||
1292 cast<VectorType>(Mask->getType())->getNumElements() !=
1293 cast<VectorType>(V1->getType())->getNumElements())
1299 //===----------------------------------------------------------------------===//
1300 // BinaryOperator Class
1301 //===----------------------------------------------------------------------===//
1303 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1304 const Type *Ty, const std::string &Name,
1305 Instruction *InsertBefore)
1306 : Instruction(Ty, iType, Ops, 2, InsertBefore) {
1307 Ops[0].init(S1, this);
1308 Ops[1].init(S2, this);
1313 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1314 const Type *Ty, const std::string &Name,
1315 BasicBlock *InsertAtEnd)
1316 : Instruction(Ty, iType, Ops, 2, InsertAtEnd) {
1317 Ops[0].init(S1, this);
1318 Ops[1].init(S2, this);
1324 void BinaryOperator::init(BinaryOps iType) {
1325 Value *LHS = getOperand(0), *RHS = getOperand(1);
1326 LHS = LHS; RHS = RHS; // Silence warnings.
1327 assert(LHS->getType() == RHS->getType() &&
1328 "Binary operator operand types must match!");
1333 assert(getType() == LHS->getType() &&
1334 "Arithmetic operation should return same type as operands!");
1335 assert((getType()->isInteger() || getType()->isFloatingPoint() ||
1336 isa<VectorType>(getType())) &&
1337 "Tried to create an arithmetic operation on a non-arithmetic type!");
1341 assert(getType() == LHS->getType() &&
1342 "Arithmetic operation should return same type as operands!");
1343 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1344 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1345 "Incorrect operand type (not integer) for S/UDIV");
1348 assert(getType() == LHS->getType() &&
1349 "Arithmetic operation should return same type as operands!");
1350 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1351 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1352 && "Incorrect operand type (not floating point) for FDIV");
1356 assert(getType() == LHS->getType() &&
1357 "Arithmetic operation should return same type as operands!");
1358 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1359 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1360 "Incorrect operand type (not integer) for S/UREM");
1363 assert(getType() == LHS->getType() &&
1364 "Arithmetic operation should return same type as operands!");
1365 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1366 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1367 && "Incorrect operand type (not floating point) for FREM");
1372 assert(getType() == LHS->getType() &&
1373 "Shift operation should return same type as operands!");
1374 assert(getType()->isInteger() &&
1375 "Shift operation requires integer operands");
1379 assert(getType() == LHS->getType() &&
1380 "Logical operation should return same type as operands!");
1381 assert((getType()->isInteger() ||
1382 (isa<VectorType>(getType()) &&
1383 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1384 "Tried to create a logical operation on a non-integral type!");
1392 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1393 const std::string &Name,
1394 Instruction *InsertBefore) {
1395 assert(S1->getType() == S2->getType() &&
1396 "Cannot create binary operator with two operands of differing type!");
1397 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1400 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1401 const std::string &Name,
1402 BasicBlock *InsertAtEnd) {
1403 BinaryOperator *Res = create(Op, S1, S2, Name);
1404 InsertAtEnd->getInstList().push_back(Res);
1408 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1409 Instruction *InsertBefore) {
1410 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1411 return new BinaryOperator(Instruction::Sub,
1413 Op->getType(), Name, InsertBefore);
1416 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1417 BasicBlock *InsertAtEnd) {
1418 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1419 return new BinaryOperator(Instruction::Sub,
1421 Op->getType(), Name, InsertAtEnd);
1424 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1425 Instruction *InsertBefore) {
1427 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1428 C = ConstantInt::getAllOnesValue(PTy->getElementType());
1429 C = ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), C));
1431 C = ConstantInt::getAllOnesValue(Op->getType());
1434 return new BinaryOperator(Instruction::Xor, Op, C,
1435 Op->getType(), Name, InsertBefore);
1438 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1439 BasicBlock *InsertAtEnd) {
1441 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1442 // Create a vector of all ones values.
1443 Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType());
1445 ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1447 AllOnes = ConstantInt::getAllOnesValue(Op->getType());
1450 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1451 Op->getType(), Name, InsertAtEnd);
1455 // isConstantAllOnes - Helper function for several functions below
1456 static inline bool isConstantAllOnes(const Value *V) {
1457 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1458 return CI->isAllOnesValue();
1459 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1460 return CV->isAllOnesValue();
1464 bool BinaryOperator::isNeg(const Value *V) {
1465 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1466 if (Bop->getOpcode() == Instruction::Sub)
1467 return Bop->getOperand(0) ==
1468 ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1472 bool BinaryOperator::isNot(const Value *V) {
1473 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1474 return (Bop->getOpcode() == Instruction::Xor &&
1475 (isConstantAllOnes(Bop->getOperand(1)) ||
1476 isConstantAllOnes(Bop->getOperand(0))));
1480 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1481 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1482 return cast<BinaryOperator>(BinOp)->getOperand(1);
1485 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1486 return getNegArgument(const_cast<Value*>(BinOp));
1489 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1490 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1491 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1492 Value *Op0 = BO->getOperand(0);
1493 Value *Op1 = BO->getOperand(1);
1494 if (isConstantAllOnes(Op0)) return Op1;
1496 assert(isConstantAllOnes(Op1));
1500 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1501 return getNotArgument(const_cast<Value*>(BinOp));
1505 // swapOperands - Exchange the two operands to this instruction. This
1506 // instruction is safe to use on any binary instruction and does not
1507 // modify the semantics of the instruction. If the instruction is
1508 // order dependent (SetLT f.e.) the opcode is changed.
1510 bool BinaryOperator::swapOperands() {
1511 if (!isCommutative())
1512 return true; // Can't commute operands
1513 std::swap(Ops[0], Ops[1]);
1517 //===----------------------------------------------------------------------===//
1519 //===----------------------------------------------------------------------===//
1521 // Just determine if this cast only deals with integral->integral conversion.
1522 bool CastInst::isIntegerCast() const {
1523 switch (getOpcode()) {
1524 default: return false;
1525 case Instruction::ZExt:
1526 case Instruction::SExt:
1527 case Instruction::Trunc:
1529 case Instruction::BitCast:
1530 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1534 bool CastInst::isLosslessCast() const {
1535 // Only BitCast can be lossless, exit fast if we're not BitCast
1536 if (getOpcode() != Instruction::BitCast)
1539 // Identity cast is always lossless
1540 const Type* SrcTy = getOperand(0)->getType();
1541 const Type* DstTy = getType();
1545 // Pointer to pointer is always lossless.
1546 if (isa<PointerType>(SrcTy))
1547 return isa<PointerType>(DstTy);
1548 return false; // Other types have no identity values
1551 /// This function determines if the CastInst does not require any bits to be
1552 /// changed in order to effect the cast. Essentially, it identifies cases where
1553 /// no code gen is necessary for the cast, hence the name no-op cast. For
1554 /// example, the following are all no-op casts:
1555 /// # bitcast uint %X, int
1556 /// # bitcast uint* %x, sbyte*
1557 /// # bitcast vector< 2 x int > %x, vector< 4 x short>
1558 /// # ptrtoint uint* %x, uint ; on 32-bit plaforms only
1559 /// @brief Determine if a cast is a no-op.
1560 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1561 switch (getOpcode()) {
1563 assert(!"Invalid CastOp");
1564 case Instruction::Trunc:
1565 case Instruction::ZExt:
1566 case Instruction::SExt:
1567 case Instruction::FPTrunc:
1568 case Instruction::FPExt:
1569 case Instruction::UIToFP:
1570 case Instruction::SIToFP:
1571 case Instruction::FPToUI:
1572 case Instruction::FPToSI:
1573 return false; // These always modify bits
1574 case Instruction::BitCast:
1575 return true; // BitCast never modifies bits.
1576 case Instruction::PtrToInt:
1577 return IntPtrTy->getPrimitiveSizeInBits() ==
1578 getType()->getPrimitiveSizeInBits();
1579 case Instruction::IntToPtr:
1580 return IntPtrTy->getPrimitiveSizeInBits() ==
1581 getOperand(0)->getType()->getPrimitiveSizeInBits();
1585 /// This function determines if a pair of casts can be eliminated and what
1586 /// opcode should be used in the elimination. This assumes that there are two
1587 /// instructions like this:
1588 /// * %F = firstOpcode SrcTy %x to MidTy
1589 /// * %S = secondOpcode MidTy %F to DstTy
1590 /// The function returns a resultOpcode so these two casts can be replaced with:
1591 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1592 /// If no such cast is permited, the function returns 0.
1593 unsigned CastInst::isEliminableCastPair(
1594 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1595 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1597 // Define the 144 possibilities for these two cast instructions. The values
1598 // in this matrix determine what to do in a given situation and select the
1599 // case in the switch below. The rows correspond to firstOp, the columns
1600 // correspond to secondOp. In looking at the table below, keep in mind
1601 // the following cast properties:
1603 // Size Compare Source Destination
1604 // Operator Src ? Size Type Sign Type Sign
1605 // -------- ------------ ------------------- ---------------------
1606 // TRUNC > Integer Any Integral Any
1607 // ZEXT < Integral Unsigned Integer Any
1608 // SEXT < Integral Signed Integer Any
1609 // FPTOUI n/a FloatPt n/a Integral Unsigned
1610 // FPTOSI n/a FloatPt n/a Integral Signed
1611 // UITOFP n/a Integral Unsigned FloatPt n/a
1612 // SITOFP n/a Integral Signed FloatPt n/a
1613 // FPTRUNC > FloatPt n/a FloatPt n/a
1614 // FPEXT < FloatPt n/a FloatPt n/a
1615 // PTRTOINT n/a Pointer n/a Integral Unsigned
1616 // INTTOPTR n/a Integral Unsigned Pointer n/a
1617 // BITCONVERT = FirstClass n/a FirstClass n/a
1619 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1620 // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
1621 // into "fptoui double to ulong", but this loses information about the range
1622 // of the produced value (we no longer know the top-part is all zeros).
1623 // Further this conversion is often much more expensive for typical hardware,
1624 // and causes issues when building libgcc. We disallow fptosi+sext for the
1626 const unsigned numCastOps =
1627 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1628 static const uint8_t CastResults[numCastOps][numCastOps] = {
1629 // T F F U S F F P I B -+
1630 // R Z S P P I I T P 2 N T |
1631 // U E E 2 2 2 2 R E I T C +- secondOp
1632 // N X X U S F F N X N 2 V |
1633 // C T T I I P P C T T P T -+
1634 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1635 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1636 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1637 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1638 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1639 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1640 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1641 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1642 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1643 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1644 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1645 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1648 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1649 [secondOp-Instruction::CastOpsBegin];
1652 // categorically disallowed
1655 // allowed, use first cast's opcode
1658 // allowed, use second cast's opcode
1661 // no-op cast in second op implies firstOp as long as the DestTy
1663 if (DstTy->isInteger())
1667 // no-op cast in second op implies firstOp as long as the DestTy
1668 // is floating point
1669 if (DstTy->isFloatingPoint())
1673 // no-op cast in first op implies secondOp as long as the SrcTy
1675 if (SrcTy->isInteger())
1679 // no-op cast in first op implies secondOp as long as the SrcTy
1680 // is a floating point
1681 if (SrcTy->isFloatingPoint())
1685 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1686 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1687 unsigned MidSize = MidTy->getPrimitiveSizeInBits();
1688 if (MidSize >= PtrSize)
1689 return Instruction::BitCast;
1693 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1694 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1695 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1696 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1697 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1698 if (SrcSize == DstSize)
1699 return Instruction::BitCast;
1700 else if (SrcSize < DstSize)
1704 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1705 return Instruction::ZExt;
1707 // fpext followed by ftrunc is allowed if the bit size returned to is
1708 // the same as the original, in which case its just a bitcast
1710 return Instruction::BitCast;
1711 return 0; // If the types are not the same we can't eliminate it.
1713 // bitcast followed by ptrtoint is allowed as long as the bitcast
1714 // is a pointer to pointer cast.
1715 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1719 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1720 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1724 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1725 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1726 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1727 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1728 if (SrcSize <= PtrSize && SrcSize == DstSize)
1729 return Instruction::BitCast;
1733 // cast combination can't happen (error in input). This is for all cases
1734 // where the MidTy is not the same for the two cast instructions.
1735 assert(!"Invalid Cast Combination");
1738 assert(!"Error in CastResults table!!!");
1744 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1745 const std::string &Name, Instruction *InsertBefore) {
1746 // Construct and return the appropriate CastInst subclass
1748 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1749 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1750 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1751 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1752 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1753 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1754 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1755 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1756 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1757 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1758 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1759 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1761 assert(!"Invalid opcode provided");
1766 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1767 const std::string &Name, BasicBlock *InsertAtEnd) {
1768 // Construct and return the appropriate CastInst subclass
1770 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1771 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1772 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1773 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1774 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1775 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1776 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1777 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1778 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1779 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1780 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1781 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1783 assert(!"Invalid opcode provided");
1788 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1789 const std::string &Name,
1790 Instruction *InsertBefore) {
1791 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1792 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1793 return create(Instruction::ZExt, S, Ty, Name, InsertBefore);
1796 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1797 const std::string &Name,
1798 BasicBlock *InsertAtEnd) {
1799 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1800 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1801 return create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
1804 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1805 const std::string &Name,
1806 Instruction *InsertBefore) {
1807 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1808 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1809 return create(Instruction::SExt, S, Ty, Name, InsertBefore);
1812 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1813 const std::string &Name,
1814 BasicBlock *InsertAtEnd) {
1815 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1816 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1817 return create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
1820 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1821 const std::string &Name,
1822 Instruction *InsertBefore) {
1823 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1824 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1825 return create(Instruction::Trunc, S, Ty, Name, InsertBefore);
1828 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1829 const std::string &Name,
1830 BasicBlock *InsertAtEnd) {
1831 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1832 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1833 return create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
1836 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1837 const std::string &Name,
1838 BasicBlock *InsertAtEnd) {
1839 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1840 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1843 if (Ty->isInteger())
1844 return create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
1845 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1848 /// @brief Create a BitCast or a PtrToInt cast instruction
1849 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1850 const std::string &Name,
1851 Instruction *InsertBefore) {
1852 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1853 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1856 if (Ty->isInteger())
1857 return create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
1858 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1861 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1862 bool isSigned, const std::string &Name,
1863 Instruction *InsertBefore) {
1864 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1865 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1866 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1867 Instruction::CastOps opcode =
1868 (SrcBits == DstBits ? Instruction::BitCast :
1869 (SrcBits > DstBits ? Instruction::Trunc :
1870 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1871 return create(opcode, C, Ty, Name, InsertBefore);
1874 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1875 bool isSigned, const std::string &Name,
1876 BasicBlock *InsertAtEnd) {
1877 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1878 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1879 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1880 Instruction::CastOps opcode =
1881 (SrcBits == DstBits ? Instruction::BitCast :
1882 (SrcBits > DstBits ? Instruction::Trunc :
1883 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1884 return create(opcode, C, Ty, Name, InsertAtEnd);
1887 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1888 const std::string &Name,
1889 Instruction *InsertBefore) {
1890 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1892 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1893 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1894 Instruction::CastOps opcode =
1895 (SrcBits == DstBits ? Instruction::BitCast :
1896 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1897 return create(opcode, C, Ty, Name, InsertBefore);
1900 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1901 const std::string &Name,
1902 BasicBlock *InsertAtEnd) {
1903 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1905 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1906 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1907 Instruction::CastOps opcode =
1908 (SrcBits == DstBits ? Instruction::BitCast :
1909 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1910 return create(opcode, C, Ty, Name, InsertAtEnd);
1913 // Check whether it is valid to call getCastOpcode for these types.
1914 // This routine must be kept in sync with getCastOpcode.
1915 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
1916 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
1919 if (SrcTy == DestTy)
1922 // Get the bit sizes, we'll need these
1923 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1924 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1926 // Run through the possibilities ...
1927 if (DestTy->isInteger()) { // Casting to integral
1928 if (SrcTy->isInteger()) { // Casting from integral
1930 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1932 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1933 // Casting from vector
1934 return DestBits == PTy->getBitWidth();
1935 } else { // Casting from something else
1936 return isa<PointerType>(SrcTy);
1938 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
1939 if (SrcTy->isInteger()) { // Casting from integral
1941 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1943 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1944 // Casting from vector
1945 return DestBits == PTy->getBitWidth();
1946 } else { // Casting from something else
1949 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
1950 // Casting to vector
1951 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
1952 // Casting from vector
1953 return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
1954 } else { // Casting from something else
1955 return DestPTy->getBitWidth() == SrcBits;
1957 } else if (isa<PointerType>(DestTy)) { // Casting to pointer
1958 if (isa<PointerType>(SrcTy)) { // Casting from pointer
1960 } else if (SrcTy->isInteger()) { // Casting from integral
1962 } else { // Casting from something else
1965 } else { // Casting to something else
1970 // Provide a way to get a "cast" where the cast opcode is inferred from the
1971 // types and size of the operand. This, basically, is a parallel of the
1972 // logic in the castIsValid function below. This axiom should hold:
1973 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
1974 // should not assert in castIsValid. In other words, this produces a "correct"
1975 // casting opcode for the arguments passed to it.
1976 // This routine must be kept in sync with isCastable.
1977 Instruction::CastOps
1978 CastInst::getCastOpcode(
1979 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
1980 // Get the bit sizes, we'll need these
1981 const Type *SrcTy = Src->getType();
1982 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1983 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1985 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
1986 "Only first class types are castable!");
1988 // Run through the possibilities ...
1989 if (DestTy->isInteger()) { // Casting to integral
1990 if (SrcTy->isInteger()) { // Casting from integral
1991 if (DestBits < SrcBits)
1992 return Trunc; // int -> smaller int
1993 else if (DestBits > SrcBits) { // its an extension
1995 return SExt; // signed -> SEXT
1997 return ZExt; // unsigned -> ZEXT
1999 return BitCast; // Same size, No-op cast
2001 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2003 return FPToSI; // FP -> sint
2005 return FPToUI; // FP -> uint
2006 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2007 assert(DestBits == PTy->getBitWidth() &&
2008 "Casting vector to integer of different width");
2009 return BitCast; // Same size, no-op cast
2011 assert(isa<PointerType>(SrcTy) &&
2012 "Casting from a value that is not first-class type");
2013 return PtrToInt; // ptr -> int
2015 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2016 if (SrcTy->isInteger()) { // Casting from integral
2018 return SIToFP; // sint -> FP
2020 return UIToFP; // uint -> FP
2021 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2022 if (DestBits < SrcBits) {
2023 return FPTrunc; // FP -> smaller FP
2024 } else if (DestBits > SrcBits) {
2025 return FPExt; // FP -> larger FP
2027 return BitCast; // same size, no-op cast
2029 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2030 assert(DestBits == PTy->getBitWidth() &&
2031 "Casting vector to floating point of different width");
2032 return BitCast; // same size, no-op cast
2034 assert(0 && "Casting pointer or non-first class to float");
2036 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2037 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2038 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2039 "Casting vector to vector of different widths");
2040 return BitCast; // vector -> vector
2041 } else if (DestPTy->getBitWidth() == SrcBits) {
2042 return BitCast; // float/int -> vector
2044 assert(!"Illegal cast to vector (wrong type or size)");
2046 } else if (isa<PointerType>(DestTy)) {
2047 if (isa<PointerType>(SrcTy)) {
2048 return BitCast; // ptr -> ptr
2049 } else if (SrcTy->isInteger()) {
2050 return IntToPtr; // int -> ptr
2052 assert(!"Casting pointer to other than pointer or int");
2055 assert(!"Casting to type that is not first-class");
2058 // If we fall through to here we probably hit an assertion cast above
2059 // and assertions are not turned on. Anything we return is an error, so
2060 // BitCast is as good a choice as any.
2064 //===----------------------------------------------------------------------===//
2065 // CastInst SubClass Constructors
2066 //===----------------------------------------------------------------------===//
2068 /// Check that the construction parameters for a CastInst are correct. This
2069 /// could be broken out into the separate constructors but it is useful to have
2070 /// it in one place and to eliminate the redundant code for getting the sizes
2071 /// of the types involved.
2073 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2075 // Check for type sanity on the arguments
2076 const Type *SrcTy = S->getType();
2077 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
2080 // Get the size of the types in bits, we'll need this later
2081 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2082 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2084 // Switch on the opcode provided
2086 default: return false; // This is an input error
2087 case Instruction::Trunc:
2088 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize > DstBitSize;
2089 case Instruction::ZExt:
2090 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2091 case Instruction::SExt:
2092 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2093 case Instruction::FPTrunc:
2094 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2095 SrcBitSize > DstBitSize;
2096 case Instruction::FPExt:
2097 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2098 SrcBitSize < DstBitSize;
2099 case Instruction::UIToFP:
2100 case Instruction::SIToFP:
2101 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2102 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2103 return SVTy->getElementType()->isInteger() &&
2104 DVTy->getElementType()->isFloatingPoint() &&
2105 SVTy->getNumElements() == DVTy->getNumElements();
2108 return SrcTy->isInteger() && DstTy->isFloatingPoint();
2109 case Instruction::FPToUI:
2110 case Instruction::FPToSI:
2111 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2112 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2113 return SVTy->getElementType()->isFloatingPoint() &&
2114 DVTy->getElementType()->isInteger() &&
2115 SVTy->getNumElements() == DVTy->getNumElements();
2118 return SrcTy->isFloatingPoint() && DstTy->isInteger();
2119 case Instruction::PtrToInt:
2120 return isa<PointerType>(SrcTy) && DstTy->isInteger();
2121 case Instruction::IntToPtr:
2122 return SrcTy->isInteger() && isa<PointerType>(DstTy);
2123 case Instruction::BitCast:
2124 // BitCast implies a no-op cast of type only. No bits change.
2125 // However, you can't cast pointers to anything but pointers.
2126 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2129 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2130 // these cases, the cast is okay if the source and destination bit widths
2132 return SrcBitSize == DstBitSize;
2136 TruncInst::TruncInst(
2137 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2138 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2139 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2142 TruncInst::TruncInst(
2143 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2144 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2145 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2149 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2150 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2151 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2155 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2156 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2157 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2160 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2161 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2162 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2166 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2167 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2168 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2171 FPTruncInst::FPTruncInst(
2172 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2173 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2174 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2177 FPTruncInst::FPTruncInst(
2178 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2179 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2180 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2183 FPExtInst::FPExtInst(
2184 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2185 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2186 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2189 FPExtInst::FPExtInst(
2190 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2191 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2192 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2195 UIToFPInst::UIToFPInst(
2196 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2197 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2198 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2201 UIToFPInst::UIToFPInst(
2202 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2203 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2204 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2207 SIToFPInst::SIToFPInst(
2208 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2209 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2210 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2213 SIToFPInst::SIToFPInst(
2214 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2215 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2216 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2219 FPToUIInst::FPToUIInst(
2220 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2221 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2222 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2225 FPToUIInst::FPToUIInst(
2226 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2227 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2228 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2231 FPToSIInst::FPToSIInst(
2232 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2233 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2234 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2237 FPToSIInst::FPToSIInst(
2238 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2239 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2240 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2243 PtrToIntInst::PtrToIntInst(
2244 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2245 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2246 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2249 PtrToIntInst::PtrToIntInst(
2250 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2251 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2252 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2255 IntToPtrInst::IntToPtrInst(
2256 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2257 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2258 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2261 IntToPtrInst::IntToPtrInst(
2262 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2263 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2264 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2267 BitCastInst::BitCastInst(
2268 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2269 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2270 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2273 BitCastInst::BitCastInst(
2274 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2275 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2276 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2279 //===----------------------------------------------------------------------===//
2281 //===----------------------------------------------------------------------===//
2283 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2284 const std::string &Name, Instruction *InsertBefore)
2285 : Instruction(Type::Int1Ty, op, Ops, 2, InsertBefore) {
2286 Ops[0].init(LHS, this);
2287 Ops[1].init(RHS, this);
2288 SubclassData = predicate;
2290 if (op == Instruction::ICmp) {
2291 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2292 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2293 "Invalid ICmp predicate value");
2294 const Type* Op0Ty = getOperand(0)->getType();
2295 const Type* Op1Ty = getOperand(1)->getType();
2296 assert(Op0Ty == Op1Ty &&
2297 "Both operands to ICmp instruction are not of the same type!");
2298 // Check that the operands are the right type
2299 assert((Op0Ty->isInteger() || isa<PointerType>(Op0Ty)) &&
2300 "Invalid operand types for ICmp instruction");
2303 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2304 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2305 "Invalid FCmp predicate value");
2306 const Type* Op0Ty = getOperand(0)->getType();
2307 const Type* Op1Ty = getOperand(1)->getType();
2308 assert(Op0Ty == Op1Ty &&
2309 "Both operands to FCmp instruction are not of the same type!");
2310 // Check that the operands are the right type
2311 assert(Op0Ty->isFloatingPoint() &&
2312 "Invalid operand types for FCmp instruction");
2315 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2316 const std::string &Name, BasicBlock *InsertAtEnd)
2317 : Instruction(Type::Int1Ty, op, Ops, 2, InsertAtEnd) {
2318 Ops[0].init(LHS, this);
2319 Ops[1].init(RHS, this);
2320 SubclassData = predicate;
2322 if (op == Instruction::ICmp) {
2323 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2324 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2325 "Invalid ICmp predicate value");
2327 const Type* Op0Ty = getOperand(0)->getType();
2328 const Type* Op1Ty = getOperand(1)->getType();
2329 assert(Op0Ty == Op1Ty &&
2330 "Both operands to ICmp instruction are not of the same type!");
2331 // Check that the operands are the right type
2332 assert(Op0Ty->isInteger() || isa<PointerType>(Op0Ty) &&
2333 "Invalid operand types for ICmp instruction");
2336 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2337 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2338 "Invalid FCmp predicate value");
2339 const Type* Op0Ty = getOperand(0)->getType();
2340 const Type* Op1Ty = getOperand(1)->getType();
2341 assert(Op0Ty == Op1Ty &&
2342 "Both operands to FCmp instruction are not of the same type!");
2343 // Check that the operands are the right type
2344 assert(Op0Ty->isFloatingPoint() &&
2345 "Invalid operand types for FCmp instruction");
2349 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2350 const std::string &Name, Instruction *InsertBefore) {
2351 if (Op == Instruction::ICmp) {
2352 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2355 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2360 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2361 const std::string &Name, BasicBlock *InsertAtEnd) {
2362 if (Op == Instruction::ICmp) {
2363 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2366 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2370 void CmpInst::swapOperands() {
2371 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2374 cast<FCmpInst>(this)->swapOperands();
2377 bool CmpInst::isCommutative() {
2378 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2379 return IC->isCommutative();
2380 return cast<FCmpInst>(this)->isCommutative();
2383 bool CmpInst::isEquality() {
2384 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2385 return IC->isEquality();
2386 return cast<FCmpInst>(this)->isEquality();
2390 ICmpInst::Predicate ICmpInst::getInversePredicate(Predicate pred) {
2393 assert(!"Unknown icmp predicate!");
2394 case ICMP_EQ: return ICMP_NE;
2395 case ICMP_NE: return ICMP_EQ;
2396 case ICMP_UGT: return ICMP_ULE;
2397 case ICMP_ULT: return ICMP_UGE;
2398 case ICMP_UGE: return ICMP_ULT;
2399 case ICMP_ULE: return ICMP_UGT;
2400 case ICMP_SGT: return ICMP_SLE;
2401 case ICMP_SLT: return ICMP_SGE;
2402 case ICMP_SGE: return ICMP_SLT;
2403 case ICMP_SLE: return ICMP_SGT;
2407 ICmpInst::Predicate ICmpInst::getSwappedPredicate(Predicate pred) {
2409 default: assert(! "Unknown icmp predicate!");
2410 case ICMP_EQ: case ICMP_NE:
2412 case ICMP_SGT: return ICMP_SLT;
2413 case ICMP_SLT: return ICMP_SGT;
2414 case ICMP_SGE: return ICMP_SLE;
2415 case ICMP_SLE: return ICMP_SGE;
2416 case ICMP_UGT: return ICMP_ULT;
2417 case ICMP_ULT: return ICMP_UGT;
2418 case ICMP_UGE: return ICMP_ULE;
2419 case ICMP_ULE: return ICMP_UGE;
2423 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2425 default: assert(! "Unknown icmp predicate!");
2426 case ICMP_EQ: case ICMP_NE:
2427 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2429 case ICMP_UGT: return ICMP_SGT;
2430 case ICMP_ULT: return ICMP_SLT;
2431 case ICMP_UGE: return ICMP_SGE;
2432 case ICMP_ULE: return ICMP_SLE;
2436 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2438 default: assert(! "Unknown icmp predicate!");
2439 case ICMP_EQ: case ICMP_NE:
2440 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2442 case ICMP_SGT: return ICMP_UGT;
2443 case ICMP_SLT: return ICMP_ULT;
2444 case ICMP_SGE: return ICMP_UGE;
2445 case ICMP_SLE: return ICMP_ULE;
2449 bool ICmpInst::isSignedPredicate(Predicate pred) {
2451 default: assert(! "Unknown icmp predicate!");
2452 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2454 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2455 case ICMP_UGE: case ICMP_ULE:
2460 /// Initialize a set of values that all satisfy the condition with C.
2463 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2466 uint32_t BitWidth = C.getBitWidth();
2468 default: assert(0 && "Invalid ICmp opcode to ConstantRange ctor!");
2469 case ICmpInst::ICMP_EQ: Upper++; break;
2470 case ICmpInst::ICMP_NE: Lower++; break;
2471 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2472 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2473 case ICmpInst::ICMP_UGT:
2474 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2476 case ICmpInst::ICMP_SGT:
2477 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2479 case ICmpInst::ICMP_ULE:
2480 Lower = APInt::getMinValue(BitWidth); Upper++;
2482 case ICmpInst::ICMP_SLE:
2483 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2485 case ICmpInst::ICMP_UGE:
2486 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2488 case ICmpInst::ICMP_SGE:
2489 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2492 return ConstantRange(Lower, Upper);
2495 FCmpInst::Predicate FCmpInst::getInversePredicate(Predicate pred) {
2498 assert(!"Unknown icmp predicate!");
2499 case FCMP_OEQ: return FCMP_UNE;
2500 case FCMP_ONE: return FCMP_UEQ;
2501 case FCMP_OGT: return FCMP_ULE;
2502 case FCMP_OLT: return FCMP_UGE;
2503 case FCMP_OGE: return FCMP_ULT;
2504 case FCMP_OLE: return FCMP_UGT;
2505 case FCMP_UEQ: return FCMP_ONE;
2506 case FCMP_UNE: return FCMP_OEQ;
2507 case FCMP_UGT: return FCMP_OLE;
2508 case FCMP_ULT: return FCMP_OGE;
2509 case FCMP_UGE: return FCMP_OLT;
2510 case FCMP_ULE: return FCMP_OGT;
2511 case FCMP_ORD: return FCMP_UNO;
2512 case FCMP_UNO: return FCMP_ORD;
2513 case FCMP_TRUE: return FCMP_FALSE;
2514 case FCMP_FALSE: return FCMP_TRUE;
2518 FCmpInst::Predicate FCmpInst::getSwappedPredicate(Predicate pred) {
2520 default: assert(!"Unknown fcmp predicate!");
2521 case FCMP_FALSE: case FCMP_TRUE:
2522 case FCMP_OEQ: case FCMP_ONE:
2523 case FCMP_UEQ: case FCMP_UNE:
2524 case FCMP_ORD: case FCMP_UNO:
2526 case FCMP_OGT: return FCMP_OLT;
2527 case FCMP_OLT: return FCMP_OGT;
2528 case FCMP_OGE: return FCMP_OLE;
2529 case FCMP_OLE: return FCMP_OGE;
2530 case FCMP_UGT: return FCMP_ULT;
2531 case FCMP_ULT: return FCMP_UGT;
2532 case FCMP_UGE: return FCMP_ULE;
2533 case FCMP_ULE: return FCMP_UGE;
2537 bool CmpInst::isUnsigned(unsigned short predicate) {
2538 switch (predicate) {
2539 default: return false;
2540 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2541 case ICmpInst::ICMP_UGE: return true;
2545 bool CmpInst::isSigned(unsigned short predicate){
2546 switch (predicate) {
2547 default: return false;
2548 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2549 case ICmpInst::ICMP_SGE: return true;
2553 bool CmpInst::isOrdered(unsigned short predicate) {
2554 switch (predicate) {
2555 default: return false;
2556 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2557 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2558 case FCmpInst::FCMP_ORD: return true;
2562 bool CmpInst::isUnordered(unsigned short predicate) {
2563 switch (predicate) {
2564 default: return false;
2565 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2566 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2567 case FCmpInst::FCMP_UNO: return true;
2571 //===----------------------------------------------------------------------===//
2572 // SwitchInst Implementation
2573 //===----------------------------------------------------------------------===//
2575 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2576 assert(Value && Default);
2577 ReservedSpace = 2+NumCases*2;
2579 OperandList = new Use[ReservedSpace];
2581 OperandList[0].init(Value, this);
2582 OperandList[1].init(Default, this);
2585 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2586 /// switch on and a default destination. The number of additional cases can
2587 /// be specified here to make memory allocation more efficient. This
2588 /// constructor can also autoinsert before another instruction.
2589 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2590 Instruction *InsertBefore)
2591 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) {
2592 init(Value, Default, NumCases);
2595 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2596 /// switch on and a default destination. The number of additional cases can
2597 /// be specified here to make memory allocation more efficient. This
2598 /// constructor also autoinserts at the end of the specified BasicBlock.
2599 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2600 BasicBlock *InsertAtEnd)
2601 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) {
2602 init(Value, Default, NumCases);
2605 SwitchInst::SwitchInst(const SwitchInst &SI)
2606 : TerminatorInst(Type::VoidTy, Instruction::Switch,
2607 new Use[SI.getNumOperands()], SI.getNumOperands()) {
2608 Use *OL = OperandList, *InOL = SI.OperandList;
2609 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2610 OL[i].init(InOL[i], this);
2611 OL[i+1].init(InOL[i+1], this);
2615 SwitchInst::~SwitchInst() {
2616 delete [] OperandList;
2620 /// addCase - Add an entry to the switch instruction...
2622 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2623 unsigned OpNo = NumOperands;
2624 if (OpNo+2 > ReservedSpace)
2625 resizeOperands(0); // Get more space!
2626 // Initialize some new operands.
2627 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2628 NumOperands = OpNo+2;
2629 OperandList[OpNo].init(OnVal, this);
2630 OperandList[OpNo+1].init(Dest, this);
2633 /// removeCase - This method removes the specified successor from the switch
2634 /// instruction. Note that this cannot be used to remove the default
2635 /// destination (successor #0).
2637 void SwitchInst::removeCase(unsigned idx) {
2638 assert(idx != 0 && "Cannot remove the default case!");
2639 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2641 unsigned NumOps = getNumOperands();
2642 Use *OL = OperandList;
2644 // Move everything after this operand down.
2646 // FIXME: we could just swap with the end of the list, then erase. However,
2647 // client might not expect this to happen. The code as it is thrashes the
2648 // use/def lists, which is kinda lame.
2649 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2651 OL[i-2+1] = OL[i+1];
2654 // Nuke the last value.
2655 OL[NumOps-2].set(0);
2656 OL[NumOps-2+1].set(0);
2657 NumOperands = NumOps-2;
2660 /// resizeOperands - resize operands - This adjusts the length of the operands
2661 /// list according to the following behavior:
2662 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2663 /// of operation. This grows the number of ops by 1.5 times.
2664 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2665 /// 3. If NumOps == NumOperands, trim the reserved space.
2667 void SwitchInst::resizeOperands(unsigned NumOps) {
2669 NumOps = getNumOperands()/2*6;
2670 } else if (NumOps*2 > NumOperands) {
2671 // No resize needed.
2672 if (ReservedSpace >= NumOps) return;
2673 } else if (NumOps == NumOperands) {
2674 if (ReservedSpace == NumOps) return;
2679 ReservedSpace = NumOps;
2680 Use *NewOps = new Use[NumOps];
2681 Use *OldOps = OperandList;
2682 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2683 NewOps[i].init(OldOps[i], this);
2687 OperandList = NewOps;
2691 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2692 return getSuccessor(idx);
2694 unsigned SwitchInst::getNumSuccessorsV() const {
2695 return getNumSuccessors();
2697 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2698 setSuccessor(idx, B);
2702 // Define these methods here so vtables don't get emitted into every translation
2703 // unit that uses these classes.
2705 GetElementPtrInst *GetElementPtrInst::clone() const {
2706 return new GetElementPtrInst(*this);
2709 BinaryOperator *BinaryOperator::clone() const {
2710 return create(getOpcode(), Ops[0], Ops[1]);
2713 FCmpInst* FCmpInst::clone() const {
2714 return new FCmpInst(getPredicate(), Ops[0], Ops[1]);
2716 ICmpInst* ICmpInst::clone() const {
2717 return new ICmpInst(getPredicate(), Ops[0], Ops[1]);
2720 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
2721 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
2722 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
2723 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
2724 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
2725 CastInst *TruncInst::clone() const { return new TruncInst(*this); }
2726 CastInst *ZExtInst::clone() const { return new ZExtInst(*this); }
2727 CastInst *SExtInst::clone() const { return new SExtInst(*this); }
2728 CastInst *FPTruncInst::clone() const { return new FPTruncInst(*this); }
2729 CastInst *FPExtInst::clone() const { return new FPExtInst(*this); }
2730 CastInst *UIToFPInst::clone() const { return new UIToFPInst(*this); }
2731 CastInst *SIToFPInst::clone() const { return new SIToFPInst(*this); }
2732 CastInst *FPToUIInst::clone() const { return new FPToUIInst(*this); }
2733 CastInst *FPToSIInst::clone() const { return new FPToSIInst(*this); }
2734 CastInst *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
2735 CastInst *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
2736 CastInst *BitCastInst::clone() const { return new BitCastInst(*this); }
2737 CallInst *CallInst::clone() const { return new CallInst(*this); }
2738 SelectInst *SelectInst::clone() const { return new SelectInst(*this); }
2739 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
2741 ExtractElementInst *ExtractElementInst::clone() const {
2742 return new ExtractElementInst(*this);
2744 InsertElementInst *InsertElementInst::clone() const {
2745 return new InsertElementInst(*this);
2747 ShuffleVectorInst *ShuffleVectorInst::clone() const {
2748 return new ShuffleVectorInst(*this);
2750 PHINode *PHINode::clone() const { return new PHINode(*this); }
2751 ReturnInst *ReturnInst::clone() const { return new ReturnInst(*this); }
2752 BranchInst *BranchInst::clone() const { return new BranchInst(*this); }
2753 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
2754 InvokeInst *InvokeInst::clone() const { return new InvokeInst(*this); }
2755 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
2756 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}