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