Fix PR1146: parameter attributes are longer part of
[oota-llvm.git] / lib / VMCore / Instructions.cpp
1 //===-- Instructions.cpp - Implement the LLVM instructions ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements all of the non-inline methods for the LLVM instruction
11 // classes.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/BasicBlock.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/ParameterAttributes.h"
21 #include "llvm/Support/CallSite.h"
22 #include "llvm/Support/ConstantRange.h"
23 #include "llvm/Support/MathExtras.h"
24 using namespace llvm;
25
26 unsigned CallSite::getCallingConv() const {
27   if (CallInst *CI = dyn_cast<CallInst>(I))
28     return CI->getCallingConv();
29   else
30     return cast<InvokeInst>(I)->getCallingConv();
31 }
32 void CallSite::setCallingConv(unsigned CC) {
33   if (CallInst *CI = dyn_cast<CallInst>(I))
34     CI->setCallingConv(CC);
35   else
36     cast<InvokeInst>(I)->setCallingConv(CC);
37 }
38 const ParamAttrsList* CallSite::getParamAttrs() const {
39   if (CallInst *CI = dyn_cast<CallInst>(I))
40     return CI->getParamAttrs();
41   else
42     return cast<InvokeInst>(I)->getParamAttrs();
43 }
44 void CallSite::setParamAttrs(const ParamAttrsList *PAL) {
45   if (CallInst *CI = dyn_cast<CallInst>(I))
46     CI->setParamAttrs(PAL);
47   else
48     cast<InvokeInst>(I)->setParamAttrs(PAL);
49 }
50
51
52
53
54 //===----------------------------------------------------------------------===//
55 //                            TerminatorInst Class
56 //===----------------------------------------------------------------------===//
57
58 // Out of line virtual method, so the vtable, etc has a home.
59 TerminatorInst::~TerminatorInst() {
60 }
61
62 // Out of line virtual method, so the vtable, etc has a home.
63 UnaryInstruction::~UnaryInstruction() {
64 }
65
66
67 //===----------------------------------------------------------------------===//
68 //                               PHINode Class
69 //===----------------------------------------------------------------------===//
70
71 PHINode::PHINode(const PHINode &PN)
72   : Instruction(PN.getType(), Instruction::PHI,
73                 new Use[PN.getNumOperands()], PN.getNumOperands()),
74     ReservedSpace(PN.getNumOperands()) {
75   Use *OL = OperandList;
76   for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
77     OL[i].init(PN.getOperand(i), this);
78     OL[i+1].init(PN.getOperand(i+1), this);
79   }
80 }
81
82 PHINode::~PHINode() {
83   delete [] OperandList;
84 }
85
86 // removeIncomingValue - Remove an incoming value.  This is useful if a
87 // predecessor basic block is deleted.
88 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
89   unsigned NumOps = getNumOperands();
90   Use *OL = OperandList;
91   assert(Idx*2 < NumOps && "BB not in PHI node!");
92   Value *Removed = OL[Idx*2];
93
94   // Move everything after this operand down.
95   //
96   // FIXME: we could just swap with the end of the list, then erase.  However,
97   // client might not expect this to happen.  The code as it is thrashes the
98   // use/def lists, which is kinda lame.
99   for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
100     OL[i-2] = OL[i];
101     OL[i-2+1] = OL[i+1];
102   }
103
104   // Nuke the last value.
105   OL[NumOps-2].set(0);
106   OL[NumOps-2+1].set(0);
107   NumOperands = NumOps-2;
108
109   // If the PHI node is dead, because it has zero entries, nuke it now.
110   if (NumOps == 2 && DeletePHIIfEmpty) {
111     // If anyone is using this PHI, make them use a dummy value instead...
112     replaceAllUsesWith(UndefValue::get(getType()));
113     eraseFromParent();
114   }
115   return Removed;
116 }
117
118 /// resizeOperands - resize operands - This adjusts the length of the operands
119 /// list according to the following behavior:
120 ///   1. If NumOps == 0, grow the operand list in response to a push_back style
121 ///      of operation.  This grows the number of ops by 1.5 times.
122 ///   2. If NumOps > NumOperands, reserve space for NumOps operands.
123 ///   3. If NumOps == NumOperands, trim the reserved space.
124 ///
125 void PHINode::resizeOperands(unsigned NumOps) {
126   if (NumOps == 0) {
127     NumOps = (getNumOperands())*3/2;
128     if (NumOps < 4) NumOps = 4;      // 4 op PHI nodes are VERY common.
129   } else if (NumOps*2 > NumOperands) {
130     // No resize needed.
131     if (ReservedSpace >= NumOps) return;
132   } else if (NumOps == NumOperands) {
133     if (ReservedSpace == NumOps) return;
134   } else {
135     return;
136   }
137
138   ReservedSpace = NumOps;
139   Use *NewOps = new Use[NumOps];
140   Use *OldOps = OperandList;
141   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
142       NewOps[i].init(OldOps[i], this);
143       OldOps[i].set(0);
144   }
145   delete [] OldOps;
146   OperandList = NewOps;
147 }
148
149 /// hasConstantValue - If the specified PHI node always merges together the same
150 /// value, return the value, otherwise return null.
151 ///
152 Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) const {
153   // If the PHI node only has one incoming value, eliminate the PHI node...
154   if (getNumIncomingValues() == 1)
155     if (getIncomingValue(0) != this)   // not  X = phi X
156       return getIncomingValue(0);
157     else
158       return UndefValue::get(getType());  // Self cycle is dead.
159       
160   // Otherwise if all of the incoming values are the same for the PHI, replace
161   // the PHI node with the incoming value.
162   //
163   Value *InVal = 0;
164   bool HasUndefInput = false;
165   for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
166     if (isa<UndefValue>(getIncomingValue(i)))
167       HasUndefInput = true;
168     else if (getIncomingValue(i) != this)  // Not the PHI node itself...
169       if (InVal && getIncomingValue(i) != InVal)
170         return 0;  // Not the same, bail out.
171       else
172         InVal = getIncomingValue(i);
173   
174   // The only case that could cause InVal to be null is if we have a PHI node
175   // that only has entries for itself.  In this case, there is no entry into the
176   // loop, so kill the PHI.
177   //
178   if (InVal == 0) InVal = UndefValue::get(getType());
179   
180   // If we have a PHI node like phi(X, undef, X), where X is defined by some
181   // instruction, we cannot always return X as the result of the PHI node.  Only
182   // do this if X is not an instruction (thus it must dominate the PHI block),
183   // or if the client is prepared to deal with this possibility.
184   if (HasUndefInput && !AllowNonDominatingInstruction)
185     if (Instruction *IV = dyn_cast<Instruction>(InVal))
186       // If it's in the entry block, it dominates everything.
187       if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
188           isa<InvokeInst>(IV))
189         return 0;   // Cannot guarantee that InVal dominates this PHINode.
190
191   // All of the incoming values are the same, return the value now.
192   return InVal;
193 }
194
195
196 //===----------------------------------------------------------------------===//
197 //                        CallInst Implementation
198 //===----------------------------------------------------------------------===//
199
200 CallInst::~CallInst() {
201   delete [] OperandList;
202   if (ParamAttrs)
203     ParamAttrs->dropRef();
204 }
205
206 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
207   ParamAttrs = 0;
208   NumOperands = NumParams+1;
209   Use *OL = OperandList = new Use[NumParams+1];
210   OL[0].init(Func, this);
211
212   const FunctionType *FTy =
213     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
214   FTy = FTy;  // silence warning.
215
216   assert((NumParams == FTy->getNumParams() ||
217           (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
218          "Calling a function with bad signature!");
219   for (unsigned i = 0; i != NumParams; ++i) {
220     assert((i >= FTy->getNumParams() || 
221             FTy->getParamType(i) == Params[i]->getType()) &&
222            "Calling a function with a bad signature!");
223     OL[i+1].init(Params[i], this);
224   }
225 }
226
227 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
228   ParamAttrs = 0;
229   NumOperands = 3;
230   Use *OL = OperandList = new Use[3];
231   OL[0].init(Func, this);
232   OL[1].init(Actual1, this);
233   OL[2].init(Actual2, this);
234
235   const FunctionType *FTy =
236     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
237   FTy = FTy;  // silence warning.
238
239   assert((FTy->getNumParams() == 2 ||
240           (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
241          "Calling a function with bad signature");
242   assert((0 >= FTy->getNumParams() || 
243           FTy->getParamType(0) == Actual1->getType()) &&
244          "Calling a function with a bad signature!");
245   assert((1 >= FTy->getNumParams() || 
246           FTy->getParamType(1) == Actual2->getType()) &&
247          "Calling a function with a bad signature!");
248 }
249
250 void CallInst::init(Value *Func, Value *Actual) {
251   ParamAttrs = 0;
252   NumOperands = 2;
253   Use *OL = OperandList = new Use[2];
254   OL[0].init(Func, this);
255   OL[1].init(Actual, this);
256
257   const FunctionType *FTy =
258     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
259   FTy = FTy;  // silence warning.
260
261   assert((FTy->getNumParams() == 1 ||
262           (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
263          "Calling a function with bad signature");
264   assert((0 == FTy->getNumParams() || 
265           FTy->getParamType(0) == Actual->getType()) &&
266          "Calling a function with a bad signature!");
267 }
268
269 void CallInst::init(Value *Func) {
270   ParamAttrs = 0;
271   NumOperands = 1;
272   Use *OL = OperandList = new Use[1];
273   OL[0].init(Func, this);
274
275   const FunctionType *FTy =
276     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
277   FTy = FTy;  // silence warning.
278
279   assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
280 }
281
282 #if 0
283 // Leave for llvm-gcc
284 CallInst::CallInst(Value *Func, Value* const *Args, unsigned NumArgs,
285                    const std::string &Name, BasicBlock *InsertAtEnd)
286   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
287                                      ->getElementType())->getReturnType(),
288                 Instruction::Call, 0, 0, InsertAtEnd) {
289   init(Func, Args, NumArgs);
290   setName(Name);
291 }
292 CallInst::CallInst(Value *Func, Value* const *Args, unsigned NumArgs,
293                    const std::string &Name, Instruction *InsertBefore)
294     : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
295                                      ->getElementType())->getReturnType(),
296                   Instruction::Call, 0, 0, InsertBefore) {
297   init(Func, Args, NumArgs);
298   setName(Name);
299 }
300
301 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
302                    const std::string &Name, Instruction  *InsertBefore)
303   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
304                                    ->getElementType())->getReturnType(),
305                 Instruction::Call, 0, 0, InsertBefore) {
306   init(Func, Actual1, Actual2);
307   setName(Name);
308 }
309
310 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
311                    const std::string &Name, BasicBlock  *InsertAtEnd)
312   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
313                                    ->getElementType())->getReturnType(),
314                 Instruction::Call, 0, 0, InsertAtEnd) {
315   init(Func, Actual1, Actual2);
316   setName(Name);
317 }
318 #endif
319 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
320                    Instruction *InsertBefore)
321   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
322                                    ->getElementType())->getReturnType(),
323                 Instruction::Call, 0, 0, InsertBefore) {
324   init(Func, Actual);
325   setName(Name);
326 }
327
328 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
329                    BasicBlock  *InsertAtEnd)
330   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
331                                    ->getElementType())->getReturnType(),
332                 Instruction::Call, 0, 0, InsertAtEnd) {
333   init(Func, Actual);
334   setName(Name);
335 }
336 CallInst::CallInst(Value *Func, const std::string &Name,
337                    Instruction *InsertBefore)
338   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
339                                    ->getElementType())->getReturnType(),
340                 Instruction::Call, 0, 0, InsertBefore) {
341   init(Func);
342   setName(Name);
343 }
344
345 CallInst::CallInst(Value *Func, const std::string &Name,
346                    BasicBlock *InsertAtEnd)
347   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
348                                    ->getElementType())->getReturnType(),
349                 Instruction::Call, 0, 0, InsertAtEnd) {
350   init(Func);
351   setName(Name);
352 }
353
354 CallInst::CallInst(const CallInst &CI)
355   : Instruction(CI.getType(), Instruction::Call, new Use[CI.getNumOperands()],
356                 CI.getNumOperands()),
357     ParamAttrs(0) {
358   setParamAttrs(CI.getParamAttrs());
359   SubclassData = CI.SubclassData;
360   Use *OL = OperandList;
361   Use *InOL = CI.OperandList;
362   for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
363     OL[i].init(InOL[i], this);
364 }
365
366 void CallInst::setParamAttrs(const ParamAttrsList *newAttrs) {
367   if (ParamAttrs == newAttrs)
368     return;
369
370   if (ParamAttrs)
371     ParamAttrs->dropRef();
372
373   if (newAttrs)
374     newAttrs->addRef();
375
376   ParamAttrs = newAttrs; 
377 }
378
379 bool CallInst::isStructReturn() const {
380   if (ParamAttrs)
381     return ParamAttrs->paramHasAttr(1, ParamAttr::StructRet);
382   return false;
383 }
384
385 //===----------------------------------------------------------------------===//
386 //                        InvokeInst Implementation
387 //===----------------------------------------------------------------------===//
388
389 InvokeInst::~InvokeInst() {
390   delete [] OperandList;
391   if (ParamAttrs)
392     ParamAttrs->dropRef();
393 }
394
395 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
396                       Value* const *Args, unsigned NumArgs) {
397   ParamAttrs = 0;
398   NumOperands = 3+NumArgs;
399   Use *OL = OperandList = new Use[3+NumArgs];
400   OL[0].init(Fn, this);
401   OL[1].init(IfNormal, this);
402   OL[2].init(IfException, this);
403   const FunctionType *FTy =
404     cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
405   FTy = FTy;  // silence warning.
406
407   assert((NumArgs == FTy->getNumParams()) ||
408          (FTy->isVarArg() && NumArgs > FTy->getNumParams()) &&
409          "Calling a function with bad signature");
410
411   for (unsigned i = 0, e = NumArgs; i != e; i++) {
412     assert((i >= FTy->getNumParams() || 
413             FTy->getParamType(i) == Args[i]->getType()) &&
414            "Invoking a function with a bad signature!");
415     
416     OL[i+3].init(Args[i], this);
417   }
418 }
419
420 InvokeInst::InvokeInst(const InvokeInst &II)
421   : TerminatorInst(II.getType(), Instruction::Invoke,
422                    new Use[II.getNumOperands()], II.getNumOperands()),
423     ParamAttrs(0) {
424   setParamAttrs(II.getParamAttrs());
425   SubclassData = II.SubclassData;
426   Use *OL = OperandList, *InOL = II.OperandList;
427   for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
428     OL[i].init(InOL[i], this);
429 }
430
431 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
432   return getSuccessor(idx);
433 }
434 unsigned InvokeInst::getNumSuccessorsV() const {
435   return getNumSuccessors();
436 }
437 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
438   return setSuccessor(idx, B);
439 }
440
441 void InvokeInst::setParamAttrs(const ParamAttrsList *newAttrs) {
442   if (ParamAttrs == newAttrs)
443     return;
444
445   if (ParamAttrs)
446     ParamAttrs->dropRef();
447
448   if (newAttrs)
449     newAttrs->addRef();
450
451   ParamAttrs = newAttrs; 
452 }
453
454 bool InvokeInst::isStructReturn() const {
455   if (ParamAttrs)
456     return ParamAttrs->paramHasAttr(1, ParamAttr::StructRet);
457   return false;
458 }
459
460 //===----------------------------------------------------------------------===//
461 //                        ReturnInst Implementation
462 //===----------------------------------------------------------------------===//
463
464 ReturnInst::ReturnInst(const ReturnInst &RI)
465   : TerminatorInst(Type::VoidTy, Instruction::Ret,
466                    &RetVal, RI.getNumOperands()) {
467   if (RI.getNumOperands())
468     RetVal.init(RI.RetVal, this);
469 }
470
471 ReturnInst::ReturnInst(Value *retVal, Instruction *InsertBefore)
472   : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertBefore) {
473   init(retVal);
474 }
475 ReturnInst::ReturnInst(Value *retVal, BasicBlock *InsertAtEnd)
476   : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertAtEnd) {
477   init(retVal);
478 }
479 ReturnInst::ReturnInst(BasicBlock *InsertAtEnd)
480   : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertAtEnd) {
481 }
482
483
484
485 void ReturnInst::init(Value *retVal) {
486   if (retVal && retVal->getType() != Type::VoidTy) {
487     assert(!isa<BasicBlock>(retVal) &&
488            "Cannot return basic block.  Probably using the incorrect ctor");
489     NumOperands = 1;
490     RetVal.init(retVal, this);
491   }
492 }
493
494 unsigned ReturnInst::getNumSuccessorsV() const {
495   return getNumSuccessors();
496 }
497
498 // Out-of-line ReturnInst method, put here so the C++ compiler can choose to
499 // emit the vtable for the class in this translation unit.
500 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
501   assert(0 && "ReturnInst has no successors!");
502 }
503
504 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
505   assert(0 && "ReturnInst has no successors!");
506   abort();
507   return 0;
508 }
509
510
511 //===----------------------------------------------------------------------===//
512 //                        UnwindInst Implementation
513 //===----------------------------------------------------------------------===//
514
515 UnwindInst::UnwindInst(Instruction *InsertBefore)
516   : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertBefore) {
517 }
518 UnwindInst::UnwindInst(BasicBlock *InsertAtEnd)
519   : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertAtEnd) {
520 }
521
522
523 unsigned UnwindInst::getNumSuccessorsV() const {
524   return getNumSuccessors();
525 }
526
527 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
528   assert(0 && "UnwindInst has no successors!");
529 }
530
531 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
532   assert(0 && "UnwindInst has no successors!");
533   abort();
534   return 0;
535 }
536
537 //===----------------------------------------------------------------------===//
538 //                      UnreachableInst Implementation
539 //===----------------------------------------------------------------------===//
540
541 UnreachableInst::UnreachableInst(Instruction *InsertBefore)
542   : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertBefore) {
543 }
544 UnreachableInst::UnreachableInst(BasicBlock *InsertAtEnd)
545   : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertAtEnd) {
546 }
547
548 unsigned UnreachableInst::getNumSuccessorsV() const {
549   return getNumSuccessors();
550 }
551
552 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
553   assert(0 && "UnwindInst has no successors!");
554 }
555
556 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
557   assert(0 && "UnwindInst has no successors!");
558   abort();
559   return 0;
560 }
561
562 //===----------------------------------------------------------------------===//
563 //                        BranchInst Implementation
564 //===----------------------------------------------------------------------===//
565
566 void BranchInst::AssertOK() {
567   if (isConditional())
568     assert(getCondition()->getType() == Type::Int1Ty &&
569            "May only branch on boolean predicates!");
570 }
571
572 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
573   : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 1, InsertBefore) {
574   assert(IfTrue != 0 && "Branch destination may not be null!");
575   Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
576 }
577 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
578                        Instruction *InsertBefore)
579 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 3, InsertBefore) {
580   Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
581   Ops[1].init(reinterpret_cast<Value*>(IfFalse), this);
582   Ops[2].init(Cond, this);
583 #ifndef NDEBUG
584   AssertOK();
585 #endif
586 }
587
588 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
589   : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 1, InsertAtEnd) {
590   assert(IfTrue != 0 && "Branch destination may not be null!");
591   Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
592 }
593
594 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
595            BasicBlock *InsertAtEnd)
596   : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 3, InsertAtEnd) {
597   Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
598   Ops[1].init(reinterpret_cast<Value*>(IfFalse), this);
599   Ops[2].init(Cond, this);
600 #ifndef NDEBUG
601   AssertOK();
602 #endif
603 }
604
605
606 BranchInst::BranchInst(const BranchInst &BI) :
607   TerminatorInst(Type::VoidTy, Instruction::Br, Ops, BI.getNumOperands()) {
608   OperandList[0].init(BI.getOperand(0), this);
609   if (BI.getNumOperands() != 1) {
610     assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
611     OperandList[1].init(BI.getOperand(1), this);
612     OperandList[2].init(BI.getOperand(2), this);
613   }
614 }
615
616 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
617   return getSuccessor(idx);
618 }
619 unsigned BranchInst::getNumSuccessorsV() const {
620   return getNumSuccessors();
621 }
622 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
623   setSuccessor(idx, B);
624 }
625
626
627 //===----------------------------------------------------------------------===//
628 //                        AllocationInst Implementation
629 //===----------------------------------------------------------------------===//
630
631 static Value *getAISize(Value *Amt) {
632   if (!Amt)
633     Amt = ConstantInt::get(Type::Int32Ty, 1);
634   else {
635     assert(!isa<BasicBlock>(Amt) &&
636            "Passed basic block into allocation size parameter! Use other ctor");
637     assert(Amt->getType() == Type::Int32Ty &&
638            "Malloc/Allocation array size is not a 32-bit integer!");
639   }
640   return Amt;
641 }
642
643 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
644                                unsigned Align, const std::string &Name,
645                                Instruction *InsertBefore)
646   : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
647                      InsertBefore), Alignment(Align) {
648   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
649   assert(Ty != Type::VoidTy && "Cannot allocate void!");
650   setName(Name);
651 }
652
653 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
654                                unsigned Align, const std::string &Name,
655                                BasicBlock *InsertAtEnd)
656   : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
657                      InsertAtEnd), Alignment(Align) {
658   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
659   assert(Ty != Type::VoidTy && "Cannot allocate void!");
660   setName(Name);
661 }
662
663 // Out of line virtual method, so the vtable, etc has a home.
664 AllocationInst::~AllocationInst() {
665 }
666
667 bool AllocationInst::isArrayAllocation() const {
668   if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
669     return CI->getZExtValue() != 1;
670   return true;
671 }
672
673 const Type *AllocationInst::getAllocatedType() const {
674   return getType()->getElementType();
675 }
676
677 AllocaInst::AllocaInst(const AllocaInst &AI)
678   : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
679                    Instruction::Alloca, AI.getAlignment()) {
680 }
681
682 MallocInst::MallocInst(const MallocInst &MI)
683   : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
684                    Instruction::Malloc, MI.getAlignment()) {
685 }
686
687 //===----------------------------------------------------------------------===//
688 //                             FreeInst Implementation
689 //===----------------------------------------------------------------------===//
690
691 void FreeInst::AssertOK() {
692   assert(isa<PointerType>(getOperand(0)->getType()) &&
693          "Can not free something of nonpointer type!");
694 }
695
696 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
697   : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertBefore) {
698   AssertOK();
699 }
700
701 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
702   : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertAtEnd) {
703   AssertOK();
704 }
705
706
707 //===----------------------------------------------------------------------===//
708 //                           LoadInst Implementation
709 //===----------------------------------------------------------------------===//
710
711 void LoadInst::AssertOK() {
712   assert(isa<PointerType>(getOperand(0)->getType()) &&
713          "Ptr must have pointer type.");
714 }
715
716 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
717   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
718                      Load, Ptr, InsertBef) {
719   setVolatile(false);
720   setAlignment(0);
721   AssertOK();
722   setName(Name);
723 }
724
725 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
726   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
727                      Load, Ptr, InsertAE) {
728   setVolatile(false);
729   setAlignment(0);
730   AssertOK();
731   setName(Name);
732 }
733
734 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
735                    Instruction *InsertBef)
736   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
737                      Load, Ptr, InsertBef) {
738   setVolatile(isVolatile);
739   setAlignment(0);
740   AssertOK();
741   setName(Name);
742 }
743
744 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile, 
745                    unsigned Align, Instruction *InsertBef)
746   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
747                      Load, Ptr, InsertBef) {
748   setVolatile(isVolatile);
749   setAlignment(Align);
750   AssertOK();
751   setName(Name);
752 }
753
754 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile, 
755                    unsigned Align, BasicBlock *InsertAE)
756   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
757                      Load, Ptr, InsertAE) {
758   setVolatile(isVolatile);
759   setAlignment(Align);
760   AssertOK();
761   setName(Name);
762 }
763
764 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
765                    BasicBlock *InsertAE)
766   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
767                      Load, Ptr, InsertAE) {
768   setVolatile(isVolatile);
769   setAlignment(0);
770   AssertOK();
771   setName(Name);
772 }
773
774
775
776 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
777   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
778                      Load, Ptr, InsertBef) {
779   setVolatile(false);
780   setAlignment(0);
781   AssertOK();
782   if (Name && Name[0]) setName(Name);
783 }
784
785 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
786   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
787                      Load, Ptr, InsertAE) {
788   setVolatile(false);
789   setAlignment(0);
790   AssertOK();
791   if (Name && Name[0]) setName(Name);
792 }
793
794 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
795                    Instruction *InsertBef)
796 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
797                    Load, Ptr, InsertBef) {
798   setVolatile(isVolatile);
799   setAlignment(0);
800   AssertOK();
801   if (Name && Name[0]) setName(Name);
802 }
803
804 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
805                    BasicBlock *InsertAE)
806   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
807                      Load, Ptr, InsertAE) {
808   setVolatile(isVolatile);
809   setAlignment(0);
810   AssertOK();
811   if (Name && Name[0]) setName(Name);
812 }
813
814 void LoadInst::setAlignment(unsigned Align) {
815   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
816   SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
817 }
818
819 //===----------------------------------------------------------------------===//
820 //                           StoreInst Implementation
821 //===----------------------------------------------------------------------===//
822
823 void StoreInst::AssertOK() {
824   assert(isa<PointerType>(getOperand(1)->getType()) &&
825          "Ptr must have pointer type!");
826   assert(getOperand(0)->getType() ==
827                  cast<PointerType>(getOperand(1)->getType())->getElementType()
828          && "Ptr must be a pointer to Val type!");
829 }
830
831
832 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
833   : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
834   Ops[0].init(val, this);
835   Ops[1].init(addr, this);
836   setVolatile(false);
837   setAlignment(0);
838   AssertOK();
839 }
840
841 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
842   : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
843   Ops[0].init(val, this);
844   Ops[1].init(addr, this);
845   setVolatile(false);
846   setAlignment(0);
847   AssertOK();
848 }
849
850 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
851                      Instruction *InsertBefore)
852   : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
853   Ops[0].init(val, this);
854   Ops[1].init(addr, this);
855   setVolatile(isVolatile);
856   setAlignment(0);
857   AssertOK();
858 }
859
860 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
861                      unsigned Align, Instruction *InsertBefore)
862   : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
863   Ops[0].init(val, this);
864   Ops[1].init(addr, this);
865   setVolatile(isVolatile);
866   setAlignment(Align);
867   AssertOK();
868 }
869
870 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
871                      unsigned Align, BasicBlock *InsertAtEnd)
872   : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
873   Ops[0].init(val, this);
874   Ops[1].init(addr, this);
875   setVolatile(isVolatile);
876   setAlignment(Align);
877   AssertOK();
878 }
879
880 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
881                      BasicBlock *InsertAtEnd)
882   : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
883   Ops[0].init(val, this);
884   Ops[1].init(addr, this);
885   setVolatile(isVolatile);
886   setAlignment(0);
887   AssertOK();
888 }
889
890 void StoreInst::setAlignment(unsigned Align) {
891   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
892   SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
893 }
894
895 //===----------------------------------------------------------------------===//
896 //                       GetElementPtrInst Implementation
897 //===----------------------------------------------------------------------===//
898
899 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx) {
900   NumOperands = 1+NumIdx;
901   Use *OL = OperandList = new Use[NumOperands];
902   OL[0].init(Ptr, this);
903
904   for (unsigned i = 0; i != NumIdx; ++i)
905     OL[i+1].init(Idx[i], this);
906 }
907
908 void GetElementPtrInst::init(Value *Ptr, Value *Idx) {
909   NumOperands = 2;
910   Use *OL = OperandList = new Use[2];
911   OL[0].init(Ptr, this);
912   OL[1].init(Idx, this);
913 }
914
915 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
916                                      const std::string &Name, Instruction *InBe)
917   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx))),
918                 GetElementPtr, 0, 0, InBe) {
919   init(Ptr, Idx);
920   setName(Name);
921 }
922
923 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
924                                      const std::string &Name, BasicBlock *IAE)
925   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx))),
926                 GetElementPtr, 0, 0, IAE) {
927   init(Ptr, Idx);
928   setName(Name);
929 }
930
931 GetElementPtrInst::~GetElementPtrInst() {
932   delete[] OperandList;
933 }
934
935 // getIndexedType - Returns the type of the element that would be loaded with
936 // a load instruction with the specified parameters.
937 //
938 // A null type is returned if the indices are invalid for the specified
939 // pointer type.
940 //
941 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
942                                               Value* const *Idxs,
943                                               unsigned NumIdx,
944                                               bool AllowCompositeLeaf) {
945   if (!isa<PointerType>(Ptr)) return 0;   // Type isn't a pointer type!
946
947   // Handle the special case of the empty set index set...
948   if (NumIdx == 0)
949     if (AllowCompositeLeaf ||
950         cast<PointerType>(Ptr)->getElementType()->isFirstClassType())
951       return cast<PointerType>(Ptr)->getElementType();
952     else
953       return 0;
954
955   unsigned CurIdx = 0;
956   while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
957     if (NumIdx == CurIdx) {
958       if (AllowCompositeLeaf || CT->isFirstClassType()) return Ptr;
959       return 0;   // Can't load a whole structure or array!?!?
960     }
961
962     Value *Index = Idxs[CurIdx++];
963     if (isa<PointerType>(CT) && CurIdx != 1)
964       return 0;  // Can only index into pointer types at the first index!
965     if (!CT->indexValid(Index)) return 0;
966     Ptr = CT->getTypeAtIndex(Index);
967
968     // If the new type forwards to another type, then it is in the middle
969     // of being refined to another type (and hence, may have dropped all
970     // references to what it was using before).  So, use the new forwarded
971     // type.
972     if (const Type * Ty = Ptr->getForwardedType()) {
973       Ptr = Ty;
974     }
975   }
976   return CurIdx == NumIdx ? Ptr : 0;
977 }
978
979 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
980   const PointerType *PTy = dyn_cast<PointerType>(Ptr);
981   if (!PTy) return 0;   // Type isn't a pointer type!
982
983   // Check the pointer index.
984   if (!PTy->indexValid(Idx)) return 0;
985
986   return PTy->getElementType();
987 }
988
989
990 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
991 /// zeros.  If so, the result pointer and the first operand have the same
992 /// value, just potentially different types.
993 bool GetElementPtrInst::hasAllZeroIndices() const {
994   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
995     if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
996       if (!CI->isZero()) return false;
997     } else {
998       return false;
999     }
1000   }
1001   return true;
1002 }
1003
1004 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1005 /// constant integers.  If so, the result pointer and the first operand have
1006 /// a constant offset between them.
1007 bool GetElementPtrInst::hasAllConstantIndices() const {
1008   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1009     if (!isa<ConstantInt>(getOperand(i)))
1010       return false;
1011   }
1012   return true;
1013 }
1014
1015
1016 //===----------------------------------------------------------------------===//
1017 //                           ExtractElementInst Implementation
1018 //===----------------------------------------------------------------------===//
1019
1020 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1021                                        const std::string &Name,
1022                                        Instruction *InsertBef)
1023   : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1024                 ExtractElement, Ops, 2, InsertBef) {
1025   assert(isValidOperands(Val, Index) &&
1026          "Invalid extractelement instruction operands!");
1027   Ops[0].init(Val, this);
1028   Ops[1].init(Index, this);
1029   setName(Name);
1030 }
1031
1032 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1033                                        const std::string &Name,
1034                                        Instruction *InsertBef)
1035   : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1036                 ExtractElement, Ops, 2, InsertBef) {
1037   Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1038   assert(isValidOperands(Val, Index) &&
1039          "Invalid extractelement instruction operands!");
1040   Ops[0].init(Val, this);
1041   Ops[1].init(Index, this);
1042   setName(Name);
1043 }
1044
1045
1046 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1047                                        const std::string &Name,
1048                                        BasicBlock *InsertAE)
1049   : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1050                 ExtractElement, Ops, 2, InsertAE) {
1051   assert(isValidOperands(Val, Index) &&
1052          "Invalid extractelement instruction operands!");
1053
1054   Ops[0].init(Val, this);
1055   Ops[1].init(Index, this);
1056   setName(Name);
1057 }
1058
1059 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1060                                        const std::string &Name,
1061                                        BasicBlock *InsertAE)
1062   : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1063                 ExtractElement, Ops, 2, InsertAE) {
1064   Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1065   assert(isValidOperands(Val, Index) &&
1066          "Invalid extractelement instruction operands!");
1067   
1068   Ops[0].init(Val, this);
1069   Ops[1].init(Index, this);
1070   setName(Name);
1071 }
1072
1073
1074 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1075   if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty)
1076     return false;
1077   return true;
1078 }
1079
1080
1081 //===----------------------------------------------------------------------===//
1082 //                           InsertElementInst Implementation
1083 //===----------------------------------------------------------------------===//
1084
1085 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
1086     : Instruction(IE.getType(), InsertElement, Ops, 3) {
1087   Ops[0].init(IE.Ops[0], this);
1088   Ops[1].init(IE.Ops[1], this);
1089   Ops[2].init(IE.Ops[2], this);
1090 }
1091 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1092                                      const std::string &Name,
1093                                      Instruction *InsertBef)
1094   : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertBef) {
1095   assert(isValidOperands(Vec, Elt, Index) &&
1096          "Invalid insertelement instruction operands!");
1097   Ops[0].init(Vec, this);
1098   Ops[1].init(Elt, this);
1099   Ops[2].init(Index, this);
1100   setName(Name);
1101 }
1102
1103 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1104                                      const std::string &Name,
1105                                      Instruction *InsertBef)
1106   : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertBef) {
1107   Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1108   assert(isValidOperands(Vec, Elt, Index) &&
1109          "Invalid insertelement instruction operands!");
1110   Ops[0].init(Vec, this);
1111   Ops[1].init(Elt, this);
1112   Ops[2].init(Index, this);
1113   setName(Name);
1114 }
1115
1116
1117 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1118                                      const std::string &Name,
1119                                      BasicBlock *InsertAE)
1120   : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertAE) {
1121   assert(isValidOperands(Vec, Elt, Index) &&
1122          "Invalid insertelement instruction operands!");
1123
1124   Ops[0].init(Vec, this);
1125   Ops[1].init(Elt, this);
1126   Ops[2].init(Index, this);
1127   setName(Name);
1128 }
1129
1130 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1131                                      const std::string &Name,
1132                                      BasicBlock *InsertAE)
1133 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertAE) {
1134   Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1135   assert(isValidOperands(Vec, Elt, Index) &&
1136          "Invalid insertelement instruction operands!");
1137   
1138   Ops[0].init(Vec, this);
1139   Ops[1].init(Elt, this);
1140   Ops[2].init(Index, this);
1141   setName(Name);
1142 }
1143
1144 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt, 
1145                                         const Value *Index) {
1146   if (!isa<VectorType>(Vec->getType()))
1147     return false;   // First operand of insertelement must be vector type.
1148   
1149   if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1150     return false;// Second operand of insertelement must be vector element type.
1151     
1152   if (Index->getType() != Type::Int32Ty)
1153     return false;  // Third operand of insertelement must be uint.
1154   return true;
1155 }
1156
1157
1158 //===----------------------------------------------------------------------===//
1159 //                      ShuffleVectorInst Implementation
1160 //===----------------------------------------------------------------------===//
1161
1162 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV) 
1163     : Instruction(SV.getType(), ShuffleVector, Ops, 3) {
1164   Ops[0].init(SV.Ops[0], this);
1165   Ops[1].init(SV.Ops[1], this);
1166   Ops[2].init(SV.Ops[2], this);
1167 }
1168
1169 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1170                                      const std::string &Name,
1171                                      Instruction *InsertBefore)
1172   : Instruction(V1->getType(), ShuffleVector, Ops, 3, InsertBefore) {
1173   assert(isValidOperands(V1, V2, Mask) &&
1174          "Invalid shuffle vector instruction operands!");
1175   Ops[0].init(V1, this);
1176   Ops[1].init(V2, this);
1177   Ops[2].init(Mask, this);
1178   setName(Name);
1179 }
1180
1181 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1182                                      const std::string &Name, 
1183                                      BasicBlock *InsertAtEnd)
1184   : Instruction(V1->getType(), ShuffleVector, Ops, 3, InsertAtEnd) {
1185   assert(isValidOperands(V1, V2, Mask) &&
1186          "Invalid shuffle vector instruction operands!");
1187
1188   Ops[0].init(V1, this);
1189   Ops[1].init(V2, this);
1190   Ops[2].init(Mask, this);
1191   setName(Name);
1192 }
1193
1194 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2, 
1195                                         const Value *Mask) {
1196   if (!isa<VectorType>(V1->getType())) return false;
1197   if (V1->getType() != V2->getType()) return false;
1198   if (!isa<VectorType>(Mask->getType()) ||
1199          cast<VectorType>(Mask->getType())->getElementType() != Type::Int32Ty ||
1200          cast<VectorType>(Mask->getType())->getNumElements() !=
1201          cast<VectorType>(V1->getType())->getNumElements())
1202     return false;
1203   return true;
1204 }
1205
1206
1207 //===----------------------------------------------------------------------===//
1208 //                             BinaryOperator Class
1209 //===----------------------------------------------------------------------===//
1210
1211 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1212                                const Type *Ty, const std::string &Name,
1213                                Instruction *InsertBefore)
1214   : Instruction(Ty, iType, Ops, 2, InsertBefore) {
1215   Ops[0].init(S1, this);
1216   Ops[1].init(S2, this);
1217   init(iType);
1218   setName(Name);
1219 }
1220
1221 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2, 
1222                                const Type *Ty, const std::string &Name,
1223                                BasicBlock *InsertAtEnd)
1224   : Instruction(Ty, iType, Ops, 2, InsertAtEnd) {
1225   Ops[0].init(S1, this);
1226   Ops[1].init(S2, this);
1227   init(iType);
1228   setName(Name);
1229 }
1230
1231
1232 void BinaryOperator::init(BinaryOps iType) {
1233   Value *LHS = getOperand(0), *RHS = getOperand(1);
1234   LHS = LHS; RHS = RHS; // Silence warnings.
1235   assert(LHS->getType() == RHS->getType() &&
1236          "Binary operator operand types must match!");
1237 #ifndef NDEBUG
1238   switch (iType) {
1239   case Add: case Sub:
1240   case Mul: 
1241     assert(getType() == LHS->getType() &&
1242            "Arithmetic operation should return same type as operands!");
1243     assert((getType()->isInteger() || getType()->isFloatingPoint() ||
1244             isa<VectorType>(getType())) &&
1245           "Tried to create an arithmetic operation on a non-arithmetic type!");
1246     break;
1247   case UDiv: 
1248   case SDiv: 
1249     assert(getType() == LHS->getType() &&
1250            "Arithmetic operation should return same type as operands!");
1251     assert((getType()->isInteger() || (isa<VectorType>(getType()) && 
1252             cast<VectorType>(getType())->getElementType()->isInteger())) &&
1253            "Incorrect operand type (not integer) for S/UDIV");
1254     break;
1255   case FDiv:
1256     assert(getType() == LHS->getType() &&
1257            "Arithmetic operation should return same type as operands!");
1258     assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1259             cast<VectorType>(getType())->getElementType()->isFloatingPoint())) 
1260             && "Incorrect operand type (not floating point) for FDIV");
1261     break;
1262   case URem: 
1263   case SRem: 
1264     assert(getType() == LHS->getType() &&
1265            "Arithmetic operation should return same type as operands!");
1266     assert((getType()->isInteger() || (isa<VectorType>(getType()) && 
1267             cast<VectorType>(getType())->getElementType()->isInteger())) &&
1268            "Incorrect operand type (not integer) for S/UREM");
1269     break;
1270   case FRem:
1271     assert(getType() == LHS->getType() &&
1272            "Arithmetic operation should return same type as operands!");
1273     assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1274             cast<VectorType>(getType())->getElementType()->isFloatingPoint())) 
1275             && "Incorrect operand type (not floating point) for FREM");
1276     break;
1277   case Shl:
1278   case LShr:
1279   case AShr:
1280     assert(getType() == LHS->getType() &&
1281            "Shift operation should return same type as operands!");
1282     assert(getType()->isInteger() && 
1283            "Shift operation requires integer operands");
1284     break;
1285   case And: case Or:
1286   case Xor:
1287     assert(getType() == LHS->getType() &&
1288            "Logical operation should return same type as operands!");
1289     assert((getType()->isInteger() ||
1290             (isa<VectorType>(getType()) && 
1291              cast<VectorType>(getType())->getElementType()->isInteger())) &&
1292            "Tried to create a logical operation on a non-integral type!");
1293     break;
1294   default:
1295     break;
1296   }
1297 #endif
1298 }
1299
1300 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1301                                        const std::string &Name,
1302                                        Instruction *InsertBefore) {
1303   assert(S1->getType() == S2->getType() &&
1304          "Cannot create binary operator with two operands of differing type!");
1305   return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1306 }
1307
1308 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1309                                        const std::string &Name,
1310                                        BasicBlock *InsertAtEnd) {
1311   BinaryOperator *Res = create(Op, S1, S2, Name);
1312   InsertAtEnd->getInstList().push_back(Res);
1313   return Res;
1314 }
1315
1316 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1317                                           Instruction *InsertBefore) {
1318   Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1319   return new BinaryOperator(Instruction::Sub,
1320                             zero, Op,
1321                             Op->getType(), Name, InsertBefore);
1322 }
1323
1324 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1325                                           BasicBlock *InsertAtEnd) {
1326   Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1327   return new BinaryOperator(Instruction::Sub,
1328                             zero, Op,
1329                             Op->getType(), Name, InsertAtEnd);
1330 }
1331
1332 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1333                                           Instruction *InsertBefore) {
1334   Constant *C;
1335   if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1336     C = ConstantInt::getAllOnesValue(PTy->getElementType());
1337     C = ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), C));
1338   } else {
1339     C = ConstantInt::getAllOnesValue(Op->getType());
1340   }
1341   
1342   return new BinaryOperator(Instruction::Xor, Op, C,
1343                             Op->getType(), Name, InsertBefore);
1344 }
1345
1346 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1347                                           BasicBlock *InsertAtEnd) {
1348   Constant *AllOnes;
1349   if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1350     // Create a vector of all ones values.
1351     Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType());
1352     AllOnes = 
1353       ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1354   } else {
1355     AllOnes = ConstantInt::getAllOnesValue(Op->getType());
1356   }
1357   
1358   return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1359                             Op->getType(), Name, InsertAtEnd);
1360 }
1361
1362
1363 // isConstantAllOnes - Helper function for several functions below
1364 static inline bool isConstantAllOnes(const Value *V) {
1365   if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1366     return CI->isAllOnesValue();
1367   if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1368     return CV->isAllOnesValue();
1369   return false;
1370 }
1371
1372 bool BinaryOperator::isNeg(const Value *V) {
1373   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1374     if (Bop->getOpcode() == Instruction::Sub)
1375       return Bop->getOperand(0) ==
1376              ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1377   return false;
1378 }
1379
1380 bool BinaryOperator::isNot(const Value *V) {
1381   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1382     return (Bop->getOpcode() == Instruction::Xor &&
1383             (isConstantAllOnes(Bop->getOperand(1)) ||
1384              isConstantAllOnes(Bop->getOperand(0))));
1385   return false;
1386 }
1387
1388 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1389   assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1390   return cast<BinaryOperator>(BinOp)->getOperand(1);
1391 }
1392
1393 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1394   return getNegArgument(const_cast<Value*>(BinOp));
1395 }
1396
1397 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1398   assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1399   BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1400   Value *Op0 = BO->getOperand(0);
1401   Value *Op1 = BO->getOperand(1);
1402   if (isConstantAllOnes(Op0)) return Op1;
1403
1404   assert(isConstantAllOnes(Op1));
1405   return Op0;
1406 }
1407
1408 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1409   return getNotArgument(const_cast<Value*>(BinOp));
1410 }
1411
1412
1413 // swapOperands - Exchange the two operands to this instruction.  This
1414 // instruction is safe to use on any binary instruction and does not
1415 // modify the semantics of the instruction.  If the instruction is
1416 // order dependent (SetLT f.e.) the opcode is changed.
1417 //
1418 bool BinaryOperator::swapOperands() {
1419   if (!isCommutative())
1420     return true; // Can't commute operands
1421   std::swap(Ops[0], Ops[1]);
1422   return false;
1423 }
1424
1425 //===----------------------------------------------------------------------===//
1426 //                                CastInst Class
1427 //===----------------------------------------------------------------------===//
1428
1429 // Just determine if this cast only deals with integral->integral conversion.
1430 bool CastInst::isIntegerCast() const {
1431   switch (getOpcode()) {
1432     default: return false;
1433     case Instruction::ZExt:
1434     case Instruction::SExt:
1435     case Instruction::Trunc:
1436       return true;
1437     case Instruction::BitCast:
1438       return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1439   }
1440 }
1441
1442 bool CastInst::isLosslessCast() const {
1443   // Only BitCast can be lossless, exit fast if we're not BitCast
1444   if (getOpcode() != Instruction::BitCast)
1445     return false;
1446
1447   // Identity cast is always lossless
1448   const Type* SrcTy = getOperand(0)->getType();
1449   const Type* DstTy = getType();
1450   if (SrcTy == DstTy)
1451     return true;
1452   
1453   // Pointer to pointer is always lossless.
1454   if (isa<PointerType>(SrcTy))
1455     return isa<PointerType>(DstTy);
1456   return false;  // Other types have no identity values
1457 }
1458
1459 /// This function determines if the CastInst does not require any bits to be
1460 /// changed in order to effect the cast. Essentially, it identifies cases where
1461 /// no code gen is necessary for the cast, hence the name no-op cast.  For 
1462 /// example, the following are all no-op casts:
1463 /// # bitcast uint %X, int
1464 /// # bitcast uint* %x, sbyte*
1465 /// # bitcast vector< 2 x int > %x, vector< 4 x short> 
1466 /// # ptrtoint uint* %x, uint     ; on 32-bit plaforms only
1467 /// @brief Determine if a cast is a no-op.
1468 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1469   switch (getOpcode()) {
1470     default:
1471       assert(!"Invalid CastOp");
1472     case Instruction::Trunc:
1473     case Instruction::ZExt:
1474     case Instruction::SExt: 
1475     case Instruction::FPTrunc:
1476     case Instruction::FPExt:
1477     case Instruction::UIToFP:
1478     case Instruction::SIToFP:
1479     case Instruction::FPToUI:
1480     case Instruction::FPToSI:
1481       return false; // These always modify bits
1482     case Instruction::BitCast:
1483       return true;  // BitCast never modifies bits.
1484     case Instruction::PtrToInt:
1485       return IntPtrTy->getPrimitiveSizeInBits() ==
1486             getType()->getPrimitiveSizeInBits();
1487     case Instruction::IntToPtr:
1488       return IntPtrTy->getPrimitiveSizeInBits() ==
1489              getOperand(0)->getType()->getPrimitiveSizeInBits();
1490   }
1491 }
1492
1493 /// This function determines if a pair of casts can be eliminated and what 
1494 /// opcode should be used in the elimination. This assumes that there are two 
1495 /// instructions like this:
1496 /// *  %F = firstOpcode SrcTy %x to MidTy
1497 /// *  %S = secondOpcode MidTy %F to DstTy
1498 /// The function returns a resultOpcode so these two casts can be replaced with:
1499 /// *  %Replacement = resultOpcode %SrcTy %x to DstTy
1500 /// If no such cast is permited, the function returns 0.
1501 unsigned CastInst::isEliminableCastPair(
1502   Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1503   const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1504 {
1505   // Define the 144 possibilities for these two cast instructions. The values
1506   // in this matrix determine what to do in a given situation and select the
1507   // case in the switch below.  The rows correspond to firstOp, the columns 
1508   // correspond to secondOp.  In looking at the table below, keep in  mind
1509   // the following cast properties:
1510   //
1511   //          Size Compare       Source               Destination
1512   // Operator  Src ? Size   Type       Sign         Type       Sign
1513   // -------- ------------ -------------------   ---------------------
1514   // TRUNC         >       Integer      Any        Integral     Any
1515   // ZEXT          <       Integral   Unsigned     Integer      Any
1516   // SEXT          <       Integral    Signed      Integer      Any
1517   // FPTOUI       n/a      FloatPt      n/a        Integral   Unsigned
1518   // FPTOSI       n/a      FloatPt      n/a        Integral    Signed 
1519   // UITOFP       n/a      Integral   Unsigned     FloatPt      n/a   
1520   // SITOFP       n/a      Integral    Signed      FloatPt      n/a   
1521   // FPTRUNC       >       FloatPt      n/a        FloatPt      n/a   
1522   // FPEXT         <       FloatPt      n/a        FloatPt      n/a   
1523   // PTRTOINT     n/a      Pointer      n/a        Integral   Unsigned
1524   // INTTOPTR     n/a      Integral   Unsigned     Pointer      n/a
1525   // BITCONVERT    =       FirstClass   n/a       FirstClass    n/a   
1526   //
1527   // NOTE: some transforms are safe, but we consider them to be non-profitable.
1528   // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
1529   // into "fptoui double to ulong", but this loses information about the range
1530   // of the produced value (we no longer know the top-part is all zeros). 
1531   // Further this conversion is often much more expensive for typical hardware,
1532   // and causes issues when building libgcc.  We disallow fptosi+sext for the 
1533   // same reason.
1534   const unsigned numCastOps = 
1535     Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1536   static const uint8_t CastResults[numCastOps][numCastOps] = {
1537     // T        F  F  U  S  F  F  P  I  B   -+
1538     // R  Z  S  P  P  I  I  T  P  2  N  T    |
1539     // U  E  E  2  2  2  2  R  E  I  T  C    +- secondOp
1540     // N  X  X  U  S  F  F  N  X  N  2  V    |
1541     // C  T  T  I  I  P  P  C  T  T  P  T   -+
1542     {  1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc      -+
1543     {  8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt        |
1544     {  8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt        |
1545     {  0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI      |
1546     {  0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI      |
1547     { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP      +- firstOp
1548     { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP      |
1549     { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc     |
1550     { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt       |
1551     {  1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt    |
1552     { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr    |
1553     {  5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast    -+
1554   };
1555
1556   int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1557                             [secondOp-Instruction::CastOpsBegin];
1558   switch (ElimCase) {
1559     case 0: 
1560       // categorically disallowed
1561       return 0;
1562     case 1: 
1563       // allowed, use first cast's opcode
1564       return firstOp;
1565     case 2: 
1566       // allowed, use second cast's opcode
1567       return secondOp;
1568     case 3: 
1569       // no-op cast in second op implies firstOp as long as the DestTy 
1570       // is integer
1571       if (DstTy->isInteger())
1572         return firstOp;
1573       return 0;
1574     case 4:
1575       // no-op cast in second op implies firstOp as long as the DestTy
1576       // is floating point
1577       if (DstTy->isFloatingPoint())
1578         return firstOp;
1579       return 0;
1580     case 5: 
1581       // no-op cast in first op implies secondOp as long as the SrcTy
1582       // is an integer
1583       if (SrcTy->isInteger())
1584         return secondOp;
1585       return 0;
1586     case 6:
1587       // no-op cast in first op implies secondOp as long as the SrcTy
1588       // is a floating point
1589       if (SrcTy->isFloatingPoint())
1590         return secondOp;
1591       return 0;
1592     case 7: { 
1593       // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1594       unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1595       unsigned MidSize = MidTy->getPrimitiveSizeInBits();
1596       if (MidSize >= PtrSize)
1597         return Instruction::BitCast;
1598       return 0;
1599     }
1600     case 8: {
1601       // ext, trunc -> bitcast,    if the SrcTy and DstTy are same size
1602       // ext, trunc -> ext,        if sizeof(SrcTy) < sizeof(DstTy)
1603       // ext, trunc -> trunc,      if sizeof(SrcTy) > sizeof(DstTy)
1604       unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1605       unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1606       if (SrcSize == DstSize)
1607         return Instruction::BitCast;
1608       else if (SrcSize < DstSize)
1609         return firstOp;
1610       return secondOp;
1611     }
1612     case 9: // zext, sext -> zext, because sext can't sign extend after zext
1613       return Instruction::ZExt;
1614     case 10:
1615       // fpext followed by ftrunc is allowed if the bit size returned to is
1616       // the same as the original, in which case its just a bitcast
1617       if (SrcTy == DstTy)
1618         return Instruction::BitCast;
1619       return 0; // If the types are not the same we can't eliminate it.
1620     case 11:
1621       // bitcast followed by ptrtoint is allowed as long as the bitcast
1622       // is a pointer to pointer cast.
1623       if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1624         return secondOp;
1625       return 0;
1626     case 12:
1627       // inttoptr, bitcast -> intptr  if bitcast is a ptr to ptr cast
1628       if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1629         return firstOp;
1630       return 0;
1631     case 13: {
1632       // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1633       unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1634       unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1635       unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1636       if (SrcSize <= PtrSize && SrcSize == DstSize)
1637         return Instruction::BitCast;
1638       return 0;
1639     }
1640     case 99: 
1641       // cast combination can't happen (error in input). This is for all cases
1642       // where the MidTy is not the same for the two cast instructions.
1643       assert(!"Invalid Cast Combination");
1644       return 0;
1645     default:
1646       assert(!"Error in CastResults table!!!");
1647       return 0;
1648   }
1649   return 0;
1650 }
1651
1652 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty, 
1653   const std::string &Name, Instruction *InsertBefore) {
1654   // Construct and return the appropriate CastInst subclass
1655   switch (op) {
1656     case Trunc:    return new TruncInst    (S, Ty, Name, InsertBefore);
1657     case ZExt:     return new ZExtInst     (S, Ty, Name, InsertBefore);
1658     case SExt:     return new SExtInst     (S, Ty, Name, InsertBefore);
1659     case FPTrunc:  return new FPTruncInst  (S, Ty, Name, InsertBefore);
1660     case FPExt:    return new FPExtInst    (S, Ty, Name, InsertBefore);
1661     case UIToFP:   return new UIToFPInst   (S, Ty, Name, InsertBefore);
1662     case SIToFP:   return new SIToFPInst   (S, Ty, Name, InsertBefore);
1663     case FPToUI:   return new FPToUIInst   (S, Ty, Name, InsertBefore);
1664     case FPToSI:   return new FPToSIInst   (S, Ty, Name, InsertBefore);
1665     case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1666     case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1667     case BitCast:  return new BitCastInst  (S, Ty, Name, InsertBefore);
1668     default:
1669       assert(!"Invalid opcode provided");
1670   }
1671   return 0;
1672 }
1673
1674 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1675   const std::string &Name, BasicBlock *InsertAtEnd) {
1676   // Construct and return the appropriate CastInst subclass
1677   switch (op) {
1678     case Trunc:    return new TruncInst    (S, Ty, Name, InsertAtEnd);
1679     case ZExt:     return new ZExtInst     (S, Ty, Name, InsertAtEnd);
1680     case SExt:     return new SExtInst     (S, Ty, Name, InsertAtEnd);
1681     case FPTrunc:  return new FPTruncInst  (S, Ty, Name, InsertAtEnd);
1682     case FPExt:    return new FPExtInst    (S, Ty, Name, InsertAtEnd);
1683     case UIToFP:   return new UIToFPInst   (S, Ty, Name, InsertAtEnd);
1684     case SIToFP:   return new SIToFPInst   (S, Ty, Name, InsertAtEnd);
1685     case FPToUI:   return new FPToUIInst   (S, Ty, Name, InsertAtEnd);
1686     case FPToSI:   return new FPToSIInst   (S, Ty, Name, InsertAtEnd);
1687     case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1688     case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1689     case BitCast:  return new BitCastInst  (S, Ty, Name, InsertAtEnd);
1690     default:
1691       assert(!"Invalid opcode provided");
1692   }
1693   return 0;
1694 }
1695
1696 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty, 
1697                                         const std::string &Name,
1698                                         Instruction *InsertBefore) {
1699   if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1700     return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1701   return create(Instruction::ZExt, S, Ty, Name, InsertBefore);
1702 }
1703
1704 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty, 
1705                                         const std::string &Name,
1706                                         BasicBlock *InsertAtEnd) {
1707   if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1708     return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1709   return create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
1710 }
1711
1712 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty, 
1713                                         const std::string &Name,
1714                                         Instruction *InsertBefore) {
1715   if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1716     return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1717   return create(Instruction::SExt, S, Ty, Name, InsertBefore);
1718 }
1719
1720 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty, 
1721                                         const std::string &Name,
1722                                         BasicBlock *InsertAtEnd) {
1723   if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1724     return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1725   return create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
1726 }
1727
1728 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1729                                          const std::string &Name,
1730                                          Instruction *InsertBefore) {
1731   if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1732     return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1733   return create(Instruction::Trunc, S, Ty, Name, InsertBefore);
1734 }
1735
1736 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1737                                          const std::string &Name, 
1738                                          BasicBlock *InsertAtEnd) {
1739   if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1740     return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1741   return create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
1742 }
1743
1744 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1745                                       const std::string &Name,
1746                                       BasicBlock *InsertAtEnd) {
1747   assert(isa<PointerType>(S->getType()) && "Invalid cast");
1748   assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1749          "Invalid cast");
1750
1751   if (Ty->isInteger())
1752     return create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
1753   return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1754 }
1755
1756 /// @brief Create a BitCast or a PtrToInt cast instruction
1757 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty, 
1758                                       const std::string &Name, 
1759                                       Instruction *InsertBefore) {
1760   assert(isa<PointerType>(S->getType()) && "Invalid cast");
1761   assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1762          "Invalid cast");
1763
1764   if (Ty->isInteger())
1765     return create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
1766   return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1767 }
1768
1769 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty, 
1770                                       bool isSigned, const std::string &Name,
1771                                       Instruction *InsertBefore) {
1772   assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1773   unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1774   unsigned DstBits = Ty->getPrimitiveSizeInBits();
1775   Instruction::CastOps opcode =
1776     (SrcBits == DstBits ? Instruction::BitCast :
1777      (SrcBits > DstBits ? Instruction::Trunc :
1778       (isSigned ? Instruction::SExt : Instruction::ZExt)));
1779   return create(opcode, C, Ty, Name, InsertBefore);
1780 }
1781
1782 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty, 
1783                                       bool isSigned, const std::string &Name,
1784                                       BasicBlock *InsertAtEnd) {
1785   assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1786   unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1787   unsigned DstBits = Ty->getPrimitiveSizeInBits();
1788   Instruction::CastOps opcode =
1789     (SrcBits == DstBits ? Instruction::BitCast :
1790      (SrcBits > DstBits ? Instruction::Trunc :
1791       (isSigned ? Instruction::SExt : Instruction::ZExt)));
1792   return create(opcode, C, Ty, Name, InsertAtEnd);
1793 }
1794
1795 CastInst *CastInst::createFPCast(Value *C, const Type *Ty, 
1796                                  const std::string &Name, 
1797                                  Instruction *InsertBefore) {
1798   assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() && 
1799          "Invalid cast");
1800   unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1801   unsigned DstBits = Ty->getPrimitiveSizeInBits();
1802   Instruction::CastOps opcode =
1803     (SrcBits == DstBits ? Instruction::BitCast :
1804      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1805   return create(opcode, C, Ty, Name, InsertBefore);
1806 }
1807
1808 CastInst *CastInst::createFPCast(Value *C, const Type *Ty, 
1809                                  const std::string &Name, 
1810                                  BasicBlock *InsertAtEnd) {
1811   assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() && 
1812          "Invalid cast");
1813   unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1814   unsigned DstBits = Ty->getPrimitiveSizeInBits();
1815   Instruction::CastOps opcode =
1816     (SrcBits == DstBits ? Instruction::BitCast :
1817      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1818   return create(opcode, C, Ty, Name, InsertAtEnd);
1819 }
1820
1821 // Provide a way to get a "cast" where the cast opcode is inferred from the 
1822 // types and size of the operand. This, basically, is a parallel of the 
1823 // logic in the castIsValid function below.  This axiom should hold:
1824 //   castIsValid( getCastOpcode(Val, Ty), Val, Ty)
1825 // should not assert in castIsValid. In other words, this produces a "correct"
1826 // casting opcode for the arguments passed to it.
1827 Instruction::CastOps
1828 CastInst::getCastOpcode(
1829   const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
1830   // Get the bit sizes, we'll need these
1831   const Type *SrcTy = Src->getType();
1832   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();   // 0 for ptr/vector
1833   unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1834
1835   // Run through the possibilities ...
1836   if (DestTy->isInteger()) {                       // Casting to integral
1837     if (SrcTy->isInteger()) {                      // Casting from integral
1838       if (DestBits < SrcBits)
1839         return Trunc;                               // int -> smaller int
1840       else if (DestBits > SrcBits) {                // its an extension
1841         if (SrcIsSigned)
1842           return SExt;                              // signed -> SEXT
1843         else
1844           return ZExt;                              // unsigned -> ZEXT
1845       } else {
1846         return BitCast;                             // Same size, No-op cast
1847       }
1848     } else if (SrcTy->isFloatingPoint()) {          // Casting from floating pt
1849       if (DestIsSigned) 
1850         return FPToSI;                              // FP -> sint
1851       else
1852         return FPToUI;                              // FP -> uint 
1853     } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1854       assert(DestBits == PTy->getBitWidth() &&
1855                "Casting vector to integer of different width");
1856       return BitCast;                             // Same size, no-op cast
1857     } else {
1858       assert(isa<PointerType>(SrcTy) &&
1859              "Casting from a value that is not first-class type");
1860       return PtrToInt;                              // ptr -> int
1861     }
1862   } else if (DestTy->isFloatingPoint()) {           // Casting to floating pt
1863     if (SrcTy->isInteger()) {                      // Casting from integral
1864       if (SrcIsSigned)
1865         return SIToFP;                              // sint -> FP
1866       else
1867         return UIToFP;                              // uint -> FP
1868     } else if (SrcTy->isFloatingPoint()) {          // Casting from floating pt
1869       if (DestBits < SrcBits) {
1870         return FPTrunc;                             // FP -> smaller FP
1871       } else if (DestBits > SrcBits) {
1872         return FPExt;                               // FP -> larger FP
1873       } else  {
1874         return BitCast;                             // same size, no-op cast
1875       }
1876     } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1877       assert(DestBits == PTy->getBitWidth() &&
1878              "Casting vector to floating point of different width");
1879         return BitCast;                             // same size, no-op cast
1880     } else {
1881       assert(0 && "Casting pointer or non-first class to float");
1882     }
1883   } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
1884     if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
1885       assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
1886              "Casting vector to vector of different widths");
1887       return BitCast;                             // vector -> vector
1888     } else if (DestPTy->getBitWidth() == SrcBits) {
1889       return BitCast;                               // float/int -> vector
1890     } else {
1891       assert(!"Illegal cast to vector (wrong type or size)");
1892     }
1893   } else if (isa<PointerType>(DestTy)) {
1894     if (isa<PointerType>(SrcTy)) {
1895       return BitCast;                               // ptr -> ptr
1896     } else if (SrcTy->isInteger()) {
1897       return IntToPtr;                              // int -> ptr
1898     } else {
1899       assert(!"Casting pointer to other than pointer or int");
1900     }
1901   } else {
1902     assert(!"Casting to type that is not first-class");
1903   }
1904
1905   // If we fall through to here we probably hit an assertion cast above
1906   // and assertions are not turned on. Anything we return is an error, so
1907   // BitCast is as good a choice as any.
1908   return BitCast;
1909 }
1910
1911 //===----------------------------------------------------------------------===//
1912 //                    CastInst SubClass Constructors
1913 //===----------------------------------------------------------------------===//
1914
1915 /// Check that the construction parameters for a CastInst are correct. This
1916 /// could be broken out into the separate constructors but it is useful to have
1917 /// it in one place and to eliminate the redundant code for getting the sizes
1918 /// of the types involved.
1919 bool 
1920 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
1921
1922   // Check for type sanity on the arguments
1923   const Type *SrcTy = S->getType();
1924   if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
1925     return false;
1926
1927   // Get the size of the types in bits, we'll need this later
1928   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1929   unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1930
1931   // Switch on the opcode provided
1932   switch (op) {
1933   default: return false; // This is an input error
1934   case Instruction::Trunc:
1935     return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize > DstBitSize;
1936   case Instruction::ZExt:
1937     return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
1938   case Instruction::SExt: 
1939     return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
1940   case Instruction::FPTrunc:
1941     return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() && 
1942       SrcBitSize > DstBitSize;
1943   case Instruction::FPExt:
1944     return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() && 
1945       SrcBitSize < DstBitSize;
1946   case Instruction::UIToFP:
1947   case Instruction::SIToFP:
1948     if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
1949       if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
1950         return SVTy->getElementType()->isInteger() &&
1951                DVTy->getElementType()->isFloatingPoint() &&
1952                SVTy->getNumElements() == DVTy->getNumElements();
1953       }
1954     }
1955     return SrcTy->isInteger() && DstTy->isFloatingPoint();
1956   case Instruction::FPToUI:
1957   case Instruction::FPToSI:
1958     if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
1959       if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
1960         return SVTy->getElementType()->isFloatingPoint() &&
1961                DVTy->getElementType()->isInteger() &&
1962                SVTy->getNumElements() == DVTy->getNumElements();
1963       }
1964     }
1965     return SrcTy->isFloatingPoint() && DstTy->isInteger();
1966   case Instruction::PtrToInt:
1967     return isa<PointerType>(SrcTy) && DstTy->isInteger();
1968   case Instruction::IntToPtr:
1969     return SrcTy->isInteger() && isa<PointerType>(DstTy);
1970   case Instruction::BitCast:
1971     // BitCast implies a no-op cast of type only. No bits change.
1972     // However, you can't cast pointers to anything but pointers.
1973     if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
1974       return false;
1975
1976     // Now we know we're not dealing with a pointer/non-poiner mismatch. In all
1977     // these cases, the cast is okay if the source and destination bit widths
1978     // are identical.
1979     return SrcBitSize == DstBitSize;
1980   }
1981 }
1982
1983 TruncInst::TruncInst(
1984   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1985 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
1986   assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
1987 }
1988
1989 TruncInst::TruncInst(
1990   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1991 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) { 
1992   assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
1993 }
1994
1995 ZExtInst::ZExtInst(
1996   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1997 )  : CastInst(Ty, ZExt, S, Name, InsertBefore) { 
1998   assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
1999 }
2000
2001 ZExtInst::ZExtInst(
2002   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2003 )  : CastInst(Ty, ZExt, S, Name, InsertAtEnd) { 
2004   assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2005 }
2006 SExtInst::SExtInst(
2007   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2008 ) : CastInst(Ty, SExt, S, Name, InsertBefore) { 
2009   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2010 }
2011
2012 SExtInst::SExtInst(
2013   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2014 )  : CastInst(Ty, SExt, S, Name, InsertAtEnd) { 
2015   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2016 }
2017
2018 FPTruncInst::FPTruncInst(
2019   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2020 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) { 
2021   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2022 }
2023
2024 FPTruncInst::FPTruncInst(
2025   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2026 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) { 
2027   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2028 }
2029
2030 FPExtInst::FPExtInst(
2031   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2032 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) { 
2033   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2034 }
2035
2036 FPExtInst::FPExtInst(
2037   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2038 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) { 
2039   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2040 }
2041
2042 UIToFPInst::UIToFPInst(
2043   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2044 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) { 
2045   assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2046 }
2047
2048 UIToFPInst::UIToFPInst(
2049   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2050 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) { 
2051   assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2052 }
2053
2054 SIToFPInst::SIToFPInst(
2055   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2056 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) { 
2057   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2058 }
2059
2060 SIToFPInst::SIToFPInst(
2061   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2062 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) { 
2063   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2064 }
2065
2066 FPToUIInst::FPToUIInst(
2067   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2068 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) { 
2069   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2070 }
2071
2072 FPToUIInst::FPToUIInst(
2073   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2074 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) { 
2075   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2076 }
2077
2078 FPToSIInst::FPToSIInst(
2079   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2080 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) { 
2081   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2082 }
2083
2084 FPToSIInst::FPToSIInst(
2085   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2086 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) { 
2087   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2088 }
2089
2090 PtrToIntInst::PtrToIntInst(
2091   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2092 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) { 
2093   assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2094 }
2095
2096 PtrToIntInst::PtrToIntInst(
2097   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2098 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) { 
2099   assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2100 }
2101
2102 IntToPtrInst::IntToPtrInst(
2103   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2104 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) { 
2105   assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2106 }
2107
2108 IntToPtrInst::IntToPtrInst(
2109   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2110 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) { 
2111   assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2112 }
2113
2114 BitCastInst::BitCastInst(
2115   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2116 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) { 
2117   assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2118 }
2119
2120 BitCastInst::BitCastInst(
2121   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2122 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) { 
2123   assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2124 }
2125
2126 //===----------------------------------------------------------------------===//
2127 //                               CmpInst Classes
2128 //===----------------------------------------------------------------------===//
2129
2130 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2131                  const std::string &Name, Instruction *InsertBefore)
2132   : Instruction(Type::Int1Ty, op, Ops, 2, InsertBefore) {
2133     Ops[0].init(LHS, this);
2134     Ops[1].init(RHS, this);
2135   SubclassData = predicate;
2136   setName(Name);
2137   if (op == Instruction::ICmp) {
2138     assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2139            predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2140            "Invalid ICmp predicate value");
2141     const Type* Op0Ty = getOperand(0)->getType();
2142     const Type* Op1Ty = getOperand(1)->getType();
2143     assert(Op0Ty == Op1Ty &&
2144            "Both operands to ICmp instruction are not of the same type!");
2145     // Check that the operands are the right type
2146     assert((Op0Ty->isInteger() || isa<PointerType>(Op0Ty)) &&
2147            "Invalid operand types for ICmp instruction");
2148     return;
2149   }
2150   assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2151   assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2152          "Invalid FCmp predicate value");
2153   const Type* Op0Ty = getOperand(0)->getType();
2154   const Type* Op1Ty = getOperand(1)->getType();
2155   assert(Op0Ty == Op1Ty &&
2156          "Both operands to FCmp instruction are not of the same type!");
2157   // Check that the operands are the right type
2158   assert(Op0Ty->isFloatingPoint() &&
2159          "Invalid operand types for FCmp instruction");
2160 }
2161   
2162 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2163                  const std::string &Name, BasicBlock *InsertAtEnd)
2164   : Instruction(Type::Int1Ty, op, Ops, 2, InsertAtEnd) {
2165   Ops[0].init(LHS, this);
2166   Ops[1].init(RHS, this);
2167   SubclassData = predicate;
2168   setName(Name);
2169   if (op == Instruction::ICmp) {
2170     assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2171            predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2172            "Invalid ICmp predicate value");
2173
2174     const Type* Op0Ty = getOperand(0)->getType();
2175     const Type* Op1Ty = getOperand(1)->getType();
2176     assert(Op0Ty == Op1Ty &&
2177           "Both operands to ICmp instruction are not of the same type!");
2178     // Check that the operands are the right type
2179     assert(Op0Ty->isInteger() || isa<PointerType>(Op0Ty) &&
2180            "Invalid operand types for ICmp instruction");
2181     return;
2182   }
2183   assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2184   assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2185          "Invalid FCmp predicate value");
2186   const Type* Op0Ty = getOperand(0)->getType();
2187   const Type* Op1Ty = getOperand(1)->getType();
2188   assert(Op0Ty == Op1Ty &&
2189           "Both operands to FCmp instruction are not of the same type!");
2190   // Check that the operands are the right type
2191   assert(Op0Ty->isFloatingPoint() &&
2192         "Invalid operand types for FCmp instruction");
2193 }
2194
2195 CmpInst *
2196 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2, 
2197                 const std::string &Name, Instruction *InsertBefore) {
2198   if (Op == Instruction::ICmp) {
2199     return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name, 
2200                         InsertBefore);
2201   }
2202   return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name, 
2203                       InsertBefore);
2204 }
2205
2206 CmpInst *
2207 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2, 
2208                 const std::string &Name, BasicBlock *InsertAtEnd) {
2209   if (Op == Instruction::ICmp) {
2210     return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name, 
2211                         InsertAtEnd);
2212   }
2213   return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name, 
2214                       InsertAtEnd);
2215 }
2216
2217 void CmpInst::swapOperands() {
2218   if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2219     IC->swapOperands();
2220   else
2221     cast<FCmpInst>(this)->swapOperands();
2222 }
2223
2224 bool CmpInst::isCommutative() {
2225   if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2226     return IC->isCommutative();
2227   return cast<FCmpInst>(this)->isCommutative();
2228 }
2229
2230 bool CmpInst::isEquality() {
2231   if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2232     return IC->isEquality();
2233   return cast<FCmpInst>(this)->isEquality();
2234 }
2235
2236
2237 ICmpInst::Predicate ICmpInst::getInversePredicate(Predicate pred) {
2238   switch (pred) {
2239     default:
2240       assert(!"Unknown icmp predicate!");
2241     case ICMP_EQ: return ICMP_NE;
2242     case ICMP_NE: return ICMP_EQ;
2243     case ICMP_UGT: return ICMP_ULE;
2244     case ICMP_ULT: return ICMP_UGE;
2245     case ICMP_UGE: return ICMP_ULT;
2246     case ICMP_ULE: return ICMP_UGT;
2247     case ICMP_SGT: return ICMP_SLE;
2248     case ICMP_SLT: return ICMP_SGE;
2249     case ICMP_SGE: return ICMP_SLT;
2250     case ICMP_SLE: return ICMP_SGT;
2251   }
2252 }
2253
2254 ICmpInst::Predicate ICmpInst::getSwappedPredicate(Predicate pred) {
2255   switch (pred) {
2256     default: assert(! "Unknown icmp predicate!");
2257     case ICMP_EQ: case ICMP_NE:
2258       return pred;
2259     case ICMP_SGT: return ICMP_SLT;
2260     case ICMP_SLT: return ICMP_SGT;
2261     case ICMP_SGE: return ICMP_SLE;
2262     case ICMP_SLE: return ICMP_SGE;
2263     case ICMP_UGT: return ICMP_ULT;
2264     case ICMP_ULT: return ICMP_UGT;
2265     case ICMP_UGE: return ICMP_ULE;
2266     case ICMP_ULE: return ICMP_UGE;
2267   }
2268 }
2269
2270 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2271   switch (pred) {
2272     default: assert(! "Unknown icmp predicate!");
2273     case ICMP_EQ: case ICMP_NE: 
2274     case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE: 
2275        return pred;
2276     case ICMP_UGT: return ICMP_SGT;
2277     case ICMP_ULT: return ICMP_SLT;
2278     case ICMP_UGE: return ICMP_SGE;
2279     case ICMP_ULE: return ICMP_SLE;
2280   }
2281 }
2282
2283 bool ICmpInst::isSignedPredicate(Predicate pred) {
2284   switch (pred) {
2285     default: assert(! "Unknown icmp predicate!");
2286     case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE: 
2287       return true;
2288     case ICMP_EQ:  case ICMP_NE: case ICMP_UGT: case ICMP_ULT: 
2289     case ICMP_UGE: case ICMP_ULE:
2290       return false;
2291   }
2292 }
2293
2294 /// Initialize a set of values that all satisfy the condition with C.
2295 ///
2296 ConstantRange 
2297 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2298   APInt Lower(C);
2299   APInt Upper(C);
2300   uint32_t BitWidth = C.getBitWidth();
2301   switch (pred) {
2302   default: assert(0 && "Invalid ICmp opcode to ConstantRange ctor!");
2303   case ICmpInst::ICMP_EQ: Upper++; break;
2304   case ICmpInst::ICMP_NE: Lower++; break;
2305   case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2306   case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2307   case ICmpInst::ICMP_UGT: 
2308     Lower++; Upper = APInt::getMinValue(BitWidth);        // Min = Next(Max)
2309     break;
2310   case ICmpInst::ICMP_SGT:
2311     Lower++; Upper = APInt::getSignedMinValue(BitWidth);  // Min = Next(Max)
2312     break;
2313   case ICmpInst::ICMP_ULE: 
2314     Lower = APInt::getMinValue(BitWidth); Upper++; 
2315     break;
2316   case ICmpInst::ICMP_SLE: 
2317     Lower = APInt::getSignedMinValue(BitWidth); Upper++; 
2318     break;
2319   case ICmpInst::ICMP_UGE:
2320     Upper = APInt::getMinValue(BitWidth);        // Min = Next(Max)
2321     break;
2322   case ICmpInst::ICMP_SGE:
2323     Upper = APInt::getSignedMinValue(BitWidth);  // Min = Next(Max)
2324     break;
2325   }
2326   return ConstantRange(Lower, Upper);
2327 }
2328
2329 FCmpInst::Predicate FCmpInst::getInversePredicate(Predicate pred) {
2330   switch (pred) {
2331     default:
2332       assert(!"Unknown icmp predicate!");
2333     case FCMP_OEQ: return FCMP_UNE;
2334     case FCMP_ONE: return FCMP_UEQ;
2335     case FCMP_OGT: return FCMP_ULE;
2336     case FCMP_OLT: return FCMP_UGE;
2337     case FCMP_OGE: return FCMP_ULT;
2338     case FCMP_OLE: return FCMP_UGT;
2339     case FCMP_UEQ: return FCMP_ONE;
2340     case FCMP_UNE: return FCMP_OEQ;
2341     case FCMP_UGT: return FCMP_OLE;
2342     case FCMP_ULT: return FCMP_OGE;
2343     case FCMP_UGE: return FCMP_OLT;
2344     case FCMP_ULE: return FCMP_OGT;
2345     case FCMP_ORD: return FCMP_UNO;
2346     case FCMP_UNO: return FCMP_ORD;
2347     case FCMP_TRUE: return FCMP_FALSE;
2348     case FCMP_FALSE: return FCMP_TRUE;
2349   }
2350 }
2351
2352 FCmpInst::Predicate FCmpInst::getSwappedPredicate(Predicate pred) {
2353   switch (pred) {
2354     default: assert(!"Unknown fcmp predicate!");
2355     case FCMP_FALSE: case FCMP_TRUE:
2356     case FCMP_OEQ: case FCMP_ONE:
2357     case FCMP_UEQ: case FCMP_UNE:
2358     case FCMP_ORD: case FCMP_UNO:
2359       return pred;
2360     case FCMP_OGT: return FCMP_OLT;
2361     case FCMP_OLT: return FCMP_OGT;
2362     case FCMP_OGE: return FCMP_OLE;
2363     case FCMP_OLE: return FCMP_OGE;
2364     case FCMP_UGT: return FCMP_ULT;
2365     case FCMP_ULT: return FCMP_UGT;
2366     case FCMP_UGE: return FCMP_ULE;
2367     case FCMP_ULE: return FCMP_UGE;
2368   }
2369 }
2370
2371 bool CmpInst::isUnsigned(unsigned short predicate) {
2372   switch (predicate) {
2373     default: return false;
2374     case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT: 
2375     case ICmpInst::ICMP_UGE: return true;
2376   }
2377 }
2378
2379 bool CmpInst::isSigned(unsigned short predicate){
2380   switch (predicate) {
2381     default: return false;
2382     case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT: 
2383     case ICmpInst::ICMP_SGE: return true;
2384   }
2385 }
2386
2387 bool CmpInst::isOrdered(unsigned short predicate) {
2388   switch (predicate) {
2389     default: return false;
2390     case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT: 
2391     case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE: 
2392     case FCmpInst::FCMP_ORD: return true;
2393   }
2394 }
2395       
2396 bool CmpInst::isUnordered(unsigned short predicate) {
2397   switch (predicate) {
2398     default: return false;
2399     case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT: 
2400     case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE: 
2401     case FCmpInst::FCMP_UNO: return true;
2402   }
2403 }
2404
2405 //===----------------------------------------------------------------------===//
2406 //                        SwitchInst Implementation
2407 //===----------------------------------------------------------------------===//
2408
2409 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2410   assert(Value && Default);
2411   ReservedSpace = 2+NumCases*2;
2412   NumOperands = 2;
2413   OperandList = new Use[ReservedSpace];
2414
2415   OperandList[0].init(Value, this);
2416   OperandList[1].init(Default, this);
2417 }
2418
2419 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2420 /// switch on and a default destination.  The number of additional cases can
2421 /// be specified here to make memory allocation more efficient.  This
2422 /// constructor can also autoinsert before another instruction.
2423 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2424                        Instruction *InsertBefore)
2425   : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) {
2426   init(Value, Default, NumCases);
2427 }
2428
2429 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2430 /// switch on and a default destination.  The number of additional cases can
2431 /// be specified here to make memory allocation more efficient.  This
2432 /// constructor also autoinserts at the end of the specified BasicBlock.
2433 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2434                        BasicBlock *InsertAtEnd)
2435   : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) {
2436   init(Value, Default, NumCases);
2437 }
2438
2439 SwitchInst::SwitchInst(const SwitchInst &SI)
2440   : TerminatorInst(Type::VoidTy, Instruction::Switch,
2441                    new Use[SI.getNumOperands()], SI.getNumOperands()) {
2442   Use *OL = OperandList, *InOL = SI.OperandList;
2443   for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2444     OL[i].init(InOL[i], this);
2445     OL[i+1].init(InOL[i+1], this);
2446   }
2447 }
2448
2449 SwitchInst::~SwitchInst() {
2450   delete [] OperandList;
2451 }
2452
2453
2454 /// addCase - Add an entry to the switch instruction...
2455 ///
2456 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2457   unsigned OpNo = NumOperands;
2458   if (OpNo+2 > ReservedSpace)
2459     resizeOperands(0);  // Get more space!
2460   // Initialize some new operands.
2461   assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2462   NumOperands = OpNo+2;
2463   OperandList[OpNo].init(OnVal, this);
2464   OperandList[OpNo+1].init(Dest, this);
2465 }
2466
2467 /// removeCase - This method removes the specified successor from the switch
2468 /// instruction.  Note that this cannot be used to remove the default
2469 /// destination (successor #0).
2470 ///
2471 void SwitchInst::removeCase(unsigned idx) {
2472   assert(idx != 0 && "Cannot remove the default case!");
2473   assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2474
2475   unsigned NumOps = getNumOperands();
2476   Use *OL = OperandList;
2477
2478   // Move everything after this operand down.
2479   //
2480   // FIXME: we could just swap with the end of the list, then erase.  However,
2481   // client might not expect this to happen.  The code as it is thrashes the
2482   // use/def lists, which is kinda lame.
2483   for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2484     OL[i-2] = OL[i];
2485     OL[i-2+1] = OL[i+1];
2486   }
2487
2488   // Nuke the last value.
2489   OL[NumOps-2].set(0);
2490   OL[NumOps-2+1].set(0);
2491   NumOperands = NumOps-2;
2492 }
2493
2494 /// resizeOperands - resize operands - This adjusts the length of the operands
2495 /// list according to the following behavior:
2496 ///   1. If NumOps == 0, grow the operand list in response to a push_back style
2497 ///      of operation.  This grows the number of ops by 1.5 times.
2498 ///   2. If NumOps > NumOperands, reserve space for NumOps operands.
2499 ///   3. If NumOps == NumOperands, trim the reserved space.
2500 ///
2501 void SwitchInst::resizeOperands(unsigned NumOps) {
2502   if (NumOps == 0) {
2503     NumOps = getNumOperands()/2*6;
2504   } else if (NumOps*2 > NumOperands) {
2505     // No resize needed.
2506     if (ReservedSpace >= NumOps) return;
2507   } else if (NumOps == NumOperands) {
2508     if (ReservedSpace == NumOps) return;
2509   } else {
2510     return;
2511   }
2512
2513   ReservedSpace = NumOps;
2514   Use *NewOps = new Use[NumOps];
2515   Use *OldOps = OperandList;
2516   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2517       NewOps[i].init(OldOps[i], this);
2518       OldOps[i].set(0);
2519   }
2520   delete [] OldOps;
2521   OperandList = NewOps;
2522 }
2523
2524
2525 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2526   return getSuccessor(idx);
2527 }
2528 unsigned SwitchInst::getNumSuccessorsV() const {
2529   return getNumSuccessors();
2530 }
2531 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2532   setSuccessor(idx, B);
2533 }
2534
2535
2536 // Define these methods here so vtables don't get emitted into every translation
2537 // unit that uses these classes.
2538
2539 GetElementPtrInst *GetElementPtrInst::clone() const {
2540   return new GetElementPtrInst(*this);
2541 }
2542
2543 BinaryOperator *BinaryOperator::clone() const {
2544   return create(getOpcode(), Ops[0], Ops[1]);
2545 }
2546
2547 FCmpInst* FCmpInst::clone() const {
2548   return new FCmpInst(getPredicate(), Ops[0], Ops[1]);
2549 }
2550 ICmpInst* ICmpInst::clone() const {
2551   return new ICmpInst(getPredicate(), Ops[0], Ops[1]);
2552 }
2553
2554 MallocInst *MallocInst::clone()   const { return new MallocInst(*this); }
2555 AllocaInst *AllocaInst::clone()   const { return new AllocaInst(*this); }
2556 FreeInst   *FreeInst::clone()     const { return new FreeInst(getOperand(0)); }
2557 LoadInst   *LoadInst::clone()     const { return new LoadInst(*this); }
2558 StoreInst  *StoreInst::clone()    const { return new StoreInst(*this); }
2559 CastInst   *TruncInst::clone()    const { return new TruncInst(*this); }
2560 CastInst   *ZExtInst::clone()     const { return new ZExtInst(*this); }
2561 CastInst   *SExtInst::clone()     const { return new SExtInst(*this); }
2562 CastInst   *FPTruncInst::clone()  const { return new FPTruncInst(*this); }
2563 CastInst   *FPExtInst::clone()    const { return new FPExtInst(*this); }
2564 CastInst   *UIToFPInst::clone()   const { return new UIToFPInst(*this); }
2565 CastInst   *SIToFPInst::clone()   const { return new SIToFPInst(*this); }
2566 CastInst   *FPToUIInst::clone()   const { return new FPToUIInst(*this); }
2567 CastInst   *FPToSIInst::clone()   const { return new FPToSIInst(*this); }
2568 CastInst   *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
2569 CastInst   *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
2570 CastInst   *BitCastInst::clone()  const { return new BitCastInst(*this); }
2571 CallInst   *CallInst::clone()     const { return new CallInst(*this); }
2572 SelectInst *SelectInst::clone()   const { return new SelectInst(*this); }
2573 VAArgInst  *VAArgInst::clone()    const { return new VAArgInst(*this); }
2574
2575 ExtractElementInst *ExtractElementInst::clone() const {
2576   return new ExtractElementInst(*this);
2577 }
2578 InsertElementInst *InsertElementInst::clone() const {
2579   return new InsertElementInst(*this);
2580 }
2581 ShuffleVectorInst *ShuffleVectorInst::clone() const {
2582   return new ShuffleVectorInst(*this);
2583 }
2584 PHINode    *PHINode::clone()    const { return new PHINode(*this); }
2585 ReturnInst *ReturnInst::clone() const { return new ReturnInst(*this); }
2586 BranchInst *BranchInst::clone() const { return new BranchInst(*this); }
2587 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
2588 InvokeInst *InvokeInst::clone() const { return new InvokeInst(*this); }
2589 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
2590 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}