1 //===-- Instructions.cpp - Implement the LLVM instructions ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements all of the non-inline methods for the LLVM instruction
13 //===----------------------------------------------------------------------===//
15 #include "llvm/BasicBlock.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/ParameterAttributes.h"
21 #include "llvm/Support/CallSite.h"
22 #include "llvm/Support/ConstantRange.h"
23 #include "llvm/Support/MathExtras.h"
26 unsigned CallSite::getCallingConv() const {
27 if (CallInst *CI = dyn_cast<CallInst>(I))
28 return CI->getCallingConv();
30 return cast<InvokeInst>(I)->getCallingConv();
32 void CallSite::setCallingConv(unsigned CC) {
33 if (CallInst *CI = dyn_cast<CallInst>(I))
34 CI->setCallingConv(CC);
36 cast<InvokeInst>(I)->setCallingConv(CC);
42 //===----------------------------------------------------------------------===//
43 // TerminatorInst Class
44 //===----------------------------------------------------------------------===//
46 // Out of line virtual method, so the vtable, etc has a home.
47 TerminatorInst::~TerminatorInst() {
50 // Out of line virtual method, so the vtable, etc has a home.
51 UnaryInstruction::~UnaryInstruction() {
55 //===----------------------------------------------------------------------===//
57 //===----------------------------------------------------------------------===//
59 PHINode::PHINode(const PHINode &PN)
60 : Instruction(PN.getType(), Instruction::PHI,
61 new Use[PN.getNumOperands()], PN.getNumOperands()),
62 ReservedSpace(PN.getNumOperands()) {
63 Use *OL = OperandList;
64 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
65 OL[i].init(PN.getOperand(i), this);
66 OL[i+1].init(PN.getOperand(i+1), this);
71 delete [] OperandList;
74 // removeIncomingValue - Remove an incoming value. This is useful if a
75 // predecessor basic block is deleted.
76 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
77 unsigned NumOps = getNumOperands();
78 Use *OL = OperandList;
79 assert(Idx*2 < NumOps && "BB not in PHI node!");
80 Value *Removed = OL[Idx*2];
82 // Move everything after this operand down.
84 // FIXME: we could just swap with the end of the list, then erase. However,
85 // client might not expect this to happen. The code as it is thrashes the
86 // use/def lists, which is kinda lame.
87 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
92 // Nuke the last value.
94 OL[NumOps-2+1].set(0);
95 NumOperands = NumOps-2;
97 // If the PHI node is dead, because it has zero entries, nuke it now.
98 if (NumOps == 2 && DeletePHIIfEmpty) {
99 // If anyone is using this PHI, make them use a dummy value instead...
100 replaceAllUsesWith(UndefValue::get(getType()));
106 /// resizeOperands - resize operands - This adjusts the length of the operands
107 /// list according to the following behavior:
108 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
109 /// of operation. This grows the number of ops by 1.5 times.
110 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
111 /// 3. If NumOps == NumOperands, trim the reserved space.
113 void PHINode::resizeOperands(unsigned NumOps) {
115 NumOps = (getNumOperands())*3/2;
116 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
117 } else if (NumOps*2 > NumOperands) {
119 if (ReservedSpace >= NumOps) return;
120 } else if (NumOps == NumOperands) {
121 if (ReservedSpace == NumOps) return;
126 ReservedSpace = NumOps;
127 Use *NewOps = new Use[NumOps];
128 Use *OldOps = OperandList;
129 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
130 NewOps[i].init(OldOps[i], this);
134 OperandList = NewOps;
137 /// hasConstantValue - If the specified PHI node always merges together the same
138 /// value, return the value, otherwise return null.
140 Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) const {
141 // If the PHI node only has one incoming value, eliminate the PHI node...
142 if (getNumIncomingValues() == 1)
143 if (getIncomingValue(0) != this) // not X = phi X
144 return getIncomingValue(0);
146 return UndefValue::get(getType()); // Self cycle is dead.
148 // Otherwise if all of the incoming values are the same for the PHI, replace
149 // the PHI node with the incoming value.
152 bool HasUndefInput = false;
153 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
154 if (isa<UndefValue>(getIncomingValue(i)))
155 HasUndefInput = true;
156 else if (getIncomingValue(i) != this) // Not the PHI node itself...
157 if (InVal && getIncomingValue(i) != InVal)
158 return 0; // Not the same, bail out.
160 InVal = getIncomingValue(i);
162 // The only case that could cause InVal to be null is if we have a PHI node
163 // that only has entries for itself. In this case, there is no entry into the
164 // loop, so kill the PHI.
166 if (InVal == 0) InVal = UndefValue::get(getType());
168 // If we have a PHI node like phi(X, undef, X), where X is defined by some
169 // instruction, we cannot always return X as the result of the PHI node. Only
170 // do this if X is not an instruction (thus it must dominate the PHI block),
171 // or if the client is prepared to deal with this possibility.
172 if (HasUndefInput && !AllowNonDominatingInstruction)
173 if (Instruction *IV = dyn_cast<Instruction>(InVal))
174 // If it's in the entry block, it dominates everything.
175 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
177 return 0; // Cannot guarantee that InVal dominates this PHINode.
179 // All of the incoming values are the same, return the value now.
184 //===----------------------------------------------------------------------===//
185 // CallInst Implementation
186 //===----------------------------------------------------------------------===//
188 CallInst::~CallInst() {
189 delete [] OperandList;
191 ParamAttrs->dropRef();
194 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
196 NumOperands = NumParams+1;
197 Use *OL = OperandList = new Use[NumParams+1];
198 OL[0].init(Func, this);
200 const FunctionType *FTy =
201 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
202 FTy = FTy; // silence warning.
204 assert((NumParams == FTy->getNumParams() ||
205 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
206 "Calling a function with bad signature!");
207 for (unsigned i = 0; i != NumParams; ++i) {
208 assert((i >= FTy->getNumParams() ||
209 FTy->getParamType(i) == Params[i]->getType()) &&
210 "Calling a function with a bad signature!");
211 OL[i+1].init(Params[i], this);
215 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
218 Use *OL = OperandList = new Use[3];
219 OL[0].init(Func, this);
220 OL[1].init(Actual1, this);
221 OL[2].init(Actual2, this);
223 const FunctionType *FTy =
224 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
225 FTy = FTy; // silence warning.
227 assert((FTy->getNumParams() == 2 ||
228 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
229 "Calling a function with bad signature");
230 assert((0 >= FTy->getNumParams() ||
231 FTy->getParamType(0) == Actual1->getType()) &&
232 "Calling a function with a bad signature!");
233 assert((1 >= FTy->getNumParams() ||
234 FTy->getParamType(1) == Actual2->getType()) &&
235 "Calling a function with a bad signature!");
238 void CallInst::init(Value *Func, Value *Actual) {
241 Use *OL = OperandList = new Use[2];
242 OL[0].init(Func, this);
243 OL[1].init(Actual, this);
245 const FunctionType *FTy =
246 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
247 FTy = FTy; // silence warning.
249 assert((FTy->getNumParams() == 1 ||
250 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
251 "Calling a function with bad signature");
252 assert((0 == FTy->getNumParams() ||
253 FTy->getParamType(0) == Actual->getType()) &&
254 "Calling a function with a bad signature!");
257 void CallInst::init(Value *Func) {
260 Use *OL = OperandList = new Use[1];
261 OL[0].init(Func, this);
263 const FunctionType *FTy =
264 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
265 FTy = FTy; // silence warning.
267 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
271 // Leave for llvm-gcc
272 CallInst::CallInst(Value *Func, Value* const *Args, unsigned NumArgs,
273 const std::string &Name, BasicBlock *InsertAtEnd)
274 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
275 ->getElementType())->getReturnType(),
276 Instruction::Call, 0, 0, InsertAtEnd) {
277 init(Func, Args, NumArgs);
280 CallInst::CallInst(Value *Func, Value* const *Args, unsigned NumArgs,
281 const std::string &Name, Instruction *InsertBefore)
282 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
283 ->getElementType())->getReturnType(),
284 Instruction::Call, 0, 0, InsertBefore) {
285 init(Func, Args, NumArgs);
289 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
290 const std::string &Name, Instruction *InsertBefore)
291 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
292 ->getElementType())->getReturnType(),
293 Instruction::Call, 0, 0, InsertBefore) {
294 init(Func, Actual1, Actual2);
298 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
299 const std::string &Name, BasicBlock *InsertAtEnd)
300 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
301 ->getElementType())->getReturnType(),
302 Instruction::Call, 0, 0, InsertAtEnd) {
303 init(Func, Actual1, Actual2);
307 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
308 Instruction *InsertBefore)
309 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
310 ->getElementType())->getReturnType(),
311 Instruction::Call, 0, 0, InsertBefore) {
316 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
317 BasicBlock *InsertAtEnd)
318 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
319 ->getElementType())->getReturnType(),
320 Instruction::Call, 0, 0, InsertAtEnd) {
324 CallInst::CallInst(Value *Func, const std::string &Name,
325 Instruction *InsertBefore)
326 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
327 ->getElementType())->getReturnType(),
328 Instruction::Call, 0, 0, InsertBefore) {
333 CallInst::CallInst(Value *Func, const std::string &Name,
334 BasicBlock *InsertAtEnd)
335 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
336 ->getElementType())->getReturnType(),
337 Instruction::Call, 0, 0, InsertAtEnd) {
342 CallInst::CallInst(const CallInst &CI)
343 : Instruction(CI.getType(), Instruction::Call, new Use[CI.getNumOperands()],
344 CI.getNumOperands()) {
346 SubclassData = CI.SubclassData;
347 Use *OL = OperandList;
348 Use *InOL = CI.OperandList;
349 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
350 OL[i].init(InOL[i], this);
353 void CallInst::setParamAttrs(ParamAttrsList *newAttrs) {
355 ParamAttrs->dropRef();
360 ParamAttrs = newAttrs;
363 //===----------------------------------------------------------------------===//
364 // InvokeInst Implementation
365 //===----------------------------------------------------------------------===//
367 InvokeInst::~InvokeInst() {
368 delete [] OperandList;
370 ParamAttrs->dropRef();
373 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
374 Value* const *Args, unsigned NumArgs) {
376 NumOperands = 3+NumArgs;
377 Use *OL = OperandList = new Use[3+NumArgs];
378 OL[0].init(Fn, this);
379 OL[1].init(IfNormal, this);
380 OL[2].init(IfException, this);
381 const FunctionType *FTy =
382 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
383 FTy = FTy; // silence warning.
385 assert((NumArgs == FTy->getNumParams()) ||
386 (FTy->isVarArg() && NumArgs > FTy->getNumParams()) &&
387 "Calling a function with bad signature");
389 for (unsigned i = 0, e = NumArgs; i != e; i++) {
390 assert((i >= FTy->getNumParams() ||
391 FTy->getParamType(i) == Args[i]->getType()) &&
392 "Invoking a function with a bad signature!");
394 OL[i+3].init(Args[i], this);
398 InvokeInst::InvokeInst(Value *Fn, BasicBlock *IfNormal,
399 BasicBlock *IfException,
400 Value* const *Args, unsigned NumArgs,
401 const std::string &Name, Instruction *InsertBefore)
402 : TerminatorInst(cast<FunctionType>(cast<PointerType>(Fn->getType())
403 ->getElementType())->getReturnType(),
404 Instruction::Invoke, 0, 0, InsertBefore) {
405 init(Fn, IfNormal, IfException, Args, NumArgs);
409 InvokeInst::InvokeInst(Value *Fn, BasicBlock *IfNormal,
410 BasicBlock *IfException,
411 Value* const *Args, unsigned NumArgs,
412 const std::string &Name, BasicBlock *InsertAtEnd)
413 : TerminatorInst(cast<FunctionType>(cast<PointerType>(Fn->getType())
414 ->getElementType())->getReturnType(),
415 Instruction::Invoke, 0, 0, InsertAtEnd) {
416 init(Fn, IfNormal, IfException, Args, NumArgs);
420 InvokeInst::InvokeInst(const InvokeInst &II)
421 : TerminatorInst(II.getType(), Instruction::Invoke,
422 new Use[II.getNumOperands()], II.getNumOperands()) {
424 SubclassData = II.SubclassData;
425 Use *OL = OperandList, *InOL = II.OperandList;
426 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
427 OL[i].init(InOL[i], this);
430 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
431 return getSuccessor(idx);
433 unsigned InvokeInst::getNumSuccessorsV() const {
434 return getNumSuccessors();
436 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
437 return setSuccessor(idx, B);
440 void InvokeInst::setParamAttrs(ParamAttrsList *newAttrs) {
442 ParamAttrs->dropRef();
447 ParamAttrs = newAttrs;
450 //===----------------------------------------------------------------------===//
451 // ReturnInst Implementation
452 //===----------------------------------------------------------------------===//
454 ReturnInst::ReturnInst(const ReturnInst &RI)
455 : TerminatorInst(Type::VoidTy, Instruction::Ret,
456 &RetVal, RI.getNumOperands()) {
457 if (RI.getNumOperands())
458 RetVal.init(RI.RetVal, this);
461 ReturnInst::ReturnInst(Value *retVal, Instruction *InsertBefore)
462 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertBefore) {
465 ReturnInst::ReturnInst(Value *retVal, BasicBlock *InsertAtEnd)
466 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertAtEnd) {
469 ReturnInst::ReturnInst(BasicBlock *InsertAtEnd)
470 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertAtEnd) {
475 void ReturnInst::init(Value *retVal) {
476 if (retVal && retVal->getType() != Type::VoidTy) {
477 assert(!isa<BasicBlock>(retVal) &&
478 "Cannot return basic block. Probably using the incorrect ctor");
480 RetVal.init(retVal, this);
484 unsigned ReturnInst::getNumSuccessorsV() const {
485 return getNumSuccessors();
488 // Out-of-line ReturnInst method, put here so the C++ compiler can choose to
489 // emit the vtable for the class in this translation unit.
490 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
491 assert(0 && "ReturnInst has no successors!");
494 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
495 assert(0 && "ReturnInst has no successors!");
501 //===----------------------------------------------------------------------===//
502 // UnwindInst Implementation
503 //===----------------------------------------------------------------------===//
505 UnwindInst::UnwindInst(Instruction *InsertBefore)
506 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertBefore) {
508 UnwindInst::UnwindInst(BasicBlock *InsertAtEnd)
509 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertAtEnd) {
513 unsigned UnwindInst::getNumSuccessorsV() const {
514 return getNumSuccessors();
517 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
518 assert(0 && "UnwindInst has no successors!");
521 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
522 assert(0 && "UnwindInst has no successors!");
527 //===----------------------------------------------------------------------===//
528 // UnreachableInst Implementation
529 //===----------------------------------------------------------------------===//
531 UnreachableInst::UnreachableInst(Instruction *InsertBefore)
532 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertBefore) {
534 UnreachableInst::UnreachableInst(BasicBlock *InsertAtEnd)
535 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertAtEnd) {
538 unsigned UnreachableInst::getNumSuccessorsV() const {
539 return getNumSuccessors();
542 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
543 assert(0 && "UnwindInst has no successors!");
546 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
547 assert(0 && "UnwindInst has no successors!");
552 //===----------------------------------------------------------------------===//
553 // BranchInst Implementation
554 //===----------------------------------------------------------------------===//
556 void BranchInst::AssertOK() {
558 assert(getCondition()->getType() == Type::Int1Ty &&
559 "May only branch on boolean predicates!");
562 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
563 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 1, InsertBefore) {
564 assert(IfTrue != 0 && "Branch destination may not be null!");
565 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
567 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
568 Instruction *InsertBefore)
569 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 3, InsertBefore) {
570 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
571 Ops[1].init(reinterpret_cast<Value*>(IfFalse), this);
572 Ops[2].init(Cond, this);
578 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
579 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 1, InsertAtEnd) {
580 assert(IfTrue != 0 && "Branch destination may not be null!");
581 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
584 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
585 BasicBlock *InsertAtEnd)
586 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 3, InsertAtEnd) {
587 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
588 Ops[1].init(reinterpret_cast<Value*>(IfFalse), this);
589 Ops[2].init(Cond, this);
596 BranchInst::BranchInst(const BranchInst &BI) :
597 TerminatorInst(Type::VoidTy, Instruction::Br, Ops, BI.getNumOperands()) {
598 OperandList[0].init(BI.getOperand(0), this);
599 if (BI.getNumOperands() != 1) {
600 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
601 OperandList[1].init(BI.getOperand(1), this);
602 OperandList[2].init(BI.getOperand(2), this);
606 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
607 return getSuccessor(idx);
609 unsigned BranchInst::getNumSuccessorsV() const {
610 return getNumSuccessors();
612 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
613 setSuccessor(idx, B);
617 //===----------------------------------------------------------------------===//
618 // AllocationInst Implementation
619 //===----------------------------------------------------------------------===//
621 static Value *getAISize(Value *Amt) {
623 Amt = ConstantInt::get(Type::Int32Ty, 1);
625 assert(!isa<BasicBlock>(Amt) &&
626 "Passed basic block into allocation size parameter! Ue other ctor");
627 assert(Amt->getType() == Type::Int32Ty &&
628 "Malloc/Allocation array size is not a 32-bit integer!");
633 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
634 unsigned Align, const std::string &Name,
635 Instruction *InsertBefore)
636 : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
637 InsertBefore), Alignment(Align) {
638 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
639 assert(Ty != Type::VoidTy && "Cannot allocate void!");
643 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
644 unsigned Align, const std::string &Name,
645 BasicBlock *InsertAtEnd)
646 : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
647 InsertAtEnd), Alignment(Align) {
648 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
649 assert(Ty != Type::VoidTy && "Cannot allocate void!");
653 // Out of line virtual method, so the vtable, etc has a home.
654 AllocationInst::~AllocationInst() {
657 bool AllocationInst::isArrayAllocation() const {
658 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
659 return CI->getZExtValue() != 1;
663 const Type *AllocationInst::getAllocatedType() const {
664 return getType()->getElementType();
667 AllocaInst::AllocaInst(const AllocaInst &AI)
668 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
669 Instruction::Alloca, AI.getAlignment()) {
672 MallocInst::MallocInst(const MallocInst &MI)
673 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
674 Instruction::Malloc, MI.getAlignment()) {
677 //===----------------------------------------------------------------------===//
678 // FreeInst Implementation
679 //===----------------------------------------------------------------------===//
681 void FreeInst::AssertOK() {
682 assert(isa<PointerType>(getOperand(0)->getType()) &&
683 "Can not free something of nonpointer type!");
686 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
687 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertBefore) {
691 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
692 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertAtEnd) {
697 //===----------------------------------------------------------------------===//
698 // LoadInst Implementation
699 //===----------------------------------------------------------------------===//
701 void LoadInst::AssertOK() {
702 assert(isa<PointerType>(getOperand(0)->getType()) &&
703 "Ptr must have pointer type.");
706 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
707 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
708 Load, Ptr, InsertBef) {
715 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
716 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
717 Load, Ptr, InsertAE) {
724 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
725 Instruction *InsertBef)
726 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
727 Load, Ptr, InsertBef) {
728 setVolatile(isVolatile);
734 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
735 unsigned Align, Instruction *InsertBef)
736 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
737 Load, Ptr, InsertBef) {
738 setVolatile(isVolatile);
744 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
745 unsigned Align, BasicBlock *InsertAE)
746 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
747 Load, Ptr, InsertAE) {
748 setVolatile(isVolatile);
754 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
755 BasicBlock *InsertAE)
756 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
757 Load, Ptr, InsertAE) {
758 setVolatile(isVolatile);
766 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
767 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
768 Load, Ptr, InsertBef) {
772 if (Name && Name[0]) setName(Name);
775 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
776 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
777 Load, Ptr, InsertAE) {
781 if (Name && Name[0]) setName(Name);
784 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
785 Instruction *InsertBef)
786 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
787 Load, Ptr, InsertBef) {
788 setVolatile(isVolatile);
791 if (Name && Name[0]) setName(Name);
794 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
795 BasicBlock *InsertAE)
796 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
797 Load, Ptr, InsertAE) {
798 setVolatile(isVolatile);
801 if (Name && Name[0]) setName(Name);
804 void LoadInst::setAlignment(unsigned Align) {
805 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
806 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
809 //===----------------------------------------------------------------------===//
810 // StoreInst Implementation
811 //===----------------------------------------------------------------------===//
813 void StoreInst::AssertOK() {
814 assert(isa<PointerType>(getOperand(1)->getType()) &&
815 "Ptr must have pointer type!");
816 assert(getOperand(0)->getType() ==
817 cast<PointerType>(getOperand(1)->getType())->getElementType()
818 && "Ptr must be a pointer to Val type!");
822 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
823 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
824 Ops[0].init(val, this);
825 Ops[1].init(addr, this);
831 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
832 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
833 Ops[0].init(val, this);
834 Ops[1].init(addr, this);
840 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
841 Instruction *InsertBefore)
842 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
843 Ops[0].init(val, this);
844 Ops[1].init(addr, this);
845 setVolatile(isVolatile);
850 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
851 unsigned Align, Instruction *InsertBefore)
852 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
853 Ops[0].init(val, this);
854 Ops[1].init(addr, this);
855 setVolatile(isVolatile);
860 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
861 unsigned Align, BasicBlock *InsertAtEnd)
862 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
863 Ops[0].init(val, this);
864 Ops[1].init(addr, this);
865 setVolatile(isVolatile);
870 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
871 BasicBlock *InsertAtEnd)
872 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
873 Ops[0].init(val, this);
874 Ops[1].init(addr, this);
875 setVolatile(isVolatile);
880 void StoreInst::setAlignment(unsigned Align) {
881 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
882 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
885 //===----------------------------------------------------------------------===//
886 // GetElementPtrInst Implementation
887 //===----------------------------------------------------------------------===//
889 // checkType - Simple wrapper function to give a better assertion failure
890 // message on bad indexes for a gep instruction.
892 static inline const Type *checkType(const Type *Ty) {
893 assert(Ty && "Invalid GetElementPtrInst indices for type!");
897 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx) {
898 NumOperands = 1+NumIdx;
899 Use *OL = OperandList = new Use[NumOperands];
900 OL[0].init(Ptr, this);
902 for (unsigned i = 0; i != NumIdx; ++i)
903 OL[i+1].init(Idx[i], this);
906 void GetElementPtrInst::init(Value *Ptr, Value *Idx0, Value *Idx1) {
908 Use *OL = OperandList = new Use[3];
909 OL[0].init(Ptr, this);
910 OL[1].init(Idx0, this);
911 OL[2].init(Idx1, this);
914 void GetElementPtrInst::init(Value *Ptr, Value *Idx) {
916 Use *OL = OperandList = new Use[2];
917 OL[0].init(Ptr, this);
918 OL[1].init(Idx, this);
922 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value* const *Idx,
924 const std::string &Name, Instruction *InBe)
925 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
926 Idx, NumIdx, true))),
927 GetElementPtr, 0, 0, InBe) {
928 init(Ptr, Idx, NumIdx);
932 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value* const *Idx,
934 const std::string &Name, BasicBlock *IAE)
935 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
936 Idx, NumIdx, true))),
937 GetElementPtr, 0, 0, IAE) {
938 init(Ptr, Idx, NumIdx);
942 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
943 const std::string &Name, Instruction *InBe)
944 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx))),
945 GetElementPtr, 0, 0, InBe) {
950 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
951 const std::string &Name, BasicBlock *IAE)
952 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx))),
953 GetElementPtr, 0, 0, IAE) {
958 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
959 const std::string &Name, Instruction *InBe)
960 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
962 GetElementPtr, 0, 0, InBe) {
963 init(Ptr, Idx0, Idx1);
967 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
968 const std::string &Name, BasicBlock *IAE)
969 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
971 GetElementPtr, 0, 0, IAE) {
972 init(Ptr, Idx0, Idx1);
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();
1000 unsigned CurIdx = 0;
1001 while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
1002 if (NumIdx == CurIdx) {
1003 if (AllowCompositeLeaf || CT->isFirstClassType()) return Ptr;
1004 return 0; // Can't load a whole structure or array!?!?
1007 Value *Index = Idxs[CurIdx++];
1008 if (isa<PointerType>(CT) && CurIdx != 1)
1009 return 0; // Can only index into pointer types at the first index!
1010 if (!CT->indexValid(Index)) return 0;
1011 Ptr = CT->getTypeAtIndex(Index);
1013 // If the new type forwards to another type, then it is in the middle
1014 // of being refined to another type (and hence, may have dropped all
1015 // references to what it was using before). So, use the new forwarded
1017 if (const Type * Ty = Ptr->getForwardedType()) {
1021 return CurIdx == NumIdx ? Ptr : 0;
1024 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1025 Value *Idx0, Value *Idx1,
1026 bool AllowCompositeLeaf) {
1027 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1028 if (!PTy) return 0; // Type isn't a pointer type!
1030 // Check the pointer index.
1031 if (!PTy->indexValid(Idx0)) return 0;
1033 const CompositeType *CT = dyn_cast<CompositeType>(PTy->getElementType());
1034 if (!CT || !CT->indexValid(Idx1)) return 0;
1036 const Type *ElTy = CT->getTypeAtIndex(Idx1);
1037 if (AllowCompositeLeaf || ElTy->isFirstClassType())
1042 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1043 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1044 if (!PTy) return 0; // Type isn't a pointer type!
1046 // Check the pointer index.
1047 if (!PTy->indexValid(Idx)) return 0;
1049 return PTy->getElementType();
1053 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1054 /// zeros. If so, the result pointer and the first operand have the same
1055 /// value, just potentially different types.
1056 bool GetElementPtrInst::hasAllZeroIndices() const {
1057 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1058 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1059 if (!CI->isZero()) return false;
1067 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1068 /// constant integers. If so, the result pointer and the first operand have
1069 /// a constant offset between them.
1070 bool GetElementPtrInst::hasAllConstantIndices() const {
1071 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1072 if (!isa<ConstantInt>(getOperand(i)))
1079 //===----------------------------------------------------------------------===//
1080 // ExtractElementInst Implementation
1081 //===----------------------------------------------------------------------===//
1083 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1084 const std::string &Name,
1085 Instruction *InsertBef)
1086 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1087 ExtractElement, Ops, 2, InsertBef) {
1088 assert(isValidOperands(Val, Index) &&
1089 "Invalid extractelement instruction operands!");
1090 Ops[0].init(Val, this);
1091 Ops[1].init(Index, this);
1095 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1096 const std::string &Name,
1097 Instruction *InsertBef)
1098 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1099 ExtractElement, Ops, 2, InsertBef) {
1100 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1101 assert(isValidOperands(Val, Index) &&
1102 "Invalid extractelement instruction operands!");
1103 Ops[0].init(Val, this);
1104 Ops[1].init(Index, this);
1109 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1110 const std::string &Name,
1111 BasicBlock *InsertAE)
1112 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1113 ExtractElement, Ops, 2, InsertAE) {
1114 assert(isValidOperands(Val, Index) &&
1115 "Invalid extractelement instruction operands!");
1117 Ops[0].init(Val, this);
1118 Ops[1].init(Index, this);
1122 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1123 const std::string &Name,
1124 BasicBlock *InsertAE)
1125 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1126 ExtractElement, Ops, 2, InsertAE) {
1127 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1128 assert(isValidOperands(Val, Index) &&
1129 "Invalid extractelement instruction operands!");
1131 Ops[0].init(Val, this);
1132 Ops[1].init(Index, this);
1137 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1138 if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty)
1144 //===----------------------------------------------------------------------===//
1145 // InsertElementInst Implementation
1146 //===----------------------------------------------------------------------===//
1148 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
1149 : Instruction(IE.getType(), InsertElement, Ops, 3) {
1150 Ops[0].init(IE.Ops[0], this);
1151 Ops[1].init(IE.Ops[1], this);
1152 Ops[2].init(IE.Ops[2], this);
1154 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1155 const std::string &Name,
1156 Instruction *InsertBef)
1157 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertBef) {
1158 assert(isValidOperands(Vec, Elt, Index) &&
1159 "Invalid insertelement instruction operands!");
1160 Ops[0].init(Vec, this);
1161 Ops[1].init(Elt, this);
1162 Ops[2].init(Index, this);
1166 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1167 const std::string &Name,
1168 Instruction *InsertBef)
1169 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertBef) {
1170 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1171 assert(isValidOperands(Vec, Elt, Index) &&
1172 "Invalid insertelement instruction operands!");
1173 Ops[0].init(Vec, this);
1174 Ops[1].init(Elt, this);
1175 Ops[2].init(Index, this);
1180 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1181 const std::string &Name,
1182 BasicBlock *InsertAE)
1183 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertAE) {
1184 assert(isValidOperands(Vec, Elt, Index) &&
1185 "Invalid insertelement instruction operands!");
1187 Ops[0].init(Vec, this);
1188 Ops[1].init(Elt, this);
1189 Ops[2].init(Index, this);
1193 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1194 const std::string &Name,
1195 BasicBlock *InsertAE)
1196 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertAE) {
1197 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1198 assert(isValidOperands(Vec, Elt, Index) &&
1199 "Invalid insertelement instruction operands!");
1201 Ops[0].init(Vec, this);
1202 Ops[1].init(Elt, this);
1203 Ops[2].init(Index, this);
1207 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1208 const Value *Index) {
1209 if (!isa<VectorType>(Vec->getType()))
1210 return false; // First operand of insertelement must be vector type.
1212 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1213 return false;// Second operand of insertelement must be vector element type.
1215 if (Index->getType() != Type::Int32Ty)
1216 return false; // Third operand of insertelement must be uint.
1221 //===----------------------------------------------------------------------===//
1222 // ShuffleVectorInst Implementation
1223 //===----------------------------------------------------------------------===//
1225 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
1226 : Instruction(SV.getType(), ShuffleVector, Ops, 3) {
1227 Ops[0].init(SV.Ops[0], this);
1228 Ops[1].init(SV.Ops[1], this);
1229 Ops[2].init(SV.Ops[2], this);
1232 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1233 const std::string &Name,
1234 Instruction *InsertBefore)
1235 : Instruction(V1->getType(), ShuffleVector, Ops, 3, InsertBefore) {
1236 assert(isValidOperands(V1, V2, Mask) &&
1237 "Invalid shuffle vector instruction operands!");
1238 Ops[0].init(V1, this);
1239 Ops[1].init(V2, this);
1240 Ops[2].init(Mask, this);
1244 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1245 const std::string &Name,
1246 BasicBlock *InsertAtEnd)
1247 : Instruction(V1->getType(), ShuffleVector, Ops, 3, InsertAtEnd) {
1248 assert(isValidOperands(V1, V2, Mask) &&
1249 "Invalid shuffle vector instruction operands!");
1251 Ops[0].init(V1, this);
1252 Ops[1].init(V2, this);
1253 Ops[2].init(Mask, this);
1257 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1258 const Value *Mask) {
1259 if (!isa<VectorType>(V1->getType())) return false;
1260 if (V1->getType() != V2->getType()) return false;
1261 if (!isa<VectorType>(Mask->getType()) ||
1262 cast<VectorType>(Mask->getType())->getElementType() != Type::Int32Ty ||
1263 cast<VectorType>(Mask->getType())->getNumElements() !=
1264 cast<VectorType>(V1->getType())->getNumElements())
1270 //===----------------------------------------------------------------------===//
1271 // BinaryOperator Class
1272 //===----------------------------------------------------------------------===//
1274 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1275 const Type *Ty, const std::string &Name,
1276 Instruction *InsertBefore)
1277 : Instruction(Ty, iType, Ops, 2, InsertBefore) {
1278 Ops[0].init(S1, this);
1279 Ops[1].init(S2, this);
1284 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1285 const Type *Ty, const std::string &Name,
1286 BasicBlock *InsertAtEnd)
1287 : Instruction(Ty, iType, Ops, 2, InsertAtEnd) {
1288 Ops[0].init(S1, this);
1289 Ops[1].init(S2, this);
1295 void BinaryOperator::init(BinaryOps iType) {
1296 Value *LHS = getOperand(0), *RHS = getOperand(1);
1297 LHS = LHS; RHS = RHS; // Silence warnings.
1298 assert(LHS->getType() == RHS->getType() &&
1299 "Binary operator operand types must match!");
1304 assert(getType() == LHS->getType() &&
1305 "Arithmetic operation should return same type as operands!");
1306 assert((getType()->isInteger() || getType()->isFloatingPoint() ||
1307 isa<VectorType>(getType())) &&
1308 "Tried to create an arithmetic operation on a non-arithmetic type!");
1312 assert(getType() == LHS->getType() &&
1313 "Arithmetic operation should return same type as operands!");
1314 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1315 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1316 "Incorrect operand type (not integer) for S/UDIV");
1319 assert(getType() == LHS->getType() &&
1320 "Arithmetic operation should return same type as operands!");
1321 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1322 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1323 && "Incorrect operand type (not floating point) for FDIV");
1327 assert(getType() == LHS->getType() &&
1328 "Arithmetic operation should return same type as operands!");
1329 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1330 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1331 "Incorrect operand type (not integer) for S/UREM");
1334 assert(getType() == LHS->getType() &&
1335 "Arithmetic operation should return same type as operands!");
1336 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1337 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1338 && "Incorrect operand type (not floating point) for FREM");
1343 assert(getType() == LHS->getType() &&
1344 "Shift operation should return same type as operands!");
1345 assert(getType()->isInteger() &&
1346 "Shift operation requires integer operands");
1350 assert(getType() == LHS->getType() &&
1351 "Logical operation should return same type as operands!");
1352 assert((getType()->isInteger() ||
1353 (isa<VectorType>(getType()) &&
1354 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1355 "Tried to create a logical operation on a non-integral type!");
1363 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1364 const std::string &Name,
1365 Instruction *InsertBefore) {
1366 assert(S1->getType() == S2->getType() &&
1367 "Cannot create binary operator with two operands of differing type!");
1368 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1371 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1372 const std::string &Name,
1373 BasicBlock *InsertAtEnd) {
1374 BinaryOperator *Res = create(Op, S1, S2, Name);
1375 InsertAtEnd->getInstList().push_back(Res);
1379 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1380 Instruction *InsertBefore) {
1381 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1382 return new BinaryOperator(Instruction::Sub,
1384 Op->getType(), Name, InsertBefore);
1387 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1388 BasicBlock *InsertAtEnd) {
1389 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1390 return new BinaryOperator(Instruction::Sub,
1392 Op->getType(), Name, InsertAtEnd);
1395 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1396 Instruction *InsertBefore) {
1398 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1399 C = ConstantInt::getAllOnesValue(PTy->getElementType());
1400 C = ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), C));
1402 C = ConstantInt::getAllOnesValue(Op->getType());
1405 return new BinaryOperator(Instruction::Xor, Op, C,
1406 Op->getType(), Name, InsertBefore);
1409 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1410 BasicBlock *InsertAtEnd) {
1412 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1413 // Create a vector of all ones values.
1414 Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType());
1416 ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1418 AllOnes = ConstantInt::getAllOnesValue(Op->getType());
1421 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1422 Op->getType(), Name, InsertAtEnd);
1426 // isConstantAllOnes - Helper function for several functions below
1427 static inline bool isConstantAllOnes(const Value *V) {
1428 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1429 return CI->isAllOnesValue();
1430 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1431 return CV->isAllOnesValue();
1435 bool BinaryOperator::isNeg(const Value *V) {
1436 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1437 if (Bop->getOpcode() == Instruction::Sub)
1438 return Bop->getOperand(0) ==
1439 ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1443 bool BinaryOperator::isNot(const Value *V) {
1444 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1445 return (Bop->getOpcode() == Instruction::Xor &&
1446 (isConstantAllOnes(Bop->getOperand(1)) ||
1447 isConstantAllOnes(Bop->getOperand(0))));
1451 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1452 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1453 return cast<BinaryOperator>(BinOp)->getOperand(1);
1456 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1457 return getNegArgument(const_cast<Value*>(BinOp));
1460 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1461 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1462 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1463 Value *Op0 = BO->getOperand(0);
1464 Value *Op1 = BO->getOperand(1);
1465 if (isConstantAllOnes(Op0)) return Op1;
1467 assert(isConstantAllOnes(Op1));
1471 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1472 return getNotArgument(const_cast<Value*>(BinOp));
1476 // swapOperands - Exchange the two operands to this instruction. This
1477 // instruction is safe to use on any binary instruction and does not
1478 // modify the semantics of the instruction. If the instruction is
1479 // order dependent (SetLT f.e.) the opcode is changed.
1481 bool BinaryOperator::swapOperands() {
1482 if (!isCommutative())
1483 return true; // Can't commute operands
1484 std::swap(Ops[0], Ops[1]);
1488 //===----------------------------------------------------------------------===//
1490 //===----------------------------------------------------------------------===//
1492 // Just determine if this cast only deals with integral->integral conversion.
1493 bool CastInst::isIntegerCast() const {
1494 switch (getOpcode()) {
1495 default: return false;
1496 case Instruction::ZExt:
1497 case Instruction::SExt:
1498 case Instruction::Trunc:
1500 case Instruction::BitCast:
1501 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1505 bool CastInst::isLosslessCast() const {
1506 // Only BitCast can be lossless, exit fast if we're not BitCast
1507 if (getOpcode() != Instruction::BitCast)
1510 // Identity cast is always lossless
1511 const Type* SrcTy = getOperand(0)->getType();
1512 const Type* DstTy = getType();
1516 // Pointer to pointer is always lossless.
1517 if (isa<PointerType>(SrcTy))
1518 return isa<PointerType>(DstTy);
1519 return false; // Other types have no identity values
1522 /// This function determines if the CastInst does not require any bits to be
1523 /// changed in order to effect the cast. Essentially, it identifies cases where
1524 /// no code gen is necessary for the cast, hence the name no-op cast. For
1525 /// example, the following are all no-op casts:
1526 /// # bitcast uint %X, int
1527 /// # bitcast uint* %x, sbyte*
1528 /// # bitcast vector< 2 x int > %x, vector< 4 x short>
1529 /// # ptrtoint uint* %x, uint ; on 32-bit plaforms only
1530 /// @brief Determine if a cast is a no-op.
1531 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1532 switch (getOpcode()) {
1534 assert(!"Invalid CastOp");
1535 case Instruction::Trunc:
1536 case Instruction::ZExt:
1537 case Instruction::SExt:
1538 case Instruction::FPTrunc:
1539 case Instruction::FPExt:
1540 case Instruction::UIToFP:
1541 case Instruction::SIToFP:
1542 case Instruction::FPToUI:
1543 case Instruction::FPToSI:
1544 return false; // These always modify bits
1545 case Instruction::BitCast:
1546 return true; // BitCast never modifies bits.
1547 case Instruction::PtrToInt:
1548 return IntPtrTy->getPrimitiveSizeInBits() ==
1549 getType()->getPrimitiveSizeInBits();
1550 case Instruction::IntToPtr:
1551 return IntPtrTy->getPrimitiveSizeInBits() ==
1552 getOperand(0)->getType()->getPrimitiveSizeInBits();
1556 /// This function determines if a pair of casts can be eliminated and what
1557 /// opcode should be used in the elimination. This assumes that there are two
1558 /// instructions like this:
1559 /// * %F = firstOpcode SrcTy %x to MidTy
1560 /// * %S = secondOpcode MidTy %F to DstTy
1561 /// The function returns a resultOpcode so these two casts can be replaced with:
1562 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1563 /// If no such cast is permited, the function returns 0.
1564 unsigned CastInst::isEliminableCastPair(
1565 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1566 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1568 // Define the 144 possibilities for these two cast instructions. The values
1569 // in this matrix determine what to do in a given situation and select the
1570 // case in the switch below. The rows correspond to firstOp, the columns
1571 // correspond to secondOp. In looking at the table below, keep in mind
1572 // the following cast properties:
1574 // Size Compare Source Destination
1575 // Operator Src ? Size Type Sign Type Sign
1576 // -------- ------------ ------------------- ---------------------
1577 // TRUNC > Integer Any Integral Any
1578 // ZEXT < Integral Unsigned Integer Any
1579 // SEXT < Integral Signed Integer Any
1580 // FPTOUI n/a FloatPt n/a Integral Unsigned
1581 // FPTOSI n/a FloatPt n/a Integral Signed
1582 // UITOFP n/a Integral Unsigned FloatPt n/a
1583 // SITOFP n/a Integral Signed FloatPt n/a
1584 // FPTRUNC > FloatPt n/a FloatPt n/a
1585 // FPEXT < FloatPt n/a FloatPt n/a
1586 // PTRTOINT n/a Pointer n/a Integral Unsigned
1587 // INTTOPTR n/a Integral Unsigned Pointer n/a
1588 // BITCONVERT = FirstClass n/a FirstClass n/a
1590 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1591 // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
1592 // into "fptoui double to ulong", but this loses information about the range
1593 // of the produced value (we no longer know the top-part is all zeros).
1594 // Further this conversion is often much more expensive for typical hardware,
1595 // and causes issues when building libgcc. We disallow fptosi+sext for the
1597 const unsigned numCastOps =
1598 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1599 static const uint8_t CastResults[numCastOps][numCastOps] = {
1600 // T F F U S F F P I B -+
1601 // R Z S P P I I T P 2 N T |
1602 // U E E 2 2 2 2 R E I T C +- secondOp
1603 // N X X U S F F N X N 2 V |
1604 // C T T I I P P C T T P T -+
1605 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1606 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1607 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1608 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1609 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1610 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1611 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1612 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1613 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1614 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1615 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1616 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1619 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1620 [secondOp-Instruction::CastOpsBegin];
1623 // categorically disallowed
1626 // allowed, use first cast's opcode
1629 // allowed, use second cast's opcode
1632 // no-op cast in second op implies firstOp as long as the DestTy
1634 if (DstTy->isInteger())
1638 // no-op cast in second op implies firstOp as long as the DestTy
1639 // is floating point
1640 if (DstTy->isFloatingPoint())
1644 // no-op cast in first op implies secondOp as long as the SrcTy
1646 if (SrcTy->isInteger())
1650 // no-op cast in first op implies secondOp as long as the SrcTy
1651 // is a floating point
1652 if (SrcTy->isFloatingPoint())
1656 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1657 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1658 unsigned MidSize = MidTy->getPrimitiveSizeInBits();
1659 if (MidSize >= PtrSize)
1660 return Instruction::BitCast;
1664 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1665 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1666 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1667 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1668 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1669 if (SrcSize == DstSize)
1670 return Instruction::BitCast;
1671 else if (SrcSize < DstSize)
1675 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1676 return Instruction::ZExt;
1678 // fpext followed by ftrunc is allowed if the bit size returned to is
1679 // the same as the original, in which case its just a bitcast
1681 return Instruction::BitCast;
1682 return 0; // If the types are not the same we can't eliminate it.
1684 // bitcast followed by ptrtoint is allowed as long as the bitcast
1685 // is a pointer to pointer cast.
1686 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1690 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1691 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1695 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1696 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1697 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1698 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1699 if (SrcSize <= PtrSize && SrcSize == DstSize)
1700 return Instruction::BitCast;
1704 // cast combination can't happen (error in input). This is for all cases
1705 // where the MidTy is not the same for the two cast instructions.
1706 assert(!"Invalid Cast Combination");
1709 assert(!"Error in CastResults table!!!");
1715 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1716 const std::string &Name, Instruction *InsertBefore) {
1717 // Construct and return the appropriate CastInst subclass
1719 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1720 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1721 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1722 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1723 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1724 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1725 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1726 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1727 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1728 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1729 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1730 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1732 assert(!"Invalid opcode provided");
1737 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1738 const std::string &Name, BasicBlock *InsertAtEnd) {
1739 // Construct and return the appropriate CastInst subclass
1741 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1742 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1743 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1744 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1745 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1746 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1747 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1748 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1749 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1750 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1751 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1752 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1754 assert(!"Invalid opcode provided");
1759 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1760 const std::string &Name,
1761 Instruction *InsertBefore) {
1762 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1763 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1764 return create(Instruction::ZExt, S, Ty, Name, InsertBefore);
1767 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1768 const std::string &Name,
1769 BasicBlock *InsertAtEnd) {
1770 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1771 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1772 return create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
1775 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1776 const std::string &Name,
1777 Instruction *InsertBefore) {
1778 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1779 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1780 return create(Instruction::SExt, S, Ty, Name, InsertBefore);
1783 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1784 const std::string &Name,
1785 BasicBlock *InsertAtEnd) {
1786 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1787 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1788 return create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
1791 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1792 const std::string &Name,
1793 Instruction *InsertBefore) {
1794 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1795 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1796 return create(Instruction::Trunc, S, Ty, Name, InsertBefore);
1799 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1800 const std::string &Name,
1801 BasicBlock *InsertAtEnd) {
1802 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1803 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1804 return create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
1807 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1808 const std::string &Name,
1809 BasicBlock *InsertAtEnd) {
1810 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1811 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1814 if (Ty->isInteger())
1815 return create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
1816 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1819 /// @brief Create a BitCast or a PtrToInt cast instruction
1820 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1821 const std::string &Name,
1822 Instruction *InsertBefore) {
1823 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1824 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1827 if (Ty->isInteger())
1828 return create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
1829 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1832 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1833 bool isSigned, const std::string &Name,
1834 Instruction *InsertBefore) {
1835 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1836 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1837 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1838 Instruction::CastOps opcode =
1839 (SrcBits == DstBits ? Instruction::BitCast :
1840 (SrcBits > DstBits ? Instruction::Trunc :
1841 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1842 return create(opcode, C, Ty, Name, InsertBefore);
1845 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1846 bool isSigned, const std::string &Name,
1847 BasicBlock *InsertAtEnd) {
1848 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1849 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1850 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1851 Instruction::CastOps opcode =
1852 (SrcBits == DstBits ? Instruction::BitCast :
1853 (SrcBits > DstBits ? Instruction::Trunc :
1854 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1855 return create(opcode, C, Ty, Name, InsertAtEnd);
1858 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1859 const std::string &Name,
1860 Instruction *InsertBefore) {
1861 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1863 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1864 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1865 Instruction::CastOps opcode =
1866 (SrcBits == DstBits ? Instruction::BitCast :
1867 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1868 return create(opcode, C, Ty, Name, InsertBefore);
1871 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1872 const std::string &Name,
1873 BasicBlock *InsertAtEnd) {
1874 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1876 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1877 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1878 Instruction::CastOps opcode =
1879 (SrcBits == DstBits ? Instruction::BitCast :
1880 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1881 return create(opcode, C, Ty, Name, InsertAtEnd);
1884 // Provide a way to get a "cast" where the cast opcode is inferred from the
1885 // types and size of the operand. This, basically, is a parallel of the
1886 // logic in the castIsValid function below. This axiom should hold:
1887 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
1888 // should not assert in castIsValid. In other words, this produces a "correct"
1889 // casting opcode for the arguments passed to it.
1890 Instruction::CastOps
1891 CastInst::getCastOpcode(
1892 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
1893 // Get the bit sizes, we'll need these
1894 const Type *SrcTy = Src->getType();
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
1901 if (DestBits < SrcBits)
1902 return Trunc; // int -> smaller int
1903 else if (DestBits > SrcBits) { // its an extension
1905 return SExt; // signed -> SEXT
1907 return ZExt; // unsigned -> ZEXT
1909 return BitCast; // Same size, No-op cast
1911 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1913 return FPToSI; // FP -> sint
1915 return FPToUI; // FP -> uint
1916 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1917 assert(DestBits == PTy->getBitWidth() &&
1918 "Casting vector to integer of different width");
1919 return BitCast; // Same size, no-op cast
1921 assert(isa<PointerType>(SrcTy) &&
1922 "Casting from a value that is not first-class type");
1923 return PtrToInt; // ptr -> int
1925 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
1926 if (SrcTy->isInteger()) { // Casting from integral
1928 return SIToFP; // sint -> FP
1930 return UIToFP; // uint -> FP
1931 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1932 if (DestBits < SrcBits) {
1933 return FPTrunc; // FP -> smaller FP
1934 } else if (DestBits > SrcBits) {
1935 return FPExt; // FP -> larger FP
1937 return BitCast; // same size, no-op cast
1939 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1940 assert(DestBits == PTy->getBitWidth() &&
1941 "Casting vector to floating point of different width");
1942 return BitCast; // same size, no-op cast
1944 assert(0 && "Casting pointer or non-first class to float");
1946 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
1947 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
1948 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
1949 "Casting vector to vector of different widths");
1950 return BitCast; // vector -> vector
1951 } else if (DestPTy->getBitWidth() == SrcBits) {
1952 return BitCast; // float/int -> vector
1954 assert(!"Illegal cast to vector (wrong type or size)");
1956 } else if (isa<PointerType>(DestTy)) {
1957 if (isa<PointerType>(SrcTy)) {
1958 return BitCast; // ptr -> ptr
1959 } else if (SrcTy->isInteger()) {
1960 return IntToPtr; // int -> ptr
1962 assert(!"Casting pointer to other than pointer or int");
1965 assert(!"Casting to type that is not first-class");
1968 // If we fall through to here we probably hit an assertion cast above
1969 // and assertions are not turned on. Anything we return is an error, so
1970 // BitCast is as good a choice as any.
1974 //===----------------------------------------------------------------------===//
1975 // CastInst SubClass Constructors
1976 //===----------------------------------------------------------------------===//
1978 /// Check that the construction parameters for a CastInst are correct. This
1979 /// could be broken out into the separate constructors but it is useful to have
1980 /// it in one place and to eliminate the redundant code for getting the sizes
1981 /// of the types involved.
1983 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
1985 // Check for type sanity on the arguments
1986 const Type *SrcTy = S->getType();
1987 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
1990 // Get the size of the types in bits, we'll need this later
1991 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1992 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1994 // Switch on the opcode provided
1996 default: return false; // This is an input error
1997 case Instruction::Trunc:
1998 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize > DstBitSize;
1999 case Instruction::ZExt:
2000 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2001 case Instruction::SExt:
2002 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2003 case Instruction::FPTrunc:
2004 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2005 SrcBitSize > DstBitSize;
2006 case Instruction::FPExt:
2007 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2008 SrcBitSize < DstBitSize;
2009 case Instruction::UIToFP:
2010 return SrcTy->isInteger() && DstTy->isFloatingPoint();
2011 case Instruction::SIToFP:
2012 return SrcTy->isInteger() && DstTy->isFloatingPoint();
2013 case Instruction::FPToUI:
2014 return SrcTy->isFloatingPoint() && DstTy->isInteger();
2015 case Instruction::FPToSI:
2016 return SrcTy->isFloatingPoint() && DstTy->isInteger();
2017 case Instruction::PtrToInt:
2018 return isa<PointerType>(SrcTy) && DstTy->isInteger();
2019 case Instruction::IntToPtr:
2020 return SrcTy->isInteger() && isa<PointerType>(DstTy);
2021 case Instruction::BitCast:
2022 // BitCast implies a no-op cast of type only. No bits change.
2023 // However, you can't cast pointers to anything but pointers.
2024 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2027 // Now we know we're not dealing with a pointer/non-poiner mismatch. In all
2028 // these cases, the cast is okay if the source and destination bit widths
2030 return SrcBitSize == DstBitSize;
2034 TruncInst::TruncInst(
2035 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2036 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2037 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2040 TruncInst::TruncInst(
2041 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2042 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2043 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2047 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2048 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2049 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2053 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2054 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2055 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2058 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2059 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2060 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2064 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2065 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2066 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2069 FPTruncInst::FPTruncInst(
2070 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2071 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2072 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2075 FPTruncInst::FPTruncInst(
2076 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2077 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2078 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2081 FPExtInst::FPExtInst(
2082 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2083 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2084 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2087 FPExtInst::FPExtInst(
2088 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2089 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2090 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2093 UIToFPInst::UIToFPInst(
2094 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2095 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2096 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2099 UIToFPInst::UIToFPInst(
2100 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2101 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2102 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2105 SIToFPInst::SIToFPInst(
2106 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2107 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2108 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2111 SIToFPInst::SIToFPInst(
2112 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2113 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2114 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2117 FPToUIInst::FPToUIInst(
2118 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2119 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2120 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2123 FPToUIInst::FPToUIInst(
2124 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2125 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2126 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2129 FPToSIInst::FPToSIInst(
2130 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2131 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2132 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2135 FPToSIInst::FPToSIInst(
2136 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2137 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2138 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2141 PtrToIntInst::PtrToIntInst(
2142 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2143 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2144 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2147 PtrToIntInst::PtrToIntInst(
2148 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2149 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2150 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2153 IntToPtrInst::IntToPtrInst(
2154 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2155 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2156 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2159 IntToPtrInst::IntToPtrInst(
2160 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2161 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2162 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2165 BitCastInst::BitCastInst(
2166 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2167 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2168 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2171 BitCastInst::BitCastInst(
2172 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2173 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2174 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2177 //===----------------------------------------------------------------------===//
2179 //===----------------------------------------------------------------------===//
2181 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2182 const std::string &Name, Instruction *InsertBefore)
2183 : Instruction(Type::Int1Ty, op, Ops, 2, InsertBefore) {
2184 Ops[0].init(LHS, this);
2185 Ops[1].init(RHS, this);
2186 SubclassData = predicate;
2188 if (op == Instruction::ICmp) {
2189 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2190 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2191 "Invalid ICmp predicate value");
2192 const Type* Op0Ty = getOperand(0)->getType();
2193 const Type* Op1Ty = getOperand(1)->getType();
2194 assert(Op0Ty == Op1Ty &&
2195 "Both operands to ICmp instruction are not of the same type!");
2196 // Check that the operands are the right type
2197 assert((Op0Ty->isInteger() || isa<PointerType>(Op0Ty)) &&
2198 "Invalid operand types for ICmp instruction");
2201 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2202 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2203 "Invalid FCmp predicate value");
2204 const Type* Op0Ty = getOperand(0)->getType();
2205 const Type* Op1Ty = getOperand(1)->getType();
2206 assert(Op0Ty == Op1Ty &&
2207 "Both operands to FCmp instruction are not of the same type!");
2208 // Check that the operands are the right type
2209 assert(Op0Ty->isFloatingPoint() &&
2210 "Invalid operand types for FCmp instruction");
2213 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2214 const std::string &Name, BasicBlock *InsertAtEnd)
2215 : Instruction(Type::Int1Ty, op, Ops, 2, InsertAtEnd) {
2216 Ops[0].init(LHS, this);
2217 Ops[1].init(RHS, this);
2218 SubclassData = predicate;
2220 if (op == Instruction::ICmp) {
2221 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2222 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2223 "Invalid ICmp predicate value");
2225 const Type* Op0Ty = getOperand(0)->getType();
2226 const Type* Op1Ty = getOperand(1)->getType();
2227 assert(Op0Ty == Op1Ty &&
2228 "Both operands to ICmp instruction are not of the same type!");
2229 // Check that the operands are the right type
2230 assert(Op0Ty->isInteger() || isa<PointerType>(Op0Ty) &&
2231 "Invalid operand types for ICmp instruction");
2234 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2235 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2236 "Invalid FCmp predicate value");
2237 const Type* Op0Ty = getOperand(0)->getType();
2238 const Type* Op1Ty = getOperand(1)->getType();
2239 assert(Op0Ty == Op1Ty &&
2240 "Both operands to FCmp instruction are not of the same type!");
2241 // Check that the operands are the right type
2242 assert(Op0Ty->isFloatingPoint() &&
2243 "Invalid operand types for FCmp instruction");
2247 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2248 const std::string &Name, Instruction *InsertBefore) {
2249 if (Op == Instruction::ICmp) {
2250 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2253 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2258 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2259 const std::string &Name, BasicBlock *InsertAtEnd) {
2260 if (Op == Instruction::ICmp) {
2261 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2264 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2268 void CmpInst::swapOperands() {
2269 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2272 cast<FCmpInst>(this)->swapOperands();
2275 bool CmpInst::isCommutative() {
2276 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2277 return IC->isCommutative();
2278 return cast<FCmpInst>(this)->isCommutative();
2281 bool CmpInst::isEquality() {
2282 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2283 return IC->isEquality();
2284 return cast<FCmpInst>(this)->isEquality();
2288 ICmpInst::Predicate ICmpInst::getInversePredicate(Predicate pred) {
2291 assert(!"Unknown icmp predicate!");
2292 case ICMP_EQ: return ICMP_NE;
2293 case ICMP_NE: return ICMP_EQ;
2294 case ICMP_UGT: return ICMP_ULE;
2295 case ICMP_ULT: return ICMP_UGE;
2296 case ICMP_UGE: return ICMP_ULT;
2297 case ICMP_ULE: return ICMP_UGT;
2298 case ICMP_SGT: return ICMP_SLE;
2299 case ICMP_SLT: return ICMP_SGE;
2300 case ICMP_SGE: return ICMP_SLT;
2301 case ICMP_SLE: return ICMP_SGT;
2305 ICmpInst::Predicate ICmpInst::getSwappedPredicate(Predicate pred) {
2307 default: assert(! "Unknown icmp predicate!");
2308 case ICMP_EQ: case ICMP_NE:
2310 case ICMP_SGT: return ICMP_SLT;
2311 case ICMP_SLT: return ICMP_SGT;
2312 case ICMP_SGE: return ICMP_SLE;
2313 case ICMP_SLE: return ICMP_SGE;
2314 case ICMP_UGT: return ICMP_ULT;
2315 case ICMP_ULT: return ICMP_UGT;
2316 case ICMP_UGE: return ICMP_ULE;
2317 case ICMP_ULE: return ICMP_UGE;
2321 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2323 default: assert(! "Unknown icmp predicate!");
2324 case ICMP_EQ: case ICMP_NE:
2325 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2327 case ICMP_UGT: return ICMP_SGT;
2328 case ICMP_ULT: return ICMP_SLT;
2329 case ICMP_UGE: return ICMP_SGE;
2330 case ICMP_ULE: return ICMP_SLE;
2334 bool ICmpInst::isSignedPredicate(Predicate pred) {
2336 default: assert(! "Unknown icmp predicate!");
2337 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2339 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2340 case ICMP_UGE: case ICMP_ULE:
2345 /// Initialize a set of values that all satisfy the condition with C.
2348 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2351 uint32_t BitWidth = C.getBitWidth();
2353 default: assert(0 && "Invalid ICmp opcode to ConstantRange ctor!");
2354 case ICmpInst::ICMP_EQ: Upper++; break;
2355 case ICmpInst::ICMP_NE: Lower++; break;
2356 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2357 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2358 case ICmpInst::ICMP_UGT:
2359 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2361 case ICmpInst::ICMP_SGT:
2362 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2364 case ICmpInst::ICMP_ULE:
2365 Lower = APInt::getMinValue(BitWidth); Upper++;
2367 case ICmpInst::ICMP_SLE:
2368 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2370 case ICmpInst::ICMP_UGE:
2371 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2373 case ICmpInst::ICMP_SGE:
2374 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2377 return ConstantRange(Lower, Upper);
2380 FCmpInst::Predicate FCmpInst::getInversePredicate(Predicate pred) {
2383 assert(!"Unknown icmp predicate!");
2384 case FCMP_OEQ: return FCMP_UNE;
2385 case FCMP_ONE: return FCMP_UEQ;
2386 case FCMP_OGT: return FCMP_ULE;
2387 case FCMP_OLT: return FCMP_UGE;
2388 case FCMP_OGE: return FCMP_ULT;
2389 case FCMP_OLE: return FCMP_UGT;
2390 case FCMP_UEQ: return FCMP_ONE;
2391 case FCMP_UNE: return FCMP_OEQ;
2392 case FCMP_UGT: return FCMP_OLE;
2393 case FCMP_ULT: return FCMP_OGE;
2394 case FCMP_UGE: return FCMP_OLT;
2395 case FCMP_ULE: return FCMP_OGT;
2396 case FCMP_ORD: return FCMP_UNO;
2397 case FCMP_UNO: return FCMP_ORD;
2398 case FCMP_TRUE: return FCMP_FALSE;
2399 case FCMP_FALSE: return FCMP_TRUE;
2403 FCmpInst::Predicate FCmpInst::getSwappedPredicate(Predicate pred) {
2405 default: assert(!"Unknown fcmp predicate!");
2406 case FCMP_FALSE: case FCMP_TRUE:
2407 case FCMP_OEQ: case FCMP_ONE:
2408 case FCMP_UEQ: case FCMP_UNE:
2409 case FCMP_ORD: case FCMP_UNO:
2411 case FCMP_OGT: return FCMP_OLT;
2412 case FCMP_OLT: return FCMP_OGT;
2413 case FCMP_OGE: return FCMP_OLE;
2414 case FCMP_OLE: return FCMP_OGE;
2415 case FCMP_UGT: return FCMP_ULT;
2416 case FCMP_ULT: return FCMP_UGT;
2417 case FCMP_UGE: return FCMP_ULE;
2418 case FCMP_ULE: return FCMP_UGE;
2422 bool CmpInst::isUnsigned(unsigned short predicate) {
2423 switch (predicate) {
2424 default: return false;
2425 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2426 case ICmpInst::ICMP_UGE: return true;
2430 bool CmpInst::isSigned(unsigned short predicate){
2431 switch (predicate) {
2432 default: return false;
2433 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2434 case ICmpInst::ICMP_SGE: return true;
2438 bool CmpInst::isOrdered(unsigned short predicate) {
2439 switch (predicate) {
2440 default: return false;
2441 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2442 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2443 case FCmpInst::FCMP_ORD: return true;
2447 bool CmpInst::isUnordered(unsigned short predicate) {
2448 switch (predicate) {
2449 default: return false;
2450 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2451 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2452 case FCmpInst::FCMP_UNO: return true;
2456 //===----------------------------------------------------------------------===//
2457 // SwitchInst Implementation
2458 //===----------------------------------------------------------------------===//
2460 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2461 assert(Value && Default);
2462 ReservedSpace = 2+NumCases*2;
2464 OperandList = new Use[ReservedSpace];
2466 OperandList[0].init(Value, this);
2467 OperandList[1].init(Default, this);
2470 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2471 /// switch on and a default destination. The number of additional cases can
2472 /// be specified here to make memory allocation more efficient. This
2473 /// constructor can also autoinsert before another instruction.
2474 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2475 Instruction *InsertBefore)
2476 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) {
2477 init(Value, Default, NumCases);
2480 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2481 /// switch on and a default destination. The number of additional cases can
2482 /// be specified here to make memory allocation more efficient. This
2483 /// constructor also autoinserts at the end of the specified BasicBlock.
2484 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2485 BasicBlock *InsertAtEnd)
2486 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) {
2487 init(Value, Default, NumCases);
2490 SwitchInst::SwitchInst(const SwitchInst &SI)
2491 : TerminatorInst(Type::VoidTy, Instruction::Switch,
2492 new Use[SI.getNumOperands()], SI.getNumOperands()) {
2493 Use *OL = OperandList, *InOL = SI.OperandList;
2494 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2495 OL[i].init(InOL[i], this);
2496 OL[i+1].init(InOL[i+1], this);
2500 SwitchInst::~SwitchInst() {
2501 delete [] OperandList;
2505 /// addCase - Add an entry to the switch instruction...
2507 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2508 unsigned OpNo = NumOperands;
2509 if (OpNo+2 > ReservedSpace)
2510 resizeOperands(0); // Get more space!
2511 // Initialize some new operands.
2512 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2513 NumOperands = OpNo+2;
2514 OperandList[OpNo].init(OnVal, this);
2515 OperandList[OpNo+1].init(Dest, this);
2518 /// removeCase - This method removes the specified successor from the switch
2519 /// instruction. Note that this cannot be used to remove the default
2520 /// destination (successor #0).
2522 void SwitchInst::removeCase(unsigned idx) {
2523 assert(idx != 0 && "Cannot remove the default case!");
2524 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2526 unsigned NumOps = getNumOperands();
2527 Use *OL = OperandList;
2529 // Move everything after this operand down.
2531 // FIXME: we could just swap with the end of the list, then erase. However,
2532 // client might not expect this to happen. The code as it is thrashes the
2533 // use/def lists, which is kinda lame.
2534 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2536 OL[i-2+1] = OL[i+1];
2539 // Nuke the last value.
2540 OL[NumOps-2].set(0);
2541 OL[NumOps-2+1].set(0);
2542 NumOperands = NumOps-2;
2545 /// resizeOperands - resize operands - This adjusts the length of the operands
2546 /// list according to the following behavior:
2547 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2548 /// of operation. This grows the number of ops by 1.5 times.
2549 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2550 /// 3. If NumOps == NumOperands, trim the reserved space.
2552 void SwitchInst::resizeOperands(unsigned NumOps) {
2554 NumOps = getNumOperands()/2*6;
2555 } else if (NumOps*2 > NumOperands) {
2556 // No resize needed.
2557 if (ReservedSpace >= NumOps) return;
2558 } else if (NumOps == NumOperands) {
2559 if (ReservedSpace == NumOps) return;
2564 ReservedSpace = NumOps;
2565 Use *NewOps = new Use[NumOps];
2566 Use *OldOps = OperandList;
2567 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2568 NewOps[i].init(OldOps[i], this);
2572 OperandList = NewOps;
2576 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2577 return getSuccessor(idx);
2579 unsigned SwitchInst::getNumSuccessorsV() const {
2580 return getNumSuccessors();
2582 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2583 setSuccessor(idx, B);
2587 // Define these methods here so vtables don't get emitted into every translation
2588 // unit that uses these classes.
2590 GetElementPtrInst *GetElementPtrInst::clone() const {
2591 return new GetElementPtrInst(*this);
2594 BinaryOperator *BinaryOperator::clone() const {
2595 return create(getOpcode(), Ops[0], Ops[1]);
2598 FCmpInst* FCmpInst::clone() const {
2599 return new FCmpInst(getPredicate(), Ops[0], Ops[1]);
2601 ICmpInst* ICmpInst::clone() const {
2602 return new ICmpInst(getPredicate(), Ops[0], Ops[1]);
2605 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
2606 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
2607 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
2608 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
2609 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
2610 CastInst *TruncInst::clone() const { return new TruncInst(*this); }
2611 CastInst *ZExtInst::clone() const { return new ZExtInst(*this); }
2612 CastInst *SExtInst::clone() const { return new SExtInst(*this); }
2613 CastInst *FPTruncInst::clone() const { return new FPTruncInst(*this); }
2614 CastInst *FPExtInst::clone() const { return new FPExtInst(*this); }
2615 CastInst *UIToFPInst::clone() const { return new UIToFPInst(*this); }
2616 CastInst *SIToFPInst::clone() const { return new SIToFPInst(*this); }
2617 CastInst *FPToUIInst::clone() const { return new FPToUIInst(*this); }
2618 CastInst *FPToSIInst::clone() const { return new FPToSIInst(*this); }
2619 CastInst *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
2620 CastInst *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
2621 CastInst *BitCastInst::clone() const { return new BitCastInst(*this); }
2622 CallInst *CallInst::clone() const { return new CallInst(*this); }
2623 SelectInst *SelectInst::clone() const { return new SelectInst(*this); }
2624 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
2626 ExtractElementInst *ExtractElementInst::clone() const {
2627 return new ExtractElementInst(*this);
2629 InsertElementInst *InsertElementInst::clone() const {
2630 return new InsertElementInst(*this);
2632 ShuffleVectorInst *ShuffleVectorInst::clone() const {
2633 return new ShuffleVectorInst(*this);
2635 PHINode *PHINode::clone() const { return new PHINode(*this); }
2636 ReturnInst *ReturnInst::clone() const { return new ReturnInst(*this); }
2637 BranchInst *BranchInst::clone() const { return new BranchInst(*this); }
2638 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
2639 InvokeInst *InvokeInst::clone() const { return new InvokeInst(*this); }
2640 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
2641 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}