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