core changes for varargs
[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/Support/CallSite.h"
21 using namespace llvm;
22
23 unsigned CallSite::getCallingConv() const {
24   if (CallInst *CI = dyn_cast<CallInst>(I))
25     return CI->getCallingConv();
26   else
27     return cast<InvokeInst>(I)->getCallingConv();
28 }
29 void CallSite::setCallingConv(unsigned CC) {
30   if (CallInst *CI = dyn_cast<CallInst>(I))
31     CI->setCallingConv(CC);
32   else
33     cast<InvokeInst>(I)->setCallingConv(CC);
34 }
35
36
37 //===----------------------------------------------------------------------===//
38 //                            TerminatorInst Class
39 //===----------------------------------------------------------------------===//
40
41 TerminatorInst::TerminatorInst(Instruction::TermOps iType,
42                                Use *Ops, unsigned NumOps, Instruction *IB)
43   : Instruction(Type::VoidTy, iType, Ops, NumOps, "", IB) {
44 }
45
46 TerminatorInst::TerminatorInst(Instruction::TermOps iType,
47                                Use *Ops, unsigned NumOps, BasicBlock *IAE)
48   : Instruction(Type::VoidTy, iType, Ops, NumOps, "", IAE) {
49 }
50
51
52
53 //===----------------------------------------------------------------------===//
54 //                               PHINode Class
55 //===----------------------------------------------------------------------===//
56
57 PHINode::PHINode(const PHINode &PN)
58   : Instruction(PN.getType(), Instruction::PHI,
59                 new Use[PN.getNumOperands()], PN.getNumOperands()),
60     ReservedSpace(PN.getNumOperands()) {
61   Use *OL = OperandList;
62   for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
63     OL[i].init(PN.getOperand(i), this);
64     OL[i+1].init(PN.getOperand(i+1), this);
65   }
66 }
67
68 PHINode::~PHINode() {
69   delete [] OperandList;
70 }
71
72 // removeIncomingValue - Remove an incoming value.  This is useful if a
73 // predecessor basic block is deleted.
74 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
75   unsigned NumOps = getNumOperands();
76   Use *OL = OperandList;
77   assert(Idx*2 < NumOps && "BB not in PHI node!");
78   Value *Removed = OL[Idx*2];
79
80   // Move everything after this operand down.
81   //
82   // FIXME: we could just swap with the end of the list, then erase.  However,
83   // client might not expect this to happen.  The code as it is thrashes the
84   // use/def lists, which is kinda lame.
85   for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
86     OL[i-2] = OL[i];
87     OL[i-2+1] = OL[i+1];
88   }
89
90   // Nuke the last value.
91   OL[NumOps-2].set(0);
92   OL[NumOps-2+1].set(0);
93   NumOperands = NumOps-2;
94
95   // If the PHI node is dead, because it has zero entries, nuke it now.
96   if (NumOps == 2 && DeletePHIIfEmpty) {
97     // If anyone is using this PHI, make them use a dummy value instead...
98     replaceAllUsesWith(UndefValue::get(getType()));
99     eraseFromParent();
100   }
101   return Removed;
102 }
103
104 /// resizeOperands - resize operands - This adjusts the length of the operands
105 /// list according to the following behavior:
106 ///   1. If NumOps == 0, grow the operand list in response to a push_back style
107 ///      of operation.  This grows the number of ops by 1.5 times.
108 ///   2. If NumOps > NumOperands, reserve space for NumOps operands.
109 ///   3. If NumOps == NumOperands, trim the reserved space.
110 ///
111 void PHINode::resizeOperands(unsigned NumOps) {
112   if (NumOps == 0) {
113     NumOps = (getNumOperands())*3/2;
114     if (NumOps < 4) NumOps = 4;      // 4 op PHI nodes are VERY common.
115   } else if (NumOps*2 > NumOperands) {
116     // No resize needed.
117     if (ReservedSpace >= NumOps) return;
118   } else if (NumOps == NumOperands) {
119     if (ReservedSpace == NumOps) return;
120   } else {
121     return;
122   }
123
124   ReservedSpace = NumOps;
125   Use *NewOps = new Use[NumOps];
126   Use *OldOps = OperandList;
127   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
128       NewOps[i].init(OldOps[i], this);
129       OldOps[i].set(0);
130   }
131   delete [] OldOps;
132   OperandList = NewOps;
133 }
134
135
136 //===----------------------------------------------------------------------===//
137 //                        CallInst Implementation
138 //===----------------------------------------------------------------------===//
139
140 CallInst::~CallInst() {
141   delete [] OperandList;
142 }
143
144 void CallInst::init(Value *Func, const std::vector<Value*> &Params) {
145   NumOperands = Params.size()+1;
146   Use *OL = OperandList = new Use[Params.size()+1];
147   OL[0].init(Func, this);
148
149   const FunctionType *FTy =
150     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
151
152   assert((Params.size() == FTy->getNumParams() ||
153           (FTy->isVarArg() && Params.size() > FTy->getNumParams())) &&
154          "Calling a function with bad signature");
155   for (unsigned i = 0, e = Params.size(); i != e; ++i)
156     OL[i+1].init(Params[i], this);
157 }
158
159 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
160   NumOperands = 3;
161   Use *OL = OperandList = new Use[3];
162   OL[0].init(Func, this);
163   OL[1].init(Actual1, this);
164   OL[2].init(Actual2, this);
165
166   const FunctionType *FTy =
167     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
168
169   assert((FTy->getNumParams() == 2 ||
170           (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
171          "Calling a function with bad signature");
172 }
173
174 void CallInst::init(Value *Func, Value *Actual) {
175   NumOperands = 2;
176   Use *OL = OperandList = new Use[2];
177   OL[0].init(Func, this);
178   OL[1].init(Actual, this);
179
180   const FunctionType *FTy =
181     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
182
183   assert((FTy->getNumParams() == 1 ||
184           (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
185          "Calling a function with bad signature");
186 }
187
188 void CallInst::init(Value *Func) {
189   NumOperands = 1;
190   Use *OL = OperandList = new Use[1];
191   OL[0].init(Func, this);
192
193   const FunctionType *MTy =
194     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
195
196   assert(MTy->getNumParams() == 0 && "Calling a function with bad signature");
197 }
198
199 CallInst::CallInst(Value *Func, const std::vector<Value*> &Params,
200                    const std::string &Name, Instruction *InsertBefore)
201   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
202                                  ->getElementType())->getReturnType(),
203                 Instruction::Call, 0, 0, Name, InsertBefore) {
204   init(Func, Params);
205 }
206
207 CallInst::CallInst(Value *Func, const std::vector<Value*> &Params,
208                    const std::string &Name, BasicBlock *InsertAtEnd)
209   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
210                                  ->getElementType())->getReturnType(),
211                 Instruction::Call, 0, 0, Name, InsertAtEnd) {
212   init(Func, Params);
213 }
214
215 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
216                    const std::string &Name, Instruction  *InsertBefore)
217   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
218                                    ->getElementType())->getReturnType(),
219                 Instruction::Call, 0, 0, Name, InsertBefore) {
220   init(Func, Actual1, Actual2);
221 }
222
223 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
224                    const std::string &Name, BasicBlock  *InsertAtEnd)
225   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
226                                    ->getElementType())->getReturnType(),
227                 Instruction::Call, 0, 0, Name, InsertAtEnd) {
228   init(Func, Actual1, Actual2);
229 }
230
231 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
232                    Instruction  *InsertBefore)
233   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
234                                    ->getElementType())->getReturnType(),
235                 Instruction::Call, 0, 0, Name, InsertBefore) {
236   init(Func, Actual);
237 }
238
239 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
240                    BasicBlock  *InsertAtEnd)
241   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
242                                    ->getElementType())->getReturnType(),
243                 Instruction::Call, 0, 0, Name, InsertAtEnd) {
244   init(Func, Actual);
245 }
246
247 CallInst::CallInst(Value *Func, const std::string &Name,
248                    Instruction *InsertBefore)
249   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
250                                    ->getElementType())->getReturnType(),
251                 Instruction::Call, 0, 0, Name, InsertBefore) {
252   init(Func);
253 }
254
255 CallInst::CallInst(Value *Func, const std::string &Name,
256                    BasicBlock *InsertAtEnd)
257   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
258                                    ->getElementType())->getReturnType(),
259                 Instruction::Call, 0, 0, Name, InsertAtEnd) {
260   init(Func);
261 }
262
263 CallInst::CallInst(const CallInst &CI)
264   : Instruction(CI.getType(), Instruction::Call, new Use[CI.getNumOperands()],
265                 CI.getNumOperands()) {
266   SubclassData = CI.SubclassData;
267   Use *OL = OperandList;
268   Use *InOL = CI.OperandList;
269   for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
270     OL[i].init(InOL[i], this);
271 }
272
273
274 //===----------------------------------------------------------------------===//
275 //                        InvokeInst Implementation
276 //===----------------------------------------------------------------------===//
277
278 InvokeInst::~InvokeInst() {
279   delete [] OperandList;
280 }
281
282 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
283                       const std::vector<Value*> &Params) {
284   NumOperands = 3+Params.size();
285   Use *OL = OperandList = new Use[3+Params.size()];
286   OL[0].init(Fn, this);
287   OL[1].init(IfNormal, this);
288   OL[2].init(IfException, this);
289   const FunctionType *FTy =
290     cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
291
292   assert((Params.size() == FTy->getNumParams()) ||
293          (FTy->isVarArg() && Params.size() > FTy->getNumParams()) &&
294          "Calling a function with bad signature");
295
296   for (unsigned i = 0, e = Params.size(); i != e; i++)
297     OL[i+3].init(Params[i], this);
298 }
299
300 InvokeInst::InvokeInst(Value *Fn, BasicBlock *IfNormal,
301                        BasicBlock *IfException,
302                        const std::vector<Value*> &Params,
303                        const std::string &Name, Instruction *InsertBefore)
304   : TerminatorInst(cast<FunctionType>(cast<PointerType>(Fn->getType())
305                                     ->getElementType())->getReturnType(),
306                    Instruction::Invoke, 0, 0, Name, InsertBefore) {
307   init(Fn, IfNormal, IfException, Params);
308 }
309
310 InvokeInst::InvokeInst(Value *Fn, BasicBlock *IfNormal,
311                        BasicBlock *IfException,
312                        const std::vector<Value*> &Params,
313                        const std::string &Name, BasicBlock *InsertAtEnd)
314   : TerminatorInst(cast<FunctionType>(cast<PointerType>(Fn->getType())
315                                     ->getElementType())->getReturnType(),
316                    Instruction::Invoke, 0, 0, Name, InsertAtEnd) {
317   init(Fn, IfNormal, IfException, Params);
318 }
319
320 InvokeInst::InvokeInst(const InvokeInst &II)
321   : TerminatorInst(II.getType(), Instruction::Invoke,
322                    new Use[II.getNumOperands()], II.getNumOperands()) {
323   SubclassData = II.SubclassData;
324   Use *OL = OperandList, *InOL = II.OperandList;
325   for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
326     OL[i].init(InOL[i], this);
327 }
328
329 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
330   return getSuccessor(idx);
331 }
332 unsigned InvokeInst::getNumSuccessorsV() const {
333   return getNumSuccessors();
334 }
335 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
336   return setSuccessor(idx, B);
337 }
338
339
340 //===----------------------------------------------------------------------===//
341 //                        ReturnInst Implementation
342 //===----------------------------------------------------------------------===//
343
344 void ReturnInst::init(Value *retVal) {
345   if (retVal && retVal->getType() != Type::VoidTy) {
346     assert(!isa<BasicBlock>(retVal) &&
347            "Cannot return basic block.  Probably using the incorrect ctor");
348     NumOperands = 1;
349     RetVal.init(retVal, this);
350   }
351 }
352
353 unsigned ReturnInst::getNumSuccessorsV() const {
354   return getNumSuccessors();
355 }
356
357 // Out-of-line ReturnInst method, put here so the C++ compiler can choose to
358 // emit the vtable for the class in this translation unit.
359 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
360   assert(0 && "ReturnInst has no successors!");
361 }
362
363 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
364   assert(0 && "ReturnInst has no successors!");
365   abort();
366   return 0;
367 }
368
369
370 //===----------------------------------------------------------------------===//
371 //                        UnwindInst Implementation
372 //===----------------------------------------------------------------------===//
373
374 unsigned UnwindInst::getNumSuccessorsV() const {
375   return getNumSuccessors();
376 }
377
378 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
379   assert(0 && "UnwindInst has no successors!");
380 }
381
382 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
383   assert(0 && "UnwindInst has no successors!");
384   abort();
385   return 0;
386 }
387
388 //===----------------------------------------------------------------------===//
389 //                      UnreachableInst Implementation
390 //===----------------------------------------------------------------------===//
391
392 unsigned UnreachableInst::getNumSuccessorsV() const {
393   return getNumSuccessors();
394 }
395
396 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
397   assert(0 && "UnwindInst has no successors!");
398 }
399
400 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
401   assert(0 && "UnwindInst has no successors!");
402   abort();
403   return 0;
404 }
405
406 //===----------------------------------------------------------------------===//
407 //                        BranchInst Implementation
408 //===----------------------------------------------------------------------===//
409
410 void BranchInst::AssertOK() {
411   if (isConditional())
412     assert(getCondition()->getType() == Type::BoolTy &&
413            "May only branch on boolean predicates!");
414 }
415
416 BranchInst::BranchInst(const BranchInst &BI) :
417   TerminatorInst(Instruction::Br, Ops, BI.getNumOperands()) {
418   OperandList[0].init(BI.getOperand(0), this);
419   if (BI.getNumOperands() != 1) {
420     assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
421     OperandList[1].init(BI.getOperand(1), this);
422     OperandList[2].init(BI.getOperand(2), this);
423   }
424 }
425
426 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
427   return getSuccessor(idx);
428 }
429 unsigned BranchInst::getNumSuccessorsV() const {
430   return getNumSuccessors();
431 }
432 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
433   setSuccessor(idx, B);
434 }
435
436
437 //===----------------------------------------------------------------------===//
438 //                        AllocationInst Implementation
439 //===----------------------------------------------------------------------===//
440
441 static Value *getAISize(Value *Amt) {
442   if (!Amt)
443     Amt = ConstantUInt::get(Type::UIntTy, 1);
444   else
445     assert(Amt->getType() == Type::UIntTy &&
446            "Malloc/Allocation array size != UIntTy!");
447   return Amt;
448 }
449
450 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
451                                const std::string &Name,
452                                Instruction *InsertBefore)
453   : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
454                      Name, InsertBefore) {
455   assert(Ty != Type::VoidTy && "Cannot allocate void!");
456 }
457
458 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
459                                const std::string &Name,
460                                BasicBlock *InsertAtEnd)
461   : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
462                      Name, InsertAtEnd) {
463   assert(Ty != Type::VoidTy && "Cannot allocate void!");
464 }
465
466 bool AllocationInst::isArrayAllocation() const {
467   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(getOperand(0)))
468     return CUI->getValue() != 1;
469   return true;
470 }
471
472 const Type *AllocationInst::getAllocatedType() const {
473   return getType()->getElementType();
474 }
475
476 AllocaInst::AllocaInst(const AllocaInst &AI)
477   : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
478                    Instruction::Alloca) {
479 }
480
481 MallocInst::MallocInst(const MallocInst &MI)
482   : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
483                    Instruction::Malloc) {
484 }
485
486 //===----------------------------------------------------------------------===//
487 //                             FreeInst Implementation
488 //===----------------------------------------------------------------------===//
489
490 void FreeInst::AssertOK() {
491   assert(isa<PointerType>(getOperand(0)->getType()) &&
492          "Can not free something of nonpointer type!");
493 }
494
495 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
496   : UnaryInstruction(Type::VoidTy, Free, Ptr, "", InsertBefore) {
497   AssertOK();
498 }
499
500 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
501   : UnaryInstruction(Type::VoidTy, Free, Ptr, "", InsertAtEnd) {
502   AssertOK();
503 }
504
505
506 //===----------------------------------------------------------------------===//
507 //                           LoadInst Implementation
508 //===----------------------------------------------------------------------===//
509
510 void LoadInst::AssertOK() {
511   assert(isa<PointerType>(getOperand(0)->getType()) &&
512          "Ptr must have pointer type.");
513 }
514
515 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
516   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
517                      Load, Ptr, Name, InsertBef) {
518   setVolatile(false);
519   AssertOK();
520 }
521
522 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
523   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
524                      Load, Ptr, Name, InsertAE) {
525   setVolatile(false);
526   AssertOK();
527 }
528
529 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
530                    Instruction *InsertBef)
531   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
532                      Load, Ptr, Name, InsertBef) {
533   setVolatile(isVolatile);
534   AssertOK();
535 }
536
537 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
538                    BasicBlock *InsertAE)
539   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
540                      Load, Ptr, Name, InsertAE) {
541   setVolatile(isVolatile);
542   AssertOK();
543 }
544
545
546 //===----------------------------------------------------------------------===//
547 //                           StoreInst Implementation
548 //===----------------------------------------------------------------------===//
549
550 void StoreInst::AssertOK() {
551   assert(isa<PointerType>(getOperand(1)->getType()) &&
552          "Ptr must have pointer type!");
553   assert(getOperand(0)->getType() ==
554                  cast<PointerType>(getOperand(1)->getType())->getElementType()
555          && "Ptr must be a pointer to Val type!");
556 }
557
558
559 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
560   : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertBefore) {
561   Ops[0].init(val, this);
562   Ops[1].init(addr, this);
563   setVolatile(false);
564   AssertOK();
565 }
566
567 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
568   : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertAtEnd) {
569   Ops[0].init(val, this);
570   Ops[1].init(addr, this);
571   setVolatile(false);
572   AssertOK();
573 }
574
575 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
576                      Instruction *InsertBefore)
577   : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertBefore) {
578   Ops[0].init(val, this);
579   Ops[1].init(addr, this);
580   setVolatile(isVolatile);
581   AssertOK();
582 }
583
584 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
585                      BasicBlock *InsertAtEnd)
586   : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertAtEnd) {
587   Ops[0].init(val, this);
588   Ops[1].init(addr, this);
589   setVolatile(isVolatile);
590   AssertOK();
591 }
592
593 //===----------------------------------------------------------------------===//
594 //                       GetElementPtrInst Implementation
595 //===----------------------------------------------------------------------===//
596
597 // checkType - Simple wrapper function to give a better assertion failure
598 // message on bad indexes for a gep instruction.
599 //
600 static inline const Type *checkType(const Type *Ty) {
601   assert(Ty && "Invalid indices for type!");
602   return Ty;
603 }
604
605 void GetElementPtrInst::init(Value *Ptr, const std::vector<Value*> &Idx) {
606   NumOperands = 1+Idx.size();
607   Use *OL = OperandList = new Use[NumOperands];
608   OL[0].init(Ptr, this);
609
610   for (unsigned i = 0, e = Idx.size(); i != e; ++i)
611     OL[i+1].init(Idx[i], this);
612 }
613
614 void GetElementPtrInst::init(Value *Ptr, Value *Idx0, Value *Idx1) {
615   NumOperands = 3;
616   Use *OL = OperandList = new Use[3];
617   OL[0].init(Ptr, this);
618   OL[1].init(Idx0, this);
619   OL[2].init(Idx1, this);
620 }
621
622 void GetElementPtrInst::init(Value *Ptr, Value *Idx) {
623   NumOperands = 2;
624   Use *OL = OperandList = new Use[2];
625   OL[0].init(Ptr, this);
626   OL[1].init(Idx, this);
627 }
628
629 GetElementPtrInst::GetElementPtrInst(Value *Ptr, const std::vector<Value*> &Idx,
630                                      const std::string &Name, Instruction *InBe)
631   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
632                                                           Idx, true))),
633                 GetElementPtr, 0, 0, Name, InBe) {
634   init(Ptr, Idx);
635 }
636
637 GetElementPtrInst::GetElementPtrInst(Value *Ptr, const std::vector<Value*> &Idx,
638                                      const std::string &Name, BasicBlock *IAE)
639   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
640                                                           Idx, true))),
641                 GetElementPtr, 0, 0, Name, IAE) {
642   init(Ptr, Idx);
643 }
644
645 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
646                                      const std::string &Name, Instruction *InBe)
647   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx))),
648                 GetElementPtr, 0, 0, Name, InBe) {
649   init(Ptr, Idx);
650 }
651
652 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
653                                      const std::string &Name, BasicBlock *IAE)
654   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx))),
655                 GetElementPtr, 0, 0, Name, IAE) {
656   init(Ptr, Idx);
657 }
658
659 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
660                                      const std::string &Name, Instruction *InBe)
661   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
662                                                           Idx0, Idx1, true))),
663                 GetElementPtr, 0, 0, Name, InBe) {
664   init(Ptr, Idx0, Idx1);
665 }
666
667 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
668                                      const std::string &Name, BasicBlock *IAE)
669   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
670                                                           Idx0, Idx1, true))),
671                 GetElementPtr, 0, 0, Name, IAE) {
672   init(Ptr, Idx0, Idx1);
673 }
674
675 GetElementPtrInst::~GetElementPtrInst() {
676   delete[] OperandList;
677 }
678
679 // getIndexedType - Returns the type of the element that would be loaded with
680 // a load instruction with the specified parameters.
681 //
682 // A null type is returned if the indices are invalid for the specified
683 // pointer type.
684 //
685 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
686                                               const std::vector<Value*> &Idx,
687                                               bool AllowCompositeLeaf) {
688   if (!isa<PointerType>(Ptr)) return 0;   // Type isn't a pointer type!
689
690   // Handle the special case of the empty set index set...
691   if (Idx.empty())
692     if (AllowCompositeLeaf ||
693         cast<PointerType>(Ptr)->getElementType()->isFirstClassType())
694       return cast<PointerType>(Ptr)->getElementType();
695     else
696       return 0;
697
698   unsigned CurIdx = 0;
699   while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
700     if (Idx.size() == CurIdx) {
701       if (AllowCompositeLeaf || CT->isFirstClassType()) return Ptr;
702       return 0;   // Can't load a whole structure or array!?!?
703     }
704
705     Value *Index = Idx[CurIdx++];
706     if (isa<PointerType>(CT) && CurIdx != 1)
707       return 0;  // Can only index into pointer types at the first index!
708     if (!CT->indexValid(Index)) return 0;
709     Ptr = CT->getTypeAtIndex(Index);
710
711     // If the new type forwards to another type, then it is in the middle
712     // of being refined to another type (and hence, may have dropped all
713     // references to what it was using before).  So, use the new forwarded
714     // type.
715     if (const Type * Ty = Ptr->getForwardedType()) {
716       Ptr = Ty;
717     }
718   }
719   return CurIdx == Idx.size() ? Ptr : 0;
720 }
721
722 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
723                                               Value *Idx0, Value *Idx1,
724                                               bool AllowCompositeLeaf) {
725   const PointerType *PTy = dyn_cast<PointerType>(Ptr);
726   if (!PTy) return 0;   // Type isn't a pointer type!
727
728   // Check the pointer index.
729   if (!PTy->indexValid(Idx0)) return 0;
730
731   const CompositeType *CT = dyn_cast<CompositeType>(PTy->getElementType());
732   if (!CT || !CT->indexValid(Idx1)) return 0;
733
734   const Type *ElTy = CT->getTypeAtIndex(Idx1);
735   if (AllowCompositeLeaf || ElTy->isFirstClassType())
736     return ElTy;
737   return 0;
738 }
739
740 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
741   const PointerType *PTy = dyn_cast<PointerType>(Ptr);
742   if (!PTy) return 0;   // Type isn't a pointer type!
743
744   // Check the pointer index.
745   if (!PTy->indexValid(Idx)) return 0;
746
747   return PTy->getElementType();
748 }
749
750 //===----------------------------------------------------------------------===//
751 //                             BinaryOperator Class
752 //===----------------------------------------------------------------------===//
753
754 void BinaryOperator::init(BinaryOps iType)
755 {
756   Value *LHS = getOperand(0), *RHS = getOperand(1);
757   assert(LHS->getType() == RHS->getType() &&
758          "Binary operator operand types must match!");
759 #ifndef NDEBUG
760   switch (iType) {
761   case Add: case Sub:
762   case Mul: case Div:
763   case Rem:
764     assert(getType() == LHS->getType() &&
765            "Arithmetic operation should return same type as operands!");
766     assert((getType()->isInteger() ||
767             getType()->isFloatingPoint() ||
768             isa<PackedType>(getType()) ) &&
769           "Tried to create an arithmetic operation on a non-arithmetic type!");
770     break;
771   case And: case Or:
772   case Xor:
773     assert(getType() == LHS->getType() &&
774            "Logical operation should return same type as operands!");
775     assert(getType()->isIntegral() &&
776            "Tried to create a logical operation on a non-integral type!");
777     break;
778   case SetLT: case SetGT: case SetLE:
779   case SetGE: case SetEQ: case SetNE:
780     assert(getType() == Type::BoolTy && "Setcc must return bool!");
781   default:
782     break;
783   }
784 #endif
785 }
786
787 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
788                                        const std::string &Name,
789                                        Instruction *InsertBefore) {
790   assert(S1->getType() == S2->getType() &&
791          "Cannot create binary operator with two operands of differing type!");
792   switch (Op) {
793   // Binary comparison operators...
794   case SetLT: case SetGT: case SetLE:
795   case SetGE: case SetEQ: case SetNE:
796     return new SetCondInst(Op, S1, S2, Name, InsertBefore);
797
798   default:
799     return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
800   }
801 }
802
803 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
804                                        const std::string &Name,
805                                        BasicBlock *InsertAtEnd) {
806   BinaryOperator *Res = create(Op, S1, S2, Name);
807   InsertAtEnd->getInstList().push_back(Res);
808   return Res;
809 }
810
811 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
812                                           Instruction *InsertBefore) {
813   if (!Op->getType()->isFloatingPoint())
814     return new BinaryOperator(Instruction::Sub,
815                               Constant::getNullValue(Op->getType()), Op,
816                               Op->getType(), Name, InsertBefore);
817   else
818     return new BinaryOperator(Instruction::Sub,
819                               ConstantFP::get(Op->getType(), -0.0), Op,
820                               Op->getType(), Name, InsertBefore);
821 }
822
823 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
824                                           BasicBlock *InsertAtEnd) {
825   if (!Op->getType()->isFloatingPoint())
826     return new BinaryOperator(Instruction::Sub,
827                               Constant::getNullValue(Op->getType()), Op,
828                               Op->getType(), Name, InsertAtEnd);
829   else
830     return new BinaryOperator(Instruction::Sub,
831                               ConstantFP::get(Op->getType(), -0.0), Op,
832                               Op->getType(), Name, InsertAtEnd);
833 }
834
835 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
836                                           Instruction *InsertBefore) {
837   return new BinaryOperator(Instruction::Xor, Op,
838                             ConstantIntegral::getAllOnesValue(Op->getType()),
839                             Op->getType(), Name, InsertBefore);
840 }
841
842 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
843                                           BasicBlock *InsertAtEnd) {
844   return new BinaryOperator(Instruction::Xor, Op,
845                             ConstantIntegral::getAllOnesValue(Op->getType()),
846                             Op->getType(), Name, InsertAtEnd);
847 }
848
849
850 // isConstantAllOnes - Helper function for several functions below
851 static inline bool isConstantAllOnes(const Value *V) {
852   return isa<ConstantIntegral>(V) &&cast<ConstantIntegral>(V)->isAllOnesValue();
853 }
854
855 bool BinaryOperator::isNeg(const Value *V) {
856   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
857     if (Bop->getOpcode() == Instruction::Sub)
858       if (!V->getType()->isFloatingPoint())
859         return Bop->getOperand(0) == Constant::getNullValue(Bop->getType());
860       else
861         return Bop->getOperand(0) == ConstantFP::get(Bop->getType(), -0.0);
862   return false;
863 }
864
865 bool BinaryOperator::isNot(const Value *V) {
866   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
867     return (Bop->getOpcode() == Instruction::Xor &&
868             (isConstantAllOnes(Bop->getOperand(1)) ||
869              isConstantAllOnes(Bop->getOperand(0))));
870   return false;
871 }
872
873 Value *BinaryOperator::getNegArgument(Value *BinOp) {
874   assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
875   return cast<BinaryOperator>(BinOp)->getOperand(1);
876 }
877
878 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
879   return getNegArgument(const_cast<Value*>(BinOp));
880 }
881
882 Value *BinaryOperator::getNotArgument(Value *BinOp) {
883   assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
884   BinaryOperator *BO = cast<BinaryOperator>(BinOp);
885   Value *Op0 = BO->getOperand(0);
886   Value *Op1 = BO->getOperand(1);
887   if (isConstantAllOnes(Op0)) return Op1;
888
889   assert(isConstantAllOnes(Op1));
890   return Op0;
891 }
892
893 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
894   return getNotArgument(const_cast<Value*>(BinOp));
895 }
896
897
898 // swapOperands - Exchange the two operands to this instruction.  This
899 // instruction is safe to use on any binary instruction and does not
900 // modify the semantics of the instruction.  If the instruction is
901 // order dependent (SetLT f.e.) the opcode is changed.
902 //
903 bool BinaryOperator::swapOperands() {
904   if (isCommutative())
905     ;  // If the instruction is commutative, it is safe to swap the operands
906   else if (SetCondInst *SCI = dyn_cast<SetCondInst>(this))
907     /// FIXME: SetCC instructions shouldn't all have different opcodes.
908     setOpcode(SCI->getSwappedCondition());
909   else
910     return true;   // Can't commute operands
911
912   std::swap(Ops[0], Ops[1]);
913   return false;
914 }
915
916
917 //===----------------------------------------------------------------------===//
918 //                             SetCondInst Class
919 //===----------------------------------------------------------------------===//
920
921 SetCondInst::SetCondInst(BinaryOps Opcode, Value *S1, Value *S2,
922                          const std::string &Name, Instruction *InsertBefore)
923   : BinaryOperator(Opcode, S1, S2, Type::BoolTy, Name, InsertBefore) {
924
925   // Make sure it's a valid type... getInverseCondition will assert out if not.
926   assert(getInverseCondition(Opcode));
927 }
928
929 SetCondInst::SetCondInst(BinaryOps Opcode, Value *S1, Value *S2,
930                          const std::string &Name, BasicBlock *InsertAtEnd)
931   : BinaryOperator(Opcode, S1, S2, Type::BoolTy, Name, InsertAtEnd) {
932
933   // Make sure it's a valid type... getInverseCondition will assert out if not.
934   assert(getInverseCondition(Opcode));
935 }
936
937 // getInverseCondition - Return the inverse of the current condition opcode.
938 // For example seteq -> setne, setgt -> setle, setlt -> setge, etc...
939 //
940 Instruction::BinaryOps SetCondInst::getInverseCondition(BinaryOps Opcode) {
941   switch (Opcode) {
942   default:
943     assert(0 && "Unknown setcc opcode!");
944   case SetEQ: return SetNE;
945   case SetNE: return SetEQ;
946   case SetGT: return SetLE;
947   case SetLT: return SetGE;
948   case SetGE: return SetLT;
949   case SetLE: return SetGT;
950   }
951 }
952
953 // getSwappedCondition - Return the condition opcode that would be the result
954 // of exchanging the two operands of the setcc instruction without changing
955 // the result produced.  Thus, seteq->seteq, setle->setge, setlt->setgt, etc.
956 //
957 Instruction::BinaryOps SetCondInst::getSwappedCondition(BinaryOps Opcode) {
958   switch (Opcode) {
959   default: assert(0 && "Unknown setcc instruction!");
960   case SetEQ: case SetNE: return Opcode;
961   case SetGT: return SetLT;
962   case SetLT: return SetGT;
963   case SetGE: return SetLE;
964   case SetLE: return SetGE;
965   }
966 }
967
968 //===----------------------------------------------------------------------===//
969 //                        SwitchInst Implementation
970 //===----------------------------------------------------------------------===//
971
972 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
973   assert(Value && Default);
974   ReservedSpace = 2+NumCases*2;
975   NumOperands = 2;
976   OperandList = new Use[ReservedSpace];
977
978   OperandList[0].init(Value, this);
979   OperandList[1].init(Default, this);
980 }
981
982 SwitchInst::SwitchInst(const SwitchInst &SI)
983   : TerminatorInst(Instruction::Switch, new Use[SI.getNumOperands()],
984                    SI.getNumOperands()) {
985   Use *OL = OperandList, *InOL = SI.OperandList;
986   for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
987     OL[i].init(InOL[i], this);
988     OL[i+1].init(InOL[i+1], this);
989   }
990 }
991
992 SwitchInst::~SwitchInst() {
993   delete [] OperandList;
994 }
995
996
997 /// addCase - Add an entry to the switch instruction...
998 ///
999 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
1000   unsigned OpNo = NumOperands;
1001   if (OpNo+2 > ReservedSpace)
1002     resizeOperands(0);  // Get more space!
1003   // Initialize some new operands.
1004   assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
1005   NumOperands = OpNo+2;
1006   OperandList[OpNo].init(OnVal, this);
1007   OperandList[OpNo+1].init(Dest, this);
1008 }
1009
1010 /// removeCase - This method removes the specified successor from the switch
1011 /// instruction.  Note that this cannot be used to remove the default
1012 /// destination (successor #0).
1013 ///
1014 void SwitchInst::removeCase(unsigned idx) {
1015   assert(idx != 0 && "Cannot remove the default case!");
1016   assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
1017
1018   unsigned NumOps = getNumOperands();
1019   Use *OL = OperandList;
1020
1021   // Move everything after this operand down.
1022   //
1023   // FIXME: we could just swap with the end of the list, then erase.  However,
1024   // client might not expect this to happen.  The code as it is thrashes the
1025   // use/def lists, which is kinda lame.
1026   for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
1027     OL[i-2] = OL[i];
1028     OL[i-2+1] = OL[i+1];
1029   }
1030
1031   // Nuke the last value.
1032   OL[NumOps-2].set(0);
1033   OL[NumOps-2+1].set(0);
1034   NumOperands = NumOps-2;
1035 }
1036
1037 /// resizeOperands - resize operands - This adjusts the length of the operands
1038 /// list according to the following behavior:
1039 ///   1. If NumOps == 0, grow the operand list in response to a push_back style
1040 ///      of operation.  This grows the number of ops by 1.5 times.
1041 ///   2. If NumOps > NumOperands, reserve space for NumOps operands.
1042 ///   3. If NumOps == NumOperands, trim the reserved space.
1043 ///
1044 void SwitchInst::resizeOperands(unsigned NumOps) {
1045   if (NumOps == 0) {
1046     NumOps = getNumOperands()/2*6;
1047   } else if (NumOps*2 > NumOperands) {
1048     // No resize needed.
1049     if (ReservedSpace >= NumOps) return;
1050   } else if (NumOps == NumOperands) {
1051     if (ReservedSpace == NumOps) return;
1052   } else {
1053     return;
1054   }
1055
1056   ReservedSpace = NumOps;
1057   Use *NewOps = new Use[NumOps];
1058   Use *OldOps = OperandList;
1059   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1060       NewOps[i].init(OldOps[i], this);
1061       OldOps[i].set(0);
1062   }
1063   delete [] OldOps;
1064   OperandList = NewOps;
1065 }
1066
1067
1068 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
1069   return getSuccessor(idx);
1070 }
1071 unsigned SwitchInst::getNumSuccessorsV() const {
1072   return getNumSuccessors();
1073 }
1074 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
1075   setSuccessor(idx, B);
1076 }
1077
1078
1079 // Define these methods here so vtables don't get emitted into every translation
1080 // unit that uses these classes.
1081
1082 GetElementPtrInst *GetElementPtrInst::clone() const {
1083   return new GetElementPtrInst(*this);
1084 }
1085
1086 BinaryOperator *BinaryOperator::clone() const {
1087   return create(getOpcode(), Ops[0], Ops[1]);
1088 }
1089
1090 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
1091 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
1092 FreeInst   *FreeInst::clone()   const { return new FreeInst(getOperand(0)); }
1093 LoadInst   *LoadInst::clone()   const { return new LoadInst(*this); }
1094 StoreInst  *StoreInst::clone()  const { return new StoreInst(*this); }
1095 CastInst   *CastInst::clone()   const { return new CastInst(*this); }
1096 CallInst   *CallInst::clone()   const { return new CallInst(*this); }
1097 ShiftInst  *ShiftInst::clone()  const { return new ShiftInst(*this); }
1098 SelectInst *SelectInst::clone() const { return new SelectInst(*this); }
1099 VAArgInst  *VAArgInst::clone()  const { return new VAArgInst(*this); }
1100 PHINode    *PHINode::clone()    const { return new PHINode(*this); }
1101 ReturnInst *ReturnInst::clone() const { return new ReturnInst(*this); }
1102 BranchInst *BranchInst::clone() const { return new BranchInst(*this); }
1103 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
1104 InvokeInst *InvokeInst::clone() const { return new InvokeInst(*this); }
1105 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
1106 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}