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