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.
196 // Otherwise if all of the incoming values are the same for the PHI, replace
197 // the PHI node with the incoming value.
200 bool HasUndefInput = false;
201 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
202 if (isa<UndefValue>(getIncomingValue(i))) {
203 HasUndefInput = true;
204 } else if (getIncomingValue(i) != this) { // Not the PHI node itself...
205 if (InVal && getIncomingValue(i) != InVal)
206 return 0; // Not the same, bail out.
208 InVal = getIncomingValue(i);
211 // The only case that could cause InVal to be null is if we have a PHI node
212 // that only has entries for itself. In this case, there is no entry into the
213 // loop, so kill the PHI.
215 if (InVal == 0) InVal = UndefValue::get(getType());
217 // If we have a PHI node like phi(X, undef, X), where X is defined by some
218 // instruction, we cannot always return X as the result of the PHI node. Only
219 // do this if X is not an instruction (thus it must dominate the PHI block),
220 // or if the client is prepared to deal with this possibility.
221 if (HasUndefInput && !AllowNonDominatingInstruction)
222 if (Instruction *IV = dyn_cast<Instruction>(InVal))
223 // If it's in the entry block, it dominates everything.
224 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
226 return 0; // Cannot guarantee that InVal dominates this PHINode.
228 // All of the incoming values are the same, return the value now.
233 //===----------------------------------------------------------------------===//
234 // CallInst Implementation
235 //===----------------------------------------------------------------------===//
237 CallInst::~CallInst() {
238 delete [] OperandList;
240 ParamAttrs->dropRef();
243 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
245 NumOperands = NumParams+1;
246 Use *OL = OperandList = new Use[NumParams+1];
247 OL[0].init(Func, this);
249 const FunctionType *FTy =
250 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
251 FTy = FTy; // silence warning.
253 assert((NumParams == FTy->getNumParams() ||
254 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
255 "Calling a function with bad signature!");
256 for (unsigned i = 0; i != NumParams; ++i) {
257 assert((i >= FTy->getNumParams() ||
258 FTy->getParamType(i) == Params[i]->getType()) &&
259 "Calling a function with a bad signature!");
260 OL[i+1].init(Params[i], this);
264 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
267 Use *OL = OperandList = new Use[3];
268 OL[0].init(Func, this);
269 OL[1].init(Actual1, this);
270 OL[2].init(Actual2, this);
272 const FunctionType *FTy =
273 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
274 FTy = FTy; // silence warning.
276 assert((FTy->getNumParams() == 2 ||
277 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
278 "Calling a function with bad signature");
279 assert((0 >= FTy->getNumParams() ||
280 FTy->getParamType(0) == Actual1->getType()) &&
281 "Calling a function with a bad signature!");
282 assert((1 >= FTy->getNumParams() ||
283 FTy->getParamType(1) == Actual2->getType()) &&
284 "Calling a function with a bad signature!");
287 void CallInst::init(Value *Func, Value *Actual) {
290 Use *OL = OperandList = new Use[2];
291 OL[0].init(Func, this);
292 OL[1].init(Actual, this);
294 const FunctionType *FTy =
295 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
296 FTy = FTy; // silence warning.
298 assert((FTy->getNumParams() == 1 ||
299 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
300 "Calling a function with bad signature");
301 assert((0 == FTy->getNumParams() ||
302 FTy->getParamType(0) == Actual->getType()) &&
303 "Calling a function with a bad signature!");
306 void CallInst::init(Value *Func) {
309 Use *OL = OperandList = new Use[1];
310 OL[0].init(Func, this);
312 const FunctionType *FTy =
313 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
314 FTy = FTy; // silence warning.
316 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
319 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
320 Instruction *InsertBefore)
321 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
322 ->getElementType())->getReturnType(),
323 Instruction::Call, 0, 0, InsertBefore) {
328 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
329 BasicBlock *InsertAtEnd)
330 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
331 ->getElementType())->getReturnType(),
332 Instruction::Call, 0, 0, InsertAtEnd) {
336 CallInst::CallInst(Value *Func, const std::string &Name,
337 Instruction *InsertBefore)
338 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
339 ->getElementType())->getReturnType(),
340 Instruction::Call, 0, 0, InsertBefore) {
345 CallInst::CallInst(Value *Func, const std::string &Name,
346 BasicBlock *InsertAtEnd)
347 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
348 ->getElementType())->getReturnType(),
349 Instruction::Call, 0, 0, InsertAtEnd) {
354 CallInst::CallInst(const CallInst &CI)
355 : Instruction(CI.getType(), Instruction::Call, new Use[CI.getNumOperands()],
356 CI.getNumOperands()),
358 setParamAttrs(CI.getParamAttrs());
359 SubclassData = CI.SubclassData;
360 Use *OL = OperandList;
361 Use *InOL = CI.OperandList;
362 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
363 OL[i].init(InOL[i], this);
366 void CallInst::setParamAttrs(const ParamAttrsList *newAttrs) {
367 if (ParamAttrs == newAttrs)
371 ParamAttrs->dropRef();
376 ParamAttrs = newAttrs;
379 bool CallInst::paramHasAttr(uint16_t i, ParameterAttributes attr) const {
380 if (ParamAttrs && ParamAttrs->paramHasAttr(i, attr))
382 if (const Function *F = getCalledFunction())
383 return F->paramHasAttr(i, attr);
387 /// @brief Determine if the call does not access memory.
388 bool CallInst::doesNotAccessMemory() const {
389 return paramHasAttr(0, ParamAttr::ReadNone);
392 /// @brief Determine if the call does not access or only reads memory.
393 bool CallInst::onlyReadsMemory() const {
394 return doesNotAccessMemory() || paramHasAttr(0, ParamAttr::ReadOnly);
397 /// @brief Determine if the call cannot return.
398 bool CallInst::doesNotReturn() const {
399 return paramHasAttr(0, ParamAttr::NoReturn);
402 /// @brief Determine if the call cannot unwind.
403 bool CallInst::doesNotThrow() const {
404 return paramHasAttr(0, ParamAttr::NoUnwind);
407 /// @brief Determine if the call returns a structure.
408 bool CallInst::isStructReturn() const {
409 // Be friendly and also check the callee.
410 return paramHasAttr(1, ParamAttr::StructRet);
413 /// @brief Determine if any call argument is an aggregate passed by value.
414 bool CallInst::hasByValArgument() const {
415 if (ParamAttrs && ParamAttrs->hasAttrSomewhere(ParamAttr::ByVal))
417 // Be consistent with other methods and check the callee too.
418 if (const Function *F = getCalledFunction())
419 if (const ParamAttrsList *PAL = F->getParamAttrs())
420 return PAL->hasAttrSomewhere(ParamAttr::ByVal);
424 void CallInst::setDoesNotThrow(bool doesNotThrow) {
425 const ParamAttrsList *PAL = getParamAttrs();
427 PAL = ParamAttrsList::includeAttrs(PAL, 0, ParamAttr::NoUnwind);
429 PAL = ParamAttrsList::excludeAttrs(PAL, 0, ParamAttr::NoUnwind);
434 //===----------------------------------------------------------------------===//
435 // InvokeInst Implementation
436 //===----------------------------------------------------------------------===//
438 InvokeInst::~InvokeInst() {
439 delete [] OperandList;
441 ParamAttrs->dropRef();
444 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
445 Value* const *Args, unsigned NumArgs) {
447 NumOperands = 3+NumArgs;
448 Use *OL = OperandList = new Use[3+NumArgs];
449 OL[0].init(Fn, this);
450 OL[1].init(IfNormal, this);
451 OL[2].init(IfException, this);
452 const FunctionType *FTy =
453 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
454 FTy = FTy; // silence warning.
456 assert(((NumArgs == FTy->getNumParams()) ||
457 (FTy->isVarArg() && NumArgs > FTy->getNumParams())) &&
458 "Calling a function with bad signature");
460 for (unsigned i = 0, e = NumArgs; i != e; i++) {
461 assert((i >= FTy->getNumParams() ||
462 FTy->getParamType(i) == Args[i]->getType()) &&
463 "Invoking a function with a bad signature!");
465 OL[i+3].init(Args[i], this);
469 InvokeInst::InvokeInst(const InvokeInst &II)
470 : TerminatorInst(II.getType(), Instruction::Invoke,
471 new Use[II.getNumOperands()], II.getNumOperands()),
473 setParamAttrs(II.getParamAttrs());
474 SubclassData = II.SubclassData;
475 Use *OL = OperandList, *InOL = II.OperandList;
476 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
477 OL[i].init(InOL[i], this);
480 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
481 return getSuccessor(idx);
483 unsigned InvokeInst::getNumSuccessorsV() const {
484 return getNumSuccessors();
486 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
487 return setSuccessor(idx, B);
490 void InvokeInst::setParamAttrs(const ParamAttrsList *newAttrs) {
491 if (ParamAttrs == newAttrs)
495 ParamAttrs->dropRef();
500 ParamAttrs = newAttrs;
503 bool InvokeInst::paramHasAttr(uint16_t i, ParameterAttributes attr) const {
504 if (ParamAttrs && ParamAttrs->paramHasAttr(i, attr))
506 if (const Function *F = getCalledFunction())
507 return F->paramHasAttr(i, attr);
512 /// @brief Determine if the call does not access memory.
513 bool InvokeInst::doesNotAccessMemory() const {
514 return paramHasAttr(0, ParamAttr::ReadNone);
517 /// @brief Determine if the call does not access or only reads memory.
518 bool InvokeInst::onlyReadsMemory() const {
519 return doesNotAccessMemory() || paramHasAttr(0, ParamAttr::ReadOnly);
522 /// @brief Determine if the call cannot return.
523 bool InvokeInst::doesNotReturn() const {
524 return paramHasAttr(0, ParamAttr::NoReturn);
527 /// @brief Determine if the call cannot unwind.
528 bool InvokeInst::doesNotThrow() const {
529 return paramHasAttr(0, ParamAttr::NoUnwind);
532 void InvokeInst::setDoesNotThrow(bool doesNotThrow) {
533 const ParamAttrsList *PAL = getParamAttrs();
535 PAL = ParamAttrsList::includeAttrs(PAL, 0, ParamAttr::NoUnwind);
537 PAL = ParamAttrsList::excludeAttrs(PAL, 0, ParamAttr::NoUnwind);
541 /// @brief Determine if the call returns a structure.
542 bool InvokeInst::isStructReturn() const {
543 // Be friendly and also check the callee.
544 return paramHasAttr(1, ParamAttr::StructRet);
548 //===----------------------------------------------------------------------===//
549 // ReturnInst Implementation
550 //===----------------------------------------------------------------------===//
552 ReturnInst::ReturnInst(const ReturnInst &RI)
553 : TerminatorInst(Type::VoidTy, Instruction::Ret,
554 &RetVal, RI.getNumOperands()) {
555 if (RI.getNumOperands())
556 RetVal.init(RI.RetVal, this);
559 ReturnInst::ReturnInst(Value *retVal, Instruction *InsertBefore)
560 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertBefore) {
563 ReturnInst::ReturnInst(Value *retVal, BasicBlock *InsertAtEnd)
564 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertAtEnd) {
567 ReturnInst::ReturnInst(BasicBlock *InsertAtEnd)
568 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertAtEnd) {
573 void ReturnInst::init(Value *retVal) {
574 if (retVal && retVal->getType() != Type::VoidTy) {
575 assert(!isa<BasicBlock>(retVal) &&
576 "Cannot return basic block. Probably using the incorrect ctor");
578 RetVal.init(retVal, this);
582 unsigned ReturnInst::getNumSuccessorsV() const {
583 return getNumSuccessors();
586 // Out-of-line ReturnInst method, put here so the C++ compiler can choose to
587 // emit the vtable for the class in this translation unit.
588 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
589 assert(0 && "ReturnInst has no successors!");
592 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
593 assert(0 && "ReturnInst has no successors!");
599 //===----------------------------------------------------------------------===//
600 // UnwindInst Implementation
601 //===----------------------------------------------------------------------===//
603 UnwindInst::UnwindInst(Instruction *InsertBefore)
604 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertBefore) {
606 UnwindInst::UnwindInst(BasicBlock *InsertAtEnd)
607 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertAtEnd) {
611 unsigned UnwindInst::getNumSuccessorsV() const {
612 return getNumSuccessors();
615 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
616 assert(0 && "UnwindInst has no successors!");
619 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
620 assert(0 && "UnwindInst has no successors!");
625 //===----------------------------------------------------------------------===//
626 // UnreachableInst Implementation
627 //===----------------------------------------------------------------------===//
629 UnreachableInst::UnreachableInst(Instruction *InsertBefore)
630 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertBefore) {
632 UnreachableInst::UnreachableInst(BasicBlock *InsertAtEnd)
633 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertAtEnd) {
636 unsigned UnreachableInst::getNumSuccessorsV() const {
637 return getNumSuccessors();
640 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
641 assert(0 && "UnwindInst has no successors!");
644 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
645 assert(0 && "UnwindInst has no successors!");
650 //===----------------------------------------------------------------------===//
651 // BranchInst Implementation
652 //===----------------------------------------------------------------------===//
654 void BranchInst::AssertOK() {
656 assert(getCondition()->getType() == Type::Int1Ty &&
657 "May only branch on boolean predicates!");
660 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
661 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 1, InsertBefore) {
662 assert(IfTrue != 0 && "Branch destination may not be null!");
663 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
665 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
666 Instruction *InsertBefore)
667 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 3, InsertBefore) {
668 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
669 Ops[1].init(reinterpret_cast<Value*>(IfFalse), this);
670 Ops[2].init(Cond, this);
676 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
677 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 1, InsertAtEnd) {
678 assert(IfTrue != 0 && "Branch destination may not be null!");
679 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
682 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
683 BasicBlock *InsertAtEnd)
684 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 3, InsertAtEnd) {
685 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
686 Ops[1].init(reinterpret_cast<Value*>(IfFalse), this);
687 Ops[2].init(Cond, this);
694 BranchInst::BranchInst(const BranchInst &BI) :
695 TerminatorInst(Type::VoidTy, Instruction::Br, Ops, BI.getNumOperands()) {
696 OperandList[0].init(BI.getOperand(0), this);
697 if (BI.getNumOperands() != 1) {
698 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
699 OperandList[1].init(BI.getOperand(1), this);
700 OperandList[2].init(BI.getOperand(2), this);
704 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
705 return getSuccessor(idx);
707 unsigned BranchInst::getNumSuccessorsV() const {
708 return getNumSuccessors();
710 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
711 setSuccessor(idx, B);
715 //===----------------------------------------------------------------------===//
716 // AllocationInst Implementation
717 //===----------------------------------------------------------------------===//
719 static Value *getAISize(Value *Amt) {
721 Amt = ConstantInt::get(Type::Int32Ty, 1);
723 assert(!isa<BasicBlock>(Amt) &&
724 "Passed basic block into allocation size parameter! Use other ctor");
725 assert(Amt->getType() == Type::Int32Ty &&
726 "Malloc/Allocation array size is not a 32-bit integer!");
731 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
732 unsigned Align, const std::string &Name,
733 Instruction *InsertBefore)
734 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
735 InsertBefore), Alignment(Align) {
736 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
737 assert(Ty != Type::VoidTy && "Cannot allocate void!");
741 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
742 unsigned Align, const std::string &Name,
743 BasicBlock *InsertAtEnd)
744 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
745 InsertAtEnd), Alignment(Align) {
746 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
747 assert(Ty != Type::VoidTy && "Cannot allocate void!");
751 // Out of line virtual method, so the vtable, etc has a home.
752 AllocationInst::~AllocationInst() {
755 bool AllocationInst::isArrayAllocation() const {
756 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
757 return CI->getZExtValue() != 1;
761 const Type *AllocationInst::getAllocatedType() const {
762 return getType()->getElementType();
765 AllocaInst::AllocaInst(const AllocaInst &AI)
766 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
767 Instruction::Alloca, AI.getAlignment()) {
770 MallocInst::MallocInst(const MallocInst &MI)
771 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
772 Instruction::Malloc, MI.getAlignment()) {
775 //===----------------------------------------------------------------------===//
776 // FreeInst Implementation
777 //===----------------------------------------------------------------------===//
779 void FreeInst::AssertOK() {
780 assert(isa<PointerType>(getOperand(0)->getType()) &&
781 "Can not free something of nonpointer type!");
784 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
785 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertBefore) {
789 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
790 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertAtEnd) {
795 //===----------------------------------------------------------------------===//
796 // LoadInst Implementation
797 //===----------------------------------------------------------------------===//
799 void LoadInst::AssertOK() {
800 assert(isa<PointerType>(getOperand(0)->getType()) &&
801 "Ptr must have pointer type.");
804 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
805 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
806 Load, Ptr, InsertBef) {
813 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
814 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
815 Load, Ptr, InsertAE) {
822 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
823 Instruction *InsertBef)
824 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
825 Load, Ptr, InsertBef) {
826 setVolatile(isVolatile);
832 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
833 unsigned Align, Instruction *InsertBef)
834 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
835 Load, Ptr, InsertBef) {
836 setVolatile(isVolatile);
842 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
843 unsigned Align, BasicBlock *InsertAE)
844 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
845 Load, Ptr, InsertAE) {
846 setVolatile(isVolatile);
852 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
853 BasicBlock *InsertAE)
854 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
855 Load, Ptr, InsertAE) {
856 setVolatile(isVolatile);
864 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
865 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
866 Load, Ptr, InsertBef) {
870 if (Name && Name[0]) setName(Name);
873 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
874 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
875 Load, Ptr, InsertAE) {
879 if (Name && Name[0]) setName(Name);
882 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
883 Instruction *InsertBef)
884 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
885 Load, Ptr, InsertBef) {
886 setVolatile(isVolatile);
889 if (Name && Name[0]) setName(Name);
892 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
893 BasicBlock *InsertAE)
894 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
895 Load, Ptr, InsertAE) {
896 setVolatile(isVolatile);
899 if (Name && Name[0]) setName(Name);
902 void LoadInst::setAlignment(unsigned Align) {
903 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
904 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
907 //===----------------------------------------------------------------------===//
908 // StoreInst Implementation
909 //===----------------------------------------------------------------------===//
911 void StoreInst::AssertOK() {
912 assert(isa<PointerType>(getOperand(1)->getType()) &&
913 "Ptr must have pointer type!");
914 assert(getOperand(0)->getType() ==
915 cast<PointerType>(getOperand(1)->getType())->getElementType()
916 && "Ptr must be a pointer to Val type!");
920 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
921 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
922 Ops[0].init(val, this);
923 Ops[1].init(addr, this);
929 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
930 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
931 Ops[0].init(val, this);
932 Ops[1].init(addr, this);
938 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
939 Instruction *InsertBefore)
940 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
941 Ops[0].init(val, this);
942 Ops[1].init(addr, this);
943 setVolatile(isVolatile);
948 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
949 unsigned Align, Instruction *InsertBefore)
950 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
951 Ops[0].init(val, this);
952 Ops[1].init(addr, this);
953 setVolatile(isVolatile);
958 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
959 unsigned Align, BasicBlock *InsertAtEnd)
960 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
961 Ops[0].init(val, this);
962 Ops[1].init(addr, this);
963 setVolatile(isVolatile);
968 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
969 BasicBlock *InsertAtEnd)
970 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
971 Ops[0].init(val, this);
972 Ops[1].init(addr, this);
973 setVolatile(isVolatile);
978 void StoreInst::setAlignment(unsigned Align) {
979 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
980 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
983 //===----------------------------------------------------------------------===//
984 // GetElementPtrInst Implementation
985 //===----------------------------------------------------------------------===//
987 static unsigned retrieveAddrSpace(const Value *Val) {
988 return cast<PointerType>(Val->getType())->getAddressSpace();
991 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx) {
992 NumOperands = 1+NumIdx;
993 Use *OL = OperandList = new Use[NumOperands];
994 OL[0].init(Ptr, this);
996 for (unsigned i = 0; i != NumIdx; ++i)
997 OL[i+1].init(Idx[i], this);
1000 void GetElementPtrInst::init(Value *Ptr, Value *Idx) {
1002 Use *OL = OperandList = new Use[2];
1003 OL[0].init(Ptr, this);
1004 OL[1].init(Idx, this);
1007 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1008 const std::string &Name, Instruction *InBe)
1009 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1010 retrieveAddrSpace(Ptr)),
1011 GetElementPtr, 0, 0, InBe) {
1016 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1017 const std::string &Name, BasicBlock *IAE)
1018 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1019 retrieveAddrSpace(Ptr)),
1020 GetElementPtr, 0, 0, IAE) {
1025 GetElementPtrInst::~GetElementPtrInst() {
1026 delete[] OperandList;
1029 // getIndexedType - Returns the type of the element that would be loaded with
1030 // a load instruction with the specified parameters.
1032 // A null type is returned if the indices are invalid for the specified
1035 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1038 bool AllowCompositeLeaf) {
1039 if (!isa<PointerType>(Ptr)) return 0; // Type isn't a pointer type!
1041 // Handle the special case of the empty set index set...
1043 if (AllowCompositeLeaf ||
1044 cast<PointerType>(Ptr)->getElementType()->isFirstClassType())
1045 return cast<PointerType>(Ptr)->getElementType();
1050 unsigned CurIdx = 0;
1051 while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
1052 if (NumIdx == CurIdx) {
1053 if (AllowCompositeLeaf || CT->isFirstClassType()) return Ptr;
1054 return 0; // Can't load a whole structure or array!?!?
1057 Value *Index = Idxs[CurIdx++];
1058 if (isa<PointerType>(CT) && CurIdx != 1)
1059 return 0; // Can only index into pointer types at the first index!
1060 if (!CT->indexValid(Index)) return 0;
1061 Ptr = CT->getTypeAtIndex(Index);
1063 // If the new type forwards to another type, then it is in the middle
1064 // of being refined to another type (and hence, may have dropped all
1065 // references to what it was using before). So, use the new forwarded
1067 if (const Type * Ty = Ptr->getForwardedType()) {
1071 return CurIdx == NumIdx ? Ptr : 0;
1074 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1075 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1076 if (!PTy) return 0; // Type isn't a pointer type!
1078 // Check the pointer index.
1079 if (!PTy->indexValid(Idx)) return 0;
1081 return PTy->getElementType();
1085 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1086 /// zeros. If so, the result pointer and the first operand have the same
1087 /// value, just potentially different types.
1088 bool GetElementPtrInst::hasAllZeroIndices() const {
1089 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1090 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1091 if (!CI->isZero()) return false;
1099 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1100 /// constant integers. If so, the result pointer and the first operand have
1101 /// a constant offset between them.
1102 bool GetElementPtrInst::hasAllConstantIndices() const {
1103 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1104 if (!isa<ConstantInt>(getOperand(i)))
1111 //===----------------------------------------------------------------------===//
1112 // ExtractElementInst Implementation
1113 //===----------------------------------------------------------------------===//
1115 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1116 const std::string &Name,
1117 Instruction *InsertBef)
1118 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1119 ExtractElement, Ops, 2, InsertBef) {
1120 assert(isValidOperands(Val, Index) &&
1121 "Invalid extractelement instruction operands!");
1122 Ops[0].init(Val, this);
1123 Ops[1].init(Index, this);
1127 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1128 const std::string &Name,
1129 Instruction *InsertBef)
1130 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1131 ExtractElement, Ops, 2, InsertBef) {
1132 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1133 assert(isValidOperands(Val, Index) &&
1134 "Invalid extractelement instruction operands!");
1135 Ops[0].init(Val, this);
1136 Ops[1].init(Index, this);
1141 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1142 const std::string &Name,
1143 BasicBlock *InsertAE)
1144 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1145 ExtractElement, Ops, 2, InsertAE) {
1146 assert(isValidOperands(Val, Index) &&
1147 "Invalid extractelement instruction operands!");
1149 Ops[0].init(Val, this);
1150 Ops[1].init(Index, this);
1154 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1155 const std::string &Name,
1156 BasicBlock *InsertAE)
1157 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1158 ExtractElement, Ops, 2, InsertAE) {
1159 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1160 assert(isValidOperands(Val, Index) &&
1161 "Invalid extractelement instruction operands!");
1163 Ops[0].init(Val, this);
1164 Ops[1].init(Index, this);
1169 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1170 if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty)
1176 //===----------------------------------------------------------------------===//
1177 // InsertElementInst Implementation
1178 //===----------------------------------------------------------------------===//
1180 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
1181 : Instruction(IE.getType(), InsertElement, Ops, 3) {
1182 Ops[0].init(IE.Ops[0], this);
1183 Ops[1].init(IE.Ops[1], this);
1184 Ops[2].init(IE.Ops[2], this);
1186 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1187 const std::string &Name,
1188 Instruction *InsertBef)
1189 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertBef) {
1190 assert(isValidOperands(Vec, Elt, Index) &&
1191 "Invalid insertelement instruction operands!");
1192 Ops[0].init(Vec, this);
1193 Ops[1].init(Elt, this);
1194 Ops[2].init(Index, this);
1198 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1199 const std::string &Name,
1200 Instruction *InsertBef)
1201 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertBef) {
1202 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1203 assert(isValidOperands(Vec, Elt, Index) &&
1204 "Invalid insertelement instruction operands!");
1205 Ops[0].init(Vec, this);
1206 Ops[1].init(Elt, this);
1207 Ops[2].init(Index, this);
1212 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1213 const std::string &Name,
1214 BasicBlock *InsertAE)
1215 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertAE) {
1216 assert(isValidOperands(Vec, Elt, Index) &&
1217 "Invalid insertelement instruction operands!");
1219 Ops[0].init(Vec, this);
1220 Ops[1].init(Elt, this);
1221 Ops[2].init(Index, this);
1225 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1226 const std::string &Name,
1227 BasicBlock *InsertAE)
1228 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertAE) {
1229 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1230 assert(isValidOperands(Vec, Elt, Index) &&
1231 "Invalid insertelement instruction operands!");
1233 Ops[0].init(Vec, this);
1234 Ops[1].init(Elt, this);
1235 Ops[2].init(Index, this);
1239 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1240 const Value *Index) {
1241 if (!isa<VectorType>(Vec->getType()))
1242 return false; // First operand of insertelement must be vector type.
1244 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1245 return false;// Second operand of insertelement must be vector element type.
1247 if (Index->getType() != Type::Int32Ty)
1248 return false; // Third operand of insertelement must be uint.
1253 //===----------------------------------------------------------------------===//
1254 // ShuffleVectorInst Implementation
1255 //===----------------------------------------------------------------------===//
1257 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
1258 : Instruction(SV.getType(), ShuffleVector, Ops, 3) {
1259 Ops[0].init(SV.Ops[0], this);
1260 Ops[1].init(SV.Ops[1], this);
1261 Ops[2].init(SV.Ops[2], this);
1264 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1265 const std::string &Name,
1266 Instruction *InsertBefore)
1267 : Instruction(V1->getType(), ShuffleVector, Ops, 3, InsertBefore) {
1268 assert(isValidOperands(V1, V2, Mask) &&
1269 "Invalid shuffle vector instruction operands!");
1270 Ops[0].init(V1, this);
1271 Ops[1].init(V2, this);
1272 Ops[2].init(Mask, this);
1276 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1277 const std::string &Name,
1278 BasicBlock *InsertAtEnd)
1279 : Instruction(V1->getType(), ShuffleVector, Ops, 3, InsertAtEnd) {
1280 assert(isValidOperands(V1, V2, Mask) &&
1281 "Invalid shuffle vector instruction operands!");
1283 Ops[0].init(V1, this);
1284 Ops[1].init(V2, this);
1285 Ops[2].init(Mask, this);
1289 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1290 const Value *Mask) {
1291 if (!isa<VectorType>(V1->getType())) return false;
1292 if (V1->getType() != V2->getType()) return false;
1293 if (!isa<VectorType>(Mask->getType()) ||
1294 cast<VectorType>(Mask->getType())->getElementType() != Type::Int32Ty ||
1295 cast<VectorType>(Mask->getType())->getNumElements() !=
1296 cast<VectorType>(V1->getType())->getNumElements())
1302 //===----------------------------------------------------------------------===//
1303 // BinaryOperator Class
1304 //===----------------------------------------------------------------------===//
1306 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1307 const Type *Ty, const std::string &Name,
1308 Instruction *InsertBefore)
1309 : Instruction(Ty, iType, Ops, 2, InsertBefore) {
1310 Ops[0].init(S1, this);
1311 Ops[1].init(S2, this);
1316 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1317 const Type *Ty, const std::string &Name,
1318 BasicBlock *InsertAtEnd)
1319 : Instruction(Ty, iType, Ops, 2, InsertAtEnd) {
1320 Ops[0].init(S1, this);
1321 Ops[1].init(S2, this);
1327 void BinaryOperator::init(BinaryOps iType) {
1328 Value *LHS = getOperand(0), *RHS = getOperand(1);
1329 LHS = LHS; RHS = RHS; // Silence warnings.
1330 assert(LHS->getType() == RHS->getType() &&
1331 "Binary operator operand types must match!");
1336 assert(getType() == LHS->getType() &&
1337 "Arithmetic operation should return same type as operands!");
1338 assert((getType()->isInteger() || getType()->isFloatingPoint() ||
1339 isa<VectorType>(getType())) &&
1340 "Tried to create an arithmetic operation on a non-arithmetic type!");
1344 assert(getType() == LHS->getType() &&
1345 "Arithmetic operation should return same type as operands!");
1346 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1347 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1348 "Incorrect operand type (not integer) for S/UDIV");
1351 assert(getType() == LHS->getType() &&
1352 "Arithmetic operation should return same type as operands!");
1353 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1354 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1355 && "Incorrect operand type (not floating point) for FDIV");
1359 assert(getType() == LHS->getType() &&
1360 "Arithmetic operation should return same type as operands!");
1361 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1362 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1363 "Incorrect operand type (not integer) for S/UREM");
1366 assert(getType() == LHS->getType() &&
1367 "Arithmetic operation should return same type as operands!");
1368 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1369 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1370 && "Incorrect operand type (not floating point) for FREM");
1375 assert(getType() == LHS->getType() &&
1376 "Shift operation should return same type as operands!");
1377 assert(getType()->isInteger() &&
1378 "Shift operation requires integer operands");
1382 assert(getType() == LHS->getType() &&
1383 "Logical operation should return same type as operands!");
1384 assert((getType()->isInteger() ||
1385 (isa<VectorType>(getType()) &&
1386 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1387 "Tried to create a logical operation on a non-integral type!");
1395 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1396 const std::string &Name,
1397 Instruction *InsertBefore) {
1398 assert(S1->getType() == S2->getType() &&
1399 "Cannot create binary operator with two operands of differing type!");
1400 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1403 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1404 const std::string &Name,
1405 BasicBlock *InsertAtEnd) {
1406 BinaryOperator *Res = create(Op, S1, S2, Name);
1407 InsertAtEnd->getInstList().push_back(Res);
1411 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1412 Instruction *InsertBefore) {
1413 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1414 return new BinaryOperator(Instruction::Sub,
1416 Op->getType(), Name, InsertBefore);
1419 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1420 BasicBlock *InsertAtEnd) {
1421 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1422 return new BinaryOperator(Instruction::Sub,
1424 Op->getType(), Name, InsertAtEnd);
1427 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1428 Instruction *InsertBefore) {
1430 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1431 C = ConstantInt::getAllOnesValue(PTy->getElementType());
1432 C = ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), C));
1434 C = ConstantInt::getAllOnesValue(Op->getType());
1437 return new BinaryOperator(Instruction::Xor, Op, C,
1438 Op->getType(), Name, InsertBefore);
1441 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1442 BasicBlock *InsertAtEnd) {
1444 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1445 // Create a vector of all ones values.
1446 Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType());
1448 ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1450 AllOnes = ConstantInt::getAllOnesValue(Op->getType());
1453 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1454 Op->getType(), Name, InsertAtEnd);
1458 // isConstantAllOnes - Helper function for several functions below
1459 static inline bool isConstantAllOnes(const Value *V) {
1460 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1461 return CI->isAllOnesValue();
1462 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1463 return CV->isAllOnesValue();
1467 bool BinaryOperator::isNeg(const Value *V) {
1468 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1469 if (Bop->getOpcode() == Instruction::Sub)
1470 return Bop->getOperand(0) ==
1471 ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1475 bool BinaryOperator::isNot(const Value *V) {
1476 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1477 return (Bop->getOpcode() == Instruction::Xor &&
1478 (isConstantAllOnes(Bop->getOperand(1)) ||
1479 isConstantAllOnes(Bop->getOperand(0))));
1483 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1484 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1485 return cast<BinaryOperator>(BinOp)->getOperand(1);
1488 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1489 return getNegArgument(const_cast<Value*>(BinOp));
1492 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1493 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1494 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1495 Value *Op0 = BO->getOperand(0);
1496 Value *Op1 = BO->getOperand(1);
1497 if (isConstantAllOnes(Op0)) return Op1;
1499 assert(isConstantAllOnes(Op1));
1503 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1504 return getNotArgument(const_cast<Value*>(BinOp));
1508 // swapOperands - Exchange the two operands to this instruction. This
1509 // instruction is safe to use on any binary instruction and does not
1510 // modify the semantics of the instruction. If the instruction is
1511 // order dependent (SetLT f.e.) the opcode is changed.
1513 bool BinaryOperator::swapOperands() {
1514 if (!isCommutative())
1515 return true; // Can't commute operands
1516 std::swap(Ops[0], Ops[1]);
1520 //===----------------------------------------------------------------------===//
1522 //===----------------------------------------------------------------------===//
1524 // Just determine if this cast only deals with integral->integral conversion.
1525 bool CastInst::isIntegerCast() const {
1526 switch (getOpcode()) {
1527 default: return false;
1528 case Instruction::ZExt:
1529 case Instruction::SExt:
1530 case Instruction::Trunc:
1532 case Instruction::BitCast:
1533 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1537 bool CastInst::isLosslessCast() const {
1538 // Only BitCast can be lossless, exit fast if we're not BitCast
1539 if (getOpcode() != Instruction::BitCast)
1542 // Identity cast is always lossless
1543 const Type* SrcTy = getOperand(0)->getType();
1544 const Type* DstTy = getType();
1548 // Pointer to pointer is always lossless.
1549 if (isa<PointerType>(SrcTy))
1550 return isa<PointerType>(DstTy);
1551 return false; // Other types have no identity values
1554 /// This function determines if the CastInst does not require any bits to be
1555 /// changed in order to effect the cast. Essentially, it identifies cases where
1556 /// no code gen is necessary for the cast, hence the name no-op cast. For
1557 /// example, the following are all no-op casts:
1558 /// # bitcast uint %X, int
1559 /// # bitcast uint* %x, sbyte*
1560 /// # bitcast vector< 2 x int > %x, vector< 4 x short>
1561 /// # ptrtoint uint* %x, uint ; on 32-bit plaforms only
1562 /// @brief Determine if a cast is a no-op.
1563 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1564 switch (getOpcode()) {
1566 assert(!"Invalid CastOp");
1567 case Instruction::Trunc:
1568 case Instruction::ZExt:
1569 case Instruction::SExt:
1570 case Instruction::FPTrunc:
1571 case Instruction::FPExt:
1572 case Instruction::UIToFP:
1573 case Instruction::SIToFP:
1574 case Instruction::FPToUI:
1575 case Instruction::FPToSI:
1576 return false; // These always modify bits
1577 case Instruction::BitCast:
1578 return true; // BitCast never modifies bits.
1579 case Instruction::PtrToInt:
1580 return IntPtrTy->getPrimitiveSizeInBits() ==
1581 getType()->getPrimitiveSizeInBits();
1582 case Instruction::IntToPtr:
1583 return IntPtrTy->getPrimitiveSizeInBits() ==
1584 getOperand(0)->getType()->getPrimitiveSizeInBits();
1588 /// This function determines if a pair of casts can be eliminated and what
1589 /// opcode should be used in the elimination. This assumes that there are two
1590 /// instructions like this:
1591 /// * %F = firstOpcode SrcTy %x to MidTy
1592 /// * %S = secondOpcode MidTy %F to DstTy
1593 /// The function returns a resultOpcode so these two casts can be replaced with:
1594 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1595 /// If no such cast is permited, the function returns 0.
1596 unsigned CastInst::isEliminableCastPair(
1597 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1598 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1600 // Define the 144 possibilities for these two cast instructions. The values
1601 // in this matrix determine what to do in a given situation and select the
1602 // case in the switch below. The rows correspond to firstOp, the columns
1603 // correspond to secondOp. In looking at the table below, keep in mind
1604 // the following cast properties:
1606 // Size Compare Source Destination
1607 // Operator Src ? Size Type Sign Type Sign
1608 // -------- ------------ ------------------- ---------------------
1609 // TRUNC > Integer Any Integral Any
1610 // ZEXT < Integral Unsigned Integer Any
1611 // SEXT < Integral Signed Integer Any
1612 // FPTOUI n/a FloatPt n/a Integral Unsigned
1613 // FPTOSI n/a FloatPt n/a Integral Signed
1614 // UITOFP n/a Integral Unsigned FloatPt n/a
1615 // SITOFP n/a Integral Signed FloatPt n/a
1616 // FPTRUNC > FloatPt n/a FloatPt n/a
1617 // FPEXT < FloatPt n/a FloatPt n/a
1618 // PTRTOINT n/a Pointer n/a Integral Unsigned
1619 // INTTOPTR n/a Integral Unsigned Pointer n/a
1620 // BITCONVERT = FirstClass n/a FirstClass n/a
1622 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1623 // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
1624 // into "fptoui double to ulong", but this loses information about the range
1625 // of the produced value (we no longer know the top-part is all zeros).
1626 // Further this conversion is often much more expensive for typical hardware,
1627 // and causes issues when building libgcc. We disallow fptosi+sext for the
1629 const unsigned numCastOps =
1630 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1631 static const uint8_t CastResults[numCastOps][numCastOps] = {
1632 // T F F U S F F P I B -+
1633 // R Z S P P I I T P 2 N T |
1634 // U E E 2 2 2 2 R E I T C +- secondOp
1635 // N X X U S F F N X N 2 V |
1636 // C T T I I P P C T T P T -+
1637 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1638 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1639 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1640 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1641 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1642 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1643 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1644 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1645 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1646 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1647 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1648 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1651 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1652 [secondOp-Instruction::CastOpsBegin];
1655 // categorically disallowed
1658 // allowed, use first cast's opcode
1661 // allowed, use second cast's opcode
1664 // no-op cast in second op implies firstOp as long as the DestTy
1666 if (DstTy->isInteger())
1670 // no-op cast in second op implies firstOp as long as the DestTy
1671 // is floating point
1672 if (DstTy->isFloatingPoint())
1676 // no-op cast in first op implies secondOp as long as the SrcTy
1678 if (SrcTy->isInteger())
1682 // no-op cast in first op implies secondOp as long as the SrcTy
1683 // is a floating point
1684 if (SrcTy->isFloatingPoint())
1688 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1689 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1690 unsigned MidSize = MidTy->getPrimitiveSizeInBits();
1691 if (MidSize >= PtrSize)
1692 return Instruction::BitCast;
1696 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1697 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1698 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1699 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1700 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1701 if (SrcSize == DstSize)
1702 return Instruction::BitCast;
1703 else if (SrcSize < DstSize)
1707 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1708 return Instruction::ZExt;
1710 // fpext followed by ftrunc is allowed if the bit size returned to is
1711 // the same as the original, in which case its just a bitcast
1713 return Instruction::BitCast;
1714 return 0; // If the types are not the same we can't eliminate it.
1716 // bitcast followed by ptrtoint is allowed as long as the bitcast
1717 // is a pointer to pointer cast.
1718 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1722 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1723 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1727 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1728 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1729 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1730 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1731 if (SrcSize <= PtrSize && SrcSize == DstSize)
1732 return Instruction::BitCast;
1736 // cast combination can't happen (error in input). This is for all cases
1737 // where the MidTy is not the same for the two cast instructions.
1738 assert(!"Invalid Cast Combination");
1741 assert(!"Error in CastResults table!!!");
1747 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1748 const std::string &Name, Instruction *InsertBefore) {
1749 // Construct and return the appropriate CastInst subclass
1751 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1752 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1753 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1754 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1755 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1756 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1757 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1758 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1759 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1760 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1761 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1762 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1764 assert(!"Invalid opcode provided");
1769 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1770 const std::string &Name, BasicBlock *InsertAtEnd) {
1771 // Construct and return the appropriate CastInst subclass
1773 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1774 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1775 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1776 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1777 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1778 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1779 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1780 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1781 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1782 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1783 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1784 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1786 assert(!"Invalid opcode provided");
1791 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1792 const std::string &Name,
1793 Instruction *InsertBefore) {
1794 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1795 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1796 return create(Instruction::ZExt, S, Ty, Name, InsertBefore);
1799 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1800 const std::string &Name,
1801 BasicBlock *InsertAtEnd) {
1802 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1803 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1804 return create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
1807 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1808 const std::string &Name,
1809 Instruction *InsertBefore) {
1810 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1811 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1812 return create(Instruction::SExt, S, Ty, Name, InsertBefore);
1815 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1816 const std::string &Name,
1817 BasicBlock *InsertAtEnd) {
1818 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1819 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1820 return create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
1823 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1824 const std::string &Name,
1825 Instruction *InsertBefore) {
1826 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1827 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1828 return create(Instruction::Trunc, S, Ty, Name, InsertBefore);
1831 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1832 const std::string &Name,
1833 BasicBlock *InsertAtEnd) {
1834 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1835 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1836 return create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
1839 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1840 const std::string &Name,
1841 BasicBlock *InsertAtEnd) {
1842 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1843 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1846 if (Ty->isInteger())
1847 return create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
1848 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1851 /// @brief Create a BitCast or a PtrToInt cast instruction
1852 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1853 const std::string &Name,
1854 Instruction *InsertBefore) {
1855 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1856 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1859 if (Ty->isInteger())
1860 return create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
1861 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1864 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1865 bool isSigned, const std::string &Name,
1866 Instruction *InsertBefore) {
1867 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1868 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1869 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1870 Instruction::CastOps opcode =
1871 (SrcBits == DstBits ? Instruction::BitCast :
1872 (SrcBits > DstBits ? Instruction::Trunc :
1873 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1874 return create(opcode, C, Ty, Name, InsertBefore);
1877 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1878 bool isSigned, const std::string &Name,
1879 BasicBlock *InsertAtEnd) {
1880 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1881 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1882 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1883 Instruction::CastOps opcode =
1884 (SrcBits == DstBits ? Instruction::BitCast :
1885 (SrcBits > DstBits ? Instruction::Trunc :
1886 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1887 return create(opcode, C, Ty, Name, InsertAtEnd);
1890 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1891 const std::string &Name,
1892 Instruction *InsertBefore) {
1893 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1895 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1896 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1897 Instruction::CastOps opcode =
1898 (SrcBits == DstBits ? Instruction::BitCast :
1899 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1900 return create(opcode, C, Ty, Name, InsertBefore);
1903 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1904 const std::string &Name,
1905 BasicBlock *InsertAtEnd) {
1906 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1908 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1909 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1910 Instruction::CastOps opcode =
1911 (SrcBits == DstBits ? Instruction::BitCast :
1912 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1913 return create(opcode, C, Ty, Name, InsertAtEnd);
1916 // Check whether it is valid to call getCastOpcode for these types.
1917 // This routine must be kept in sync with getCastOpcode.
1918 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
1919 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
1922 if (SrcTy == DestTy)
1925 // Get the bit sizes, we'll need these
1926 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1927 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1929 // Run through the possibilities ...
1930 if (DestTy->isInteger()) { // Casting to integral
1931 if (SrcTy->isInteger()) { // Casting from integral
1933 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1935 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1936 // Casting from vector
1937 return DestBits == PTy->getBitWidth();
1938 } else { // Casting from something else
1939 return isa<PointerType>(SrcTy);
1941 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
1942 if (SrcTy->isInteger()) { // Casting from integral
1944 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1946 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1947 // Casting from vector
1948 return DestBits == PTy->getBitWidth();
1949 } else { // Casting from something else
1952 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
1953 // Casting to vector
1954 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
1955 // Casting from vector
1956 return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
1957 } else { // Casting from something else
1958 return DestPTy->getBitWidth() == SrcBits;
1960 } else if (isa<PointerType>(DestTy)) { // Casting to pointer
1961 if (isa<PointerType>(SrcTy)) { // Casting from pointer
1963 } else if (SrcTy->isInteger()) { // Casting from integral
1965 } else { // Casting from something else
1968 } else { // Casting to something else
1973 // Provide a way to get a "cast" where the cast opcode is inferred from the
1974 // types and size of the operand. This, basically, is a parallel of the
1975 // logic in the castIsValid function below. This axiom should hold:
1976 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
1977 // should not assert in castIsValid. In other words, this produces a "correct"
1978 // casting opcode for the arguments passed to it.
1979 // This routine must be kept in sync with isCastable.
1980 Instruction::CastOps
1981 CastInst::getCastOpcode(
1982 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
1983 // Get the bit sizes, we'll need these
1984 const Type *SrcTy = Src->getType();
1985 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1986 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1988 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
1989 "Only first class types are castable!");
1991 // Run through the possibilities ...
1992 if (DestTy->isInteger()) { // Casting to integral
1993 if (SrcTy->isInteger()) { // Casting from integral
1994 if (DestBits < SrcBits)
1995 return Trunc; // int -> smaller int
1996 else if (DestBits > SrcBits) { // its an extension
1998 return SExt; // signed -> SEXT
2000 return ZExt; // unsigned -> ZEXT
2002 return BitCast; // Same size, No-op cast
2004 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2006 return FPToSI; // FP -> sint
2008 return FPToUI; // FP -> uint
2009 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2010 assert(DestBits == PTy->getBitWidth() &&
2011 "Casting vector to integer of different width");
2012 return BitCast; // Same size, no-op cast
2014 assert(isa<PointerType>(SrcTy) &&
2015 "Casting from a value that is not first-class type");
2016 return PtrToInt; // ptr -> int
2018 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2019 if (SrcTy->isInteger()) { // Casting from integral
2021 return SIToFP; // sint -> FP
2023 return UIToFP; // uint -> FP
2024 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2025 if (DestBits < SrcBits) {
2026 return FPTrunc; // FP -> smaller FP
2027 } else if (DestBits > SrcBits) {
2028 return FPExt; // FP -> larger FP
2030 return BitCast; // same size, no-op cast
2032 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2033 assert(DestBits == PTy->getBitWidth() &&
2034 "Casting vector to floating point of different width");
2035 return BitCast; // same size, no-op cast
2037 assert(0 && "Casting pointer or non-first class to float");
2039 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2040 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2041 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2042 "Casting vector to vector of different widths");
2043 return BitCast; // vector -> vector
2044 } else if (DestPTy->getBitWidth() == SrcBits) {
2045 return BitCast; // float/int -> vector
2047 assert(!"Illegal cast to vector (wrong type or size)");
2049 } else if (isa<PointerType>(DestTy)) {
2050 if (isa<PointerType>(SrcTy)) {
2051 return BitCast; // ptr -> ptr
2052 } else if (SrcTy->isInteger()) {
2053 return IntToPtr; // int -> ptr
2055 assert(!"Casting pointer to other than pointer or int");
2058 assert(!"Casting to type that is not first-class");
2061 // If we fall through to here we probably hit an assertion cast above
2062 // and assertions are not turned on. Anything we return is an error, so
2063 // BitCast is as good a choice as any.
2067 //===----------------------------------------------------------------------===//
2068 // CastInst SubClass Constructors
2069 //===----------------------------------------------------------------------===//
2071 /// Check that the construction parameters for a CastInst are correct. This
2072 /// could be broken out into the separate constructors but it is useful to have
2073 /// it in one place and to eliminate the redundant code for getting the sizes
2074 /// of the types involved.
2076 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2078 // Check for type sanity on the arguments
2079 const Type *SrcTy = S->getType();
2080 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
2083 // Get the size of the types in bits, we'll need this later
2084 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2085 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2087 // Switch on the opcode provided
2089 default: return false; // This is an input error
2090 case Instruction::Trunc:
2091 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize > DstBitSize;
2092 case Instruction::ZExt:
2093 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2094 case Instruction::SExt:
2095 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2096 case Instruction::FPTrunc:
2097 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2098 SrcBitSize > DstBitSize;
2099 case Instruction::FPExt:
2100 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2101 SrcBitSize < DstBitSize;
2102 case Instruction::UIToFP:
2103 case Instruction::SIToFP:
2104 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2105 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2106 return SVTy->getElementType()->isInteger() &&
2107 DVTy->getElementType()->isFloatingPoint() &&
2108 SVTy->getNumElements() == DVTy->getNumElements();
2111 return SrcTy->isInteger() && DstTy->isFloatingPoint();
2112 case Instruction::FPToUI:
2113 case Instruction::FPToSI:
2114 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2115 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2116 return SVTy->getElementType()->isFloatingPoint() &&
2117 DVTy->getElementType()->isInteger() &&
2118 SVTy->getNumElements() == DVTy->getNumElements();
2121 return SrcTy->isFloatingPoint() && DstTy->isInteger();
2122 case Instruction::PtrToInt:
2123 return isa<PointerType>(SrcTy) && DstTy->isInteger();
2124 case Instruction::IntToPtr:
2125 return SrcTy->isInteger() && isa<PointerType>(DstTy);
2126 case Instruction::BitCast:
2127 // BitCast implies a no-op cast of type only. No bits change.
2128 // However, you can't cast pointers to anything but pointers.
2129 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2132 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2133 // these cases, the cast is okay if the source and destination bit widths
2135 return SrcBitSize == DstBitSize;
2139 TruncInst::TruncInst(
2140 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2141 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2142 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2145 TruncInst::TruncInst(
2146 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2147 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2148 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2152 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2153 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2154 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2158 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2159 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2160 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2163 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2164 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2165 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2169 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2170 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2171 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2174 FPTruncInst::FPTruncInst(
2175 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2176 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2177 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2180 FPTruncInst::FPTruncInst(
2181 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2182 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2183 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2186 FPExtInst::FPExtInst(
2187 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2188 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2189 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2192 FPExtInst::FPExtInst(
2193 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2194 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2195 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2198 UIToFPInst::UIToFPInst(
2199 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2200 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2201 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2204 UIToFPInst::UIToFPInst(
2205 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2206 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2207 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2210 SIToFPInst::SIToFPInst(
2211 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2212 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2213 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2216 SIToFPInst::SIToFPInst(
2217 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2218 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2219 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2222 FPToUIInst::FPToUIInst(
2223 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2224 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2225 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2228 FPToUIInst::FPToUIInst(
2229 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2230 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2231 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2234 FPToSIInst::FPToSIInst(
2235 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2236 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2237 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2240 FPToSIInst::FPToSIInst(
2241 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2242 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2243 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2246 PtrToIntInst::PtrToIntInst(
2247 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2248 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2249 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2252 PtrToIntInst::PtrToIntInst(
2253 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2254 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2255 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2258 IntToPtrInst::IntToPtrInst(
2259 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2260 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2261 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2264 IntToPtrInst::IntToPtrInst(
2265 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2266 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2267 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2270 BitCastInst::BitCastInst(
2271 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2272 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2273 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2276 BitCastInst::BitCastInst(
2277 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2278 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2279 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2282 //===----------------------------------------------------------------------===//
2284 //===----------------------------------------------------------------------===//
2286 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2287 const std::string &Name, Instruction *InsertBefore)
2288 : Instruction(Type::Int1Ty, op, Ops, 2, InsertBefore) {
2289 Ops[0].init(LHS, this);
2290 Ops[1].init(RHS, this);
2291 SubclassData = predicate;
2293 if (op == Instruction::ICmp) {
2294 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2295 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2296 "Invalid ICmp predicate value");
2297 const Type* Op0Ty = getOperand(0)->getType();
2298 const Type* Op1Ty = getOperand(1)->getType();
2299 assert(Op0Ty == Op1Ty &&
2300 "Both operands to ICmp instruction are not of the same type!");
2301 // Check that the operands are the right type
2302 assert((Op0Ty->isInteger() || isa<PointerType>(Op0Ty)) &&
2303 "Invalid operand types for ICmp instruction");
2306 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2307 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2308 "Invalid FCmp predicate value");
2309 const Type* Op0Ty = getOperand(0)->getType();
2310 const Type* Op1Ty = getOperand(1)->getType();
2311 assert(Op0Ty == Op1Ty &&
2312 "Both operands to FCmp instruction are not of the same type!");
2313 // Check that the operands are the right type
2314 assert(Op0Ty->isFloatingPoint() &&
2315 "Invalid operand types for FCmp instruction");
2318 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2319 const std::string &Name, BasicBlock *InsertAtEnd)
2320 : Instruction(Type::Int1Ty, op, Ops, 2, InsertAtEnd) {
2321 Ops[0].init(LHS, this);
2322 Ops[1].init(RHS, this);
2323 SubclassData = predicate;
2325 if (op == Instruction::ICmp) {
2326 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2327 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2328 "Invalid ICmp predicate value");
2330 const Type* Op0Ty = getOperand(0)->getType();
2331 const Type* Op1Ty = getOperand(1)->getType();
2332 assert(Op0Ty == Op1Ty &&
2333 "Both operands to ICmp instruction are not of the same type!");
2334 // Check that the operands are the right type
2335 assert((Op0Ty->isInteger() || isa<PointerType>(Op0Ty)) &&
2336 "Invalid operand types for ICmp instruction");
2339 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2340 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2341 "Invalid FCmp predicate value");
2342 const Type* Op0Ty = getOperand(0)->getType();
2343 const Type* Op1Ty = getOperand(1)->getType();
2344 assert(Op0Ty == Op1Ty &&
2345 "Both operands to FCmp instruction are not of the same type!");
2346 // Check that the operands are the right type
2347 assert(Op0Ty->isFloatingPoint() &&
2348 "Invalid operand types for FCmp instruction");
2352 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2353 const std::string &Name, Instruction *InsertBefore) {
2354 if (Op == Instruction::ICmp) {
2355 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2358 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2363 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2364 const std::string &Name, BasicBlock *InsertAtEnd) {
2365 if (Op == Instruction::ICmp) {
2366 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2369 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2373 void CmpInst::swapOperands() {
2374 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2377 cast<FCmpInst>(this)->swapOperands();
2380 bool CmpInst::isCommutative() {
2381 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2382 return IC->isCommutative();
2383 return cast<FCmpInst>(this)->isCommutative();
2386 bool CmpInst::isEquality() {
2387 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2388 return IC->isEquality();
2389 return cast<FCmpInst>(this)->isEquality();
2393 ICmpInst::Predicate ICmpInst::getInversePredicate(Predicate pred) {
2396 assert(!"Unknown icmp predicate!");
2397 case ICMP_EQ: return ICMP_NE;
2398 case ICMP_NE: return ICMP_EQ;
2399 case ICMP_UGT: return ICMP_ULE;
2400 case ICMP_ULT: return ICMP_UGE;
2401 case ICMP_UGE: return ICMP_ULT;
2402 case ICMP_ULE: return ICMP_UGT;
2403 case ICMP_SGT: return ICMP_SLE;
2404 case ICMP_SLT: return ICMP_SGE;
2405 case ICMP_SGE: return ICMP_SLT;
2406 case ICMP_SLE: return ICMP_SGT;
2410 ICmpInst::Predicate ICmpInst::getSwappedPredicate(Predicate pred) {
2412 default: assert(! "Unknown icmp predicate!");
2413 case ICMP_EQ: case ICMP_NE:
2415 case ICMP_SGT: return ICMP_SLT;
2416 case ICMP_SLT: return ICMP_SGT;
2417 case ICMP_SGE: return ICMP_SLE;
2418 case ICMP_SLE: return ICMP_SGE;
2419 case ICMP_UGT: return ICMP_ULT;
2420 case ICMP_ULT: return ICMP_UGT;
2421 case ICMP_UGE: return ICMP_ULE;
2422 case ICMP_ULE: return ICMP_UGE;
2426 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2428 default: assert(! "Unknown icmp predicate!");
2429 case ICMP_EQ: case ICMP_NE:
2430 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2432 case ICMP_UGT: return ICMP_SGT;
2433 case ICMP_ULT: return ICMP_SLT;
2434 case ICMP_UGE: return ICMP_SGE;
2435 case ICMP_ULE: return ICMP_SLE;
2439 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2441 default: assert(! "Unknown icmp predicate!");
2442 case ICMP_EQ: case ICMP_NE:
2443 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2445 case ICMP_SGT: return ICMP_UGT;
2446 case ICMP_SLT: return ICMP_ULT;
2447 case ICMP_SGE: return ICMP_UGE;
2448 case ICMP_SLE: return ICMP_ULE;
2452 bool ICmpInst::isSignedPredicate(Predicate pred) {
2454 default: assert(! "Unknown icmp predicate!");
2455 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2457 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2458 case ICMP_UGE: case ICMP_ULE:
2463 /// Initialize a set of values that all satisfy the condition with C.
2466 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2469 uint32_t BitWidth = C.getBitWidth();
2471 default: assert(0 && "Invalid ICmp opcode to ConstantRange ctor!");
2472 case ICmpInst::ICMP_EQ: Upper++; break;
2473 case ICmpInst::ICMP_NE: Lower++; break;
2474 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2475 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2476 case ICmpInst::ICMP_UGT:
2477 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2479 case ICmpInst::ICMP_SGT:
2480 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2482 case ICmpInst::ICMP_ULE:
2483 Lower = APInt::getMinValue(BitWidth); Upper++;
2485 case ICmpInst::ICMP_SLE:
2486 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2488 case ICmpInst::ICMP_UGE:
2489 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2491 case ICmpInst::ICMP_SGE:
2492 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2495 return ConstantRange(Lower, Upper);
2498 FCmpInst::Predicate FCmpInst::getInversePredicate(Predicate pred) {
2501 assert(!"Unknown icmp predicate!");
2502 case FCMP_OEQ: return FCMP_UNE;
2503 case FCMP_ONE: return FCMP_UEQ;
2504 case FCMP_OGT: return FCMP_ULE;
2505 case FCMP_OLT: return FCMP_UGE;
2506 case FCMP_OGE: return FCMP_ULT;
2507 case FCMP_OLE: return FCMP_UGT;
2508 case FCMP_UEQ: return FCMP_ONE;
2509 case FCMP_UNE: return FCMP_OEQ;
2510 case FCMP_UGT: return FCMP_OLE;
2511 case FCMP_ULT: return FCMP_OGE;
2512 case FCMP_UGE: return FCMP_OLT;
2513 case FCMP_ULE: return FCMP_OGT;
2514 case FCMP_ORD: return FCMP_UNO;
2515 case FCMP_UNO: return FCMP_ORD;
2516 case FCMP_TRUE: return FCMP_FALSE;
2517 case FCMP_FALSE: return FCMP_TRUE;
2521 FCmpInst::Predicate FCmpInst::getSwappedPredicate(Predicate pred) {
2523 default: assert(!"Unknown fcmp predicate!");
2524 case FCMP_FALSE: case FCMP_TRUE:
2525 case FCMP_OEQ: case FCMP_ONE:
2526 case FCMP_UEQ: case FCMP_UNE:
2527 case FCMP_ORD: case FCMP_UNO:
2529 case FCMP_OGT: return FCMP_OLT;
2530 case FCMP_OLT: return FCMP_OGT;
2531 case FCMP_OGE: return FCMP_OLE;
2532 case FCMP_OLE: return FCMP_OGE;
2533 case FCMP_UGT: return FCMP_ULT;
2534 case FCMP_ULT: return FCMP_UGT;
2535 case FCMP_UGE: return FCMP_ULE;
2536 case FCMP_ULE: return FCMP_UGE;
2540 bool CmpInst::isUnsigned(unsigned short predicate) {
2541 switch (predicate) {
2542 default: return false;
2543 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2544 case ICmpInst::ICMP_UGE: return true;
2548 bool CmpInst::isSigned(unsigned short predicate){
2549 switch (predicate) {
2550 default: return false;
2551 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2552 case ICmpInst::ICMP_SGE: return true;
2556 bool CmpInst::isOrdered(unsigned short predicate) {
2557 switch (predicate) {
2558 default: return false;
2559 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2560 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2561 case FCmpInst::FCMP_ORD: return true;
2565 bool CmpInst::isUnordered(unsigned short predicate) {
2566 switch (predicate) {
2567 default: return false;
2568 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2569 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2570 case FCmpInst::FCMP_UNO: return true;
2574 //===----------------------------------------------------------------------===//
2575 // SwitchInst Implementation
2576 //===----------------------------------------------------------------------===//
2578 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2579 assert(Value && Default);
2580 ReservedSpace = 2+NumCases*2;
2582 OperandList = new Use[ReservedSpace];
2584 OperandList[0].init(Value, this);
2585 OperandList[1].init(Default, this);
2588 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2589 /// switch on and a default destination. The number of additional cases can
2590 /// be specified here to make memory allocation more efficient. This
2591 /// constructor can also autoinsert before another instruction.
2592 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2593 Instruction *InsertBefore)
2594 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) {
2595 init(Value, Default, NumCases);
2598 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2599 /// switch on and a default destination. The number of additional cases can
2600 /// be specified here to make memory allocation more efficient. This
2601 /// constructor also autoinserts at the end of the specified BasicBlock.
2602 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2603 BasicBlock *InsertAtEnd)
2604 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) {
2605 init(Value, Default, NumCases);
2608 SwitchInst::SwitchInst(const SwitchInst &SI)
2609 : TerminatorInst(Type::VoidTy, Instruction::Switch,
2610 new Use[SI.getNumOperands()], SI.getNumOperands()) {
2611 Use *OL = OperandList, *InOL = SI.OperandList;
2612 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2613 OL[i].init(InOL[i], this);
2614 OL[i+1].init(InOL[i+1], this);
2618 SwitchInst::~SwitchInst() {
2619 delete [] OperandList;
2623 /// addCase - Add an entry to the switch instruction...
2625 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2626 unsigned OpNo = NumOperands;
2627 if (OpNo+2 > ReservedSpace)
2628 resizeOperands(0); // Get more space!
2629 // Initialize some new operands.
2630 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2631 NumOperands = OpNo+2;
2632 OperandList[OpNo].init(OnVal, this);
2633 OperandList[OpNo+1].init(Dest, this);
2636 /// removeCase - This method removes the specified successor from the switch
2637 /// instruction. Note that this cannot be used to remove the default
2638 /// destination (successor #0).
2640 void SwitchInst::removeCase(unsigned idx) {
2641 assert(idx != 0 && "Cannot remove the default case!");
2642 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2644 unsigned NumOps = getNumOperands();
2645 Use *OL = OperandList;
2647 // Move everything after this operand down.
2649 // FIXME: we could just swap with the end of the list, then erase. However,
2650 // client might not expect this to happen. The code as it is thrashes the
2651 // use/def lists, which is kinda lame.
2652 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2654 OL[i-2+1] = OL[i+1];
2657 // Nuke the last value.
2658 OL[NumOps-2].set(0);
2659 OL[NumOps-2+1].set(0);
2660 NumOperands = NumOps-2;
2663 /// resizeOperands - resize operands - This adjusts the length of the operands
2664 /// list according to the following behavior:
2665 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2666 /// of operation. This grows the number of ops by 1.5 times.
2667 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2668 /// 3. If NumOps == NumOperands, trim the reserved space.
2670 void SwitchInst::resizeOperands(unsigned NumOps) {
2672 NumOps = getNumOperands()/2*6;
2673 } else if (NumOps*2 > NumOperands) {
2674 // No resize needed.
2675 if (ReservedSpace >= NumOps) return;
2676 } else if (NumOps == NumOperands) {
2677 if (ReservedSpace == NumOps) return;
2682 ReservedSpace = NumOps;
2683 Use *NewOps = new Use[NumOps];
2684 Use *OldOps = OperandList;
2685 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2686 NewOps[i].init(OldOps[i], this);
2690 OperandList = NewOps;
2694 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2695 return getSuccessor(idx);
2697 unsigned SwitchInst::getNumSuccessorsV() const {
2698 return getNumSuccessors();
2700 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2701 setSuccessor(idx, B);
2704 //===----------------------------------------------------------------------===//
2705 // GetResultInst Implementation
2706 //===----------------------------------------------------------------------===//
2708 GetResultInst::GetResultInst(Value *Aggregate, unsigned Index,
2709 const std::string &Name,
2710 Instruction *InsertBef)
2711 : Instruction(cast<StructType>(Aggregate->getType())->getElementType(Index),
2712 GetResult, &Aggr, 1, InsertBef) {
2713 assert(isValidOperands(Aggregate, Index) && "Invalid GetResultInst operands!");
2714 Aggr.init(Aggregate, this);
2719 bool GetResultInst::isValidOperands(const Value *Aggregate, unsigned Index) {
2722 if (const StructType *STy = dyn_cast<StructType>(Aggregate->getType()))
2723 if (Index < STy->getNumElements())
2730 // Define these methods here so vtables don't get emitted into every translation
2731 // unit that uses these classes.
2733 GetElementPtrInst *GetElementPtrInst::clone() const {
2734 return new GetElementPtrInst(*this);
2737 BinaryOperator *BinaryOperator::clone() const {
2738 return create(getOpcode(), Ops[0], Ops[1]);
2741 FCmpInst* FCmpInst::clone() const {
2742 return new FCmpInst(getPredicate(), Ops[0], Ops[1]);
2744 ICmpInst* ICmpInst::clone() const {
2745 return new ICmpInst(getPredicate(), Ops[0], Ops[1]);
2748 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
2749 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
2750 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
2751 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
2752 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
2753 CastInst *TruncInst::clone() const { return new TruncInst(*this); }
2754 CastInst *ZExtInst::clone() const { return new ZExtInst(*this); }
2755 CastInst *SExtInst::clone() const { return new SExtInst(*this); }
2756 CastInst *FPTruncInst::clone() const { return new FPTruncInst(*this); }
2757 CastInst *FPExtInst::clone() const { return new FPExtInst(*this); }
2758 CastInst *UIToFPInst::clone() const { return new UIToFPInst(*this); }
2759 CastInst *SIToFPInst::clone() const { return new SIToFPInst(*this); }
2760 CastInst *FPToUIInst::clone() const { return new FPToUIInst(*this); }
2761 CastInst *FPToSIInst::clone() const { return new FPToSIInst(*this); }
2762 CastInst *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
2763 CastInst *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
2764 CastInst *BitCastInst::clone() const { return new BitCastInst(*this); }
2765 CallInst *CallInst::clone() const { return new CallInst(*this); }
2766 SelectInst *SelectInst::clone() const { return new SelectInst(*this); }
2767 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
2769 ExtractElementInst *ExtractElementInst::clone() const {
2770 return new ExtractElementInst(*this);
2772 InsertElementInst *InsertElementInst::clone() const {
2773 return new InsertElementInst(*this);
2775 ShuffleVectorInst *ShuffleVectorInst::clone() const {
2776 return new ShuffleVectorInst(*this);
2778 PHINode *PHINode::clone() const { return new PHINode(*this); }
2779 ReturnInst *ReturnInst::clone() const { return new ReturnInst(*this); }
2780 BranchInst *BranchInst::clone() const { return new BranchInst(*this); }
2781 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
2782 InvokeInst *InvokeInst::clone() const { return new InvokeInst(*this); }
2783 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
2784 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}
2785 GetResultInst *GetResultInst::clone() const { return new GetResultInst(*this); }