Add support for new style casts
[oota-llvm.git] / lib / AsmParser / llvmAsmParser.y
1 //===-- llvmAsmParser.y - Parser for llvm assembly files ---------*- C++ -*--=//
2 //
3 //  This file implements the bison parser for LLVM assembly languages files.
4 //
5 //===------------------------------------------------------------------------=//
6
7 //
8 // TODO: Parse comments and add them to an internal node... so that they may
9 // be saved in the bytecode format as well as everything else.  Very important
10 // for a general IR format.
11 //
12
13 %{
14 #include "ParserInternals.h"
15 #include "llvm/Assembly/Parser.h"
16 #include "llvm/SymbolTable.h"
17 #include "llvm/Module.h"
18 #include "llvm/GlobalVariable.h"
19 #include "llvm/Method.h"
20 #include "llvm/BasicBlock.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/iTerminators.h"
23 #include "llvm/iMemory.h"
24 #include "llvm/Support/STLExtras.h"
25 #include "llvm/Support/DepthFirstIterator.h"
26 #include <list>
27 #include <utility>            // Get definition of pair class
28 #include <algorithm>
29 #include <stdio.h>            // This embarasment is due to our flex lexer...
30
31 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit 
32 int yylex();                       // declaration" of xxx warnings.
33 int yyparse();
34
35 static Module *ParserResult;
36 string CurFilename;
37
38 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
39 // relating to upreferences in the input stream.
40 //
41 //#define DEBUG_UPREFS 1
42 #ifdef DEBUG_UPREFS
43 #define UR_OUT(X) cerr << X
44 #else
45 #define UR_OUT(X)
46 #endif
47
48 // This contains info used when building the body of a method.  It is destroyed
49 // when the method is completed.
50 //
51 typedef vector<Value *> ValueList;           // Numbered defs
52 static void ResolveDefinitions(vector<ValueList> &LateResolvers);
53 static void ResolveTypes      (vector<PATypeHolder<Type> > &LateResolveTypes);
54
55 static struct PerModuleInfo {
56   Module *CurrentModule;
57   vector<ValueList>    Values;     // Module level numbered definitions
58   vector<ValueList>    LateResolveValues;
59   vector<PATypeHolder<Type> > Types, LateResolveTypes;
60
61   void ModuleDone() {
62     // If we could not resolve some methods at method compilation time (calls to
63     // methods before they are defined), resolve them now...  Types are resolved
64     // when the constant pool has been completely parsed.
65     //
66     ResolveDefinitions(LateResolveValues);
67
68     Values.clear();         // Clear out method local definitions
69     Types.clear();
70     CurrentModule = 0;
71   }
72 } CurModule;
73
74 static struct PerMethodInfo {
75   Method *CurrentMethod;         // Pointer to current method being created
76
77   vector<ValueList> Values;      // Keep track of numbered definitions
78   vector<ValueList> LateResolveValues;
79   vector<PATypeHolder<Type> > Types, LateResolveTypes;
80   bool isDeclare;                // Is this method a forward declararation?
81
82   inline PerMethodInfo() {
83     CurrentMethod = 0;
84     isDeclare = false;
85   }
86
87   inline ~PerMethodInfo() {}
88
89   inline void MethodStart(Method *M) {
90     CurrentMethod = M;
91   }
92
93   void MethodDone() {
94     // If we could not resolve some blocks at parsing time (forward branches)
95     // resolve the branches now...
96     ResolveDefinitions(LateResolveValues);
97
98     Values.clear();         // Clear out method local definitions
99     Types.clear();
100     CurrentMethod = 0;
101     isDeclare = false;
102   }
103 } CurMeth;  // Info for the current method...
104
105
106 //===----------------------------------------------------------------------===//
107 //               Code to handle definitions of all the types
108 //===----------------------------------------------------------------------===//
109
110 static void InsertValue(Value *D, vector<ValueList> &ValueTab = CurMeth.Values){
111   if (!D->hasName()) {             // Is this a numbered definition?
112     unsigned type = D->getType()->getUniqueID();
113     if (ValueTab.size() <= type)
114       ValueTab.resize(type+1, ValueList());
115     //printf("Values[%d][%d] = %d\n", type, ValueTab[type].size(), D);
116     ValueTab[type].push_back(D);
117   }
118 }
119
120 // TODO: FIXME when Type are not const
121 static void InsertType(const Type *Ty, vector<PATypeHolder<Type> > &Types) {
122   Types.push_back(Ty);
123 }
124
125 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
126   switch (D.Type) {
127   case 0: {                 // Is it a numbered definition?
128     unsigned Num = (unsigned)D.Num;
129
130     // Module constants occupy the lowest numbered slots...
131     if (Num < CurModule.Types.size()) 
132       return CurModule.Types[Num];
133
134     Num -= CurModule.Types.size();
135
136     // Check that the number is within bounds...
137     if (Num <= CurMeth.Types.size())
138       return CurMeth.Types[Num];
139   }
140   case 1: {                // Is it a named definition?
141     string Name(D.Name);
142     SymbolTable *SymTab = 0;
143     if (CurMeth.CurrentMethod) 
144       SymTab = CurMeth.CurrentMethod->getSymbolTable();
145     Value *N = SymTab ? SymTab->lookup(Type::TypeTy, Name) : 0;
146
147     if (N == 0) {
148       // Symbol table doesn't automatically chain yet... because the method
149       // hasn't been added to the module...
150       //
151       SymTab = CurModule.CurrentModule->getSymbolTable();
152       if (SymTab)
153         N = SymTab->lookup(Type::TypeTy, Name);
154       if (N == 0) break;
155     }
156
157     D.destroy();  // Free old strdup'd memory...
158     return N->castTypeAsserting();
159   }
160   default:
161     ThrowException("Invalid symbol type reference!");
162   }
163
164   // If we reached here, we referenced either a symbol that we don't know about
165   // or an id number that hasn't been read yet.  We may be referencing something
166   // forward, so just create an entry to be resolved later and get to it...
167   //
168   if (DoNotImprovise) return 0;  // Do we just want a null to be returned?
169
170   vector<PATypeHolder<Type> > *LateResolver = CurMeth.CurrentMethod ? 
171     &CurMeth.LateResolveTypes : &CurModule.LateResolveTypes;
172
173   Type *Typ = new TypePlaceHolder(Type::TypeTy, D);
174   InsertType(Typ, *LateResolver);
175   return Typ;
176 }
177
178 static Value *getVal(const Type *Ty, const ValID &D, 
179                      bool DoNotImprovise = false) {
180   assert(Ty != Type::TypeTy && "Should use getTypeVal for types!");
181
182   switch (D.Type) {
183   case ValID::NumberVal: {                 // Is it a numbered definition?
184     unsigned type = Ty->getUniqueID();
185     unsigned Num = (unsigned)D.Num;
186
187     // Module constants occupy the lowest numbered slots...
188     if (type < CurModule.Values.size()) {
189       if (Num < CurModule.Values[type].size()) 
190         return CurModule.Values[type][Num];
191
192       Num -= CurModule.Values[type].size();
193     }
194
195     // Make sure that our type is within bounds
196     if (CurMeth.Values.size() <= type)
197       break;
198
199     // Check that the number is within bounds...
200     if (CurMeth.Values[type].size() <= Num)
201       break;
202   
203     return CurMeth.Values[type][Num];
204   }
205   case ValID::NameVal: {                // Is it a named definition?
206     string Name(D.Name);
207     SymbolTable *SymTab = 0;
208     if (CurMeth.CurrentMethod) 
209       SymTab = CurMeth.CurrentMethod->getSymbolTable();
210     Value *N = SymTab ? SymTab->lookup(Ty, Name) : 0;
211
212     if (N == 0) {
213       // Symbol table doesn't automatically chain yet... because the method
214       // hasn't been added to the module...
215       //
216       SymTab = CurModule.CurrentModule->getSymbolTable();
217       if (SymTab)
218         N = SymTab->lookup(Ty, Name);
219       if (N == 0) break;
220     }
221
222     D.destroy();  // Free old strdup'd memory...
223     return N;
224   }
225
226   case ValID::ConstSIntVal:     // Is it a constant pool reference??
227   case ValID::ConstUIntVal:     // Is it an unsigned const pool reference?
228   case ValID::ConstStringVal:   // Is it a string const pool reference?
229   case ValID::ConstFPVal:       // Is it a floating point const pool reference?
230   case ValID::ConstNullVal: {   // Is it a null value?
231     ConstPoolVal *CPV = 0;
232
233     // Check to make sure that "Ty" is an integral type, and that our 
234     // value will fit into the specified type...
235     switch (D.Type) {
236     case ValID::ConstSIntVal:
237       if (Ty == Type::BoolTy) {  // Special handling for boolean data
238         CPV = ConstPoolBool::get(D.ConstPool64 != 0);
239       } else {
240         if (!ConstPoolSInt::isValueValidForType(Ty, D.ConstPool64))
241           ThrowException("Symbolic constant pool value '" +
242                          itostr(D.ConstPool64) + "' is invalid for type '" + 
243                          Ty->getName() + "'!");
244         CPV = ConstPoolSInt::get(Ty, D.ConstPool64);
245       }
246       break;
247     case ValID::ConstUIntVal:
248       if (!ConstPoolUInt::isValueValidForType(Ty, D.UConstPool64)) {
249         if (!ConstPoolSInt::isValueValidForType(Ty, D.ConstPool64)) {
250           ThrowException("Integral constant pool reference is invalid!");
251         } else {     // This is really a signed reference.  Transmogrify.
252           CPV = ConstPoolSInt::get(Ty, D.ConstPool64);
253         }
254       } else {
255         CPV = ConstPoolUInt::get(Ty, D.UConstPool64);
256       }
257       break;
258     case ValID::ConstStringVal:
259       cerr << "FIXME: TODO: String constants [sbyte] not implemented yet!\n";
260       abort();
261       break;
262     case ValID::ConstFPVal:
263       if (!ConstPoolFP::isValueValidForType(Ty, D.ConstPoolFP))
264         ThrowException("FP constant invalid for type!!");
265       CPV = ConstPoolFP::get(Ty, D.ConstPoolFP);
266       break;
267     case ValID::ConstNullVal:
268       if (!Ty->isPointerType())
269         ThrowException("Cannot create a a non pointer null!");
270       CPV = ConstPoolPointer::getNullPointer(Ty->castPointerType());
271       break;
272     default:
273       assert(0 && "Unhandled case!");
274     }
275     assert(CPV && "How did we escape creating a constant??");
276     return CPV;
277   }   // End of case 2,3,4
278   default:
279     assert(0 && "Unhandled case!");
280   }   // End of switch
281
282
283   // If we reached here, we referenced either a symbol that we don't know about
284   // or an id number that hasn't been read yet.  We may be referencing something
285   // forward, so just create an entry to be resolved later and get to it...
286   //
287   if (DoNotImprovise) return 0;  // Do we just want a null to be returned?
288
289   Value *d = 0;
290   vector<ValueList> *LateResolver =  (CurMeth.CurrentMethod) ? 
291     &CurMeth.LateResolveValues : &CurModule.LateResolveValues;
292
293   switch (Ty->getPrimitiveID()) {
294   case Type::LabelTyID:  d = new   BBPlaceHolder(Ty, D); break;
295   case Type::MethodTyID: d = new MethPlaceHolder(Ty, D); 
296                          LateResolver = &CurModule.LateResolveValues; break;
297   default:               d = new ValuePlaceHolder(Ty, D); break;
298   }
299
300   assert(d != 0 && "How did we not make something?");
301   InsertValue(d, *LateResolver);
302   return d;
303 }
304
305
306 //===----------------------------------------------------------------------===//
307 //              Code to handle forward references in instructions
308 //===----------------------------------------------------------------------===//
309 //
310 // This code handles the late binding needed with statements that reference
311 // values not defined yet... for example, a forward branch, or the PHI node for
312 // a loop body.
313 //
314 // This keeps a table (CurMeth.LateResolveValues) of all such forward references
315 // and back patchs after we are done.
316 //
317
318 // ResolveDefinitions - If we could not resolve some defs at parsing 
319 // time (forward branches, phi functions for loops, etc...) resolve the 
320 // defs now...
321 //
322 static void ResolveDefinitions(vector<ValueList> &LateResolvers) {
323   // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
324   for (unsigned ty = 0; ty < LateResolvers.size(); ty++) {
325     while (!LateResolvers[ty].empty()) {
326       Value *V = LateResolvers[ty].back();
327       LateResolvers[ty].pop_back();
328       ValID &DID = getValIDFromPlaceHolder(V);
329
330       Value *TheRealValue = getVal(Type::getUniqueIDType(ty), DID, true);
331
332       if (TheRealValue == 0) {
333         if (DID.Type == 1)
334           ThrowException("Reference to an invalid definition: '" +DID.getName()+
335                          "' of type '" + V->getType()->getDescription() + "'",
336                          getLineNumFromPlaceHolder(V));
337         else
338           ThrowException("Reference to an invalid definition: #" +
339                          itostr(DID.Num) + " of type '" + 
340                          V->getType()->getDescription() + "'",
341                          getLineNumFromPlaceHolder(V));
342       }
343
344       assert(!V->isType() && "Types should be in LateResolveTypes!");
345
346       V->replaceAllUsesWith(TheRealValue);
347       delete V;
348     }
349   }
350
351   LateResolvers.clear();
352 }
353
354
355 // ResolveTypes - This goes through the forward referenced type table and makes
356 // sure that all type references are complete.  This code is executed after the
357 // constant pool of a method or module is completely parsed.
358 //
359 static void ResolveTypes(vector<PATypeHolder<Type> > &LateResolveTypes) {
360   while (!LateResolveTypes.empty()) {
361     const Type *Ty = LateResolveTypes.back();
362     ValID &DID = getValIDFromPlaceHolder(Ty);
363
364     const Type *TheRealType = getTypeVal(DID, true);
365     if (TheRealType == 0) {
366       if (DID.Type == 1)
367         ThrowException("Reference to an invalid type: '" +DID.getName(),
368                        getLineNumFromPlaceHolder(Ty));
369       else
370         ThrowException("Reference to an invalid type: #" + itostr(DID.Num),
371                        getLineNumFromPlaceHolder(Ty));
372     }
373
374     // FIXME: When types are not const
375     DerivedType *DTy = const_cast<DerivedType*>(Ty->castDerivedTypeAsserting());
376     
377     // Refine the opaque type we had to the new type we are getting.
378     DTy->refineAbstractTypeTo(TheRealType);
379
380     // No need to delete type, refine does that for us.
381     LateResolveTypes.pop_back();
382   }
383 }
384
385 // setValueName - Set the specified value to the name given.  The name may be
386 // null potentially, in which case this is a noop.  The string passed in is
387 // assumed to be a malloc'd string buffer, and is freed by this function.
388 //
389 static void setValueName(Value *V, char *NameStr) {
390   if (NameStr == 0) return;
391   string Name(NameStr);           // Copy string
392   free(NameStr);                  // Free old string
393
394   SymbolTable *ST = CurMeth.CurrentMethod ? 
395     CurMeth.CurrentMethod->getSymbolTableSure() : 
396     CurModule.CurrentModule->getSymbolTableSure();
397
398   Value *Existing = ST->lookup(V->getType(), Name);
399   if (Existing) {    // Inserting a name that is already defined???
400     // There is only one case where this is allowed: when we are refining an
401     // opaque type.  In this case, Existing will be an opaque type.
402     if (const Type *Ty = Existing->castType())
403       if (Ty->isOpaqueType()) {
404         // We ARE replacing an opaque type!
405
406         // TODO: FIXME when types are not const!
407         const_cast<DerivedType*>(Ty->castDerivedTypeAsserting())->refineAbstractTypeTo(V->castTypeAsserting());
408         return;
409       }
410
411     // Otherwise, we are a simple redefinition of a value, check to see if it
412     // is defined the same as the old one...
413     if (const Type *Ty = dyn_cast<const Type>(Existing)) {
414       if (Ty == cast<const Type>(V)) return;  // Yes, it's equal.
415     } else {
416
417     }
418     ThrowException("Redefinition of value name '" + Name + "' in the '" +
419                    V->getType()->getDescription() + "' type plane!");
420   }
421
422   V->setName(Name, ST);
423 }
424
425
426 //===----------------------------------------------------------------------===//
427 // Code for handling upreferences in type names...
428 //
429
430 // TypeContains - Returns true if Ty contains E in it.
431 //
432 static bool TypeContains(const Type *Ty, const Type *E) {
433   return find(df_begin(Ty), df_end(Ty), E) != df_end(Ty);
434 }
435
436
437 static vector<pair<unsigned, OpaqueType *> > UpRefs;
438
439 static PATypeHolder<Type> HandleUpRefs(const Type *ty) {
440   PATypeHolder<Type> Ty(ty);
441   UR_OUT(UpRefs.size() << " upreferences active!\n");
442   for (unsigned i = 0; i < UpRefs.size(); ) {
443     UR_OUT("TypeContains(" << Ty->getDescription() << ", " 
444            << UpRefs[i].second->getDescription() << ") = " 
445            << TypeContains(Ty, UpRefs[i].second) << endl);
446     if (TypeContains(Ty, UpRefs[i].second)) {
447       unsigned Level = --UpRefs[i].first;   // Decrement level of upreference
448       UR_OUT("Uplevel Ref Level = " << Level << endl);
449       if (Level == 0) {                     // Upreference should be resolved! 
450         UR_OUT("About to resolve upreference!\n";
451                string OldName = UpRefs[i].second->getDescription());
452         UpRefs[i].second->refineAbstractTypeTo(Ty);
453         UpRefs.erase(UpRefs.begin()+i);     // Remove from upreference list...
454         UR_OUT("Type '" << OldName << "' refined upreference to: "
455                << (const void*)Ty << ", " << Ty->getDescription() << endl);
456         continue;
457       }
458     }
459
460     ++i;                                  // Otherwise, no resolve, move on...
461   }
462   // FIXME: TODO: this should return the updated type
463   return Ty;
464 }
465
466 template <class TypeTy>
467 inline static void TypeDone(PATypeHolder<TypeTy> *Ty) {
468   if (UpRefs.size())
469     ThrowException("Invalid upreference in type: " + (*Ty)->getDescription());
470 }
471
472 // newTH - Allocate a new type holder for the specified type
473 template <class TypeTy>
474 inline static PATypeHolder<TypeTy> *newTH(const TypeTy *Ty) {
475   return new PATypeHolder<TypeTy>(Ty);
476 }
477 template <class TypeTy>
478 inline static PATypeHolder<TypeTy> *newTH(const PATypeHolder<TypeTy> &TH) {
479   return new PATypeHolder<TypeTy>(TH);
480 }
481
482
483 // newTHC - Allocate a new type holder for the specified type that can be
484 // casted to a new Type type.
485 template <class TypeTy, class OldTy>
486 inline static PATypeHolder<TypeTy> *newTHC(const PATypeHolder<OldTy> &Old) {
487   return new PATypeHolder<TypeTy>((const TypeTy*)Old.get());
488 }
489
490
491 //===----------------------------------------------------------------------===//
492 //            RunVMAsmParser - Define an interface to this parser
493 //===----------------------------------------------------------------------===//
494 //
495 Module *RunVMAsmParser(const string &Filename, FILE *F) {
496   llvmAsmin = F;
497   CurFilename = Filename;
498   llvmAsmlineno = 1;      // Reset the current line number...
499
500   CurModule.CurrentModule = new Module();  // Allocate a new module to read
501   yyparse();       // Parse the file.
502   Module *Result = ParserResult;
503   llvmAsmin = stdin;    // F is about to go away, don't use it anymore...
504   ParserResult = 0;
505
506   return Result;
507 }
508
509 %}
510
511 %union {
512   Module                           *ModuleVal;
513   Method                           *MethodVal;
514   MethodArgument                   *MethArgVal;
515   BasicBlock                       *BasicBlockVal;
516   TerminatorInst                   *TermInstVal;
517   Instruction                      *InstVal;
518   ConstPoolVal                     *ConstVal;
519
520   const Type                       *PrimType;
521   PATypeHolder<Type>               *TypeVal;
522   PATypeHolder<ArrayType>          *ArrayTypeTy;
523   PATypeHolder<StructType>         *StructTypeTy;
524   PATypeHolder<PointerType>        *PointerTypeTy;
525   Value                            *ValueVal;
526
527   list<MethodArgument*>            *MethodArgList;
528   list<Value*>                     *ValueList;
529   list<PATypeHolder<Type> >        *TypeList;
530   list<pair<Value*, BasicBlock*> > *PHIList;   // Represent the RHS of PHI node
531   list<pair<ConstPoolVal*, BasicBlock*> > *JumpTable;
532   vector<ConstPoolVal*>            *ConstVector;
533
534   int64_t                           SInt64Val;
535   uint64_t                          UInt64Val;
536   int                               SIntVal;
537   unsigned                          UIntVal;
538   double                            FPVal;
539   bool                              BoolVal;
540
541   char                             *StrVal;   // This memory is strdup'd!
542   ValID                             ValIDVal; // strdup'd memory maybe!
543
544   Instruction::UnaryOps             UnaryOpVal;
545   Instruction::BinaryOps            BinaryOpVal;
546   Instruction::TermOps              TermOpVal;
547   Instruction::MemoryOps            MemOpVal;
548   Instruction::OtherOps             OtherOpVal;
549 }
550
551 %type <ModuleVal>     Module MethodList
552 %type <MethodVal>     Method MethodProto MethodHeader BasicBlockList
553 %type <BasicBlockVal> BasicBlock InstructionList
554 %type <TermInstVal>   BBTerminatorInst
555 %type <InstVal>       Inst InstVal MemoryInst
556 %type <ConstVal>      ConstVal ExtendedConstVal
557 %type <ConstVector>   ConstVector UByteList
558 %type <MethodArgList> ArgList ArgListH
559 %type <MethArgVal>    ArgVal
560 %type <PHIList>       PHIList
561 %type <ValueList>     ValueRefList ValueRefListE  // For call param lists
562 %type <TypeList>      TypeListI ArgTypeListI
563 %type <JumpTable>     JumpTable
564 %type <BoolVal>       GlobalType                  // GLOBAL or CONSTANT?
565
566 %type <ValIDVal>      ValueRef ConstValueRef // Reference to a definition or BB
567 %type <ValueVal>      ResolvedVal            // <type> <valref> pair
568 // Tokens and types for handling constant integer values
569 //
570 // ESINT64VAL - A negative number within long long range
571 %token <SInt64Val> ESINT64VAL
572
573 // EUINT64VAL - A positive number within uns. long long range
574 %token <UInt64Val> EUINT64VAL
575 %type  <SInt64Val> EINT64VAL
576
577 %token  <SIntVal>   SINTVAL   // Signed 32 bit ints...
578 %token  <UIntVal>   UINTVAL   // Unsigned 32 bit ints...
579 %type   <SIntVal>   INTVAL
580 %token  <FPVal>     FPVAL     // Float or Double constant
581
582 // Built in types...
583 %type  <TypeVal> Types TypesV UpRTypes UpRTypesV
584 %type  <PrimType> SIntType UIntType IntType FPType PrimType   // Classifications
585 %token <TypeVal>  OPAQUE
586 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
587 %token <PrimType> FLOAT DOUBLE TYPE LABEL
588 %type  <ArrayTypeTy> ArrayType ArrayTypeI
589 %type  <StructTypeTy> StructType StructTypeI
590 %type  <PointerTypeTy> PointerType PointerTypeI
591
592 %token <StrVal>     VAR_ID LABELSTR STRINGCONSTANT
593 %type  <StrVal>  OptVAR_ID OptAssign
594
595
596 %token IMPLEMENTATION TRUE FALSE BEGINTOK END DECLARE GLOBAL CONSTANT UNINIT
597 %token TO DOTDOTDOT STRING NULL_TOK
598
599 // Basic Block Terminating Operators 
600 %token <TermOpVal> RET BR SWITCH
601
602 // Unary Operators 
603 %type  <UnaryOpVal> UnaryOps  // all the unary operators
604 %token <UnaryOpVal> NOT
605
606 // Binary Operators 
607 %type  <BinaryOpVal> BinaryOps  // all the binary operators
608 %token <BinaryOpVal> ADD SUB MUL DIV REM
609 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE  // Binary Comarators
610
611 // Memory Instructions
612 %token <MemoryOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
613
614 // Other Operators
615 %type  <OtherOpVal> ShiftOps
616 %token <OtherOpVal> PHI CALL CAST SHL SHR
617
618 %start Module
619 %%
620
621 // Handle constant integer size restriction and conversion...
622 //
623
624 INTVAL : SINTVAL
625 INTVAL : UINTVAL {
626   if ($1 > (uint32_t)INT32_MAX)     // Outside of my range!
627     ThrowException("Value too large for type!");
628   $$ = (int32_t)$1;
629 }
630
631
632 EINT64VAL : ESINT64VAL       // These have same type and can't cause problems...
633 EINT64VAL : EUINT64VAL {
634   if ($1 > (uint64_t)INT64_MAX)     // Outside of my range!
635     ThrowException("Value too large for type!");
636   $$ = (int64_t)$1;
637 }
638
639 // Operations that are notably excluded from this list include: 
640 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
641 //
642 UnaryOps  : NOT
643 BinaryOps : ADD | SUB | MUL | DIV | REM
644 BinaryOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
645 ShiftOps  : SHL | SHR
646
647 // These are some types that allow classification if we only want a particular 
648 // thing... for example, only a signed, unsigned, or integral type.
649 SIntType :  LONG |  INT |  SHORT | SBYTE
650 UIntType : ULONG | UINT | USHORT | UBYTE
651 IntType  : SIntType | UIntType
652 FPType   : FLOAT | DOUBLE
653
654 // OptAssign - Value producing statements have an optional assignment component
655 OptAssign : VAR_ID '=' {
656     $$ = $1;
657   }
658   | /*empty*/ { 
659     $$ = 0; 
660   }
661
662
663 //===----------------------------------------------------------------------===//
664 // Types includes all predefined types... except void, because it can only be
665 // used in specific contexts (method returning void for example).  To have
666 // access to it, a user must explicitly use TypesV.
667 //
668
669 // TypesV includes all of 'Types', but it also includes the void type.
670 TypesV    : Types    | VOID { $$ = newTH($1); }
671 UpRTypesV : UpRTypes | VOID { $$ = newTH($1); }
672
673 Types     : UpRTypes {
674     TypeDone($$ = $1);
675   }
676
677
678 // Derived types are added later...
679 //
680 PrimType : BOOL | SBYTE | UBYTE | SHORT  | USHORT | INT   | UINT 
681 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE   | LABEL
682 UpRTypes : OPAQUE | PrimType { $$ = newTH($1); }
683 UpRTypes : ValueRef {                    // Named types are also simple types...
684   $$ = newTH(getTypeVal($1));
685 }
686
687 // ArrayTypeI - Internal version of ArrayType that can have incomplete uprefs
688 //
689 ArrayTypeI : '[' UpRTypesV ']' {               // Unsized array type?
690     $$ = newTHC<ArrayType>(HandleUpRefs(ArrayType::get(*$2)));
691     delete $2;
692   }
693   | '[' EUINT64VAL 'x' UpRTypes ']' {          // Sized array type?
694     $$ = newTHC<ArrayType>(HandleUpRefs(ArrayType::get(*$4, (int)$2)));
695     delete $4;
696   }
697
698 StructTypeI : '{' TypeListI '}' {              // Structure type?
699     vector<const Type*> Elements;
700     mapto($2->begin(), $2->end(), back_inserter(Elements), 
701         mem_fun_ref(&PATypeHandle<Type>::get));
702
703     $$ = newTHC<StructType>(HandleUpRefs(StructType::get(Elements)));
704     delete $2;
705   }
706   | '{' '}' {                                  // Empty structure type?
707     $$ = newTH(StructType::get(vector<const Type*>()));
708   }
709
710 PointerTypeI : UpRTypes '*' {                             // Pointer type?
711     $$ = newTHC<PointerType>(HandleUpRefs(PointerType::get(*$1)));
712     delete $1;  // Delete the type handle
713   }
714
715 // Include derived types in the Types production.
716 //
717 UpRTypes : '\\' EUINT64VAL {                   // Type UpReference
718     if ($2 > (uint64_t)INT64_MAX) ThrowException("Value out of range!");
719     OpaqueType *OT = OpaqueType::get();        // Use temporary placeholder
720     UpRefs.push_back(make_pair((unsigned)$2, OT));  // Add to vector...
721     $$ = newTH<Type>(OT);
722     UR_OUT("New Upreference!\n");
723   }
724   | UpRTypesV '(' ArgTypeListI ')' {           // Method derived type?
725     vector<const Type*> Params;
726     mapto($3->begin(), $3->end(), back_inserter(Params), 
727           mem_fun_ref(&PATypeHandle<Type>::get));
728     $$ = newTH(HandleUpRefs(MethodType::get(*$1, Params)));
729     delete $3;      // Delete the argument list
730     delete $1;      // Delete the old type handle
731   }
732   | ArrayTypeI {                               // [Un]sized array type?
733     $$ = newTHC<Type>(*$1); delete $1;
734   }
735   | StructTypeI {                              // Structure type?
736     $$ = newTHC<Type>(*$1); delete $1;
737   }
738   | PointerTypeI {                             // Pointer type?
739     $$ = newTHC<Type>(*$1); delete $1;
740   }
741
742 // Define some helpful top level types that do not allow UpReferences to escape
743 //
744 ArrayType   : ArrayTypeI   { TypeDone($$ = $1); }
745 StructType  : StructTypeI  { TypeDone($$ = $1); }
746 PointerType : PointerTypeI { TypeDone($$ = $1); }
747
748
749 // TypeList - Used for struct declarations and as a basis for method type 
750 // declaration type lists
751 //
752 TypeListI : UpRTypes {
753     $$ = new list<PATypeHolder<Type> >();
754     $$->push_back(*$1); delete $1;
755   }
756   | TypeListI ',' UpRTypes {
757     ($$=$1)->push_back(*$3); delete $3;
758   }
759
760 // ArgTypeList - List of types for a method type declaration...
761 ArgTypeListI : TypeListI
762   | TypeListI ',' DOTDOTDOT {
763     ($$=$1)->push_back(Type::VoidTy);
764   }
765   | DOTDOTDOT {
766     ($$ = new list<PATypeHolder<Type> >())->push_back(Type::VoidTy);
767   }
768   | /*empty*/ {
769     $$ = new list<PATypeHolder<Type> >();
770   }
771
772
773 // ConstVal - The various declarations that go into the constant pool.  This
774 // includes all forward declarations of types, constants, and functions.
775 //
776 // This is broken into two sections: ExtendedConstVal and ConstVal
777 //
778 ExtendedConstVal: ArrayType '[' ConstVector ']' { // Nonempty unsized arr
779     const ArrayType *ATy = *$1;
780     const Type *ETy = ATy->getElementType();
781     int NumElements = ATy->getNumElements();
782
783     // Verify that we have the correct size...
784     if (NumElements != -1 && NumElements != (int)$3->size())
785       ThrowException("Type mismatch: constant sized array initialized with " +
786                      utostr($3->size()) +  " arguments, but has size of " + 
787                      itostr(NumElements) + "!");
788
789     // Verify all elements are correct type!
790     for (unsigned i = 0; i < $3->size(); i++) {
791       if (ETy != (*$3)[i]->getType())
792         ThrowException("Element #" + utostr(i) + " is not of type '" + 
793                        ETy->getName() + "' as required!\nIt is of type '" +
794                        (*$3)[i]->getType()->getName() + "'.");
795     }
796
797     $$ = ConstPoolArray::get(ATy, *$3);
798     delete $1; delete $3;
799   }
800   | ArrayType '[' ']' {
801     int NumElements = (*$1)->getNumElements();
802     if (NumElements != -1 && NumElements != 0) 
803       ThrowException("Type mismatch: constant sized array initialized with 0"
804                      " arguments, but has size of " + itostr(NumElements) +"!");
805     $$ = ConstPoolArray::get((*$1), vector<ConstPoolVal*>());
806     delete $1;
807   }
808   | ArrayType 'c' STRINGCONSTANT {
809     const ArrayType *ATy = *$1;
810     int NumElements = ATy->getNumElements();
811     const Type *ETy = ATy->getElementType();
812     char *EndStr = UnEscapeLexed($3, true);
813     if (NumElements != -1 && NumElements != (EndStr-$3))
814       ThrowException("Can't build string constant of size " + 
815                      itostr((int)(EndStr-$3)) +
816                      " when array has size " + itostr(NumElements) + "!");
817     vector<ConstPoolVal*> Vals;
818     if (ETy == Type::SByteTy) {
819       for (char *C = $3; C != EndStr; ++C)
820         Vals.push_back(ConstPoolSInt::get(ETy, *C));
821     } else if (ETy == Type::UByteTy) {
822       for (char *C = $3; C != EndStr; ++C)
823         Vals.push_back(ConstPoolUInt::get(ETy, *C));
824     } else {
825       free($3);
826       ThrowException("Cannot build string arrays of non byte sized elements!");
827     }
828     free($3);
829     $$ = ConstPoolArray::get(ATy, Vals);
830     delete $1;
831   }
832   | StructType '{' ConstVector '}' {
833     // FIXME: TODO: Check to see that the constants are compatible with the type
834     // initializer!
835     $$ = ConstPoolStruct::get(*$1, *$3);
836     delete $1; delete $3;
837   }
838 /*
839   | Types '*' ConstVal {
840     assert(0);
841     $$ = 0;
842   }
843 */
844
845 ConstVal : ExtendedConstVal {
846     $$ = $1;
847   }
848   | SIntType EINT64VAL {     // integral constants
849     if (!ConstPoolSInt::isValueValidForType($1, $2))
850       ThrowException("Constant value doesn't fit in type!");
851     $$ = ConstPoolSInt::get($1, $2);
852   } 
853   | UIntType EUINT64VAL {           // integral constants
854     if (!ConstPoolUInt::isValueValidForType($1, $2))
855       ThrowException("Constant value doesn't fit in type!");
856     $$ = ConstPoolUInt::get($1, $2);
857   } 
858   | BOOL TRUE {                     // Boolean constants
859     $$ = ConstPoolBool::True;
860   }
861   | BOOL FALSE {                    // Boolean constants
862     $$ = ConstPoolBool::False;
863   }
864   | FPType FPVAL {                   // Float & Double constants
865     $$ = ConstPoolFP::get($1, $2);
866   }
867
868 // ConstVector - A list of comma seperated constants.
869 ConstVector : ConstVector ',' ConstVal {
870     ($$ = $1)->push_back($3);
871   }
872   | ConstVal {
873     $$ = new vector<ConstPoolVal*>();
874     $$->push_back($1);
875   }
876
877
878 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
879 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; }
880
881
882 // ConstPool - Constants with optional names assigned to them.
883 ConstPool : ConstPool OptAssign ConstVal { 
884     setValueName($3, $2);
885     InsertValue($3);
886   }
887   | ConstPool OptAssign TYPE TypesV {  // Types can be defined in the const pool
888     // TODO: FIXME when Type are not const
889     setValueName(const_cast<Type*>($4->get()), $2);
890
891     if (!$2) {
892       InsertType($4->get(),
893                  CurMeth.CurrentMethod ? CurMeth.Types : CurModule.Types);
894     }
895     delete $4;
896   }
897   | ConstPool MethodProto {            // Method prototypes can be in const pool
898   }
899   | ConstPool OptAssign GlobalType ResolvedVal {
900     const Type *Ty = $4->getType();
901     // Global declarations appear in Constant Pool
902     ConstPoolVal *Initializer = $4->castConstant();
903     if (Initializer == 0)
904       ThrowException("Global value initializer is not a constant!");
905          
906     GlobalVariable *GV = new GlobalVariable(PointerType::get(Ty), $3,
907                                             Initializer);
908     setValueName(GV, $2);
909
910     CurModule.CurrentModule->getGlobalList().push_back(GV);
911     InsertValue(GV, CurModule.Values);
912   }
913   | ConstPool OptAssign UNINIT GlobalType Types {
914     const Type *Ty = *$5;
915     // Global declarations appear in Constant Pool
916     if (Ty->isArrayType() && Ty->castArrayType()->isUnsized()) {
917       ThrowException("Type '" + Ty->getDescription() +
918                      "' is not a sized type!");
919     }
920
921     GlobalVariable *GV = new GlobalVariable(PointerType::get(Ty), $4);
922     setValueName(GV, $2);
923
924     CurModule.CurrentModule->getGlobalList().push_back(GV);
925     InsertValue(GV, CurModule.Values);
926   }
927   | /* empty: end of list */ { 
928   }
929
930
931 //===----------------------------------------------------------------------===//
932 //                             Rules to match Modules
933 //===----------------------------------------------------------------------===//
934
935 // Module rule: Capture the result of parsing the whole file into a result
936 // variable...
937 //
938 Module : MethodList {
939   $$ = ParserResult = $1;
940   CurModule.ModuleDone();
941 }
942
943 // MethodList - A list of methods, preceeded by a constant pool.
944 //
945 MethodList : MethodList Method {
946     $$ = $1;
947     if (!$2->getParent())
948       $1->getMethodList().push_back($2);
949     CurMeth.MethodDone();
950   } 
951   | MethodList MethodProto {
952     $$ = $1;
953   }
954   | ConstPool IMPLEMENTATION {
955     $$ = CurModule.CurrentModule;
956     // Resolve circular types before we parse the body of the module
957     ResolveTypes(CurModule.LateResolveTypes);
958   }
959
960
961 //===----------------------------------------------------------------------===//
962 //                       Rules to match Method Headers
963 //===----------------------------------------------------------------------===//
964
965 OptVAR_ID : VAR_ID | /*empty*/ { $$ = 0; }
966
967 ArgVal : Types OptVAR_ID {
968   $$ = new MethodArgument(*$1); delete $1;
969   setValueName($$, $2);
970 }
971
972 ArgListH : ArgVal ',' ArgListH {
973     $$ = $3;
974     $3->push_front($1);
975   }
976   | ArgVal {
977     $$ = new list<MethodArgument*>();
978     $$->push_front($1);
979   }
980   | DOTDOTDOT {
981     $$ = new list<MethodArgument*>();
982     $$->push_back(new MethodArgument(Type::VoidTy));
983   }
984
985 ArgList : ArgListH {
986     $$ = $1;
987   }
988   | /* empty */ {
989     $$ = 0;
990   }
991
992 MethodHeaderH : TypesV STRINGCONSTANT '(' ArgList ')' {
993   UnEscapeLexed($2);
994   vector<const Type*> ParamTypeList;
995   if ($4)
996     for (list<MethodArgument*>::iterator I = $4->begin(); I != $4->end(); ++I)
997       ParamTypeList.push_back((*I)->getType());
998
999   const MethodType *MT = MethodType::get(*$1, ParamTypeList);
1000   delete $1;
1001
1002   Method *M = 0;
1003   if (SymbolTable *ST = CurModule.CurrentModule->getSymbolTable()) {
1004     if (Value *V = ST->lookup(MT, $2)) {  // Method already in symtab?
1005       M =  cast<Method>(V);
1006
1007       // Yes it is.  If this is the case, either we need to be a forward decl,
1008       // or it needs to be.
1009       if (!CurMeth.isDeclare && !M->isExternal())
1010         ThrowException("Redefinition of method '" + string($2) + "'!");      
1011     }
1012   }
1013
1014   if (M == 0) {  // Not already defined?
1015     M = new Method(MT, $2);
1016     InsertValue(M, CurModule.Values);
1017   }
1018
1019   free($2);  // Free strdup'd memory!
1020
1021   CurMeth.MethodStart(M);
1022
1023   // Add all of the arguments we parsed to the method...
1024   if ($4 && !CurMeth.isDeclare) {        // Is null if empty...
1025     Method::ArgumentListType &ArgList = M->getArgumentList();
1026
1027     for (list<MethodArgument*>::iterator I = $4->begin(); I != $4->end(); ++I) {
1028       InsertValue(*I);
1029       ArgList.push_back(*I);
1030     }
1031     delete $4;                     // We're now done with the argument list
1032   }
1033 }
1034
1035 MethodHeader : MethodHeaderH ConstPool BEGINTOK {
1036   $$ = CurMeth.CurrentMethod;
1037
1038   // Resolve circular types before we parse the body of the method.
1039   ResolveTypes(CurMeth.LateResolveTypes);
1040 }
1041
1042 Method : BasicBlockList END {
1043   $$ = $1;
1044 }
1045
1046 MethodProto : DECLARE { CurMeth.isDeclare = true; } MethodHeaderH {
1047   $$ = CurMeth.CurrentMethod;
1048   if (!$$->getParent())
1049     CurModule.CurrentModule->getMethodList().push_back($$);
1050   CurMeth.MethodDone();
1051 }
1052
1053 //===----------------------------------------------------------------------===//
1054 //                        Rules to match Basic Blocks
1055 //===----------------------------------------------------------------------===//
1056
1057 ConstValueRef : ESINT64VAL {    // A reference to a direct constant
1058     $$ = ValID::create($1);
1059   }
1060   | EUINT64VAL {
1061     $$ = ValID::create($1);
1062   }
1063   | FPVAL {                     // Perhaps it's an FP constant?
1064     $$ = ValID::create($1);
1065   }
1066   | TRUE {
1067     $$ = ValID::create((int64_t)1);
1068   } 
1069   | FALSE {
1070     $$ = ValID::create((int64_t)0);
1071   }
1072   | NULL_TOK {
1073     $$ = ValID::createNull();
1074   }
1075
1076 /*
1077   | STRINGCONSTANT {        // Quoted strings work too... especially for methods
1078     $$ = ValID::create_conststr($1);
1079   }
1080 */
1081
1082 // ValueRef - A reference to a definition... 
1083 ValueRef : INTVAL {           // Is it an integer reference...?
1084     $$ = ValID::create($1);
1085   }
1086   | VAR_ID {                 // Is it a named reference...?
1087     $$ = ValID::create($1);
1088   }
1089   | ConstValueRef {
1090     $$ = $1;
1091   }
1092
1093 // ResolvedVal - a <type> <value> pair.  This is used only in cases where the
1094 // type immediately preceeds the value reference, and allows complex constant
1095 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1096 ResolvedVal : ExtendedConstVal {
1097     $$ = $1;
1098   }
1099   | Types ValueRef {
1100     $$ = getVal(*$1, $2); delete $1;
1101   }
1102
1103
1104 BasicBlockList : BasicBlockList BasicBlock {
1105     $1->getBasicBlocks().push_back($2);
1106     $$ = $1;
1107   }
1108   | MethodHeader BasicBlock { // Do not allow methods with 0 basic blocks   
1109     $$ = $1;                  // in them...
1110     $1->getBasicBlocks().push_back($2);
1111   }
1112
1113
1114 // Basic blocks are terminated by branching instructions: 
1115 // br, br/cc, switch, ret
1116 //
1117 BasicBlock : InstructionList BBTerminatorInst  {
1118     $1->getInstList().push_back($2);
1119     InsertValue($1);
1120     $$ = $1;
1121   }
1122   | LABELSTR InstructionList BBTerminatorInst  {
1123     $2->getInstList().push_back($3);
1124     setValueName($2, $1);
1125
1126     InsertValue($2);
1127     $$ = $2;
1128   }
1129
1130 InstructionList : InstructionList Inst {
1131     $1->getInstList().push_back($2);
1132     $$ = $1;
1133   }
1134   | /* empty */ {
1135     $$ = new BasicBlock();
1136   }
1137
1138 BBTerminatorInst : RET ResolvedVal {              // Return with a result...
1139     $$ = new ReturnInst($2);
1140   }
1141   | RET VOID {                                       // Return with no result...
1142     $$ = new ReturnInst();
1143   }
1144   | BR LABEL ValueRef {                         // Unconditional Branch...
1145     $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $3)));
1146   }                                                  // Conditional Branch...
1147   | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {  
1148     $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $6)), 
1149                         cast<BasicBlock>(getVal(Type::LabelTy, $9)),
1150                         getVal(Type::BoolTy, $3));
1151   }
1152   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1153     SwitchInst *S = new SwitchInst(getVal($2, $3), 
1154                                    cast<BasicBlock>(getVal(Type::LabelTy, $6)));
1155     $$ = S;
1156
1157     list<pair<ConstPoolVal*, BasicBlock*> >::iterator I = $8->begin(), 
1158                                                       end = $8->end();
1159     for (; I != end; ++I)
1160       S->dest_push_back(I->first, I->second);
1161   }
1162
1163 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1164     $$ = $1;
1165     ConstPoolVal *V = getVal($2, $3, true)->castConstantAsserting();
1166     if (V == 0)
1167       ThrowException("May only switch on a constant pool value!");
1168
1169     $$->push_back(make_pair(V, cast<BasicBlock>(getVal($5, $6))));
1170   }
1171   | IntType ConstValueRef ',' LABEL ValueRef {
1172     $$ = new list<pair<ConstPoolVal*, BasicBlock*> >();
1173     ConstPoolVal *V = getVal($1, $2, true)->castConstantAsserting();
1174
1175     if (V == 0)
1176       ThrowException("May only switch on a constant pool value!");
1177
1178     $$->push_back(make_pair(V, cast<BasicBlock>(getVal($4, $5))));
1179   }
1180
1181 Inst : OptAssign InstVal {
1182   setValueName($2, $1);  // Is this definition named?? if so, assign the name...
1183
1184   InsertValue($2);
1185   $$ = $2;
1186 }
1187
1188 PHIList : Types '[' ValueRef ',' ValueRef ']' {    // Used for PHI nodes
1189     $$ = new list<pair<Value*, BasicBlock*> >();
1190     $$->push_back(make_pair(getVal(*$1, $3), 
1191                             cast<BasicBlock>(getVal(Type::LabelTy, $5))));
1192     delete $1;
1193   }
1194   | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1195     $$ = $1;
1196     $1->push_back(make_pair(getVal($1->front().first->getType(), $4),
1197                             cast<BasicBlock>(getVal(Type::LabelTy, $6))));
1198   }
1199
1200
1201 ValueRefList : ResolvedVal {    // Used for call statements, and memory insts...
1202     $$ = new list<Value*>();
1203     $$->push_back($1);
1204   }
1205   | ValueRefList ',' ResolvedVal {
1206     $$ = $1;
1207     $1->push_back($3);
1208   }
1209
1210 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1211 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; }
1212
1213 InstVal : BinaryOps Types ValueRef ',' ValueRef {
1214     $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1215     if ($$ == 0)
1216       ThrowException("binary operator returned null!");
1217     delete $2;
1218   }
1219   | UnaryOps ResolvedVal {
1220     $$ = UnaryOperator::create($1, $2);
1221     if ($$ == 0)
1222       ThrowException("unary operator returned null!");
1223   }
1224   | ShiftOps ResolvedVal ',' ResolvedVal {
1225     if ($4->getType() != Type::UByteTy)
1226       ThrowException("Shift amount must be ubyte!");
1227     $$ = new ShiftInst($1, $2, $4);
1228   }
1229   | CAST ResolvedVal TO Types {
1230     $$ = new CastInst($2, *$4);
1231     delete $4;
1232   }
1233   | PHI PHIList {
1234     const Type *Ty = $2->front().first->getType();
1235     $$ = new PHINode(Ty);
1236     while ($2->begin() != $2->end()) {
1237       if ($2->front().first->getType() != Ty) 
1238         ThrowException("All elements of a PHI node must be of the same type!");
1239       ((PHINode*)$$)->addIncoming($2->front().first, $2->front().second);
1240       $2->pop_front();
1241     }
1242     delete $2;  // Free the list...
1243   } 
1244   | CALL TypesV ValueRef '(' ValueRefListE ')' {
1245     const MethodType *Ty;
1246
1247     if (!(Ty = dyn_cast<MethodType>($2->get()))) {
1248       // Pull out the types of all of the arguments...
1249       vector<const Type*> ParamTypes;
1250       for (list<Value*>::iterator I = $5->begin(), E = $5->end(); I != E; ++I)
1251         ParamTypes.push_back((*I)->getType());
1252       Ty = MethodType::get(*$2, ParamTypes);
1253     }
1254     delete $2;
1255
1256     Value *V = getVal(Ty, $3);   // Get the method we're calling...
1257
1258     // Create the call node...
1259     if (!$5) {                                   // Has no arguments?
1260       $$ = new CallInst(cast<Method>(V), vector<Value*>());
1261     } else {                                     // Has arguments?
1262       // Loop through MethodType's arguments and ensure they are specified
1263       // correctly!
1264       //
1265       MethodType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1266       MethodType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
1267       list<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1268
1269       for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1270         if ((*ArgI)->getType() != *I)
1271           ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1272                          (*I)->getName() + "'!");
1273
1274       if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1275         ThrowException("Invalid number of parameters detected!");
1276
1277       $$ = new CallInst(cast<Method>(V),
1278                         vector<Value*>($5->begin(), $5->end()));
1279     }
1280     delete $5;
1281   }
1282   | MemoryInst {
1283     $$ = $1;
1284   }
1285
1286 // UByteList - List of ubyte values for load and store instructions
1287 UByteList : ',' ConstVector { 
1288   $$ = $2; 
1289 } | /* empty */ { 
1290   $$ = new vector<ConstPoolVal*>(); 
1291 }
1292
1293 MemoryInst : MALLOC Types {
1294     $$ = new MallocInst(PointerType::get(*$2));
1295     delete $2;
1296   }
1297   | MALLOC Types ',' UINT ValueRef {
1298     if (!(*$2)->isArrayType() || ((const ArrayType*)$2->get())->isSized())
1299       ThrowException("Trying to allocate " + (*$2)->getName() + 
1300                      " as unsized array!");
1301     const Type *Ty = PointerType::get(*$2);
1302     $$ = new MallocInst(Ty, getVal($4, $5));
1303     delete $2;
1304   }
1305   | ALLOCA Types {
1306     $$ = new AllocaInst(PointerType::get(*$2));
1307     delete $2;
1308   }
1309   | ALLOCA Types ',' UINT ValueRef {
1310     if (!(*$2)->isArrayType() || ((const ArrayType*)$2->get())->isSized())
1311       ThrowException("Trying to allocate " + (*$2)->getName() + 
1312                      " as unsized array!");
1313     const Type *Ty = PointerType::get(*$2);
1314     Value *ArrSize = getVal($4, $5);
1315     $$ = new AllocaInst(Ty, ArrSize);
1316     delete $2;
1317   }
1318   | FREE ResolvedVal {
1319     if (!$2->getType()->isPointerType())
1320       ThrowException("Trying to free nonpointer type " + 
1321                      $2->getType()->getName() + "!");
1322     $$ = new FreeInst($2);
1323   }
1324
1325   | LOAD Types ValueRef UByteList {
1326     if (!(*$2)->isPointerType())
1327       ThrowException("Can't load from nonpointer type: " + (*$2)->getName());
1328     if (LoadInst::getIndexedType(*$2, *$4) == 0)
1329       ThrowException("Invalid indices for load instruction!");
1330
1331     $$ = new LoadInst(getVal(*$2, $3), *$4);
1332     delete $4;   // Free the vector...
1333     delete $2;
1334   }
1335   | STORE ResolvedVal ',' Types ValueRef UByteList {
1336     if (!(*$4)->isPointerType())
1337       ThrowException("Can't store to a nonpointer type: " + (*$4)->getName());
1338     const Type *ElTy = StoreInst::getIndexedType(*$4, *$6);
1339     if (ElTy == 0)
1340       ThrowException("Can't store into that field list!");
1341     if (ElTy != $2->getType())
1342       ThrowException("Can't store '" + $2->getType()->getName() +
1343                      "' into space of type '" + ElTy->getName() + "'!");
1344     $$ = new StoreInst($2, getVal(*$4, $5), *$6);
1345     delete $4; delete $6;
1346   }
1347   | GETELEMENTPTR Types ValueRef UByteList {
1348     if (!(*$2)->isPointerType())
1349       ThrowException("getelementptr insn requires pointer operand!");
1350     if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
1351       ThrowException("Can't get element ptr '" + (*$2)->getName() + "'!");
1352     $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
1353     delete $2; delete $4;
1354   }
1355
1356 %%
1357 int yyerror(const char *ErrorMsg) {
1358   ThrowException(string("Parse error: ") + ErrorMsg);
1359   return 0;
1360 }