Implement constant pointers, and null specifically in the parser, bytecode writer...
[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, baaad
412     ThrowException("Redefinition of value name '" + Name + "' in the '" +
413                    V->getType()->getDescription() + "' type plane!");
414   }
415
416   V->setName(Name, ST);
417 }
418
419
420 //===----------------------------------------------------------------------===//
421 // Code for handling upreferences in type names...
422 //
423
424 // TypeContains - Returns true if Ty contains E in it.
425 //
426 static bool TypeContains(const Type *Ty, const Type *E) {
427   return find(df_begin(Ty), df_end(Ty), E) != df_end(Ty);
428 }
429
430
431 static vector<pair<unsigned, OpaqueType *> > UpRefs;
432
433 static PATypeHolder<Type> HandleUpRefs(const Type *ty) {
434   PATypeHolder<Type> Ty(ty);
435   UR_OUT(UpRefs.size() << " upreferences active!\n");
436   for (unsigned i = 0; i < UpRefs.size(); ) {
437     UR_OUT("TypeContains(" << Ty->getDescription() << ", " 
438            << UpRefs[i].second->getDescription() << ") = " 
439            << TypeContains(Ty, UpRefs[i].second) << endl);
440     if (TypeContains(Ty, UpRefs[i].second)) {
441       unsigned Level = --UpRefs[i].first;   // Decrement level of upreference
442       UR_OUT("Uplevel Ref Level = " << Level << endl);
443       if (Level == 0) {                     // Upreference should be resolved! 
444         UR_OUT("About to resolve upreference!\n";
445                string OldName = UpRefs[i].second->getDescription());
446         UpRefs[i].second->refineAbstractTypeTo(Ty);
447         UpRefs.erase(UpRefs.begin()+i);     // Remove from upreference list...
448         UR_OUT("Type '" << OldName << "' refined upreference to: "
449                << (const void*)Ty << ", " << Ty->getDescription() << endl);
450         continue;
451       }
452     }
453
454     ++i;                                  // Otherwise, no resolve, move on...
455   }
456   // FIXME: TODO: this should return the updated type
457   return Ty;
458 }
459
460 template <class TypeTy>
461 inline static void TypeDone(PATypeHolder<TypeTy> *Ty) {
462   if (UpRefs.size())
463     ThrowException("Invalid upreference in type: " + (*Ty)->getDescription());
464 }
465
466 // newTH - Allocate a new type holder for the specified type
467 template <class TypeTy>
468 inline static PATypeHolder<TypeTy> *newTH(const TypeTy *Ty) {
469   return new PATypeHolder<TypeTy>(Ty);
470 }
471 template <class TypeTy>
472 inline static PATypeHolder<TypeTy> *newTH(const PATypeHolder<TypeTy> &TH) {
473   return new PATypeHolder<TypeTy>(TH);
474 }
475
476
477 // newTHC - Allocate a new type holder for the specified type that can be
478 // casted to a new Type type.
479 template <class TypeTy, class OldTy>
480 inline static PATypeHolder<TypeTy> *newTHC(const PATypeHolder<OldTy> &Old) {
481   return new PATypeHolder<TypeTy>((const TypeTy*)Old.get());
482 }
483
484
485 //===----------------------------------------------------------------------===//
486 //            RunVMAsmParser - Define an interface to this parser
487 //===----------------------------------------------------------------------===//
488 //
489 Module *RunVMAsmParser(const string &Filename, FILE *F) {
490   llvmAsmin = F;
491   CurFilename = Filename;
492   llvmAsmlineno = 1;      // Reset the current line number...
493
494   CurModule.CurrentModule = new Module();  // Allocate a new module to read
495   yyparse();       // Parse the file.
496   Module *Result = ParserResult;
497   llvmAsmin = stdin;    // F is about to go away, don't use it anymore...
498   ParserResult = 0;
499
500   return Result;
501 }
502
503 %}
504
505 %union {
506   Module                           *ModuleVal;
507   Method                           *MethodVal;
508   MethodArgument                   *MethArgVal;
509   BasicBlock                       *BasicBlockVal;
510   TerminatorInst                   *TermInstVal;
511   Instruction                      *InstVal;
512   ConstPoolVal                     *ConstVal;
513
514   const Type                       *PrimType;
515   PATypeHolder<Type>               *TypeVal;
516   PATypeHolder<ArrayType>          *ArrayTypeTy;
517   PATypeHolder<StructType>         *StructTypeTy;
518   PATypeHolder<PointerType>        *PointerTypeTy;
519   Value                            *ValueVal;
520
521   list<MethodArgument*>            *MethodArgList;
522   list<Value*>                     *ValueList;
523   list<PATypeHolder<Type> >        *TypeList;
524   list<pair<Value*, BasicBlock*> > *PHIList;   // Represent the RHS of PHI node
525   list<pair<ConstPoolVal*, BasicBlock*> > *JumpTable;
526   vector<ConstPoolVal*>            *ConstVector;
527
528   int64_t                           SInt64Val;
529   uint64_t                          UInt64Val;
530   int                               SIntVal;
531   unsigned                          UIntVal;
532   double                            FPVal;
533   bool                              BoolVal;
534
535   char                             *StrVal;   // This memory is strdup'd!
536   ValID                             ValIDVal; // strdup'd memory maybe!
537
538   Instruction::UnaryOps             UnaryOpVal;
539   Instruction::BinaryOps            BinaryOpVal;
540   Instruction::TermOps              TermOpVal;
541   Instruction::MemoryOps            MemOpVal;
542   Instruction::OtherOps             OtherOpVal;
543 }
544
545 %type <ModuleVal>     Module MethodList
546 %type <MethodVal>     Method MethodProto MethodHeader BasicBlockList
547 %type <BasicBlockVal> BasicBlock InstructionList
548 %type <TermInstVal>   BBTerminatorInst
549 %type <InstVal>       Inst InstVal MemoryInst
550 %type <ConstVal>      ConstVal ExtendedConstVal
551 %type <ConstVector>   ConstVector UByteList
552 %type <MethodArgList> ArgList ArgListH
553 %type <MethArgVal>    ArgVal
554 %type <PHIList>       PHIList
555 %type <ValueList>     ValueRefList ValueRefListE  // For call param lists
556 %type <TypeList>      TypeListI ArgTypeListI
557 %type <JumpTable>     JumpTable
558 %type <BoolVal>       GlobalType                  // GLOBAL or CONSTANT?
559
560 %type <ValIDVal>      ValueRef ConstValueRef // Reference to a definition or BB
561 %type <ValueVal>      ResolvedVal            // <type> <valref> pair
562 // Tokens and types for handling constant integer values
563 //
564 // ESINT64VAL - A negative number within long long range
565 %token <SInt64Val> ESINT64VAL
566
567 // EUINT64VAL - A positive number within uns. long long range
568 %token <UInt64Val> EUINT64VAL
569 %type  <SInt64Val> EINT64VAL
570
571 %token  <SIntVal>   SINTVAL   // Signed 32 bit ints...
572 %token  <UIntVal>   UINTVAL   // Unsigned 32 bit ints...
573 %type   <SIntVal>   INTVAL
574 %token  <FPVal>     FPVAL     // Float or Double constant
575
576 // Built in types...
577 %type  <TypeVal> Types TypesV UpRTypes UpRTypesV
578 %type  <PrimType> SIntType UIntType IntType FPType PrimType   // Classifications
579 %token <TypeVal>  OPAQUE
580 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
581 %token <PrimType> FLOAT DOUBLE TYPE LABEL
582 %type  <ArrayTypeTy> ArrayType ArrayTypeI
583 %type  <StructTypeTy> StructType StructTypeI
584 %type  <PointerTypeTy> PointerType PointerTypeI
585
586 %token <StrVal>     VAR_ID LABELSTR STRINGCONSTANT
587 %type  <StrVal>  OptVAR_ID OptAssign
588
589
590 %token IMPLEMENTATION TRUE FALSE BEGINTOK END DECLARE GLOBAL CONSTANT UNINIT
591 %token TO DOTDOTDOT STRING NULL_TOK
592
593 // Basic Block Terminating Operators 
594 %token <TermOpVal> RET BR SWITCH
595
596 // Unary Operators 
597 %type  <UnaryOpVal> UnaryOps  // all the unary operators
598 %token <UnaryOpVal> NOT
599
600 // Binary Operators 
601 %type  <BinaryOpVal> BinaryOps  // all the binary operators
602 %token <BinaryOpVal> ADD SUB MUL DIV REM
603 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE  // Binary Comarators
604
605 // Memory Instructions
606 %token <MemoryOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
607
608 // Other Operators
609 %type  <OtherOpVal> ShiftOps
610 %token <OtherOpVal> PHI CALL CAST SHL SHR
611
612 %start Module
613 %%
614
615 // Handle constant integer size restriction and conversion...
616 //
617
618 INTVAL : SINTVAL
619 INTVAL : UINTVAL {
620   if ($1 > (uint32_t)INT32_MAX)     // Outside of my range!
621     ThrowException("Value too large for type!");
622   $$ = (int32_t)$1;
623 }
624
625
626 EINT64VAL : ESINT64VAL       // These have same type and can't cause problems...
627 EINT64VAL : EUINT64VAL {
628   if ($1 > (uint64_t)INT64_MAX)     // Outside of my range!
629     ThrowException("Value too large for type!");
630   $$ = (int64_t)$1;
631 }
632
633 // Operations that are notably excluded from this list include: 
634 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
635 //
636 UnaryOps  : NOT
637 BinaryOps : ADD | SUB | MUL | DIV | REM
638 BinaryOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
639 ShiftOps  : SHL | SHR
640
641 // These are some types that allow classification if we only want a particular 
642 // thing... for example, only a signed, unsigned, or integral type.
643 SIntType :  LONG |  INT |  SHORT | SBYTE
644 UIntType : ULONG | UINT | USHORT | UBYTE
645 IntType  : SIntType | UIntType
646 FPType   : FLOAT | DOUBLE
647
648 // OptAssign - Value producing statements have an optional assignment component
649 OptAssign : VAR_ID '=' {
650     $$ = $1;
651   }
652   | /*empty*/ { 
653     $$ = 0; 
654   }
655
656
657 //===----------------------------------------------------------------------===//
658 // Types includes all predefined types... except void, because it can only be
659 // used in specific contexts (method returning void for example).  To have
660 // access to it, a user must explicitly use TypesV.
661 //
662
663 // TypesV includes all of 'Types', but it also includes the void type.
664 TypesV    : Types    | VOID { $$ = newTH($1); }
665 UpRTypesV : UpRTypes | VOID { $$ = newTH($1); }
666
667 Types     : UpRTypes {
668     TypeDone($$ = $1);
669   }
670
671
672 // Derived types are added later...
673 //
674 PrimType : BOOL | SBYTE | UBYTE | SHORT  | USHORT | INT   | UINT 
675 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE   | LABEL
676 UpRTypes : OPAQUE | PrimType { $$ = newTH($1); }
677 UpRTypes : ValueRef {                    // Named types are also simple types...
678   $$ = newTH(getTypeVal($1));
679 }
680
681 // ArrayTypeI - Internal version of ArrayType that can have incomplete uprefs
682 //
683 ArrayTypeI : '[' UpRTypesV ']' {               // Unsized array type?
684     $$ = newTHC<ArrayType>(HandleUpRefs(ArrayType::get(*$2)));
685     delete $2;
686   }
687   | '[' EUINT64VAL 'x' UpRTypes ']' {          // Sized array type?
688     $$ = newTHC<ArrayType>(HandleUpRefs(ArrayType::get(*$4, (int)$2)));
689     delete $4;
690   }
691
692 StructTypeI : '{' TypeListI '}' {              // Structure type?
693     vector<const Type*> Elements;
694     mapto($2->begin(), $2->end(), back_inserter(Elements), 
695         mem_fun_ref(&PATypeHandle<Type>::get));
696
697     $$ = newTHC<StructType>(HandleUpRefs(StructType::get(Elements)));
698     delete $2;
699   }
700   | '{' '}' {                                  // Empty structure type?
701     $$ = newTH(StructType::get(vector<const Type*>()));
702   }
703
704 PointerTypeI : UpRTypes '*' {                             // Pointer type?
705     $$ = newTHC<PointerType>(HandleUpRefs(PointerType::get(*$1)));
706     delete $1;  // Delete the type handle
707   }
708
709 // Include derived types in the Types production.
710 //
711 UpRTypes : '\\' EUINT64VAL {                   // Type UpReference
712     if ($2 > (uint64_t)INT64_MAX) ThrowException("Value out of range!");
713     OpaqueType *OT = OpaqueType::get();        // Use temporary placeholder
714     UpRefs.push_back(make_pair((unsigned)$2, OT));  // Add to vector...
715     $$ = newTH<Type>(OT);
716     UR_OUT("New Upreference!\n");
717   }
718   | UpRTypesV '(' ArgTypeListI ')' {           // Method derived type?
719     vector<const Type*> Params;
720     mapto($3->begin(), $3->end(), back_inserter(Params), 
721           mem_fun_ref(&PATypeHandle<Type>::get));
722     $$ = newTH(HandleUpRefs(MethodType::get(*$1, Params)));
723     delete $3;      // Delete the argument list
724     delete $1;      // Delete the old type handle
725   }
726   | ArrayTypeI {                               // [Un]sized array type?
727     $$ = newTHC<Type>(*$1); delete $1;
728   }
729   | StructTypeI {                              // Structure type?
730     $$ = newTHC<Type>(*$1); delete $1;
731   }
732   | PointerTypeI {                             // Pointer type?
733     $$ = newTHC<Type>(*$1); delete $1;
734   }
735
736 // Define some helpful top level types that do not allow UpReferences to escape
737 //
738 ArrayType   : ArrayTypeI   { TypeDone($$ = $1); }
739 StructType  : StructTypeI  { TypeDone($$ = $1); }
740 PointerType : PointerTypeI { TypeDone($$ = $1); }
741
742
743 // TypeList - Used for struct declarations and as a basis for method type 
744 // declaration type lists
745 //
746 TypeListI : UpRTypes {
747     $$ = new list<PATypeHolder<Type> >();
748     $$->push_back(*$1); delete $1;
749   }
750   | TypeListI ',' UpRTypes {
751     ($$=$1)->push_back(*$3); delete $3;
752   }
753
754 // ArgTypeList - List of types for a method type declaration...
755 ArgTypeListI : TypeListI
756   | TypeListI ',' DOTDOTDOT {
757     ($$=$1)->push_back(Type::VoidTy);
758   }
759   | DOTDOTDOT {
760     ($$ = new list<PATypeHolder<Type> >())->push_back(Type::VoidTy);
761   }
762   | /*empty*/ {
763     $$ = new list<PATypeHolder<Type> >();
764   }
765
766
767 // ConstVal - The various declarations that go into the constant pool.  This
768 // includes all forward declarations of types, constants, and functions.
769 //
770 // This is broken into two sections: ExtendedConstVal and ConstVal
771 //
772 ExtendedConstVal: ArrayType '[' ConstVector ']' { // Nonempty unsized arr
773     const ArrayType *ATy = *$1;
774     const Type *ETy = ATy->getElementType();
775     int NumElements = ATy->getNumElements();
776
777     // Verify that we have the correct size...
778     if (NumElements != -1 && NumElements != (int)$3->size())
779       ThrowException("Type mismatch: constant sized array initialized with " +
780                      utostr($3->size()) +  " arguments, but has size of " + 
781                      itostr(NumElements) + "!");
782
783     // Verify all elements are correct type!
784     for (unsigned i = 0; i < $3->size(); i++) {
785       if (ETy != (*$3)[i]->getType())
786         ThrowException("Element #" + utostr(i) + " is not of type '" + 
787                        ETy->getName() + "' as required!\nIt is of type '" +
788                        (*$3)[i]->getType()->getName() + "'.");
789     }
790
791     $$ = ConstPoolArray::get(ATy, *$3);
792     delete $1; delete $3;
793   }
794   | ArrayType '[' ']' {
795     int NumElements = (*$1)->getNumElements();
796     if (NumElements != -1 && NumElements != 0) 
797       ThrowException("Type mismatch: constant sized array initialized with 0"
798                      " arguments, but has size of " + itostr(NumElements) +"!");
799     $$ = ConstPoolArray::get((*$1), vector<ConstPoolVal*>());
800     delete $1;
801   }
802   | ArrayType 'c' STRINGCONSTANT {
803     const ArrayType *ATy = *$1;
804     int NumElements = ATy->getNumElements();
805     const Type *ETy = ATy->getElementType();
806     char *EndStr = UnEscapeLexed($3, true);
807     if (NumElements != -1 && NumElements != (EndStr-$3))
808       ThrowException("Can't build string constant of size " + 
809                      itostr((int)(EndStr-$3)) +
810                      " when array has size " + itostr(NumElements) + "!");
811     vector<ConstPoolVal*> Vals;
812     if (ETy == Type::SByteTy) {
813       for (char *C = $3; C != EndStr; ++C)
814         Vals.push_back(ConstPoolSInt::get(ETy, *C));
815     } else if (ETy == Type::UByteTy) {
816       for (char *C = $3; C != EndStr; ++C)
817         Vals.push_back(ConstPoolUInt::get(ETy, *C));
818     } else {
819       free($3);
820       ThrowException("Cannot build string arrays of non byte sized elements!");
821     }
822     free($3);
823     $$ = ConstPoolArray::get(ATy, Vals);
824     delete $1;
825   }
826   | StructType '{' ConstVector '}' {
827     // FIXME: TODO: Check to see that the constants are compatible with the type
828     // initializer!
829     $$ = ConstPoolStruct::get(*$1, *$3);
830     delete $1; delete $3;
831   }
832 /*
833   | Types '*' ConstVal {
834     assert(0);
835     $$ = 0;
836   }
837 */
838
839 ConstVal : ExtendedConstVal {
840     $$ = $1;
841   }
842   | SIntType EINT64VAL {     // integral constants
843     if (!ConstPoolSInt::isValueValidForType($1, $2))
844       ThrowException("Constant value doesn't fit in type!");
845     $$ = ConstPoolSInt::get($1, $2);
846   } 
847   | UIntType EUINT64VAL {           // integral constants
848     if (!ConstPoolUInt::isValueValidForType($1, $2))
849       ThrowException("Constant value doesn't fit in type!");
850     $$ = ConstPoolUInt::get($1, $2);
851   } 
852   | BOOL TRUE {                     // Boolean constants
853     $$ = ConstPoolBool::True;
854   }
855   | BOOL FALSE {                    // Boolean constants
856     $$ = ConstPoolBool::False;
857   }
858   | FPType FPVAL {                   // Float & Double constants
859     $$ = ConstPoolFP::get($1, $2);
860   }
861
862 // ConstVector - A list of comma seperated constants.
863 ConstVector : ConstVector ',' ConstVal {
864     ($$ = $1)->push_back($3);
865   }
866   | ConstVal {
867     $$ = new vector<ConstPoolVal*>();
868     $$->push_back($1);
869   }
870
871
872 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
873 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; }
874
875
876 // ConstPool - Constants with optional names assigned to them.
877 ConstPool : ConstPool OptAssign ConstVal { 
878     setValueName($3, $2);
879     InsertValue($3);
880   }
881   | ConstPool OptAssign TYPE TypesV {  // Types can be defined in the const pool
882     // TODO: FIXME when Type are not const
883     setValueName(const_cast<Type*>($4->get()), $2);
884
885     if (!$2) {
886       InsertType($4->get(),
887                  CurMeth.CurrentMethod ? CurMeth.Types : CurModule.Types);
888     }
889     delete $4;
890   }
891   | ConstPool MethodProto {            // Method prototypes can be in const pool
892   }
893   | ConstPool OptAssign GlobalType ResolvedVal {
894     const Type *Ty = $4->getType();
895     // Global declarations appear in Constant Pool
896     ConstPoolVal *Initializer = $4->castConstant();
897     if (Initializer == 0)
898       ThrowException("Global value initializer is not a constant!");
899          
900     GlobalVariable *GV = new GlobalVariable(PointerType::get(Ty), $3,
901                                             Initializer);
902     setValueName(GV, $2);
903
904     CurModule.CurrentModule->getGlobalList().push_back(GV);
905     InsertValue(GV, CurModule.Values);
906   }
907   | ConstPool OptAssign UNINIT GlobalType Types {
908     const Type *Ty = *$5;
909     // Global declarations appear in Constant Pool
910     if (Ty->isArrayType() && Ty->castArrayType()->isUnsized()) {
911       ThrowException("Type '" + Ty->getDescription() +
912                      "' is not a sized type!");
913     }
914
915     GlobalVariable *GV = new GlobalVariable(PointerType::get(Ty), $4);
916     setValueName(GV, $2);
917
918     CurModule.CurrentModule->getGlobalList().push_back(GV);
919     InsertValue(GV, CurModule.Values);
920   }
921   | /* empty: end of list */ { 
922   }
923
924
925 //===----------------------------------------------------------------------===//
926 //                             Rules to match Modules
927 //===----------------------------------------------------------------------===//
928
929 // Module rule: Capture the result of parsing the whole file into a result
930 // variable...
931 //
932 Module : MethodList {
933   $$ = ParserResult = $1;
934   CurModule.ModuleDone();
935 }
936
937 // MethodList - A list of methods, preceeded by a constant pool.
938 //
939 MethodList : MethodList Method {
940     $$ = $1;
941     if (!$2->getParent())
942       $1->getMethodList().push_back($2);
943     CurMeth.MethodDone();
944   } 
945   | MethodList MethodProto {
946     $$ = $1;
947   }
948   | ConstPool IMPLEMENTATION {
949     $$ = CurModule.CurrentModule;
950     // Resolve circular types before we parse the body of the module
951     ResolveTypes(CurModule.LateResolveTypes);
952   }
953
954
955 //===----------------------------------------------------------------------===//
956 //                       Rules to match Method Headers
957 //===----------------------------------------------------------------------===//
958
959 OptVAR_ID : VAR_ID | /*empty*/ { $$ = 0; }
960
961 ArgVal : Types OptVAR_ID {
962   $$ = new MethodArgument(*$1); delete $1;
963   setValueName($$, $2);
964 }
965
966 ArgListH : ArgVal ',' ArgListH {
967     $$ = $3;
968     $3->push_front($1);
969   }
970   | ArgVal {
971     $$ = new list<MethodArgument*>();
972     $$->push_front($1);
973   }
974   | DOTDOTDOT {
975     $$ = new list<MethodArgument*>();
976     $$->push_back(new MethodArgument(Type::VoidTy));
977   }
978
979 ArgList : ArgListH {
980     $$ = $1;
981   }
982   | /* empty */ {
983     $$ = 0;
984   }
985
986 MethodHeaderH : TypesV STRINGCONSTANT '(' ArgList ')' {
987   UnEscapeLexed($2);
988   vector<const Type*> ParamTypeList;
989   if ($4)
990     for (list<MethodArgument*>::iterator I = $4->begin(); I != $4->end(); ++I)
991       ParamTypeList.push_back((*I)->getType());
992
993   const MethodType *MT = MethodType::get(*$1, ParamTypeList);
994   delete $1;
995
996   Method *M = 0;
997   if (SymbolTable *ST = CurModule.CurrentModule->getSymbolTable()) {
998     if (Value *V = ST->lookup(MT, $2)) {  // Method already in symtab?
999       M = V->castMethodAsserting();
1000
1001       // Yes it is.  If this is the case, either we need to be a forward decl,
1002       // or it needs to be.
1003       if (!CurMeth.isDeclare && !M->isExternal())
1004         ThrowException("Redefinition of method '" + string($2) + "'!");      
1005     }
1006   }
1007
1008   if (M == 0) {  // Not already defined?
1009     M = new Method(MT, $2);
1010     InsertValue(M, CurModule.Values);
1011   }
1012
1013   free($2);  // Free strdup'd memory!
1014
1015   CurMeth.MethodStart(M);
1016
1017   // Add all of the arguments we parsed to the method...
1018   if ($4 && !CurMeth.isDeclare) {        // Is null if empty...
1019     Method::ArgumentListType &ArgList = M->getArgumentList();
1020
1021     for (list<MethodArgument*>::iterator I = $4->begin(); I != $4->end(); ++I) {
1022       InsertValue(*I);
1023       ArgList.push_back(*I);
1024     }
1025     delete $4;                     // We're now done with the argument list
1026   }
1027 }
1028
1029 MethodHeader : MethodHeaderH ConstPool BEGINTOK {
1030   $$ = CurMeth.CurrentMethod;
1031
1032   // Resolve circular types before we parse the body of the method.
1033   ResolveTypes(CurMeth.LateResolveTypes);
1034 }
1035
1036 Method : BasicBlockList END {
1037   $$ = $1;
1038 }
1039
1040 MethodProto : DECLARE { CurMeth.isDeclare = true; } MethodHeaderH {
1041   $$ = CurMeth.CurrentMethod;
1042   if (!$$->getParent())
1043     CurModule.CurrentModule->getMethodList().push_back($$);
1044   CurMeth.MethodDone();
1045 }
1046
1047 //===----------------------------------------------------------------------===//
1048 //                        Rules to match Basic Blocks
1049 //===----------------------------------------------------------------------===//
1050
1051 ConstValueRef : ESINT64VAL {    // A reference to a direct constant
1052     $$ = ValID::create($1);
1053   }
1054   | EUINT64VAL {
1055     $$ = ValID::create($1);
1056   }
1057   | FPVAL {                     // Perhaps it's an FP constant?
1058     $$ = ValID::create($1);
1059   }
1060   | TRUE {
1061     $$ = ValID::create((int64_t)1);
1062   } 
1063   | FALSE {
1064     $$ = ValID::create((int64_t)0);
1065   }
1066   | NULL_TOK {
1067     $$ = ValID::createNull();
1068   }
1069
1070 /*
1071   | STRINGCONSTANT {        // Quoted strings work too... especially for methods
1072     $$ = ValID::create_conststr($1);
1073   }
1074 */
1075
1076 // ValueRef - A reference to a definition... 
1077 ValueRef : INTVAL {           // Is it an integer reference...?
1078     $$ = ValID::create($1);
1079   }
1080   | VAR_ID {                 // Is it a named reference...?
1081     $$ = ValID::create($1);
1082   }
1083   | ConstValueRef {
1084     $$ = $1;
1085   }
1086
1087 // ResolvedVal - a <type> <value> pair.  This is used only in cases where the
1088 // type immediately preceeds the value reference, and allows complex constant
1089 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1090 ResolvedVal : ExtendedConstVal {
1091     $$ = $1;
1092   }
1093   | Types ValueRef {
1094     $$ = getVal(*$1, $2); delete $1;
1095   }
1096
1097
1098 BasicBlockList : BasicBlockList BasicBlock {
1099     $1->getBasicBlocks().push_back($2);
1100     $$ = $1;
1101   }
1102   | MethodHeader BasicBlock { // Do not allow methods with 0 basic blocks   
1103     $$ = $1;                  // in them...
1104     $1->getBasicBlocks().push_back($2);
1105   }
1106
1107
1108 // Basic blocks are terminated by branching instructions: 
1109 // br, br/cc, switch, ret
1110 //
1111 BasicBlock : InstructionList BBTerminatorInst  {
1112     $1->getInstList().push_back($2);
1113     InsertValue($1);
1114     $$ = $1;
1115   }
1116   | LABELSTR InstructionList BBTerminatorInst  {
1117     $2->getInstList().push_back($3);
1118     setValueName($2, $1);
1119
1120     InsertValue($2);
1121     $$ = $2;
1122   }
1123
1124 InstructionList : InstructionList Inst {
1125     $1->getInstList().push_back($2);
1126     $$ = $1;
1127   }
1128   | /* empty */ {
1129     $$ = new BasicBlock();
1130   }
1131
1132 BBTerminatorInst : RET ResolvedVal {              // Return with a result...
1133     $$ = new ReturnInst($2);
1134   }
1135   | RET VOID {                                       // Return with no result...
1136     $$ = new ReturnInst();
1137   }
1138   | BR LABEL ValueRef {                         // Unconditional Branch...
1139     $$ = new BranchInst(getVal(Type::LabelTy, $3)->castBasicBlockAsserting());
1140   }                                                  // Conditional Branch...
1141   | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {  
1142     $$ = new BranchInst(getVal(Type::LabelTy, $6)->castBasicBlockAsserting(), 
1143                         getVal(Type::LabelTy, $9)->castBasicBlockAsserting(),
1144                         getVal(Type::BoolTy, $3));
1145   }
1146   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1147     SwitchInst *S = new SwitchInst(getVal($2, $3), 
1148                           getVal(Type::LabelTy, $6)->castBasicBlockAsserting());
1149     $$ = S;
1150
1151     list<pair<ConstPoolVal*, BasicBlock*> >::iterator I = $8->begin(), 
1152                                                       end = $8->end();
1153     for (; I != end; ++I)
1154       S->dest_push_back(I->first, I->second);
1155   }
1156
1157 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1158     $$ = $1;
1159     ConstPoolVal *V = getVal($2, $3, true)->castConstantAsserting();
1160     if (V == 0)
1161       ThrowException("May only switch on a constant pool value!");
1162
1163     $$->push_back(make_pair(V, getVal($5, $6)->castBasicBlockAsserting()));
1164   }
1165   | IntType ConstValueRef ',' LABEL ValueRef {
1166     $$ = new list<pair<ConstPoolVal*, BasicBlock*> >();
1167     ConstPoolVal *V = getVal($1, $2, true)->castConstantAsserting();
1168
1169     if (V == 0)
1170       ThrowException("May only switch on a constant pool value!");
1171
1172     $$->push_back(make_pair(V, getVal($4, $5)->castBasicBlockAsserting()));
1173   }
1174
1175 Inst : OptAssign InstVal {
1176   setValueName($2, $1);  // Is this definition named?? if so, assign the name...
1177
1178   InsertValue($2);
1179   $$ = $2;
1180 }
1181
1182 PHIList : Types '[' ValueRef ',' ValueRef ']' {    // Used for PHI nodes
1183     $$ = new list<pair<Value*, BasicBlock*> >();
1184     $$->push_back(make_pair(getVal(*$1, $3), 
1185                          getVal(Type::LabelTy, $5)->castBasicBlockAsserting()));
1186     delete $1;
1187   }
1188   | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1189     $$ = $1;
1190     $1->push_back(make_pair(getVal($1->front().first->getType(), $4),
1191                          getVal(Type::LabelTy, $6)->castBasicBlockAsserting()));
1192   }
1193
1194
1195 ValueRefList : ResolvedVal {    // Used for call statements, and memory insts...
1196     $$ = new list<Value*>();
1197     $$->push_back($1);
1198   }
1199   | ValueRefList ',' ResolvedVal {
1200     $$ = $1;
1201     $1->push_back($3);
1202   }
1203
1204 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1205 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; }
1206
1207 InstVal : BinaryOps Types ValueRef ',' ValueRef {
1208     $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1209     if ($$ == 0)
1210       ThrowException("binary operator returned null!");
1211     delete $2;
1212   }
1213   | UnaryOps ResolvedVal {
1214     $$ = UnaryOperator::create($1, $2);
1215     if ($$ == 0)
1216       ThrowException("unary operator returned null!");
1217   }
1218   | ShiftOps ResolvedVal ',' ResolvedVal {
1219     if ($4->getType() != Type::UByteTy)
1220       ThrowException("Shift amount must be ubyte!");
1221     $$ = new ShiftInst($1, $2, $4);
1222   }
1223   | CAST ResolvedVal TO Types {
1224     $$ = new CastInst($2, *$4);
1225     delete $4;
1226   }
1227   | PHI PHIList {
1228     const Type *Ty = $2->front().first->getType();
1229     $$ = new PHINode(Ty);
1230     while ($2->begin() != $2->end()) {
1231       if ($2->front().first->getType() != Ty) 
1232         ThrowException("All elements of a PHI node must be of the same type!");
1233       ((PHINode*)$$)->addIncoming($2->front().first, $2->front().second);
1234       $2->pop_front();
1235     }
1236     delete $2;  // Free the list...
1237   } 
1238   | CALL TypesV ValueRef '(' ValueRefListE ')' {
1239     const MethodType *Ty;
1240
1241     if (!(Ty = (*$2)->dyncastMethodType())) {
1242       // Pull out the types of all of the arguments...
1243       vector<const Type*> ParamTypes;
1244       for (list<Value*>::iterator I = $5->begin(), E = $5->end(); I != E; ++I)
1245         ParamTypes.push_back((*I)->getType());
1246       Ty = MethodType::get(*$2, ParamTypes);
1247     }
1248     delete $2;
1249
1250     Value *V = getVal(Ty, $3);   // Get the method we're calling...
1251
1252     // Create the call node...
1253     if (!$5) {                                   // Has no arguments?
1254       $$ = new CallInst(V->castMethodAsserting(), vector<Value*>());
1255     } else {                                     // Has arguments?
1256       // Loop through MethodType's arguments and ensure they are specified
1257       // correctly!
1258       //
1259       MethodType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1260       MethodType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
1261       list<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1262
1263       for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1264         if ((*ArgI)->getType() != *I)
1265           ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1266                          (*I)->getName() + "'!");
1267
1268       if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1269         ThrowException("Invalid number of parameters detected!");
1270
1271       $$ = new CallInst(V->castMethodAsserting(),
1272                         vector<Value*>($5->begin(), $5->end()));
1273     }
1274     delete $5;
1275   }
1276   | MemoryInst {
1277     $$ = $1;
1278   }
1279
1280 // UByteList - List of ubyte values for load and store instructions
1281 UByteList : ',' ConstVector { 
1282   $$ = $2; 
1283 } | /* empty */ { 
1284   $$ = new vector<ConstPoolVal*>(); 
1285 }
1286
1287 MemoryInst : MALLOC Types {
1288     $$ = new MallocInst(PointerType::get(*$2));
1289     delete $2;
1290   }
1291   | MALLOC Types ',' UINT ValueRef {
1292     if (!(*$2)->isArrayType() || ((const ArrayType*)$2->get())->isSized())
1293       ThrowException("Trying to allocate " + (*$2)->getName() + 
1294                      " as unsized array!");
1295     const Type *Ty = PointerType::get(*$2);
1296     $$ = new MallocInst(Ty, getVal($4, $5));
1297     delete $2;
1298   }
1299   | ALLOCA Types {
1300     $$ = new AllocaInst(PointerType::get(*$2));
1301     delete $2;
1302   }
1303   | ALLOCA Types ',' UINT ValueRef {
1304     if (!(*$2)->isArrayType() || ((const ArrayType*)$2->get())->isSized())
1305       ThrowException("Trying to allocate " + (*$2)->getName() + 
1306                      " as unsized array!");
1307     const Type *Ty = PointerType::get(*$2);
1308     Value *ArrSize = getVal($4, $5);
1309     $$ = new AllocaInst(Ty, ArrSize);
1310     delete $2;
1311   }
1312   | FREE ResolvedVal {
1313     if (!$2->getType()->isPointerType())
1314       ThrowException("Trying to free nonpointer type " + 
1315                      $2->getType()->getName() + "!");
1316     $$ = new FreeInst($2);
1317   }
1318
1319   | LOAD Types ValueRef UByteList {
1320     if (!(*$2)->isPointerType())
1321       ThrowException("Can't load from nonpointer type: " + (*$2)->getName());
1322     if (LoadInst::getIndexedType(*$2, *$4) == 0)
1323       ThrowException("Invalid indices for load instruction!");
1324
1325     $$ = new LoadInst(getVal(*$2, $3), *$4);
1326     delete $4;   // Free the vector...
1327     delete $2;
1328   }
1329   | STORE ResolvedVal ',' Types ValueRef UByteList {
1330     if (!(*$4)->isPointerType())
1331       ThrowException("Can't store to a nonpointer type: " + (*$4)->getName());
1332     const Type *ElTy = StoreInst::getIndexedType(*$4, *$6);
1333     if (ElTy == 0)
1334       ThrowException("Can't store into that field list!");
1335     if (ElTy != $2->getType())
1336       ThrowException("Can't store '" + $2->getType()->getName() +
1337                      "' into space of type '" + ElTy->getName() + "'!");
1338     $$ = new StoreInst($2, getVal(*$4, $5), *$6);
1339     delete $4; delete $6;
1340   }
1341   | GETELEMENTPTR Types ValueRef UByteList {
1342     if (!(*$2)->isPointerType())
1343       ThrowException("getelementptr insn requires pointer operand!");
1344     if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
1345       ThrowException("Can't get element ptr '" + (*$2)->getName() + "'!");
1346     $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
1347     delete $2; delete $4;
1348   }
1349
1350 %%
1351 int yyerror(const char *ErrorMsg) {
1352   ThrowException(string("Parse error: ") + ErrorMsg);
1353   return 0;
1354 }