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 unsigned CallSite::getCallingConv() const {
31 if (CallInst *CI = dyn_cast<CallInst>(I))
32 return CI->getCallingConv();
34 return cast<InvokeInst>(I)->getCallingConv();
36 void CallSite::setCallingConv(unsigned CC) {
37 if (CallInst *CI = dyn_cast<CallInst>(I))
38 CI->setCallingConv(CC);
40 cast<InvokeInst>(I)->setCallingConv(CC);
42 const ParamAttrsList* CallSite::getParamAttrs() const {
43 if (CallInst *CI = dyn_cast<CallInst>(I))
44 return CI->getParamAttrs();
46 return cast<InvokeInst>(I)->getParamAttrs();
48 void CallSite::setParamAttrs(const ParamAttrsList *PAL) {
49 if (CallInst *CI = dyn_cast<CallInst>(I))
50 CI->setParamAttrs(PAL);
52 cast<InvokeInst>(I)->setParamAttrs(PAL);
54 bool CallSite::paramHasAttr(uint16_t i, unsigned attr) const {
55 if (CallInst *CI = dyn_cast<CallInst>(I))
56 return CI->paramHasAttr(i, (ParameterAttributes)attr);
58 return cast<InvokeInst>(I)->paramHasAttr(i, (ParameterAttributes)attr);
60 bool CallSite::doesNotAccessMemory() const {
61 if (CallInst *CI = dyn_cast<CallInst>(I))
62 return CI->doesNotAccessMemory();
64 return cast<InvokeInst>(I)->doesNotAccessMemory();
66 bool CallSite::onlyReadsMemory() const {
67 if (CallInst *CI = dyn_cast<CallInst>(I))
68 return CI->onlyReadsMemory();
70 return cast<InvokeInst>(I)->onlyReadsMemory();
72 bool CallSite::doesNotThrow() const {
73 if (CallInst *CI = dyn_cast<CallInst>(I))
74 return CI->doesNotThrow();
76 return cast<InvokeInst>(I)->doesNotThrow();
78 void CallSite::setDoesNotThrow(bool doesNotThrow) {
79 if (CallInst *CI = dyn_cast<CallInst>(I))
80 CI->setDoesNotThrow(doesNotThrow);
82 cast<InvokeInst>(I)->setDoesNotThrow(doesNotThrow);
85 //===----------------------------------------------------------------------===//
86 // TerminatorInst Class
87 //===----------------------------------------------------------------------===//
89 // Out of line virtual method, so the vtable, etc has a home.
90 TerminatorInst::~TerminatorInst() {
93 // Out of line virtual method, so the vtable, etc has a home.
94 UnaryInstruction::~UnaryInstruction() {
98 //===----------------------------------------------------------------------===//
100 //===----------------------------------------------------------------------===//
102 PHINode::PHINode(const PHINode &PN)
103 : Instruction(PN.getType(), Instruction::PHI,
104 new Use[PN.getNumOperands()], PN.getNumOperands()),
105 ReservedSpace(PN.getNumOperands()) {
106 Use *OL = OperandList;
107 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
108 OL[i].init(PN.getOperand(i), this);
109 OL[i+1].init(PN.getOperand(i+1), this);
113 PHINode::~PHINode() {
114 delete [] OperandList;
117 // removeIncomingValue - Remove an incoming value. This is useful if a
118 // predecessor basic block is deleted.
119 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
120 unsigned NumOps = getNumOperands();
121 Use *OL = OperandList;
122 assert(Idx*2 < NumOps && "BB not in PHI node!");
123 Value *Removed = OL[Idx*2];
125 // Move everything after this operand down.
127 // FIXME: we could just swap with the end of the list, then erase. However,
128 // client might not expect this to happen. The code as it is thrashes the
129 // use/def lists, which is kinda lame.
130 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
135 // Nuke the last value.
137 OL[NumOps-2+1].set(0);
138 NumOperands = NumOps-2;
140 // If the PHI node is dead, because it has zero entries, nuke it now.
141 if (NumOps == 2 && DeletePHIIfEmpty) {
142 // If anyone is using this PHI, make them use a dummy value instead...
143 replaceAllUsesWith(UndefValue::get(getType()));
149 /// resizeOperands - resize operands - This adjusts the length of the operands
150 /// list according to the following behavior:
151 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
152 /// of operation. This grows the number of ops by 1.5 times.
153 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
154 /// 3. If NumOps == NumOperands, trim the reserved space.
156 void PHINode::resizeOperands(unsigned NumOps) {
158 NumOps = (getNumOperands())*3/2;
159 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
160 } else if (NumOps*2 > NumOperands) {
162 if (ReservedSpace >= NumOps) return;
163 } else if (NumOps == NumOperands) {
164 if (ReservedSpace == NumOps) return;
169 ReservedSpace = NumOps;
170 Use *NewOps = new Use[NumOps];
171 Use *OldOps = OperandList;
172 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
173 NewOps[i].init(OldOps[i], this);
177 OperandList = NewOps;
180 /// hasConstantValue - If the specified PHI node always merges together the same
181 /// value, return the value, otherwise return null.
183 Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) const {
184 // If the PHI node only has one incoming value, eliminate the PHI node...
185 if (getNumIncomingValues() == 1)
186 if (getIncomingValue(0) != this) // not X = phi X
187 return getIncomingValue(0);
189 return UndefValue::get(getType()); // Self cycle is dead.
191 // Otherwise if all of the incoming values are the same for the PHI, replace
192 // the PHI node with the incoming value.
195 bool HasUndefInput = false;
196 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
197 if (isa<UndefValue>(getIncomingValue(i)))
198 HasUndefInput = true;
199 else if (getIncomingValue(i) != this) // Not the PHI node itself...
200 if (InVal && getIncomingValue(i) != InVal)
201 return 0; // Not the same, bail out.
203 InVal = getIncomingValue(i);
205 // The only case that could cause InVal to be null is if we have a PHI node
206 // that only has entries for itself. In this case, there is no entry into the
207 // loop, so kill the PHI.
209 if (InVal == 0) InVal = UndefValue::get(getType());
211 // If we have a PHI node like phi(X, undef, X), where X is defined by some
212 // instruction, we cannot always return X as the result of the PHI node. Only
213 // do this if X is not an instruction (thus it must dominate the PHI block),
214 // or if the client is prepared to deal with this possibility.
215 if (HasUndefInput && !AllowNonDominatingInstruction)
216 if (Instruction *IV = dyn_cast<Instruction>(InVal))
217 // If it's in the entry block, it dominates everything.
218 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
220 return 0; // Cannot guarantee that InVal dominates this PHINode.
222 // All of the incoming values are the same, return the value now.
227 //===----------------------------------------------------------------------===//
228 // CallInst Implementation
229 //===----------------------------------------------------------------------===//
231 CallInst::~CallInst() {
232 delete [] OperandList;
234 ParamAttrs->dropRef();
237 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
239 NumOperands = NumParams+1;
240 Use *OL = OperandList = new Use[NumParams+1];
241 OL[0].init(Func, this);
243 const FunctionType *FTy =
244 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
245 FTy = FTy; // silence warning.
247 assert((NumParams == FTy->getNumParams() ||
248 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
249 "Calling a function with bad signature!");
250 for (unsigned i = 0; i != NumParams; ++i) {
251 assert((i >= FTy->getNumParams() ||
252 FTy->getParamType(i) == Params[i]->getType()) &&
253 "Calling a function with a bad signature!");
254 OL[i+1].init(Params[i], this);
258 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
261 Use *OL = OperandList = new Use[3];
262 OL[0].init(Func, this);
263 OL[1].init(Actual1, this);
264 OL[2].init(Actual2, this);
266 const FunctionType *FTy =
267 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
268 FTy = FTy; // silence warning.
270 assert((FTy->getNumParams() == 2 ||
271 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
272 "Calling a function with bad signature");
273 assert((0 >= FTy->getNumParams() ||
274 FTy->getParamType(0) == Actual1->getType()) &&
275 "Calling a function with a bad signature!");
276 assert((1 >= FTy->getNumParams() ||
277 FTy->getParamType(1) == Actual2->getType()) &&
278 "Calling a function with a bad signature!");
281 void CallInst::init(Value *Func, Value *Actual) {
284 Use *OL = OperandList = new Use[2];
285 OL[0].init(Func, this);
286 OL[1].init(Actual, this);
288 const FunctionType *FTy =
289 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
290 FTy = FTy; // silence warning.
292 assert((FTy->getNumParams() == 1 ||
293 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
294 "Calling a function with bad signature");
295 assert((0 == FTy->getNumParams() ||
296 FTy->getParamType(0) == Actual->getType()) &&
297 "Calling a function with a bad signature!");
300 void CallInst::init(Value *Func) {
303 Use *OL = OperandList = new Use[1];
304 OL[0].init(Func, this);
306 const FunctionType *FTy =
307 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
308 FTy = FTy; // silence warning.
310 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
313 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
314 Instruction *InsertBefore)
315 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
316 ->getElementType())->getReturnType(),
317 Instruction::Call, 0, 0, InsertBefore) {
322 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
323 BasicBlock *InsertAtEnd)
324 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
325 ->getElementType())->getReturnType(),
326 Instruction::Call, 0, 0, InsertAtEnd) {
330 CallInst::CallInst(Value *Func, const std::string &Name,
331 Instruction *InsertBefore)
332 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
333 ->getElementType())->getReturnType(),
334 Instruction::Call, 0, 0, InsertBefore) {
339 CallInst::CallInst(Value *Func, const std::string &Name,
340 BasicBlock *InsertAtEnd)
341 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
342 ->getElementType())->getReturnType(),
343 Instruction::Call, 0, 0, InsertAtEnd) {
348 CallInst::CallInst(const CallInst &CI)
349 : Instruction(CI.getType(), Instruction::Call, new Use[CI.getNumOperands()],
350 CI.getNumOperands()),
352 setParamAttrs(CI.getParamAttrs());
353 SubclassData = CI.SubclassData;
354 Use *OL = OperandList;
355 Use *InOL = CI.OperandList;
356 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
357 OL[i].init(InOL[i], this);
360 void CallInst::setParamAttrs(const ParamAttrsList *newAttrs) {
361 if (ParamAttrs == newAttrs)
365 ParamAttrs->dropRef();
370 ParamAttrs = newAttrs;
373 bool CallInst::paramHasAttr(uint16_t i, unsigned attr) const {
374 if (ParamAttrs && ParamAttrs->paramHasAttr(i, (ParameterAttributes)attr))
376 if (const Function *F = getCalledFunction())
377 return F->paramHasAttr(i, (ParameterAttributes)attr);
381 /// @brief Determine if the call does not access memory.
382 bool CallInst::doesNotAccessMemory() const {
383 return paramHasAttr(0, ParamAttr::ReadNone);
386 /// @brief Determine if the call does not access or only reads memory.
387 bool CallInst::onlyReadsMemory() const {
388 return doesNotAccessMemory() || paramHasAttr(0, ParamAttr::ReadOnly);
391 /// @brief Determine if the call cannot return.
392 bool CallInst::doesNotReturn() const {
393 return paramHasAttr(0, ParamAttr::NoReturn);
396 /// @brief Determine if the call cannot unwind.
397 bool CallInst::doesNotThrow() const {
398 return paramHasAttr(0, ParamAttr::NoUnwind);
401 /// @brief Determine if the call returns a structure.
402 bool CallInst::isStructReturn() const {
403 // Be friendly and also check the callee.
404 return paramHasAttr(1, ParamAttr::StructRet);
407 void CallInst::setDoesNotThrow(bool doesNotThrow) {
408 const ParamAttrsList *PAL = getParamAttrs();
410 PAL = ParamAttrsList::includeAttrs(PAL, 0, ParamAttr::NoUnwind);
412 PAL = ParamAttrsList::excludeAttrs(PAL, 0, ParamAttr::NoUnwind);
417 //===----------------------------------------------------------------------===//
418 // InvokeInst Implementation
419 //===----------------------------------------------------------------------===//
421 InvokeInst::~InvokeInst() {
422 delete [] OperandList;
424 ParamAttrs->dropRef();
427 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
428 Value* const *Args, unsigned NumArgs) {
430 NumOperands = 3+NumArgs;
431 Use *OL = OperandList = new Use[3+NumArgs];
432 OL[0].init(Fn, this);
433 OL[1].init(IfNormal, this);
434 OL[2].init(IfException, this);
435 const FunctionType *FTy =
436 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
437 FTy = FTy; // silence warning.
439 assert((NumArgs == FTy->getNumParams()) ||
440 (FTy->isVarArg() && NumArgs > FTy->getNumParams()) &&
441 "Calling a function with bad signature");
443 for (unsigned i = 0, e = NumArgs; i != e; i++) {
444 assert((i >= FTy->getNumParams() ||
445 FTy->getParamType(i) == Args[i]->getType()) &&
446 "Invoking a function with a bad signature!");
448 OL[i+3].init(Args[i], this);
452 InvokeInst::InvokeInst(const InvokeInst &II)
453 : TerminatorInst(II.getType(), Instruction::Invoke,
454 new Use[II.getNumOperands()], II.getNumOperands()),
456 setParamAttrs(II.getParamAttrs());
457 SubclassData = II.SubclassData;
458 Use *OL = OperandList, *InOL = II.OperandList;
459 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
460 OL[i].init(InOL[i], this);
463 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
464 return getSuccessor(idx);
466 unsigned InvokeInst::getNumSuccessorsV() const {
467 return getNumSuccessors();
469 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
470 return setSuccessor(idx, B);
473 void InvokeInst::setParamAttrs(const ParamAttrsList *newAttrs) {
474 if (ParamAttrs == newAttrs)
478 ParamAttrs->dropRef();
483 ParamAttrs = newAttrs;
486 bool InvokeInst::paramHasAttr(uint16_t i, unsigned attr) const {
487 if (ParamAttrs && ParamAttrs->paramHasAttr(i, (ParameterAttributes)attr))
489 if (const Function *F = getCalledFunction())
490 return F->paramHasAttr(i, (ParameterAttributes)attr);
495 /// @brief Determine if the call does not access memory.
496 bool InvokeInst::doesNotAccessMemory() const {
497 return paramHasAttr(0, ParamAttr::ReadNone);
500 /// @brief Determine if the call does not access or only reads memory.
501 bool InvokeInst::onlyReadsMemory() const {
502 return doesNotAccessMemory() || paramHasAttr(0, ParamAttr::ReadOnly);
505 /// @brief Determine if the call cannot return.
506 bool InvokeInst::doesNotReturn() const {
507 return paramHasAttr(0, ParamAttr::NoReturn);
510 /// @brief Determine if the call cannot unwind.
511 bool InvokeInst::doesNotThrow() const {
512 return paramHasAttr(0, ParamAttr::NoUnwind);
515 void InvokeInst::setDoesNotThrow(bool doesNotThrow) {
516 const ParamAttrsList *PAL = getParamAttrs();
518 PAL = ParamAttrsList::includeAttrs(PAL, 0, ParamAttr::NoUnwind);
520 PAL = ParamAttrsList::excludeAttrs(PAL, 0, ParamAttr::NoUnwind);
524 /// @brief Determine if the call returns a structure.
525 bool InvokeInst::isStructReturn() const {
526 // Be friendly and also check the callee.
527 return paramHasAttr(1, ParamAttr::StructRet);
531 //===----------------------------------------------------------------------===//
532 // ReturnInst Implementation
533 //===----------------------------------------------------------------------===//
535 ReturnInst::ReturnInst(const ReturnInst &RI)
536 : TerminatorInst(Type::VoidTy, Instruction::Ret,
537 &RetVal, RI.getNumOperands()) {
538 if (RI.getNumOperands())
539 RetVal.init(RI.RetVal, this);
542 ReturnInst::ReturnInst(Value *retVal, Instruction *InsertBefore)
543 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertBefore) {
546 ReturnInst::ReturnInst(Value *retVal, BasicBlock *InsertAtEnd)
547 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertAtEnd) {
550 ReturnInst::ReturnInst(BasicBlock *InsertAtEnd)
551 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertAtEnd) {
556 void ReturnInst::init(Value *retVal) {
557 if (retVal && retVal->getType() != Type::VoidTy) {
558 assert(!isa<BasicBlock>(retVal) &&
559 "Cannot return basic block. Probably using the incorrect ctor");
561 RetVal.init(retVal, this);
565 unsigned ReturnInst::getNumSuccessorsV() const {
566 return getNumSuccessors();
569 // Out-of-line ReturnInst method, put here so the C++ compiler can choose to
570 // emit the vtable for the class in this translation unit.
571 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
572 assert(0 && "ReturnInst has no successors!");
575 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
576 assert(0 && "ReturnInst has no successors!");
582 //===----------------------------------------------------------------------===//
583 // UnwindInst Implementation
584 //===----------------------------------------------------------------------===//
586 UnwindInst::UnwindInst(Instruction *InsertBefore)
587 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertBefore) {
589 UnwindInst::UnwindInst(BasicBlock *InsertAtEnd)
590 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertAtEnd) {
594 unsigned UnwindInst::getNumSuccessorsV() const {
595 return getNumSuccessors();
598 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
599 assert(0 && "UnwindInst has no successors!");
602 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
603 assert(0 && "UnwindInst has no successors!");
608 //===----------------------------------------------------------------------===//
609 // UnreachableInst Implementation
610 //===----------------------------------------------------------------------===//
612 UnreachableInst::UnreachableInst(Instruction *InsertBefore)
613 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertBefore) {
615 UnreachableInst::UnreachableInst(BasicBlock *InsertAtEnd)
616 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertAtEnd) {
619 unsigned UnreachableInst::getNumSuccessorsV() const {
620 return getNumSuccessors();
623 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
624 assert(0 && "UnwindInst has no successors!");
627 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
628 assert(0 && "UnwindInst has no successors!");
633 //===----------------------------------------------------------------------===//
634 // BranchInst Implementation
635 //===----------------------------------------------------------------------===//
637 void BranchInst::AssertOK() {
639 assert(getCondition()->getType() == Type::Int1Ty &&
640 "May only branch on boolean predicates!");
643 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
644 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 1, InsertBefore) {
645 assert(IfTrue != 0 && "Branch destination may not be null!");
646 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
648 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
649 Instruction *InsertBefore)
650 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 3, InsertBefore) {
651 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
652 Ops[1].init(reinterpret_cast<Value*>(IfFalse), this);
653 Ops[2].init(Cond, this);
659 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
660 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 1, InsertAtEnd) {
661 assert(IfTrue != 0 && "Branch destination may not be null!");
662 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
665 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
666 BasicBlock *InsertAtEnd)
667 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 3, InsertAtEnd) {
668 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
669 Ops[1].init(reinterpret_cast<Value*>(IfFalse), this);
670 Ops[2].init(Cond, this);
677 BranchInst::BranchInst(const BranchInst &BI) :
678 TerminatorInst(Type::VoidTy, Instruction::Br, Ops, BI.getNumOperands()) {
679 OperandList[0].init(BI.getOperand(0), this);
680 if (BI.getNumOperands() != 1) {
681 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
682 OperandList[1].init(BI.getOperand(1), this);
683 OperandList[2].init(BI.getOperand(2), this);
687 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
688 return getSuccessor(idx);
690 unsigned BranchInst::getNumSuccessorsV() const {
691 return getNumSuccessors();
693 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
694 setSuccessor(idx, B);
698 //===----------------------------------------------------------------------===//
699 // AllocationInst Implementation
700 //===----------------------------------------------------------------------===//
702 static Value *getAISize(Value *Amt) {
704 Amt = ConstantInt::get(Type::Int32Ty, 1);
706 assert(!isa<BasicBlock>(Amt) &&
707 "Passed basic block into allocation size parameter! Use other ctor");
708 assert(Amt->getType() == Type::Int32Ty &&
709 "Malloc/Allocation array size is not a 32-bit integer!");
714 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
715 unsigned Align, const std::string &Name,
716 Instruction *InsertBefore)
717 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
718 InsertBefore), Alignment(Align) {
719 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
720 assert(Ty != Type::VoidTy && "Cannot allocate void!");
724 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
725 unsigned Align, const std::string &Name,
726 BasicBlock *InsertAtEnd)
727 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
728 InsertAtEnd), Alignment(Align) {
729 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
730 assert(Ty != Type::VoidTy && "Cannot allocate void!");
734 // Out of line virtual method, so the vtable, etc has a home.
735 AllocationInst::~AllocationInst() {
738 bool AllocationInst::isArrayAllocation() const {
739 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
740 return CI->getZExtValue() != 1;
744 const Type *AllocationInst::getAllocatedType() const {
745 return getType()->getElementType();
748 AllocaInst::AllocaInst(const AllocaInst &AI)
749 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
750 Instruction::Alloca, AI.getAlignment()) {
753 MallocInst::MallocInst(const MallocInst &MI)
754 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
755 Instruction::Malloc, MI.getAlignment()) {
758 //===----------------------------------------------------------------------===//
759 // FreeInst Implementation
760 //===----------------------------------------------------------------------===//
762 void FreeInst::AssertOK() {
763 assert(isa<PointerType>(getOperand(0)->getType()) &&
764 "Can not free something of nonpointer type!");
767 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
768 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertBefore) {
772 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
773 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertAtEnd) {
778 //===----------------------------------------------------------------------===//
779 // LoadInst Implementation
780 //===----------------------------------------------------------------------===//
782 void LoadInst::AssertOK() {
783 assert(isa<PointerType>(getOperand(0)->getType()) &&
784 "Ptr must have pointer type.");
787 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
788 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
789 Load, Ptr, InsertBef) {
796 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
797 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
798 Load, Ptr, InsertAE) {
805 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
806 Instruction *InsertBef)
807 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
808 Load, Ptr, InsertBef) {
809 setVolatile(isVolatile);
815 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
816 unsigned Align, Instruction *InsertBef)
817 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
818 Load, Ptr, InsertBef) {
819 setVolatile(isVolatile);
825 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
826 unsigned Align, BasicBlock *InsertAE)
827 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
828 Load, Ptr, InsertAE) {
829 setVolatile(isVolatile);
835 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
836 BasicBlock *InsertAE)
837 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
838 Load, Ptr, InsertAE) {
839 setVolatile(isVolatile);
847 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
848 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
849 Load, Ptr, InsertBef) {
853 if (Name && Name[0]) setName(Name);
856 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
857 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
858 Load, Ptr, InsertAE) {
862 if (Name && Name[0]) setName(Name);
865 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
866 Instruction *InsertBef)
867 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
868 Load, Ptr, InsertBef) {
869 setVolatile(isVolatile);
872 if (Name && Name[0]) setName(Name);
875 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
876 BasicBlock *InsertAE)
877 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
878 Load, Ptr, InsertAE) {
879 setVolatile(isVolatile);
882 if (Name && Name[0]) setName(Name);
885 void LoadInst::setAlignment(unsigned Align) {
886 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
887 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
890 //===----------------------------------------------------------------------===//
891 // StoreInst Implementation
892 //===----------------------------------------------------------------------===//
894 void StoreInst::AssertOK() {
895 assert(isa<PointerType>(getOperand(1)->getType()) &&
896 "Ptr must have pointer type!");
897 assert(getOperand(0)->getType() ==
898 cast<PointerType>(getOperand(1)->getType())->getElementType()
899 && "Ptr must be a pointer to Val type!");
903 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
904 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
905 Ops[0].init(val, this);
906 Ops[1].init(addr, this);
912 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
913 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
914 Ops[0].init(val, this);
915 Ops[1].init(addr, this);
921 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
922 Instruction *InsertBefore)
923 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
924 Ops[0].init(val, this);
925 Ops[1].init(addr, this);
926 setVolatile(isVolatile);
931 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
932 unsigned Align, Instruction *InsertBefore)
933 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
934 Ops[0].init(val, this);
935 Ops[1].init(addr, this);
936 setVolatile(isVolatile);
941 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
942 unsigned Align, BasicBlock *InsertAtEnd)
943 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
944 Ops[0].init(val, this);
945 Ops[1].init(addr, this);
946 setVolatile(isVolatile);
951 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
952 BasicBlock *InsertAtEnd)
953 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
954 Ops[0].init(val, this);
955 Ops[1].init(addr, this);
956 setVolatile(isVolatile);
961 void StoreInst::setAlignment(unsigned Align) {
962 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
963 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
966 //===----------------------------------------------------------------------===//
967 // GetElementPtrInst Implementation
968 //===----------------------------------------------------------------------===//
970 static unsigned retrieveAddrSpace(const Value *Val) {
971 return cast<PointerType>(Val->getType())->getAddressSpace();
974 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx) {
975 NumOperands = 1+NumIdx;
976 Use *OL = OperandList = new Use[NumOperands];
977 OL[0].init(Ptr, this);
979 for (unsigned i = 0; i != NumIdx; ++i)
980 OL[i+1].init(Idx[i], this);
983 void GetElementPtrInst::init(Value *Ptr, Value *Idx) {
985 Use *OL = OperandList = new Use[2];
986 OL[0].init(Ptr, this);
987 OL[1].init(Idx, this);
990 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
991 const std::string &Name, Instruction *InBe)
992 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
993 retrieveAddrSpace(Ptr)),
994 GetElementPtr, 0, 0, InBe) {
999 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1000 const std::string &Name, BasicBlock *IAE)
1001 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1002 retrieveAddrSpace(Ptr)),
1003 GetElementPtr, 0, 0, IAE) {
1008 GetElementPtrInst::~GetElementPtrInst() {
1009 delete[] OperandList;
1012 // getIndexedType - Returns the type of the element that would be loaded with
1013 // a load instruction with the specified parameters.
1015 // A null type is returned if the indices are invalid for the specified
1018 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1021 bool AllowCompositeLeaf) {
1022 if (!isa<PointerType>(Ptr)) return 0; // Type isn't a pointer type!
1024 // Handle the special case of the empty set index set...
1026 if (AllowCompositeLeaf ||
1027 cast<PointerType>(Ptr)->getElementType()->isFirstClassType())
1028 return cast<PointerType>(Ptr)->getElementType();
1032 unsigned CurIdx = 0;
1033 while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
1034 if (NumIdx == CurIdx) {
1035 if (AllowCompositeLeaf || CT->isFirstClassType()) return Ptr;
1036 return 0; // Can't load a whole structure or array!?!?
1039 Value *Index = Idxs[CurIdx++];
1040 if (isa<PointerType>(CT) && CurIdx != 1)
1041 return 0; // Can only index into pointer types at the first index!
1042 if (!CT->indexValid(Index)) return 0;
1043 Ptr = CT->getTypeAtIndex(Index);
1045 // If the new type forwards to another type, then it is in the middle
1046 // of being refined to another type (and hence, may have dropped all
1047 // references to what it was using before). So, use the new forwarded
1049 if (const Type * Ty = Ptr->getForwardedType()) {
1053 return CurIdx == NumIdx ? Ptr : 0;
1056 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1057 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1058 if (!PTy) return 0; // Type isn't a pointer type!
1060 // Check the pointer index.
1061 if (!PTy->indexValid(Idx)) return 0;
1063 return PTy->getElementType();
1067 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1068 /// zeros. If so, the result pointer and the first operand have the same
1069 /// value, just potentially different types.
1070 bool GetElementPtrInst::hasAllZeroIndices() const {
1071 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1072 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1073 if (!CI->isZero()) return false;
1081 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1082 /// constant integers. If so, the result pointer and the first operand have
1083 /// a constant offset between them.
1084 bool GetElementPtrInst::hasAllConstantIndices() const {
1085 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1086 if (!isa<ConstantInt>(getOperand(i)))
1093 //===----------------------------------------------------------------------===//
1094 // ExtractElementInst Implementation
1095 //===----------------------------------------------------------------------===//
1097 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1098 const std::string &Name,
1099 Instruction *InsertBef)
1100 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1101 ExtractElement, Ops, 2, InsertBef) {
1102 assert(isValidOperands(Val, Index) &&
1103 "Invalid extractelement instruction operands!");
1104 Ops[0].init(Val, this);
1105 Ops[1].init(Index, this);
1109 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1110 const std::string &Name,
1111 Instruction *InsertBef)
1112 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1113 ExtractElement, Ops, 2, InsertBef) {
1114 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1115 assert(isValidOperands(Val, Index) &&
1116 "Invalid extractelement instruction operands!");
1117 Ops[0].init(Val, this);
1118 Ops[1].init(Index, this);
1123 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1124 const std::string &Name,
1125 BasicBlock *InsertAE)
1126 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1127 ExtractElement, Ops, 2, InsertAE) {
1128 assert(isValidOperands(Val, Index) &&
1129 "Invalid extractelement instruction operands!");
1131 Ops[0].init(Val, this);
1132 Ops[1].init(Index, this);
1136 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1137 const std::string &Name,
1138 BasicBlock *InsertAE)
1139 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1140 ExtractElement, Ops, 2, InsertAE) {
1141 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1142 assert(isValidOperands(Val, Index) &&
1143 "Invalid extractelement instruction operands!");
1145 Ops[0].init(Val, this);
1146 Ops[1].init(Index, this);
1151 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1152 if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty)
1158 //===----------------------------------------------------------------------===//
1159 // InsertElementInst Implementation
1160 //===----------------------------------------------------------------------===//
1162 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
1163 : Instruction(IE.getType(), InsertElement, Ops, 3) {
1164 Ops[0].init(IE.Ops[0], this);
1165 Ops[1].init(IE.Ops[1], this);
1166 Ops[2].init(IE.Ops[2], this);
1168 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1169 const std::string &Name,
1170 Instruction *InsertBef)
1171 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertBef) {
1172 assert(isValidOperands(Vec, Elt, Index) &&
1173 "Invalid insertelement instruction operands!");
1174 Ops[0].init(Vec, this);
1175 Ops[1].init(Elt, this);
1176 Ops[2].init(Index, this);
1180 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1181 const std::string &Name,
1182 Instruction *InsertBef)
1183 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertBef) {
1184 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1185 assert(isValidOperands(Vec, Elt, Index) &&
1186 "Invalid insertelement instruction operands!");
1187 Ops[0].init(Vec, this);
1188 Ops[1].init(Elt, this);
1189 Ops[2].init(Index, this);
1194 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1195 const std::string &Name,
1196 BasicBlock *InsertAE)
1197 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertAE) {
1198 assert(isValidOperands(Vec, Elt, Index) &&
1199 "Invalid insertelement instruction operands!");
1201 Ops[0].init(Vec, this);
1202 Ops[1].init(Elt, this);
1203 Ops[2].init(Index, this);
1207 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1208 const std::string &Name,
1209 BasicBlock *InsertAE)
1210 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertAE) {
1211 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1212 assert(isValidOperands(Vec, Elt, Index) &&
1213 "Invalid insertelement instruction operands!");
1215 Ops[0].init(Vec, this);
1216 Ops[1].init(Elt, this);
1217 Ops[2].init(Index, this);
1221 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1222 const Value *Index) {
1223 if (!isa<VectorType>(Vec->getType()))
1224 return false; // First operand of insertelement must be vector type.
1226 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1227 return false;// Second operand of insertelement must be vector element type.
1229 if (Index->getType() != Type::Int32Ty)
1230 return false; // Third operand of insertelement must be uint.
1235 //===----------------------------------------------------------------------===//
1236 // ShuffleVectorInst Implementation
1237 //===----------------------------------------------------------------------===//
1239 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
1240 : Instruction(SV.getType(), ShuffleVector, Ops, 3) {
1241 Ops[0].init(SV.Ops[0], this);
1242 Ops[1].init(SV.Ops[1], this);
1243 Ops[2].init(SV.Ops[2], this);
1246 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1247 const std::string &Name,
1248 Instruction *InsertBefore)
1249 : Instruction(V1->getType(), ShuffleVector, Ops, 3, InsertBefore) {
1250 assert(isValidOperands(V1, V2, Mask) &&
1251 "Invalid shuffle vector instruction operands!");
1252 Ops[0].init(V1, this);
1253 Ops[1].init(V2, this);
1254 Ops[2].init(Mask, this);
1258 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1259 const std::string &Name,
1260 BasicBlock *InsertAtEnd)
1261 : Instruction(V1->getType(), ShuffleVector, Ops, 3, InsertAtEnd) {
1262 assert(isValidOperands(V1, V2, Mask) &&
1263 "Invalid shuffle vector instruction operands!");
1265 Ops[0].init(V1, this);
1266 Ops[1].init(V2, this);
1267 Ops[2].init(Mask, this);
1271 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1272 const Value *Mask) {
1273 if (!isa<VectorType>(V1->getType())) return false;
1274 if (V1->getType() != V2->getType()) return false;
1275 if (!isa<VectorType>(Mask->getType()) ||
1276 cast<VectorType>(Mask->getType())->getElementType() != Type::Int32Ty ||
1277 cast<VectorType>(Mask->getType())->getNumElements() !=
1278 cast<VectorType>(V1->getType())->getNumElements())
1284 //===----------------------------------------------------------------------===//
1285 // BinaryOperator Class
1286 //===----------------------------------------------------------------------===//
1288 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1289 const Type *Ty, const std::string &Name,
1290 Instruction *InsertBefore)
1291 : Instruction(Ty, iType, Ops, 2, InsertBefore) {
1292 Ops[0].init(S1, this);
1293 Ops[1].init(S2, this);
1298 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1299 const Type *Ty, const std::string &Name,
1300 BasicBlock *InsertAtEnd)
1301 : Instruction(Ty, iType, Ops, 2, InsertAtEnd) {
1302 Ops[0].init(S1, this);
1303 Ops[1].init(S2, this);
1309 void BinaryOperator::init(BinaryOps iType) {
1310 Value *LHS = getOperand(0), *RHS = getOperand(1);
1311 LHS = LHS; RHS = RHS; // Silence warnings.
1312 assert(LHS->getType() == RHS->getType() &&
1313 "Binary operator operand types must match!");
1318 assert(getType() == LHS->getType() &&
1319 "Arithmetic operation should return same type as operands!");
1320 assert((getType()->isInteger() || getType()->isFloatingPoint() ||
1321 isa<VectorType>(getType())) &&
1322 "Tried to create an arithmetic operation on a non-arithmetic type!");
1326 assert(getType() == LHS->getType() &&
1327 "Arithmetic operation should return same type as operands!");
1328 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1329 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1330 "Incorrect operand type (not integer) for S/UDIV");
1333 assert(getType() == LHS->getType() &&
1334 "Arithmetic operation should return same type as operands!");
1335 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1336 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1337 && "Incorrect operand type (not floating point) for FDIV");
1341 assert(getType() == LHS->getType() &&
1342 "Arithmetic operation should return same type as operands!");
1343 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1344 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1345 "Incorrect operand type (not integer) for S/UREM");
1348 assert(getType() == LHS->getType() &&
1349 "Arithmetic operation should return same type as operands!");
1350 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1351 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1352 && "Incorrect operand type (not floating point) for FREM");
1357 assert(getType() == LHS->getType() &&
1358 "Shift operation should return same type as operands!");
1359 assert(getType()->isInteger() &&
1360 "Shift operation requires integer operands");
1364 assert(getType() == LHS->getType() &&
1365 "Logical operation should return same type as operands!");
1366 assert((getType()->isInteger() ||
1367 (isa<VectorType>(getType()) &&
1368 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1369 "Tried to create a logical operation on a non-integral type!");
1377 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1378 const std::string &Name,
1379 Instruction *InsertBefore) {
1380 assert(S1->getType() == S2->getType() &&
1381 "Cannot create binary operator with two operands of differing type!");
1382 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1385 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1386 const std::string &Name,
1387 BasicBlock *InsertAtEnd) {
1388 BinaryOperator *Res = create(Op, S1, S2, Name);
1389 InsertAtEnd->getInstList().push_back(Res);
1393 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1394 Instruction *InsertBefore) {
1395 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1396 return new BinaryOperator(Instruction::Sub,
1398 Op->getType(), Name, InsertBefore);
1401 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1402 BasicBlock *InsertAtEnd) {
1403 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1404 return new BinaryOperator(Instruction::Sub,
1406 Op->getType(), Name, InsertAtEnd);
1409 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1410 Instruction *InsertBefore) {
1412 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1413 C = ConstantInt::getAllOnesValue(PTy->getElementType());
1414 C = ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), C));
1416 C = ConstantInt::getAllOnesValue(Op->getType());
1419 return new BinaryOperator(Instruction::Xor, Op, C,
1420 Op->getType(), Name, InsertBefore);
1423 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1424 BasicBlock *InsertAtEnd) {
1426 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1427 // Create a vector of all ones values.
1428 Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType());
1430 ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1432 AllOnes = ConstantInt::getAllOnesValue(Op->getType());
1435 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1436 Op->getType(), Name, InsertAtEnd);
1440 // isConstantAllOnes - Helper function for several functions below
1441 static inline bool isConstantAllOnes(const Value *V) {
1442 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1443 return CI->isAllOnesValue();
1444 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1445 return CV->isAllOnesValue();
1449 bool BinaryOperator::isNeg(const Value *V) {
1450 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1451 if (Bop->getOpcode() == Instruction::Sub)
1452 return Bop->getOperand(0) ==
1453 ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1457 bool BinaryOperator::isNot(const Value *V) {
1458 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1459 return (Bop->getOpcode() == Instruction::Xor &&
1460 (isConstantAllOnes(Bop->getOperand(1)) ||
1461 isConstantAllOnes(Bop->getOperand(0))));
1465 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1466 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1467 return cast<BinaryOperator>(BinOp)->getOperand(1);
1470 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1471 return getNegArgument(const_cast<Value*>(BinOp));
1474 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1475 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1476 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1477 Value *Op0 = BO->getOperand(0);
1478 Value *Op1 = BO->getOperand(1);
1479 if (isConstantAllOnes(Op0)) return Op1;
1481 assert(isConstantAllOnes(Op1));
1485 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1486 return getNotArgument(const_cast<Value*>(BinOp));
1490 // swapOperands - Exchange the two operands to this instruction. This
1491 // instruction is safe to use on any binary instruction and does not
1492 // modify the semantics of the instruction. If the instruction is
1493 // order dependent (SetLT f.e.) the opcode is changed.
1495 bool BinaryOperator::swapOperands() {
1496 if (!isCommutative())
1497 return true; // Can't commute operands
1498 std::swap(Ops[0], Ops[1]);
1502 //===----------------------------------------------------------------------===//
1504 //===----------------------------------------------------------------------===//
1506 // Just determine if this cast only deals with integral->integral conversion.
1507 bool CastInst::isIntegerCast() const {
1508 switch (getOpcode()) {
1509 default: return false;
1510 case Instruction::ZExt:
1511 case Instruction::SExt:
1512 case Instruction::Trunc:
1514 case Instruction::BitCast:
1515 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1519 bool CastInst::isLosslessCast() const {
1520 // Only BitCast can be lossless, exit fast if we're not BitCast
1521 if (getOpcode() != Instruction::BitCast)
1524 // Identity cast is always lossless
1525 const Type* SrcTy = getOperand(0)->getType();
1526 const Type* DstTy = getType();
1530 // Pointer to pointer is always lossless.
1531 if (isa<PointerType>(SrcTy))
1532 return isa<PointerType>(DstTy);
1533 return false; // Other types have no identity values
1536 /// This function determines if the CastInst does not require any bits to be
1537 /// changed in order to effect the cast. Essentially, it identifies cases where
1538 /// no code gen is necessary for the cast, hence the name no-op cast. For
1539 /// example, the following are all no-op casts:
1540 /// # bitcast uint %X, int
1541 /// # bitcast uint* %x, sbyte*
1542 /// # bitcast vector< 2 x int > %x, vector< 4 x short>
1543 /// # ptrtoint uint* %x, uint ; on 32-bit plaforms only
1544 /// @brief Determine if a cast is a no-op.
1545 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1546 switch (getOpcode()) {
1548 assert(!"Invalid CastOp");
1549 case Instruction::Trunc:
1550 case Instruction::ZExt:
1551 case Instruction::SExt:
1552 case Instruction::FPTrunc:
1553 case Instruction::FPExt:
1554 case Instruction::UIToFP:
1555 case Instruction::SIToFP:
1556 case Instruction::FPToUI:
1557 case Instruction::FPToSI:
1558 return false; // These always modify bits
1559 case Instruction::BitCast:
1560 return true; // BitCast never modifies bits.
1561 case Instruction::PtrToInt:
1562 return IntPtrTy->getPrimitiveSizeInBits() ==
1563 getType()->getPrimitiveSizeInBits();
1564 case Instruction::IntToPtr:
1565 return IntPtrTy->getPrimitiveSizeInBits() ==
1566 getOperand(0)->getType()->getPrimitiveSizeInBits();
1570 /// This function determines if a pair of casts can be eliminated and what
1571 /// opcode should be used in the elimination. This assumes that there are two
1572 /// instructions like this:
1573 /// * %F = firstOpcode SrcTy %x to MidTy
1574 /// * %S = secondOpcode MidTy %F to DstTy
1575 /// The function returns a resultOpcode so these two casts can be replaced with:
1576 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1577 /// If no such cast is permited, the function returns 0.
1578 unsigned CastInst::isEliminableCastPair(
1579 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1580 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1582 // Define the 144 possibilities for these two cast instructions. The values
1583 // in this matrix determine what to do in a given situation and select the
1584 // case in the switch below. The rows correspond to firstOp, the columns
1585 // correspond to secondOp. In looking at the table below, keep in mind
1586 // the following cast properties:
1588 // Size Compare Source Destination
1589 // Operator Src ? Size Type Sign Type Sign
1590 // -------- ------------ ------------------- ---------------------
1591 // TRUNC > Integer Any Integral Any
1592 // ZEXT < Integral Unsigned Integer Any
1593 // SEXT < Integral Signed Integer Any
1594 // FPTOUI n/a FloatPt n/a Integral Unsigned
1595 // FPTOSI n/a FloatPt n/a Integral Signed
1596 // UITOFP n/a Integral Unsigned FloatPt n/a
1597 // SITOFP n/a Integral Signed FloatPt n/a
1598 // FPTRUNC > FloatPt n/a FloatPt n/a
1599 // FPEXT < FloatPt n/a FloatPt n/a
1600 // PTRTOINT n/a Pointer n/a Integral Unsigned
1601 // INTTOPTR n/a Integral Unsigned Pointer n/a
1602 // BITCONVERT = FirstClass n/a FirstClass n/a
1604 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1605 // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
1606 // into "fptoui double to ulong", but this loses information about the range
1607 // of the produced value (we no longer know the top-part is all zeros).
1608 // Further this conversion is often much more expensive for typical hardware,
1609 // and causes issues when building libgcc. We disallow fptosi+sext for the
1611 const unsigned numCastOps =
1612 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1613 static const uint8_t CastResults[numCastOps][numCastOps] = {
1614 // T F F U S F F P I B -+
1615 // R Z S P P I I T P 2 N T |
1616 // U E E 2 2 2 2 R E I T C +- secondOp
1617 // N X X U S F F N X N 2 V |
1618 // C T T I I P P C T T P T -+
1619 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1620 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1621 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1622 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1623 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1624 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1625 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1626 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1627 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1628 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1629 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1630 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1633 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1634 [secondOp-Instruction::CastOpsBegin];
1637 // categorically disallowed
1640 // allowed, use first cast's opcode
1643 // allowed, use second cast's opcode
1646 // no-op cast in second op implies firstOp as long as the DestTy
1648 if (DstTy->isInteger())
1652 // no-op cast in second op implies firstOp as long as the DestTy
1653 // is floating point
1654 if (DstTy->isFloatingPoint())
1658 // no-op cast in first op implies secondOp as long as the SrcTy
1660 if (SrcTy->isInteger())
1664 // no-op cast in first op implies secondOp as long as the SrcTy
1665 // is a floating point
1666 if (SrcTy->isFloatingPoint())
1670 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1671 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1672 unsigned MidSize = MidTy->getPrimitiveSizeInBits();
1673 if (MidSize >= PtrSize)
1674 return Instruction::BitCast;
1678 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1679 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1680 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1681 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1682 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1683 if (SrcSize == DstSize)
1684 return Instruction::BitCast;
1685 else if (SrcSize < DstSize)
1689 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1690 return Instruction::ZExt;
1692 // fpext followed by ftrunc is allowed if the bit size returned to is
1693 // the same as the original, in which case its just a bitcast
1695 return Instruction::BitCast;
1696 return 0; // If the types are not the same we can't eliminate it.
1698 // bitcast followed by ptrtoint is allowed as long as the bitcast
1699 // is a pointer to pointer cast.
1700 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1704 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1705 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1709 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1710 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1711 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1712 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1713 if (SrcSize <= PtrSize && SrcSize == DstSize)
1714 return Instruction::BitCast;
1718 // cast combination can't happen (error in input). This is for all cases
1719 // where the MidTy is not the same for the two cast instructions.
1720 assert(!"Invalid Cast Combination");
1723 assert(!"Error in CastResults table!!!");
1729 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1730 const std::string &Name, Instruction *InsertBefore) {
1731 // Construct and return the appropriate CastInst subclass
1733 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1734 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1735 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1736 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1737 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1738 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1739 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1740 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1741 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1742 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1743 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1744 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1746 assert(!"Invalid opcode provided");
1751 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1752 const std::string &Name, BasicBlock *InsertAtEnd) {
1753 // Construct and return the appropriate CastInst subclass
1755 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1756 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1757 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1758 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1759 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1760 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1761 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1762 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1763 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1764 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1765 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1766 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1768 assert(!"Invalid opcode provided");
1773 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1774 const std::string &Name,
1775 Instruction *InsertBefore) {
1776 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1777 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1778 return create(Instruction::ZExt, S, Ty, Name, InsertBefore);
1781 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1782 const std::string &Name,
1783 BasicBlock *InsertAtEnd) {
1784 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1785 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1786 return create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
1789 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1790 const std::string &Name,
1791 Instruction *InsertBefore) {
1792 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1793 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1794 return create(Instruction::SExt, S, Ty, Name, InsertBefore);
1797 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1798 const std::string &Name,
1799 BasicBlock *InsertAtEnd) {
1800 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1801 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1802 return create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
1805 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1806 const std::string &Name,
1807 Instruction *InsertBefore) {
1808 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1809 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1810 return create(Instruction::Trunc, S, Ty, Name, InsertBefore);
1813 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1814 const std::string &Name,
1815 BasicBlock *InsertAtEnd) {
1816 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1817 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1818 return create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
1821 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1822 const std::string &Name,
1823 BasicBlock *InsertAtEnd) {
1824 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1825 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1828 if (Ty->isInteger())
1829 return create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
1830 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1833 /// @brief Create a BitCast or a PtrToInt cast instruction
1834 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1835 const std::string &Name,
1836 Instruction *InsertBefore) {
1837 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1838 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1841 if (Ty->isInteger())
1842 return create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
1843 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1846 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1847 bool isSigned, const std::string &Name,
1848 Instruction *InsertBefore) {
1849 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1850 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1851 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1852 Instruction::CastOps opcode =
1853 (SrcBits == DstBits ? Instruction::BitCast :
1854 (SrcBits > DstBits ? Instruction::Trunc :
1855 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1856 return create(opcode, C, Ty, Name, InsertBefore);
1859 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1860 bool isSigned, const std::string &Name,
1861 BasicBlock *InsertAtEnd) {
1862 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1863 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1864 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1865 Instruction::CastOps opcode =
1866 (SrcBits == DstBits ? Instruction::BitCast :
1867 (SrcBits > DstBits ? Instruction::Trunc :
1868 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1869 return create(opcode, C, Ty, Name, InsertAtEnd);
1872 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1873 const std::string &Name,
1874 Instruction *InsertBefore) {
1875 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1877 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1878 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1879 Instruction::CastOps opcode =
1880 (SrcBits == DstBits ? Instruction::BitCast :
1881 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1882 return create(opcode, C, Ty, Name, InsertBefore);
1885 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1886 const std::string &Name,
1887 BasicBlock *InsertAtEnd) {
1888 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1890 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1891 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1892 Instruction::CastOps opcode =
1893 (SrcBits == DstBits ? Instruction::BitCast :
1894 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1895 return create(opcode, C, Ty, Name, InsertAtEnd);
1898 // Provide a way to get a "cast" where the cast opcode is inferred from the
1899 // types and size of the operand. This, basically, is a parallel of the
1900 // logic in the castIsValid function below. This axiom should hold:
1901 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
1902 // should not assert in castIsValid. In other words, this produces a "correct"
1903 // casting opcode for the arguments passed to it.
1904 Instruction::CastOps
1905 CastInst::getCastOpcode(
1906 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
1907 // Get the bit sizes, we'll need these
1908 const Type *SrcTy = Src->getType();
1909 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1910 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1912 // Run through the possibilities ...
1913 if (DestTy->isInteger()) { // Casting to integral
1914 if (SrcTy->isInteger()) { // Casting from integral
1915 if (DestBits < SrcBits)
1916 return Trunc; // int -> smaller int
1917 else if (DestBits > SrcBits) { // its an extension
1919 return SExt; // signed -> SEXT
1921 return ZExt; // unsigned -> ZEXT
1923 return BitCast; // Same size, No-op cast
1925 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1927 return FPToSI; // FP -> sint
1929 return FPToUI; // FP -> uint
1930 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1931 assert(DestBits == PTy->getBitWidth() &&
1932 "Casting vector to integer of different width");
1933 return BitCast; // Same size, no-op cast
1935 assert(isa<PointerType>(SrcTy) &&
1936 "Casting from a value that is not first-class type");
1937 return PtrToInt; // ptr -> int
1939 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
1940 if (SrcTy->isInteger()) { // Casting from integral
1942 return SIToFP; // sint -> FP
1944 return UIToFP; // uint -> FP
1945 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1946 if (DestBits < SrcBits) {
1947 return FPTrunc; // FP -> smaller FP
1948 } else if (DestBits > SrcBits) {
1949 return FPExt; // FP -> larger FP
1951 return BitCast; // same size, no-op cast
1953 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1954 assert(DestBits == PTy->getBitWidth() &&
1955 "Casting vector to floating point of different width");
1956 return BitCast; // same size, no-op cast
1958 assert(0 && "Casting pointer or non-first class to float");
1960 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
1961 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
1962 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
1963 "Casting vector to vector of different widths");
1964 return BitCast; // vector -> vector
1965 } else if (DestPTy->getBitWidth() == SrcBits) {
1966 return BitCast; // float/int -> vector
1968 assert(!"Illegal cast to vector (wrong type or size)");
1970 } else if (isa<PointerType>(DestTy)) {
1971 if (isa<PointerType>(SrcTy)) {
1972 return BitCast; // ptr -> ptr
1973 } else if (SrcTy->isInteger()) {
1974 return IntToPtr; // int -> ptr
1976 assert(!"Casting pointer to other than pointer or int");
1979 assert(!"Casting to type that is not first-class");
1982 // If we fall through to here we probably hit an assertion cast above
1983 // and assertions are not turned on. Anything we return is an error, so
1984 // BitCast is as good a choice as any.
1988 //===----------------------------------------------------------------------===//
1989 // CastInst SubClass Constructors
1990 //===----------------------------------------------------------------------===//
1992 /// Check that the construction parameters for a CastInst are correct. This
1993 /// could be broken out into the separate constructors but it is useful to have
1994 /// it in one place and to eliminate the redundant code for getting the sizes
1995 /// of the types involved.
1997 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
1999 // Check for type sanity on the arguments
2000 const Type *SrcTy = S->getType();
2001 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
2004 // Get the size of the types in bits, we'll need this later
2005 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2006 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2008 // Switch on the opcode provided
2010 default: return false; // This is an input error
2011 case Instruction::Trunc:
2012 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize > DstBitSize;
2013 case Instruction::ZExt:
2014 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2015 case Instruction::SExt:
2016 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2017 case Instruction::FPTrunc:
2018 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2019 SrcBitSize > DstBitSize;
2020 case Instruction::FPExt:
2021 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2022 SrcBitSize < DstBitSize;
2023 case Instruction::UIToFP:
2024 case Instruction::SIToFP:
2025 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2026 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2027 return SVTy->getElementType()->isInteger() &&
2028 DVTy->getElementType()->isFloatingPoint() &&
2029 SVTy->getNumElements() == DVTy->getNumElements();
2032 return SrcTy->isInteger() && DstTy->isFloatingPoint();
2033 case Instruction::FPToUI:
2034 case Instruction::FPToSI:
2035 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2036 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2037 return SVTy->getElementType()->isFloatingPoint() &&
2038 DVTy->getElementType()->isInteger() &&
2039 SVTy->getNumElements() == DVTy->getNumElements();
2042 return SrcTy->isFloatingPoint() && DstTy->isInteger();
2043 case Instruction::PtrToInt:
2044 return isa<PointerType>(SrcTy) && DstTy->isInteger();
2045 case Instruction::IntToPtr:
2046 return SrcTy->isInteger() && isa<PointerType>(DstTy);
2047 case Instruction::BitCast:
2048 // BitCast implies a no-op cast of type only. No bits change.
2049 // However, you can't cast pointers to anything but pointers.
2050 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2053 // Now we know we're not dealing with a pointer/non-poiner mismatch. In all
2054 // these cases, the cast is okay if the source and destination bit widths
2056 return SrcBitSize == DstBitSize;
2060 TruncInst::TruncInst(
2061 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2062 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2063 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2066 TruncInst::TruncInst(
2067 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2068 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2069 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2073 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2074 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2075 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2079 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2080 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2081 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2084 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2085 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2086 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2090 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2091 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2092 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2095 FPTruncInst::FPTruncInst(
2096 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2097 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2098 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2101 FPTruncInst::FPTruncInst(
2102 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2103 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2104 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2107 FPExtInst::FPExtInst(
2108 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2109 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2110 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2113 FPExtInst::FPExtInst(
2114 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2115 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2116 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2119 UIToFPInst::UIToFPInst(
2120 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2121 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2122 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2125 UIToFPInst::UIToFPInst(
2126 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2127 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2128 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2131 SIToFPInst::SIToFPInst(
2132 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2133 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2134 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2137 SIToFPInst::SIToFPInst(
2138 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2139 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2140 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2143 FPToUIInst::FPToUIInst(
2144 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2145 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2146 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2149 FPToUIInst::FPToUIInst(
2150 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2151 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2152 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2155 FPToSIInst::FPToSIInst(
2156 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2157 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2158 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2161 FPToSIInst::FPToSIInst(
2162 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2163 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2164 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2167 PtrToIntInst::PtrToIntInst(
2168 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2169 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2170 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2173 PtrToIntInst::PtrToIntInst(
2174 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2175 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2176 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2179 IntToPtrInst::IntToPtrInst(
2180 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2181 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2182 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2185 IntToPtrInst::IntToPtrInst(
2186 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2187 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2188 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2191 BitCastInst::BitCastInst(
2192 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2193 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2194 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2197 BitCastInst::BitCastInst(
2198 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2199 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2200 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2203 //===----------------------------------------------------------------------===//
2205 //===----------------------------------------------------------------------===//
2207 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2208 const std::string &Name, Instruction *InsertBefore)
2209 : Instruction(Type::Int1Ty, op, Ops, 2, InsertBefore) {
2210 Ops[0].init(LHS, this);
2211 Ops[1].init(RHS, this);
2212 SubclassData = predicate;
2214 if (op == Instruction::ICmp) {
2215 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2216 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2217 "Invalid ICmp predicate value");
2218 const Type* Op0Ty = getOperand(0)->getType();
2219 const Type* Op1Ty = getOperand(1)->getType();
2220 assert(Op0Ty == Op1Ty &&
2221 "Both operands to ICmp instruction are not of the same type!");
2222 // Check that the operands are the right type
2223 assert((Op0Ty->isInteger() || isa<PointerType>(Op0Ty)) &&
2224 "Invalid operand types for ICmp instruction");
2227 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2228 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2229 "Invalid FCmp predicate value");
2230 const Type* Op0Ty = getOperand(0)->getType();
2231 const Type* Op1Ty = getOperand(1)->getType();
2232 assert(Op0Ty == Op1Ty &&
2233 "Both operands to FCmp instruction are not of the same type!");
2234 // Check that the operands are the right type
2235 assert(Op0Ty->isFloatingPoint() &&
2236 "Invalid operand types for FCmp instruction");
2239 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2240 const std::string &Name, BasicBlock *InsertAtEnd)
2241 : Instruction(Type::Int1Ty, op, Ops, 2, InsertAtEnd) {
2242 Ops[0].init(LHS, this);
2243 Ops[1].init(RHS, this);
2244 SubclassData = predicate;
2246 if (op == Instruction::ICmp) {
2247 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2248 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2249 "Invalid ICmp predicate value");
2251 const Type* Op0Ty = getOperand(0)->getType();
2252 const Type* Op1Ty = getOperand(1)->getType();
2253 assert(Op0Ty == Op1Ty &&
2254 "Both operands to ICmp instruction are not of the same type!");
2255 // Check that the operands are the right type
2256 assert(Op0Ty->isInteger() || isa<PointerType>(Op0Ty) &&
2257 "Invalid operand types for ICmp instruction");
2260 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2261 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2262 "Invalid FCmp predicate value");
2263 const Type* Op0Ty = getOperand(0)->getType();
2264 const Type* Op1Ty = getOperand(1)->getType();
2265 assert(Op0Ty == Op1Ty &&
2266 "Both operands to FCmp instruction are not of the same type!");
2267 // Check that the operands are the right type
2268 assert(Op0Ty->isFloatingPoint() &&
2269 "Invalid operand types for FCmp instruction");
2273 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2274 const std::string &Name, Instruction *InsertBefore) {
2275 if (Op == Instruction::ICmp) {
2276 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2279 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2284 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2285 const std::string &Name, BasicBlock *InsertAtEnd) {
2286 if (Op == Instruction::ICmp) {
2287 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2290 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2294 void CmpInst::swapOperands() {
2295 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2298 cast<FCmpInst>(this)->swapOperands();
2301 bool CmpInst::isCommutative() {
2302 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2303 return IC->isCommutative();
2304 return cast<FCmpInst>(this)->isCommutative();
2307 bool CmpInst::isEquality() {
2308 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2309 return IC->isEquality();
2310 return cast<FCmpInst>(this)->isEquality();
2314 ICmpInst::Predicate ICmpInst::getInversePredicate(Predicate pred) {
2317 assert(!"Unknown icmp predicate!");
2318 case ICMP_EQ: return ICMP_NE;
2319 case ICMP_NE: return ICMP_EQ;
2320 case ICMP_UGT: return ICMP_ULE;
2321 case ICMP_ULT: return ICMP_UGE;
2322 case ICMP_UGE: return ICMP_ULT;
2323 case ICMP_ULE: return ICMP_UGT;
2324 case ICMP_SGT: return ICMP_SLE;
2325 case ICMP_SLT: return ICMP_SGE;
2326 case ICMP_SGE: return ICMP_SLT;
2327 case ICMP_SLE: return ICMP_SGT;
2331 ICmpInst::Predicate ICmpInst::getSwappedPredicate(Predicate pred) {
2333 default: assert(! "Unknown icmp predicate!");
2334 case ICMP_EQ: case ICMP_NE:
2336 case ICMP_SGT: return ICMP_SLT;
2337 case ICMP_SLT: return ICMP_SGT;
2338 case ICMP_SGE: return ICMP_SLE;
2339 case ICMP_SLE: return ICMP_SGE;
2340 case ICMP_UGT: return ICMP_ULT;
2341 case ICMP_ULT: return ICMP_UGT;
2342 case ICMP_UGE: return ICMP_ULE;
2343 case ICMP_ULE: return ICMP_UGE;
2347 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2349 default: assert(! "Unknown icmp predicate!");
2350 case ICMP_EQ: case ICMP_NE:
2351 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2353 case ICMP_UGT: return ICMP_SGT;
2354 case ICMP_ULT: return ICMP_SLT;
2355 case ICMP_UGE: return ICMP_SGE;
2356 case ICMP_ULE: return ICMP_SLE;
2360 bool ICmpInst::isSignedPredicate(Predicate pred) {
2362 default: assert(! "Unknown icmp predicate!");
2363 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2365 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2366 case ICMP_UGE: case ICMP_ULE:
2371 /// Initialize a set of values that all satisfy the condition with C.
2374 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2377 uint32_t BitWidth = C.getBitWidth();
2379 default: assert(0 && "Invalid ICmp opcode to ConstantRange ctor!");
2380 case ICmpInst::ICMP_EQ: Upper++; break;
2381 case ICmpInst::ICMP_NE: Lower++; break;
2382 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2383 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2384 case ICmpInst::ICMP_UGT:
2385 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2387 case ICmpInst::ICMP_SGT:
2388 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2390 case ICmpInst::ICMP_ULE:
2391 Lower = APInt::getMinValue(BitWidth); Upper++;
2393 case ICmpInst::ICMP_SLE:
2394 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2396 case ICmpInst::ICMP_UGE:
2397 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2399 case ICmpInst::ICMP_SGE:
2400 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2403 return ConstantRange(Lower, Upper);
2406 FCmpInst::Predicate FCmpInst::getInversePredicate(Predicate pred) {
2409 assert(!"Unknown icmp predicate!");
2410 case FCMP_OEQ: return FCMP_UNE;
2411 case FCMP_ONE: return FCMP_UEQ;
2412 case FCMP_OGT: return FCMP_ULE;
2413 case FCMP_OLT: return FCMP_UGE;
2414 case FCMP_OGE: return FCMP_ULT;
2415 case FCMP_OLE: return FCMP_UGT;
2416 case FCMP_UEQ: return FCMP_ONE;
2417 case FCMP_UNE: return FCMP_OEQ;
2418 case FCMP_UGT: return FCMP_OLE;
2419 case FCMP_ULT: return FCMP_OGE;
2420 case FCMP_UGE: return FCMP_OLT;
2421 case FCMP_ULE: return FCMP_OGT;
2422 case FCMP_ORD: return FCMP_UNO;
2423 case FCMP_UNO: return FCMP_ORD;
2424 case FCMP_TRUE: return FCMP_FALSE;
2425 case FCMP_FALSE: return FCMP_TRUE;
2429 FCmpInst::Predicate FCmpInst::getSwappedPredicate(Predicate pred) {
2431 default: assert(!"Unknown fcmp predicate!");
2432 case FCMP_FALSE: case FCMP_TRUE:
2433 case FCMP_OEQ: case FCMP_ONE:
2434 case FCMP_UEQ: case FCMP_UNE:
2435 case FCMP_ORD: case FCMP_UNO:
2437 case FCMP_OGT: return FCMP_OLT;
2438 case FCMP_OLT: return FCMP_OGT;
2439 case FCMP_OGE: return FCMP_OLE;
2440 case FCMP_OLE: return FCMP_OGE;
2441 case FCMP_UGT: return FCMP_ULT;
2442 case FCMP_ULT: return FCMP_UGT;
2443 case FCMP_UGE: return FCMP_ULE;
2444 case FCMP_ULE: return FCMP_UGE;
2448 bool CmpInst::isUnsigned(unsigned short predicate) {
2449 switch (predicate) {
2450 default: return false;
2451 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2452 case ICmpInst::ICMP_UGE: return true;
2456 bool CmpInst::isSigned(unsigned short predicate){
2457 switch (predicate) {
2458 default: return false;
2459 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2460 case ICmpInst::ICMP_SGE: return true;
2464 bool CmpInst::isOrdered(unsigned short predicate) {
2465 switch (predicate) {
2466 default: return false;
2467 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2468 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2469 case FCmpInst::FCMP_ORD: return true;
2473 bool CmpInst::isUnordered(unsigned short predicate) {
2474 switch (predicate) {
2475 default: return false;
2476 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2477 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2478 case FCmpInst::FCMP_UNO: return true;
2482 //===----------------------------------------------------------------------===//
2483 // SwitchInst Implementation
2484 //===----------------------------------------------------------------------===//
2486 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2487 assert(Value && Default);
2488 ReservedSpace = 2+NumCases*2;
2490 OperandList = new Use[ReservedSpace];
2492 OperandList[0].init(Value, this);
2493 OperandList[1].init(Default, this);
2496 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2497 /// switch on and a default destination. The number of additional cases can
2498 /// be specified here to make memory allocation more efficient. This
2499 /// constructor can also autoinsert before another instruction.
2500 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2501 Instruction *InsertBefore)
2502 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) {
2503 init(Value, Default, NumCases);
2506 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2507 /// switch on and a default destination. The number of additional cases can
2508 /// be specified here to make memory allocation more efficient. This
2509 /// constructor also autoinserts at the end of the specified BasicBlock.
2510 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2511 BasicBlock *InsertAtEnd)
2512 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) {
2513 init(Value, Default, NumCases);
2516 SwitchInst::SwitchInst(const SwitchInst &SI)
2517 : TerminatorInst(Type::VoidTy, Instruction::Switch,
2518 new Use[SI.getNumOperands()], SI.getNumOperands()) {
2519 Use *OL = OperandList, *InOL = SI.OperandList;
2520 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2521 OL[i].init(InOL[i], this);
2522 OL[i+1].init(InOL[i+1], this);
2526 SwitchInst::~SwitchInst() {
2527 delete [] OperandList;
2531 /// addCase - Add an entry to the switch instruction...
2533 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2534 unsigned OpNo = NumOperands;
2535 if (OpNo+2 > ReservedSpace)
2536 resizeOperands(0); // Get more space!
2537 // Initialize some new operands.
2538 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2539 NumOperands = OpNo+2;
2540 OperandList[OpNo].init(OnVal, this);
2541 OperandList[OpNo+1].init(Dest, this);
2544 /// removeCase - This method removes the specified successor from the switch
2545 /// instruction. Note that this cannot be used to remove the default
2546 /// destination (successor #0).
2548 void SwitchInst::removeCase(unsigned idx) {
2549 assert(idx != 0 && "Cannot remove the default case!");
2550 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2552 unsigned NumOps = getNumOperands();
2553 Use *OL = OperandList;
2555 // Move everything after this operand down.
2557 // FIXME: we could just swap with the end of the list, then erase. However,
2558 // client might not expect this to happen. The code as it is thrashes the
2559 // use/def lists, which is kinda lame.
2560 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2562 OL[i-2+1] = OL[i+1];
2565 // Nuke the last value.
2566 OL[NumOps-2].set(0);
2567 OL[NumOps-2+1].set(0);
2568 NumOperands = NumOps-2;
2571 /// resizeOperands - resize operands - This adjusts the length of the operands
2572 /// list according to the following behavior:
2573 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2574 /// of operation. This grows the number of ops by 1.5 times.
2575 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2576 /// 3. If NumOps == NumOperands, trim the reserved space.
2578 void SwitchInst::resizeOperands(unsigned NumOps) {
2580 NumOps = getNumOperands()/2*6;
2581 } else if (NumOps*2 > NumOperands) {
2582 // No resize needed.
2583 if (ReservedSpace >= NumOps) return;
2584 } else if (NumOps == NumOperands) {
2585 if (ReservedSpace == NumOps) return;
2590 ReservedSpace = NumOps;
2591 Use *NewOps = new Use[NumOps];
2592 Use *OldOps = OperandList;
2593 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2594 NewOps[i].init(OldOps[i], this);
2598 OperandList = NewOps;
2602 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2603 return getSuccessor(idx);
2605 unsigned SwitchInst::getNumSuccessorsV() const {
2606 return getNumSuccessors();
2608 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2609 setSuccessor(idx, B);
2613 // Define these methods here so vtables don't get emitted into every translation
2614 // unit that uses these classes.
2616 GetElementPtrInst *GetElementPtrInst::clone() const {
2617 return new GetElementPtrInst(*this);
2620 BinaryOperator *BinaryOperator::clone() const {
2621 return create(getOpcode(), Ops[0], Ops[1]);
2624 FCmpInst* FCmpInst::clone() const {
2625 return new FCmpInst(getPredicate(), Ops[0], Ops[1]);
2627 ICmpInst* ICmpInst::clone() const {
2628 return new ICmpInst(getPredicate(), Ops[0], Ops[1]);
2631 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
2632 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
2633 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
2634 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
2635 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
2636 CastInst *TruncInst::clone() const { return new TruncInst(*this); }
2637 CastInst *ZExtInst::clone() const { return new ZExtInst(*this); }
2638 CastInst *SExtInst::clone() const { return new SExtInst(*this); }
2639 CastInst *FPTruncInst::clone() const { return new FPTruncInst(*this); }
2640 CastInst *FPExtInst::clone() const { return new FPExtInst(*this); }
2641 CastInst *UIToFPInst::clone() const { return new UIToFPInst(*this); }
2642 CastInst *SIToFPInst::clone() const { return new SIToFPInst(*this); }
2643 CastInst *FPToUIInst::clone() const { return new FPToUIInst(*this); }
2644 CastInst *FPToSIInst::clone() const { return new FPToSIInst(*this); }
2645 CastInst *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
2646 CastInst *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
2647 CastInst *BitCastInst::clone() const { return new BitCastInst(*this); }
2648 CallInst *CallInst::clone() const { return new CallInst(*this); }
2649 SelectInst *SelectInst::clone() const { return new SelectInst(*this); }
2650 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
2652 ExtractElementInst *ExtractElementInst::clone() const {
2653 return new ExtractElementInst(*this);
2655 InsertElementInst *InsertElementInst::clone() const {
2656 return new InsertElementInst(*this);
2658 ShuffleVectorInst *ShuffleVectorInst::clone() const {
2659 return new ShuffleVectorInst(*this);
2661 PHINode *PHINode::clone() const { return new PHINode(*this); }
2662 ReturnInst *ReturnInst::clone() const { return new ReturnInst(*this); }
2663 BranchInst *BranchInst::clone() const { return new BranchInst(*this); }
2664 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
2665 InvokeInst *InvokeInst::clone() const { return new InvokeInst(*this); }
2666 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
2667 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}