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/Support/CallSite.h"
23 unsigned CallSite::getCallingConv() const {
24 if (CallInst *CI = dyn_cast<CallInst>(I))
25 return CI->getCallingConv();
27 return cast<InvokeInst>(I)->getCallingConv();
29 void CallSite::setCallingConv(unsigned CC) {
30 if (CallInst *CI = dyn_cast<CallInst>(I))
31 CI->setCallingConv(CC);
33 cast<InvokeInst>(I)->setCallingConv(CC);
39 //===----------------------------------------------------------------------===//
40 // TerminatorInst Class
41 //===----------------------------------------------------------------------===//
43 TerminatorInst::TerminatorInst(Instruction::TermOps iType,
44 Use *Ops, unsigned NumOps, Instruction *IB)
45 : Instruction(Type::VoidTy, iType, Ops, NumOps, "", IB) {
48 TerminatorInst::TerminatorInst(Instruction::TermOps iType,
49 Use *Ops, unsigned NumOps, BasicBlock *IAE)
50 : Instruction(Type::VoidTy, iType, Ops, NumOps, "", IAE) {
53 // Out of line virtual method, so the vtable, etc has a home.
54 TerminatorInst::~TerminatorInst() {
57 // Out of line virtual method, so the vtable, etc has a home.
58 UnaryInstruction::~UnaryInstruction() {
62 //===----------------------------------------------------------------------===//
64 //===----------------------------------------------------------------------===//
66 PHINode::PHINode(const PHINode &PN)
67 : Instruction(PN.getType(), Instruction::PHI,
68 new Use[PN.getNumOperands()], PN.getNumOperands()),
69 ReservedSpace(PN.getNumOperands()) {
70 Use *OL = OperandList;
71 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
72 OL[i].init(PN.getOperand(i), this);
73 OL[i+1].init(PN.getOperand(i+1), this);
78 delete [] OperandList;
81 // removeIncomingValue - Remove an incoming value. This is useful if a
82 // predecessor basic block is deleted.
83 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
84 unsigned NumOps = getNumOperands();
85 Use *OL = OperandList;
86 assert(Idx*2 < NumOps && "BB not in PHI node!");
87 Value *Removed = OL[Idx*2];
89 // Move everything after this operand down.
91 // FIXME: we could just swap with the end of the list, then erase. However,
92 // client might not expect this to happen. The code as it is thrashes the
93 // use/def lists, which is kinda lame.
94 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
99 // Nuke the last value.
101 OL[NumOps-2+1].set(0);
102 NumOperands = NumOps-2;
104 // If the PHI node is dead, because it has zero entries, nuke it now.
105 if (NumOps == 2 && DeletePHIIfEmpty) {
106 // If anyone is using this PHI, make them use a dummy value instead...
107 replaceAllUsesWith(UndefValue::get(getType()));
113 /// resizeOperands - resize operands - This adjusts the length of the operands
114 /// list according to the following behavior:
115 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
116 /// of operation. This grows the number of ops by 1.5 times.
117 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
118 /// 3. If NumOps == NumOperands, trim the reserved space.
120 void PHINode::resizeOperands(unsigned NumOps) {
122 NumOps = (getNumOperands())*3/2;
123 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
124 } else if (NumOps*2 > NumOperands) {
126 if (ReservedSpace >= NumOps) return;
127 } else if (NumOps == NumOperands) {
128 if (ReservedSpace == NumOps) return;
133 ReservedSpace = NumOps;
134 Use *NewOps = new Use[NumOps];
135 Use *OldOps = OperandList;
136 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
137 NewOps[i].init(OldOps[i], this);
141 OperandList = NewOps;
144 /// hasConstantValue - If the specified PHI node always merges together the same
145 /// value, return the value, otherwise return null.
147 Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) const {
148 // If the PHI node only has one incoming value, eliminate the PHI node...
149 if (getNumIncomingValues() == 1)
150 if (getIncomingValue(0) != this) // not X = phi X
151 return getIncomingValue(0);
153 return UndefValue::get(getType()); // Self cycle is dead.
155 // Otherwise if all of the incoming values are the same for the PHI, replace
156 // the PHI node with the incoming value.
159 bool HasUndefInput = false;
160 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
161 if (isa<UndefValue>(getIncomingValue(i)))
162 HasUndefInput = true;
163 else if (getIncomingValue(i) != this) // Not the PHI node itself...
164 if (InVal && getIncomingValue(i) != InVal)
165 return 0; // Not the same, bail out.
167 InVal = getIncomingValue(i);
169 // The only case that could cause InVal to be null is if we have a PHI node
170 // that only has entries for itself. In this case, there is no entry into the
171 // loop, so kill the PHI.
173 if (InVal == 0) InVal = UndefValue::get(getType());
175 // If we have a PHI node like phi(X, undef, X), where X is defined by some
176 // instruction, we cannot always return X as the result of the PHI node. Only
177 // do this if X is not an instruction (thus it must dominate the PHI block),
178 // or if the client is prepared to deal with this possibility.
179 if (HasUndefInput && !AllowNonDominatingInstruction)
180 if (Instruction *IV = dyn_cast<Instruction>(InVal))
181 // If it's in the entry block, it dominates everything.
182 if (IV->getParent() != &IV->getParent()->getParent()->front() ||
184 return 0; // Cannot guarantee that InVal dominates this PHINode.
186 // All of the incoming values are the same, return the value now.
191 //===----------------------------------------------------------------------===//
192 // CallInst Implementation
193 //===----------------------------------------------------------------------===//
195 CallInst::~CallInst() {
196 delete [] OperandList;
199 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
200 NumOperands = NumParams+1;
201 Use *OL = OperandList = new Use[NumParams+1];
202 OL[0].init(Func, this);
204 const FunctionType *FTy =
205 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
206 FTy = FTy; // silence warning.
208 assert((NumParams == FTy->getNumParams() ||
209 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
210 "Calling a function with bad signature!");
211 for (unsigned i = 0; i != NumParams; ++i) {
212 assert((i >= FTy->getNumParams() ||
213 FTy->getParamType(i) == Params[i]->getType()) &&
214 "Calling a function with a bad signature!");
215 OL[i+1].init(Params[i], this);
219 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
221 Use *OL = OperandList = new Use[3];
222 OL[0].init(Func, this);
223 OL[1].init(Actual1, this);
224 OL[2].init(Actual2, this);
226 const FunctionType *FTy =
227 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
228 FTy = FTy; // silence warning.
230 assert((FTy->getNumParams() == 2 ||
231 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
232 "Calling a function with bad signature");
233 assert((0 >= FTy->getNumParams() ||
234 FTy->getParamType(0) == Actual1->getType()) &&
235 "Calling a function with a bad signature!");
236 assert((1 >= FTy->getNumParams() ||
237 FTy->getParamType(1) == Actual2->getType()) &&
238 "Calling a function with a bad signature!");
241 void CallInst::init(Value *Func, Value *Actual) {
243 Use *OL = OperandList = new Use[2];
244 OL[0].init(Func, this);
245 OL[1].init(Actual, this);
247 const FunctionType *FTy =
248 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
249 FTy = FTy; // silence warning.
251 assert((FTy->getNumParams() == 1 ||
252 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
253 "Calling a function with bad signature");
254 assert((0 == FTy->getNumParams() ||
255 FTy->getParamType(0) == Actual->getType()) &&
256 "Calling a function with a bad signature!");
259 void CallInst::init(Value *Func) {
261 Use *OL = OperandList = new Use[1];
262 OL[0].init(Func, this);
264 const FunctionType *FTy =
265 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
266 FTy = FTy; // silence warning.
268 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
271 CallInst::CallInst(Value *Func, const std::vector<Value*> &Params,
272 const std::string &Name, Instruction *InsertBefore)
273 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
274 ->getElementType())->getReturnType(),
275 Instruction::Call, 0, 0, Name, InsertBefore) {
276 init(Func, &Params[0], Params.size());
279 CallInst::CallInst(Value *Func, const std::vector<Value*> &Params,
280 const std::string &Name, BasicBlock *InsertAtEnd)
281 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
282 ->getElementType())->getReturnType(),
283 Instruction::Call, 0, 0, Name, InsertAtEnd) {
284 init(Func, &Params[0], Params.size());
287 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
288 const std::string &Name, Instruction *InsertBefore)
289 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
290 ->getElementType())->getReturnType(),
291 Instruction::Call, 0, 0, Name, InsertBefore) {
292 init(Func, Actual1, Actual2);
295 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
296 const std::string &Name, BasicBlock *InsertAtEnd)
297 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
298 ->getElementType())->getReturnType(),
299 Instruction::Call, 0, 0, Name, InsertAtEnd) {
300 init(Func, Actual1, Actual2);
303 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
304 Instruction *InsertBefore)
305 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
306 ->getElementType())->getReturnType(),
307 Instruction::Call, 0, 0, Name, InsertBefore) {
311 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
312 BasicBlock *InsertAtEnd)
313 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
314 ->getElementType())->getReturnType(),
315 Instruction::Call, 0, 0, Name, InsertAtEnd) {
319 CallInst::CallInst(Value *Func, const std::string &Name,
320 Instruction *InsertBefore)
321 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
322 ->getElementType())->getReturnType(),
323 Instruction::Call, 0, 0, Name, InsertBefore) {
327 CallInst::CallInst(Value *Func, const std::string &Name,
328 BasicBlock *InsertAtEnd)
329 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
330 ->getElementType())->getReturnType(),
331 Instruction::Call, 0, 0, Name, InsertAtEnd) {
335 CallInst::CallInst(const CallInst &CI)
336 : Instruction(CI.getType(), Instruction::Call, new Use[CI.getNumOperands()],
337 CI.getNumOperands()) {
338 SubclassData = CI.SubclassData;
339 Use *OL = OperandList;
340 Use *InOL = CI.OperandList;
341 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
342 OL[i].init(InOL[i], this);
346 //===----------------------------------------------------------------------===//
347 // InvokeInst Implementation
348 //===----------------------------------------------------------------------===//
350 InvokeInst::~InvokeInst() {
351 delete [] OperandList;
354 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
355 const std::vector<Value*> &Params) {
356 NumOperands = 3+Params.size();
357 Use *OL = OperandList = new Use[3+Params.size()];
358 OL[0].init(Fn, this);
359 OL[1].init(IfNormal, this);
360 OL[2].init(IfException, this);
361 const FunctionType *FTy =
362 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
363 FTy = FTy; // silence warning.
365 assert((Params.size() == FTy->getNumParams()) ||
366 (FTy->isVarArg() && Params.size() > FTy->getNumParams()) &&
367 "Calling a function with bad signature");
369 for (unsigned i = 0, e = Params.size(); i != e; i++) {
370 assert((i >= FTy->getNumParams() ||
371 FTy->getParamType(i) == Params[i]->getType()) &&
372 "Invoking a function with a bad signature!");
374 OL[i+3].init(Params[i], this);
378 InvokeInst::InvokeInst(Value *Fn, BasicBlock *IfNormal,
379 BasicBlock *IfException,
380 const std::vector<Value*> &Params,
381 const std::string &Name, Instruction *InsertBefore)
382 : TerminatorInst(cast<FunctionType>(cast<PointerType>(Fn->getType())
383 ->getElementType())->getReturnType(),
384 Instruction::Invoke, 0, 0, Name, InsertBefore) {
385 init(Fn, IfNormal, IfException, Params);
388 InvokeInst::InvokeInst(Value *Fn, BasicBlock *IfNormal,
389 BasicBlock *IfException,
390 const std::vector<Value*> &Params,
391 const std::string &Name, BasicBlock *InsertAtEnd)
392 : TerminatorInst(cast<FunctionType>(cast<PointerType>(Fn->getType())
393 ->getElementType())->getReturnType(),
394 Instruction::Invoke, 0, 0, Name, InsertAtEnd) {
395 init(Fn, IfNormal, IfException, Params);
398 InvokeInst::InvokeInst(const InvokeInst &II)
399 : TerminatorInst(II.getType(), Instruction::Invoke,
400 new Use[II.getNumOperands()], II.getNumOperands()) {
401 SubclassData = II.SubclassData;
402 Use *OL = OperandList, *InOL = II.OperandList;
403 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
404 OL[i].init(InOL[i], this);
407 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
408 return getSuccessor(idx);
410 unsigned InvokeInst::getNumSuccessorsV() const {
411 return getNumSuccessors();
413 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
414 return setSuccessor(idx, B);
418 //===----------------------------------------------------------------------===//
419 // ReturnInst Implementation
420 //===----------------------------------------------------------------------===//
422 void ReturnInst::init(Value *retVal) {
423 if (retVal && retVal->getType() != Type::VoidTy) {
424 assert(!isa<BasicBlock>(retVal) &&
425 "Cannot return basic block. Probably using the incorrect ctor");
427 RetVal.init(retVal, this);
431 unsigned ReturnInst::getNumSuccessorsV() const {
432 return getNumSuccessors();
435 // Out-of-line ReturnInst method, put here so the C++ compiler can choose to
436 // emit the vtable for the class in this translation unit.
437 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
438 assert(0 && "ReturnInst has no successors!");
441 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
442 assert(0 && "ReturnInst has no successors!");
448 //===----------------------------------------------------------------------===//
449 // UnwindInst Implementation
450 //===----------------------------------------------------------------------===//
452 unsigned UnwindInst::getNumSuccessorsV() const {
453 return getNumSuccessors();
456 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
457 assert(0 && "UnwindInst has no successors!");
460 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
461 assert(0 && "UnwindInst has no successors!");
466 //===----------------------------------------------------------------------===//
467 // UnreachableInst Implementation
468 //===----------------------------------------------------------------------===//
470 unsigned UnreachableInst::getNumSuccessorsV() const {
471 return getNumSuccessors();
474 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
475 assert(0 && "UnwindInst has no successors!");
478 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
479 assert(0 && "UnwindInst has no successors!");
484 //===----------------------------------------------------------------------===//
485 // BranchInst Implementation
486 //===----------------------------------------------------------------------===//
488 void BranchInst::AssertOK() {
490 assert(getCondition()->getType() == Type::Int1Ty &&
491 "May only branch on boolean predicates!");
494 BranchInst::BranchInst(const BranchInst &BI) :
495 TerminatorInst(Instruction::Br, Ops, BI.getNumOperands()) {
496 OperandList[0].init(BI.getOperand(0), this);
497 if (BI.getNumOperands() != 1) {
498 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
499 OperandList[1].init(BI.getOperand(1), this);
500 OperandList[2].init(BI.getOperand(2), this);
504 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
505 return getSuccessor(idx);
507 unsigned BranchInst::getNumSuccessorsV() const {
508 return getNumSuccessors();
510 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
511 setSuccessor(idx, B);
515 //===----------------------------------------------------------------------===//
516 // AllocationInst Implementation
517 //===----------------------------------------------------------------------===//
519 static Value *getAISize(Value *Amt) {
521 Amt = ConstantInt::get(Type::Int32Ty, 1);
523 assert(!isa<BasicBlock>(Amt) &&
524 "Passed basic block into allocation size parameter! Ue other ctor");
525 assert(Amt->getType() == Type::Int32Ty &&
526 "Malloc/Allocation array size is not a 32-bit integer!");
531 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
532 unsigned Align, const std::string &Name,
533 Instruction *InsertBefore)
534 : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
535 Name, InsertBefore), Alignment(Align) {
536 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
537 assert(Ty != Type::VoidTy && "Cannot allocate void!");
540 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
541 unsigned Align, const std::string &Name,
542 BasicBlock *InsertAtEnd)
543 : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
544 Name, InsertAtEnd), Alignment(Align) {
545 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
546 assert(Ty != Type::VoidTy && "Cannot allocate void!");
549 // Out of line virtual method, so the vtable, etc has a home.
550 AllocationInst::~AllocationInst() {
553 bool AllocationInst::isArrayAllocation() const {
554 if (ConstantInt *CUI = dyn_cast<ConstantInt>(getOperand(0)))
555 return CUI->getZExtValue() != 1;
559 const Type *AllocationInst::getAllocatedType() const {
560 return getType()->getElementType();
563 AllocaInst::AllocaInst(const AllocaInst &AI)
564 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
565 Instruction::Alloca, AI.getAlignment()) {
568 MallocInst::MallocInst(const MallocInst &MI)
569 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
570 Instruction::Malloc, MI.getAlignment()) {
573 //===----------------------------------------------------------------------===//
574 // FreeInst Implementation
575 //===----------------------------------------------------------------------===//
577 void FreeInst::AssertOK() {
578 assert(isa<PointerType>(getOperand(0)->getType()) &&
579 "Can not free something of nonpointer type!");
582 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
583 : UnaryInstruction(Type::VoidTy, Free, Ptr, "", InsertBefore) {
587 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
588 : UnaryInstruction(Type::VoidTy, Free, Ptr, "", InsertAtEnd) {
593 //===----------------------------------------------------------------------===//
594 // LoadInst Implementation
595 //===----------------------------------------------------------------------===//
597 void LoadInst::AssertOK() {
598 assert(isa<PointerType>(getOperand(0)->getType()) &&
599 "Ptr must have pointer type.");
602 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
603 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
604 Load, Ptr, Name, InsertBef) {
609 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
610 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
611 Load, Ptr, Name, InsertAE) {
616 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
617 Instruction *InsertBef)
618 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
619 Load, Ptr, Name, InsertBef) {
620 setVolatile(isVolatile);
624 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
625 BasicBlock *InsertAE)
626 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
627 Load, Ptr, Name, InsertAE) {
628 setVolatile(isVolatile);
633 //===----------------------------------------------------------------------===//
634 // StoreInst Implementation
635 //===----------------------------------------------------------------------===//
637 void StoreInst::AssertOK() {
638 assert(isa<PointerType>(getOperand(1)->getType()) &&
639 "Ptr must have pointer type!");
640 assert(getOperand(0)->getType() ==
641 cast<PointerType>(getOperand(1)->getType())->getElementType()
642 && "Ptr must be a pointer to Val type!");
646 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
647 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertBefore) {
648 Ops[0].init(val, this);
649 Ops[1].init(addr, this);
654 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
655 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertAtEnd) {
656 Ops[0].init(val, this);
657 Ops[1].init(addr, this);
662 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
663 Instruction *InsertBefore)
664 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertBefore) {
665 Ops[0].init(val, this);
666 Ops[1].init(addr, this);
667 setVolatile(isVolatile);
671 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
672 BasicBlock *InsertAtEnd)
673 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertAtEnd) {
674 Ops[0].init(val, this);
675 Ops[1].init(addr, this);
676 setVolatile(isVolatile);
680 //===----------------------------------------------------------------------===//
681 // GetElementPtrInst Implementation
682 //===----------------------------------------------------------------------===//
684 // checkType - Simple wrapper function to give a better assertion failure
685 // message on bad indexes for a gep instruction.
687 static inline const Type *checkType(const Type *Ty) {
688 assert(Ty && "Invalid GetElementPtrInst indices for type!");
692 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx) {
693 NumOperands = 1+NumIdx;
694 Use *OL = OperandList = new Use[NumOperands];
695 OL[0].init(Ptr, this);
697 for (unsigned i = 0; i != NumIdx; ++i)
698 OL[i+1].init(Idx[i], this);
701 void GetElementPtrInst::init(Value *Ptr, Value *Idx0, Value *Idx1) {
703 Use *OL = OperandList = new Use[3];
704 OL[0].init(Ptr, this);
705 OL[1].init(Idx0, this);
706 OL[2].init(Idx1, this);
709 void GetElementPtrInst::init(Value *Ptr, Value *Idx) {
711 Use *OL = OperandList = new Use[2];
712 OL[0].init(Ptr, this);
713 OL[1].init(Idx, this);
717 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value* const *Idx,
719 const std::string &Name, Instruction *InBe)
720 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
721 Idx, NumIdx, true))),
722 GetElementPtr, 0, 0, Name, InBe) {
723 init(Ptr, Idx, NumIdx);
726 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value* const *Idx,
728 const std::string &Name, BasicBlock *IAE)
729 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
730 Idx, NumIdx, true))),
731 GetElementPtr, 0, 0, Name, IAE) {
732 init(Ptr, Idx, NumIdx);
735 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
736 const std::string &Name, Instruction *InBe)
737 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
739 GetElementPtr, 0, 0, Name, InBe) {
743 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
744 const std::string &Name, BasicBlock *IAE)
745 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
747 GetElementPtr, 0, 0, Name, IAE) {
751 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
752 const std::string &Name, Instruction *InBe)
753 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
755 GetElementPtr, 0, 0, Name, InBe) {
756 init(Ptr, Idx0, Idx1);
759 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
760 const std::string &Name, BasicBlock *IAE)
761 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
763 GetElementPtr, 0, 0, Name, IAE) {
764 init(Ptr, Idx0, Idx1);
767 GetElementPtrInst::~GetElementPtrInst() {
768 delete[] OperandList;
771 // getIndexedType - Returns the type of the element that would be loaded with
772 // a load instruction with the specified parameters.
774 // A null type is returned if the indices are invalid for the specified
777 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
780 bool AllowCompositeLeaf) {
781 if (!isa<PointerType>(Ptr)) return 0; // Type isn't a pointer type!
783 // Handle the special case of the empty set index set...
785 if (AllowCompositeLeaf ||
786 cast<PointerType>(Ptr)->getElementType()->isFirstClassType())
787 return cast<PointerType>(Ptr)->getElementType();
792 while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
793 if (NumIdx == CurIdx) {
794 if (AllowCompositeLeaf || CT->isFirstClassType()) return Ptr;
795 return 0; // Can't load a whole structure or array!?!?
798 Value *Index = Idxs[CurIdx++];
799 if (isa<PointerType>(CT) && CurIdx != 1)
800 return 0; // Can only index into pointer types at the first index!
801 if (!CT->indexValid(Index)) return 0;
802 Ptr = CT->getTypeAtIndex(Index);
804 // If the new type forwards to another type, then it is in the middle
805 // of being refined to another type (and hence, may have dropped all
806 // references to what it was using before). So, use the new forwarded
808 if (const Type * Ty = Ptr->getForwardedType()) {
812 return CurIdx == NumIdx ? Ptr : 0;
815 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
816 Value *Idx0, Value *Idx1,
817 bool AllowCompositeLeaf) {
818 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
819 if (!PTy) return 0; // Type isn't a pointer type!
821 // Check the pointer index.
822 if (!PTy->indexValid(Idx0)) return 0;
824 const CompositeType *CT = dyn_cast<CompositeType>(PTy->getElementType());
825 if (!CT || !CT->indexValid(Idx1)) return 0;
827 const Type *ElTy = CT->getTypeAtIndex(Idx1);
828 if (AllowCompositeLeaf || ElTy->isFirstClassType())
833 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
834 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
835 if (!PTy) return 0; // Type isn't a pointer type!
837 // Check the pointer index.
838 if (!PTy->indexValid(Idx)) return 0;
840 return PTy->getElementType();
843 //===----------------------------------------------------------------------===//
844 // ExtractElementInst Implementation
845 //===----------------------------------------------------------------------===//
847 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
848 const std::string &Name,
849 Instruction *InsertBef)
850 : Instruction(cast<PackedType>(Val->getType())->getElementType(),
851 ExtractElement, Ops, 2, Name, InsertBef) {
852 assert(isValidOperands(Val, Index) &&
853 "Invalid extractelement instruction operands!");
854 Ops[0].init(Val, this);
855 Ops[1].init(Index, this);
858 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
859 const std::string &Name,
860 Instruction *InsertBef)
861 : Instruction(cast<PackedType>(Val->getType())->getElementType(),
862 ExtractElement, Ops, 2, Name, InsertBef) {
863 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
864 assert(isValidOperands(Val, Index) &&
865 "Invalid extractelement instruction operands!");
866 Ops[0].init(Val, this);
867 Ops[1].init(Index, this);
871 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
872 const std::string &Name,
873 BasicBlock *InsertAE)
874 : Instruction(cast<PackedType>(Val->getType())->getElementType(),
875 ExtractElement, Ops, 2, Name, InsertAE) {
876 assert(isValidOperands(Val, Index) &&
877 "Invalid extractelement instruction operands!");
879 Ops[0].init(Val, this);
880 Ops[1].init(Index, this);
883 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
884 const std::string &Name,
885 BasicBlock *InsertAE)
886 : Instruction(cast<PackedType>(Val->getType())->getElementType(),
887 ExtractElement, Ops, 2, Name, InsertAE) {
888 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
889 assert(isValidOperands(Val, Index) &&
890 "Invalid extractelement instruction operands!");
892 Ops[0].init(Val, this);
893 Ops[1].init(Index, this);
897 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
898 if (!isa<PackedType>(Val->getType()) || Index->getType() != Type::Int32Ty)
904 //===----------------------------------------------------------------------===//
905 // InsertElementInst Implementation
906 //===----------------------------------------------------------------------===//
908 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
909 : Instruction(IE.getType(), InsertElement, Ops, 3) {
910 Ops[0].init(IE.Ops[0], this);
911 Ops[1].init(IE.Ops[1], this);
912 Ops[2].init(IE.Ops[2], this);
914 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
915 const std::string &Name,
916 Instruction *InsertBef)
917 : Instruction(Vec->getType(), InsertElement, Ops, 3, Name, InsertBef) {
918 assert(isValidOperands(Vec, Elt, Index) &&
919 "Invalid insertelement instruction operands!");
920 Ops[0].init(Vec, this);
921 Ops[1].init(Elt, this);
922 Ops[2].init(Index, this);
925 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
926 const std::string &Name,
927 Instruction *InsertBef)
928 : Instruction(Vec->getType(), InsertElement, Ops, 3, Name, InsertBef) {
929 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
930 assert(isValidOperands(Vec, Elt, Index) &&
931 "Invalid insertelement instruction operands!");
932 Ops[0].init(Vec, this);
933 Ops[1].init(Elt, this);
934 Ops[2].init(Index, this);
938 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
939 const std::string &Name,
940 BasicBlock *InsertAE)
941 : Instruction(Vec->getType(), InsertElement, Ops, 3, Name, InsertAE) {
942 assert(isValidOperands(Vec, Elt, Index) &&
943 "Invalid insertelement instruction operands!");
945 Ops[0].init(Vec, this);
946 Ops[1].init(Elt, this);
947 Ops[2].init(Index, this);
950 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
951 const std::string &Name,
952 BasicBlock *InsertAE)
953 : Instruction(Vec->getType(), InsertElement, Ops, 3, Name, InsertAE) {
954 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
955 assert(isValidOperands(Vec, Elt, Index) &&
956 "Invalid insertelement instruction operands!");
958 Ops[0].init(Vec, this);
959 Ops[1].init(Elt, this);
960 Ops[2].init(Index, this);
963 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
964 const Value *Index) {
965 if (!isa<PackedType>(Vec->getType()))
966 return false; // First operand of insertelement must be packed type.
968 if (Elt->getType() != cast<PackedType>(Vec->getType())->getElementType())
969 return false;// Second operand of insertelement must be packed element type.
971 if (Index->getType() != Type::Int32Ty)
972 return false; // Third operand of insertelement must be uint.
977 //===----------------------------------------------------------------------===//
978 // ShuffleVectorInst Implementation
979 //===----------------------------------------------------------------------===//
981 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
982 : Instruction(SV.getType(), ShuffleVector, Ops, 3) {
983 Ops[0].init(SV.Ops[0], this);
984 Ops[1].init(SV.Ops[1], this);
985 Ops[2].init(SV.Ops[2], this);
988 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
989 const std::string &Name,
990 Instruction *InsertBefore)
991 : Instruction(V1->getType(), ShuffleVector, Ops, 3, Name, InsertBefore) {
992 assert(isValidOperands(V1, V2, Mask) &&
993 "Invalid shuffle vector instruction operands!");
994 Ops[0].init(V1, this);
995 Ops[1].init(V2, this);
996 Ops[2].init(Mask, this);
999 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1000 const std::string &Name,
1001 BasicBlock *InsertAtEnd)
1002 : Instruction(V1->getType(), ShuffleVector, Ops, 3, Name, InsertAtEnd) {
1003 assert(isValidOperands(V1, V2, Mask) &&
1004 "Invalid shuffle vector instruction operands!");
1006 Ops[0].init(V1, this);
1007 Ops[1].init(V2, this);
1008 Ops[2].init(Mask, this);
1011 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1012 const Value *Mask) {
1013 if (!isa<PackedType>(V1->getType())) return false;
1014 if (V1->getType() != V2->getType()) return false;
1015 if (!isa<PackedType>(Mask->getType()) ||
1016 cast<PackedType>(Mask->getType())->getElementType() != Type::Int32Ty ||
1017 cast<PackedType>(Mask->getType())->getNumElements() !=
1018 cast<PackedType>(V1->getType())->getNumElements())
1024 //===----------------------------------------------------------------------===//
1025 // BinaryOperator Class
1026 //===----------------------------------------------------------------------===//
1028 void BinaryOperator::init(BinaryOps iType)
1030 Value *LHS = getOperand(0), *RHS = getOperand(1);
1031 LHS = LHS; RHS = RHS; // Silence warnings.
1032 assert(LHS->getType() == RHS->getType() &&
1033 "Binary operator operand types must match!");
1038 assert(getType() == LHS->getType() &&
1039 "Arithmetic operation should return same type as operands!");
1040 assert((getType()->isInteger() || getType()->isFloatingPoint() ||
1041 isa<PackedType>(getType())) &&
1042 "Tried to create an arithmetic operation on a non-arithmetic type!");
1046 assert(getType() == LHS->getType() &&
1047 "Arithmetic operation should return same type as operands!");
1048 assert((getType()->isInteger() || (isa<PackedType>(getType()) &&
1049 cast<PackedType>(getType())->getElementType()->isInteger())) &&
1050 "Incorrect operand type (not integer) for S/UDIV");
1053 assert(getType() == LHS->getType() &&
1054 "Arithmetic operation should return same type as operands!");
1055 assert((getType()->isFloatingPoint() || (isa<PackedType>(getType()) &&
1056 cast<PackedType>(getType())->getElementType()->isFloatingPoint()))
1057 && "Incorrect operand type (not floating point) for FDIV");
1061 assert(getType() == LHS->getType() &&
1062 "Arithmetic operation should return same type as operands!");
1063 assert((getType()->isInteger() || (isa<PackedType>(getType()) &&
1064 cast<PackedType>(getType())->getElementType()->isInteger())) &&
1065 "Incorrect operand type (not integer) for S/UREM");
1068 assert(getType() == LHS->getType() &&
1069 "Arithmetic operation should return same type as operands!");
1070 assert((getType()->isFloatingPoint() || (isa<PackedType>(getType()) &&
1071 cast<PackedType>(getType())->getElementType()->isFloatingPoint()))
1072 && "Incorrect operand type (not floating point) for FREM");
1077 assert(getType() == LHS->getType() &&
1078 "Shift operation should return same type as operands!");
1079 assert(getType()->isInteger() &&
1080 "Shift operation requires integer operands");
1084 assert(getType() == LHS->getType() &&
1085 "Logical operation should return same type as operands!");
1086 assert((getType()->isInteger() ||
1087 (isa<PackedType>(getType()) &&
1088 cast<PackedType>(getType())->getElementType()->isInteger())) &&
1089 "Tried to create a logical operation on a non-integral type!");
1097 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1098 const std::string &Name,
1099 Instruction *InsertBefore) {
1100 assert(S1->getType() == S2->getType() &&
1101 "Cannot create binary operator with two operands of differing type!");
1102 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1105 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1106 const std::string &Name,
1107 BasicBlock *InsertAtEnd) {
1108 BinaryOperator *Res = create(Op, S1, S2, Name);
1109 InsertAtEnd->getInstList().push_back(Res);
1113 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1114 Instruction *InsertBefore) {
1115 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1116 return new BinaryOperator(Instruction::Sub,
1118 Op->getType(), Name, InsertBefore);
1121 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1122 BasicBlock *InsertAtEnd) {
1123 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1124 return new BinaryOperator(Instruction::Sub,
1126 Op->getType(), Name, InsertAtEnd);
1129 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1130 Instruction *InsertBefore) {
1132 if (const PackedType *PTy = dyn_cast<PackedType>(Op->getType())) {
1133 C = ConstantInt::getAllOnesValue(PTy->getElementType());
1134 C = ConstantPacked::get(std::vector<Constant*>(PTy->getNumElements(), C));
1136 C = ConstantInt::getAllOnesValue(Op->getType());
1139 return new BinaryOperator(Instruction::Xor, Op, C,
1140 Op->getType(), Name, InsertBefore);
1143 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1144 BasicBlock *InsertAtEnd) {
1146 if (const PackedType *PTy = dyn_cast<PackedType>(Op->getType())) {
1147 // Create a vector of all ones values.
1148 Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType());
1150 ConstantPacked::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1152 AllOnes = ConstantInt::getAllOnesValue(Op->getType());
1155 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1156 Op->getType(), Name, InsertAtEnd);
1160 // isConstantAllOnes - Helper function for several functions below
1161 static inline bool isConstantAllOnes(const Value *V) {
1162 return isa<ConstantInt>(V) &&cast<ConstantInt>(V)->isAllOnesValue();
1165 bool BinaryOperator::isNeg(const Value *V) {
1166 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1167 if (Bop->getOpcode() == Instruction::Sub)
1168 return Bop->getOperand(0) ==
1169 ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1173 bool BinaryOperator::isNot(const Value *V) {
1174 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1175 return (Bop->getOpcode() == Instruction::Xor &&
1176 (isConstantAllOnes(Bop->getOperand(1)) ||
1177 isConstantAllOnes(Bop->getOperand(0))));
1181 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1182 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1183 return cast<BinaryOperator>(BinOp)->getOperand(1);
1186 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1187 return getNegArgument(const_cast<Value*>(BinOp));
1190 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1191 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1192 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1193 Value *Op0 = BO->getOperand(0);
1194 Value *Op1 = BO->getOperand(1);
1195 if (isConstantAllOnes(Op0)) return Op1;
1197 assert(isConstantAllOnes(Op1));
1201 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1202 return getNotArgument(const_cast<Value*>(BinOp));
1206 // swapOperands - Exchange the two operands to this instruction. This
1207 // instruction is safe to use on any binary instruction and does not
1208 // modify the semantics of the instruction. If the instruction is
1209 // order dependent (SetLT f.e.) the opcode is changed.
1211 bool BinaryOperator::swapOperands() {
1212 if (!isCommutative())
1213 return true; // Can't commute operands
1214 std::swap(Ops[0], Ops[1]);
1218 //===----------------------------------------------------------------------===//
1220 //===----------------------------------------------------------------------===//
1222 // Just determine if this cast only deals with integral->integral conversion.
1223 bool CastInst::isIntegerCast() const {
1224 switch (getOpcode()) {
1225 default: return false;
1226 case Instruction::ZExt:
1227 case Instruction::SExt:
1228 case Instruction::Trunc:
1230 case Instruction::BitCast:
1231 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1235 bool CastInst::isLosslessCast() const {
1236 // Only BitCast can be lossless, exit fast if we're not BitCast
1237 if (getOpcode() != Instruction::BitCast)
1240 // Identity cast is always lossless
1241 const Type* SrcTy = getOperand(0)->getType();
1242 const Type* DstTy = getType();
1246 // Pointer to pointer is always lossless.
1247 if (isa<PointerType>(SrcTy))
1248 return isa<PointerType>(DstTy);
1249 return false; // Other types have no identity values
1252 /// This function determines if the CastInst does not require any bits to be
1253 /// changed in order to effect the cast. Essentially, it identifies cases where
1254 /// no code gen is necessary for the cast, hence the name no-op cast. For
1255 /// example, the following are all no-op casts:
1256 /// # bitcast uint %X, int
1257 /// # bitcast uint* %x, sbyte*
1258 /// # bitcast packed< 2 x int > %x, packed< 4 x short>
1259 /// # ptrtoint uint* %x, uint ; on 32-bit plaforms only
1260 /// @brief Determine if a cast is a no-op.
1261 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1262 switch (getOpcode()) {
1264 assert(!"Invalid CastOp");
1265 case Instruction::Trunc:
1266 case Instruction::ZExt:
1267 case Instruction::SExt:
1268 case Instruction::FPTrunc:
1269 case Instruction::FPExt:
1270 case Instruction::UIToFP:
1271 case Instruction::SIToFP:
1272 case Instruction::FPToUI:
1273 case Instruction::FPToSI:
1274 return false; // These always modify bits
1275 case Instruction::BitCast:
1276 return true; // BitCast never modifies bits.
1277 case Instruction::PtrToInt:
1278 return IntPtrTy->getPrimitiveSizeInBits() ==
1279 getType()->getPrimitiveSizeInBits();
1280 case Instruction::IntToPtr:
1281 return IntPtrTy->getPrimitiveSizeInBits() ==
1282 getOperand(0)->getType()->getPrimitiveSizeInBits();
1286 /// This function determines if a pair of casts can be eliminated and what
1287 /// opcode should be used in the elimination. This assumes that there are two
1288 /// instructions like this:
1289 /// * %F = firstOpcode SrcTy %x to MidTy
1290 /// * %S = secondOpcode MidTy %F to DstTy
1291 /// The function returns a resultOpcode so these two casts can be replaced with:
1292 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1293 /// If no such cast is permited, the function returns 0.
1294 unsigned CastInst::isEliminableCastPair(
1295 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1296 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1298 // Define the 144 possibilities for these two cast instructions. The values
1299 // in this matrix determine what to do in a given situation and select the
1300 // case in the switch below. The rows correspond to firstOp, the columns
1301 // correspond to secondOp. In looking at the table below, keep in mind
1302 // the following cast properties:
1304 // Size Compare Source Destination
1305 // Operator Src ? Size Type Sign Type Sign
1306 // -------- ------------ ------------------- ---------------------
1307 // TRUNC > Integer Any Integral Any
1308 // ZEXT < Integral Unsigned Integer Any
1309 // SEXT < Integral Signed Integer Any
1310 // FPTOUI n/a FloatPt n/a Integral Unsigned
1311 // FPTOSI n/a FloatPt n/a Integral Signed
1312 // UITOFP n/a Integral Unsigned FloatPt n/a
1313 // SITOFP n/a Integral Signed FloatPt n/a
1314 // FPTRUNC > FloatPt n/a FloatPt n/a
1315 // FPEXT < FloatPt n/a FloatPt n/a
1316 // PTRTOINT n/a Pointer n/a Integral Unsigned
1317 // INTTOPTR n/a Integral Unsigned Pointer n/a
1318 // BITCONVERT = FirstClass n/a FirstClass n/a
1320 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1321 // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
1322 // into "fptoui double to ulong", but this loses information about the range
1323 // of the produced value (we no longer know the top-part is all zeros).
1324 // Further this conversion is often much more expensive for typical hardware,
1325 // and causes issues when building libgcc. We disallow fptosi+sext for the
1327 const unsigned numCastOps =
1328 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1329 static const uint8_t CastResults[numCastOps][numCastOps] = {
1330 // T F F U S F F P I B -+
1331 // R Z S P P I I T P 2 N T |
1332 // U E E 2 2 2 2 R E I T C +- secondOp
1333 // N X X U S F F N X N 2 V |
1334 // C T T I I P P C T T P T -+
1335 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1336 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1337 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1338 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1339 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1340 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1341 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1342 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1343 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1344 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1345 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1346 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1349 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1350 [secondOp-Instruction::CastOpsBegin];
1353 // categorically disallowed
1356 // allowed, use first cast's opcode
1359 // allowed, use second cast's opcode
1362 // no-op cast in second op implies firstOp as long as the DestTy
1364 if (DstTy->isInteger())
1368 // no-op cast in second op implies firstOp as long as the DestTy
1369 // is floating point
1370 if (DstTy->isFloatingPoint())
1374 // no-op cast in first op implies secondOp as long as the SrcTy
1376 if (SrcTy->isInteger())
1380 // no-op cast in first op implies secondOp as long as the SrcTy
1381 // is a floating point
1382 if (SrcTy->isFloatingPoint())
1386 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1387 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1388 unsigned MidSize = MidTy->getPrimitiveSizeInBits();
1389 if (MidSize >= PtrSize)
1390 return Instruction::BitCast;
1394 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1395 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1396 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1397 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1398 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1399 if (SrcSize == DstSize)
1400 return Instruction::BitCast;
1401 else if (SrcSize < DstSize)
1405 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1406 return Instruction::ZExt;
1408 // fpext followed by ftrunc is allowed if the bit size returned to is
1409 // the same as the original, in which case its just a bitcast
1411 return Instruction::BitCast;
1412 return 0; // If the types are not the same we can't eliminate it.
1414 // bitcast followed by ptrtoint is allowed as long as the bitcast
1415 // is a pointer to pointer cast.
1416 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1420 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1421 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1425 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1426 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1427 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1428 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1429 if (SrcSize <= PtrSize && SrcSize == DstSize)
1430 return Instruction::BitCast;
1434 // cast combination can't happen (error in input). This is for all cases
1435 // where the MidTy is not the same for the two cast instructions.
1436 assert(!"Invalid Cast Combination");
1439 assert(!"Error in CastResults table!!!");
1445 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1446 const std::string &Name, Instruction *InsertBefore) {
1447 // Construct and return the appropriate CastInst subclass
1449 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1450 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1451 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1452 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1453 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1454 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1455 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1456 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1457 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1458 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1459 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1460 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1462 assert(!"Invalid opcode provided");
1467 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1468 const std::string &Name, BasicBlock *InsertAtEnd) {
1469 // Construct and return the appropriate CastInst subclass
1471 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1472 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1473 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1474 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1475 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1476 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1477 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1478 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1479 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1480 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1481 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1482 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1484 assert(!"Invalid opcode provided");
1489 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1490 const std::string &Name,
1491 Instruction *InsertBefore) {
1492 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1493 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1494 return create(Instruction::ZExt, S, Ty, Name, InsertBefore);
1497 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1498 const std::string &Name,
1499 BasicBlock *InsertAtEnd) {
1500 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1501 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1502 return create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
1505 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1506 const std::string &Name,
1507 Instruction *InsertBefore) {
1508 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1509 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1510 return create(Instruction::SExt, S, Ty, Name, InsertBefore);
1513 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1514 const std::string &Name,
1515 BasicBlock *InsertAtEnd) {
1516 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1517 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1518 return create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
1521 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1522 const std::string &Name,
1523 Instruction *InsertBefore) {
1524 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1525 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1526 return create(Instruction::Trunc, S, Ty, Name, InsertBefore);
1529 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1530 const std::string &Name,
1531 BasicBlock *InsertAtEnd) {
1532 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1533 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1534 return create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
1537 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1538 const std::string &Name,
1539 BasicBlock *InsertAtEnd) {
1540 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1541 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1544 if (Ty->isInteger())
1545 return create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
1546 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1549 /// @brief Create a BitCast or a PtrToInt cast instruction
1550 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1551 const std::string &Name,
1552 Instruction *InsertBefore) {
1553 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1554 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1557 if (Ty->isInteger())
1558 return create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
1559 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1562 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1563 bool isSigned, const std::string &Name,
1564 Instruction *InsertBefore) {
1565 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1566 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1567 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1568 Instruction::CastOps opcode =
1569 (SrcBits == DstBits ? Instruction::BitCast :
1570 (SrcBits > DstBits ? Instruction::Trunc :
1571 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1572 return create(opcode, C, Ty, Name, InsertBefore);
1575 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1576 bool isSigned, const std::string &Name,
1577 BasicBlock *InsertAtEnd) {
1578 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1579 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1580 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1581 Instruction::CastOps opcode =
1582 (SrcBits == DstBits ? Instruction::BitCast :
1583 (SrcBits > DstBits ? Instruction::Trunc :
1584 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1585 return create(opcode, C, Ty, Name, InsertAtEnd);
1588 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1589 const std::string &Name,
1590 Instruction *InsertBefore) {
1591 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1593 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1594 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1595 Instruction::CastOps opcode =
1596 (SrcBits == DstBits ? Instruction::BitCast :
1597 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1598 return create(opcode, C, Ty, Name, InsertBefore);
1601 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1602 const std::string &Name,
1603 BasicBlock *InsertAtEnd) {
1604 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1606 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1607 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1608 Instruction::CastOps opcode =
1609 (SrcBits == DstBits ? Instruction::BitCast :
1610 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1611 return create(opcode, C, Ty, Name, InsertAtEnd);
1614 // Provide a way to get a "cast" where the cast opcode is inferred from the
1615 // types and size of the operand. This, basically, is a parallel of the
1616 // logic in the castIsValid function below. This axiom should hold:
1617 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
1618 // should not assert in castIsValid. In other words, this produces a "correct"
1619 // casting opcode for the arguments passed to it.
1620 Instruction::CastOps
1621 CastInst::getCastOpcode(
1622 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
1623 // Get the bit sizes, we'll need these
1624 const Type *SrcTy = Src->getType();
1625 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/packed
1626 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/packed
1628 // Run through the possibilities ...
1629 if (DestTy->isInteger()) { // Casting to integral
1630 if (SrcTy->isInteger()) { // Casting from integral
1631 if (DestBits < SrcBits)
1632 return Trunc; // int -> smaller int
1633 else if (DestBits > SrcBits) { // its an extension
1635 return SExt; // signed -> SEXT
1637 return ZExt; // unsigned -> ZEXT
1639 return BitCast; // Same size, No-op cast
1641 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1643 return FPToSI; // FP -> sint
1645 return FPToUI; // FP -> uint
1646 } else if (const PackedType *PTy = dyn_cast<PackedType>(SrcTy)) {
1647 assert(DestBits == PTy->getBitWidth() &&
1648 "Casting packed to integer of different width");
1649 return BitCast; // Same size, no-op cast
1651 assert(isa<PointerType>(SrcTy) &&
1652 "Casting from a value that is not first-class type");
1653 return PtrToInt; // ptr -> int
1655 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
1656 if (SrcTy->isInteger()) { // Casting from integral
1658 return SIToFP; // sint -> FP
1660 return UIToFP; // uint -> FP
1661 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1662 if (DestBits < SrcBits) {
1663 return FPTrunc; // FP -> smaller FP
1664 } else if (DestBits > SrcBits) {
1665 return FPExt; // FP -> larger FP
1667 return BitCast; // same size, no-op cast
1669 } else if (const PackedType *PTy = dyn_cast<PackedType>(SrcTy)) {
1670 assert(DestBits == PTy->getBitWidth() &&
1671 "Casting packed to floating point of different width");
1672 return BitCast; // same size, no-op cast
1674 assert(0 && "Casting pointer or non-first class to float");
1676 } else if (const PackedType *DestPTy = dyn_cast<PackedType>(DestTy)) {
1677 if (const PackedType *SrcPTy = dyn_cast<PackedType>(SrcTy)) {
1678 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
1679 "Casting packed to packed of different widths");
1680 return BitCast; // packed -> packed
1681 } else if (DestPTy->getBitWidth() == SrcBits) {
1682 return BitCast; // float/int -> packed
1684 assert(!"Illegal cast to packed (wrong type or size)");
1686 } else if (isa<PointerType>(DestTy)) {
1687 if (isa<PointerType>(SrcTy)) {
1688 return BitCast; // ptr -> ptr
1689 } else if (SrcTy->isInteger()) {
1690 return IntToPtr; // int -> ptr
1692 assert(!"Casting pointer to other than pointer or int");
1695 assert(!"Casting to type that is not first-class");
1698 // If we fall through to here we probably hit an assertion cast above
1699 // and assertions are not turned on. Anything we return is an error, so
1700 // BitCast is as good a choice as any.
1704 //===----------------------------------------------------------------------===//
1705 // CastInst SubClass Constructors
1706 //===----------------------------------------------------------------------===//
1708 /// Check that the construction parameters for a CastInst are correct. This
1709 /// could be broken out into the separate constructors but it is useful to have
1710 /// it in one place and to eliminate the redundant code for getting the sizes
1711 /// of the types involved.
1713 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
1715 // Check for type sanity on the arguments
1716 const Type *SrcTy = S->getType();
1717 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
1720 // Get the size of the types in bits, we'll need this later
1721 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1722 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1724 // Switch on the opcode provided
1726 default: return false; // This is an input error
1727 case Instruction::Trunc:
1728 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize > DstBitSize;
1729 case Instruction::ZExt:
1730 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
1731 case Instruction::SExt:
1732 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
1733 case Instruction::FPTrunc:
1734 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
1735 SrcBitSize > DstBitSize;
1736 case Instruction::FPExt:
1737 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
1738 SrcBitSize < DstBitSize;
1739 case Instruction::UIToFP:
1740 return SrcTy->isInteger() && DstTy->isFloatingPoint();
1741 case Instruction::SIToFP:
1742 return SrcTy->isInteger() && DstTy->isFloatingPoint();
1743 case Instruction::FPToUI:
1744 return SrcTy->isFloatingPoint() && DstTy->isInteger();
1745 case Instruction::FPToSI:
1746 return SrcTy->isFloatingPoint() && DstTy->isInteger();
1747 case Instruction::PtrToInt:
1748 return isa<PointerType>(SrcTy) && DstTy->isInteger();
1749 case Instruction::IntToPtr:
1750 return SrcTy->isInteger() && isa<PointerType>(DstTy);
1751 case Instruction::BitCast:
1752 // BitCast implies a no-op cast of type only. No bits change.
1753 // However, you can't cast pointers to anything but pointers.
1754 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
1757 // Now we know we're not dealing with a pointer/non-poiner mismatch. In all
1758 // these cases, the cast is okay if the source and destination bit widths
1760 return SrcBitSize == DstBitSize;
1764 TruncInst::TruncInst(
1765 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1766 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
1767 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
1770 TruncInst::TruncInst(
1771 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1772 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
1773 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
1777 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1778 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
1779 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
1783 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1784 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
1785 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
1788 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1789 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
1790 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
1794 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1795 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
1796 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
1799 FPTruncInst::FPTruncInst(
1800 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1801 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
1802 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
1805 FPTruncInst::FPTruncInst(
1806 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1807 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
1808 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
1811 FPExtInst::FPExtInst(
1812 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1813 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
1814 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
1817 FPExtInst::FPExtInst(
1818 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1819 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
1820 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
1823 UIToFPInst::UIToFPInst(
1824 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1825 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
1826 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
1829 UIToFPInst::UIToFPInst(
1830 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1831 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
1832 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
1835 SIToFPInst::SIToFPInst(
1836 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1837 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
1838 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
1841 SIToFPInst::SIToFPInst(
1842 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1843 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
1844 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
1847 FPToUIInst::FPToUIInst(
1848 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1849 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
1850 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
1853 FPToUIInst::FPToUIInst(
1854 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1855 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
1856 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
1859 FPToSIInst::FPToSIInst(
1860 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1861 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
1862 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
1865 FPToSIInst::FPToSIInst(
1866 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1867 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
1868 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
1871 PtrToIntInst::PtrToIntInst(
1872 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1873 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
1874 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
1877 PtrToIntInst::PtrToIntInst(
1878 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1879 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
1880 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
1883 IntToPtrInst::IntToPtrInst(
1884 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1885 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
1886 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
1889 IntToPtrInst::IntToPtrInst(
1890 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1891 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
1892 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
1895 BitCastInst::BitCastInst(
1896 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1897 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
1898 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
1901 BitCastInst::BitCastInst(
1902 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1903 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
1904 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
1907 //===----------------------------------------------------------------------===//
1909 //===----------------------------------------------------------------------===//
1911 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
1912 const std::string &Name, Instruction *InsertBefore)
1913 : Instruction(Type::Int1Ty, op, Ops, 2, Name, InsertBefore) {
1914 Ops[0].init(LHS, this);
1915 Ops[1].init(RHS, this);
1916 SubclassData = predicate;
1917 if (op == Instruction::ICmp) {
1918 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
1919 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
1920 "Invalid ICmp predicate value");
1921 const Type* Op0Ty = getOperand(0)->getType();
1922 const Type* Op1Ty = getOperand(1)->getType();
1923 assert(Op0Ty == Op1Ty &&
1924 "Both operands to ICmp instruction are not of the same type!");
1925 // Check that the operands are the right type
1926 assert((Op0Ty->isInteger() || isa<PointerType>(Op0Ty)) &&
1927 "Invalid operand types for ICmp instruction");
1930 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
1931 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
1932 "Invalid FCmp predicate value");
1933 const Type* Op0Ty = getOperand(0)->getType();
1934 const Type* Op1Ty = getOperand(1)->getType();
1935 assert(Op0Ty == Op1Ty &&
1936 "Both operands to FCmp instruction are not of the same type!");
1937 // Check that the operands are the right type
1938 assert(Op0Ty->isFloatingPoint() &&
1939 "Invalid operand types for FCmp instruction");
1942 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
1943 const std::string &Name, BasicBlock *InsertAtEnd)
1944 : Instruction(Type::Int1Ty, op, Ops, 2, Name, InsertAtEnd) {
1945 Ops[0].init(LHS, this);
1946 Ops[1].init(RHS, this);
1947 SubclassData = predicate;
1948 if (op == Instruction::ICmp) {
1949 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
1950 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
1951 "Invalid ICmp predicate value");
1953 const Type* Op0Ty = getOperand(0)->getType();
1954 const Type* Op1Ty = getOperand(1)->getType();
1955 assert(Op0Ty == Op1Ty &&
1956 "Both operands to ICmp instruction are not of the same type!");
1957 // Check that the operands are the right type
1958 assert(Op0Ty->isInteger() || isa<PointerType>(Op0Ty) &&
1959 "Invalid operand types for ICmp instruction");
1962 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
1963 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
1964 "Invalid FCmp predicate value");
1965 const Type* Op0Ty = getOperand(0)->getType();
1966 const Type* Op1Ty = getOperand(1)->getType();
1967 assert(Op0Ty == Op1Ty &&
1968 "Both operands to FCmp instruction are not of the same type!");
1969 // Check that the operands are the right type
1970 assert(Op0Ty->isFloatingPoint() &&
1971 "Invalid operand types for FCmp instruction");
1975 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
1976 const std::string &Name, Instruction *InsertBefore) {
1977 if (Op == Instruction::ICmp) {
1978 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
1981 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
1986 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
1987 const std::string &Name, BasicBlock *InsertAtEnd) {
1988 if (Op == Instruction::ICmp) {
1989 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
1992 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
1996 void CmpInst::swapOperands() {
1997 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2000 cast<FCmpInst>(this)->swapOperands();
2003 bool CmpInst::isCommutative() {
2004 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2005 return IC->isCommutative();
2006 return cast<FCmpInst>(this)->isCommutative();
2009 bool CmpInst::isEquality() {
2010 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2011 return IC->isEquality();
2012 return cast<FCmpInst>(this)->isEquality();
2016 ICmpInst::Predicate ICmpInst::getInversePredicate(Predicate pred) {
2019 assert(!"Unknown icmp predicate!");
2020 case ICMP_EQ: return ICMP_NE;
2021 case ICMP_NE: return ICMP_EQ;
2022 case ICMP_UGT: return ICMP_ULE;
2023 case ICMP_ULT: return ICMP_UGE;
2024 case ICMP_UGE: return ICMP_ULT;
2025 case ICMP_ULE: return ICMP_UGT;
2026 case ICMP_SGT: return ICMP_SLE;
2027 case ICMP_SLT: return ICMP_SGE;
2028 case ICMP_SGE: return ICMP_SLT;
2029 case ICMP_SLE: return ICMP_SGT;
2033 ICmpInst::Predicate ICmpInst::getSwappedPredicate(Predicate pred) {
2035 default: assert(! "Unknown icmp predicate!");
2036 case ICMP_EQ: case ICMP_NE:
2038 case ICMP_SGT: return ICMP_SLT;
2039 case ICMP_SLT: return ICMP_SGT;
2040 case ICMP_SGE: return ICMP_SLE;
2041 case ICMP_SLE: return ICMP_SGE;
2042 case ICMP_UGT: return ICMP_ULT;
2043 case ICMP_ULT: return ICMP_UGT;
2044 case ICMP_UGE: return ICMP_ULE;
2045 case ICMP_ULE: return ICMP_UGE;
2049 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2051 default: assert(! "Unknown icmp predicate!");
2052 case ICMP_EQ: case ICMP_NE:
2053 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2055 case ICMP_UGT: return ICMP_SGT;
2056 case ICMP_ULT: return ICMP_SLT;
2057 case ICMP_UGE: return ICMP_SGE;
2058 case ICMP_ULE: return ICMP_SLE;
2062 bool ICmpInst::isSignedPredicate(Predicate pred) {
2064 default: assert(! "Unknown icmp predicate!");
2065 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2067 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2068 case ICMP_UGE: case ICMP_ULE:
2073 FCmpInst::Predicate FCmpInst::getInversePredicate(Predicate pred) {
2076 assert(!"Unknown icmp predicate!");
2077 case FCMP_OEQ: return FCMP_UNE;
2078 case FCMP_ONE: return FCMP_UEQ;
2079 case FCMP_OGT: return FCMP_ULE;
2080 case FCMP_OLT: return FCMP_UGE;
2081 case FCMP_OGE: return FCMP_ULT;
2082 case FCMP_OLE: return FCMP_UGT;
2083 case FCMP_UEQ: return FCMP_ONE;
2084 case FCMP_UNE: return FCMP_OEQ;
2085 case FCMP_UGT: return FCMP_OLE;
2086 case FCMP_ULT: return FCMP_OGE;
2087 case FCMP_UGE: return FCMP_OLT;
2088 case FCMP_ULE: return FCMP_OGT;
2089 case FCMP_ORD: return FCMP_UNO;
2090 case FCMP_UNO: return FCMP_ORD;
2091 case FCMP_TRUE: return FCMP_FALSE;
2092 case FCMP_FALSE: return FCMP_TRUE;
2096 FCmpInst::Predicate FCmpInst::getSwappedPredicate(Predicate pred) {
2098 default: assert(!"Unknown fcmp predicate!");
2099 case FCMP_FALSE: case FCMP_TRUE:
2100 case FCMP_OEQ: case FCMP_ONE:
2101 case FCMP_UEQ: case FCMP_UNE:
2102 case FCMP_ORD: case FCMP_UNO:
2104 case FCMP_OGT: return FCMP_OLT;
2105 case FCMP_OLT: return FCMP_OGT;
2106 case FCMP_OGE: return FCMP_OLE;
2107 case FCMP_OLE: return FCMP_OGE;
2108 case FCMP_UGT: return FCMP_ULT;
2109 case FCMP_ULT: return FCMP_UGT;
2110 case FCMP_UGE: return FCMP_ULE;
2111 case FCMP_ULE: return FCMP_UGE;
2115 bool CmpInst::isUnsigned(unsigned short predicate) {
2116 switch (predicate) {
2117 default: return false;
2118 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2119 case ICmpInst::ICMP_UGE: return true;
2123 bool CmpInst::isSigned(unsigned short predicate){
2124 switch (predicate) {
2125 default: return false;
2126 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2127 case ICmpInst::ICMP_SGE: return true;
2131 bool CmpInst::isOrdered(unsigned short predicate) {
2132 switch (predicate) {
2133 default: return false;
2134 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2135 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2136 case FCmpInst::FCMP_ORD: return true;
2140 bool CmpInst::isUnordered(unsigned short predicate) {
2141 switch (predicate) {
2142 default: return false;
2143 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2144 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2145 case FCmpInst::FCMP_UNO: return true;
2149 //===----------------------------------------------------------------------===//
2150 // SwitchInst Implementation
2151 //===----------------------------------------------------------------------===//
2153 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2154 assert(Value && Default);
2155 ReservedSpace = 2+NumCases*2;
2157 OperandList = new Use[ReservedSpace];
2159 OperandList[0].init(Value, this);
2160 OperandList[1].init(Default, this);
2163 SwitchInst::SwitchInst(const SwitchInst &SI)
2164 : TerminatorInst(Instruction::Switch, new Use[SI.getNumOperands()],
2165 SI.getNumOperands()) {
2166 Use *OL = OperandList, *InOL = SI.OperandList;
2167 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2168 OL[i].init(InOL[i], this);
2169 OL[i+1].init(InOL[i+1], this);
2173 SwitchInst::~SwitchInst() {
2174 delete [] OperandList;
2178 /// addCase - Add an entry to the switch instruction...
2180 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2181 unsigned OpNo = NumOperands;
2182 if (OpNo+2 > ReservedSpace)
2183 resizeOperands(0); // Get more space!
2184 // Initialize some new operands.
2185 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2186 NumOperands = OpNo+2;
2187 OperandList[OpNo].init(OnVal, this);
2188 OperandList[OpNo+1].init(Dest, this);
2191 /// removeCase - This method removes the specified successor from the switch
2192 /// instruction. Note that this cannot be used to remove the default
2193 /// destination (successor #0).
2195 void SwitchInst::removeCase(unsigned idx) {
2196 assert(idx != 0 && "Cannot remove the default case!");
2197 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2199 unsigned NumOps = getNumOperands();
2200 Use *OL = OperandList;
2202 // Move everything after this operand down.
2204 // FIXME: we could just swap with the end of the list, then erase. However,
2205 // client might not expect this to happen. The code as it is thrashes the
2206 // use/def lists, which is kinda lame.
2207 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2209 OL[i-2+1] = OL[i+1];
2212 // Nuke the last value.
2213 OL[NumOps-2].set(0);
2214 OL[NumOps-2+1].set(0);
2215 NumOperands = NumOps-2;
2218 /// resizeOperands - resize operands - This adjusts the length of the operands
2219 /// list according to the following behavior:
2220 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2221 /// of operation. This grows the number of ops by 1.5 times.
2222 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2223 /// 3. If NumOps == NumOperands, trim the reserved space.
2225 void SwitchInst::resizeOperands(unsigned NumOps) {
2227 NumOps = getNumOperands()/2*6;
2228 } else if (NumOps*2 > NumOperands) {
2229 // No resize needed.
2230 if (ReservedSpace >= NumOps) return;
2231 } else if (NumOps == NumOperands) {
2232 if (ReservedSpace == NumOps) return;
2237 ReservedSpace = NumOps;
2238 Use *NewOps = new Use[NumOps];
2239 Use *OldOps = OperandList;
2240 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2241 NewOps[i].init(OldOps[i], this);
2245 OperandList = NewOps;
2249 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2250 return getSuccessor(idx);
2252 unsigned SwitchInst::getNumSuccessorsV() const {
2253 return getNumSuccessors();
2255 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2256 setSuccessor(idx, B);
2260 // Define these methods here so vtables don't get emitted into every translation
2261 // unit that uses these classes.
2263 GetElementPtrInst *GetElementPtrInst::clone() const {
2264 return new GetElementPtrInst(*this);
2267 BinaryOperator *BinaryOperator::clone() const {
2268 return create(getOpcode(), Ops[0], Ops[1]);
2271 CmpInst* CmpInst::clone() const {
2272 return create(getOpcode(), getPredicate(), Ops[0], Ops[1]);
2275 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
2276 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
2277 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
2278 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
2279 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
2280 CastInst *TruncInst::clone() const { return new TruncInst(*this); }
2281 CastInst *ZExtInst::clone() const { return new ZExtInst(*this); }
2282 CastInst *SExtInst::clone() const { return new SExtInst(*this); }
2283 CastInst *FPTruncInst::clone() const { return new FPTruncInst(*this); }
2284 CastInst *FPExtInst::clone() const { return new FPExtInst(*this); }
2285 CastInst *UIToFPInst::clone() const { return new UIToFPInst(*this); }
2286 CastInst *SIToFPInst::clone() const { return new SIToFPInst(*this); }
2287 CastInst *FPToUIInst::clone() const { return new FPToUIInst(*this); }
2288 CastInst *FPToSIInst::clone() const { return new FPToSIInst(*this); }
2289 CastInst *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
2290 CastInst *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
2291 CastInst *BitCastInst::clone() const { return new BitCastInst(*this); }
2292 CallInst *CallInst::clone() const { return new CallInst(*this); }
2293 SelectInst *SelectInst::clone() const { return new SelectInst(*this); }
2294 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
2296 ExtractElementInst *ExtractElementInst::clone() const {
2297 return new ExtractElementInst(*this);
2299 InsertElementInst *InsertElementInst::clone() const {
2300 return new InsertElementInst(*this);
2302 ShuffleVectorInst *ShuffleVectorInst::clone() const {
2303 return new ShuffleVectorInst(*this);
2305 PHINode *PHINode::clone() const { return new PHINode(*this); }
2306 ReturnInst *ReturnInst::clone() const { return new ReturnInst(*this); }
2307 BranchInst *BranchInst::clone() const { return new BranchInst(*this); }
2308 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
2309 InvokeInst *InvokeInst::clone() const { return new InvokeInst(*this); }
2310 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
2311 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}