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