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 // Out of line virtual method, so the vtable, etc has a home.
104 UnaryInstruction::~UnaryInstruction() {
108 //===----------------------------------------------------------------------===//
110 //===----------------------------------------------------------------------===//
112 PHINode::PHINode(const PHINode &PN)
113 : Instruction(PN.getType(), Instruction::PHI,
114 new Use[PN.getNumOperands()], PN.getNumOperands()),
115 ReservedSpace(PN.getNumOperands()) {
116 Use *OL = OperandList;
117 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
118 OL[i].init(PN.getOperand(i), this);
119 OL[i+1].init(PN.getOperand(i+1), this);
123 PHINode::~PHINode() {
124 delete [] OperandList;
127 // removeIncomingValue - Remove an incoming value. This is useful if a
128 // predecessor basic block is deleted.
129 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
130 unsigned NumOps = getNumOperands();
131 Use *OL = OperandList;
132 assert(Idx*2 < NumOps && "BB not in PHI node!");
133 Value *Removed = OL[Idx*2];
135 // Move everything after this operand down.
137 // FIXME: we could just swap with the end of the list, then erase. However,
138 // client might not expect this to happen. The code as it is thrashes the
139 // use/def lists, which is kinda lame.
140 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
145 // Nuke the last value.
147 OL[NumOps-2+1].set(0);
148 NumOperands = NumOps-2;
150 // If the PHI node is dead, because it has zero entries, nuke it now.
151 if (NumOps == 2 && DeletePHIIfEmpty) {
152 // If anyone is using this PHI, make them use a dummy value instead...
153 replaceAllUsesWith(UndefValue::get(getType()));
159 /// resizeOperands - resize operands - This adjusts the length of the operands
160 /// list according to the following behavior:
161 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
162 /// of operation. This grows the number of ops by 1.5 times.
163 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
164 /// 3. If NumOps == NumOperands, trim the reserved space.
166 void PHINode::resizeOperands(unsigned NumOps) {
168 NumOps = (getNumOperands())*3/2;
169 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
170 } else if (NumOps*2 > NumOperands) {
172 if (ReservedSpace >= NumOps) return;
173 } else if (NumOps == NumOperands) {
174 if (ReservedSpace == NumOps) return;
179 ReservedSpace = NumOps;
180 Use *NewOps = new Use[NumOps];
181 Use *OldOps = OperandList;
182 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
183 NewOps[i].init(OldOps[i], this);
187 OperandList = NewOps;
190 /// hasConstantValue - If the specified PHI node always merges together the same
191 /// value, return the value, otherwise return null.
193 Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) const {
194 // If the PHI node only has one incoming value, eliminate the PHI node...
195 if (getNumIncomingValues() == 1) {
196 if (getIncomingValue(0) != this) // not X = phi X
197 return getIncomingValue(0);
199 return UndefValue::get(getType()); // Self cycle is dead.
202 // Otherwise if all of the incoming values are the same for the PHI, replace
203 // the PHI node with the incoming value.
206 bool HasUndefInput = false;
207 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
208 if (isa<UndefValue>(getIncomingValue(i))) {
209 HasUndefInput = true;
210 } else if (getIncomingValue(i) != this) { // Not the PHI node itself...
211 if (InVal && getIncomingValue(i) != InVal)
212 return 0; // Not the same, bail out.
214 InVal = getIncomingValue(i);
217 // The only case that could cause InVal to be null is if we have a PHI node
218 // that only has entries for itself. In this case, there is no entry into the
219 // loop, so kill the PHI.
221 if (InVal == 0) InVal = UndefValue::get(getType());
223 // If we have a PHI node like phi(X, undef, X), where X is defined by some
224 // instruction, we cannot always return X as the result of the PHI node. Only
225 // do this if X is not an instruction (thus it must dominate the PHI block),
226 // or if the client is prepared to deal with this possibility.
227 if (HasUndefInput && !AllowNonDominatingInstruction)
228 if (Instruction *IV = dyn_cast<Instruction>(InVal))
229 // If it's in the entry block, it dominates everything.
230 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
232 return 0; // Cannot guarantee that InVal dominates this PHINode.
234 // All of the incoming values are the same, return the value now.
239 //===----------------------------------------------------------------------===//
240 // CallInst Implementation
241 //===----------------------------------------------------------------------===//
243 CallInst::~CallInst() {
244 delete [] OperandList;
247 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
248 NumOperands = NumParams+1;
249 Use *OL = OperandList = new Use[NumParams+1];
250 OL[0].init(Func, this);
252 const FunctionType *FTy =
253 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
254 FTy = FTy; // silence warning.
256 assert((NumParams == FTy->getNumParams() ||
257 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
258 "Calling a function with bad signature!");
259 for (unsigned i = 0; i != NumParams; ++i) {
260 assert((i >= FTy->getNumParams() ||
261 FTy->getParamType(i) == Params[i]->getType()) &&
262 "Calling a function with a bad signature!");
263 OL[i+1].init(Params[i], this);
267 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
269 Use *OL = OperandList = new Use[3];
270 OL[0].init(Func, this);
271 OL[1].init(Actual1, this);
272 OL[2].init(Actual2, this);
274 const FunctionType *FTy =
275 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
276 FTy = FTy; // silence warning.
278 assert((FTy->getNumParams() == 2 ||
279 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
280 "Calling a function with bad signature");
281 assert((0 >= FTy->getNumParams() ||
282 FTy->getParamType(0) == Actual1->getType()) &&
283 "Calling a function with a bad signature!");
284 assert((1 >= FTy->getNumParams() ||
285 FTy->getParamType(1) == Actual2->getType()) &&
286 "Calling a function with a bad signature!");
289 void CallInst::init(Value *Func, Value *Actual) {
291 Use *OL = OperandList = new Use[2];
292 OL[0].init(Func, this);
293 OL[1].init(Actual, this);
295 const FunctionType *FTy =
296 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
297 FTy = FTy; // silence warning.
299 assert((FTy->getNumParams() == 1 ||
300 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
301 "Calling a function with bad signature");
302 assert((0 == FTy->getNumParams() ||
303 FTy->getParamType(0) == Actual->getType()) &&
304 "Calling a function with a bad signature!");
307 void CallInst::init(Value *Func) {
309 Use *OL = OperandList = new Use[1];
310 OL[0].init(Func, this);
312 const FunctionType *FTy =
313 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
314 FTy = FTy; // silence warning.
316 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
319 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
320 Instruction *InsertBefore)
321 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
322 ->getElementType())->getReturnType(),
323 Instruction::Call, 0, 0, InsertBefore) {
328 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
329 BasicBlock *InsertAtEnd)
330 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
331 ->getElementType())->getReturnType(),
332 Instruction::Call, 0, 0, InsertAtEnd) {
336 CallInst::CallInst(Value *Func, const std::string &Name,
337 Instruction *InsertBefore)
338 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
339 ->getElementType())->getReturnType(),
340 Instruction::Call, 0, 0, InsertBefore) {
345 CallInst::CallInst(Value *Func, const std::string &Name,
346 BasicBlock *InsertAtEnd)
347 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
348 ->getElementType())->getReturnType(),
349 Instruction::Call, 0, 0, InsertAtEnd) {
354 CallInst::CallInst(const CallInst &CI)
355 : Instruction(CI.getType(), Instruction::Call, new Use[CI.getNumOperands()],
356 CI.getNumOperands()) {
357 setParamAttrs(CI.getParamAttrs());
358 SubclassData = CI.SubclassData;
359 Use *OL = OperandList;
360 Use *InOL = CI.OperandList;
361 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
362 OL[i].init(InOL[i], this);
365 bool CallInst::paramHasAttr(unsigned i, ParameterAttributes attr) const {
366 if (ParamAttrs.paramHasAttr(i, attr))
368 if (const Function *F = getCalledFunction())
369 return F->paramHasAttr(i, attr);
373 void CallInst::setDoesNotThrow(bool doesNotThrow) {
374 PAListPtr PAL = getParamAttrs();
376 PAL = PAL.addAttr(0, ParamAttr::NoUnwind);
378 PAL = PAL.removeAttr(0, ParamAttr::NoUnwind);
383 //===----------------------------------------------------------------------===//
384 // InvokeInst Implementation
385 //===----------------------------------------------------------------------===//
387 InvokeInst::~InvokeInst() {
388 delete [] OperandList;
391 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
392 Value* const *Args, unsigned NumArgs) {
393 NumOperands = 3+NumArgs;
394 Use *OL = OperandList = new Use[3+NumArgs];
395 OL[0].init(Fn, this);
396 OL[1].init(IfNormal, this);
397 OL[2].init(IfException, this);
398 const FunctionType *FTy =
399 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
400 FTy = FTy; // silence warning.
402 assert(((NumArgs == FTy->getNumParams()) ||
403 (FTy->isVarArg() && NumArgs > FTy->getNumParams())) &&
404 "Calling a function with bad signature");
406 for (unsigned i = 0, e = NumArgs; i != e; i++) {
407 assert((i >= FTy->getNumParams() ||
408 FTy->getParamType(i) == Args[i]->getType()) &&
409 "Invoking a function with a bad signature!");
411 OL[i+3].init(Args[i], this);
415 InvokeInst::InvokeInst(const InvokeInst &II)
416 : TerminatorInst(II.getType(), Instruction::Invoke,
417 new Use[II.getNumOperands()], II.getNumOperands()) {
418 setParamAttrs(II.getParamAttrs());
419 SubclassData = II.SubclassData;
420 Use *OL = OperandList, *InOL = II.OperandList;
421 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
422 OL[i].init(InOL[i], this);
425 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
426 return getSuccessor(idx);
428 unsigned InvokeInst::getNumSuccessorsV() const {
429 return getNumSuccessors();
431 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
432 return setSuccessor(idx, B);
435 bool InvokeInst::paramHasAttr(unsigned i, ParameterAttributes attr) const {
436 if (ParamAttrs.paramHasAttr(i, attr))
438 if (const Function *F = getCalledFunction())
439 return F->paramHasAttr(i, attr);
443 void InvokeInst::setDoesNotThrow(bool doesNotThrow) {
444 PAListPtr PAL = getParamAttrs();
446 PAL = PAL.addAttr(0, ParamAttr::NoUnwind);
448 PAL = PAL.removeAttr(0, ParamAttr::NoUnwind);
453 //===----------------------------------------------------------------------===//
454 // ReturnInst Implementation
455 //===----------------------------------------------------------------------===//
457 ReturnInst::ReturnInst(const ReturnInst &RI)
458 : TerminatorInst(Type::VoidTy, Instruction::Ret,
459 &RetVal, RI.getNumOperands()) {
460 unsigned N = RI.getNumOperands();
462 RetVal.init(RI.RetVal, this);
464 Use *OL = OperandList = new Use[N];
465 for (unsigned i = 0; i < N; ++i)
466 OL[i].init(RI.getOperand(i), this);
470 ReturnInst::ReturnInst(Value *retVal, Instruction *InsertBefore)
471 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertBefore) {
475 ReturnInst::ReturnInst(Value *retVal, BasicBlock *InsertAtEnd)
476 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertAtEnd) {
480 ReturnInst::ReturnInst(BasicBlock *InsertAtEnd)
481 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertAtEnd) {
484 ReturnInst::ReturnInst(Value * const* retVals, unsigned N,
485 Instruction *InsertBefore)
486 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, N, InsertBefore) {
490 ReturnInst::ReturnInst(Value * const* retVals, unsigned N,
491 BasicBlock *InsertAtEnd)
492 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, N, InsertAtEnd) {
496 ReturnInst::ReturnInst(Value * const* retVals, unsigned N)
497 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, N) {
502 void ReturnInst::init(Value * const* retVals, unsigned N) {
503 assert (N > 0 && "Invalid operands numbers in ReturnInst init");
506 if (NumOperands == 1) {
508 if (V->getType() == Type::VoidTy)
510 RetVal.init(V, this);
514 Use *OL = OperandList = new Use[NumOperands];
515 for (unsigned i = 0; i < NumOperands; ++i) {
516 Value *V = *retVals++;
517 assert(!isa<BasicBlock>(V) &&
518 "Cannot return basic block. Probably using the incorrect ctor");
523 unsigned ReturnInst::getNumSuccessorsV() const {
524 return getNumSuccessors();
527 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
528 /// emit the vtable for the class in this translation unit.
529 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
530 assert(0 && "ReturnInst has no successors!");
533 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
534 assert(0 && "ReturnInst has no successors!");
539 ReturnInst::~ReturnInst() {
541 delete [] OperandList;
544 //===----------------------------------------------------------------------===//
545 // UnwindInst Implementation
546 //===----------------------------------------------------------------------===//
548 UnwindInst::UnwindInst(Instruction *InsertBefore)
549 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertBefore) {
551 UnwindInst::UnwindInst(BasicBlock *InsertAtEnd)
552 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertAtEnd) {
556 unsigned UnwindInst::getNumSuccessorsV() const {
557 return getNumSuccessors();
560 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
561 assert(0 && "UnwindInst has no successors!");
564 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
565 assert(0 && "UnwindInst has no successors!");
570 //===----------------------------------------------------------------------===//
571 // UnreachableInst Implementation
572 //===----------------------------------------------------------------------===//
574 UnreachableInst::UnreachableInst(Instruction *InsertBefore)
575 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertBefore) {
577 UnreachableInst::UnreachableInst(BasicBlock *InsertAtEnd)
578 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertAtEnd) {
581 unsigned UnreachableInst::getNumSuccessorsV() const {
582 return getNumSuccessors();
585 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
586 assert(0 && "UnwindInst has no successors!");
589 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
590 assert(0 && "UnwindInst has no successors!");
595 //===----------------------------------------------------------------------===//
596 // BranchInst Implementation
597 //===----------------------------------------------------------------------===//
599 void BranchInst::AssertOK() {
601 assert(getCondition()->getType() == Type::Int1Ty &&
602 "May only branch on boolean predicates!");
605 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
606 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 1, InsertBefore) {
607 assert(IfTrue != 0 && "Branch destination may not be null!");
608 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
610 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
611 Instruction *InsertBefore)
612 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 3, InsertBefore) {
613 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
614 Ops[1].init(reinterpret_cast<Value*>(IfFalse), this);
615 Ops[2].init(Cond, this);
621 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
622 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 1, InsertAtEnd) {
623 assert(IfTrue != 0 && "Branch destination may not be null!");
624 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
627 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
628 BasicBlock *InsertAtEnd)
629 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 3, InsertAtEnd) {
630 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
631 Ops[1].init(reinterpret_cast<Value*>(IfFalse), this);
632 Ops[2].init(Cond, this);
639 BranchInst::BranchInst(const BranchInst &BI) :
640 TerminatorInst(Type::VoidTy, Instruction::Br, Ops, BI.getNumOperands()) {
641 OperandList[0].init(BI.getOperand(0), this);
642 if (BI.getNumOperands() != 1) {
643 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
644 OperandList[1].init(BI.getOperand(1), this);
645 OperandList[2].init(BI.getOperand(2), this);
649 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
650 return getSuccessor(idx);
652 unsigned BranchInst::getNumSuccessorsV() const {
653 return getNumSuccessors();
655 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
656 setSuccessor(idx, B);
660 //===----------------------------------------------------------------------===//
661 // AllocationInst Implementation
662 //===----------------------------------------------------------------------===//
664 static Value *getAISize(Value *Amt) {
666 Amt = ConstantInt::get(Type::Int32Ty, 1);
668 assert(!isa<BasicBlock>(Amt) &&
669 "Passed basic block into allocation size parameter! Use other ctor");
670 assert(Amt->getType() == Type::Int32Ty &&
671 "Malloc/Allocation array size is not a 32-bit integer!");
676 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
677 unsigned Align, const std::string &Name,
678 Instruction *InsertBefore)
679 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
682 assert(Ty != Type::VoidTy && "Cannot allocate void!");
686 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
687 unsigned Align, const std::string &Name,
688 BasicBlock *InsertAtEnd)
689 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
692 assert(Ty != Type::VoidTy && "Cannot allocate void!");
696 // Out of line virtual method, so the vtable, etc has a home.
697 AllocationInst::~AllocationInst() {
700 void AllocationInst::setAlignment(unsigned Align) {
701 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
702 SubclassData = Log2_32(Align) + 1;
703 assert(getAlignment() == Align && "Alignment representation error!");
706 bool AllocationInst::isArrayAllocation() const {
707 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
708 return CI->getZExtValue() != 1;
712 const Type *AllocationInst::getAllocatedType() const {
713 return getType()->getElementType();
716 AllocaInst::AllocaInst(const AllocaInst &AI)
717 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
718 Instruction::Alloca, AI.getAlignment()) {
721 MallocInst::MallocInst(const MallocInst &MI)
722 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
723 Instruction::Malloc, MI.getAlignment()) {
726 //===----------------------------------------------------------------------===//
727 // FreeInst Implementation
728 //===----------------------------------------------------------------------===//
730 void FreeInst::AssertOK() {
731 assert(isa<PointerType>(getOperand(0)->getType()) &&
732 "Can not free something of nonpointer type!");
735 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
736 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertBefore) {
740 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
741 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertAtEnd) {
746 //===----------------------------------------------------------------------===//
747 // LoadInst Implementation
748 //===----------------------------------------------------------------------===//
750 void LoadInst::AssertOK() {
751 assert(isa<PointerType>(getOperand(0)->getType()) &&
752 "Ptr must have pointer type.");
755 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
756 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
757 Load, Ptr, InsertBef) {
764 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
765 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
766 Load, Ptr, InsertAE) {
773 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
774 Instruction *InsertBef)
775 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
776 Load, Ptr, InsertBef) {
777 setVolatile(isVolatile);
783 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
784 unsigned Align, Instruction *InsertBef)
785 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
786 Load, Ptr, InsertBef) {
787 setVolatile(isVolatile);
793 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
794 unsigned Align, BasicBlock *InsertAE)
795 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
796 Load, Ptr, InsertAE) {
797 setVolatile(isVolatile);
803 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
804 BasicBlock *InsertAE)
805 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
806 Load, Ptr, InsertAE) {
807 setVolatile(isVolatile);
815 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
816 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
817 Load, Ptr, InsertBef) {
821 if (Name && Name[0]) setName(Name);
824 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
825 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
826 Load, Ptr, InsertAE) {
830 if (Name && Name[0]) setName(Name);
833 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
834 Instruction *InsertBef)
835 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
836 Load, Ptr, InsertBef) {
837 setVolatile(isVolatile);
840 if (Name && Name[0]) setName(Name);
843 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
844 BasicBlock *InsertAE)
845 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
846 Load, Ptr, InsertAE) {
847 setVolatile(isVolatile);
850 if (Name && Name[0]) setName(Name);
853 void LoadInst::setAlignment(unsigned Align) {
854 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
855 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
858 //===----------------------------------------------------------------------===//
859 // StoreInst Implementation
860 //===----------------------------------------------------------------------===//
862 void StoreInst::AssertOK() {
863 assert(isa<PointerType>(getOperand(1)->getType()) &&
864 "Ptr must have pointer type!");
865 assert(getOperand(0)->getType() ==
866 cast<PointerType>(getOperand(1)->getType())->getElementType()
867 && "Ptr must be a pointer to Val type!");
871 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
872 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
873 Ops[0].init(val, this);
874 Ops[1].init(addr, this);
880 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
881 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
882 Ops[0].init(val, this);
883 Ops[1].init(addr, this);
889 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
890 Instruction *InsertBefore)
891 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
892 Ops[0].init(val, this);
893 Ops[1].init(addr, this);
894 setVolatile(isVolatile);
899 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
900 unsigned Align, Instruction *InsertBefore)
901 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
902 Ops[0].init(val, this);
903 Ops[1].init(addr, this);
904 setVolatile(isVolatile);
909 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
910 unsigned Align, BasicBlock *InsertAtEnd)
911 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
912 Ops[0].init(val, this);
913 Ops[1].init(addr, this);
914 setVolatile(isVolatile);
919 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
920 BasicBlock *InsertAtEnd)
921 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
922 Ops[0].init(val, this);
923 Ops[1].init(addr, this);
924 setVolatile(isVolatile);
929 void StoreInst::setAlignment(unsigned Align) {
930 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
931 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
934 //===----------------------------------------------------------------------===//
935 // GetElementPtrInst Implementation
936 //===----------------------------------------------------------------------===//
938 static unsigned retrieveAddrSpace(const Value *Val) {
939 return cast<PointerType>(Val->getType())->getAddressSpace();
942 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx) {
943 NumOperands = 1+NumIdx;
944 Use *OL = OperandList = new Use[NumOperands];
945 OL[0].init(Ptr, this);
947 for (unsigned i = 0; i != NumIdx; ++i)
948 OL[i+1].init(Idx[i], this);
951 void GetElementPtrInst::init(Value *Ptr, Value *Idx) {
953 Use *OL = OperandList = new Use[2];
954 OL[0].init(Ptr, this);
955 OL[1].init(Idx, this);
958 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
959 const std::string &Name, Instruction *InBe)
960 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
961 retrieveAddrSpace(Ptr)),
962 GetElementPtr, 0, 0, InBe) {
967 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
968 const std::string &Name, BasicBlock *IAE)
969 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
970 retrieveAddrSpace(Ptr)),
971 GetElementPtr, 0, 0, IAE) {
976 GetElementPtrInst::~GetElementPtrInst() {
977 delete[] OperandList;
980 // getIndexedType - Returns the type of the element that would be loaded with
981 // a load instruction with the specified parameters.
983 // A null type is returned if the indices are invalid for the specified
986 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
989 bool AllowCompositeLeaf) {
990 if (!isa<PointerType>(Ptr)) return 0; // Type isn't a pointer type!
992 // Handle the special case of the empty set index set...
994 if (AllowCompositeLeaf ||
995 cast<PointerType>(Ptr)->getElementType()->isFirstClassType())
996 return cast<PointerType>(Ptr)->getElementType();
1001 unsigned CurIdx = 0;
1002 while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
1003 if (NumIdx == CurIdx) {
1004 if (AllowCompositeLeaf || CT->isFirstClassType()) return Ptr;
1005 return 0; // Can't load a whole structure or array!?!?
1008 Value *Index = Idxs[CurIdx++];
1009 if (isa<PointerType>(CT) && CurIdx != 1)
1010 return 0; // Can only index into pointer types at the first index!
1011 if (!CT->indexValid(Index)) return 0;
1012 Ptr = CT->getTypeAtIndex(Index);
1014 // If the new type forwards to another type, then it is in the middle
1015 // of being refined to another type (and hence, may have dropped all
1016 // references to what it was using before). So, use the new forwarded
1018 if (const Type * Ty = Ptr->getForwardedType()) {
1022 return CurIdx == NumIdx ? Ptr : 0;
1025 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1026 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1027 if (!PTy) return 0; // Type isn't a pointer type!
1029 // Check the pointer index.
1030 if (!PTy->indexValid(Idx)) return 0;
1032 return PTy->getElementType();
1036 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1037 /// zeros. If so, the result pointer and the first operand have the same
1038 /// value, just potentially different types.
1039 bool GetElementPtrInst::hasAllZeroIndices() const {
1040 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1041 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1042 if (!CI->isZero()) return false;
1050 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1051 /// constant integers. If so, the result pointer and the first operand have
1052 /// a constant offset between them.
1053 bool GetElementPtrInst::hasAllConstantIndices() const {
1054 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1055 if (!isa<ConstantInt>(getOperand(i)))
1062 //===----------------------------------------------------------------------===//
1063 // ExtractElementInst Implementation
1064 //===----------------------------------------------------------------------===//
1066 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1067 const std::string &Name,
1068 Instruction *InsertBef)
1069 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1070 ExtractElement, Ops, 2, InsertBef) {
1071 assert(isValidOperands(Val, Index) &&
1072 "Invalid extractelement instruction operands!");
1073 Ops[0].init(Val, this);
1074 Ops[1].init(Index, this);
1078 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1079 const std::string &Name,
1080 Instruction *InsertBef)
1081 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1082 ExtractElement, Ops, 2, InsertBef) {
1083 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1084 assert(isValidOperands(Val, Index) &&
1085 "Invalid extractelement instruction operands!");
1086 Ops[0].init(Val, this);
1087 Ops[1].init(Index, this);
1092 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1093 const std::string &Name,
1094 BasicBlock *InsertAE)
1095 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1096 ExtractElement, Ops, 2, InsertAE) {
1097 assert(isValidOperands(Val, Index) &&
1098 "Invalid extractelement instruction operands!");
1100 Ops[0].init(Val, this);
1101 Ops[1].init(Index, this);
1105 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1106 const std::string &Name,
1107 BasicBlock *InsertAE)
1108 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1109 ExtractElement, Ops, 2, InsertAE) {
1110 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1111 assert(isValidOperands(Val, Index) &&
1112 "Invalid extractelement instruction operands!");
1114 Ops[0].init(Val, this);
1115 Ops[1].init(Index, this);
1120 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1121 if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty)
1127 //===----------------------------------------------------------------------===//
1128 // InsertElementInst Implementation
1129 //===----------------------------------------------------------------------===//
1131 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
1132 : Instruction(IE.getType(), InsertElement, Ops, 3) {
1133 Ops[0].init(IE.Ops[0], this);
1134 Ops[1].init(IE.Ops[1], this);
1135 Ops[2].init(IE.Ops[2], this);
1137 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1138 const std::string &Name,
1139 Instruction *InsertBef)
1140 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertBef) {
1141 assert(isValidOperands(Vec, Elt, Index) &&
1142 "Invalid insertelement instruction operands!");
1143 Ops[0].init(Vec, this);
1144 Ops[1].init(Elt, this);
1145 Ops[2].init(Index, this);
1149 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1150 const std::string &Name,
1151 Instruction *InsertBef)
1152 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertBef) {
1153 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1154 assert(isValidOperands(Vec, Elt, Index) &&
1155 "Invalid insertelement instruction operands!");
1156 Ops[0].init(Vec, this);
1157 Ops[1].init(Elt, this);
1158 Ops[2].init(Index, this);
1163 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1164 const std::string &Name,
1165 BasicBlock *InsertAE)
1166 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertAE) {
1167 assert(isValidOperands(Vec, Elt, Index) &&
1168 "Invalid insertelement instruction operands!");
1170 Ops[0].init(Vec, this);
1171 Ops[1].init(Elt, this);
1172 Ops[2].init(Index, this);
1176 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1177 const std::string &Name,
1178 BasicBlock *InsertAE)
1179 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertAE) {
1180 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1181 assert(isValidOperands(Vec, Elt, Index) &&
1182 "Invalid insertelement instruction operands!");
1184 Ops[0].init(Vec, this);
1185 Ops[1].init(Elt, this);
1186 Ops[2].init(Index, this);
1190 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1191 const Value *Index) {
1192 if (!isa<VectorType>(Vec->getType()))
1193 return false; // First operand of insertelement must be vector type.
1195 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1196 return false;// Second operand of insertelement must be vector element type.
1198 if (Index->getType() != Type::Int32Ty)
1199 return false; // Third operand of insertelement must be uint.
1204 //===----------------------------------------------------------------------===//
1205 // ShuffleVectorInst Implementation
1206 //===----------------------------------------------------------------------===//
1208 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
1209 : Instruction(SV.getType(), ShuffleVector, Ops, 3) {
1210 Ops[0].init(SV.Ops[0], this);
1211 Ops[1].init(SV.Ops[1], this);
1212 Ops[2].init(SV.Ops[2], this);
1215 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1216 const std::string &Name,
1217 Instruction *InsertBefore)
1218 : Instruction(V1->getType(), ShuffleVector, Ops, 3, InsertBefore) {
1219 assert(isValidOperands(V1, V2, Mask) &&
1220 "Invalid shuffle vector instruction operands!");
1221 Ops[0].init(V1, this);
1222 Ops[1].init(V2, this);
1223 Ops[2].init(Mask, this);
1227 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1228 const std::string &Name,
1229 BasicBlock *InsertAtEnd)
1230 : Instruction(V1->getType(), ShuffleVector, Ops, 3, InsertAtEnd) {
1231 assert(isValidOperands(V1, V2, Mask) &&
1232 "Invalid shuffle vector instruction operands!");
1234 Ops[0].init(V1, this);
1235 Ops[1].init(V2, this);
1236 Ops[2].init(Mask, this);
1240 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1241 const Value *Mask) {
1242 if (!isa<VectorType>(V1->getType()) ||
1243 V1->getType() != V2->getType())
1246 const VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1247 if (!isa<Constant>(Mask) || MaskTy == 0 ||
1248 MaskTy->getElementType() != Type::Int32Ty ||
1249 MaskTy->getNumElements() !=
1250 cast<VectorType>(V1->getType())->getNumElements())
1255 /// getMaskValue - Return the index from the shuffle mask for the specified
1256 /// output result. This is either -1 if the element is undef or a number less
1257 /// than 2*numelements.
1258 int ShuffleVectorInst::getMaskValue(unsigned i) const {
1259 const Constant *Mask = cast<Constant>(getOperand(2));
1260 if (isa<UndefValue>(Mask)) return -1;
1261 if (isa<ConstantAggregateZero>(Mask)) return 0;
1262 const ConstantVector *MaskCV = cast<ConstantVector>(Mask);
1263 assert(i < MaskCV->getNumOperands() && "Index out of range");
1265 if (isa<UndefValue>(MaskCV->getOperand(i)))
1267 return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
1271 //===----------------------------------------------------------------------===//
1272 // BinaryOperator Class
1273 //===----------------------------------------------------------------------===//
1275 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1276 const Type *Ty, const std::string &Name,
1277 Instruction *InsertBefore)
1278 : Instruction(Ty, iType, Ops, 2, InsertBefore) {
1279 Ops[0].init(S1, this);
1280 Ops[1].init(S2, this);
1285 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1286 const Type *Ty, const std::string &Name,
1287 BasicBlock *InsertAtEnd)
1288 : Instruction(Ty, iType, Ops, 2, InsertAtEnd) {
1289 Ops[0].init(S1, this);
1290 Ops[1].init(S2, this);
1296 void BinaryOperator::init(BinaryOps iType) {
1297 Value *LHS = getOperand(0), *RHS = getOperand(1);
1298 LHS = LHS; RHS = RHS; // Silence warnings.
1299 assert(LHS->getType() == RHS->getType() &&
1300 "Binary operator operand types must match!");
1305 assert(getType() == LHS->getType() &&
1306 "Arithmetic operation should return same type as operands!");
1307 assert((getType()->isInteger() || getType()->isFloatingPoint() ||
1308 isa<VectorType>(getType())) &&
1309 "Tried to create an arithmetic operation on a non-arithmetic type!");
1313 assert(getType() == LHS->getType() &&
1314 "Arithmetic operation should return same type as operands!");
1315 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1316 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1317 "Incorrect operand type (not integer) for S/UDIV");
1320 assert(getType() == LHS->getType() &&
1321 "Arithmetic operation should return same type as operands!");
1322 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1323 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1324 && "Incorrect operand type (not floating point) for FDIV");
1328 assert(getType() == LHS->getType() &&
1329 "Arithmetic operation should return same type as operands!");
1330 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1331 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1332 "Incorrect operand type (not integer) for S/UREM");
1335 assert(getType() == LHS->getType() &&
1336 "Arithmetic operation should return same type as operands!");
1337 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1338 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1339 && "Incorrect operand type (not floating point) for FREM");
1344 assert(getType() == LHS->getType() &&
1345 "Shift operation should return same type as operands!");
1346 assert(getType()->isInteger() &&
1347 "Shift operation requires integer operands");
1351 assert(getType() == LHS->getType() &&
1352 "Logical operation should return same type as operands!");
1353 assert((getType()->isInteger() ||
1354 (isa<VectorType>(getType()) &&
1355 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1356 "Tried to create a logical operation on a non-integral type!");
1364 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1365 const std::string &Name,
1366 Instruction *InsertBefore) {
1367 assert(S1->getType() == S2->getType() &&
1368 "Cannot create binary operator with two operands of differing type!");
1369 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1372 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1373 const std::string &Name,
1374 BasicBlock *InsertAtEnd) {
1375 BinaryOperator *Res = create(Op, S1, S2, Name);
1376 InsertAtEnd->getInstList().push_back(Res);
1380 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1381 Instruction *InsertBefore) {
1382 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1383 return new BinaryOperator(Instruction::Sub,
1385 Op->getType(), Name, InsertBefore);
1388 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1389 BasicBlock *InsertAtEnd) {
1390 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1391 return new BinaryOperator(Instruction::Sub,
1393 Op->getType(), Name, InsertAtEnd);
1396 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1397 Instruction *InsertBefore) {
1399 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1400 C = ConstantInt::getAllOnesValue(PTy->getElementType());
1401 C = ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), C));
1403 C = ConstantInt::getAllOnesValue(Op->getType());
1406 return new BinaryOperator(Instruction::Xor, Op, C,
1407 Op->getType(), Name, InsertBefore);
1410 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1411 BasicBlock *InsertAtEnd) {
1413 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1414 // Create a vector of all ones values.
1415 Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType());
1417 ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1419 AllOnes = ConstantInt::getAllOnesValue(Op->getType());
1422 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1423 Op->getType(), Name, InsertAtEnd);
1427 // isConstantAllOnes - Helper function for several functions below
1428 static inline bool isConstantAllOnes(const Value *V) {
1429 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1430 return CI->isAllOnesValue();
1431 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1432 return CV->isAllOnesValue();
1436 bool BinaryOperator::isNeg(const Value *V) {
1437 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1438 if (Bop->getOpcode() == Instruction::Sub)
1439 return Bop->getOperand(0) ==
1440 ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1444 bool BinaryOperator::isNot(const Value *V) {
1445 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1446 return (Bop->getOpcode() == Instruction::Xor &&
1447 (isConstantAllOnes(Bop->getOperand(1)) ||
1448 isConstantAllOnes(Bop->getOperand(0))));
1452 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1453 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1454 return cast<BinaryOperator>(BinOp)->getOperand(1);
1457 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1458 return getNegArgument(const_cast<Value*>(BinOp));
1461 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1462 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1463 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1464 Value *Op0 = BO->getOperand(0);
1465 Value *Op1 = BO->getOperand(1);
1466 if (isConstantAllOnes(Op0)) return Op1;
1468 assert(isConstantAllOnes(Op1));
1472 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1473 return getNotArgument(const_cast<Value*>(BinOp));
1477 // swapOperands - Exchange the two operands to this instruction. This
1478 // instruction is safe to use on any binary instruction and does not
1479 // modify the semantics of the instruction. If the instruction is
1480 // order dependent (SetLT f.e.) the opcode is changed.
1482 bool BinaryOperator::swapOperands() {
1483 if (!isCommutative())
1484 return true; // Can't commute operands
1485 std::swap(Ops[0], Ops[1]);
1489 //===----------------------------------------------------------------------===//
1491 //===----------------------------------------------------------------------===//
1493 // Just determine if this cast only deals with integral->integral conversion.
1494 bool CastInst::isIntegerCast() const {
1495 switch (getOpcode()) {
1496 default: return false;
1497 case Instruction::ZExt:
1498 case Instruction::SExt:
1499 case Instruction::Trunc:
1501 case Instruction::BitCast:
1502 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1506 bool CastInst::isLosslessCast() const {
1507 // Only BitCast can be lossless, exit fast if we're not BitCast
1508 if (getOpcode() != Instruction::BitCast)
1511 // Identity cast is always lossless
1512 const Type* SrcTy = getOperand(0)->getType();
1513 const Type* DstTy = getType();
1517 // Pointer to pointer is always lossless.
1518 if (isa<PointerType>(SrcTy))
1519 return isa<PointerType>(DstTy);
1520 return false; // Other types have no identity values
1523 /// This function determines if the CastInst does not require any bits to be
1524 /// changed in order to effect the cast. Essentially, it identifies cases where
1525 /// no code gen is necessary for the cast, hence the name no-op cast. For
1526 /// example, the following are all no-op casts:
1527 /// # bitcast uint %X, int
1528 /// # bitcast uint* %x, sbyte*
1529 /// # bitcast vector< 2 x int > %x, vector< 4 x short>
1530 /// # ptrtoint uint* %x, uint ; on 32-bit plaforms only
1531 /// @brief Determine if a cast is a no-op.
1532 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1533 switch (getOpcode()) {
1535 assert(!"Invalid CastOp");
1536 case Instruction::Trunc:
1537 case Instruction::ZExt:
1538 case Instruction::SExt:
1539 case Instruction::FPTrunc:
1540 case Instruction::FPExt:
1541 case Instruction::UIToFP:
1542 case Instruction::SIToFP:
1543 case Instruction::FPToUI:
1544 case Instruction::FPToSI:
1545 return false; // These always modify bits
1546 case Instruction::BitCast:
1547 return true; // BitCast never modifies bits.
1548 case Instruction::PtrToInt:
1549 return IntPtrTy->getPrimitiveSizeInBits() ==
1550 getType()->getPrimitiveSizeInBits();
1551 case Instruction::IntToPtr:
1552 return IntPtrTy->getPrimitiveSizeInBits() ==
1553 getOperand(0)->getType()->getPrimitiveSizeInBits();
1557 /// This function determines if a pair of casts can be eliminated and what
1558 /// opcode should be used in the elimination. This assumes that there are two
1559 /// instructions like this:
1560 /// * %F = firstOpcode SrcTy %x to MidTy
1561 /// * %S = secondOpcode MidTy %F to DstTy
1562 /// The function returns a resultOpcode so these two casts can be replaced with:
1563 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1564 /// If no such cast is permited, the function returns 0.
1565 unsigned CastInst::isEliminableCastPair(
1566 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1567 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1569 // Define the 144 possibilities for these two cast instructions. The values
1570 // in this matrix determine what to do in a given situation and select the
1571 // case in the switch below. The rows correspond to firstOp, the columns
1572 // correspond to secondOp. In looking at the table below, keep in mind
1573 // the following cast properties:
1575 // Size Compare Source Destination
1576 // Operator Src ? Size Type Sign Type Sign
1577 // -------- ------------ ------------------- ---------------------
1578 // TRUNC > Integer Any Integral Any
1579 // ZEXT < Integral Unsigned Integer Any
1580 // SEXT < Integral Signed Integer Any
1581 // FPTOUI n/a FloatPt n/a Integral Unsigned
1582 // FPTOSI n/a FloatPt n/a Integral Signed
1583 // UITOFP n/a Integral Unsigned FloatPt n/a
1584 // SITOFP n/a Integral Signed FloatPt n/a
1585 // FPTRUNC > FloatPt n/a FloatPt n/a
1586 // FPEXT < FloatPt n/a FloatPt n/a
1587 // PTRTOINT n/a Pointer n/a Integral Unsigned
1588 // INTTOPTR n/a Integral Unsigned Pointer n/a
1589 // BITCONVERT = FirstClass n/a FirstClass n/a
1591 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1592 // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
1593 // into "fptoui double to ulong", but this loses information about the range
1594 // of the produced value (we no longer know the top-part is all zeros).
1595 // Further this conversion is often much more expensive for typical hardware,
1596 // and causes issues when building libgcc. We disallow fptosi+sext for the
1598 const unsigned numCastOps =
1599 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1600 static const uint8_t CastResults[numCastOps][numCastOps] = {
1601 // T F F U S F F P I B -+
1602 // R Z S P P I I T P 2 N T |
1603 // U E E 2 2 2 2 R E I T C +- secondOp
1604 // N X X U S F F N X N 2 V |
1605 // C T T I I P P C T T P T -+
1606 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1607 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1608 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1609 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1610 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1611 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1612 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1613 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1614 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1615 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1616 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1617 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1620 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1621 [secondOp-Instruction::CastOpsBegin];
1624 // categorically disallowed
1627 // allowed, use first cast's opcode
1630 // allowed, use second cast's opcode
1633 // no-op cast in second op implies firstOp as long as the DestTy
1635 if (DstTy->isInteger())
1639 // no-op cast in second op implies firstOp as long as the DestTy
1640 // is floating point
1641 if (DstTy->isFloatingPoint())
1645 // no-op cast in first op implies secondOp as long as the SrcTy
1647 if (SrcTy->isInteger())
1651 // no-op cast in first op implies secondOp as long as the SrcTy
1652 // is a floating point
1653 if (SrcTy->isFloatingPoint())
1657 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1658 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1659 unsigned MidSize = MidTy->getPrimitiveSizeInBits();
1660 if (MidSize >= PtrSize)
1661 return Instruction::BitCast;
1665 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1666 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1667 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1668 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1669 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1670 if (SrcSize == DstSize)
1671 return Instruction::BitCast;
1672 else if (SrcSize < DstSize)
1676 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1677 return Instruction::ZExt;
1679 // fpext followed by ftrunc is allowed if the bit size returned to is
1680 // the same as the original, in which case its just a bitcast
1682 return Instruction::BitCast;
1683 return 0; // If the types are not the same we can't eliminate it.
1685 // bitcast followed by ptrtoint is allowed as long as the bitcast
1686 // is a pointer to pointer cast.
1687 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1691 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1692 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1696 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1697 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1698 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1699 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1700 if (SrcSize <= PtrSize && SrcSize == DstSize)
1701 return Instruction::BitCast;
1705 // cast combination can't happen (error in input). This is for all cases
1706 // where the MidTy is not the same for the two cast instructions.
1707 assert(!"Invalid Cast Combination");
1710 assert(!"Error in CastResults table!!!");
1716 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1717 const std::string &Name, Instruction *InsertBefore) {
1718 // Construct and return the appropriate CastInst subclass
1720 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1721 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1722 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1723 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1724 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1725 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1726 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1727 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1728 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1729 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1730 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1731 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1733 assert(!"Invalid opcode provided");
1738 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1739 const std::string &Name, BasicBlock *InsertAtEnd) {
1740 // Construct and return the appropriate CastInst subclass
1742 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1743 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1744 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1745 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1746 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1747 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1748 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1749 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1750 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1751 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1752 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1753 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1755 assert(!"Invalid opcode provided");
1760 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1761 const std::string &Name,
1762 Instruction *InsertBefore) {
1763 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1764 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1765 return create(Instruction::ZExt, S, Ty, Name, InsertBefore);
1768 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1769 const std::string &Name,
1770 BasicBlock *InsertAtEnd) {
1771 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1772 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1773 return create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
1776 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1777 const std::string &Name,
1778 Instruction *InsertBefore) {
1779 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1780 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1781 return create(Instruction::SExt, S, Ty, Name, InsertBefore);
1784 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1785 const std::string &Name,
1786 BasicBlock *InsertAtEnd) {
1787 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1788 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1789 return create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
1792 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1793 const std::string &Name,
1794 Instruction *InsertBefore) {
1795 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1796 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1797 return create(Instruction::Trunc, S, Ty, Name, InsertBefore);
1800 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1801 const std::string &Name,
1802 BasicBlock *InsertAtEnd) {
1803 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1804 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1805 return create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
1808 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1809 const std::string &Name,
1810 BasicBlock *InsertAtEnd) {
1811 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1812 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1815 if (Ty->isInteger())
1816 return create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
1817 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1820 /// @brief Create a BitCast or a PtrToInt cast instruction
1821 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1822 const std::string &Name,
1823 Instruction *InsertBefore) {
1824 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1825 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1828 if (Ty->isInteger())
1829 return create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
1830 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1833 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1834 bool isSigned, const std::string &Name,
1835 Instruction *InsertBefore) {
1836 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1837 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1838 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1839 Instruction::CastOps opcode =
1840 (SrcBits == DstBits ? Instruction::BitCast :
1841 (SrcBits > DstBits ? Instruction::Trunc :
1842 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1843 return create(opcode, C, Ty, Name, InsertBefore);
1846 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1847 bool isSigned, const std::string &Name,
1848 BasicBlock *InsertAtEnd) {
1849 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1850 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1851 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1852 Instruction::CastOps opcode =
1853 (SrcBits == DstBits ? Instruction::BitCast :
1854 (SrcBits > DstBits ? Instruction::Trunc :
1855 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1856 return create(opcode, C, Ty, Name, InsertAtEnd);
1859 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1860 const std::string &Name,
1861 Instruction *InsertBefore) {
1862 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1864 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1865 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1866 Instruction::CastOps opcode =
1867 (SrcBits == DstBits ? Instruction::BitCast :
1868 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1869 return create(opcode, C, Ty, Name, InsertBefore);
1872 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1873 const std::string &Name,
1874 BasicBlock *InsertAtEnd) {
1875 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1877 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1878 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1879 Instruction::CastOps opcode =
1880 (SrcBits == DstBits ? Instruction::BitCast :
1881 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1882 return create(opcode, C, Ty, Name, InsertAtEnd);
1885 // Check whether it is valid to call getCastOpcode for these types.
1886 // This routine must be kept in sync with getCastOpcode.
1887 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
1888 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
1891 if (SrcTy == DestTy)
1894 // Get the bit sizes, we'll need these
1895 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1896 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1898 // Run through the possibilities ...
1899 if (DestTy->isInteger()) { // Casting to integral
1900 if (SrcTy->isInteger()) { // Casting from integral
1902 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1904 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1905 // Casting from vector
1906 return DestBits == PTy->getBitWidth();
1907 } else { // Casting from something else
1908 return isa<PointerType>(SrcTy);
1910 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
1911 if (SrcTy->isInteger()) { // Casting from integral
1913 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1915 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1916 // Casting from vector
1917 return DestBits == PTy->getBitWidth();
1918 } else { // Casting from something else
1921 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
1922 // Casting to vector
1923 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
1924 // Casting from vector
1925 return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
1926 } else { // Casting from something else
1927 return DestPTy->getBitWidth() == SrcBits;
1929 } else if (isa<PointerType>(DestTy)) { // Casting to pointer
1930 if (isa<PointerType>(SrcTy)) { // Casting from pointer
1932 } else if (SrcTy->isInteger()) { // Casting from integral
1934 } else { // Casting from something else
1937 } else { // Casting to something else
1942 // Provide a way to get a "cast" where the cast opcode is inferred from the
1943 // types and size of the operand. This, basically, is a parallel of the
1944 // logic in the castIsValid function below. This axiom should hold:
1945 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
1946 // should not assert in castIsValid. In other words, this produces a "correct"
1947 // casting opcode for the arguments passed to it.
1948 // This routine must be kept in sync with isCastable.
1949 Instruction::CastOps
1950 CastInst::getCastOpcode(
1951 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
1952 // Get the bit sizes, we'll need these
1953 const Type *SrcTy = Src->getType();
1954 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1955 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1957 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
1958 "Only first class types are castable!");
1960 // Run through the possibilities ...
1961 if (DestTy->isInteger()) { // Casting to integral
1962 if (SrcTy->isInteger()) { // Casting from integral
1963 if (DestBits < SrcBits)
1964 return Trunc; // int -> smaller int
1965 else if (DestBits > SrcBits) { // its an extension
1967 return SExt; // signed -> SEXT
1969 return ZExt; // unsigned -> ZEXT
1971 return BitCast; // Same size, No-op cast
1973 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1975 return FPToSI; // FP -> sint
1977 return FPToUI; // FP -> uint
1978 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1979 assert(DestBits == PTy->getBitWidth() &&
1980 "Casting vector to integer of different width");
1981 return BitCast; // Same size, no-op cast
1983 assert(isa<PointerType>(SrcTy) &&
1984 "Casting from a value that is not first-class type");
1985 return PtrToInt; // ptr -> int
1987 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
1988 if (SrcTy->isInteger()) { // Casting from integral
1990 return SIToFP; // sint -> FP
1992 return UIToFP; // uint -> FP
1993 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1994 if (DestBits < SrcBits) {
1995 return FPTrunc; // FP -> smaller FP
1996 } else if (DestBits > SrcBits) {
1997 return FPExt; // FP -> larger FP
1999 return BitCast; // same size, no-op cast
2001 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2002 assert(DestBits == PTy->getBitWidth() &&
2003 "Casting vector to floating point of different width");
2004 return BitCast; // same size, no-op cast
2006 assert(0 && "Casting pointer or non-first class to float");
2008 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2009 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2010 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2011 "Casting vector to vector of different widths");
2012 return BitCast; // vector -> vector
2013 } else if (DestPTy->getBitWidth() == SrcBits) {
2014 return BitCast; // float/int -> vector
2016 assert(!"Illegal cast to vector (wrong type or size)");
2018 } else if (isa<PointerType>(DestTy)) {
2019 if (isa<PointerType>(SrcTy)) {
2020 return BitCast; // ptr -> ptr
2021 } else if (SrcTy->isInteger()) {
2022 return IntToPtr; // int -> ptr
2024 assert(!"Casting pointer to other than pointer or int");
2027 assert(!"Casting to type that is not first-class");
2030 // If we fall through to here we probably hit an assertion cast above
2031 // and assertions are not turned on. Anything we return is an error, so
2032 // BitCast is as good a choice as any.
2036 //===----------------------------------------------------------------------===//
2037 // CastInst SubClass Constructors
2038 //===----------------------------------------------------------------------===//
2040 /// Check that the construction parameters for a CastInst are correct. This
2041 /// could be broken out into the separate constructors but it is useful to have
2042 /// it in one place and to eliminate the redundant code for getting the sizes
2043 /// of the types involved.
2045 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2047 // Check for type sanity on the arguments
2048 const Type *SrcTy = S->getType();
2049 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
2052 // Get the size of the types in bits, we'll need this later
2053 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2054 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2056 // Switch on the opcode provided
2058 default: return false; // This is an input error
2059 case Instruction::Trunc:
2060 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize > DstBitSize;
2061 case Instruction::ZExt:
2062 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2063 case Instruction::SExt:
2064 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2065 case Instruction::FPTrunc:
2066 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2067 SrcBitSize > DstBitSize;
2068 case Instruction::FPExt:
2069 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2070 SrcBitSize < DstBitSize;
2071 case Instruction::UIToFP:
2072 case Instruction::SIToFP:
2073 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2074 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2075 return SVTy->getElementType()->isInteger() &&
2076 DVTy->getElementType()->isFloatingPoint() &&
2077 SVTy->getNumElements() == DVTy->getNumElements();
2080 return SrcTy->isInteger() && DstTy->isFloatingPoint();
2081 case Instruction::FPToUI:
2082 case Instruction::FPToSI:
2083 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2084 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2085 return SVTy->getElementType()->isFloatingPoint() &&
2086 DVTy->getElementType()->isInteger() &&
2087 SVTy->getNumElements() == DVTy->getNumElements();
2090 return SrcTy->isFloatingPoint() && DstTy->isInteger();
2091 case Instruction::PtrToInt:
2092 return isa<PointerType>(SrcTy) && DstTy->isInteger();
2093 case Instruction::IntToPtr:
2094 return SrcTy->isInteger() && isa<PointerType>(DstTy);
2095 case Instruction::BitCast:
2096 // BitCast implies a no-op cast of type only. No bits change.
2097 // However, you can't cast pointers to anything but pointers.
2098 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2101 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2102 // these cases, the cast is okay if the source and destination bit widths
2104 return SrcBitSize == DstBitSize;
2108 TruncInst::TruncInst(
2109 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2110 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2111 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2114 TruncInst::TruncInst(
2115 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2116 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2117 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2121 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2122 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2123 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2127 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2128 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2129 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2132 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2133 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2134 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2138 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2139 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2140 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2143 FPTruncInst::FPTruncInst(
2144 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2145 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2146 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2149 FPTruncInst::FPTruncInst(
2150 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2151 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2152 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2155 FPExtInst::FPExtInst(
2156 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2157 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2158 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2161 FPExtInst::FPExtInst(
2162 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2163 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2164 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2167 UIToFPInst::UIToFPInst(
2168 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2169 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2170 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2173 UIToFPInst::UIToFPInst(
2174 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2175 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2176 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2179 SIToFPInst::SIToFPInst(
2180 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2181 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2182 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2185 SIToFPInst::SIToFPInst(
2186 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2187 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2188 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2191 FPToUIInst::FPToUIInst(
2192 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2193 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2194 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2197 FPToUIInst::FPToUIInst(
2198 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2199 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2200 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2203 FPToSIInst::FPToSIInst(
2204 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2205 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2206 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2209 FPToSIInst::FPToSIInst(
2210 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2211 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2212 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2215 PtrToIntInst::PtrToIntInst(
2216 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2217 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2218 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2221 PtrToIntInst::PtrToIntInst(
2222 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2223 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2224 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2227 IntToPtrInst::IntToPtrInst(
2228 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2229 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2230 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2233 IntToPtrInst::IntToPtrInst(
2234 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2235 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2236 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2239 BitCastInst::BitCastInst(
2240 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2241 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2242 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2245 BitCastInst::BitCastInst(
2246 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2247 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2248 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2251 //===----------------------------------------------------------------------===//
2253 //===----------------------------------------------------------------------===//
2255 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2256 const std::string &Name, Instruction *InsertBefore)
2257 : Instruction(Type::Int1Ty, op, Ops, 2, InsertBefore) {
2258 Ops[0].init(LHS, this);
2259 Ops[1].init(RHS, this);
2260 SubclassData = predicate;
2262 if (op == Instruction::ICmp) {
2263 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2264 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2265 "Invalid ICmp predicate value");
2266 const Type* Op0Ty = getOperand(0)->getType();
2267 const Type* Op1Ty = getOperand(1)->getType();
2268 assert(Op0Ty == Op1Ty &&
2269 "Both operands to ICmp instruction are not of the same type!");
2270 // Check that the operands are the right type
2271 assert((Op0Ty->isInteger() || isa<PointerType>(Op0Ty)) &&
2272 "Invalid operand types for ICmp instruction");
2275 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2276 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2277 "Invalid FCmp predicate value");
2278 const Type* Op0Ty = getOperand(0)->getType();
2279 const Type* Op1Ty = getOperand(1)->getType();
2280 assert(Op0Ty == Op1Ty &&
2281 "Both operands to FCmp instruction are not of the same type!");
2282 // Check that the operands are the right type
2283 assert(Op0Ty->isFloatingPoint() &&
2284 "Invalid operand types for FCmp instruction");
2287 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2288 const std::string &Name, BasicBlock *InsertAtEnd)
2289 : Instruction(Type::Int1Ty, op, Ops, 2, InsertAtEnd) {
2290 Ops[0].init(LHS, this);
2291 Ops[1].init(RHS, this);
2292 SubclassData = predicate;
2294 if (op == Instruction::ICmp) {
2295 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2296 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2297 "Invalid ICmp predicate value");
2299 const Type* Op0Ty = getOperand(0)->getType();
2300 const Type* Op1Ty = getOperand(1)->getType();
2301 assert(Op0Ty == Op1Ty &&
2302 "Both operands to ICmp instruction are not of the same type!");
2303 // Check that the operands are the right type
2304 assert((Op0Ty->isInteger() || isa<PointerType>(Op0Ty)) &&
2305 "Invalid operand types for ICmp instruction");
2308 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2309 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2310 "Invalid FCmp predicate value");
2311 const Type* Op0Ty = getOperand(0)->getType();
2312 const Type* Op1Ty = getOperand(1)->getType();
2313 assert(Op0Ty == Op1Ty &&
2314 "Both operands to FCmp instruction are not of the same type!");
2315 // Check that the operands are the right type
2316 assert(Op0Ty->isFloatingPoint() &&
2317 "Invalid operand types for FCmp instruction");
2321 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2322 const std::string &Name, Instruction *InsertBefore) {
2323 if (Op == Instruction::ICmp) {
2324 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2327 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2332 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2333 const std::string &Name, BasicBlock *InsertAtEnd) {
2334 if (Op == Instruction::ICmp) {
2335 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2338 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2342 void CmpInst::swapOperands() {
2343 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2346 cast<FCmpInst>(this)->swapOperands();
2349 bool CmpInst::isCommutative() {
2350 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2351 return IC->isCommutative();
2352 return cast<FCmpInst>(this)->isCommutative();
2355 bool CmpInst::isEquality() {
2356 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2357 return IC->isEquality();
2358 return cast<FCmpInst>(this)->isEquality();
2362 ICmpInst::Predicate ICmpInst::getInversePredicate(Predicate pred) {
2365 assert(!"Unknown icmp predicate!");
2366 case ICMP_EQ: return ICMP_NE;
2367 case ICMP_NE: return ICMP_EQ;
2368 case ICMP_UGT: return ICMP_ULE;
2369 case ICMP_ULT: return ICMP_UGE;
2370 case ICMP_UGE: return ICMP_ULT;
2371 case ICMP_ULE: return ICMP_UGT;
2372 case ICMP_SGT: return ICMP_SLE;
2373 case ICMP_SLT: return ICMP_SGE;
2374 case ICMP_SGE: return ICMP_SLT;
2375 case ICMP_SLE: return ICMP_SGT;
2379 ICmpInst::Predicate ICmpInst::getSwappedPredicate(Predicate pred) {
2381 default: assert(! "Unknown icmp predicate!");
2382 case ICMP_EQ: case ICMP_NE:
2384 case ICMP_SGT: return ICMP_SLT;
2385 case ICMP_SLT: return ICMP_SGT;
2386 case ICMP_SGE: return ICMP_SLE;
2387 case ICMP_SLE: return ICMP_SGE;
2388 case ICMP_UGT: return ICMP_ULT;
2389 case ICMP_ULT: return ICMP_UGT;
2390 case ICMP_UGE: return ICMP_ULE;
2391 case ICMP_ULE: return ICMP_UGE;
2395 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2397 default: assert(! "Unknown icmp predicate!");
2398 case ICMP_EQ: case ICMP_NE:
2399 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2401 case ICMP_UGT: return ICMP_SGT;
2402 case ICMP_ULT: return ICMP_SLT;
2403 case ICMP_UGE: return ICMP_SGE;
2404 case ICMP_ULE: return ICMP_SLE;
2408 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2410 default: assert(! "Unknown icmp predicate!");
2411 case ICMP_EQ: case ICMP_NE:
2412 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2414 case ICMP_SGT: return ICMP_UGT;
2415 case ICMP_SLT: return ICMP_ULT;
2416 case ICMP_SGE: return ICMP_UGE;
2417 case ICMP_SLE: return ICMP_ULE;
2421 bool ICmpInst::isSignedPredicate(Predicate pred) {
2423 default: assert(! "Unknown icmp predicate!");
2424 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2426 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2427 case ICMP_UGE: case ICMP_ULE:
2432 /// Initialize a set of values that all satisfy the condition with C.
2435 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2438 uint32_t BitWidth = C.getBitWidth();
2440 default: assert(0 && "Invalid ICmp opcode to ConstantRange ctor!");
2441 case ICmpInst::ICMP_EQ: Upper++; break;
2442 case ICmpInst::ICMP_NE: Lower++; break;
2443 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2444 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2445 case ICmpInst::ICMP_UGT:
2446 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2448 case ICmpInst::ICMP_SGT:
2449 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2451 case ICmpInst::ICMP_ULE:
2452 Lower = APInt::getMinValue(BitWidth); Upper++;
2454 case ICmpInst::ICMP_SLE:
2455 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2457 case ICmpInst::ICMP_UGE:
2458 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2460 case ICmpInst::ICMP_SGE:
2461 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2464 return ConstantRange(Lower, Upper);
2467 FCmpInst::Predicate FCmpInst::getInversePredicate(Predicate pred) {
2470 assert(!"Unknown icmp predicate!");
2471 case FCMP_OEQ: return FCMP_UNE;
2472 case FCMP_ONE: return FCMP_UEQ;
2473 case FCMP_OGT: return FCMP_ULE;
2474 case FCMP_OLT: return FCMP_UGE;
2475 case FCMP_OGE: return FCMP_ULT;
2476 case FCMP_OLE: return FCMP_UGT;
2477 case FCMP_UEQ: return FCMP_ONE;
2478 case FCMP_UNE: return FCMP_OEQ;
2479 case FCMP_UGT: return FCMP_OLE;
2480 case FCMP_ULT: return FCMP_OGE;
2481 case FCMP_UGE: return FCMP_OLT;
2482 case FCMP_ULE: return FCMP_OGT;
2483 case FCMP_ORD: return FCMP_UNO;
2484 case FCMP_UNO: return FCMP_ORD;
2485 case FCMP_TRUE: return FCMP_FALSE;
2486 case FCMP_FALSE: return FCMP_TRUE;
2490 FCmpInst::Predicate FCmpInst::getSwappedPredicate(Predicate pred) {
2492 default: assert(!"Unknown fcmp predicate!");
2493 case FCMP_FALSE: case FCMP_TRUE:
2494 case FCMP_OEQ: case FCMP_ONE:
2495 case FCMP_UEQ: case FCMP_UNE:
2496 case FCMP_ORD: case FCMP_UNO:
2498 case FCMP_OGT: return FCMP_OLT;
2499 case FCMP_OLT: return FCMP_OGT;
2500 case FCMP_OGE: return FCMP_OLE;
2501 case FCMP_OLE: return FCMP_OGE;
2502 case FCMP_UGT: return FCMP_ULT;
2503 case FCMP_ULT: return FCMP_UGT;
2504 case FCMP_UGE: return FCMP_ULE;
2505 case FCMP_ULE: return FCMP_UGE;
2509 bool CmpInst::isUnsigned(unsigned short predicate) {
2510 switch (predicate) {
2511 default: return false;
2512 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2513 case ICmpInst::ICMP_UGE: return true;
2517 bool CmpInst::isSigned(unsigned short predicate){
2518 switch (predicate) {
2519 default: return false;
2520 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2521 case ICmpInst::ICMP_SGE: return true;
2525 bool CmpInst::isOrdered(unsigned short predicate) {
2526 switch (predicate) {
2527 default: return false;
2528 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2529 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2530 case FCmpInst::FCMP_ORD: return true;
2534 bool CmpInst::isUnordered(unsigned short predicate) {
2535 switch (predicate) {
2536 default: return false;
2537 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2538 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2539 case FCmpInst::FCMP_UNO: return true;
2543 //===----------------------------------------------------------------------===//
2544 // SwitchInst Implementation
2545 //===----------------------------------------------------------------------===//
2547 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2548 assert(Value && Default);
2549 ReservedSpace = 2+NumCases*2;
2551 OperandList = new Use[ReservedSpace];
2553 OperandList[0].init(Value, this);
2554 OperandList[1].init(Default, this);
2557 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2558 /// switch on and a default destination. The number of additional cases can
2559 /// be specified here to make memory allocation more efficient. This
2560 /// constructor can also autoinsert before another instruction.
2561 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2562 Instruction *InsertBefore)
2563 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) {
2564 init(Value, Default, NumCases);
2567 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2568 /// switch on and a default destination. The number of additional cases can
2569 /// be specified here to make memory allocation more efficient. This
2570 /// constructor also autoinserts at the end of the specified BasicBlock.
2571 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2572 BasicBlock *InsertAtEnd)
2573 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) {
2574 init(Value, Default, NumCases);
2577 SwitchInst::SwitchInst(const SwitchInst &SI)
2578 : TerminatorInst(Type::VoidTy, Instruction::Switch,
2579 new Use[SI.getNumOperands()], SI.getNumOperands()) {
2580 Use *OL = OperandList, *InOL = SI.OperandList;
2581 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2582 OL[i].init(InOL[i], this);
2583 OL[i+1].init(InOL[i+1], this);
2587 SwitchInst::~SwitchInst() {
2588 delete [] OperandList;
2592 /// addCase - Add an entry to the switch instruction...
2594 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2595 unsigned OpNo = NumOperands;
2596 if (OpNo+2 > ReservedSpace)
2597 resizeOperands(0); // Get more space!
2598 // Initialize some new operands.
2599 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2600 NumOperands = OpNo+2;
2601 OperandList[OpNo].init(OnVal, this);
2602 OperandList[OpNo+1].init(Dest, this);
2605 /// removeCase - This method removes the specified successor from the switch
2606 /// instruction. Note that this cannot be used to remove the default
2607 /// destination (successor #0).
2609 void SwitchInst::removeCase(unsigned idx) {
2610 assert(idx != 0 && "Cannot remove the default case!");
2611 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2613 unsigned NumOps = getNumOperands();
2614 Use *OL = OperandList;
2616 // Move everything after this operand down.
2618 // FIXME: we could just swap with the end of the list, then erase. However,
2619 // client might not expect this to happen. The code as it is thrashes the
2620 // use/def lists, which is kinda lame.
2621 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2623 OL[i-2+1] = OL[i+1];
2626 // Nuke the last value.
2627 OL[NumOps-2].set(0);
2628 OL[NumOps-2+1].set(0);
2629 NumOperands = NumOps-2;
2632 /// resizeOperands - resize operands - This adjusts the length of the operands
2633 /// list according to the following behavior:
2634 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2635 /// of operation. This grows the number of ops by 1.5 times.
2636 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2637 /// 3. If NumOps == NumOperands, trim the reserved space.
2639 void SwitchInst::resizeOperands(unsigned NumOps) {
2641 NumOps = getNumOperands()/2*6;
2642 } else if (NumOps*2 > NumOperands) {
2643 // No resize needed.
2644 if (ReservedSpace >= NumOps) return;
2645 } else if (NumOps == NumOperands) {
2646 if (ReservedSpace == NumOps) return;
2651 ReservedSpace = NumOps;
2652 Use *NewOps = new Use[NumOps];
2653 Use *OldOps = OperandList;
2654 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2655 NewOps[i].init(OldOps[i], this);
2659 OperandList = NewOps;
2663 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2664 return getSuccessor(idx);
2666 unsigned SwitchInst::getNumSuccessorsV() const {
2667 return getNumSuccessors();
2669 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2670 setSuccessor(idx, B);
2673 //===----------------------------------------------------------------------===//
2674 // GetResultInst Implementation
2675 //===----------------------------------------------------------------------===//
2677 GetResultInst::GetResultInst(Value *Aggregate, unsigned Index,
2678 const std::string &Name,
2679 Instruction *InsertBef)
2680 : Instruction(cast<StructType>(Aggregate->getType())->getElementType(Index),
2681 GetResult, &Aggr, 1, InsertBef) {
2682 assert(isValidOperands(Aggregate, Index) && "Invalid GetResultInst operands!");
2683 Aggr.init(Aggregate, this);
2688 bool GetResultInst::isValidOperands(const Value *Aggregate, unsigned Index) {
2692 if (const StructType *STy = dyn_cast<StructType>(Aggregate->getType())) {
2693 unsigned NumElements = STy->getNumElements();
2694 if (Index >= NumElements || NumElements == 0)
2697 // getresult aggregate value's element types are restricted to
2698 // avoid nested aggregates.
2699 for (unsigned i = 0; i < NumElements; ++i)
2700 if (!STy->getElementType(i)->isFirstClassType())
2703 // Otherwise, Aggregate is valid.
2709 // Define these methods here so vtables don't get emitted into every translation
2710 // unit that uses these classes.
2712 GetElementPtrInst *GetElementPtrInst::clone() const {
2713 return new(getNumOperands()) GetElementPtrInst(*this);
2716 BinaryOperator *BinaryOperator::clone() const {
2717 return create(getOpcode(), Ops[0], Ops[1]);
2720 FCmpInst* FCmpInst::clone() const {
2721 return new FCmpInst(getPredicate(), Ops[0], Ops[1]);
2723 ICmpInst* ICmpInst::clone() const {
2724 return new ICmpInst(getPredicate(), Ops[0], Ops[1]);
2727 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
2728 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
2729 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
2730 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
2731 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
2732 CastInst *TruncInst::clone() const { return new TruncInst(*this); }
2733 CastInst *ZExtInst::clone() const { return new ZExtInst(*this); }
2734 CastInst *SExtInst::clone() const { return new SExtInst(*this); }
2735 CastInst *FPTruncInst::clone() const { return new FPTruncInst(*this); }
2736 CastInst *FPExtInst::clone() const { return new FPExtInst(*this); }
2737 CastInst *UIToFPInst::clone() const { return new UIToFPInst(*this); }
2738 CastInst *SIToFPInst::clone() const { return new SIToFPInst(*this); }
2739 CastInst *FPToUIInst::clone() const { return new FPToUIInst(*this); }
2740 CastInst *FPToSIInst::clone() const { return new FPToSIInst(*this); }
2741 CastInst *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
2742 CastInst *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
2743 CastInst *BitCastInst::clone() const { return new BitCastInst(*this); }
2744 CallInst *CallInst::clone() const { return new(getNumOperands()) CallInst(*this); }
2745 SelectInst *SelectInst::clone() const { return new(getNumOperands()) SelectInst(*this); }
2746 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
2748 ExtractElementInst *ExtractElementInst::clone() const {
2749 return new ExtractElementInst(*this);
2751 InsertElementInst *InsertElementInst::clone() const {
2752 return InsertElementInst::Create(*this);
2754 ShuffleVectorInst *ShuffleVectorInst::clone() const {
2755 return new ShuffleVectorInst(*this);
2757 PHINode *PHINode::clone() const { return new PHINode(*this); }
2758 ReturnInst *ReturnInst::clone() const { return new(getNumOperands()) ReturnInst(*this); }
2759 BranchInst *BranchInst::clone() const { return new(getNumOperands()) BranchInst(*this); }
2760 SwitchInst *SwitchInst::clone() const { return new(getNumOperands()) SwitchInst(*this); }
2761 InvokeInst *InvokeInst::clone() const { return new(getNumOperands()) InvokeInst(*this); }
2762 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
2763 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}
2764 GetResultInst *GetResultInst::clone() const { return new GetResultInst(*this); }