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::BoolTy &&
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::UIntTy, 1);
518 assert(!isa<BasicBlock>(Amt) &&
519 "Passed basic block into allocation size parameter! Ue other ctor");
520 assert(Amt->getType() == Type::UIntTy &&
521 "Malloc/Allocation array size != UIntTy!");
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, const std::vector<Value*> &Idx) {
688 NumOperands = 1+Idx.size();
689 Use *OL = OperandList = new Use[NumOperands];
690 OL[0].init(Ptr, this);
692 for (unsigned i = 0, e = Idx.size(); i != e; ++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) {
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) {
727 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
728 const std::string &Name, Instruction *InBe)
729 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx))),
730 GetElementPtr, 0, 0, Name, InBe) {
734 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
735 const std::string &Name, BasicBlock *IAE)
736 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx))),
737 GetElementPtr, 0, 0, Name, IAE) {
741 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
742 const std::string &Name, Instruction *InBe)
743 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
745 GetElementPtr, 0, 0, Name, InBe) {
746 init(Ptr, Idx0, Idx1);
749 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
750 const std::string &Name, BasicBlock *IAE)
751 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
753 GetElementPtr, 0, 0, Name, IAE) {
754 init(Ptr, Idx0, Idx1);
757 GetElementPtrInst::~GetElementPtrInst() {
758 delete[] OperandList;
761 // getIndexedType - Returns the type of the element that would be loaded with
762 // a load instruction with the specified parameters.
764 // A null type is returned if the indices are invalid for the specified
767 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
768 const std::vector<Value*> &Idx,
769 bool AllowCompositeLeaf) {
770 if (!isa<PointerType>(Ptr)) return 0; // Type isn't a pointer type!
772 // Handle the special case of the empty set index set...
774 if (AllowCompositeLeaf ||
775 cast<PointerType>(Ptr)->getElementType()->isFirstClassType())
776 return cast<PointerType>(Ptr)->getElementType();
781 while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
782 if (Idx.size() == CurIdx) {
783 if (AllowCompositeLeaf || CT->isFirstClassType()) return Ptr;
784 return 0; // Can't load a whole structure or array!?!?
787 Value *Index = Idx[CurIdx++];
788 if (isa<PointerType>(CT) && CurIdx != 1)
789 return 0; // Can only index into pointer types at the first index!
790 if (!CT->indexValid(Index)) return 0;
791 Ptr = CT->getTypeAtIndex(Index);
793 // If the new type forwards to another type, then it is in the middle
794 // of being refined to another type (and hence, may have dropped all
795 // references to what it was using before). So, use the new forwarded
797 if (const Type * Ty = Ptr->getForwardedType()) {
801 return CurIdx == Idx.size() ? Ptr : 0;
804 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
805 Value *Idx0, Value *Idx1,
806 bool AllowCompositeLeaf) {
807 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
808 if (!PTy) return 0; // Type isn't a pointer type!
810 // Check the pointer index.
811 if (!PTy->indexValid(Idx0)) return 0;
813 const CompositeType *CT = dyn_cast<CompositeType>(PTy->getElementType());
814 if (!CT || !CT->indexValid(Idx1)) return 0;
816 const Type *ElTy = CT->getTypeAtIndex(Idx1);
817 if (AllowCompositeLeaf || ElTy->isFirstClassType())
822 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
823 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
824 if (!PTy) return 0; // Type isn't a pointer type!
826 // Check the pointer index.
827 if (!PTy->indexValid(Idx)) return 0;
829 return PTy->getElementType();
832 //===----------------------------------------------------------------------===//
833 // ExtractElementInst Implementation
834 //===----------------------------------------------------------------------===//
836 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
837 const std::string &Name,
838 Instruction *InsertBef)
839 : Instruction(cast<PackedType>(Val->getType())->getElementType(),
840 ExtractElement, Ops, 2, Name, InsertBef) {
841 assert(isValidOperands(Val, Index) &&
842 "Invalid extractelement instruction operands!");
843 Ops[0].init(Val, this);
844 Ops[1].init(Index, this);
847 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
848 const std::string &Name,
849 Instruction *InsertBef)
850 : Instruction(cast<PackedType>(Val->getType())->getElementType(),
851 ExtractElement, Ops, 2, Name, InsertBef) {
852 Constant *Index = ConstantInt::get(Type::UIntTy, IndexV);
853 assert(isValidOperands(Val, Index) &&
854 "Invalid extractelement instruction operands!");
855 Ops[0].init(Val, this);
856 Ops[1].init(Index, this);
860 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
861 const std::string &Name,
862 BasicBlock *InsertAE)
863 : Instruction(cast<PackedType>(Val->getType())->getElementType(),
864 ExtractElement, Ops, 2, Name, InsertAE) {
865 assert(isValidOperands(Val, Index) &&
866 "Invalid extractelement instruction operands!");
868 Ops[0].init(Val, this);
869 Ops[1].init(Index, this);
872 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
873 const std::string &Name,
874 BasicBlock *InsertAE)
875 : Instruction(cast<PackedType>(Val->getType())->getElementType(),
876 ExtractElement, Ops, 2, Name, InsertAE) {
877 Constant *Index = ConstantInt::get(Type::UIntTy, IndexV);
878 assert(isValidOperands(Val, Index) &&
879 "Invalid extractelement instruction operands!");
881 Ops[0].init(Val, this);
882 Ops[1].init(Index, this);
886 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
887 if (!isa<PackedType>(Val->getType()) || Index->getType() != Type::UIntTy)
893 //===----------------------------------------------------------------------===//
894 // InsertElementInst Implementation
895 //===----------------------------------------------------------------------===//
897 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
898 : Instruction(IE.getType(), InsertElement, Ops, 3) {
899 Ops[0].init(IE.Ops[0], this);
900 Ops[1].init(IE.Ops[1], this);
901 Ops[2].init(IE.Ops[2], this);
903 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
904 const std::string &Name,
905 Instruction *InsertBef)
906 : Instruction(Vec->getType(), InsertElement, Ops, 3, Name, InsertBef) {
907 assert(isValidOperands(Vec, Elt, Index) &&
908 "Invalid insertelement instruction operands!");
909 Ops[0].init(Vec, this);
910 Ops[1].init(Elt, this);
911 Ops[2].init(Index, this);
914 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
915 const std::string &Name,
916 Instruction *InsertBef)
917 : Instruction(Vec->getType(), InsertElement, Ops, 3, Name, InsertBef) {
918 Constant *Index = ConstantInt::get(Type::UIntTy, IndexV);
919 assert(isValidOperands(Vec, Elt, Index) &&
920 "Invalid insertelement instruction operands!");
921 Ops[0].init(Vec, this);
922 Ops[1].init(Elt, this);
923 Ops[2].init(Index, this);
927 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
928 const std::string &Name,
929 BasicBlock *InsertAE)
930 : Instruction(Vec->getType(), InsertElement, Ops, 3, Name, InsertAE) {
931 assert(isValidOperands(Vec, Elt, Index) &&
932 "Invalid insertelement instruction operands!");
934 Ops[0].init(Vec, this);
935 Ops[1].init(Elt, this);
936 Ops[2].init(Index, this);
939 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
940 const std::string &Name,
941 BasicBlock *InsertAE)
942 : Instruction(Vec->getType(), InsertElement, Ops, 3, Name, InsertAE) {
943 Constant *Index = ConstantInt::get(Type::UIntTy, IndexV);
944 assert(isValidOperands(Vec, Elt, Index) &&
945 "Invalid insertelement instruction operands!");
947 Ops[0].init(Vec, this);
948 Ops[1].init(Elt, this);
949 Ops[2].init(Index, this);
952 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
953 const Value *Index) {
954 if (!isa<PackedType>(Vec->getType()))
955 return false; // First operand of insertelement must be packed type.
957 if (Elt->getType() != cast<PackedType>(Vec->getType())->getElementType())
958 return false;// Second operand of insertelement must be packed element type.
960 if (Index->getType() != Type::UIntTy)
961 return false; // Third operand of insertelement must be uint.
966 //===----------------------------------------------------------------------===//
967 // ShuffleVectorInst Implementation
968 //===----------------------------------------------------------------------===//
970 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
971 : Instruction(SV.getType(), ShuffleVector, Ops, 3) {
972 Ops[0].init(SV.Ops[0], this);
973 Ops[1].init(SV.Ops[1], this);
974 Ops[2].init(SV.Ops[2], this);
977 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
978 const std::string &Name,
979 Instruction *InsertBefore)
980 : Instruction(V1->getType(), ShuffleVector, Ops, 3, Name, InsertBefore) {
981 assert(isValidOperands(V1, V2, Mask) &&
982 "Invalid shuffle vector instruction operands!");
983 Ops[0].init(V1, this);
984 Ops[1].init(V2, this);
985 Ops[2].init(Mask, this);
988 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
989 const std::string &Name,
990 BasicBlock *InsertAtEnd)
991 : Instruction(V1->getType(), ShuffleVector, Ops, 3, Name, InsertAtEnd) {
992 assert(isValidOperands(V1, V2, Mask) &&
993 "Invalid shuffle vector instruction operands!");
995 Ops[0].init(V1, this);
996 Ops[1].init(V2, this);
997 Ops[2].init(Mask, this);
1000 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1001 const Value *Mask) {
1002 if (!isa<PackedType>(V1->getType())) return false;
1003 if (V1->getType() != V2->getType()) return false;
1004 if (!isa<PackedType>(Mask->getType()) ||
1005 cast<PackedType>(Mask->getType())->getElementType() != Type::UIntTy ||
1006 cast<PackedType>(Mask->getType())->getNumElements() !=
1007 cast<PackedType>(V1->getType())->getNumElements())
1013 //===----------------------------------------------------------------------===//
1014 // BinaryOperator Class
1015 //===----------------------------------------------------------------------===//
1017 void BinaryOperator::init(BinaryOps iType)
1019 Value *LHS = getOperand(0), *RHS = getOperand(1);
1020 assert(LHS->getType() == RHS->getType() &&
1021 "Binary operator operand types must match!");
1026 assert(getType() == LHS->getType() &&
1027 "Arithmetic operation should return same type as operands!");
1028 assert((getType()->isInteger() || getType()->isFloatingPoint() ||
1029 isa<PackedType>(getType())) &&
1030 "Tried to create an arithmetic operation on a non-arithmetic type!");
1034 assert(getType() == LHS->getType() &&
1035 "Arithmetic operation should return same type as operands!");
1036 assert((getType()->isInteger() || (isa<PackedType>(getType()) &&
1037 cast<PackedType>(getType())->getElementType()->isInteger())) &&
1038 "Incorrect operand type (not integer) for S/UDIV");
1041 assert(getType() == LHS->getType() &&
1042 "Arithmetic operation should return same type as operands!");
1043 assert((getType()->isFloatingPoint() || (isa<PackedType>(getType()) &&
1044 cast<PackedType>(getType())->getElementType()->isFloatingPoint()))
1045 && "Incorrect operand type (not floating point) for FDIV");
1049 assert(getType() == LHS->getType() &&
1050 "Arithmetic operation should return same type as operands!");
1051 assert((getType()->isInteger() || (isa<PackedType>(getType()) &&
1052 cast<PackedType>(getType())->getElementType()->isInteger())) &&
1053 "Incorrect operand type (not integer) for S/UREM");
1056 assert(getType() == LHS->getType() &&
1057 "Arithmetic operation should return same type as operands!");
1058 assert((getType()->isFloatingPoint() || (isa<PackedType>(getType()) &&
1059 cast<PackedType>(getType())->getElementType()->isFloatingPoint()))
1060 && "Incorrect operand type (not floating point) for FREM");
1064 assert(getType() == LHS->getType() &&
1065 "Logical operation should return same type as operands!");
1066 assert((getType()->isIntegral() ||
1067 (isa<PackedType>(getType()) &&
1068 cast<PackedType>(getType())->getElementType()->isIntegral())) &&
1069 "Tried to create a logical operation on a non-integral type!");
1071 case SetLT: case SetGT: case SetLE:
1072 case SetGE: case SetEQ: case SetNE:
1073 assert(getType() == Type::BoolTy && "Setcc must return bool!");
1080 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1081 const std::string &Name,
1082 Instruction *InsertBefore) {
1083 assert(S1->getType() == S2->getType() &&
1084 "Cannot create binary operator with two operands of differing type!");
1086 // Binary comparison operators...
1087 case SetLT: case SetGT: case SetLE:
1088 case SetGE: case SetEQ: case SetNE:
1089 return new SetCondInst(Op, S1, S2, Name, InsertBefore);
1092 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1096 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1097 const std::string &Name,
1098 BasicBlock *InsertAtEnd) {
1099 BinaryOperator *Res = create(Op, S1, S2, Name);
1100 InsertAtEnd->getInstList().push_back(Res);
1104 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1105 Instruction *InsertBefore) {
1106 if (!Op->getType()->isFloatingPoint())
1107 return new BinaryOperator(Instruction::Sub,
1108 Constant::getNullValue(Op->getType()), Op,
1109 Op->getType(), Name, InsertBefore);
1111 return new BinaryOperator(Instruction::Sub,
1112 ConstantFP::get(Op->getType(), -0.0), Op,
1113 Op->getType(), Name, InsertBefore);
1116 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1117 BasicBlock *InsertAtEnd) {
1118 if (!Op->getType()->isFloatingPoint())
1119 return new BinaryOperator(Instruction::Sub,
1120 Constant::getNullValue(Op->getType()), Op,
1121 Op->getType(), Name, InsertAtEnd);
1123 return new BinaryOperator(Instruction::Sub,
1124 ConstantFP::get(Op->getType(), -0.0), Op,
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 = ConstantIntegral::getAllOnesValue(PTy->getElementType());
1133 C = ConstantPacked::get(std::vector<Constant*>(PTy->getNumElements(), C));
1135 C = ConstantIntegral::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 = ConstantIntegral::getAllOnesValue(PTy->getElementType());
1149 ConstantPacked::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1151 AllOnes = ConstantIntegral::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<ConstantIntegral>(V) &&cast<ConstantIntegral>(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 if (!V->getType()->isFloatingPoint())
1168 return Bop->getOperand(0) == Constant::getNullValue(Bop->getType());
1170 return Bop->getOperand(0) == ConstantFP::get(Bop->getType(), -0.0);
1174 bool BinaryOperator::isNot(const Value *V) {
1175 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1176 return (Bop->getOpcode() == Instruction::Xor &&
1177 (isConstantAllOnes(Bop->getOperand(1)) ||
1178 isConstantAllOnes(Bop->getOperand(0))));
1182 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1183 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1184 return cast<BinaryOperator>(BinOp)->getOperand(1);
1187 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1188 return getNegArgument(const_cast<Value*>(BinOp));
1191 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1192 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1193 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1194 Value *Op0 = BO->getOperand(0);
1195 Value *Op1 = BO->getOperand(1);
1196 if (isConstantAllOnes(Op0)) return Op1;
1198 assert(isConstantAllOnes(Op1));
1202 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1203 return getNotArgument(const_cast<Value*>(BinOp));
1207 // swapOperands - Exchange the two operands to this instruction. This
1208 // instruction is safe to use on any binary instruction and does not
1209 // modify the semantics of the instruction. If the instruction is
1210 // order dependent (SetLT f.e.) the opcode is changed.
1212 bool BinaryOperator::swapOperands() {
1213 if (isCommutative())
1214 ; // If the instruction is commutative, it is safe to swap the operands
1215 else if (SetCondInst *SCI = dyn_cast<SetCondInst>(this))
1216 /// FIXME: SetCC instructions shouldn't all have different opcodes.
1217 setOpcode(SCI->getSwappedCondition());
1219 return true; // Can't commute operands
1221 std::swap(Ops[0], Ops[1]);
1225 //===----------------------------------------------------------------------===//
1227 //===----------------------------------------------------------------------===//
1229 // Just determine if this cast only deals with integral->integral conversion.
1230 bool CastInst::isIntegerCast() const {
1231 switch (getOpcode()) {
1232 default: return false;
1233 case Instruction::ZExt:
1234 case Instruction::SExt:
1235 case Instruction::Trunc:
1237 case Instruction::BitCast:
1238 return getOperand(0)->getType()->isIntegral() && getType()->isIntegral();
1242 bool CastInst::isLosslessCast() const {
1243 // Only BitCast can be lossless, exit fast if we're not BitCast
1244 if (getOpcode() != Instruction::BitCast)
1247 // Identity cast is always lossless
1248 const Type* SrcTy = getOperand(0)->getType();
1249 const Type* DstTy = getType();
1253 // The remaining possibilities are lossless if the typeID of the source type
1254 // matches the type ID of the destination in size and fundamental type. This
1255 // prevents things like int -> ptr, int -> float, packed -> int, mismatched
1256 // packed types of the same size, and etc.
1257 switch (SrcTy->getTypeID()) {
1258 case Type::UByteTyID: return DstTy == Type::SByteTy;
1259 case Type::SByteTyID: return DstTy == Type::UByteTy;
1260 case Type::UShortTyID: return DstTy == Type::ShortTy;
1261 case Type::ShortTyID: return DstTy == Type::UShortTy;
1262 case Type::UIntTyID: return DstTy == Type::IntTy;
1263 case Type::IntTyID: return DstTy == Type::UIntTy;
1264 case Type::ULongTyID: return DstTy == Type::LongTy;
1265 case Type::LongTyID: return DstTy == Type::ULongTy;
1266 case Type::PointerTyID: return isa<PointerType>(DstTy);
1270 return false; // Other types have no identity values
1273 /// This function determines if the CastInst does not require any bits to be
1274 /// changed in order to effect the cast. Essentially, it identifies cases where
1275 /// no code gen is necessary for the cast, hence the name no-op cast. For
1276 /// example, the following are all no-op casts:
1277 /// # bitcast uint %X, int
1278 /// # bitcast uint* %x, sbyte*
1279 /// # bitcast packed< 2 x int > %x, packed< 4 x short>
1280 /// # ptrtoint uint* %x, uint ; on 32-bit plaforms only
1281 /// @brief Determine if a cast is a no-op.
1282 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1283 switch (getOpcode()) {
1285 assert(!"Invalid CastOp");
1286 case Instruction::Trunc:
1287 case Instruction::ZExt:
1288 case Instruction::SExt:
1289 case Instruction::FPTrunc:
1290 case Instruction::FPExt:
1291 case Instruction::UIToFP:
1292 case Instruction::SIToFP:
1293 case Instruction::FPToUI:
1294 case Instruction::FPToSI:
1295 return false; // These always modify bits
1296 case Instruction::BitCast:
1297 return true; // BitCast never modifies bits.
1298 case Instruction::PtrToInt:
1299 return IntPtrTy->getPrimitiveSizeInBits() ==
1300 getType()->getPrimitiveSizeInBits();
1301 case Instruction::IntToPtr:
1302 return IntPtrTy->getPrimitiveSizeInBits() ==
1303 getOperand(0)->getType()->getPrimitiveSizeInBits();
1307 /// This function determines if a pair of casts can be eliminated and what
1308 /// opcode should be used in the elimination. This assumes that there are two
1309 /// instructions like this:
1310 /// * %F = firstOpcode SrcTy %x to MidTy
1311 /// * %S = secondOpcode MidTy %F to DstTy
1312 /// The function returns a resultOpcode so these two casts can be replaced with:
1313 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1314 /// If no such cast is permited, the function returns 0.
1315 unsigned CastInst::isEliminableCastPair(
1316 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1317 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1319 // Define the 144 possibilities for these two cast instructions. The values
1320 // in this matrix determine what to do in a given situation and select the
1321 // case in the switch below. The rows correspond to firstOp, the columns
1322 // correspond to secondOp. In looking at the table below, keep in mind
1323 // the following cast properties:
1325 // Size Compare Source Destination
1326 // Operator Src ? Size Type Sign Type Sign
1327 // -------- ------------ ------------------- ---------------------
1328 // TRUNC > Integer Any Integral Any
1329 // ZEXT < Integral Unsigned Integer Any
1330 // SEXT < Integral Signed Integer Any
1331 // FPTOUI n/a FloatPt n/a Integral Unsigned
1332 // FPTOSI n/a FloatPt n/a Integral Signed
1333 // UITOFP n/a Integral Unsigned FloatPt n/a
1334 // SITOFP n/a Integral Signed FloatPt n/a
1335 // FPTRUNC > FloatPt n/a FloatPt n/a
1336 // FPEXT < FloatPt n/a FloatPt n/a
1337 // PTRTOINT n/a Pointer n/a Integral Unsigned
1338 // INTTOPTR n/a Integral Unsigned Pointer n/a
1339 // BITCONVERT = FirstClass n/a FirstClass n/a
1341 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1342 // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
1343 // into "fptoui double to ulong", but this loses information about the range
1344 // of the produced value (we no longer know the top-part is all zeros).
1345 // Further this conversion is often much more expensive for typical hardware,
1346 // and causes issues when building libgcc. We disallow fptosi+sext for the
1348 const unsigned numCastOps =
1349 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1350 static const uint8_t CastResults[numCastOps][numCastOps] = {
1351 // T F F U S F F P I B -+
1352 // R Z S P P I I T P 2 N T |
1353 // U E E 2 2 2 2 R E I T C +- secondOp
1354 // N X X U S F F N X N 2 V |
1355 // C T T I I P P C T T P T -+
1356 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1357 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1358 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1359 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1360 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1361 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1362 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1363 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1364 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1365 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1366 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1367 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1370 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1371 [secondOp-Instruction::CastOpsBegin];
1374 // categorically disallowed
1377 // allowed, use first cast's opcode
1380 // allowed, use second cast's opcode
1383 // no-op cast in second op implies firstOp as long as the DestTy
1385 if (DstTy->isInteger())
1389 // no-op cast in second op implies firstOp as long as the DestTy
1390 // is floating point
1391 if (DstTy->isFloatingPoint())
1395 // no-op cast in first op implies secondOp as long as the SrcTy
1397 if (SrcTy->isInteger())
1401 // no-op cast in first op implies secondOp as long as the SrcTy
1402 // is a floating point
1403 if (SrcTy->isFloatingPoint())
1407 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1408 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1409 unsigned MidSize = MidTy->getPrimitiveSizeInBits();
1410 if (MidSize >= PtrSize)
1411 return Instruction::BitCast;
1415 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1416 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1417 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1418 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1419 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1420 if (SrcSize == DstSize)
1421 return Instruction::BitCast;
1422 else if (SrcSize < DstSize)
1426 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1427 return Instruction::ZExt;
1429 // fpext followed by ftrunc is allowed if the bit size returned to is
1430 // the same as the original, in which case its just a bitcast
1432 return Instruction::BitCast;
1433 return 0; // If the types are not the same we can't eliminate it.
1435 // bitcast followed by ptrtoint is allowed as long as the bitcast
1436 // is a pointer to pointer cast.
1437 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1441 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1442 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1446 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1447 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1448 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1449 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1450 if (SrcSize <= PtrSize && SrcSize == DstSize)
1451 return Instruction::BitCast;
1455 // cast combination can't happen (error in input). This is for all cases
1456 // where the MidTy is not the same for the two cast instructions.
1457 assert(!"Invalid Cast Combination");
1460 assert(!"Error in CastResults table!!!");
1466 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1467 const std::string &Name, Instruction *InsertBefore) {
1468 // Construct and return the appropriate CastInst subclass
1470 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1471 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1472 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1473 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1474 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1475 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1476 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1477 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1478 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1479 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1480 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1481 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1483 assert(!"Invalid opcode provided");
1488 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1489 const std::string &Name, BasicBlock *InsertAtEnd) {
1490 // Construct and return the appropriate CastInst subclass
1492 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1493 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1494 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1495 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1496 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1497 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1498 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1499 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1500 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1501 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1502 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1503 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1505 assert(!"Invalid opcode provided");
1510 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1511 const std::string &Name,
1512 Instruction *InsertBefore) {
1513 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1514 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1515 return create(Instruction::ZExt, S, Ty, Name, InsertBefore);
1518 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1519 const std::string &Name,
1520 BasicBlock *InsertAtEnd) {
1521 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1522 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1523 return create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
1526 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1527 const std::string &Name,
1528 Instruction *InsertBefore) {
1529 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1530 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1531 return create(Instruction::SExt, S, Ty, Name, InsertBefore);
1534 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1535 const std::string &Name,
1536 BasicBlock *InsertAtEnd) {
1537 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1538 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1539 return create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
1542 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1543 const std::string &Name,
1544 Instruction *InsertBefore) {
1545 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1546 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1547 return create(Instruction::Trunc, S, Ty, Name, InsertBefore);
1550 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1551 const std::string &Name,
1552 BasicBlock *InsertAtEnd) {
1553 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1554 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1555 return create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
1558 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1559 const std::string &Name,
1560 BasicBlock *InsertAtEnd) {
1561 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1562 assert((Ty->isIntegral() || Ty->getTypeID() == Type::PointerTyID) &&
1565 if (Ty->isIntegral())
1566 return create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
1567 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1570 /// @brief Create a BitCast or a PtrToInt cast instruction
1571 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1572 const std::string &Name,
1573 Instruction *InsertBefore) {
1574 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1575 assert((Ty->isIntegral() || Ty->getTypeID() == Type::PointerTyID) &&
1578 if (Ty->isIntegral())
1579 return create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
1580 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1583 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1584 bool isSigned, const std::string &Name,
1585 Instruction *InsertBefore) {
1586 assert(C->getType()->isIntegral() && Ty->isIntegral() && "Invalid cast");
1587 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1588 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1589 Instruction::CastOps opcode =
1590 (SrcBits == DstBits ? Instruction::BitCast :
1591 (SrcBits > DstBits ? Instruction::Trunc :
1592 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1593 return create(opcode, C, Ty, Name, InsertBefore);
1596 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1597 bool isSigned, const std::string &Name,
1598 BasicBlock *InsertAtEnd) {
1599 assert(C->getType()->isIntegral() && Ty->isIntegral() && "Invalid cast");
1600 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1601 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1602 Instruction::CastOps opcode =
1603 (SrcBits == DstBits ? Instruction::BitCast :
1604 (SrcBits > DstBits ? Instruction::Trunc :
1605 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1606 return create(opcode, C, Ty, Name, InsertAtEnd);
1609 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1610 const std::string &Name,
1611 Instruction *InsertBefore) {
1612 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1614 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1615 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1616 Instruction::CastOps opcode =
1617 (SrcBits == DstBits ? Instruction::BitCast :
1618 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1619 return create(opcode, C, Ty, Name, InsertBefore);
1622 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1623 const std::string &Name,
1624 BasicBlock *InsertAtEnd) {
1625 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1627 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1628 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1629 Instruction::CastOps opcode =
1630 (SrcBits == DstBits ? Instruction::BitCast :
1631 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1632 return create(opcode, C, Ty, Name, InsertAtEnd);
1635 // Provide a way to get a "cast" where the cast opcode is inferred from the
1636 // types and size of the operand. This, basically, is a parallel of the
1637 // logic in the checkCast function below. This axiom should hold:
1638 // checkCast( getCastOpcode(Val, Ty), Val, Ty)
1639 // should not assert in checkCast. In other words, this produces a "correct"
1640 // casting opcode for the arguments passed to it.
1641 Instruction::CastOps
1642 CastInst::getCastOpcode(
1643 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
1644 // Get the bit sizes, we'll need these
1645 const Type *SrcTy = Src->getType();
1646 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/packed
1647 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/packed
1649 // Run through the possibilities ...
1650 if (DestTy->isIntegral()) { // Casting to integral
1651 if (SrcTy->isIntegral()) { // Casting from integral
1652 if (DestBits < SrcBits)
1653 return Trunc; // int -> smaller int
1654 else if (DestBits > SrcBits) { // its an extension
1656 return SExt; // signed -> SEXT
1658 return ZExt; // unsigned -> ZEXT
1660 return BitCast; // Same size, No-op cast
1662 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1664 return FPToSI; // FP -> sint
1666 return FPToUI; // FP -> uint
1667 } else if (const PackedType *PTy = dyn_cast<PackedType>(SrcTy)) {
1668 assert(DestBits == PTy->getBitWidth() &&
1669 "Casting packed to integer of different width");
1670 return BitCast; // Same size, no-op cast
1672 assert(isa<PointerType>(SrcTy) &&
1673 "Casting from a value that is not first-class type");
1674 return PtrToInt; // ptr -> int
1676 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
1677 if (SrcTy->isIntegral()) { // Casting from integral
1679 return SIToFP; // sint -> FP
1681 return UIToFP; // uint -> FP
1682 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1683 if (DestBits < SrcBits) {
1684 return FPTrunc; // FP -> smaller FP
1685 } else if (DestBits > SrcBits) {
1686 return FPExt; // FP -> larger FP
1688 return BitCast; // same size, no-op cast
1690 } else if (const PackedType *PTy = dyn_cast<PackedType>(SrcTy)) {
1691 assert(DestBits == PTy->getBitWidth() &&
1692 "Casting packed to floating point of different width");
1693 return BitCast; // same size, no-op cast
1695 assert(0 && "Casting pointer or non-first class to float");
1697 } else if (const PackedType *DestPTy = dyn_cast<PackedType>(DestTy)) {
1698 if (const PackedType *SrcPTy = dyn_cast<PackedType>(SrcTy)) {
1699 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
1700 "Casting packed to packed of different widths");
1701 return BitCast; // packed -> packed
1702 } else if (DestPTy->getBitWidth() == SrcBits) {
1703 return BitCast; // float/int -> packed
1705 assert(!"Illegal cast to packed (wrong type or size)");
1707 } else if (isa<PointerType>(DestTy)) {
1708 if (isa<PointerType>(SrcTy)) {
1709 return BitCast; // ptr -> ptr
1710 } else if (SrcTy->isIntegral()) {
1711 return IntToPtr; // int -> ptr
1713 assert(!"Casting pointer to other than pointer or int");
1716 assert(!"Casting to type that is not first-class");
1719 // If we fall through to here we probably hit an assertion cast above
1720 // and assertions are not turned on. Anything we return is an error, so
1721 // BitCast is as good a choice as any.
1725 //===----------------------------------------------------------------------===//
1726 // CastInst SubClass Constructors
1727 //===----------------------------------------------------------------------===//
1729 /// Check that the construction parameters for a CastInst are correct. This
1730 /// could be broken out into the separate constructors but it is useful to have
1731 /// it in one place and to eliminate the redundant code for getting the sizes
1732 /// of the types involved.
1734 checkCast(Instruction::CastOps op, Value *S, const Type *DstTy) {
1736 // Check for type sanity on the arguments
1737 const Type *SrcTy = S->getType();
1738 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
1741 // Get the size of the types in bits, we'll need this later
1742 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1743 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1745 // Switch on the opcode provided
1747 default: return false; // This is an input error
1748 case Instruction::Trunc:
1749 return SrcTy->isInteger() && DstTy->isIntegral() && SrcBitSize > DstBitSize;
1750 case Instruction::ZExt:
1751 return SrcTy->isIntegral() && DstTy->isInteger() && SrcBitSize < DstBitSize;
1752 case Instruction::SExt:
1753 return SrcTy->isIntegral() && DstTy->isInteger() && SrcBitSize < DstBitSize;
1754 case Instruction::FPTrunc:
1755 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
1756 SrcBitSize > DstBitSize;
1757 case Instruction::FPExt:
1758 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
1759 SrcBitSize < DstBitSize;
1760 case Instruction::UIToFP:
1761 return SrcTy->isIntegral() && DstTy->isFloatingPoint();
1762 case Instruction::SIToFP:
1763 return SrcTy->isIntegral() && DstTy->isFloatingPoint();
1764 case Instruction::FPToUI:
1765 return SrcTy->isFloatingPoint() && DstTy->isIntegral();
1766 case Instruction::FPToSI:
1767 return SrcTy->isFloatingPoint() && DstTy->isIntegral();
1768 case Instruction::PtrToInt:
1769 return isa<PointerType>(SrcTy) && DstTy->isIntegral();
1770 case Instruction::IntToPtr:
1771 return SrcTy->isIntegral() && isa<PointerType>(DstTy);
1772 case Instruction::BitCast:
1773 // BitCast implies a no-op cast of type only. No bits change.
1774 // However, you can't cast pointers to anything but pointers.
1775 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
1778 // Now we know we're not dealing with a pointer/non-poiner mismatch. In all
1779 // these cases, the cast is okay if the source and destination bit widths
1781 return SrcBitSize == DstBitSize;
1785 CastInst *CastInst::createInferredCast(
1786 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore)
1788 return createInferredCast(S, S->getType()->isSigned(), Ty, Ty->isSigned(),
1789 Name, InsertBefore);
1792 CastInst *CastInst::createInferredCast(
1793 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd)
1795 return createInferredCast(S, S->getType()->isSigned(), Ty, Ty->isSigned(),
1799 TruncInst::TruncInst(
1800 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1801 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
1802 assert(checkCast(getOpcode(), S, Ty) && "Illegal Trunc");
1805 TruncInst::TruncInst(
1806 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1807 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
1808 assert(checkCast(getOpcode(), S, Ty) && "Illegal Trunc");
1812 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1813 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
1814 assert(checkCast(getOpcode(), S, Ty) && "Illegal ZExt");
1818 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1819 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
1820 assert(checkCast(getOpcode(), S, Ty) && "Illegal ZExt");
1823 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1824 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
1825 assert(checkCast(getOpcode(), S, Ty) && "Illegal SExt");
1829 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1830 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
1831 assert(checkCast(getOpcode(), S, Ty) && "Illegal SExt");
1834 FPTruncInst::FPTruncInst(
1835 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1836 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
1837 assert(checkCast(getOpcode(), S, Ty) && "Illegal FPTrunc");
1840 FPTruncInst::FPTruncInst(
1841 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1842 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
1843 assert(checkCast(getOpcode(), S, Ty) && "Illegal FPTrunc");
1846 FPExtInst::FPExtInst(
1847 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1848 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
1849 assert(checkCast(getOpcode(), S, Ty) && "Illegal FPExt");
1852 FPExtInst::FPExtInst(
1853 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1854 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
1855 assert(checkCast(getOpcode(), S, Ty) && "Illegal FPExt");
1858 UIToFPInst::UIToFPInst(
1859 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1860 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
1861 assert(checkCast(getOpcode(), S, Ty) && "Illegal UIToFP");
1864 UIToFPInst::UIToFPInst(
1865 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1866 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
1867 assert(checkCast(getOpcode(), S, Ty) && "Illegal UIToFP");
1870 SIToFPInst::SIToFPInst(
1871 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1872 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
1873 assert(checkCast(getOpcode(), S, Ty) && "Illegal SIToFP");
1876 SIToFPInst::SIToFPInst(
1877 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1878 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
1879 assert(checkCast(getOpcode(), S, Ty) && "Illegal SIToFP");
1882 FPToUIInst::FPToUIInst(
1883 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1884 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
1885 assert(checkCast(getOpcode(), S, Ty) && "Illegal FPToUI");
1888 FPToUIInst::FPToUIInst(
1889 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1890 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
1891 assert(checkCast(getOpcode(), S, Ty) && "Illegal FPToUI");
1894 FPToSIInst::FPToSIInst(
1895 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1896 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
1897 assert(checkCast(getOpcode(), S, Ty) && "Illegal FPToSI");
1900 FPToSIInst::FPToSIInst(
1901 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1902 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
1903 assert(checkCast(getOpcode(), S, Ty) && "Illegal FPToSI");
1906 PtrToIntInst::PtrToIntInst(
1907 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1908 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
1909 assert(checkCast(getOpcode(), S, Ty) && "Illegal PtrToInt");
1912 PtrToIntInst::PtrToIntInst(
1913 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1914 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
1915 assert(checkCast(getOpcode(), S, Ty) && "Illegal PtrToInt");
1918 IntToPtrInst::IntToPtrInst(
1919 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1920 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
1921 assert(checkCast(getOpcode(), S, Ty) && "Illegal IntToPtr");
1924 IntToPtrInst::IntToPtrInst(
1925 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1926 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
1927 assert(checkCast(getOpcode(), S, Ty) && "Illegal IntToPtr");
1930 BitCastInst::BitCastInst(
1931 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1932 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
1933 assert(checkCast(getOpcode(), S, Ty) && "Illegal BitCast");
1936 BitCastInst::BitCastInst(
1937 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1938 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
1939 assert(checkCast(getOpcode(), S, Ty) && "Illegal BitCast");
1942 //===----------------------------------------------------------------------===//
1943 // SetCondInst Class
1944 //===----------------------------------------------------------------------===//
1946 SetCondInst::SetCondInst(BinaryOps Opcode, Value *S1, Value *S2,
1947 const std::string &Name, Instruction *InsertBefore)
1948 : BinaryOperator(Opcode, S1, S2, Type::BoolTy, Name, InsertBefore) {
1950 // Make sure it's a valid type... getInverseCondition will assert out if not.
1951 assert(getInverseCondition(Opcode));
1954 SetCondInst::SetCondInst(BinaryOps Opcode, Value *S1, Value *S2,
1955 const std::string &Name, BasicBlock *InsertAtEnd)
1956 : BinaryOperator(Opcode, S1, S2, Type::BoolTy, Name, InsertAtEnd) {
1958 // Make sure it's a valid type... getInverseCondition will assert out if not.
1959 assert(getInverseCondition(Opcode));
1962 // getInverseCondition - Return the inverse of the current condition opcode.
1963 // For example seteq -> setne, setgt -> setle, setlt -> setge, etc...
1965 Instruction::BinaryOps SetCondInst::getInverseCondition(BinaryOps Opcode) {
1968 assert(0 && "Unknown setcc opcode!");
1969 case SetEQ: return SetNE;
1970 case SetNE: return SetEQ;
1971 case SetGT: return SetLE;
1972 case SetLT: return SetGE;
1973 case SetGE: return SetLT;
1974 case SetLE: return SetGT;
1978 // getSwappedCondition - Return the condition opcode that would be the result
1979 // of exchanging the two operands of the setcc instruction without changing
1980 // the result produced. Thus, seteq->seteq, setle->setge, setlt->setgt, etc.
1982 Instruction::BinaryOps SetCondInst::getSwappedCondition(BinaryOps Opcode) {
1984 default: assert(0 && "Unknown setcc instruction!");
1985 case SetEQ: case SetNE: return Opcode;
1986 case SetGT: return SetLT;
1987 case SetLT: return SetGT;
1988 case SetGE: return SetLE;
1989 case SetLE: return SetGE;
1994 //===----------------------------------------------------------------------===//
1996 //===----------------------------------------------------------------------===//
1998 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
1999 const std::string &Name, Instruction *InsertBefore)
2000 : Instruction(Type::BoolTy, op, Ops, 2, Name, InsertBefore) {
2001 Ops[0].init(LHS, this);
2002 Ops[1].init(RHS, this);
2003 SubclassData = predicate;
2004 if (op == Instruction::ICmp) {
2005 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2006 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2007 "Invalid ICmp predicate value");
2008 const Type* Op0Ty = getOperand(0)->getType();
2009 const Type* Op1Ty = getOperand(1)->getType();
2010 assert(Op0Ty == Op1Ty &&
2011 "Both operands to ICmp instruction are not of the same type!");
2012 // Check that the operands are the right type
2013 assert(Op0Ty->isIntegral() || Op0Ty->getTypeID() == Type::PointerTyID ||
2014 (isa<PackedType>(Op0Ty) &&
2015 cast<PackedType>(Op0Ty)->getElementType()->isIntegral()) &&
2016 "Invalid operand types for ICmp instruction");
2019 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2020 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2021 "Invalid FCmp predicate value");
2022 const Type* Op0Ty = getOperand(0)->getType();
2023 const Type* Op1Ty = getOperand(1)->getType();
2024 assert(Op0Ty == Op1Ty &&
2025 "Both operands to FCmp instruction are not of the same type!");
2026 // Check that the operands are the right type
2027 assert(Op0Ty->isFloatingPoint() || (isa<PackedType>(Op0Ty) &&
2028 cast<PackedType>(Op0Ty)->getElementType()->isFloatingPoint()) &&
2029 "Invalid operand types for FCmp instruction");
2032 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2033 const std::string &Name, BasicBlock *InsertAtEnd)
2034 : Instruction(Type::BoolTy, op, Ops, 2, Name, InsertAtEnd) {
2035 Ops[0].init(LHS, this);
2036 Ops[1].init(RHS, this);
2037 SubclassData = predicate;
2038 if (op == Instruction::ICmp) {
2039 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2040 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2041 "Invalid ICmp predicate value");
2043 const Type* Op0Ty = getOperand(0)->getType();
2044 const Type* Op1Ty = getOperand(1)->getType();
2045 assert(Op0Ty == Op1Ty &&
2046 "Both operands to ICmp instruction are not of the same type!");
2047 // Check that the operands are the right type
2048 assert(Op0Ty->isIntegral() || Op0Ty->getTypeID() == Type::PointerTyID ||
2049 (isa<PackedType>(Op0Ty) &&
2050 cast<PackedType>(Op0Ty)->getElementType()->isIntegral()) &&
2051 "Invalid operand types for ICmp instruction");
2054 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2055 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2056 "Invalid FCmp predicate value");
2057 const Type* Op0Ty = getOperand(0)->getType();
2058 const Type* Op1Ty = getOperand(1)->getType();
2059 assert(Op0Ty == Op1Ty &&
2060 "Both operands to FCmp instruction are not of the same type!");
2061 // Check that the operands are the right type
2062 assert(Op0Ty->isFloatingPoint() || (isa<PackedType>(Op0Ty) &&
2063 cast<PackedType>(Op0Ty)->getElementType()->isFloatingPoint()) &&
2064 "Invalid operand types for FCmp instruction");
2068 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2069 const std::string &Name, Instruction *InsertBefore) {
2070 if (Op == Instruction::ICmp) {
2071 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2074 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2079 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2080 const std::string &Name, BasicBlock *InsertAtEnd) {
2081 if (Op == Instruction::ICmp) {
2082 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2085 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2089 void CmpInst::swapOperands() {
2090 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2093 cast<FCmpInst>(this)->swapOperands();
2096 bool CmpInst::isCommutative() {
2097 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2098 return IC->isCommutative();
2099 return cast<FCmpInst>(this)->isCommutative();
2102 bool CmpInst::isEquality() {
2103 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2104 return IC->isEquality();
2105 return cast<FCmpInst>(this)->isEquality();
2109 ICmpInst::Predicate ICmpInst::getInversePredicate(Predicate pred) {
2112 assert(!"Unknown icmp predicate!");
2113 case ICMP_EQ: return ICMP_NE;
2114 case ICMP_NE: return ICMP_EQ;
2115 case ICMP_UGT: return ICMP_ULE;
2116 case ICMP_ULT: return ICMP_UGE;
2117 case ICMP_UGE: return ICMP_ULT;
2118 case ICMP_ULE: return ICMP_UGT;
2119 case ICMP_SGT: return ICMP_SLE;
2120 case ICMP_SLT: return ICMP_SGE;
2121 case ICMP_SGE: return ICMP_SLT;
2122 case ICMP_SLE: return ICMP_SGT;
2126 ICmpInst::Predicate ICmpInst::getSwappedPredicate(Predicate pred) {
2128 default: assert(! "Unknown setcc instruction!");
2129 case ICMP_EQ: case ICMP_NE:
2131 case ICMP_SGT: return ICMP_SLT;
2132 case ICMP_SLT: return ICMP_SGT;
2133 case ICMP_SGE: return ICMP_SLE;
2134 case ICMP_SLE: return ICMP_SGE;
2135 case ICMP_UGT: return ICMP_ULT;
2136 case ICMP_ULT: return ICMP_UGT;
2137 case ICMP_UGE: return ICMP_ULE;
2138 case ICMP_ULE: return ICMP_UGE;
2142 FCmpInst::Predicate FCmpInst::getInversePredicate(Predicate pred) {
2145 assert(!"Unknown icmp predicate!");
2146 case FCMP_OEQ: return FCMP_UNE;
2147 case FCMP_ONE: return FCMP_UEQ;
2148 case FCMP_OGT: return FCMP_ULE;
2149 case FCMP_OLT: return FCMP_UGE;
2150 case FCMP_OGE: return FCMP_ULT;
2151 case FCMP_OLE: return FCMP_UGT;
2152 case FCMP_UEQ: return FCMP_ONE;
2153 case FCMP_UNE: return FCMP_OEQ;
2154 case FCMP_UGT: return FCMP_OLE;
2155 case FCMP_ULT: return FCMP_OGE;
2156 case FCMP_UGE: return FCMP_OLT;
2157 case FCMP_ULE: return FCMP_OGT;
2158 case FCMP_ORD: return FCMP_UNO;
2159 case FCMP_UNO: return FCMP_ORD;
2160 case FCMP_TRUE: return FCMP_FALSE;
2161 case FCMP_FALSE: return FCMP_TRUE;
2165 FCmpInst::Predicate FCmpInst::getSwappedPredicate(Predicate pred) {
2167 default: assert(!"Unknown setcc instruction!");
2168 case FCMP_FALSE: case FCMP_TRUE:
2169 case FCMP_OEQ: case FCMP_ONE:
2170 case FCMP_UEQ: case FCMP_UNE:
2171 case FCMP_ORD: case FCMP_UNO:
2173 case FCMP_OGT: return FCMP_OLT;
2174 case FCMP_OLT: return FCMP_OGT;
2175 case FCMP_OGE: return FCMP_OLE;
2176 case FCMP_OLE: return FCMP_OGE;
2177 case FCMP_UGT: return FCMP_ULT;
2178 case FCMP_ULT: return FCMP_UGT;
2179 case FCMP_UGE: return FCMP_ULE;
2180 case FCMP_ULE: return FCMP_UGE;
2184 //===----------------------------------------------------------------------===//
2185 // SwitchInst Implementation
2186 //===----------------------------------------------------------------------===//
2188 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2189 assert(Value && Default);
2190 ReservedSpace = 2+NumCases*2;
2192 OperandList = new Use[ReservedSpace];
2194 OperandList[0].init(Value, this);
2195 OperandList[1].init(Default, this);
2198 SwitchInst::SwitchInst(const SwitchInst &SI)
2199 : TerminatorInst(Instruction::Switch, new Use[SI.getNumOperands()],
2200 SI.getNumOperands()) {
2201 Use *OL = OperandList, *InOL = SI.OperandList;
2202 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2203 OL[i].init(InOL[i], this);
2204 OL[i+1].init(InOL[i+1], this);
2208 SwitchInst::~SwitchInst() {
2209 delete [] OperandList;
2213 /// addCase - Add an entry to the switch instruction...
2215 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2216 unsigned OpNo = NumOperands;
2217 if (OpNo+2 > ReservedSpace)
2218 resizeOperands(0); // Get more space!
2219 // Initialize some new operands.
2220 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2221 NumOperands = OpNo+2;
2222 OperandList[OpNo].init(OnVal, this);
2223 OperandList[OpNo+1].init(Dest, this);
2226 /// removeCase - This method removes the specified successor from the switch
2227 /// instruction. Note that this cannot be used to remove the default
2228 /// destination (successor #0).
2230 void SwitchInst::removeCase(unsigned idx) {
2231 assert(idx != 0 && "Cannot remove the default case!");
2232 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2234 unsigned NumOps = getNumOperands();
2235 Use *OL = OperandList;
2237 // Move everything after this operand down.
2239 // FIXME: we could just swap with the end of the list, then erase. However,
2240 // client might not expect this to happen. The code as it is thrashes the
2241 // use/def lists, which is kinda lame.
2242 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2244 OL[i-2+1] = OL[i+1];
2247 // Nuke the last value.
2248 OL[NumOps-2].set(0);
2249 OL[NumOps-2+1].set(0);
2250 NumOperands = NumOps-2;
2253 /// resizeOperands - resize operands - This adjusts the length of the operands
2254 /// list according to the following behavior:
2255 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2256 /// of operation. This grows the number of ops by 1.5 times.
2257 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2258 /// 3. If NumOps == NumOperands, trim the reserved space.
2260 void SwitchInst::resizeOperands(unsigned NumOps) {
2262 NumOps = getNumOperands()/2*6;
2263 } else if (NumOps*2 > NumOperands) {
2264 // No resize needed.
2265 if (ReservedSpace >= NumOps) return;
2266 } else if (NumOps == NumOperands) {
2267 if (ReservedSpace == NumOps) return;
2272 ReservedSpace = NumOps;
2273 Use *NewOps = new Use[NumOps];
2274 Use *OldOps = OperandList;
2275 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2276 NewOps[i].init(OldOps[i], this);
2280 OperandList = NewOps;
2284 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2285 return getSuccessor(idx);
2287 unsigned SwitchInst::getNumSuccessorsV() const {
2288 return getNumSuccessors();
2290 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2291 setSuccessor(idx, B);
2295 // Define these methods here so vtables don't get emitted into every translation
2296 // unit that uses these classes.
2298 GetElementPtrInst *GetElementPtrInst::clone() const {
2299 return new GetElementPtrInst(*this);
2302 BinaryOperator *BinaryOperator::clone() const {
2303 return create(getOpcode(), Ops[0], Ops[1]);
2306 CmpInst* CmpInst::clone() const {
2307 return create(getOpcode(), getPredicate(), Ops[0], Ops[1]);
2310 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
2311 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
2312 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
2313 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
2314 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
2315 CastInst *TruncInst::clone() const { return new TruncInst(*this); }
2316 CastInst *ZExtInst::clone() const { return new ZExtInst(*this); }
2317 CastInst *SExtInst::clone() const { return new SExtInst(*this); }
2318 CastInst *FPTruncInst::clone() const { return new FPTruncInst(*this); }
2319 CastInst *FPExtInst::clone() const { return new FPExtInst(*this); }
2320 CastInst *UIToFPInst::clone() const { return new UIToFPInst(*this); }
2321 CastInst *SIToFPInst::clone() const { return new SIToFPInst(*this); }
2322 CastInst *FPToUIInst::clone() const { return new FPToUIInst(*this); }
2323 CastInst *FPToSIInst::clone() const { return new FPToSIInst(*this); }
2324 CastInst *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
2325 CastInst *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
2326 CastInst *BitCastInst::clone() const { return new BitCastInst(*this); }
2327 CallInst *CallInst::clone() const { return new CallInst(*this); }
2328 ShiftInst *ShiftInst::clone() const { return new ShiftInst(*this); }
2329 SelectInst *SelectInst::clone() const { return new SelectInst(*this); }
2330 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
2332 ExtractElementInst *ExtractElementInst::clone() const {
2333 return new ExtractElementInst(*this);
2335 InsertElementInst *InsertElementInst::clone() const {
2336 return new InsertElementInst(*this);
2338 ShuffleVectorInst *ShuffleVectorInst::clone() const {
2339 return new ShuffleVectorInst(*this);
2341 PHINode *PHINode::clone() const { return new PHINode(*this); }
2342 ReturnInst *ReturnInst::clone() const { return new ReturnInst(*this); }
2343 BranchInst *BranchInst::clone() const { return new BranchInst(*this); }
2344 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
2345 InvokeInst *InvokeInst::clone() const { return new InvokeInst(*this); }
2346 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
2347 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}