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