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/Support/CallSite.h"
21 #include "llvm/Support/ConstantRange.h"
22 #include "llvm/Support/MathExtras.h"
25 //===----------------------------------------------------------------------===//
27 //===----------------------------------------------------------------------===//
29 CallSite::CallSite(Instruction *C) {
30 assert((isa<CallInst>(C) || isa<InvokeInst>(C)) && "Not a call!");
33 unsigned CallSite::getCallingConv() const {
34 if (CallInst *CI = dyn_cast<CallInst>(I))
35 return CI->getCallingConv();
37 return cast<InvokeInst>(I)->getCallingConv();
39 void CallSite::setCallingConv(unsigned CC) {
40 if (CallInst *CI = dyn_cast<CallInst>(I))
41 CI->setCallingConv(CC);
43 cast<InvokeInst>(I)->setCallingConv(CC);
45 const PAListPtr &CallSite::getParamAttrs() const {
46 if (CallInst *CI = dyn_cast<CallInst>(I))
47 return CI->getParamAttrs();
49 return cast<InvokeInst>(I)->getParamAttrs();
51 void CallSite::setParamAttrs(const PAListPtr &PAL) {
52 if (CallInst *CI = dyn_cast<CallInst>(I))
53 CI->setParamAttrs(PAL);
55 cast<InvokeInst>(I)->setParamAttrs(PAL);
57 bool CallSite::paramHasAttr(uint16_t i, ParameterAttributes attr) const {
58 if (CallInst *CI = dyn_cast<CallInst>(I))
59 return CI->paramHasAttr(i, attr);
61 return cast<InvokeInst>(I)->paramHasAttr(i, attr);
63 uint16_t CallSite::getParamAlignment(uint16_t i) const {
64 if (CallInst *CI = dyn_cast<CallInst>(I))
65 return CI->getParamAlignment(i);
67 return cast<InvokeInst>(I)->getParamAlignment(i);
70 bool CallSite::doesNotAccessMemory() const {
71 if (CallInst *CI = dyn_cast<CallInst>(I))
72 return CI->doesNotAccessMemory();
74 return cast<InvokeInst>(I)->doesNotAccessMemory();
76 bool CallSite::onlyReadsMemory() const {
77 if (CallInst *CI = dyn_cast<CallInst>(I))
78 return CI->onlyReadsMemory();
80 return cast<InvokeInst>(I)->onlyReadsMemory();
82 bool CallSite::doesNotThrow() const {
83 if (CallInst *CI = dyn_cast<CallInst>(I))
84 return CI->doesNotThrow();
86 return cast<InvokeInst>(I)->doesNotThrow();
88 void CallSite::setDoesNotThrow(bool doesNotThrow) {
89 if (CallInst *CI = dyn_cast<CallInst>(I))
90 CI->setDoesNotThrow(doesNotThrow);
92 cast<InvokeInst>(I)->setDoesNotThrow(doesNotThrow);
95 //===----------------------------------------------------------------------===//
96 // TerminatorInst Class
97 //===----------------------------------------------------------------------===//
99 // Out of line virtual method, so the vtable, etc has a home.
100 TerminatorInst::~TerminatorInst() {
103 //===----------------------------------------------------------------------===//
104 // UnaryInstruction Class
105 //===----------------------------------------------------------------------===//
107 // Out of line virtual method, so the vtable, etc has a home.
108 UnaryInstruction::~UnaryInstruction() {
111 //===----------------------------------------------------------------------===//
113 //===----------------------------------------------------------------------===//
115 PHINode::PHINode(const PHINode &PN)
116 : Instruction(PN.getType(), Instruction::PHI,
117 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
118 ReservedSpace(PN.getNumOperands()) {
119 Use *OL = OperandList;
120 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
121 OL[i].init(PN.getOperand(i), this);
122 OL[i+1].init(PN.getOperand(i+1), this);
126 PHINode::~PHINode() {
127 dropHungoffUses(OperandList);
130 // removeIncomingValue - Remove an incoming value. This is useful if a
131 // predecessor basic block is deleted.
132 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
133 unsigned NumOps = getNumOperands();
134 Use *OL = OperandList;
135 assert(Idx*2 < NumOps && "BB not in PHI node!");
136 Value *Removed = OL[Idx*2];
138 // Move everything after this operand down.
140 // FIXME: we could just swap with the end of the list, then erase. However,
141 // client might not expect this to happen. The code as it is thrashes the
142 // use/def lists, which is kinda lame.
143 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
148 // Nuke the last value.
150 OL[NumOps-2+1].set(0);
151 NumOperands = NumOps-2;
153 // If the PHI node is dead, because it has zero entries, nuke it now.
154 if (NumOps == 2 && DeletePHIIfEmpty) {
155 // If anyone is using this PHI, make them use a dummy value instead...
156 replaceAllUsesWith(UndefValue::get(getType()));
162 /// resizeOperands - resize operands - This adjusts the length of the operands
163 /// list according to the following behavior:
164 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
165 /// of operation. This grows the number of ops by 1.5 times.
166 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
167 /// 3. If NumOps == NumOperands, trim the reserved space.
169 void PHINode::resizeOperands(unsigned NumOps) {
170 unsigned e = getNumOperands();
173 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
174 } else if (NumOps*2 > NumOperands) {
176 if (ReservedSpace >= NumOps) return;
177 } else if (NumOps == NumOperands) {
178 if (ReservedSpace == NumOps) return;
183 ReservedSpace = NumOps;
184 Use *OldOps = OperandList;
185 Use *NewOps = allocHungoffUses(NumOps);
186 for (unsigned i = 0; i != e; ++i) {
187 NewOps[i].init(OldOps[i], this);
189 OperandList = NewOps;
190 if (OldOps) Use::zap(OldOps, OldOps + e, true);
193 /// hasConstantValue - If the specified PHI node always merges together the same
194 /// value, return the value, otherwise return null.
196 Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) const {
197 // If the PHI node only has one incoming value, eliminate the PHI node...
198 if (getNumIncomingValues() == 1) {
199 if (getIncomingValue(0) != this) // not X = phi X
200 return getIncomingValue(0);
202 return UndefValue::get(getType()); // Self cycle is dead.
205 // Otherwise if all of the incoming values are the same for the PHI, replace
206 // the PHI node with the incoming value.
209 bool HasUndefInput = false;
210 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
211 if (isa<UndefValue>(getIncomingValue(i))) {
212 HasUndefInput = true;
213 } else if (getIncomingValue(i) != this) { // Not the PHI node itself...
214 if (InVal && getIncomingValue(i) != InVal)
215 return 0; // Not the same, bail out.
217 InVal = getIncomingValue(i);
220 // The only case that could cause InVal to be null is if we have a PHI node
221 // that only has entries for itself. In this case, there is no entry into the
222 // loop, so kill the PHI.
224 if (InVal == 0) InVal = UndefValue::get(getType());
226 // If we have a PHI node like phi(X, undef, X), where X is defined by some
227 // instruction, we cannot always return X as the result of the PHI node. Only
228 // do this if X is not an instruction (thus it must dominate the PHI block),
229 // or if the client is prepared to deal with this possibility.
230 if (HasUndefInput && !AllowNonDominatingInstruction)
231 if (Instruction *IV = dyn_cast<Instruction>(InVal))
232 // If it's in the entry block, it dominates everything.
233 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
235 return 0; // Cannot guarantee that InVal dominates this PHINode.
237 // All of the incoming values are the same, return the value now.
242 //===----------------------------------------------------------------------===//
243 // CallInst Implementation
244 //===----------------------------------------------------------------------===//
246 CallInst::~CallInst() {
249 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
250 assert(NumOperands == NumParams+1 && "NumOperands not set up?");
251 Use *OL = OperandList;
252 OL[0].init(Func, this);
254 const FunctionType *FTy =
255 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
256 FTy = FTy; // silence warning.
258 assert((NumParams == FTy->getNumParams() ||
259 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
260 "Calling a function with bad signature!");
261 for (unsigned i = 0; i != NumParams; ++i) {
262 assert((i >= FTy->getNumParams() ||
263 FTy->getParamType(i) == Params[i]->getType()) &&
264 "Calling a function with a bad signature!");
265 OL[i+1].init(Params[i], this);
269 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
270 assert(NumOperands == 3 && "NumOperands not set up?");
271 Use *OL = OperandList;
272 OL[0].init(Func, this);
273 OL[1].init(Actual1, this);
274 OL[2].init(Actual2, this);
276 const FunctionType *FTy =
277 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
278 FTy = FTy; // silence warning.
280 assert((FTy->getNumParams() == 2 ||
281 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
282 "Calling a function with bad signature");
283 assert((0 >= FTy->getNumParams() ||
284 FTy->getParamType(0) == Actual1->getType()) &&
285 "Calling a function with a bad signature!");
286 assert((1 >= FTy->getNumParams() ||
287 FTy->getParamType(1) == Actual2->getType()) &&
288 "Calling a function with a bad signature!");
291 void CallInst::init(Value *Func, Value *Actual) {
292 assert(NumOperands == 2 && "NumOperands not set up?");
293 Use *OL = OperandList;
294 OL[0].init(Func, this);
295 OL[1].init(Actual, this);
297 const FunctionType *FTy =
298 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
299 FTy = FTy; // silence warning.
301 assert((FTy->getNumParams() == 1 ||
302 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
303 "Calling a function with bad signature");
304 assert((0 == FTy->getNumParams() ||
305 FTy->getParamType(0) == Actual->getType()) &&
306 "Calling a function with a bad signature!");
309 void CallInst::init(Value *Func) {
310 assert(NumOperands == 1 && "NumOperands not set up?");
311 Use *OL = OperandList;
312 OL[0].init(Func, this);
314 const FunctionType *FTy =
315 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
316 FTy = FTy; // silence warning.
318 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
321 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
322 Instruction *InsertBefore)
323 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
324 ->getElementType())->getReturnType(),
326 OperandTraits<CallInst>::op_end(this) - 2,
332 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
333 BasicBlock *InsertAtEnd)
334 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
335 ->getElementType())->getReturnType(),
337 OperandTraits<CallInst>::op_end(this) - 2,
342 CallInst::CallInst(Value *Func, const std::string &Name,
343 Instruction *InsertBefore)
344 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
345 ->getElementType())->getReturnType(),
347 OperandTraits<CallInst>::op_end(this) - 1,
353 CallInst::CallInst(Value *Func, const std::string &Name,
354 BasicBlock *InsertAtEnd)
355 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
356 ->getElementType())->getReturnType(),
358 OperandTraits<CallInst>::op_end(this) - 1,
364 CallInst::CallInst(const CallInst &CI)
365 : Instruction(CI.getType(), Instruction::Call,
366 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
367 CI.getNumOperands()) {
368 setParamAttrs(CI.getParamAttrs());
369 SubclassData = CI.SubclassData;
370 Use *OL = OperandList;
371 Use *InOL = CI.OperandList;
372 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
373 OL[i].init(InOL[i], this);
376 bool CallInst::paramHasAttr(unsigned i, ParameterAttributes attr) const {
377 if (ParamAttrs.paramHasAttr(i, attr))
379 if (const Function *F = getCalledFunction())
380 return F->paramHasAttr(i, attr);
384 void CallInst::setDoesNotThrow(bool doesNotThrow) {
385 PAListPtr PAL = getParamAttrs();
387 PAL = PAL.addAttr(0, ParamAttr::NoUnwind);
389 PAL = PAL.removeAttr(0, ParamAttr::NoUnwind);
394 //===----------------------------------------------------------------------===//
395 // InvokeInst Implementation
396 //===----------------------------------------------------------------------===//
398 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
399 Value* const *Args, unsigned NumArgs) {
400 assert(NumOperands == 3+NumArgs && "NumOperands not set up?");
401 Use *OL = OperandList;
402 OL[0].init(Fn, this);
403 OL[1].init(IfNormal, this);
404 OL[2].init(IfException, this);
405 const FunctionType *FTy =
406 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
407 FTy = FTy; // silence warning.
409 assert(((NumArgs == FTy->getNumParams()) ||
410 (FTy->isVarArg() && NumArgs > FTy->getNumParams())) &&
411 "Calling a function with bad signature");
413 for (unsigned i = 0, e = NumArgs; i != e; i++) {
414 assert((i >= FTy->getNumParams() ||
415 FTy->getParamType(i) == Args[i]->getType()) &&
416 "Invoking a function with a bad signature!");
418 OL[i+3].init(Args[i], this);
422 InvokeInst::InvokeInst(const InvokeInst &II)
423 : TerminatorInst(II.getType(), Instruction::Invoke,
424 OperandTraits<InvokeInst>::op_end(this)
425 - II.getNumOperands(),
426 II.getNumOperands()) {
427 setParamAttrs(II.getParamAttrs());
428 SubclassData = II.SubclassData;
429 Use *OL = OperandList, *InOL = II.OperandList;
430 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
431 OL[i].init(InOL[i], this);
434 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
435 return getSuccessor(idx);
437 unsigned InvokeInst::getNumSuccessorsV() const {
438 return getNumSuccessors();
440 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
441 return setSuccessor(idx, B);
444 bool InvokeInst::paramHasAttr(unsigned i, ParameterAttributes attr) const {
445 if (ParamAttrs.paramHasAttr(i, attr))
447 if (const Function *F = getCalledFunction())
448 return F->paramHasAttr(i, attr);
452 void InvokeInst::setDoesNotThrow(bool doesNotThrow) {
453 PAListPtr PAL = getParamAttrs();
455 PAL = PAL.addAttr(0, ParamAttr::NoUnwind);
457 PAL = PAL.removeAttr(0, ParamAttr::NoUnwind);
462 //===----------------------------------------------------------------------===//
463 // ReturnInst Implementation
464 //===----------------------------------------------------------------------===//
466 ReturnInst::ReturnInst(const ReturnInst &RI)
467 : TerminatorInst(Type::VoidTy, Instruction::Ret,
468 OperandTraits<ReturnInst>::op_end(this)
469 - RI.getNumOperands(),
470 RI.getNumOperands()) {
471 unsigned N = RI.getNumOperands();
473 Op<0>().init(RI.Op<0>(), this);
475 Use *OL = OperandList;
476 for (unsigned i = 0; i < N; ++i)
477 OL[i].init(RI.getOperand(i), this);
481 ReturnInst::ReturnInst(Value *retVal, Instruction *InsertBefore)
482 : TerminatorInst(Type::VoidTy, Instruction::Ret,
483 OperandTraits<ReturnInst>::op_end(this) - (retVal != 0),
484 retVal != 0, InsertBefore) {
488 ReturnInst::ReturnInst(Value *retVal, BasicBlock *InsertAtEnd)
489 : TerminatorInst(Type::VoidTy, Instruction::Ret,
490 OperandTraits<ReturnInst>::op_end(this) - (retVal != 0),
491 retVal != 0, InsertAtEnd) {
495 ReturnInst::ReturnInst(BasicBlock *InsertAtEnd)
496 : TerminatorInst(Type::VoidTy, Instruction::Ret,
497 OperandTraits<ReturnInst>::op_end(this),
501 ReturnInst::ReturnInst(Value * const* retVals, unsigned N,
502 Instruction *InsertBefore)
503 : TerminatorInst(Type::VoidTy, Instruction::Ret,
504 OperandTraits<ReturnInst>::op_end(this) - N,
509 ReturnInst::ReturnInst(Value * const* retVals, unsigned N,
510 BasicBlock *InsertAtEnd)
511 : TerminatorInst(Type::VoidTy, Instruction::Ret,
512 OperandTraits<ReturnInst>::op_end(this) - N,
518 void ReturnInst::init(Value * const* retVals, unsigned N) {
519 assert (N > 0 && "Invalid operands numbers in ReturnInst init");
522 if (NumOperands == 1) {
524 if (V->getType() == Type::VoidTy)
526 Op<0>().init(V, this);
530 Use *OL = OperandList;
531 for (unsigned i = 0; i < NumOperands; ++i) {
532 Value *V = *retVals++;
533 assert(!isa<BasicBlock>(V) &&
534 "Cannot return basic block. Probably using the incorrect ctor");
539 unsigned ReturnInst::getNumSuccessorsV() const {
540 return getNumSuccessors();
543 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
544 /// emit the vtable for the class in this translation unit.
545 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
546 assert(0 && "ReturnInst has no successors!");
549 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
550 assert(0 && "ReturnInst has no successors!");
555 ReturnInst::~ReturnInst() {
558 //===----------------------------------------------------------------------===//
559 // UnwindInst Implementation
560 //===----------------------------------------------------------------------===//
562 UnwindInst::UnwindInst(Instruction *InsertBefore)
563 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertBefore) {
565 UnwindInst::UnwindInst(BasicBlock *InsertAtEnd)
566 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertAtEnd) {
570 unsigned UnwindInst::getNumSuccessorsV() const {
571 return getNumSuccessors();
574 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
575 assert(0 && "UnwindInst has no successors!");
578 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
579 assert(0 && "UnwindInst has no successors!");
584 //===----------------------------------------------------------------------===//
585 // UnreachableInst Implementation
586 //===----------------------------------------------------------------------===//
588 UnreachableInst::UnreachableInst(Instruction *InsertBefore)
589 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertBefore) {
591 UnreachableInst::UnreachableInst(BasicBlock *InsertAtEnd)
592 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertAtEnd) {
595 unsigned UnreachableInst::getNumSuccessorsV() const {
596 return getNumSuccessors();
599 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
600 assert(0 && "UnwindInst has no successors!");
603 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
604 assert(0 && "UnwindInst has no successors!");
609 //===----------------------------------------------------------------------===//
610 // BranchInst Implementation
611 //===----------------------------------------------------------------------===//
613 void BranchInst::AssertOK() {
615 assert(getCondition()->getType() == Type::Int1Ty &&
616 "May only branch on boolean predicates!");
619 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
620 : TerminatorInst(Type::VoidTy, Instruction::Br,
621 OperandTraits<BranchInst>::op_end(this) - 1,
623 assert(IfTrue != 0 && "Branch destination may not be null!");
624 Op<0>().init(reinterpret_cast<Value*>(IfTrue), this);
626 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
627 Instruction *InsertBefore)
628 : TerminatorInst(Type::VoidTy, Instruction::Br,
629 OperandTraits<BranchInst>::op_end(this) - 3,
631 Op<0>().init(reinterpret_cast<Value*>(IfTrue), this);
632 Op<1>().init(reinterpret_cast<Value*>(IfFalse), this);
633 Op<2>().init(Cond, this);
639 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
640 : TerminatorInst(Type::VoidTy, Instruction::Br,
641 OperandTraits<BranchInst>::op_end(this) - 1,
643 assert(IfTrue != 0 && "Branch destination may not be null!");
644 Op<0>().init(reinterpret_cast<Value*>(IfTrue), this);
647 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
648 BasicBlock *InsertAtEnd)
649 : TerminatorInst(Type::VoidTy, Instruction::Br,
650 OperandTraits<BranchInst>::op_end(this) - 3,
652 Op<0>().init(reinterpret_cast<Value*>(IfTrue), this);
653 Op<1>().init(reinterpret_cast<Value*>(IfFalse), this);
654 Op<2>().init(Cond, this);
661 BranchInst::BranchInst(const BranchInst &BI) :
662 TerminatorInst(Type::VoidTy, Instruction::Br,
663 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
664 BI.getNumOperands()) {
665 OperandList[0].init(BI.getOperand(0), this);
666 if (BI.getNumOperands() != 1) {
667 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
668 OperandList[1].init(BI.getOperand(1), this);
669 OperandList[2].init(BI.getOperand(2), this);
673 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
674 return getSuccessor(idx);
676 unsigned BranchInst::getNumSuccessorsV() const {
677 return getNumSuccessors();
679 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
680 setSuccessor(idx, B);
684 //===----------------------------------------------------------------------===//
685 // AllocationInst Implementation
686 //===----------------------------------------------------------------------===//
688 static Value *getAISize(Value *Amt) {
690 Amt = ConstantInt::get(Type::Int32Ty, 1);
692 assert(!isa<BasicBlock>(Amt) &&
693 "Passed basic block into allocation size parameter! Use other ctor");
694 assert(Amt->getType() == Type::Int32Ty &&
695 "Malloc/Allocation array size is not a 32-bit integer!");
700 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
701 unsigned Align, const std::string &Name,
702 Instruction *InsertBefore)
703 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
706 assert(Ty != Type::VoidTy && "Cannot allocate void!");
710 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
711 unsigned Align, const std::string &Name,
712 BasicBlock *InsertAtEnd)
713 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
716 assert(Ty != Type::VoidTy && "Cannot allocate void!");
720 // Out of line virtual method, so the vtable, etc has a home.
721 AllocationInst::~AllocationInst() {
724 void AllocationInst::setAlignment(unsigned Align) {
725 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
726 SubclassData = Log2_32(Align) + 1;
727 assert(getAlignment() == Align && "Alignment representation error!");
730 bool AllocationInst::isArrayAllocation() const {
731 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
732 return CI->getZExtValue() != 1;
736 const Type *AllocationInst::getAllocatedType() const {
737 return getType()->getElementType();
740 AllocaInst::AllocaInst(const AllocaInst &AI)
741 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
742 Instruction::Alloca, AI.getAlignment()) {
745 MallocInst::MallocInst(const MallocInst &MI)
746 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
747 Instruction::Malloc, MI.getAlignment()) {
750 //===----------------------------------------------------------------------===//
751 // FreeInst Implementation
752 //===----------------------------------------------------------------------===//
754 void FreeInst::AssertOK() {
755 assert(isa<PointerType>(getOperand(0)->getType()) &&
756 "Can not free something of nonpointer type!");
759 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
760 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertBefore) {
764 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
765 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertAtEnd) {
770 //===----------------------------------------------------------------------===//
771 // LoadInst Implementation
772 //===----------------------------------------------------------------------===//
774 void LoadInst::AssertOK() {
775 assert(isa<PointerType>(getOperand(0)->getType()) &&
776 "Ptr must have pointer type.");
779 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
780 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
781 Load, Ptr, InsertBef) {
788 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
789 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
790 Load, Ptr, InsertAE) {
797 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
798 Instruction *InsertBef)
799 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
800 Load, Ptr, InsertBef) {
801 setVolatile(isVolatile);
807 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
808 unsigned Align, Instruction *InsertBef)
809 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
810 Load, Ptr, InsertBef) {
811 setVolatile(isVolatile);
817 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
818 unsigned Align, BasicBlock *InsertAE)
819 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
820 Load, Ptr, InsertAE) {
821 setVolatile(isVolatile);
827 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
828 BasicBlock *InsertAE)
829 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
830 Load, Ptr, InsertAE) {
831 setVolatile(isVolatile);
839 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
840 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
841 Load, Ptr, InsertBef) {
845 if (Name && Name[0]) setName(Name);
848 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
849 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
850 Load, Ptr, InsertAE) {
854 if (Name && Name[0]) setName(Name);
857 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
858 Instruction *InsertBef)
859 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
860 Load, Ptr, InsertBef) {
861 setVolatile(isVolatile);
864 if (Name && Name[0]) setName(Name);
867 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
868 BasicBlock *InsertAE)
869 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
870 Load, Ptr, InsertAE) {
871 setVolatile(isVolatile);
874 if (Name && Name[0]) setName(Name);
877 void LoadInst::setAlignment(unsigned Align) {
878 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
879 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
882 //===----------------------------------------------------------------------===//
883 // StoreInst Implementation
884 //===----------------------------------------------------------------------===//
886 void StoreInst::AssertOK() {
887 assert(isa<PointerType>(getOperand(1)->getType()) &&
888 "Ptr must have pointer type!");
889 assert(getOperand(0)->getType() ==
890 cast<PointerType>(getOperand(1)->getType())->getElementType()
891 && "Ptr must be a pointer to Val type!");
895 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
896 : Instruction(Type::VoidTy, Store,
897 OperandTraits<StoreInst>::op_begin(this),
898 OperandTraits<StoreInst>::operands(this),
900 Op<0>().init(val, this);
901 Op<1>().init(addr, this);
907 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
908 : Instruction(Type::VoidTy, Store,
909 OperandTraits<StoreInst>::op_begin(this),
910 OperandTraits<StoreInst>::operands(this),
912 Op<0>().init(val, this);
913 Op<1>().init(addr, this);
919 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
920 Instruction *InsertBefore)
921 : Instruction(Type::VoidTy, Store,
922 OperandTraits<StoreInst>::op_begin(this),
923 OperandTraits<StoreInst>::operands(this),
925 Op<0>().init(val, this);
926 Op<1>().init(addr, this);
927 setVolatile(isVolatile);
932 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
933 unsigned Align, Instruction *InsertBefore)
934 : Instruction(Type::VoidTy, Store,
935 OperandTraits<StoreInst>::op_begin(this),
936 OperandTraits<StoreInst>::operands(this),
938 Op<0>().init(val, this);
939 Op<1>().init(addr, this);
940 setVolatile(isVolatile);
945 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
946 unsigned Align, BasicBlock *InsertAtEnd)
947 : Instruction(Type::VoidTy, Store,
948 OperandTraits<StoreInst>::op_begin(this),
949 OperandTraits<StoreInst>::operands(this),
951 Op<0>().init(val, this);
952 Op<1>().init(addr, this);
953 setVolatile(isVolatile);
958 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
959 BasicBlock *InsertAtEnd)
960 : Instruction(Type::VoidTy, Store,
961 OperandTraits<StoreInst>::op_begin(this),
962 OperandTraits<StoreInst>::operands(this),
964 Op<0>().init(val, this);
965 Op<1>().init(addr, this);
966 setVolatile(isVolatile);
971 void StoreInst::setAlignment(unsigned Align) {
972 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
973 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
976 //===----------------------------------------------------------------------===//
977 // GetElementPtrInst Implementation
978 //===----------------------------------------------------------------------===//
980 static unsigned retrieveAddrSpace(const Value *Val) {
981 return cast<PointerType>(Val->getType())->getAddressSpace();
984 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx) {
985 assert(NumOperands == 1+NumIdx && "NumOperands not initialized?");
986 Use *OL = OperandList;
987 OL[0].init(Ptr, this);
989 for (unsigned i = 0; i != NumIdx; ++i)
990 OL[i+1].init(Idx[i], this);
993 void GetElementPtrInst::init(Value *Ptr, Value *Idx) {
994 assert(NumOperands == 2 && "NumOperands not initialized?");
995 Use *OL = OperandList;
996 OL[0].init(Ptr, this);
997 OL[1].init(Idx, this);
1000 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1001 : Instruction(reinterpret_cast<const Type*>(GEPI.getType()), GetElementPtr,
1002 OperandTraits<GetElementPtrInst>::op_end(this)
1003 - GEPI.getNumOperands(),
1004 GEPI.getNumOperands()) {
1005 Use *OL = OperandList;
1006 Use *GEPIOL = GEPI.OperandList;
1007 for (unsigned i = 0, E = NumOperands; i != E; ++i)
1008 OL[i].init(GEPIOL[i], this);
1011 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1012 const std::string &Name, Instruction *InBe)
1013 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1014 retrieveAddrSpace(Ptr)),
1016 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1022 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1023 const std::string &Name, BasicBlock *IAE)
1024 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1025 retrieveAddrSpace(Ptr)),
1027 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1033 // getIndexedType - Returns the type of the element that would be loaded with
1034 // a load instruction with the specified parameters.
1036 // A null type is returned if the indices are invalid for the specified
1039 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1042 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1043 if (!PTy) return 0; // Type isn't a pointer type!
1044 const Type *Agg = PTy->getElementType();
1046 // Handle the special case of the empty set index set...
1050 return ExtractValueInst::getIndexedType(Agg, Idxs+1, Idxs+NumIdx);
1053 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1054 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1055 if (!PTy) return 0; // Type isn't a pointer type!
1057 // Check the pointer index.
1058 if (!PTy->indexValid(Idx)) return 0;
1060 return PTy->getElementType();
1064 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1065 /// zeros. If so, the result pointer and the first operand have the same
1066 /// value, just potentially different types.
1067 bool GetElementPtrInst::hasAllZeroIndices() const {
1068 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1069 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1070 if (!CI->isZero()) return false;
1078 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1079 /// constant integers. If so, the result pointer and the first operand have
1080 /// a constant offset between them.
1081 bool GetElementPtrInst::hasAllConstantIndices() const {
1082 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1083 if (!isa<ConstantInt>(getOperand(i)))
1090 //===----------------------------------------------------------------------===//
1091 // ExtractElementInst Implementation
1092 //===----------------------------------------------------------------------===//
1094 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1095 const std::string &Name,
1096 Instruction *InsertBef)
1097 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1099 OperandTraits<ExtractElementInst>::op_begin(this),
1101 assert(isValidOperands(Val, Index) &&
1102 "Invalid extractelement instruction operands!");
1103 Op<0>().init(Val, this);
1104 Op<1>().init(Index, this);
1108 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1109 const std::string &Name,
1110 Instruction *InsertBef)
1111 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1113 OperandTraits<ExtractElementInst>::op_begin(this),
1115 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1116 assert(isValidOperands(Val, Index) &&
1117 "Invalid extractelement instruction operands!");
1118 Op<0>().init(Val, this);
1119 Op<1>().init(Index, this);
1124 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1125 const std::string &Name,
1126 BasicBlock *InsertAE)
1127 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1129 OperandTraits<ExtractElementInst>::op_begin(this),
1131 assert(isValidOperands(Val, Index) &&
1132 "Invalid extractelement instruction operands!");
1134 Op<0>().init(Val, this);
1135 Op<1>().init(Index, this);
1139 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1140 const std::string &Name,
1141 BasicBlock *InsertAE)
1142 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1144 OperandTraits<ExtractElementInst>::op_begin(this),
1146 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1147 assert(isValidOperands(Val, Index) &&
1148 "Invalid extractelement instruction operands!");
1150 Op<0>().init(Val, this);
1151 Op<1>().init(Index, this);
1156 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1157 if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty)
1163 //===----------------------------------------------------------------------===//
1164 // InsertElementInst Implementation
1165 //===----------------------------------------------------------------------===//
1167 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
1168 : Instruction(IE.getType(), InsertElement,
1169 OperandTraits<InsertElementInst>::op_begin(this), 3) {
1170 Op<0>().init(IE.Op<0>(), this);
1171 Op<1>().init(IE.Op<1>(), this);
1172 Op<2>().init(IE.Op<2>(), this);
1174 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1175 const std::string &Name,
1176 Instruction *InsertBef)
1177 : Instruction(Vec->getType(), InsertElement,
1178 OperandTraits<InsertElementInst>::op_begin(this),
1180 assert(isValidOperands(Vec, Elt, Index) &&
1181 "Invalid insertelement instruction operands!");
1182 Op<0>().init(Vec, this);
1183 Op<1>().init(Elt, this);
1184 Op<2>().init(Index, this);
1188 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1189 const std::string &Name,
1190 Instruction *InsertBef)
1191 : Instruction(Vec->getType(), InsertElement,
1192 OperandTraits<InsertElementInst>::op_begin(this),
1194 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1195 assert(isValidOperands(Vec, Elt, Index) &&
1196 "Invalid insertelement instruction operands!");
1197 Op<0>().init(Vec, this);
1198 Op<1>().init(Elt, this);
1199 Op<2>().init(Index, this);
1204 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1205 const std::string &Name,
1206 BasicBlock *InsertAE)
1207 : Instruction(Vec->getType(), InsertElement,
1208 OperandTraits<InsertElementInst>::op_begin(this),
1210 assert(isValidOperands(Vec, Elt, Index) &&
1211 "Invalid insertelement instruction operands!");
1213 Op<0>().init(Vec, this);
1214 Op<1>().init(Elt, this);
1215 Op<2>().init(Index, this);
1219 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1220 const std::string &Name,
1221 BasicBlock *InsertAE)
1222 : Instruction(Vec->getType(), InsertElement,
1223 OperandTraits<InsertElementInst>::op_begin(this),
1225 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1226 assert(isValidOperands(Vec, Elt, Index) &&
1227 "Invalid insertelement instruction operands!");
1229 Op<0>().init(Vec, this);
1230 Op<1>().init(Elt, this);
1231 Op<2>().init(Index, this);
1235 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1236 const Value *Index) {
1237 if (!isa<VectorType>(Vec->getType()))
1238 return false; // First operand of insertelement must be vector type.
1240 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1241 return false;// Second operand of insertelement must be vector element type.
1243 if (Index->getType() != Type::Int32Ty)
1244 return false; // Third operand of insertelement must be uint.
1249 //===----------------------------------------------------------------------===//
1250 // ShuffleVectorInst Implementation
1251 //===----------------------------------------------------------------------===//
1253 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
1254 : Instruction(SV.getType(), ShuffleVector,
1255 OperandTraits<ShuffleVectorInst>::op_begin(this),
1256 OperandTraits<ShuffleVectorInst>::operands(this)) {
1257 Op<0>().init(SV.Op<0>(), this);
1258 Op<1>().init(SV.Op<1>(), this);
1259 Op<2>().init(SV.Op<2>(), this);
1262 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1263 const std::string &Name,
1264 Instruction *InsertBefore)
1265 : Instruction(V1->getType(), ShuffleVector,
1266 OperandTraits<ShuffleVectorInst>::op_begin(this),
1267 OperandTraits<ShuffleVectorInst>::operands(this),
1269 assert(isValidOperands(V1, V2, Mask) &&
1270 "Invalid shuffle vector instruction operands!");
1271 Op<0>().init(V1, this);
1272 Op<1>().init(V2, this);
1273 Op<2>().init(Mask, this);
1277 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1278 const std::string &Name,
1279 BasicBlock *InsertAtEnd)
1280 : Instruction(V1->getType(), ShuffleVector,
1281 OperandTraits<ShuffleVectorInst>::op_begin(this),
1282 OperandTraits<ShuffleVectorInst>::operands(this),
1284 assert(isValidOperands(V1, V2, Mask) &&
1285 "Invalid shuffle vector instruction operands!");
1287 Op<0>().init(V1, this);
1288 Op<1>().init(V2, this);
1289 Op<2>().init(Mask, this);
1293 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1294 const Value *Mask) {
1295 if (!isa<VectorType>(V1->getType()) ||
1296 V1->getType() != V2->getType())
1299 const VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1300 if (!isa<Constant>(Mask) || MaskTy == 0 ||
1301 MaskTy->getElementType() != Type::Int32Ty ||
1302 MaskTy->getNumElements() !=
1303 cast<VectorType>(V1->getType())->getNumElements())
1308 /// getMaskValue - Return the index from the shuffle mask for the specified
1309 /// output result. This is either -1 if the element is undef or a number less
1310 /// than 2*numelements.
1311 int ShuffleVectorInst::getMaskValue(unsigned i) const {
1312 const Constant *Mask = cast<Constant>(getOperand(2));
1313 if (isa<UndefValue>(Mask)) return -1;
1314 if (isa<ConstantAggregateZero>(Mask)) return 0;
1315 const ConstantVector *MaskCV = cast<ConstantVector>(Mask);
1316 assert(i < MaskCV->getNumOperands() && "Index out of range");
1318 if (isa<UndefValue>(MaskCV->getOperand(i)))
1320 return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
1323 //===----------------------------------------------------------------------===//
1324 // ExtractValueInst Class
1325 //===----------------------------------------------------------------------===//
1327 // getIndexedType - Returns the type of the element that would be extracted
1328 // with an extractvalue instruction with the specified parameters.
1330 // A null type is returned if the indices are invalid for the specified
1333 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1336 unsigned CurIdx = 0;
1337 for (; CurIdx != NumIdx; ++CurIdx) {
1338 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1340 Value *Index = Idxs[CurIdx];
1341 if (!CT->indexValid(Index)) return 0;
1342 Agg = CT->getTypeAtIndex(Index);
1344 // If the new type forwards to another type, then it is in the middle
1345 // of being refined to another type (and hence, may have dropped all
1346 // references to what it was using before). So, use the new forwarded
1348 if (const Type *Ty = Agg->getForwardedType())
1351 return CurIdx == NumIdx ? Agg : 0;
1354 //===----------------------------------------------------------------------===//
1355 // BinaryOperator Class
1356 //===----------------------------------------------------------------------===//
1358 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1359 const Type *Ty, const std::string &Name,
1360 Instruction *InsertBefore)
1361 : Instruction(Ty, iType,
1362 OperandTraits<BinaryOperator>::op_begin(this),
1363 OperandTraits<BinaryOperator>::operands(this),
1365 Op<0>().init(S1, this);
1366 Op<1>().init(S2, this);
1371 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1372 const Type *Ty, const std::string &Name,
1373 BasicBlock *InsertAtEnd)
1374 : Instruction(Ty, iType,
1375 OperandTraits<BinaryOperator>::op_begin(this),
1376 OperandTraits<BinaryOperator>::operands(this),
1378 Op<0>().init(S1, this);
1379 Op<1>().init(S2, this);
1385 void BinaryOperator::init(BinaryOps iType) {
1386 Value *LHS = getOperand(0), *RHS = getOperand(1);
1387 LHS = LHS; RHS = RHS; // Silence warnings.
1388 assert(LHS->getType() == RHS->getType() &&
1389 "Binary operator operand types must match!");
1394 assert(getType() == LHS->getType() &&
1395 "Arithmetic operation should return same type as operands!");
1396 assert((getType()->isInteger() || getType()->isFloatingPoint() ||
1397 isa<VectorType>(getType())) &&
1398 "Tried to create an arithmetic operation on a non-arithmetic type!");
1402 assert(getType() == LHS->getType() &&
1403 "Arithmetic operation should return same type as operands!");
1404 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1405 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1406 "Incorrect operand type (not integer) for S/UDIV");
1409 assert(getType() == LHS->getType() &&
1410 "Arithmetic operation should return same type as operands!");
1411 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1412 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1413 && "Incorrect operand type (not floating point) for FDIV");
1417 assert(getType() == LHS->getType() &&
1418 "Arithmetic operation should return same type as operands!");
1419 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1420 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1421 "Incorrect operand type (not integer) for S/UREM");
1424 assert(getType() == LHS->getType() &&
1425 "Arithmetic operation should return same type as operands!");
1426 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1427 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1428 && "Incorrect operand type (not floating point) for FREM");
1433 assert(getType() == LHS->getType() &&
1434 "Shift operation should return same type as operands!");
1435 assert(getType()->isInteger() &&
1436 "Shift operation requires integer operands");
1440 assert(getType() == LHS->getType() &&
1441 "Logical operation should return same type as operands!");
1442 assert((getType()->isInteger() ||
1443 (isa<VectorType>(getType()) &&
1444 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1445 "Tried to create a logical operation on a non-integral type!");
1453 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1454 const std::string &Name,
1455 Instruction *InsertBefore) {
1456 assert(S1->getType() == S2->getType() &&
1457 "Cannot create binary operator with two operands of differing type!");
1458 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1461 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1462 const std::string &Name,
1463 BasicBlock *InsertAtEnd) {
1464 BinaryOperator *Res = create(Op, S1, S2, Name);
1465 InsertAtEnd->getInstList().push_back(Res);
1469 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1470 Instruction *InsertBefore) {
1471 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1472 return new BinaryOperator(Instruction::Sub,
1474 Op->getType(), Name, InsertBefore);
1477 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1478 BasicBlock *InsertAtEnd) {
1479 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1480 return new BinaryOperator(Instruction::Sub,
1482 Op->getType(), Name, InsertAtEnd);
1485 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1486 Instruction *InsertBefore) {
1488 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1489 C = ConstantInt::getAllOnesValue(PTy->getElementType());
1490 C = ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), C));
1492 C = ConstantInt::getAllOnesValue(Op->getType());
1495 return new BinaryOperator(Instruction::Xor, Op, C,
1496 Op->getType(), Name, InsertBefore);
1499 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1500 BasicBlock *InsertAtEnd) {
1502 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1503 // Create a vector of all ones values.
1504 Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType());
1506 ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1508 AllOnes = ConstantInt::getAllOnesValue(Op->getType());
1511 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1512 Op->getType(), Name, InsertAtEnd);
1516 // isConstantAllOnes - Helper function for several functions below
1517 static inline bool isConstantAllOnes(const Value *V) {
1518 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1519 return CI->isAllOnesValue();
1520 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1521 return CV->isAllOnesValue();
1525 bool BinaryOperator::isNeg(const Value *V) {
1526 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1527 if (Bop->getOpcode() == Instruction::Sub)
1528 return Bop->getOperand(0) ==
1529 ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1533 bool BinaryOperator::isNot(const Value *V) {
1534 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1535 return (Bop->getOpcode() == Instruction::Xor &&
1536 (isConstantAllOnes(Bop->getOperand(1)) ||
1537 isConstantAllOnes(Bop->getOperand(0))));
1541 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1542 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1543 return cast<BinaryOperator>(BinOp)->getOperand(1);
1546 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1547 return getNegArgument(const_cast<Value*>(BinOp));
1550 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1551 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1552 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1553 Value *Op0 = BO->getOperand(0);
1554 Value *Op1 = BO->getOperand(1);
1555 if (isConstantAllOnes(Op0)) return Op1;
1557 assert(isConstantAllOnes(Op1));
1561 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1562 return getNotArgument(const_cast<Value*>(BinOp));
1566 // swapOperands - Exchange the two operands to this instruction. This
1567 // instruction is safe to use on any binary instruction and does not
1568 // modify the semantics of the instruction. If the instruction is
1569 // order dependent (SetLT f.e.) the opcode is changed.
1571 bool BinaryOperator::swapOperands() {
1572 if (!isCommutative())
1573 return true; // Can't commute operands
1574 Op<0>().swap(Op<1>());
1578 //===----------------------------------------------------------------------===//
1580 //===----------------------------------------------------------------------===//
1582 // Just determine if this cast only deals with integral->integral conversion.
1583 bool CastInst::isIntegerCast() const {
1584 switch (getOpcode()) {
1585 default: return false;
1586 case Instruction::ZExt:
1587 case Instruction::SExt:
1588 case Instruction::Trunc:
1590 case Instruction::BitCast:
1591 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1595 bool CastInst::isLosslessCast() const {
1596 // Only BitCast can be lossless, exit fast if we're not BitCast
1597 if (getOpcode() != Instruction::BitCast)
1600 // Identity cast is always lossless
1601 const Type* SrcTy = getOperand(0)->getType();
1602 const Type* DstTy = getType();
1606 // Pointer to pointer is always lossless.
1607 if (isa<PointerType>(SrcTy))
1608 return isa<PointerType>(DstTy);
1609 return false; // Other types have no identity values
1612 /// This function determines if the CastInst does not require any bits to be
1613 /// changed in order to effect the cast. Essentially, it identifies cases where
1614 /// no code gen is necessary for the cast, hence the name no-op cast. For
1615 /// example, the following are all no-op casts:
1616 /// # bitcast i32* %x to i8*
1617 /// # bitcast <2 x i32> %x to <4 x i16>
1618 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
1619 /// @brief Determine if a cast is a no-op.
1620 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1621 switch (getOpcode()) {
1623 assert(!"Invalid CastOp");
1624 case Instruction::Trunc:
1625 case Instruction::ZExt:
1626 case Instruction::SExt:
1627 case Instruction::FPTrunc:
1628 case Instruction::FPExt:
1629 case Instruction::UIToFP:
1630 case Instruction::SIToFP:
1631 case Instruction::FPToUI:
1632 case Instruction::FPToSI:
1633 return false; // These always modify bits
1634 case Instruction::BitCast:
1635 return true; // BitCast never modifies bits.
1636 case Instruction::PtrToInt:
1637 return IntPtrTy->getPrimitiveSizeInBits() ==
1638 getType()->getPrimitiveSizeInBits();
1639 case Instruction::IntToPtr:
1640 return IntPtrTy->getPrimitiveSizeInBits() ==
1641 getOperand(0)->getType()->getPrimitiveSizeInBits();
1645 /// This function determines if a pair of casts can be eliminated and what
1646 /// opcode should be used in the elimination. This assumes that there are two
1647 /// instructions like this:
1648 /// * %F = firstOpcode SrcTy %x to MidTy
1649 /// * %S = secondOpcode MidTy %F to DstTy
1650 /// The function returns a resultOpcode so these two casts can be replaced with:
1651 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1652 /// If no such cast is permited, the function returns 0.
1653 unsigned CastInst::isEliminableCastPair(
1654 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1655 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1657 // Define the 144 possibilities for these two cast instructions. The values
1658 // in this matrix determine what to do in a given situation and select the
1659 // case in the switch below. The rows correspond to firstOp, the columns
1660 // correspond to secondOp. In looking at the table below, keep in mind
1661 // the following cast properties:
1663 // Size Compare Source Destination
1664 // Operator Src ? Size Type Sign Type Sign
1665 // -------- ------------ ------------------- ---------------------
1666 // TRUNC > Integer Any Integral Any
1667 // ZEXT < Integral Unsigned Integer Any
1668 // SEXT < Integral Signed Integer Any
1669 // FPTOUI n/a FloatPt n/a Integral Unsigned
1670 // FPTOSI n/a FloatPt n/a Integral Signed
1671 // UITOFP n/a Integral Unsigned FloatPt n/a
1672 // SITOFP n/a Integral Signed FloatPt n/a
1673 // FPTRUNC > FloatPt n/a FloatPt n/a
1674 // FPEXT < FloatPt n/a FloatPt n/a
1675 // PTRTOINT n/a Pointer n/a Integral Unsigned
1676 // INTTOPTR n/a Integral Unsigned Pointer n/a
1677 // BITCONVERT = FirstClass n/a FirstClass n/a
1679 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1680 // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
1681 // into "fptoui double to ulong", but this loses information about the range
1682 // of the produced value (we no longer know the top-part is all zeros).
1683 // Further this conversion is often much more expensive for typical hardware,
1684 // and causes issues when building libgcc. We disallow fptosi+sext for the
1686 const unsigned numCastOps =
1687 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1688 static const uint8_t CastResults[numCastOps][numCastOps] = {
1689 // T F F U S F F P I B -+
1690 // R Z S P P I I T P 2 N T |
1691 // U E E 2 2 2 2 R E I T C +- secondOp
1692 // N X X U S F F N X N 2 V |
1693 // C T T I I P P C T T P T -+
1694 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1695 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1696 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1697 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1698 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1699 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1700 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1701 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1702 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1703 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1704 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1705 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1708 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1709 [secondOp-Instruction::CastOpsBegin];
1712 // categorically disallowed
1715 // allowed, use first cast's opcode
1718 // allowed, use second cast's opcode
1721 // no-op cast in second op implies firstOp as long as the DestTy
1723 if (DstTy->isInteger())
1727 // no-op cast in second op implies firstOp as long as the DestTy
1728 // is floating point
1729 if (DstTy->isFloatingPoint())
1733 // no-op cast in first op implies secondOp as long as the SrcTy
1735 if (SrcTy->isInteger())
1739 // no-op cast in first op implies secondOp as long as the SrcTy
1740 // is a floating point
1741 if (SrcTy->isFloatingPoint())
1745 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1746 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1747 unsigned MidSize = MidTy->getPrimitiveSizeInBits();
1748 if (MidSize >= PtrSize)
1749 return Instruction::BitCast;
1753 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1754 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1755 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1756 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1757 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1758 if (SrcSize == DstSize)
1759 return Instruction::BitCast;
1760 else if (SrcSize < DstSize)
1764 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1765 return Instruction::ZExt;
1767 // fpext followed by ftrunc is allowed if the bit size returned to is
1768 // the same as the original, in which case its just a bitcast
1770 return Instruction::BitCast;
1771 return 0; // If the types are not the same we can't eliminate it.
1773 // bitcast followed by ptrtoint is allowed as long as the bitcast
1774 // is a pointer to pointer cast.
1775 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1779 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1780 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1784 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1785 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1786 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1787 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1788 if (SrcSize <= PtrSize && SrcSize == DstSize)
1789 return Instruction::BitCast;
1793 // cast combination can't happen (error in input). This is for all cases
1794 // where the MidTy is not the same for the two cast instructions.
1795 assert(!"Invalid Cast Combination");
1798 assert(!"Error in CastResults table!!!");
1804 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1805 const std::string &Name, Instruction *InsertBefore) {
1806 // Construct and return the appropriate CastInst subclass
1808 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1809 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1810 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1811 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1812 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1813 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1814 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1815 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1816 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1817 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1818 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1819 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1821 assert(!"Invalid opcode provided");
1826 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1827 const std::string &Name, BasicBlock *InsertAtEnd) {
1828 // Construct and return the appropriate CastInst subclass
1830 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1831 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1832 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1833 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1834 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1835 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1836 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1837 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1838 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1839 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1840 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1841 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1843 assert(!"Invalid opcode provided");
1848 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1849 const std::string &Name,
1850 Instruction *InsertBefore) {
1851 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1852 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1853 return create(Instruction::ZExt, S, Ty, Name, InsertBefore);
1856 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1857 const std::string &Name,
1858 BasicBlock *InsertAtEnd) {
1859 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1860 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1861 return create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
1864 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1865 const std::string &Name,
1866 Instruction *InsertBefore) {
1867 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1868 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1869 return create(Instruction::SExt, S, Ty, Name, InsertBefore);
1872 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1873 const std::string &Name,
1874 BasicBlock *InsertAtEnd) {
1875 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1876 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1877 return create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
1880 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1881 const std::string &Name,
1882 Instruction *InsertBefore) {
1883 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1884 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1885 return create(Instruction::Trunc, S, Ty, Name, InsertBefore);
1888 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1889 const std::string &Name,
1890 BasicBlock *InsertAtEnd) {
1891 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1892 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1893 return create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
1896 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1897 const std::string &Name,
1898 BasicBlock *InsertAtEnd) {
1899 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1900 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1903 if (Ty->isInteger())
1904 return create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
1905 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1908 /// @brief Create a BitCast or a PtrToInt cast instruction
1909 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1910 const std::string &Name,
1911 Instruction *InsertBefore) {
1912 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1913 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1916 if (Ty->isInteger())
1917 return create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
1918 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1921 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1922 bool isSigned, const std::string &Name,
1923 Instruction *InsertBefore) {
1924 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1925 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1926 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1927 Instruction::CastOps opcode =
1928 (SrcBits == DstBits ? Instruction::BitCast :
1929 (SrcBits > DstBits ? Instruction::Trunc :
1930 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1931 return create(opcode, C, Ty, Name, InsertBefore);
1934 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1935 bool isSigned, const std::string &Name,
1936 BasicBlock *InsertAtEnd) {
1937 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1938 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1939 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1940 Instruction::CastOps opcode =
1941 (SrcBits == DstBits ? Instruction::BitCast :
1942 (SrcBits > DstBits ? Instruction::Trunc :
1943 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1944 return create(opcode, C, Ty, Name, InsertAtEnd);
1947 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1948 const std::string &Name,
1949 Instruction *InsertBefore) {
1950 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1952 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1953 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1954 Instruction::CastOps opcode =
1955 (SrcBits == DstBits ? Instruction::BitCast :
1956 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1957 return create(opcode, C, Ty, Name, InsertBefore);
1960 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1961 const std::string &Name,
1962 BasicBlock *InsertAtEnd) {
1963 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1965 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1966 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1967 Instruction::CastOps opcode =
1968 (SrcBits == DstBits ? Instruction::BitCast :
1969 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1970 return create(opcode, C, Ty, Name, InsertAtEnd);
1973 // Check whether it is valid to call getCastOpcode for these types.
1974 // This routine must be kept in sync with getCastOpcode.
1975 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
1976 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
1979 if (SrcTy == DestTy)
1982 // Get the bit sizes, we'll need these
1983 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1984 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1986 // Run through the possibilities ...
1987 if (DestTy->isInteger()) { // Casting to integral
1988 if (SrcTy->isInteger()) { // Casting from integral
1990 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1992 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1993 // Casting from vector
1994 return DestBits == PTy->getBitWidth();
1995 } else { // Casting from something else
1996 return isa<PointerType>(SrcTy);
1998 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
1999 if (SrcTy->isInteger()) { // Casting from integral
2001 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2003 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2004 // Casting from vector
2005 return DestBits == PTy->getBitWidth();
2006 } else { // Casting from something else
2009 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2010 // Casting to vector
2011 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2012 // Casting from vector
2013 return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
2014 } else { // Casting from something else
2015 return DestPTy->getBitWidth() == SrcBits;
2017 } else if (isa<PointerType>(DestTy)) { // Casting to pointer
2018 if (isa<PointerType>(SrcTy)) { // Casting from pointer
2020 } else if (SrcTy->isInteger()) { // Casting from integral
2022 } else { // Casting from something else
2025 } else { // Casting to something else
2030 // Provide a way to get a "cast" where the cast opcode is inferred from the
2031 // types and size of the operand. This, basically, is a parallel of the
2032 // logic in the castIsValid function below. This axiom should hold:
2033 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2034 // should not assert in castIsValid. In other words, this produces a "correct"
2035 // casting opcode for the arguments passed to it.
2036 // This routine must be kept in sync with isCastable.
2037 Instruction::CastOps
2038 CastInst::getCastOpcode(
2039 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
2040 // Get the bit sizes, we'll need these
2041 const Type *SrcTy = Src->getType();
2042 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2043 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2045 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2046 "Only first class types are castable!");
2048 // Run through the possibilities ...
2049 if (DestTy->isInteger()) { // Casting to integral
2050 if (SrcTy->isInteger()) { // Casting from integral
2051 if (DestBits < SrcBits)
2052 return Trunc; // int -> smaller int
2053 else if (DestBits > SrcBits) { // its an extension
2055 return SExt; // signed -> SEXT
2057 return ZExt; // unsigned -> ZEXT
2059 return BitCast; // Same size, No-op cast
2061 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2063 return FPToSI; // FP -> sint
2065 return FPToUI; // FP -> uint
2066 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2067 assert(DestBits == PTy->getBitWidth() &&
2068 "Casting vector to integer of different width");
2069 return BitCast; // Same size, no-op cast
2071 assert(isa<PointerType>(SrcTy) &&
2072 "Casting from a value that is not first-class type");
2073 return PtrToInt; // ptr -> int
2075 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2076 if (SrcTy->isInteger()) { // Casting from integral
2078 return SIToFP; // sint -> FP
2080 return UIToFP; // uint -> FP
2081 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2082 if (DestBits < SrcBits) {
2083 return FPTrunc; // FP -> smaller FP
2084 } else if (DestBits > SrcBits) {
2085 return FPExt; // FP -> larger FP
2087 return BitCast; // same size, no-op cast
2089 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2090 assert(DestBits == PTy->getBitWidth() &&
2091 "Casting vector to floating point of different width");
2092 return BitCast; // same size, no-op cast
2094 assert(0 && "Casting pointer or non-first class to float");
2096 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2097 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2098 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2099 "Casting vector to vector of different widths");
2100 return BitCast; // vector -> vector
2101 } else if (DestPTy->getBitWidth() == SrcBits) {
2102 return BitCast; // float/int -> vector
2104 assert(!"Illegal cast to vector (wrong type or size)");
2106 } else if (isa<PointerType>(DestTy)) {
2107 if (isa<PointerType>(SrcTy)) {
2108 return BitCast; // ptr -> ptr
2109 } else if (SrcTy->isInteger()) {
2110 return IntToPtr; // int -> ptr
2112 assert(!"Casting pointer to other than pointer or int");
2115 assert(!"Casting to type that is not first-class");
2118 // If we fall through to here we probably hit an assertion cast above
2119 // and assertions are not turned on. Anything we return is an error, so
2120 // BitCast is as good a choice as any.
2124 //===----------------------------------------------------------------------===//
2125 // CastInst SubClass Constructors
2126 //===----------------------------------------------------------------------===//
2128 /// Check that the construction parameters for a CastInst are correct. This
2129 /// could be broken out into the separate constructors but it is useful to have
2130 /// it in one place and to eliminate the redundant code for getting the sizes
2131 /// of the types involved.
2133 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2135 // Check for type sanity on the arguments
2136 const Type *SrcTy = S->getType();
2137 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
2140 // Get the size of the types in bits, we'll need this later
2141 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2142 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2144 // Switch on the opcode provided
2146 default: return false; // This is an input error
2147 case Instruction::Trunc:
2148 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize > DstBitSize;
2149 case Instruction::ZExt:
2150 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2151 case Instruction::SExt:
2152 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2153 case Instruction::FPTrunc:
2154 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2155 SrcBitSize > DstBitSize;
2156 case Instruction::FPExt:
2157 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2158 SrcBitSize < DstBitSize;
2159 case Instruction::UIToFP:
2160 case Instruction::SIToFP:
2161 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2162 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2163 return SVTy->getElementType()->isInteger() &&
2164 DVTy->getElementType()->isFloatingPoint() &&
2165 SVTy->getNumElements() == DVTy->getNumElements();
2168 return SrcTy->isInteger() && DstTy->isFloatingPoint();
2169 case Instruction::FPToUI:
2170 case Instruction::FPToSI:
2171 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2172 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2173 return SVTy->getElementType()->isFloatingPoint() &&
2174 DVTy->getElementType()->isInteger() &&
2175 SVTy->getNumElements() == DVTy->getNumElements();
2178 return SrcTy->isFloatingPoint() && DstTy->isInteger();
2179 case Instruction::PtrToInt:
2180 return isa<PointerType>(SrcTy) && DstTy->isInteger();
2181 case Instruction::IntToPtr:
2182 return SrcTy->isInteger() && isa<PointerType>(DstTy);
2183 case Instruction::BitCast:
2184 // BitCast implies a no-op cast of type only. No bits change.
2185 // However, you can't cast pointers to anything but pointers.
2186 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2189 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2190 // these cases, the cast is okay if the source and destination bit widths
2192 return SrcBitSize == DstBitSize;
2196 TruncInst::TruncInst(
2197 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2198 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2199 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2202 TruncInst::TruncInst(
2203 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2204 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2205 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2209 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2210 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2211 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2215 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2216 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2217 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2220 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2221 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2222 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2226 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2227 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2228 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2231 FPTruncInst::FPTruncInst(
2232 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2233 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2234 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2237 FPTruncInst::FPTruncInst(
2238 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2239 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2240 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2243 FPExtInst::FPExtInst(
2244 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2245 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2246 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2249 FPExtInst::FPExtInst(
2250 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2251 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2252 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2255 UIToFPInst::UIToFPInst(
2256 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2257 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2258 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2261 UIToFPInst::UIToFPInst(
2262 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2263 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2264 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2267 SIToFPInst::SIToFPInst(
2268 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2269 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2270 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2273 SIToFPInst::SIToFPInst(
2274 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2275 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2276 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2279 FPToUIInst::FPToUIInst(
2280 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2281 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2282 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2285 FPToUIInst::FPToUIInst(
2286 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2287 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2288 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2291 FPToSIInst::FPToSIInst(
2292 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2293 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2294 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2297 FPToSIInst::FPToSIInst(
2298 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2299 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2300 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2303 PtrToIntInst::PtrToIntInst(
2304 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2305 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2306 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2309 PtrToIntInst::PtrToIntInst(
2310 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2311 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2312 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2315 IntToPtrInst::IntToPtrInst(
2316 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2317 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2318 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2321 IntToPtrInst::IntToPtrInst(
2322 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2323 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2324 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2327 BitCastInst::BitCastInst(
2328 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2329 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2330 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2333 BitCastInst::BitCastInst(
2334 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2335 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2336 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2339 //===----------------------------------------------------------------------===//
2341 //===----------------------------------------------------------------------===//
2343 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2344 Value *LHS, Value *RHS, const std::string &Name,
2345 Instruction *InsertBefore)
2346 : Instruction(ty, op,
2347 OperandTraits<CmpInst>::op_begin(this),
2348 OperandTraits<CmpInst>::operands(this),
2350 Op<0>().init(LHS, this);
2351 Op<1>().init(RHS, this);
2352 SubclassData = predicate;
2356 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2357 Value *LHS, Value *RHS, const std::string &Name,
2358 BasicBlock *InsertAtEnd)
2359 : Instruction(ty, op,
2360 OperandTraits<CmpInst>::op_begin(this),
2361 OperandTraits<CmpInst>::operands(this),
2363 Op<0>().init(LHS, this);
2364 Op<1>().init(RHS, this);
2365 SubclassData = predicate;
2370 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2371 const std::string &Name, Instruction *InsertBefore) {
2372 if (Op == Instruction::ICmp) {
2373 return new ICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2376 if (Op == Instruction::FCmp) {
2377 return new FCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2380 if (Op == Instruction::VICmp) {
2381 return new VICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2384 return new VFCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2389 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2390 const std::string &Name, BasicBlock *InsertAtEnd) {
2391 if (Op == Instruction::ICmp) {
2392 return new ICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2395 if (Op == Instruction::FCmp) {
2396 return new FCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2399 if (Op == Instruction::VICmp) {
2400 return new VICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2403 return new VFCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2407 void CmpInst::swapOperands() {
2408 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2411 cast<FCmpInst>(this)->swapOperands();
2414 bool CmpInst::isCommutative() {
2415 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2416 return IC->isCommutative();
2417 return cast<FCmpInst>(this)->isCommutative();
2420 bool CmpInst::isEquality() {
2421 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2422 return IC->isEquality();
2423 return cast<FCmpInst>(this)->isEquality();
2427 ICmpInst::Predicate ICmpInst::getInversePredicate(Predicate pred) {
2430 assert(!"Unknown icmp predicate!");
2431 case ICMP_EQ: return ICMP_NE;
2432 case ICMP_NE: return ICMP_EQ;
2433 case ICMP_UGT: return ICMP_ULE;
2434 case ICMP_ULT: return ICMP_UGE;
2435 case ICMP_UGE: return ICMP_ULT;
2436 case ICMP_ULE: return ICMP_UGT;
2437 case ICMP_SGT: return ICMP_SLE;
2438 case ICMP_SLT: return ICMP_SGE;
2439 case ICMP_SGE: return ICMP_SLT;
2440 case ICMP_SLE: return ICMP_SGT;
2444 ICmpInst::Predicate ICmpInst::getSwappedPredicate(Predicate pred) {
2446 default: assert(! "Unknown icmp predicate!");
2447 case ICMP_EQ: case ICMP_NE:
2449 case ICMP_SGT: return ICMP_SLT;
2450 case ICMP_SLT: return ICMP_SGT;
2451 case ICMP_SGE: return ICMP_SLE;
2452 case ICMP_SLE: return ICMP_SGE;
2453 case ICMP_UGT: return ICMP_ULT;
2454 case ICMP_ULT: return ICMP_UGT;
2455 case ICMP_UGE: return ICMP_ULE;
2456 case ICMP_ULE: return ICMP_UGE;
2460 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2462 default: assert(! "Unknown icmp predicate!");
2463 case ICMP_EQ: case ICMP_NE:
2464 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2466 case ICMP_UGT: return ICMP_SGT;
2467 case ICMP_ULT: return ICMP_SLT;
2468 case ICMP_UGE: return ICMP_SGE;
2469 case ICMP_ULE: return ICMP_SLE;
2473 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2475 default: assert(! "Unknown icmp predicate!");
2476 case ICMP_EQ: case ICMP_NE:
2477 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2479 case ICMP_SGT: return ICMP_UGT;
2480 case ICMP_SLT: return ICMP_ULT;
2481 case ICMP_SGE: return ICMP_UGE;
2482 case ICMP_SLE: return ICMP_ULE;
2486 bool ICmpInst::isSignedPredicate(Predicate pred) {
2488 default: assert(! "Unknown icmp predicate!");
2489 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2491 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2492 case ICMP_UGE: case ICMP_ULE:
2497 /// Initialize a set of values that all satisfy the condition with C.
2500 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2503 uint32_t BitWidth = C.getBitWidth();
2505 default: assert(0 && "Invalid ICmp opcode to ConstantRange ctor!");
2506 case ICmpInst::ICMP_EQ: Upper++; break;
2507 case ICmpInst::ICMP_NE: Lower++; break;
2508 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2509 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2510 case ICmpInst::ICMP_UGT:
2511 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2513 case ICmpInst::ICMP_SGT:
2514 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2516 case ICmpInst::ICMP_ULE:
2517 Lower = APInt::getMinValue(BitWidth); Upper++;
2519 case ICmpInst::ICMP_SLE:
2520 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2522 case ICmpInst::ICMP_UGE:
2523 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2525 case ICmpInst::ICMP_SGE:
2526 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2529 return ConstantRange(Lower, Upper);
2532 FCmpInst::Predicate FCmpInst::getInversePredicate(Predicate pred) {
2535 assert(!"Unknown icmp predicate!");
2536 case FCMP_OEQ: return FCMP_UNE;
2537 case FCMP_ONE: return FCMP_UEQ;
2538 case FCMP_OGT: return FCMP_ULE;
2539 case FCMP_OLT: return FCMP_UGE;
2540 case FCMP_OGE: return FCMP_ULT;
2541 case FCMP_OLE: return FCMP_UGT;
2542 case FCMP_UEQ: return FCMP_ONE;
2543 case FCMP_UNE: return FCMP_OEQ;
2544 case FCMP_UGT: return FCMP_OLE;
2545 case FCMP_ULT: return FCMP_OGE;
2546 case FCMP_UGE: return FCMP_OLT;
2547 case FCMP_ULE: return FCMP_OGT;
2548 case FCMP_ORD: return FCMP_UNO;
2549 case FCMP_UNO: return FCMP_ORD;
2550 case FCMP_TRUE: return FCMP_FALSE;
2551 case FCMP_FALSE: return FCMP_TRUE;
2555 FCmpInst::Predicate FCmpInst::getSwappedPredicate(Predicate pred) {
2557 default: assert(!"Unknown fcmp predicate!");
2558 case FCMP_FALSE: case FCMP_TRUE:
2559 case FCMP_OEQ: case FCMP_ONE:
2560 case FCMP_UEQ: case FCMP_UNE:
2561 case FCMP_ORD: case FCMP_UNO:
2563 case FCMP_OGT: return FCMP_OLT;
2564 case FCMP_OLT: return FCMP_OGT;
2565 case FCMP_OGE: return FCMP_OLE;
2566 case FCMP_OLE: return FCMP_OGE;
2567 case FCMP_UGT: return FCMP_ULT;
2568 case FCMP_ULT: return FCMP_UGT;
2569 case FCMP_UGE: return FCMP_ULE;
2570 case FCMP_ULE: return FCMP_UGE;
2574 bool CmpInst::isUnsigned(unsigned short predicate) {
2575 switch (predicate) {
2576 default: return false;
2577 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2578 case ICmpInst::ICMP_UGE: return true;
2582 bool CmpInst::isSigned(unsigned short predicate){
2583 switch (predicate) {
2584 default: return false;
2585 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2586 case ICmpInst::ICMP_SGE: return true;
2590 bool CmpInst::isOrdered(unsigned short predicate) {
2591 switch (predicate) {
2592 default: return false;
2593 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2594 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2595 case FCmpInst::FCMP_ORD: return true;
2599 bool CmpInst::isUnordered(unsigned short predicate) {
2600 switch (predicate) {
2601 default: return false;
2602 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2603 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2604 case FCmpInst::FCMP_UNO: return true;
2608 //===----------------------------------------------------------------------===//
2609 // SwitchInst Implementation
2610 //===----------------------------------------------------------------------===//
2612 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2613 assert(Value && Default);
2614 ReservedSpace = 2+NumCases*2;
2616 OperandList = allocHungoffUses(ReservedSpace);
2618 OperandList[0].init(Value, this);
2619 OperandList[1].init(Default, this);
2622 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2623 /// switch on and a default destination. The number of additional cases can
2624 /// be specified here to make memory allocation more efficient. This
2625 /// constructor can also autoinsert before another instruction.
2626 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2627 Instruction *InsertBefore)
2628 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) {
2629 init(Value, Default, NumCases);
2632 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2633 /// switch on and a default destination. The number of additional cases can
2634 /// be specified here to make memory allocation more efficient. This
2635 /// constructor also autoinserts at the end of the specified BasicBlock.
2636 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2637 BasicBlock *InsertAtEnd)
2638 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) {
2639 init(Value, Default, NumCases);
2642 SwitchInst::SwitchInst(const SwitchInst &SI)
2643 : TerminatorInst(Type::VoidTy, Instruction::Switch,
2644 allocHungoffUses(SI.getNumOperands()), SI.getNumOperands()) {
2645 Use *OL = OperandList, *InOL = SI.OperandList;
2646 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2647 OL[i].init(InOL[i], this);
2648 OL[i+1].init(InOL[i+1], this);
2652 SwitchInst::~SwitchInst() {
2653 dropHungoffUses(OperandList);
2657 /// addCase - Add an entry to the switch instruction...
2659 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2660 unsigned OpNo = NumOperands;
2661 if (OpNo+2 > ReservedSpace)
2662 resizeOperands(0); // Get more space!
2663 // Initialize some new operands.
2664 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2665 NumOperands = OpNo+2;
2666 OperandList[OpNo].init(OnVal, this);
2667 OperandList[OpNo+1].init(Dest, this);
2670 /// removeCase - This method removes the specified successor from the switch
2671 /// instruction. Note that this cannot be used to remove the default
2672 /// destination (successor #0).
2674 void SwitchInst::removeCase(unsigned idx) {
2675 assert(idx != 0 && "Cannot remove the default case!");
2676 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2678 unsigned NumOps = getNumOperands();
2679 Use *OL = OperandList;
2681 // Move everything after this operand down.
2683 // FIXME: we could just swap with the end of the list, then erase. However,
2684 // client might not expect this to happen. The code as it is thrashes the
2685 // use/def lists, which is kinda lame.
2686 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2688 OL[i-2+1] = OL[i+1];
2691 // Nuke the last value.
2692 OL[NumOps-2].set(0);
2693 OL[NumOps-2+1].set(0);
2694 NumOperands = NumOps-2;
2697 /// resizeOperands - resize operands - This adjusts the length of the operands
2698 /// list according to the following behavior:
2699 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2700 /// of operation. This grows the number of ops by 3 times.
2701 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2702 /// 3. If NumOps == NumOperands, trim the reserved space.
2704 void SwitchInst::resizeOperands(unsigned NumOps) {
2705 unsigned e = getNumOperands();
2708 } else if (NumOps*2 > NumOperands) {
2709 // No resize needed.
2710 if (ReservedSpace >= NumOps) return;
2711 } else if (NumOps == NumOperands) {
2712 if (ReservedSpace == NumOps) return;
2717 ReservedSpace = NumOps;
2718 Use *NewOps = allocHungoffUses(NumOps);
2719 Use *OldOps = OperandList;
2720 for (unsigned i = 0; i != e; ++i) {
2721 NewOps[i].init(OldOps[i], this);
2723 OperandList = NewOps;
2724 if (OldOps) Use::zap(OldOps, OldOps + e, true);
2728 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2729 return getSuccessor(idx);
2731 unsigned SwitchInst::getNumSuccessorsV() const {
2732 return getNumSuccessors();
2734 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2735 setSuccessor(idx, B);
2738 //===----------------------------------------------------------------------===//
2739 // GetResultInst Implementation
2740 //===----------------------------------------------------------------------===//
2742 GetResultInst::GetResultInst(Value *Aggregate, unsigned Index,
2743 const std::string &Name,
2744 Instruction *InsertBef)
2745 : UnaryInstruction(cast<StructType>(Aggregate->getType())
2746 ->getElementType(Index),
2747 GetResult, Aggregate, InsertBef),
2749 assert(isValidOperands(Aggregate, Index)
2750 && "Invalid GetResultInst operands!");
2754 bool GetResultInst::isValidOperands(const Value *Aggregate, unsigned Index) {
2758 if (const StructType *STy = dyn_cast<StructType>(Aggregate->getType())) {
2759 unsigned NumElements = STy->getNumElements();
2760 if (Index >= NumElements || NumElements == 0)
2763 // getresult aggregate value's element types are restricted to
2764 // avoid nested aggregates.
2765 for (unsigned i = 0; i < NumElements; ++i)
2766 if (!STy->getElementType(i)->isFirstClassType())
2769 // Otherwise, Aggregate is valid.
2775 // Define these methods here so vtables don't get emitted into every translation
2776 // unit that uses these classes.
2778 GetElementPtrInst *GetElementPtrInst::clone() const {
2779 return new(getNumOperands()) GetElementPtrInst(*this);
2782 BinaryOperator *BinaryOperator::clone() const {
2783 return create(getOpcode(), Op<0>(), Op<1>());
2786 FCmpInst* FCmpInst::clone() const {
2787 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
2789 ICmpInst* ICmpInst::clone() const {
2790 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
2793 VFCmpInst* VFCmpInst::clone() const {
2794 return new VFCmpInst(getPredicate(), Op<0>(), Op<1>());
2796 VICmpInst* VICmpInst::clone() const {
2797 return new VICmpInst(getPredicate(), Op<0>(), Op<1>());
2800 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
2801 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
2802 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
2803 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
2804 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
2805 CastInst *TruncInst::clone() const { return new TruncInst(*this); }
2806 CastInst *ZExtInst::clone() const { return new ZExtInst(*this); }
2807 CastInst *SExtInst::clone() const { return new SExtInst(*this); }
2808 CastInst *FPTruncInst::clone() const { return new FPTruncInst(*this); }
2809 CastInst *FPExtInst::clone() const { return new FPExtInst(*this); }
2810 CastInst *UIToFPInst::clone() const { return new UIToFPInst(*this); }
2811 CastInst *SIToFPInst::clone() const { return new SIToFPInst(*this); }
2812 CastInst *FPToUIInst::clone() const { return new FPToUIInst(*this); }
2813 CastInst *FPToSIInst::clone() const { return new FPToSIInst(*this); }
2814 CastInst *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
2815 CastInst *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
2816 CastInst *BitCastInst::clone() const { return new BitCastInst(*this); }
2817 CallInst *CallInst::clone() const {
2818 return new(getNumOperands()) CallInst(*this);
2820 SelectInst *SelectInst::clone() const {
2821 return new(getNumOperands()) SelectInst(*this);
2823 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
2825 ExtractElementInst *ExtractElementInst::clone() const {
2826 return new ExtractElementInst(*this);
2828 InsertElementInst *InsertElementInst::clone() const {
2829 return InsertElementInst::Create(*this);
2831 ShuffleVectorInst *ShuffleVectorInst::clone() const {
2832 return new ShuffleVectorInst(*this);
2834 PHINode *PHINode::clone() const { return new PHINode(*this); }
2835 ReturnInst *ReturnInst::clone() const {
2836 return new(getNumOperands()) ReturnInst(*this);
2838 BranchInst *BranchInst::clone() const {
2839 return new(getNumOperands()) BranchInst(*this);
2841 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
2842 InvokeInst *InvokeInst::clone() const {
2843 return new(getNumOperands()) InvokeInst(*this);
2845 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
2846 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}
2847 GetResultInst *GetResultInst::clone() const { return new GetResultInst(*this); }