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