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, const std::vector<Value*> &Params) {
200 NumOperands = Params.size()+1;
201 Use *OL = OperandList = new Use[Params.size()+1];
202 OL[0].init(Func, this);
204 const FunctionType *FTy =
205 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
207 assert((Params.size() == FTy->getNumParams() ||
208 (FTy->isVarArg() && Params.size() > FTy->getNumParams())) &&
209 "Calling a function with bad signature!");
210 for (unsigned i = 0, e = Params.size(); i != e; ++i) {
211 assert((i >= FTy->getNumParams() ||
212 FTy->getParamType(i) == Params[i]->getType()) &&
213 "Calling a function with a bad signature!");
214 OL[i+1].init(Params[i], this);
218 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
220 Use *OL = OperandList = new Use[3];
221 OL[0].init(Func, this);
222 OL[1].init(Actual1, this);
223 OL[2].init(Actual2, this);
225 const FunctionType *FTy =
226 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
228 assert((FTy->getNumParams() == 2 ||
229 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
230 "Calling a function with bad signature");
231 assert((0 >= FTy->getNumParams() ||
232 FTy->getParamType(0) == Actual1->getType()) &&
233 "Calling a function with a bad signature!");
234 assert((1 >= FTy->getNumParams() ||
235 FTy->getParamType(1) == Actual2->getType()) &&
236 "Calling a function with a bad signature!");
239 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());
248 assert((FTy->getNumParams() == 1 ||
249 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
250 "Calling a function with bad signature");
251 assert((0 == FTy->getNumParams() ||
252 FTy->getParamType(0) == Actual->getType()) &&
253 "Calling a function with a bad signature!");
256 void CallInst::init(Value *Func) {
258 Use *OL = OperandList = new Use[1];
259 OL[0].init(Func, this);
261 const FunctionType *MTy =
262 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
264 assert(MTy->getNumParams() == 0 && "Calling a function with bad signature");
267 CallInst::CallInst(Value *Func, const std::vector<Value*> &Params,
268 const std::string &Name, Instruction *InsertBefore)
269 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
270 ->getElementType())->getReturnType(),
271 Instruction::Call, 0, 0, Name, InsertBefore) {
275 CallInst::CallInst(Value *Func, const std::vector<Value*> &Params,
276 const std::string &Name, BasicBlock *InsertAtEnd)
277 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
278 ->getElementType())->getReturnType(),
279 Instruction::Call, 0, 0, Name, InsertAtEnd) {
283 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
284 const std::string &Name, Instruction *InsertBefore)
285 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
286 ->getElementType())->getReturnType(),
287 Instruction::Call, 0, 0, Name, InsertBefore) {
288 init(Func, Actual1, Actual2);
291 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
292 const std::string &Name, BasicBlock *InsertAtEnd)
293 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
294 ->getElementType())->getReturnType(),
295 Instruction::Call, 0, 0, Name, InsertAtEnd) {
296 init(Func, Actual1, Actual2);
299 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
300 Instruction *InsertBefore)
301 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
302 ->getElementType())->getReturnType(),
303 Instruction::Call, 0, 0, Name, InsertBefore) {
307 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
308 BasicBlock *InsertAtEnd)
309 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
310 ->getElementType())->getReturnType(),
311 Instruction::Call, 0, 0, Name, InsertAtEnd) {
315 CallInst::CallInst(Value *Func, const std::string &Name,
316 Instruction *InsertBefore)
317 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
318 ->getElementType())->getReturnType(),
319 Instruction::Call, 0, 0, Name, InsertBefore) {
323 CallInst::CallInst(Value *Func, const std::string &Name,
324 BasicBlock *InsertAtEnd)
325 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
326 ->getElementType())->getReturnType(),
327 Instruction::Call, 0, 0, Name, InsertAtEnd) {
331 CallInst::CallInst(const CallInst &CI)
332 : Instruction(CI.getType(), Instruction::Call, new Use[CI.getNumOperands()],
333 CI.getNumOperands()) {
334 SubclassData = CI.SubclassData;
335 Use *OL = OperandList;
336 Use *InOL = CI.OperandList;
337 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
338 OL[i].init(InOL[i], this);
342 //===----------------------------------------------------------------------===//
343 // InvokeInst Implementation
344 //===----------------------------------------------------------------------===//
346 InvokeInst::~InvokeInst() {
347 delete [] OperandList;
350 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
351 const std::vector<Value*> &Params) {
352 NumOperands = 3+Params.size();
353 Use *OL = OperandList = new Use[3+Params.size()];
354 OL[0].init(Fn, this);
355 OL[1].init(IfNormal, this);
356 OL[2].init(IfException, this);
357 const FunctionType *FTy =
358 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
360 assert((Params.size() == FTy->getNumParams()) ||
361 (FTy->isVarArg() && Params.size() > FTy->getNumParams()) &&
362 "Calling a function with bad signature");
364 for (unsigned i = 0, e = Params.size(); i != e; i++) {
365 assert((i >= FTy->getNumParams() ||
366 FTy->getParamType(i) == Params[i]->getType()) &&
367 "Invoking a function with a bad signature!");
369 OL[i+3].init(Params[i], this);
373 InvokeInst::InvokeInst(Value *Fn, BasicBlock *IfNormal,
374 BasicBlock *IfException,
375 const std::vector<Value*> &Params,
376 const std::string &Name, Instruction *InsertBefore)
377 : TerminatorInst(cast<FunctionType>(cast<PointerType>(Fn->getType())
378 ->getElementType())->getReturnType(),
379 Instruction::Invoke, 0, 0, Name, InsertBefore) {
380 init(Fn, IfNormal, IfException, Params);
383 InvokeInst::InvokeInst(Value *Fn, BasicBlock *IfNormal,
384 BasicBlock *IfException,
385 const std::vector<Value*> &Params,
386 const std::string &Name, BasicBlock *InsertAtEnd)
387 : TerminatorInst(cast<FunctionType>(cast<PointerType>(Fn->getType())
388 ->getElementType())->getReturnType(),
389 Instruction::Invoke, 0, 0, Name, InsertAtEnd) {
390 init(Fn, IfNormal, IfException, Params);
393 InvokeInst::InvokeInst(const InvokeInst &II)
394 : TerminatorInst(II.getType(), Instruction::Invoke,
395 new Use[II.getNumOperands()], II.getNumOperands()) {
396 SubclassData = II.SubclassData;
397 Use *OL = OperandList, *InOL = II.OperandList;
398 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
399 OL[i].init(InOL[i], this);
402 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
403 return getSuccessor(idx);
405 unsigned InvokeInst::getNumSuccessorsV() const {
406 return getNumSuccessors();
408 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
409 return setSuccessor(idx, B);
413 //===----------------------------------------------------------------------===//
414 // ReturnInst Implementation
415 //===----------------------------------------------------------------------===//
417 void ReturnInst::init(Value *retVal) {
418 if (retVal && retVal->getType() != Type::VoidTy) {
419 assert(!isa<BasicBlock>(retVal) &&
420 "Cannot return basic block. Probably using the incorrect ctor");
422 RetVal.init(retVal, this);
426 unsigned ReturnInst::getNumSuccessorsV() const {
427 return getNumSuccessors();
430 // Out-of-line ReturnInst method, put here so the C++ compiler can choose to
431 // emit the vtable for the class in this translation unit.
432 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
433 assert(0 && "ReturnInst has no successors!");
436 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
437 assert(0 && "ReturnInst has no successors!");
443 //===----------------------------------------------------------------------===//
444 // UnwindInst Implementation
445 //===----------------------------------------------------------------------===//
447 unsigned UnwindInst::getNumSuccessorsV() const {
448 return getNumSuccessors();
451 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
452 assert(0 && "UnwindInst has no successors!");
455 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
456 assert(0 && "UnwindInst has no successors!");
461 //===----------------------------------------------------------------------===//
462 // UnreachableInst Implementation
463 //===----------------------------------------------------------------------===//
465 unsigned UnreachableInst::getNumSuccessorsV() const {
466 return getNumSuccessors();
469 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
470 assert(0 && "UnwindInst has no successors!");
473 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
474 assert(0 && "UnwindInst has no successors!");
479 //===----------------------------------------------------------------------===//
480 // BranchInst Implementation
481 //===----------------------------------------------------------------------===//
483 void BranchInst::AssertOK() {
485 assert(getCondition()->getType() == Type::Int1Ty &&
486 "May only branch on boolean predicates!");
489 BranchInst::BranchInst(const BranchInst &BI) :
490 TerminatorInst(Instruction::Br, Ops, BI.getNumOperands()) {
491 OperandList[0].init(BI.getOperand(0), this);
492 if (BI.getNumOperands() != 1) {
493 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
494 OperandList[1].init(BI.getOperand(1), this);
495 OperandList[2].init(BI.getOperand(2), this);
499 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
500 return getSuccessor(idx);
502 unsigned BranchInst::getNumSuccessorsV() const {
503 return getNumSuccessors();
505 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
506 setSuccessor(idx, B);
510 //===----------------------------------------------------------------------===//
511 // AllocationInst Implementation
512 //===----------------------------------------------------------------------===//
514 static Value *getAISize(Value *Amt) {
516 Amt = ConstantInt::get(Type::Int32Ty, 1);
518 assert(!isa<BasicBlock>(Amt) &&
519 "Passed basic block into allocation size parameter! Ue other ctor");
520 assert(Amt->getType() == Type::Int32Ty &&
521 "Malloc/Allocation array size is not a 32-bit integer!");
526 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
527 unsigned Align, const std::string &Name,
528 Instruction *InsertBefore)
529 : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
530 Name, InsertBefore), Alignment(Align) {
531 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
532 assert(Ty != Type::VoidTy && "Cannot allocate void!");
535 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
536 unsigned Align, const std::string &Name,
537 BasicBlock *InsertAtEnd)
538 : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
539 Name, InsertAtEnd), Alignment(Align) {
540 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
541 assert(Ty != Type::VoidTy && "Cannot allocate void!");
544 // Out of line virtual method, so the vtable, etc has a home.
545 AllocationInst::~AllocationInst() {
548 bool AllocationInst::isArrayAllocation() const {
549 if (ConstantInt *CUI = dyn_cast<ConstantInt>(getOperand(0)))
550 return CUI->getZExtValue() != 1;
554 const Type *AllocationInst::getAllocatedType() const {
555 return getType()->getElementType();
558 AllocaInst::AllocaInst(const AllocaInst &AI)
559 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
560 Instruction::Alloca, AI.getAlignment()) {
563 MallocInst::MallocInst(const MallocInst &MI)
564 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
565 Instruction::Malloc, MI.getAlignment()) {
568 //===----------------------------------------------------------------------===//
569 // FreeInst Implementation
570 //===----------------------------------------------------------------------===//
572 void FreeInst::AssertOK() {
573 assert(isa<PointerType>(getOperand(0)->getType()) &&
574 "Can not free something of nonpointer type!");
577 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
578 : UnaryInstruction(Type::VoidTy, Free, Ptr, "", InsertBefore) {
582 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
583 : UnaryInstruction(Type::VoidTy, Free, Ptr, "", InsertAtEnd) {
588 //===----------------------------------------------------------------------===//
589 // LoadInst Implementation
590 //===----------------------------------------------------------------------===//
592 void LoadInst::AssertOK() {
593 assert(isa<PointerType>(getOperand(0)->getType()) &&
594 "Ptr must have pointer type.");
597 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
598 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
599 Load, Ptr, Name, InsertBef) {
604 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
605 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
606 Load, Ptr, Name, InsertAE) {
611 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
612 Instruction *InsertBef)
613 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
614 Load, Ptr, Name, InsertBef) {
615 setVolatile(isVolatile);
619 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
620 BasicBlock *InsertAE)
621 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
622 Load, Ptr, Name, InsertAE) {
623 setVolatile(isVolatile);
628 //===----------------------------------------------------------------------===//
629 // StoreInst Implementation
630 //===----------------------------------------------------------------------===//
632 void StoreInst::AssertOK() {
633 assert(isa<PointerType>(getOperand(1)->getType()) &&
634 "Ptr must have pointer type!");
635 assert(getOperand(0)->getType() ==
636 cast<PointerType>(getOperand(1)->getType())->getElementType()
637 && "Ptr must be a pointer to Val type!");
641 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
642 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertBefore) {
643 Ops[0].init(val, this);
644 Ops[1].init(addr, this);
649 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
650 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertAtEnd) {
651 Ops[0].init(val, this);
652 Ops[1].init(addr, this);
657 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
658 Instruction *InsertBefore)
659 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertBefore) {
660 Ops[0].init(val, this);
661 Ops[1].init(addr, this);
662 setVolatile(isVolatile);
666 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
667 BasicBlock *InsertAtEnd)
668 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertAtEnd) {
669 Ops[0].init(val, this);
670 Ops[1].init(addr, this);
671 setVolatile(isVolatile);
675 //===----------------------------------------------------------------------===//
676 // GetElementPtrInst Implementation
677 //===----------------------------------------------------------------------===//
679 // checkType - Simple wrapper function to give a better assertion failure
680 // message on bad indexes for a gep instruction.
682 static inline const Type *checkType(const Type *Ty) {
683 assert(Ty && "Invalid GetElementPtrInst indices for type!");
687 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx) {
688 NumOperands = 1+NumIdx;
689 Use *OL = OperandList = new Use[NumOperands];
690 OL[0].init(Ptr, this);
692 for (unsigned i = 0; i != NumIdx; ++i)
693 OL[i+1].init(Idx[i], this);
696 void GetElementPtrInst::init(Value *Ptr, Value *Idx0, Value *Idx1) {
698 Use *OL = OperandList = new Use[3];
699 OL[0].init(Ptr, this);
700 OL[1].init(Idx0, this);
701 OL[2].init(Idx1, this);
704 void GetElementPtrInst::init(Value *Ptr, Value *Idx) {
706 Use *OL = OperandList = new Use[2];
707 OL[0].init(Ptr, this);
708 OL[1].init(Idx, this);
711 GetElementPtrInst::GetElementPtrInst(Value *Ptr, const std::vector<Value*> &Idx,
712 const std::string &Name, Instruction *InBe)
713 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
715 GetElementPtr, 0, 0, Name, InBe) {
716 init(Ptr, &Idx[0], Idx.size());
719 GetElementPtrInst::GetElementPtrInst(Value *Ptr, const std::vector<Value*> &Idx,
720 const std::string &Name, BasicBlock *IAE)
721 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
723 GetElementPtr, 0, 0, Name, IAE) {
724 init(Ptr, &Idx[0], Idx.size());
727 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value* const *Idx,
729 const std::string &Name, Instruction *InBe)
730 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
732 GetElementPtr, 0, 0, Name, InBe) {
733 init(Ptr, Idx, NumIdx);
736 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value* const *Idx,
738 const std::string &Name, BasicBlock *IAE)
739 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
741 GetElementPtr, 0, 0, Name, IAE) {
742 init(Ptr, Idx, NumIdx);
745 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
746 const std::string &Name, Instruction *InBe)
747 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx))),
748 GetElementPtr, 0, 0, Name, InBe) {
752 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
753 const std::string &Name, BasicBlock *IAE)
754 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx))),
755 GetElementPtr, 0, 0, Name, IAE) {
759 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
760 const std::string &Name, Instruction *InBe)
761 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
763 GetElementPtr, 0, 0, Name, InBe) {
764 init(Ptr, Idx0, Idx1);
767 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
768 const std::string &Name, BasicBlock *IAE)
769 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
771 GetElementPtr, 0, 0, Name, IAE) {
772 init(Ptr, Idx0, Idx1);
775 GetElementPtrInst::~GetElementPtrInst() {
776 delete[] OperandList;
779 // getIndexedType - Returns the type of the element that would be loaded with
780 // a load instruction with the specified parameters.
782 // A null type is returned if the indices are invalid for the specified
785 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
788 bool AllowCompositeLeaf) {
789 if (!isa<PointerType>(Ptr)) return 0; // Type isn't a pointer type!
791 // Handle the special case of the empty set index set...
793 if (AllowCompositeLeaf ||
794 cast<PointerType>(Ptr)->getElementType()->isFirstClassType())
795 return cast<PointerType>(Ptr)->getElementType();
800 while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
801 if (NumIdx == CurIdx) {
802 if (AllowCompositeLeaf || CT->isFirstClassType()) return Ptr;
803 return 0; // Can't load a whole structure or array!?!?
806 Value *Index = Idxs[CurIdx++];
807 if (isa<PointerType>(CT) && CurIdx != 1)
808 return 0; // Can only index into pointer types at the first index!
809 if (!CT->indexValid(Index)) return 0;
810 Ptr = CT->getTypeAtIndex(Index);
812 // If the new type forwards to another type, then it is in the middle
813 // of being refined to another type (and hence, may have dropped all
814 // references to what it was using before). So, use the new forwarded
816 if (const Type * Ty = Ptr->getForwardedType()) {
820 return CurIdx == NumIdx ? Ptr : 0;
823 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
824 Value *Idx0, Value *Idx1,
825 bool AllowCompositeLeaf) {
826 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
827 if (!PTy) return 0; // Type isn't a pointer type!
829 // Check the pointer index.
830 if (!PTy->indexValid(Idx0)) return 0;
832 const CompositeType *CT = dyn_cast<CompositeType>(PTy->getElementType());
833 if (!CT || !CT->indexValid(Idx1)) return 0;
835 const Type *ElTy = CT->getTypeAtIndex(Idx1);
836 if (AllowCompositeLeaf || ElTy->isFirstClassType())
841 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
842 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
843 if (!PTy) return 0; // Type isn't a pointer type!
845 // Check the pointer index.
846 if (!PTy->indexValid(Idx)) return 0;
848 return PTy->getElementType();
851 //===----------------------------------------------------------------------===//
852 // ExtractElementInst Implementation
853 //===----------------------------------------------------------------------===//
855 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
856 const std::string &Name,
857 Instruction *InsertBef)
858 : Instruction(cast<PackedType>(Val->getType())->getElementType(),
859 ExtractElement, Ops, 2, Name, InsertBef) {
860 assert(isValidOperands(Val, Index) &&
861 "Invalid extractelement instruction operands!");
862 Ops[0].init(Val, this);
863 Ops[1].init(Index, this);
866 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
867 const std::string &Name,
868 Instruction *InsertBef)
869 : Instruction(cast<PackedType>(Val->getType())->getElementType(),
870 ExtractElement, Ops, 2, Name, InsertBef) {
871 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
872 assert(isValidOperands(Val, Index) &&
873 "Invalid extractelement instruction operands!");
874 Ops[0].init(Val, this);
875 Ops[1].init(Index, this);
879 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
880 const std::string &Name,
881 BasicBlock *InsertAE)
882 : Instruction(cast<PackedType>(Val->getType())->getElementType(),
883 ExtractElement, Ops, 2, Name, InsertAE) {
884 assert(isValidOperands(Val, Index) &&
885 "Invalid extractelement instruction operands!");
887 Ops[0].init(Val, this);
888 Ops[1].init(Index, this);
891 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
892 const std::string &Name,
893 BasicBlock *InsertAE)
894 : Instruction(cast<PackedType>(Val->getType())->getElementType(),
895 ExtractElement, Ops, 2, Name, InsertAE) {
896 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
897 assert(isValidOperands(Val, Index) &&
898 "Invalid extractelement instruction operands!");
900 Ops[0].init(Val, this);
901 Ops[1].init(Index, this);
905 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
906 if (!isa<PackedType>(Val->getType()) || Index->getType() != Type::Int32Ty)
912 //===----------------------------------------------------------------------===//
913 // InsertElementInst Implementation
914 //===----------------------------------------------------------------------===//
916 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
917 : Instruction(IE.getType(), InsertElement, Ops, 3) {
918 Ops[0].init(IE.Ops[0], this);
919 Ops[1].init(IE.Ops[1], this);
920 Ops[2].init(IE.Ops[2], this);
922 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
923 const std::string &Name,
924 Instruction *InsertBef)
925 : Instruction(Vec->getType(), InsertElement, Ops, 3, Name, InsertBef) {
926 assert(isValidOperands(Vec, Elt, Index) &&
927 "Invalid insertelement instruction operands!");
928 Ops[0].init(Vec, this);
929 Ops[1].init(Elt, this);
930 Ops[2].init(Index, this);
933 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
934 const std::string &Name,
935 Instruction *InsertBef)
936 : Instruction(Vec->getType(), InsertElement, Ops, 3, Name, InsertBef) {
937 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
938 assert(isValidOperands(Vec, Elt, Index) &&
939 "Invalid insertelement instruction operands!");
940 Ops[0].init(Vec, this);
941 Ops[1].init(Elt, this);
942 Ops[2].init(Index, this);
946 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
947 const std::string &Name,
948 BasicBlock *InsertAE)
949 : Instruction(Vec->getType(), InsertElement, Ops, 3, Name, InsertAE) {
950 assert(isValidOperands(Vec, Elt, Index) &&
951 "Invalid insertelement instruction operands!");
953 Ops[0].init(Vec, this);
954 Ops[1].init(Elt, this);
955 Ops[2].init(Index, this);
958 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
959 const std::string &Name,
960 BasicBlock *InsertAE)
961 : Instruction(Vec->getType(), InsertElement, Ops, 3, Name, InsertAE) {
962 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
963 assert(isValidOperands(Vec, Elt, Index) &&
964 "Invalid insertelement instruction operands!");
966 Ops[0].init(Vec, this);
967 Ops[1].init(Elt, this);
968 Ops[2].init(Index, this);
971 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
972 const Value *Index) {
973 if (!isa<PackedType>(Vec->getType()))
974 return false; // First operand of insertelement must be packed type.
976 if (Elt->getType() != cast<PackedType>(Vec->getType())->getElementType())
977 return false;// Second operand of insertelement must be packed element type.
979 if (Index->getType() != Type::Int32Ty)
980 return false; // Third operand of insertelement must be uint.
985 //===----------------------------------------------------------------------===//
986 // ShuffleVectorInst Implementation
987 //===----------------------------------------------------------------------===//
989 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
990 : Instruction(SV.getType(), ShuffleVector, Ops, 3) {
991 Ops[0].init(SV.Ops[0], this);
992 Ops[1].init(SV.Ops[1], this);
993 Ops[2].init(SV.Ops[2], this);
996 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
997 const std::string &Name,
998 Instruction *InsertBefore)
999 : Instruction(V1->getType(), ShuffleVector, Ops, 3, Name, InsertBefore) {
1000 assert(isValidOperands(V1, V2, Mask) &&
1001 "Invalid shuffle vector instruction operands!");
1002 Ops[0].init(V1, this);
1003 Ops[1].init(V2, this);
1004 Ops[2].init(Mask, this);
1007 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1008 const std::string &Name,
1009 BasicBlock *InsertAtEnd)
1010 : Instruction(V1->getType(), ShuffleVector, Ops, 3, Name, InsertAtEnd) {
1011 assert(isValidOperands(V1, V2, Mask) &&
1012 "Invalid shuffle vector instruction operands!");
1014 Ops[0].init(V1, this);
1015 Ops[1].init(V2, this);
1016 Ops[2].init(Mask, this);
1019 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1020 const Value *Mask) {
1021 if (!isa<PackedType>(V1->getType())) return false;
1022 if (V1->getType() != V2->getType()) return false;
1023 if (!isa<PackedType>(Mask->getType()) ||
1024 cast<PackedType>(Mask->getType())->getElementType() != Type::Int32Ty ||
1025 cast<PackedType>(Mask->getType())->getNumElements() !=
1026 cast<PackedType>(V1->getType())->getNumElements())
1032 //===----------------------------------------------------------------------===//
1033 // BinaryOperator Class
1034 //===----------------------------------------------------------------------===//
1036 void BinaryOperator::init(BinaryOps iType)
1038 Value *LHS = getOperand(0), *RHS = getOperand(1);
1039 assert(LHS->getType() == RHS->getType() &&
1040 "Binary operator operand types must match!");
1045 assert(getType() == LHS->getType() &&
1046 "Arithmetic operation should return same type as operands!");
1047 assert((getType()->isInteger() || getType()->isFloatingPoint() ||
1048 isa<PackedType>(getType())) &&
1049 "Tried to create an arithmetic operation on a non-arithmetic type!");
1053 assert(getType() == LHS->getType() &&
1054 "Arithmetic operation should return same type as operands!");
1055 assert((getType()->isInteger() || (isa<PackedType>(getType()) &&
1056 cast<PackedType>(getType())->getElementType()->isInteger())) &&
1057 "Incorrect operand type (not integer) for S/UDIV");
1060 assert(getType() == LHS->getType() &&
1061 "Arithmetic operation should return same type as operands!");
1062 assert((getType()->isFloatingPoint() || (isa<PackedType>(getType()) &&
1063 cast<PackedType>(getType())->getElementType()->isFloatingPoint()))
1064 && "Incorrect operand type (not floating point) for FDIV");
1068 assert(getType() == LHS->getType() &&
1069 "Arithmetic operation should return same type as operands!");
1070 assert((getType()->isInteger() || (isa<PackedType>(getType()) &&
1071 cast<PackedType>(getType())->getElementType()->isInteger())) &&
1072 "Incorrect operand type (not integer) for S/UREM");
1075 assert(getType() == LHS->getType() &&
1076 "Arithmetic operation should return same type as operands!");
1077 assert((getType()->isFloatingPoint() || (isa<PackedType>(getType()) &&
1078 cast<PackedType>(getType())->getElementType()->isFloatingPoint()))
1079 && "Incorrect operand type (not floating point) for FREM");
1083 assert(getType() == LHS->getType() &&
1084 "Logical operation should return same type as operands!");
1085 assert((getType()->isInteger() ||
1086 (isa<PackedType>(getType()) &&
1087 cast<PackedType>(getType())->getElementType()->isInteger())) &&
1088 "Tried to create a logical operation on a non-integral type!");
1096 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1097 const std::string &Name,
1098 Instruction *InsertBefore) {
1099 assert(S1->getType() == S2->getType() &&
1100 "Cannot create binary operator with two operands of differing type!");
1101 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1104 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1105 const std::string &Name,
1106 BasicBlock *InsertAtEnd) {
1107 BinaryOperator *Res = create(Op, S1, S2, Name);
1108 InsertAtEnd->getInstList().push_back(Res);
1112 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1113 Instruction *InsertBefore) {
1114 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1115 return new BinaryOperator(Instruction::Sub,
1117 Op->getType(), Name, InsertBefore);
1120 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1121 BasicBlock *InsertAtEnd) {
1122 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1123 return new BinaryOperator(Instruction::Sub,
1125 Op->getType(), Name, InsertAtEnd);
1128 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1129 Instruction *InsertBefore) {
1131 if (const PackedType *PTy = dyn_cast<PackedType>(Op->getType())) {
1132 C = ConstantInt::getAllOnesValue(PTy->getElementType());
1133 C = ConstantPacked::get(std::vector<Constant*>(PTy->getNumElements(), C));
1135 C = ConstantInt::getAllOnesValue(Op->getType());
1138 return new BinaryOperator(Instruction::Xor, Op, C,
1139 Op->getType(), Name, InsertBefore);
1142 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1143 BasicBlock *InsertAtEnd) {
1145 if (const PackedType *PTy = dyn_cast<PackedType>(Op->getType())) {
1146 // Create a vector of all ones values.
1147 Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType());
1149 ConstantPacked::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1151 AllOnes = ConstantInt::getAllOnesValue(Op->getType());
1154 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1155 Op->getType(), Name, InsertAtEnd);
1159 // isConstantAllOnes - Helper function for several functions below
1160 static inline bool isConstantAllOnes(const Value *V) {
1161 return isa<ConstantInt>(V) &&cast<ConstantInt>(V)->isAllOnesValue();
1164 bool BinaryOperator::isNeg(const Value *V) {
1165 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1166 if (Bop->getOpcode() == Instruction::Sub)
1167 return Bop->getOperand(0) ==
1168 ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1172 bool BinaryOperator::isNot(const Value *V) {
1173 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1174 return (Bop->getOpcode() == Instruction::Xor &&
1175 (isConstantAllOnes(Bop->getOperand(1)) ||
1176 isConstantAllOnes(Bop->getOperand(0))));
1180 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1181 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1182 return cast<BinaryOperator>(BinOp)->getOperand(1);
1185 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1186 return getNegArgument(const_cast<Value*>(BinOp));
1189 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1190 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1191 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1192 Value *Op0 = BO->getOperand(0);
1193 Value *Op1 = BO->getOperand(1);
1194 if (isConstantAllOnes(Op0)) return Op1;
1196 assert(isConstantAllOnes(Op1));
1200 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1201 return getNotArgument(const_cast<Value*>(BinOp));
1205 // swapOperands - Exchange the two operands to this instruction. This
1206 // instruction is safe to use on any binary instruction and does not
1207 // modify the semantics of the instruction. If the instruction is
1208 // order dependent (SetLT f.e.) the opcode is changed.
1210 bool BinaryOperator::swapOperands() {
1211 if (!isCommutative())
1212 return true; // Can't commute operands
1213 std::swap(Ops[0], Ops[1]);
1217 //===----------------------------------------------------------------------===//
1219 //===----------------------------------------------------------------------===//
1221 // Just determine if this cast only deals with integral->integral conversion.
1222 bool CastInst::isIntegerCast() const {
1223 switch (getOpcode()) {
1224 default: return false;
1225 case Instruction::ZExt:
1226 case Instruction::SExt:
1227 case Instruction::Trunc:
1229 case Instruction::BitCast:
1230 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1234 bool CastInst::isLosslessCast() const {
1235 // Only BitCast can be lossless, exit fast if we're not BitCast
1236 if (getOpcode() != Instruction::BitCast)
1239 // Identity cast is always lossless
1240 const Type* SrcTy = getOperand(0)->getType();
1241 const Type* DstTy = getType();
1245 // Pointer to pointer is always lossless.
1246 if (isa<PointerType>(SrcTy))
1247 return isa<PointerType>(DstTy);
1248 return false; // Other types have no identity values
1251 /// This function determines if the CastInst does not require any bits to be
1252 /// changed in order to effect the cast. Essentially, it identifies cases where
1253 /// no code gen is necessary for the cast, hence the name no-op cast. For
1254 /// example, the following are all no-op casts:
1255 /// # bitcast uint %X, int
1256 /// # bitcast uint* %x, sbyte*
1257 /// # bitcast packed< 2 x int > %x, packed< 4 x short>
1258 /// # ptrtoint uint* %x, uint ; on 32-bit plaforms only
1259 /// @brief Determine if a cast is a no-op.
1260 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1261 switch (getOpcode()) {
1263 assert(!"Invalid CastOp");
1264 case Instruction::Trunc:
1265 case Instruction::ZExt:
1266 case Instruction::SExt:
1267 case Instruction::FPTrunc:
1268 case Instruction::FPExt:
1269 case Instruction::UIToFP:
1270 case Instruction::SIToFP:
1271 case Instruction::FPToUI:
1272 case Instruction::FPToSI:
1273 return false; // These always modify bits
1274 case Instruction::BitCast:
1275 return true; // BitCast never modifies bits.
1276 case Instruction::PtrToInt:
1277 return IntPtrTy->getPrimitiveSizeInBits() ==
1278 getType()->getPrimitiveSizeInBits();
1279 case Instruction::IntToPtr:
1280 return IntPtrTy->getPrimitiveSizeInBits() ==
1281 getOperand(0)->getType()->getPrimitiveSizeInBits();
1285 /// This function determines if a pair of casts can be eliminated and what
1286 /// opcode should be used in the elimination. This assumes that there are two
1287 /// instructions like this:
1288 /// * %F = firstOpcode SrcTy %x to MidTy
1289 /// * %S = secondOpcode MidTy %F to DstTy
1290 /// The function returns a resultOpcode so these two casts can be replaced with:
1291 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1292 /// If no such cast is permited, the function returns 0.
1293 unsigned CastInst::isEliminableCastPair(
1294 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1295 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1297 // Define the 144 possibilities for these two cast instructions. The values
1298 // in this matrix determine what to do in a given situation and select the
1299 // case in the switch below. The rows correspond to firstOp, the columns
1300 // correspond to secondOp. In looking at the table below, keep in mind
1301 // the following cast properties:
1303 // Size Compare Source Destination
1304 // Operator Src ? Size Type Sign Type Sign
1305 // -------- ------------ ------------------- ---------------------
1306 // TRUNC > Integer Any Integral Any
1307 // ZEXT < Integral Unsigned Integer Any
1308 // SEXT < Integral Signed Integer Any
1309 // FPTOUI n/a FloatPt n/a Integral Unsigned
1310 // FPTOSI n/a FloatPt n/a Integral Signed
1311 // UITOFP n/a Integral Unsigned FloatPt n/a
1312 // SITOFP n/a Integral Signed FloatPt n/a
1313 // FPTRUNC > FloatPt n/a FloatPt n/a
1314 // FPEXT < FloatPt n/a FloatPt n/a
1315 // PTRTOINT n/a Pointer n/a Integral Unsigned
1316 // INTTOPTR n/a Integral Unsigned Pointer n/a
1317 // BITCONVERT = FirstClass n/a FirstClass n/a
1319 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1320 // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
1321 // into "fptoui double to ulong", but this loses information about the range
1322 // of the produced value (we no longer know the top-part is all zeros).
1323 // Further this conversion is often much more expensive for typical hardware,
1324 // and causes issues when building libgcc. We disallow fptosi+sext for the
1326 const unsigned numCastOps =
1327 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1328 static const uint8_t CastResults[numCastOps][numCastOps] = {
1329 // T F F U S F F P I B -+
1330 // R Z S P P I I T P 2 N T |
1331 // U E E 2 2 2 2 R E I T C +- secondOp
1332 // N X X U S F F N X N 2 V |
1333 // C T T I I P P C T T P T -+
1334 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1335 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1336 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1337 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1338 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1339 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1340 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1341 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1342 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1343 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1344 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1345 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1348 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1349 [secondOp-Instruction::CastOpsBegin];
1352 // categorically disallowed
1355 // allowed, use first cast's opcode
1358 // allowed, use second cast's opcode
1361 // no-op cast in second op implies firstOp as long as the DestTy
1363 if (DstTy->isInteger())
1367 // no-op cast in second op implies firstOp as long as the DestTy
1368 // is floating point
1369 if (DstTy->isFloatingPoint())
1373 // no-op cast in first op implies secondOp as long as the SrcTy
1375 if (SrcTy->isInteger())
1379 // no-op cast in first op implies secondOp as long as the SrcTy
1380 // is a floating point
1381 if (SrcTy->isFloatingPoint())
1385 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1386 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1387 unsigned MidSize = MidTy->getPrimitiveSizeInBits();
1388 if (MidSize >= PtrSize)
1389 return Instruction::BitCast;
1393 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1394 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1395 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1396 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1397 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1398 if (SrcSize == DstSize)
1399 return Instruction::BitCast;
1400 else if (SrcSize < DstSize)
1404 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1405 return Instruction::ZExt;
1407 // fpext followed by ftrunc is allowed if the bit size returned to is
1408 // the same as the original, in which case its just a bitcast
1410 return Instruction::BitCast;
1411 return 0; // If the types are not the same we can't eliminate it.
1413 // bitcast followed by ptrtoint is allowed as long as the bitcast
1414 // is a pointer to pointer cast.
1415 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1419 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1420 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1424 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1425 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1426 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1427 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1428 if (SrcSize <= PtrSize && SrcSize == DstSize)
1429 return Instruction::BitCast;
1433 // cast combination can't happen (error in input). This is for all cases
1434 // where the MidTy is not the same for the two cast instructions.
1435 assert(!"Invalid Cast Combination");
1438 assert(!"Error in CastResults table!!!");
1444 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1445 const std::string &Name, Instruction *InsertBefore) {
1446 // Construct and return the appropriate CastInst subclass
1448 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1449 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1450 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1451 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1452 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1453 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1454 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1455 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1456 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1457 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1458 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1459 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1461 assert(!"Invalid opcode provided");
1466 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1467 const std::string &Name, BasicBlock *InsertAtEnd) {
1468 // Construct and return the appropriate CastInst subclass
1470 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1471 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1472 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1473 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1474 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1475 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1476 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1477 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1478 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1479 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1480 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1481 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1483 assert(!"Invalid opcode provided");
1488 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1489 const std::string &Name,
1490 Instruction *InsertBefore) {
1491 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1492 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1493 return create(Instruction::ZExt, S, Ty, Name, InsertBefore);
1496 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1497 const std::string &Name,
1498 BasicBlock *InsertAtEnd) {
1499 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1500 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1501 return create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
1504 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1505 const std::string &Name,
1506 Instruction *InsertBefore) {
1507 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1508 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1509 return create(Instruction::SExt, S, Ty, Name, InsertBefore);
1512 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1513 const std::string &Name,
1514 BasicBlock *InsertAtEnd) {
1515 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1516 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1517 return create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
1520 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1521 const std::string &Name,
1522 Instruction *InsertBefore) {
1523 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1524 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1525 return create(Instruction::Trunc, S, Ty, Name, InsertBefore);
1528 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1529 const std::string &Name,
1530 BasicBlock *InsertAtEnd) {
1531 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1532 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1533 return create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
1536 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1537 const std::string &Name,
1538 BasicBlock *InsertAtEnd) {
1539 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1540 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1543 if (Ty->isInteger())
1544 return create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
1545 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1548 /// @brief Create a BitCast or a PtrToInt cast instruction
1549 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1550 const std::string &Name,
1551 Instruction *InsertBefore) {
1552 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1553 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1556 if (Ty->isInteger())
1557 return create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
1558 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1561 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1562 bool isSigned, const std::string &Name,
1563 Instruction *InsertBefore) {
1564 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1565 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1566 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1567 Instruction::CastOps opcode =
1568 (SrcBits == DstBits ? Instruction::BitCast :
1569 (SrcBits > DstBits ? Instruction::Trunc :
1570 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1571 return create(opcode, C, Ty, Name, InsertBefore);
1574 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1575 bool isSigned, const std::string &Name,
1576 BasicBlock *InsertAtEnd) {
1577 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1578 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1579 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1580 Instruction::CastOps opcode =
1581 (SrcBits == DstBits ? Instruction::BitCast :
1582 (SrcBits > DstBits ? Instruction::Trunc :
1583 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1584 return create(opcode, C, Ty, Name, InsertAtEnd);
1587 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1588 const std::string &Name,
1589 Instruction *InsertBefore) {
1590 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1592 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1593 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1594 Instruction::CastOps opcode =
1595 (SrcBits == DstBits ? Instruction::BitCast :
1596 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1597 return create(opcode, C, Ty, Name, InsertBefore);
1600 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1601 const std::string &Name,
1602 BasicBlock *InsertAtEnd) {
1603 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1605 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1606 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1607 Instruction::CastOps opcode =
1608 (SrcBits == DstBits ? Instruction::BitCast :
1609 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1610 return create(opcode, C, Ty, Name, InsertAtEnd);
1613 // Provide a way to get a "cast" where the cast opcode is inferred from the
1614 // types and size of the operand. This, basically, is a parallel of the
1615 // logic in the castIsValid function below. This axiom should hold:
1616 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
1617 // should not assert in castIsValid. In other words, this produces a "correct"
1618 // casting opcode for the arguments passed to it.
1619 Instruction::CastOps
1620 CastInst::getCastOpcode(
1621 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
1622 // Get the bit sizes, we'll need these
1623 const Type *SrcTy = Src->getType();
1624 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/packed
1625 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/packed
1627 // Run through the possibilities ...
1628 if (DestTy->isInteger()) { // Casting to integral
1629 if (SrcTy->isInteger()) { // Casting from integral
1630 if (DestBits < SrcBits)
1631 return Trunc; // int -> smaller int
1632 else if (DestBits > SrcBits) { // its an extension
1634 return SExt; // signed -> SEXT
1636 return ZExt; // unsigned -> ZEXT
1638 return BitCast; // Same size, No-op cast
1640 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1642 return FPToSI; // FP -> sint
1644 return FPToUI; // FP -> uint
1645 } else if (const PackedType *PTy = dyn_cast<PackedType>(SrcTy)) {
1646 assert(DestBits == PTy->getBitWidth() &&
1647 "Casting packed to integer of different width");
1648 return BitCast; // Same size, no-op cast
1650 assert(isa<PointerType>(SrcTy) &&
1651 "Casting from a value that is not first-class type");
1652 return PtrToInt; // ptr -> int
1654 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
1655 if (SrcTy->isInteger()) { // Casting from integral
1657 return SIToFP; // sint -> FP
1659 return UIToFP; // uint -> FP
1660 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1661 if (DestBits < SrcBits) {
1662 return FPTrunc; // FP -> smaller FP
1663 } else if (DestBits > SrcBits) {
1664 return FPExt; // FP -> larger FP
1666 return BitCast; // same size, no-op cast
1668 } else if (const PackedType *PTy = dyn_cast<PackedType>(SrcTy)) {
1669 assert(DestBits == PTy->getBitWidth() &&
1670 "Casting packed to floating point of different width");
1671 return BitCast; // same size, no-op cast
1673 assert(0 && "Casting pointer or non-first class to float");
1675 } else if (const PackedType *DestPTy = dyn_cast<PackedType>(DestTy)) {
1676 if (const PackedType *SrcPTy = dyn_cast<PackedType>(SrcTy)) {
1677 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
1678 "Casting packed to packed of different widths");
1679 return BitCast; // packed -> packed
1680 } else if (DestPTy->getBitWidth() == SrcBits) {
1681 return BitCast; // float/int -> packed
1683 assert(!"Illegal cast to packed (wrong type or size)");
1685 } else if (isa<PointerType>(DestTy)) {
1686 if (isa<PointerType>(SrcTy)) {
1687 return BitCast; // ptr -> ptr
1688 } else if (SrcTy->isInteger()) {
1689 return IntToPtr; // int -> ptr
1691 assert(!"Casting pointer to other than pointer or int");
1694 assert(!"Casting to type that is not first-class");
1697 // If we fall through to here we probably hit an assertion cast above
1698 // and assertions are not turned on. Anything we return is an error, so
1699 // BitCast is as good a choice as any.
1703 //===----------------------------------------------------------------------===//
1704 // CastInst SubClass Constructors
1705 //===----------------------------------------------------------------------===//
1707 /// Check that the construction parameters for a CastInst are correct. This
1708 /// could be broken out into the separate constructors but it is useful to have
1709 /// it in one place and to eliminate the redundant code for getting the sizes
1710 /// of the types involved.
1712 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
1714 // Check for type sanity on the arguments
1715 const Type *SrcTy = S->getType();
1716 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
1719 // Get the size of the types in bits, we'll need this later
1720 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1721 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1723 // Switch on the opcode provided
1725 default: return false; // This is an input error
1726 case Instruction::Trunc:
1727 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize > DstBitSize;
1728 case Instruction::ZExt:
1729 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
1730 case Instruction::SExt:
1731 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
1732 case Instruction::FPTrunc:
1733 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
1734 SrcBitSize > DstBitSize;
1735 case Instruction::FPExt:
1736 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
1737 SrcBitSize < DstBitSize;
1738 case Instruction::UIToFP:
1739 return SrcTy->isInteger() && DstTy->isFloatingPoint();
1740 case Instruction::SIToFP:
1741 return SrcTy->isInteger() && DstTy->isFloatingPoint();
1742 case Instruction::FPToUI:
1743 return SrcTy->isFloatingPoint() && DstTy->isInteger();
1744 case Instruction::FPToSI:
1745 return SrcTy->isFloatingPoint() && DstTy->isInteger();
1746 case Instruction::PtrToInt:
1747 return isa<PointerType>(SrcTy) && DstTy->isInteger();
1748 case Instruction::IntToPtr:
1749 return SrcTy->isInteger() && isa<PointerType>(DstTy);
1750 case Instruction::BitCast:
1751 // BitCast implies a no-op cast of type only. No bits change.
1752 // However, you can't cast pointers to anything but pointers.
1753 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
1756 // Now we know we're not dealing with a pointer/non-poiner mismatch. In all
1757 // these cases, the cast is okay if the source and destination bit widths
1759 return SrcBitSize == DstBitSize;
1763 TruncInst::TruncInst(
1764 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1765 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
1766 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
1769 TruncInst::TruncInst(
1770 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1771 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
1772 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
1776 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1777 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
1778 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
1782 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1783 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
1784 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
1787 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1788 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
1789 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
1793 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1794 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
1795 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
1798 FPTruncInst::FPTruncInst(
1799 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1800 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
1801 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
1804 FPTruncInst::FPTruncInst(
1805 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1806 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
1807 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
1810 FPExtInst::FPExtInst(
1811 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1812 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
1813 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
1816 FPExtInst::FPExtInst(
1817 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1818 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
1819 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
1822 UIToFPInst::UIToFPInst(
1823 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1824 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
1825 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
1828 UIToFPInst::UIToFPInst(
1829 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1830 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
1831 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
1834 SIToFPInst::SIToFPInst(
1835 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1836 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
1837 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
1840 SIToFPInst::SIToFPInst(
1841 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1842 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
1843 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
1846 FPToUIInst::FPToUIInst(
1847 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1848 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
1849 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
1852 FPToUIInst::FPToUIInst(
1853 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1854 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
1855 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
1858 FPToSIInst::FPToSIInst(
1859 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1860 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
1861 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
1864 FPToSIInst::FPToSIInst(
1865 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1866 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
1867 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
1870 PtrToIntInst::PtrToIntInst(
1871 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1872 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
1873 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
1876 PtrToIntInst::PtrToIntInst(
1877 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1878 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
1879 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
1882 IntToPtrInst::IntToPtrInst(
1883 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1884 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
1885 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
1888 IntToPtrInst::IntToPtrInst(
1889 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1890 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
1891 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
1894 BitCastInst::BitCastInst(
1895 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1896 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
1897 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
1900 BitCastInst::BitCastInst(
1901 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1902 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
1903 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
1906 //===----------------------------------------------------------------------===//
1908 //===----------------------------------------------------------------------===//
1910 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
1911 const std::string &Name, Instruction *InsertBefore)
1912 : Instruction(Type::Int1Ty, op, Ops, 2, Name, InsertBefore) {
1913 Ops[0].init(LHS, this);
1914 Ops[1].init(RHS, this);
1915 SubclassData = predicate;
1916 if (op == Instruction::ICmp) {
1917 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
1918 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
1919 "Invalid ICmp predicate value");
1920 const Type* Op0Ty = getOperand(0)->getType();
1921 const Type* Op1Ty = getOperand(1)->getType();
1922 assert(Op0Ty == Op1Ty &&
1923 "Both operands to ICmp instruction are not of the same type!");
1924 // Check that the operands are the right type
1925 assert((Op0Ty->isInteger() || isa<PointerType>(Op0Ty)) &&
1926 "Invalid operand types for ICmp instruction");
1929 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
1930 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
1931 "Invalid FCmp predicate value");
1932 const Type* Op0Ty = getOperand(0)->getType();
1933 const Type* Op1Ty = getOperand(1)->getType();
1934 assert(Op0Ty == Op1Ty &&
1935 "Both operands to FCmp instruction are not of the same type!");
1936 // Check that the operands are the right type
1937 assert(Op0Ty->isFloatingPoint() &&
1938 "Invalid operand types for FCmp instruction");
1941 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
1942 const std::string &Name, BasicBlock *InsertAtEnd)
1943 : Instruction(Type::Int1Ty, op, Ops, 2, Name, InsertAtEnd) {
1944 Ops[0].init(LHS, this);
1945 Ops[1].init(RHS, this);
1946 SubclassData = predicate;
1947 if (op == Instruction::ICmp) {
1948 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
1949 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
1950 "Invalid ICmp predicate value");
1952 const Type* Op0Ty = getOperand(0)->getType();
1953 const Type* Op1Ty = getOperand(1)->getType();
1954 assert(Op0Ty == Op1Ty &&
1955 "Both operands to ICmp instruction are not of the same type!");
1956 // Check that the operands are the right type
1957 assert(Op0Ty->isInteger() || isa<PointerType>(Op0Ty) &&
1958 "Invalid operand types for ICmp instruction");
1961 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
1962 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
1963 "Invalid FCmp predicate value");
1964 const Type* Op0Ty = getOperand(0)->getType();
1965 const Type* Op1Ty = getOperand(1)->getType();
1966 assert(Op0Ty == Op1Ty &&
1967 "Both operands to FCmp instruction are not of the same type!");
1968 // Check that the operands are the right type
1969 assert(Op0Ty->isFloatingPoint() &&
1970 "Invalid operand types for FCmp instruction");
1974 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
1975 const std::string &Name, Instruction *InsertBefore) {
1976 if (Op == Instruction::ICmp) {
1977 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
1980 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
1985 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
1986 const std::string &Name, BasicBlock *InsertAtEnd) {
1987 if (Op == Instruction::ICmp) {
1988 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
1991 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
1995 void CmpInst::swapOperands() {
1996 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
1999 cast<FCmpInst>(this)->swapOperands();
2002 bool CmpInst::isCommutative() {
2003 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2004 return IC->isCommutative();
2005 return cast<FCmpInst>(this)->isCommutative();
2008 bool CmpInst::isEquality() {
2009 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2010 return IC->isEquality();
2011 return cast<FCmpInst>(this)->isEquality();
2015 ICmpInst::Predicate ICmpInst::getInversePredicate(Predicate pred) {
2018 assert(!"Unknown icmp predicate!");
2019 case ICMP_EQ: return ICMP_NE;
2020 case ICMP_NE: return ICMP_EQ;
2021 case ICMP_UGT: return ICMP_ULE;
2022 case ICMP_ULT: return ICMP_UGE;
2023 case ICMP_UGE: return ICMP_ULT;
2024 case ICMP_ULE: return ICMP_UGT;
2025 case ICMP_SGT: return ICMP_SLE;
2026 case ICMP_SLT: return ICMP_SGE;
2027 case ICMP_SGE: return ICMP_SLT;
2028 case ICMP_SLE: return ICMP_SGT;
2032 ICmpInst::Predicate ICmpInst::getSwappedPredicate(Predicate pred) {
2034 default: assert(! "Unknown icmp predicate!");
2035 case ICMP_EQ: case ICMP_NE:
2037 case ICMP_SGT: return ICMP_SLT;
2038 case ICMP_SLT: return ICMP_SGT;
2039 case ICMP_SGE: return ICMP_SLE;
2040 case ICMP_SLE: return ICMP_SGE;
2041 case ICMP_UGT: return ICMP_ULT;
2042 case ICMP_ULT: return ICMP_UGT;
2043 case ICMP_UGE: return ICMP_ULE;
2044 case ICMP_ULE: return ICMP_UGE;
2048 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2050 default: assert(! "Unknown icmp predicate!");
2051 case ICMP_EQ: case ICMP_NE:
2052 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2054 case ICMP_UGT: return ICMP_SGT;
2055 case ICMP_ULT: return ICMP_SLT;
2056 case ICMP_UGE: return ICMP_SGE;
2057 case ICMP_ULE: return ICMP_SLE;
2061 bool ICmpInst::isSignedPredicate(Predicate pred) {
2063 default: assert(! "Unknown icmp predicate!");
2064 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2066 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2067 case ICMP_UGE: case ICMP_ULE:
2072 FCmpInst::Predicate FCmpInst::getInversePredicate(Predicate pred) {
2075 assert(!"Unknown icmp predicate!");
2076 case FCMP_OEQ: return FCMP_UNE;
2077 case FCMP_ONE: return FCMP_UEQ;
2078 case FCMP_OGT: return FCMP_ULE;
2079 case FCMP_OLT: return FCMP_UGE;
2080 case FCMP_OGE: return FCMP_ULT;
2081 case FCMP_OLE: return FCMP_UGT;
2082 case FCMP_UEQ: return FCMP_ONE;
2083 case FCMP_UNE: return FCMP_OEQ;
2084 case FCMP_UGT: return FCMP_OLE;
2085 case FCMP_ULT: return FCMP_OGE;
2086 case FCMP_UGE: return FCMP_OLT;
2087 case FCMP_ULE: return FCMP_OGT;
2088 case FCMP_ORD: return FCMP_UNO;
2089 case FCMP_UNO: return FCMP_ORD;
2090 case FCMP_TRUE: return FCMP_FALSE;
2091 case FCMP_FALSE: return FCMP_TRUE;
2095 FCmpInst::Predicate FCmpInst::getSwappedPredicate(Predicate pred) {
2097 default: assert(!"Unknown fcmp predicate!");
2098 case FCMP_FALSE: case FCMP_TRUE:
2099 case FCMP_OEQ: case FCMP_ONE:
2100 case FCMP_UEQ: case FCMP_UNE:
2101 case FCMP_ORD: case FCMP_UNO:
2103 case FCMP_OGT: return FCMP_OLT;
2104 case FCMP_OLT: return FCMP_OGT;
2105 case FCMP_OGE: return FCMP_OLE;
2106 case FCMP_OLE: return FCMP_OGE;
2107 case FCMP_UGT: return FCMP_ULT;
2108 case FCMP_ULT: return FCMP_UGT;
2109 case FCMP_UGE: return FCMP_ULE;
2110 case FCMP_ULE: return FCMP_UGE;
2114 bool CmpInst::isUnsigned(unsigned short predicate) {
2115 switch (predicate) {
2116 default: return false;
2117 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2118 case ICmpInst::ICMP_UGE: return true;
2122 bool CmpInst::isSigned(unsigned short predicate){
2123 switch (predicate) {
2124 default: return false;
2125 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2126 case ICmpInst::ICMP_SGE: return true;
2130 bool CmpInst::isOrdered(unsigned short predicate) {
2131 switch (predicate) {
2132 default: return false;
2133 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2134 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2135 case FCmpInst::FCMP_ORD: return true;
2139 bool CmpInst::isUnordered(unsigned short predicate) {
2140 switch (predicate) {
2141 default: return false;
2142 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2143 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2144 case FCmpInst::FCMP_UNO: return true;
2148 //===----------------------------------------------------------------------===//
2149 // SwitchInst Implementation
2150 //===----------------------------------------------------------------------===//
2152 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2153 assert(Value && Default);
2154 ReservedSpace = 2+NumCases*2;
2156 OperandList = new Use[ReservedSpace];
2158 OperandList[0].init(Value, this);
2159 OperandList[1].init(Default, this);
2162 SwitchInst::SwitchInst(const SwitchInst &SI)
2163 : TerminatorInst(Instruction::Switch, new Use[SI.getNumOperands()],
2164 SI.getNumOperands()) {
2165 Use *OL = OperandList, *InOL = SI.OperandList;
2166 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2167 OL[i].init(InOL[i], this);
2168 OL[i+1].init(InOL[i+1], this);
2172 SwitchInst::~SwitchInst() {
2173 delete [] OperandList;
2177 /// addCase - Add an entry to the switch instruction...
2179 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2180 unsigned OpNo = NumOperands;
2181 if (OpNo+2 > ReservedSpace)
2182 resizeOperands(0); // Get more space!
2183 // Initialize some new operands.
2184 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2185 NumOperands = OpNo+2;
2186 OperandList[OpNo].init(OnVal, this);
2187 OperandList[OpNo+1].init(Dest, this);
2190 /// removeCase - This method removes the specified successor from the switch
2191 /// instruction. Note that this cannot be used to remove the default
2192 /// destination (successor #0).
2194 void SwitchInst::removeCase(unsigned idx) {
2195 assert(idx != 0 && "Cannot remove the default case!");
2196 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2198 unsigned NumOps = getNumOperands();
2199 Use *OL = OperandList;
2201 // Move everything after this operand down.
2203 // FIXME: we could just swap with the end of the list, then erase. However,
2204 // client might not expect this to happen. The code as it is thrashes the
2205 // use/def lists, which is kinda lame.
2206 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2208 OL[i-2+1] = OL[i+1];
2211 // Nuke the last value.
2212 OL[NumOps-2].set(0);
2213 OL[NumOps-2+1].set(0);
2214 NumOperands = NumOps-2;
2217 /// resizeOperands - resize operands - This adjusts the length of the operands
2218 /// list according to the following behavior:
2219 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2220 /// of operation. This grows the number of ops by 1.5 times.
2221 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2222 /// 3. If NumOps == NumOperands, trim the reserved space.
2224 void SwitchInst::resizeOperands(unsigned NumOps) {
2226 NumOps = getNumOperands()/2*6;
2227 } else if (NumOps*2 > NumOperands) {
2228 // No resize needed.
2229 if (ReservedSpace >= NumOps) return;
2230 } else if (NumOps == NumOperands) {
2231 if (ReservedSpace == NumOps) return;
2236 ReservedSpace = NumOps;
2237 Use *NewOps = new Use[NumOps];
2238 Use *OldOps = OperandList;
2239 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2240 NewOps[i].init(OldOps[i], this);
2244 OperandList = NewOps;
2248 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2249 return getSuccessor(idx);
2251 unsigned SwitchInst::getNumSuccessorsV() const {
2252 return getNumSuccessors();
2254 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2255 setSuccessor(idx, B);
2259 // Define these methods here so vtables don't get emitted into every translation
2260 // unit that uses these classes.
2262 GetElementPtrInst *GetElementPtrInst::clone() const {
2263 return new GetElementPtrInst(*this);
2266 BinaryOperator *BinaryOperator::clone() const {
2267 return create(getOpcode(), Ops[0], Ops[1]);
2270 CmpInst* CmpInst::clone() const {
2271 return create(getOpcode(), getPredicate(), Ops[0], Ops[1]);
2274 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
2275 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
2276 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
2277 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
2278 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
2279 CastInst *TruncInst::clone() const { return new TruncInst(*this); }
2280 CastInst *ZExtInst::clone() const { return new ZExtInst(*this); }
2281 CastInst *SExtInst::clone() const { return new SExtInst(*this); }
2282 CastInst *FPTruncInst::clone() const { return new FPTruncInst(*this); }
2283 CastInst *FPExtInst::clone() const { return new FPExtInst(*this); }
2284 CastInst *UIToFPInst::clone() const { return new UIToFPInst(*this); }
2285 CastInst *SIToFPInst::clone() const { return new SIToFPInst(*this); }
2286 CastInst *FPToUIInst::clone() const { return new FPToUIInst(*this); }
2287 CastInst *FPToSIInst::clone() const { return new FPToSIInst(*this); }
2288 CastInst *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
2289 CastInst *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
2290 CastInst *BitCastInst::clone() const { return new BitCastInst(*this); }
2291 CallInst *CallInst::clone() const { return new CallInst(*this); }
2292 ShiftInst *ShiftInst::clone() const { return new ShiftInst(*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();}