1 //===-- Instructions.cpp - Implement the LLVM instructions ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements all of the non-inline methods for the LLVM instruction
13 //===----------------------------------------------------------------------===//
15 #include "llvm/BasicBlock.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Support/CallSite.h"
23 unsigned CallSite::getCallingConv() const {
24 if (CallInst *CI = dyn_cast<CallInst>(I))
25 return CI->getCallingConv();
27 return cast<InvokeInst>(I)->getCallingConv();
29 void CallSite::setCallingConv(unsigned CC) {
30 if (CallInst *CI = dyn_cast<CallInst>(I))
31 CI->setCallingConv(CC);
33 cast<InvokeInst>(I)->setCallingConv(CC);
39 //===----------------------------------------------------------------------===//
40 // TerminatorInst Class
41 //===----------------------------------------------------------------------===//
43 TerminatorInst::TerminatorInst(Instruction::TermOps iType,
44 Use *Ops, unsigned NumOps, Instruction *IB)
45 : Instruction(Type::VoidTy, iType, Ops, NumOps, "", IB) {
48 TerminatorInst::TerminatorInst(Instruction::TermOps iType,
49 Use *Ops, unsigned NumOps, BasicBlock *IAE)
50 : Instruction(Type::VoidTy, iType, Ops, NumOps, "", IAE) {
53 // Out of line virtual method, so the vtable, etc has a home.
54 TerminatorInst::~TerminatorInst() {
57 // Out of line virtual method, so the vtable, etc has a home.
58 UnaryInstruction::~UnaryInstruction() {
62 //===----------------------------------------------------------------------===//
64 //===----------------------------------------------------------------------===//
66 PHINode::PHINode(const PHINode &PN)
67 : Instruction(PN.getType(), Instruction::PHI,
68 new Use[PN.getNumOperands()], PN.getNumOperands()),
69 ReservedSpace(PN.getNumOperands()) {
70 Use *OL = OperandList;
71 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
72 OL[i].init(PN.getOperand(i), this);
73 OL[i+1].init(PN.getOperand(i+1), this);
78 delete [] OperandList;
81 // removeIncomingValue - Remove an incoming value. This is useful if a
82 // predecessor basic block is deleted.
83 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
84 unsigned NumOps = getNumOperands();
85 Use *OL = OperandList;
86 assert(Idx*2 < NumOps && "BB not in PHI node!");
87 Value *Removed = OL[Idx*2];
89 // Move everything after this operand down.
91 // FIXME: we could just swap with the end of the list, then erase. However,
92 // client might not expect this to happen. The code as it is thrashes the
93 // use/def lists, which is kinda lame.
94 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
99 // Nuke the last value.
101 OL[NumOps-2+1].set(0);
102 NumOperands = NumOps-2;
104 // If the PHI node is dead, because it has zero entries, nuke it now.
105 if (NumOps == 2 && DeletePHIIfEmpty) {
106 // If anyone is using this PHI, make them use a dummy value instead...
107 replaceAllUsesWith(UndefValue::get(getType()));
113 /// resizeOperands - resize operands - This adjusts the length of the operands
114 /// list according to the following behavior:
115 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
116 /// of operation. This grows the number of ops by 1.5 times.
117 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
118 /// 3. If NumOps == NumOperands, trim the reserved space.
120 void PHINode::resizeOperands(unsigned NumOps) {
122 NumOps = (getNumOperands())*3/2;
123 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
124 } else if (NumOps*2 > NumOperands) {
126 if (ReservedSpace >= NumOps) return;
127 } else if (NumOps == NumOperands) {
128 if (ReservedSpace == NumOps) return;
133 ReservedSpace = NumOps;
134 Use *NewOps = new Use[NumOps];
135 Use *OldOps = OperandList;
136 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
137 NewOps[i].init(OldOps[i], this);
141 OperandList = NewOps;
144 /// hasConstantValue - If the specified PHI node always merges together the same
145 /// value, return the value, otherwise return null.
147 Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) const {
148 // If the PHI node only has one incoming value, eliminate the PHI node...
149 if (getNumIncomingValues() == 1)
150 if (getIncomingValue(0) != this) // not X = phi X
151 return getIncomingValue(0);
153 return UndefValue::get(getType()); // Self cycle is dead.
155 // Otherwise if all of the incoming values are the same for the PHI, replace
156 // the PHI node with the incoming value.
159 bool HasUndefInput = false;
160 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
161 if (isa<UndefValue>(getIncomingValue(i)))
162 HasUndefInput = true;
163 else if (getIncomingValue(i) != this) // Not the PHI node itself...
164 if (InVal && getIncomingValue(i) != InVal)
165 return 0; // Not the same, bail out.
167 InVal = getIncomingValue(i);
169 // The only case that could cause InVal to be null is if we have a PHI node
170 // that only has entries for itself. In this case, there is no entry into the
171 // loop, so kill the PHI.
173 if (InVal == 0) InVal = UndefValue::get(getType());
175 // If we have a PHI node like phi(X, undef, X), where X is defined by some
176 // instruction, we cannot always return X as the result of the PHI node. Only
177 // do this if X is not an instruction (thus it must dominate the PHI block),
178 // or if the client is prepared to deal with this possibility.
179 if (HasUndefInput && !AllowNonDominatingInstruction)
180 if (Instruction *IV = dyn_cast<Instruction>(InVal))
181 // If it's in the entry block, it dominates everything.
182 if (IV->getParent() != &IV->getParent()->getParent()->front() ||
184 return 0; // Cannot guarantee that InVal dominates this PHINode.
186 // All of the incoming values are the same, return the value now.
191 //===----------------------------------------------------------------------===//
192 // CallInst Implementation
193 //===----------------------------------------------------------------------===//
195 CallInst::~CallInst() {
196 delete [] OperandList;
199 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
200 NumOperands = NumParams+1;
201 Use *OL = OperandList = new Use[NumParams+1];
202 OL[0].init(Func, this);
204 const FunctionType *FTy =
205 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
206 FTy = FTy; // silence warning.
208 assert((NumParams == FTy->getNumParams() ||
209 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
210 "Calling a function with bad signature!");
211 for (unsigned i = 0; i != NumParams; ++i) {
212 assert((i >= FTy->getNumParams() ||
213 FTy->getParamType(i) == Params[i]->getType()) &&
214 "Calling a function with a bad signature!");
215 OL[i+1].init(Params[i], this);
219 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
221 Use *OL = OperandList = new Use[3];
222 OL[0].init(Func, this);
223 OL[1].init(Actual1, this);
224 OL[2].init(Actual2, this);
226 const FunctionType *FTy =
227 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
228 FTy = FTy; // silence warning.
230 assert((FTy->getNumParams() == 2 ||
231 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
232 "Calling a function with bad signature");
233 assert((0 >= FTy->getNumParams() ||
234 FTy->getParamType(0) == Actual1->getType()) &&
235 "Calling a function with a bad signature!");
236 assert((1 >= FTy->getNumParams() ||
237 FTy->getParamType(1) == Actual2->getType()) &&
238 "Calling a function with a bad signature!");
241 void CallInst::init(Value *Func, Value *Actual) {
243 Use *OL = OperandList = new Use[2];
244 OL[0].init(Func, this);
245 OL[1].init(Actual, this);
247 const FunctionType *FTy =
248 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
249 FTy = FTy; // silence warning.
251 assert((FTy->getNumParams() == 1 ||
252 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
253 "Calling a function with bad signature");
254 assert((0 == FTy->getNumParams() ||
255 FTy->getParamType(0) == Actual->getType()) &&
256 "Calling a function with a bad signature!");
259 void CallInst::init(Value *Func) {
261 Use *OL = OperandList = new Use[1];
262 OL[0].init(Func, this);
264 const FunctionType *FTy =
265 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
266 FTy = FTy; // silence warning.
268 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
271 CallInst::CallInst(Value *Func, Value* const *Args, unsigned NumArgs,
272 const std::string &Name, BasicBlock *InsertAtEnd)
273 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
274 ->getElementType())->getReturnType(),
275 Instruction::Call, 0, 0, Name, InsertAtEnd) {
276 init(Func, Args, NumArgs);
278 CallInst::CallInst(Value *Func, Value* const *Args, unsigned NumArgs,
279 const std::string &Name, Instruction *InsertBefore)
280 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
281 ->getElementType())->getReturnType(),
282 Instruction::Call, 0, 0, Name, InsertBefore) {
283 init(Func, Args, NumArgs);
286 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
287 const std::string &Name, Instruction *InsertBefore)
288 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
289 ->getElementType())->getReturnType(),
290 Instruction::Call, 0, 0, Name, InsertBefore) {
291 init(Func, Actual1, Actual2);
294 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
295 const std::string &Name, BasicBlock *InsertAtEnd)
296 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
297 ->getElementType())->getReturnType(),
298 Instruction::Call, 0, 0, Name, InsertAtEnd) {
299 init(Func, Actual1, Actual2);
302 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
303 Instruction *InsertBefore)
304 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
305 ->getElementType())->getReturnType(),
306 Instruction::Call, 0, 0, Name, InsertBefore) {
310 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
311 BasicBlock *InsertAtEnd)
312 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
313 ->getElementType())->getReturnType(),
314 Instruction::Call, 0, 0, Name, InsertAtEnd) {
318 CallInst::CallInst(Value *Func, const std::string &Name,
319 Instruction *InsertBefore)
320 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
321 ->getElementType())->getReturnType(),
322 Instruction::Call, 0, 0, Name, InsertBefore) {
326 CallInst::CallInst(Value *Func, const std::string &Name,
327 BasicBlock *InsertAtEnd)
328 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
329 ->getElementType())->getReturnType(),
330 Instruction::Call, 0, 0, Name, InsertAtEnd) {
334 CallInst::CallInst(const CallInst &CI)
335 : Instruction(CI.getType(), Instruction::Call, new Use[CI.getNumOperands()],
336 CI.getNumOperands()) {
337 SubclassData = CI.SubclassData;
338 Use *OL = OperandList;
339 Use *InOL = CI.OperandList;
340 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
341 OL[i].init(InOL[i], this);
345 //===----------------------------------------------------------------------===//
346 // InvokeInst Implementation
347 //===----------------------------------------------------------------------===//
349 InvokeInst::~InvokeInst() {
350 delete [] OperandList;
353 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
354 Value* const *Args, unsigned NumArgs) {
355 NumOperands = 3+NumArgs;
356 Use *OL = OperandList = new Use[3+NumArgs];
357 OL[0].init(Fn, this);
358 OL[1].init(IfNormal, this);
359 OL[2].init(IfException, this);
360 const FunctionType *FTy =
361 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
362 FTy = FTy; // silence warning.
364 assert((NumArgs == FTy->getNumParams()) ||
365 (FTy->isVarArg() && NumArgs > FTy->getNumParams()) &&
366 "Calling a function with bad signature");
368 for (unsigned i = 0, e = NumArgs; i != e; i++) {
369 assert((i >= FTy->getNumParams() ||
370 FTy->getParamType(i) == Args[i]->getType()) &&
371 "Invoking a function with a bad signature!");
373 OL[i+3].init(Args[i], this);
377 InvokeInst::InvokeInst(Value *Fn, BasicBlock *IfNormal,
378 BasicBlock *IfException,
379 Value* const *Args, unsigned NumArgs,
380 const std::string &Name, Instruction *InsertBefore)
381 : TerminatorInst(cast<FunctionType>(cast<PointerType>(Fn->getType())
382 ->getElementType())->getReturnType(),
383 Instruction::Invoke, 0, 0, Name, InsertBefore) {
384 init(Fn, IfNormal, IfException, Args, NumArgs);
387 InvokeInst::InvokeInst(Value *Fn, BasicBlock *IfNormal,
388 BasicBlock *IfException,
389 Value* const *Args, unsigned NumArgs,
390 const std::string &Name, BasicBlock *InsertAtEnd)
391 : TerminatorInst(cast<FunctionType>(cast<PointerType>(Fn->getType())
392 ->getElementType())->getReturnType(),
393 Instruction::Invoke, 0, 0, Name, InsertAtEnd) {
394 init(Fn, IfNormal, IfException, Args, NumArgs);
397 InvokeInst::InvokeInst(const InvokeInst &II)
398 : TerminatorInst(II.getType(), Instruction::Invoke,
399 new Use[II.getNumOperands()], II.getNumOperands()) {
400 SubclassData = II.SubclassData;
401 Use *OL = OperandList, *InOL = II.OperandList;
402 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
403 OL[i].init(InOL[i], this);
406 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
407 return getSuccessor(idx);
409 unsigned InvokeInst::getNumSuccessorsV() const {
410 return getNumSuccessors();
412 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
413 return setSuccessor(idx, B);
417 //===----------------------------------------------------------------------===//
418 // ReturnInst Implementation
419 //===----------------------------------------------------------------------===//
421 void ReturnInst::init(Value *retVal) {
422 if (retVal && retVal->getType() != Type::VoidTy) {
423 assert(!isa<BasicBlock>(retVal) &&
424 "Cannot return basic block. Probably using the incorrect ctor");
426 RetVal.init(retVal, this);
430 unsigned ReturnInst::getNumSuccessorsV() const {
431 return getNumSuccessors();
434 // Out-of-line ReturnInst method, put here so the C++ compiler can choose to
435 // emit the vtable for the class in this translation unit.
436 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
437 assert(0 && "ReturnInst has no successors!");
440 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
441 assert(0 && "ReturnInst has no successors!");
447 //===----------------------------------------------------------------------===//
448 // UnwindInst Implementation
449 //===----------------------------------------------------------------------===//
451 unsigned UnwindInst::getNumSuccessorsV() const {
452 return getNumSuccessors();
455 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
456 assert(0 && "UnwindInst has no successors!");
459 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
460 assert(0 && "UnwindInst has no successors!");
465 //===----------------------------------------------------------------------===//
466 // UnreachableInst Implementation
467 //===----------------------------------------------------------------------===//
469 unsigned UnreachableInst::getNumSuccessorsV() const {
470 return getNumSuccessors();
473 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
474 assert(0 && "UnwindInst has no successors!");
477 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
478 assert(0 && "UnwindInst has no successors!");
483 //===----------------------------------------------------------------------===//
484 // BranchInst Implementation
485 //===----------------------------------------------------------------------===//
487 void BranchInst::AssertOK() {
489 assert(getCondition()->getType() == Type::Int1Ty &&
490 "May only branch on boolean predicates!");
493 BranchInst::BranchInst(const BranchInst &BI) :
494 TerminatorInst(Instruction::Br, Ops, BI.getNumOperands()) {
495 OperandList[0].init(BI.getOperand(0), this);
496 if (BI.getNumOperands() != 1) {
497 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
498 OperandList[1].init(BI.getOperand(1), this);
499 OperandList[2].init(BI.getOperand(2), this);
503 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
504 return getSuccessor(idx);
506 unsigned BranchInst::getNumSuccessorsV() const {
507 return getNumSuccessors();
509 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
510 setSuccessor(idx, B);
514 //===----------------------------------------------------------------------===//
515 // AllocationInst Implementation
516 //===----------------------------------------------------------------------===//
518 static Value *getAISize(Value *Amt) {
520 Amt = ConstantInt::get(Type::Int32Ty, 1);
522 assert(!isa<BasicBlock>(Amt) &&
523 "Passed basic block into allocation size parameter! Ue other ctor");
524 assert(Amt->getType() == Type::Int32Ty &&
525 "Malloc/Allocation array size is not a 32-bit integer!");
530 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
531 unsigned Align, const std::string &Name,
532 Instruction *InsertBefore)
533 : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
534 0, InsertBefore), Alignment(Align) {
535 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
536 assert(Ty != Type::VoidTy && "Cannot allocate void!");
540 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
541 unsigned Align, const std::string &Name,
542 BasicBlock *InsertAtEnd)
543 : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
544 0, InsertAtEnd), Alignment(Align) {
545 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
546 assert(Ty != Type::VoidTy && "Cannot allocate void!");
550 // Out of line virtual method, so the vtable, etc has a home.
551 AllocationInst::~AllocationInst() {
554 bool AllocationInst::isArrayAllocation() const {
555 if (ConstantInt *CUI = dyn_cast<ConstantInt>(getOperand(0)))
556 return CUI->getZExtValue() != 1;
560 const Type *AllocationInst::getAllocatedType() const {
561 return getType()->getElementType();
564 AllocaInst::AllocaInst(const AllocaInst &AI)
565 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
566 Instruction::Alloca, AI.getAlignment()) {
569 MallocInst::MallocInst(const MallocInst &MI)
570 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
571 Instruction::Malloc, MI.getAlignment()) {
574 //===----------------------------------------------------------------------===//
575 // FreeInst Implementation
576 //===----------------------------------------------------------------------===//
578 void FreeInst::AssertOK() {
579 assert(isa<PointerType>(getOperand(0)->getType()) &&
580 "Can not free something of nonpointer type!");
583 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
584 : UnaryInstruction(Type::VoidTy, Free, Ptr, 0, InsertBefore) {
588 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
589 : UnaryInstruction(Type::VoidTy, Free, Ptr, 0, InsertAtEnd) {
594 //===----------------------------------------------------------------------===//
595 // LoadInst Implementation
596 //===----------------------------------------------------------------------===//
598 void LoadInst::AssertOK() {
599 assert(isa<PointerType>(getOperand(0)->getType()) &&
600 "Ptr must have pointer type.");
603 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
604 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
605 Load, Ptr, 0, InsertBef) {
611 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
612 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
613 Load, Ptr, 0, InsertAE) {
619 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
620 Instruction *InsertBef)
621 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
622 Load, Ptr, 0, InsertBef) {
623 setVolatile(isVolatile);
628 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
629 BasicBlock *InsertAE)
630 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
631 Load, Ptr, 0, InsertAE) {
632 setVolatile(isVolatile);
639 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
640 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
641 Load, Ptr, Name, InsertBef) {
646 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
647 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
648 Load, Ptr, Name, InsertAE) {
653 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
654 Instruction *InsertBef)
655 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
656 Load, Ptr, Name, InsertBef) {
657 setVolatile(isVolatile);
661 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
662 BasicBlock *InsertAE)
663 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
664 Load, Ptr, Name, InsertAE) {
665 setVolatile(isVolatile);
670 //===----------------------------------------------------------------------===//
671 // StoreInst Implementation
672 //===----------------------------------------------------------------------===//
674 void StoreInst::AssertOK() {
675 assert(isa<PointerType>(getOperand(1)->getType()) &&
676 "Ptr must have pointer type!");
677 assert(getOperand(0)->getType() ==
678 cast<PointerType>(getOperand(1)->getType())->getElementType()
679 && "Ptr must be a pointer to Val type!");
683 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
684 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertBefore) {
685 Ops[0].init(val, this);
686 Ops[1].init(addr, this);
691 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
692 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertAtEnd) {
693 Ops[0].init(val, this);
694 Ops[1].init(addr, this);
699 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
700 Instruction *InsertBefore)
701 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertBefore) {
702 Ops[0].init(val, this);
703 Ops[1].init(addr, this);
704 setVolatile(isVolatile);
708 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
709 BasicBlock *InsertAtEnd)
710 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertAtEnd) {
711 Ops[0].init(val, this);
712 Ops[1].init(addr, this);
713 setVolatile(isVolatile);
717 //===----------------------------------------------------------------------===//
718 // GetElementPtrInst Implementation
719 //===----------------------------------------------------------------------===//
721 // checkType - Simple wrapper function to give a better assertion failure
722 // message on bad indexes for a gep instruction.
724 static inline const Type *checkType(const Type *Ty) {
725 assert(Ty && "Invalid GetElementPtrInst indices for type!");
729 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx) {
730 NumOperands = 1+NumIdx;
731 Use *OL = OperandList = new Use[NumOperands];
732 OL[0].init(Ptr, this);
734 for (unsigned i = 0; i != NumIdx; ++i)
735 OL[i+1].init(Idx[i], this);
738 void GetElementPtrInst::init(Value *Ptr, Value *Idx0, Value *Idx1) {
740 Use *OL = OperandList = new Use[3];
741 OL[0].init(Ptr, this);
742 OL[1].init(Idx0, this);
743 OL[2].init(Idx1, this);
746 void GetElementPtrInst::init(Value *Ptr, Value *Idx) {
748 Use *OL = OperandList = new Use[2];
749 OL[0].init(Ptr, this);
750 OL[1].init(Idx, this);
754 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value* const *Idx,
756 const std::string &Name, Instruction *InBe)
757 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
758 Idx, NumIdx, true))),
759 GetElementPtr, 0, 0, Name, InBe) {
760 init(Ptr, Idx, NumIdx);
763 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value* const *Idx,
765 const std::string &Name, BasicBlock *IAE)
766 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
767 Idx, NumIdx, true))),
768 GetElementPtr, 0, 0, Name, IAE) {
769 init(Ptr, Idx, NumIdx);
772 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
773 const std::string &Name, Instruction *InBe)
774 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
776 GetElementPtr, 0, 0, Name, InBe) {
780 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
781 const std::string &Name, BasicBlock *IAE)
782 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
784 GetElementPtr, 0, 0, Name, IAE) {
788 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
789 const std::string &Name, Instruction *InBe)
790 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
792 GetElementPtr, 0, 0, Name, InBe) {
793 init(Ptr, Idx0, Idx1);
796 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
797 const std::string &Name, BasicBlock *IAE)
798 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
800 GetElementPtr, 0, 0, Name, IAE) {
801 init(Ptr, Idx0, Idx1);
804 GetElementPtrInst::~GetElementPtrInst() {
805 delete[] OperandList;
808 // getIndexedType - Returns the type of the element that would be loaded with
809 // a load instruction with the specified parameters.
811 // A null type is returned if the indices are invalid for the specified
814 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
817 bool AllowCompositeLeaf) {
818 if (!isa<PointerType>(Ptr)) return 0; // Type isn't a pointer type!
820 // Handle the special case of the empty set index set...
822 if (AllowCompositeLeaf ||
823 cast<PointerType>(Ptr)->getElementType()->isFirstClassType())
824 return cast<PointerType>(Ptr)->getElementType();
829 while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
830 if (NumIdx == CurIdx) {
831 if (AllowCompositeLeaf || CT->isFirstClassType()) return Ptr;
832 return 0; // Can't load a whole structure or array!?!?
835 Value *Index = Idxs[CurIdx++];
836 if (isa<PointerType>(CT) && CurIdx != 1)
837 return 0; // Can only index into pointer types at the first index!
838 if (!CT->indexValid(Index)) return 0;
839 Ptr = CT->getTypeAtIndex(Index);
841 // If the new type forwards to another type, then it is in the middle
842 // of being refined to another type (and hence, may have dropped all
843 // references to what it was using before). So, use the new forwarded
845 if (const Type * Ty = Ptr->getForwardedType()) {
849 return CurIdx == NumIdx ? Ptr : 0;
852 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
853 Value *Idx0, Value *Idx1,
854 bool AllowCompositeLeaf) {
855 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
856 if (!PTy) return 0; // Type isn't a pointer type!
858 // Check the pointer index.
859 if (!PTy->indexValid(Idx0)) return 0;
861 const CompositeType *CT = dyn_cast<CompositeType>(PTy->getElementType());
862 if (!CT || !CT->indexValid(Idx1)) return 0;
864 const Type *ElTy = CT->getTypeAtIndex(Idx1);
865 if (AllowCompositeLeaf || ElTy->isFirstClassType())
870 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
871 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
872 if (!PTy) return 0; // Type isn't a pointer type!
874 // Check the pointer index.
875 if (!PTy->indexValid(Idx)) return 0;
877 return PTy->getElementType();
880 //===----------------------------------------------------------------------===//
881 // ExtractElementInst Implementation
882 //===----------------------------------------------------------------------===//
884 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
885 const std::string &Name,
886 Instruction *InsertBef)
887 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
888 ExtractElement, Ops, 2, Name, InsertBef) {
889 assert(isValidOperands(Val, Index) &&
890 "Invalid extractelement instruction operands!");
891 Ops[0].init(Val, this);
892 Ops[1].init(Index, this);
895 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
896 const std::string &Name,
897 Instruction *InsertBef)
898 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
899 ExtractElement, Ops, 2, Name, InsertBef) {
900 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
901 assert(isValidOperands(Val, Index) &&
902 "Invalid extractelement instruction operands!");
903 Ops[0].init(Val, this);
904 Ops[1].init(Index, this);
908 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
909 const std::string &Name,
910 BasicBlock *InsertAE)
911 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
912 ExtractElement, Ops, 2, Name, InsertAE) {
913 assert(isValidOperands(Val, Index) &&
914 "Invalid extractelement instruction operands!");
916 Ops[0].init(Val, this);
917 Ops[1].init(Index, this);
920 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
921 const std::string &Name,
922 BasicBlock *InsertAE)
923 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
924 ExtractElement, Ops, 2, Name, InsertAE) {
925 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
926 assert(isValidOperands(Val, Index) &&
927 "Invalid extractelement instruction operands!");
929 Ops[0].init(Val, this);
930 Ops[1].init(Index, this);
934 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
935 if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty)
941 //===----------------------------------------------------------------------===//
942 // InsertElementInst Implementation
943 //===----------------------------------------------------------------------===//
945 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
946 : Instruction(IE.getType(), InsertElement, Ops, 3) {
947 Ops[0].init(IE.Ops[0], this);
948 Ops[1].init(IE.Ops[1], this);
949 Ops[2].init(IE.Ops[2], this);
951 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
952 const std::string &Name,
953 Instruction *InsertBef)
954 : Instruction(Vec->getType(), InsertElement, Ops, 3, Name, InsertBef) {
955 assert(isValidOperands(Vec, Elt, Index) &&
956 "Invalid insertelement instruction operands!");
957 Ops[0].init(Vec, this);
958 Ops[1].init(Elt, this);
959 Ops[2].init(Index, this);
962 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
963 const std::string &Name,
964 Instruction *InsertBef)
965 : Instruction(Vec->getType(), InsertElement, Ops, 3, Name, InsertBef) {
966 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
967 assert(isValidOperands(Vec, Elt, Index) &&
968 "Invalid insertelement instruction operands!");
969 Ops[0].init(Vec, this);
970 Ops[1].init(Elt, this);
971 Ops[2].init(Index, this);
975 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
976 const std::string &Name,
977 BasicBlock *InsertAE)
978 : Instruction(Vec->getType(), InsertElement, Ops, 3, Name, InsertAE) {
979 assert(isValidOperands(Vec, Elt, Index) &&
980 "Invalid insertelement instruction operands!");
982 Ops[0].init(Vec, this);
983 Ops[1].init(Elt, this);
984 Ops[2].init(Index, this);
987 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
988 const std::string &Name,
989 BasicBlock *InsertAE)
990 : Instruction(Vec->getType(), InsertElement, Ops, 3, Name, InsertAE) {
991 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
992 assert(isValidOperands(Vec, Elt, Index) &&
993 "Invalid insertelement instruction operands!");
995 Ops[0].init(Vec, this);
996 Ops[1].init(Elt, this);
997 Ops[2].init(Index, this);
1000 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1001 const Value *Index) {
1002 if (!isa<VectorType>(Vec->getType()))
1003 return false; // First operand of insertelement must be vector type.
1005 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1006 return false;// Second operand of insertelement must be packed element type.
1008 if (Index->getType() != Type::Int32Ty)
1009 return false; // Third operand of insertelement must be uint.
1014 //===----------------------------------------------------------------------===//
1015 // ShuffleVectorInst Implementation
1016 //===----------------------------------------------------------------------===//
1018 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
1019 : Instruction(SV.getType(), ShuffleVector, Ops, 3) {
1020 Ops[0].init(SV.Ops[0], this);
1021 Ops[1].init(SV.Ops[1], this);
1022 Ops[2].init(SV.Ops[2], this);
1025 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1026 const std::string &Name,
1027 Instruction *InsertBefore)
1028 : Instruction(V1->getType(), ShuffleVector, Ops, 3, Name, InsertBefore) {
1029 assert(isValidOperands(V1, V2, Mask) &&
1030 "Invalid shuffle vector instruction operands!");
1031 Ops[0].init(V1, this);
1032 Ops[1].init(V2, this);
1033 Ops[2].init(Mask, this);
1036 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1037 const std::string &Name,
1038 BasicBlock *InsertAtEnd)
1039 : Instruction(V1->getType(), ShuffleVector, Ops, 3, Name, InsertAtEnd) {
1040 assert(isValidOperands(V1, V2, Mask) &&
1041 "Invalid shuffle vector instruction operands!");
1043 Ops[0].init(V1, this);
1044 Ops[1].init(V2, this);
1045 Ops[2].init(Mask, this);
1048 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1049 const Value *Mask) {
1050 if (!isa<VectorType>(V1->getType())) return false;
1051 if (V1->getType() != V2->getType()) return false;
1052 if (!isa<VectorType>(Mask->getType()) ||
1053 cast<VectorType>(Mask->getType())->getElementType() != Type::Int32Ty ||
1054 cast<VectorType>(Mask->getType())->getNumElements() !=
1055 cast<VectorType>(V1->getType())->getNumElements())
1061 //===----------------------------------------------------------------------===//
1062 // BinaryOperator Class
1063 //===----------------------------------------------------------------------===//
1065 void BinaryOperator::init(BinaryOps iType)
1067 Value *LHS = getOperand(0), *RHS = getOperand(1);
1068 LHS = LHS; RHS = RHS; // Silence warnings.
1069 assert(LHS->getType() == RHS->getType() &&
1070 "Binary operator operand types must match!");
1075 assert(getType() == LHS->getType() &&
1076 "Arithmetic operation should return same type as operands!");
1077 assert((getType()->isInteger() || getType()->isFloatingPoint() ||
1078 isa<VectorType>(getType())) &&
1079 "Tried to create an arithmetic operation on a non-arithmetic type!");
1083 assert(getType() == LHS->getType() &&
1084 "Arithmetic operation should return same type as operands!");
1085 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1086 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1087 "Incorrect operand type (not integer) for S/UDIV");
1090 assert(getType() == LHS->getType() &&
1091 "Arithmetic operation should return same type as operands!");
1092 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1093 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1094 && "Incorrect operand type (not floating point) for FDIV");
1098 assert(getType() == LHS->getType() &&
1099 "Arithmetic operation should return same type as operands!");
1100 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1101 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1102 "Incorrect operand type (not integer) for S/UREM");
1105 assert(getType() == LHS->getType() &&
1106 "Arithmetic operation should return same type as operands!");
1107 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1108 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1109 && "Incorrect operand type (not floating point) for FREM");
1114 assert(getType() == LHS->getType() &&
1115 "Shift operation should return same type as operands!");
1116 assert(getType()->isInteger() &&
1117 "Shift operation requires integer operands");
1121 assert(getType() == LHS->getType() &&
1122 "Logical operation should return same type as operands!");
1123 assert((getType()->isInteger() ||
1124 (isa<VectorType>(getType()) &&
1125 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1126 "Tried to create a logical operation on a non-integral type!");
1134 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1135 const std::string &Name,
1136 Instruction *InsertBefore) {
1137 assert(S1->getType() == S2->getType() &&
1138 "Cannot create binary operator with two operands of differing type!");
1139 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1142 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1143 const std::string &Name,
1144 BasicBlock *InsertAtEnd) {
1145 BinaryOperator *Res = create(Op, S1, S2, Name);
1146 InsertAtEnd->getInstList().push_back(Res);
1150 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1151 Instruction *InsertBefore) {
1152 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1153 return new BinaryOperator(Instruction::Sub,
1155 Op->getType(), Name, InsertBefore);
1158 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1159 BasicBlock *InsertAtEnd) {
1160 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1161 return new BinaryOperator(Instruction::Sub,
1163 Op->getType(), Name, InsertAtEnd);
1166 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1167 Instruction *InsertBefore) {
1169 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1170 C = ConstantInt::getAllOnesValue(PTy->getElementType());
1171 C = ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), C));
1173 C = ConstantInt::getAllOnesValue(Op->getType());
1176 return new BinaryOperator(Instruction::Xor, Op, C,
1177 Op->getType(), Name, InsertBefore);
1180 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1181 BasicBlock *InsertAtEnd) {
1183 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1184 // Create a vector of all ones values.
1185 Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType());
1187 ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1189 AllOnes = ConstantInt::getAllOnesValue(Op->getType());
1192 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1193 Op->getType(), Name, InsertAtEnd);
1197 // isConstantAllOnes - Helper function for several functions below
1198 static inline bool isConstantAllOnes(const Value *V) {
1199 return isa<ConstantInt>(V) &&cast<ConstantInt>(V)->isAllOnesValue();
1202 bool BinaryOperator::isNeg(const Value *V) {
1203 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1204 if (Bop->getOpcode() == Instruction::Sub)
1205 return Bop->getOperand(0) ==
1206 ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1210 bool BinaryOperator::isNot(const Value *V) {
1211 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1212 return (Bop->getOpcode() == Instruction::Xor &&
1213 (isConstantAllOnes(Bop->getOperand(1)) ||
1214 isConstantAllOnes(Bop->getOperand(0))));
1218 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1219 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1220 return cast<BinaryOperator>(BinOp)->getOperand(1);
1223 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1224 return getNegArgument(const_cast<Value*>(BinOp));
1227 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1228 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1229 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1230 Value *Op0 = BO->getOperand(0);
1231 Value *Op1 = BO->getOperand(1);
1232 if (isConstantAllOnes(Op0)) return Op1;
1234 assert(isConstantAllOnes(Op1));
1238 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1239 return getNotArgument(const_cast<Value*>(BinOp));
1243 // swapOperands - Exchange the two operands to this instruction. This
1244 // instruction is safe to use on any binary instruction and does not
1245 // modify the semantics of the instruction. If the instruction is
1246 // order dependent (SetLT f.e.) the opcode is changed.
1248 bool BinaryOperator::swapOperands() {
1249 if (!isCommutative())
1250 return true; // Can't commute operands
1251 std::swap(Ops[0], Ops[1]);
1255 //===----------------------------------------------------------------------===//
1257 //===----------------------------------------------------------------------===//
1259 // Just determine if this cast only deals with integral->integral conversion.
1260 bool CastInst::isIntegerCast() const {
1261 switch (getOpcode()) {
1262 default: return false;
1263 case Instruction::ZExt:
1264 case Instruction::SExt:
1265 case Instruction::Trunc:
1267 case Instruction::BitCast:
1268 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1272 bool CastInst::isLosslessCast() const {
1273 // Only BitCast can be lossless, exit fast if we're not BitCast
1274 if (getOpcode() != Instruction::BitCast)
1277 // Identity cast is always lossless
1278 const Type* SrcTy = getOperand(0)->getType();
1279 const Type* DstTy = getType();
1283 // Pointer to pointer is always lossless.
1284 if (isa<PointerType>(SrcTy))
1285 return isa<PointerType>(DstTy);
1286 return false; // Other types have no identity values
1289 /// This function determines if the CastInst does not require any bits to be
1290 /// changed in order to effect the cast. Essentially, it identifies cases where
1291 /// no code gen is necessary for the cast, hence the name no-op cast. For
1292 /// example, the following are all no-op casts:
1293 /// # bitcast uint %X, int
1294 /// # bitcast uint* %x, sbyte*
1295 /// # bitcast packed< 2 x int > %x, packed< 4 x short>
1296 /// # ptrtoint uint* %x, uint ; on 32-bit plaforms only
1297 /// @brief Determine if a cast is a no-op.
1298 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1299 switch (getOpcode()) {
1301 assert(!"Invalid CastOp");
1302 case Instruction::Trunc:
1303 case Instruction::ZExt:
1304 case Instruction::SExt:
1305 case Instruction::FPTrunc:
1306 case Instruction::FPExt:
1307 case Instruction::UIToFP:
1308 case Instruction::SIToFP:
1309 case Instruction::FPToUI:
1310 case Instruction::FPToSI:
1311 return false; // These always modify bits
1312 case Instruction::BitCast:
1313 return true; // BitCast never modifies bits.
1314 case Instruction::PtrToInt:
1315 return IntPtrTy->getPrimitiveSizeInBits() ==
1316 getType()->getPrimitiveSizeInBits();
1317 case Instruction::IntToPtr:
1318 return IntPtrTy->getPrimitiveSizeInBits() ==
1319 getOperand(0)->getType()->getPrimitiveSizeInBits();
1323 /// This function determines if a pair of casts can be eliminated and what
1324 /// opcode should be used in the elimination. This assumes that there are two
1325 /// instructions like this:
1326 /// * %F = firstOpcode SrcTy %x to MidTy
1327 /// * %S = secondOpcode MidTy %F to DstTy
1328 /// The function returns a resultOpcode so these two casts can be replaced with:
1329 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1330 /// If no such cast is permited, the function returns 0.
1331 unsigned CastInst::isEliminableCastPair(
1332 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1333 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1335 // Define the 144 possibilities for these two cast instructions. The values
1336 // in this matrix determine what to do in a given situation and select the
1337 // case in the switch below. The rows correspond to firstOp, the columns
1338 // correspond to secondOp. In looking at the table below, keep in mind
1339 // the following cast properties:
1341 // Size Compare Source Destination
1342 // Operator Src ? Size Type Sign Type Sign
1343 // -------- ------------ ------------------- ---------------------
1344 // TRUNC > Integer Any Integral Any
1345 // ZEXT < Integral Unsigned Integer Any
1346 // SEXT < Integral Signed Integer Any
1347 // FPTOUI n/a FloatPt n/a Integral Unsigned
1348 // FPTOSI n/a FloatPt n/a Integral Signed
1349 // UITOFP n/a Integral Unsigned FloatPt n/a
1350 // SITOFP n/a Integral Signed FloatPt n/a
1351 // FPTRUNC > FloatPt n/a FloatPt n/a
1352 // FPEXT < FloatPt n/a FloatPt n/a
1353 // PTRTOINT n/a Pointer n/a Integral Unsigned
1354 // INTTOPTR n/a Integral Unsigned Pointer n/a
1355 // BITCONVERT = FirstClass n/a FirstClass n/a
1357 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1358 // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
1359 // into "fptoui double to ulong", but this loses information about the range
1360 // of the produced value (we no longer know the top-part is all zeros).
1361 // Further this conversion is often much more expensive for typical hardware,
1362 // and causes issues when building libgcc. We disallow fptosi+sext for the
1364 const unsigned numCastOps =
1365 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1366 static const uint8_t CastResults[numCastOps][numCastOps] = {
1367 // T F F U S F F P I B -+
1368 // R Z S P P I I T P 2 N T |
1369 // U E E 2 2 2 2 R E I T C +- secondOp
1370 // N X X U S F F N X N 2 V |
1371 // C T T I I P P C T T P T -+
1372 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1373 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1374 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1375 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1376 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1377 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1378 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1379 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1380 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1381 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1382 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1383 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1386 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1387 [secondOp-Instruction::CastOpsBegin];
1390 // categorically disallowed
1393 // allowed, use first cast's opcode
1396 // allowed, use second cast's opcode
1399 // no-op cast in second op implies firstOp as long as the DestTy
1401 if (DstTy->isInteger())
1405 // no-op cast in second op implies firstOp as long as the DestTy
1406 // is floating point
1407 if (DstTy->isFloatingPoint())
1411 // no-op cast in first op implies secondOp as long as the SrcTy
1413 if (SrcTy->isInteger())
1417 // no-op cast in first op implies secondOp as long as the SrcTy
1418 // is a floating point
1419 if (SrcTy->isFloatingPoint())
1423 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1424 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1425 unsigned MidSize = MidTy->getPrimitiveSizeInBits();
1426 if (MidSize >= PtrSize)
1427 return Instruction::BitCast;
1431 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1432 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1433 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1434 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1435 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1436 if (SrcSize == DstSize)
1437 return Instruction::BitCast;
1438 else if (SrcSize < DstSize)
1442 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1443 return Instruction::ZExt;
1445 // fpext followed by ftrunc is allowed if the bit size returned to is
1446 // the same as the original, in which case its just a bitcast
1448 return Instruction::BitCast;
1449 return 0; // If the types are not the same we can't eliminate it.
1451 // bitcast followed by ptrtoint is allowed as long as the bitcast
1452 // is a pointer to pointer cast.
1453 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1457 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1458 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1462 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1463 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1464 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1465 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1466 if (SrcSize <= PtrSize && SrcSize == DstSize)
1467 return Instruction::BitCast;
1471 // cast combination can't happen (error in input). This is for all cases
1472 // where the MidTy is not the same for the two cast instructions.
1473 assert(!"Invalid Cast Combination");
1476 assert(!"Error in CastResults table!!!");
1482 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1483 const std::string &Name, Instruction *InsertBefore) {
1484 // Construct and return the appropriate CastInst subclass
1486 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1487 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1488 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1489 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1490 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1491 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1492 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1493 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1494 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1495 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1496 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1497 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1499 assert(!"Invalid opcode provided");
1504 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1505 const std::string &Name, BasicBlock *InsertAtEnd) {
1506 // Construct and return the appropriate CastInst subclass
1508 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1509 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1510 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1511 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1512 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1513 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1514 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1515 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1516 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1517 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1518 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1519 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1521 assert(!"Invalid opcode provided");
1526 CastInst *CastInst::createZExtOrBitCast(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::ZExt, S, Ty, Name, InsertBefore);
1534 CastInst *CastInst::createZExtOrBitCast(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::ZExt, S, Ty, Name, InsertAtEnd);
1542 CastInst *CastInst::createSExtOrBitCast(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::SExt, S, Ty, Name, InsertBefore);
1550 CastInst *CastInst::createSExtOrBitCast(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::SExt, S, Ty, Name, InsertAtEnd);
1558 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1559 const std::string &Name,
1560 Instruction *InsertBefore) {
1561 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1562 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1563 return create(Instruction::Trunc, S, Ty, Name, InsertBefore);
1566 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1567 const std::string &Name,
1568 BasicBlock *InsertAtEnd) {
1569 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1570 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1571 return create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
1574 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1575 const std::string &Name,
1576 BasicBlock *InsertAtEnd) {
1577 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1578 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1581 if (Ty->isInteger())
1582 return create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
1583 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1586 /// @brief Create a BitCast or a PtrToInt cast instruction
1587 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1588 const std::string &Name,
1589 Instruction *InsertBefore) {
1590 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1591 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1594 if (Ty->isInteger())
1595 return create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
1596 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1599 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1600 bool isSigned, const std::string &Name,
1601 Instruction *InsertBefore) {
1602 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1603 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1604 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1605 Instruction::CastOps opcode =
1606 (SrcBits == DstBits ? Instruction::BitCast :
1607 (SrcBits > DstBits ? Instruction::Trunc :
1608 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1609 return create(opcode, C, Ty, Name, InsertBefore);
1612 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1613 bool isSigned, const std::string &Name,
1614 BasicBlock *InsertAtEnd) {
1615 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1616 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1617 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1618 Instruction::CastOps opcode =
1619 (SrcBits == DstBits ? Instruction::BitCast :
1620 (SrcBits > DstBits ? Instruction::Trunc :
1621 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1622 return create(opcode, C, Ty, Name, InsertAtEnd);
1625 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1626 const std::string &Name,
1627 Instruction *InsertBefore) {
1628 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1630 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1631 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1632 Instruction::CastOps opcode =
1633 (SrcBits == DstBits ? Instruction::BitCast :
1634 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1635 return create(opcode, C, Ty, Name, InsertBefore);
1638 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1639 const std::string &Name,
1640 BasicBlock *InsertAtEnd) {
1641 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1643 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1644 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1645 Instruction::CastOps opcode =
1646 (SrcBits == DstBits ? Instruction::BitCast :
1647 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1648 return create(opcode, C, Ty, Name, InsertAtEnd);
1651 // Provide a way to get a "cast" where the cast opcode is inferred from the
1652 // types and size of the operand. This, basically, is a parallel of the
1653 // logic in the castIsValid function below. This axiom should hold:
1654 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
1655 // should not assert in castIsValid. In other words, this produces a "correct"
1656 // casting opcode for the arguments passed to it.
1657 Instruction::CastOps
1658 CastInst::getCastOpcode(
1659 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
1660 // Get the bit sizes, we'll need these
1661 const Type *SrcTy = Src->getType();
1662 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/packed
1663 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/packed
1665 // Run through the possibilities ...
1666 if (DestTy->isInteger()) { // Casting to integral
1667 if (SrcTy->isInteger()) { // Casting from integral
1668 if (DestBits < SrcBits)
1669 return Trunc; // int -> smaller int
1670 else if (DestBits > SrcBits) { // its an extension
1672 return SExt; // signed -> SEXT
1674 return ZExt; // unsigned -> ZEXT
1676 return BitCast; // Same size, No-op cast
1678 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1680 return FPToSI; // FP -> sint
1682 return FPToUI; // FP -> uint
1683 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1684 assert(DestBits == PTy->getBitWidth() &&
1685 "Casting packed to integer of different width");
1686 return BitCast; // Same size, no-op cast
1688 assert(isa<PointerType>(SrcTy) &&
1689 "Casting from a value that is not first-class type");
1690 return PtrToInt; // ptr -> int
1692 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
1693 if (SrcTy->isInteger()) { // Casting from integral
1695 return SIToFP; // sint -> FP
1697 return UIToFP; // uint -> FP
1698 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1699 if (DestBits < SrcBits) {
1700 return FPTrunc; // FP -> smaller FP
1701 } else if (DestBits > SrcBits) {
1702 return FPExt; // FP -> larger FP
1704 return BitCast; // same size, no-op cast
1706 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1707 assert(DestBits == PTy->getBitWidth() &&
1708 "Casting packed to floating point of different width");
1709 return BitCast; // same size, no-op cast
1711 assert(0 && "Casting pointer or non-first class to float");
1713 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
1714 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
1715 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
1716 "Casting packed to packed of different widths");
1717 return BitCast; // packed -> packed
1718 } else if (DestPTy->getBitWidth() == SrcBits) {
1719 return BitCast; // float/int -> packed
1721 assert(!"Illegal cast to packed (wrong type or size)");
1723 } else if (isa<PointerType>(DestTy)) {
1724 if (isa<PointerType>(SrcTy)) {
1725 return BitCast; // ptr -> ptr
1726 } else if (SrcTy->isInteger()) {
1727 return IntToPtr; // int -> ptr
1729 assert(!"Casting pointer to other than pointer or int");
1732 assert(!"Casting to type that is not first-class");
1735 // If we fall through to here we probably hit an assertion cast above
1736 // and assertions are not turned on. Anything we return is an error, so
1737 // BitCast is as good a choice as any.
1741 //===----------------------------------------------------------------------===//
1742 // CastInst SubClass Constructors
1743 //===----------------------------------------------------------------------===//
1745 /// Check that the construction parameters for a CastInst are correct. This
1746 /// could be broken out into the separate constructors but it is useful to have
1747 /// it in one place and to eliminate the redundant code for getting the sizes
1748 /// of the types involved.
1750 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
1752 // Check for type sanity on the arguments
1753 const Type *SrcTy = S->getType();
1754 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
1757 // Get the size of the types in bits, we'll need this later
1758 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1759 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1761 // Switch on the opcode provided
1763 default: return false; // This is an input error
1764 case Instruction::Trunc:
1765 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize > DstBitSize;
1766 case Instruction::ZExt:
1767 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
1768 case Instruction::SExt:
1769 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
1770 case Instruction::FPTrunc:
1771 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
1772 SrcBitSize > DstBitSize;
1773 case Instruction::FPExt:
1774 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
1775 SrcBitSize < DstBitSize;
1776 case Instruction::UIToFP:
1777 return SrcTy->isInteger() && DstTy->isFloatingPoint();
1778 case Instruction::SIToFP:
1779 return SrcTy->isInteger() && DstTy->isFloatingPoint();
1780 case Instruction::FPToUI:
1781 return SrcTy->isFloatingPoint() && DstTy->isInteger();
1782 case Instruction::FPToSI:
1783 return SrcTy->isFloatingPoint() && DstTy->isInteger();
1784 case Instruction::PtrToInt:
1785 return isa<PointerType>(SrcTy) && DstTy->isInteger();
1786 case Instruction::IntToPtr:
1787 return SrcTy->isInteger() && isa<PointerType>(DstTy);
1788 case Instruction::BitCast:
1789 // BitCast implies a no-op cast of type only. No bits change.
1790 // However, you can't cast pointers to anything but pointers.
1791 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
1794 // Now we know we're not dealing with a pointer/non-poiner mismatch. In all
1795 // these cases, the cast is okay if the source and destination bit widths
1797 return SrcBitSize == DstBitSize;
1801 TruncInst::TruncInst(
1802 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1803 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
1804 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
1807 TruncInst::TruncInst(
1808 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1809 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
1810 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
1814 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1815 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
1816 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
1820 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1821 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
1822 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
1825 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1826 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
1827 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
1831 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1832 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
1833 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
1836 FPTruncInst::FPTruncInst(
1837 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1838 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
1839 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
1842 FPTruncInst::FPTruncInst(
1843 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1844 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
1845 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
1848 FPExtInst::FPExtInst(
1849 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1850 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
1851 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
1854 FPExtInst::FPExtInst(
1855 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1856 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
1857 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
1860 UIToFPInst::UIToFPInst(
1861 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1862 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
1863 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
1866 UIToFPInst::UIToFPInst(
1867 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1868 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
1869 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
1872 SIToFPInst::SIToFPInst(
1873 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1874 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
1875 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
1878 SIToFPInst::SIToFPInst(
1879 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1880 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
1881 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
1884 FPToUIInst::FPToUIInst(
1885 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1886 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
1887 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
1890 FPToUIInst::FPToUIInst(
1891 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1892 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
1893 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
1896 FPToSIInst::FPToSIInst(
1897 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1898 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
1899 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
1902 FPToSIInst::FPToSIInst(
1903 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1904 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
1905 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
1908 PtrToIntInst::PtrToIntInst(
1909 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1910 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
1911 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
1914 PtrToIntInst::PtrToIntInst(
1915 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1916 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
1917 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
1920 IntToPtrInst::IntToPtrInst(
1921 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1922 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
1923 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
1926 IntToPtrInst::IntToPtrInst(
1927 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1928 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
1929 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
1932 BitCastInst::BitCastInst(
1933 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1934 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
1935 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
1938 BitCastInst::BitCastInst(
1939 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1940 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
1941 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
1944 //===----------------------------------------------------------------------===//
1946 //===----------------------------------------------------------------------===//
1948 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
1949 const std::string &Name, Instruction *InsertBefore)
1950 : Instruction(Type::Int1Ty, op, Ops, 2, Name, InsertBefore) {
1951 Ops[0].init(LHS, this);
1952 Ops[1].init(RHS, this);
1953 SubclassData = predicate;
1954 if (op == Instruction::ICmp) {
1955 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
1956 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
1957 "Invalid ICmp predicate value");
1958 const Type* Op0Ty = getOperand(0)->getType();
1959 const Type* Op1Ty = getOperand(1)->getType();
1960 assert(Op0Ty == Op1Ty &&
1961 "Both operands to ICmp instruction are not of the same type!");
1962 // Check that the operands are the right type
1963 assert((Op0Ty->isInteger() || isa<PointerType>(Op0Ty)) &&
1964 "Invalid operand types for ICmp instruction");
1967 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
1968 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
1969 "Invalid FCmp predicate value");
1970 const Type* Op0Ty = getOperand(0)->getType();
1971 const Type* Op1Ty = getOperand(1)->getType();
1972 assert(Op0Ty == Op1Ty &&
1973 "Both operands to FCmp instruction are not of the same type!");
1974 // Check that the operands are the right type
1975 assert(Op0Ty->isFloatingPoint() &&
1976 "Invalid operand types for FCmp instruction");
1979 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
1980 const std::string &Name, BasicBlock *InsertAtEnd)
1981 : Instruction(Type::Int1Ty, op, Ops, 2, Name, InsertAtEnd) {
1982 Ops[0].init(LHS, this);
1983 Ops[1].init(RHS, this);
1984 SubclassData = predicate;
1985 if (op == Instruction::ICmp) {
1986 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
1987 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
1988 "Invalid ICmp predicate value");
1990 const Type* Op0Ty = getOperand(0)->getType();
1991 const Type* Op1Ty = getOperand(1)->getType();
1992 assert(Op0Ty == Op1Ty &&
1993 "Both operands to ICmp instruction are not of the same type!");
1994 // Check that the operands are the right type
1995 assert(Op0Ty->isInteger() || isa<PointerType>(Op0Ty) &&
1996 "Invalid operand types for ICmp instruction");
1999 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2000 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2001 "Invalid FCmp predicate value");
2002 const Type* Op0Ty = getOperand(0)->getType();
2003 const Type* Op1Ty = getOperand(1)->getType();
2004 assert(Op0Ty == Op1Ty &&
2005 "Both operands to FCmp instruction are not of the same type!");
2006 // Check that the operands are the right type
2007 assert(Op0Ty->isFloatingPoint() &&
2008 "Invalid operand types for FCmp instruction");
2012 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2013 const std::string &Name, Instruction *InsertBefore) {
2014 if (Op == Instruction::ICmp) {
2015 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2018 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2023 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2024 const std::string &Name, BasicBlock *InsertAtEnd) {
2025 if (Op == Instruction::ICmp) {
2026 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2029 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2033 void CmpInst::swapOperands() {
2034 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2037 cast<FCmpInst>(this)->swapOperands();
2040 bool CmpInst::isCommutative() {
2041 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2042 return IC->isCommutative();
2043 return cast<FCmpInst>(this)->isCommutative();
2046 bool CmpInst::isEquality() {
2047 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2048 return IC->isEquality();
2049 return cast<FCmpInst>(this)->isEquality();
2053 ICmpInst::Predicate ICmpInst::getInversePredicate(Predicate pred) {
2056 assert(!"Unknown icmp predicate!");
2057 case ICMP_EQ: return ICMP_NE;
2058 case ICMP_NE: return ICMP_EQ;
2059 case ICMP_UGT: return ICMP_ULE;
2060 case ICMP_ULT: return ICMP_UGE;
2061 case ICMP_UGE: return ICMP_ULT;
2062 case ICMP_ULE: return ICMP_UGT;
2063 case ICMP_SGT: return ICMP_SLE;
2064 case ICMP_SLT: return ICMP_SGE;
2065 case ICMP_SGE: return ICMP_SLT;
2066 case ICMP_SLE: return ICMP_SGT;
2070 ICmpInst::Predicate ICmpInst::getSwappedPredicate(Predicate pred) {
2072 default: assert(! "Unknown icmp predicate!");
2073 case ICMP_EQ: case ICMP_NE:
2075 case ICMP_SGT: return ICMP_SLT;
2076 case ICMP_SLT: return ICMP_SGT;
2077 case ICMP_SGE: return ICMP_SLE;
2078 case ICMP_SLE: return ICMP_SGE;
2079 case ICMP_UGT: return ICMP_ULT;
2080 case ICMP_ULT: return ICMP_UGT;
2081 case ICMP_UGE: return ICMP_ULE;
2082 case ICMP_ULE: return ICMP_UGE;
2086 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2088 default: assert(! "Unknown icmp predicate!");
2089 case ICMP_EQ: case ICMP_NE:
2090 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2092 case ICMP_UGT: return ICMP_SGT;
2093 case ICMP_ULT: return ICMP_SLT;
2094 case ICMP_UGE: return ICMP_SGE;
2095 case ICMP_ULE: return ICMP_SLE;
2099 bool ICmpInst::isSignedPredicate(Predicate pred) {
2101 default: assert(! "Unknown icmp predicate!");
2102 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2104 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2105 case ICMP_UGE: case ICMP_ULE:
2110 FCmpInst::Predicate FCmpInst::getInversePredicate(Predicate pred) {
2113 assert(!"Unknown icmp predicate!");
2114 case FCMP_OEQ: return FCMP_UNE;
2115 case FCMP_ONE: return FCMP_UEQ;
2116 case FCMP_OGT: return FCMP_ULE;
2117 case FCMP_OLT: return FCMP_UGE;
2118 case FCMP_OGE: return FCMP_ULT;
2119 case FCMP_OLE: return FCMP_UGT;
2120 case FCMP_UEQ: return FCMP_ONE;
2121 case FCMP_UNE: return FCMP_OEQ;
2122 case FCMP_UGT: return FCMP_OLE;
2123 case FCMP_ULT: return FCMP_OGE;
2124 case FCMP_UGE: return FCMP_OLT;
2125 case FCMP_ULE: return FCMP_OGT;
2126 case FCMP_ORD: return FCMP_UNO;
2127 case FCMP_UNO: return FCMP_ORD;
2128 case FCMP_TRUE: return FCMP_FALSE;
2129 case FCMP_FALSE: return FCMP_TRUE;
2133 FCmpInst::Predicate FCmpInst::getSwappedPredicate(Predicate pred) {
2135 default: assert(!"Unknown fcmp predicate!");
2136 case FCMP_FALSE: case FCMP_TRUE:
2137 case FCMP_OEQ: case FCMP_ONE:
2138 case FCMP_UEQ: case FCMP_UNE:
2139 case FCMP_ORD: case FCMP_UNO:
2141 case FCMP_OGT: return FCMP_OLT;
2142 case FCMP_OLT: return FCMP_OGT;
2143 case FCMP_OGE: return FCMP_OLE;
2144 case FCMP_OLE: return FCMP_OGE;
2145 case FCMP_UGT: return FCMP_ULT;
2146 case FCMP_ULT: return FCMP_UGT;
2147 case FCMP_UGE: return FCMP_ULE;
2148 case FCMP_ULE: return FCMP_UGE;
2152 bool CmpInst::isUnsigned(unsigned short predicate) {
2153 switch (predicate) {
2154 default: return false;
2155 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2156 case ICmpInst::ICMP_UGE: return true;
2160 bool CmpInst::isSigned(unsigned short predicate){
2161 switch (predicate) {
2162 default: return false;
2163 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2164 case ICmpInst::ICMP_SGE: return true;
2168 bool CmpInst::isOrdered(unsigned short predicate) {
2169 switch (predicate) {
2170 default: return false;
2171 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2172 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2173 case FCmpInst::FCMP_ORD: return true;
2177 bool CmpInst::isUnordered(unsigned short predicate) {
2178 switch (predicate) {
2179 default: return false;
2180 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2181 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2182 case FCmpInst::FCMP_UNO: return true;
2186 //===----------------------------------------------------------------------===//
2187 // SwitchInst Implementation
2188 //===----------------------------------------------------------------------===//
2190 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2191 assert(Value && Default);
2192 ReservedSpace = 2+NumCases*2;
2194 OperandList = new Use[ReservedSpace];
2196 OperandList[0].init(Value, this);
2197 OperandList[1].init(Default, this);
2200 SwitchInst::SwitchInst(const SwitchInst &SI)
2201 : TerminatorInst(Instruction::Switch, new Use[SI.getNumOperands()],
2202 SI.getNumOperands()) {
2203 Use *OL = OperandList, *InOL = SI.OperandList;
2204 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2205 OL[i].init(InOL[i], this);
2206 OL[i+1].init(InOL[i+1], this);
2210 SwitchInst::~SwitchInst() {
2211 delete [] OperandList;
2215 /// addCase - Add an entry to the switch instruction...
2217 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2218 unsigned OpNo = NumOperands;
2219 if (OpNo+2 > ReservedSpace)
2220 resizeOperands(0); // Get more space!
2221 // Initialize some new operands.
2222 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2223 NumOperands = OpNo+2;
2224 OperandList[OpNo].init(OnVal, this);
2225 OperandList[OpNo+1].init(Dest, this);
2228 /// removeCase - This method removes the specified successor from the switch
2229 /// instruction. Note that this cannot be used to remove the default
2230 /// destination (successor #0).
2232 void SwitchInst::removeCase(unsigned idx) {
2233 assert(idx != 0 && "Cannot remove the default case!");
2234 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2236 unsigned NumOps = getNumOperands();
2237 Use *OL = OperandList;
2239 // Move everything after this operand down.
2241 // FIXME: we could just swap with the end of the list, then erase. However,
2242 // client might not expect this to happen. The code as it is thrashes the
2243 // use/def lists, which is kinda lame.
2244 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2246 OL[i-2+1] = OL[i+1];
2249 // Nuke the last value.
2250 OL[NumOps-2].set(0);
2251 OL[NumOps-2+1].set(0);
2252 NumOperands = NumOps-2;
2255 /// resizeOperands - resize operands - This adjusts the length of the operands
2256 /// list according to the following behavior:
2257 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2258 /// of operation. This grows the number of ops by 1.5 times.
2259 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2260 /// 3. If NumOps == NumOperands, trim the reserved space.
2262 void SwitchInst::resizeOperands(unsigned NumOps) {
2264 NumOps = getNumOperands()/2*6;
2265 } else if (NumOps*2 > NumOperands) {
2266 // No resize needed.
2267 if (ReservedSpace >= NumOps) return;
2268 } else if (NumOps == NumOperands) {
2269 if (ReservedSpace == NumOps) return;
2274 ReservedSpace = NumOps;
2275 Use *NewOps = new Use[NumOps];
2276 Use *OldOps = OperandList;
2277 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2278 NewOps[i].init(OldOps[i], this);
2282 OperandList = NewOps;
2286 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2287 return getSuccessor(idx);
2289 unsigned SwitchInst::getNumSuccessorsV() const {
2290 return getNumSuccessors();
2292 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2293 setSuccessor(idx, B);
2297 // Define these methods here so vtables don't get emitted into every translation
2298 // unit that uses these classes.
2300 GetElementPtrInst *GetElementPtrInst::clone() const {
2301 return new GetElementPtrInst(*this);
2304 BinaryOperator *BinaryOperator::clone() const {
2305 return create(getOpcode(), Ops[0], Ops[1]);
2308 CmpInst* CmpInst::clone() const {
2309 return create(getOpcode(), getPredicate(), Ops[0], Ops[1]);
2312 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
2313 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
2314 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
2315 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
2316 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
2317 CastInst *TruncInst::clone() const { return new TruncInst(*this); }
2318 CastInst *ZExtInst::clone() const { return new ZExtInst(*this); }
2319 CastInst *SExtInst::clone() const { return new SExtInst(*this); }
2320 CastInst *FPTruncInst::clone() const { return new FPTruncInst(*this); }
2321 CastInst *FPExtInst::clone() const { return new FPExtInst(*this); }
2322 CastInst *UIToFPInst::clone() const { return new UIToFPInst(*this); }
2323 CastInst *SIToFPInst::clone() const { return new SIToFPInst(*this); }
2324 CastInst *FPToUIInst::clone() const { return new FPToUIInst(*this); }
2325 CastInst *FPToSIInst::clone() const { return new FPToSIInst(*this); }
2326 CastInst *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
2327 CastInst *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
2328 CastInst *BitCastInst::clone() const { return new BitCastInst(*this); }
2329 CallInst *CallInst::clone() const { return new CallInst(*this); }
2330 SelectInst *SelectInst::clone() const { return new SelectInst(*this); }
2331 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
2333 ExtractElementInst *ExtractElementInst::clone() const {
2334 return new ExtractElementInst(*this);
2336 InsertElementInst *InsertElementInst::clone() const {
2337 return new InsertElementInst(*this);
2339 ShuffleVectorInst *ShuffleVectorInst::clone() const {
2340 return new ShuffleVectorInst(*this);
2342 PHINode *PHINode::clone() const { return new PHINode(*this); }
2343 ReturnInst *ReturnInst::clone() const { return new ReturnInst(*this); }
2344 BranchInst *BranchInst::clone() const { return new BranchInst(*this); }
2345 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
2346 InvokeInst *InvokeInst::clone() const { return new InvokeInst(*this); }
2347 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
2348 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}