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