Replace a bunch of complex ConstantPointerRef referring code with simple
[oota-llvm.git] / lib / AsmParser / llvmAsmParser.y
1 //===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements the bison parser for LLVM assembly languages files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 %{
15 #include "ParserInternals.h"
16 #include "llvm/SymbolTable.h"
17 #include "llvm/Module.h"
18 #include "llvm/iTerminators.h"
19 #include "llvm/iMemory.h"
20 #include "llvm/iOperators.h"
21 #include "llvm/iPHINode.h"
22 #include "llvm/Support/GetElementPtrTypeIterator.h"
23 #include "Support/STLExtras.h"
24 #include <algorithm>
25 #include <iostream>
26 #include <list>
27 #include <utility>
28
29 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
30 int yylex();                       // declaration" of xxx warnings.
31 int yyparse();
32
33 namespace llvm {
34
35 static Module *ParserResult;
36 std::string CurFilename;
37
38 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
39 // relating to upreferences in the input stream.
40 //
41 //#define DEBUG_UPREFS 1
42 #ifdef DEBUG_UPREFS
43 #define UR_OUT(X) std::cerr << X
44 #else
45 #define UR_OUT(X)
46 #endif
47
48 #define YYERROR_VERBOSE 1
49
50 // HACK ALERT: This variable is used to implement the automatic conversion of
51 // variable argument instructions from their old to new forms.  When this
52 // compatiblity "Feature" is removed, this should be too.
53 //
54 static BasicBlock *CurBB;
55 static bool ObsoleteVarArgs;
56
57
58 // This contains info used when building the body of a function.  It is
59 // destroyed when the function is completed.
60 //
61 typedef std::vector<Value *> ValueList;           // Numbered defs
62 static void ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
63                                std::map<const Type *,ValueList> *FutureLateResolvers = 0);
64
65 static struct PerModuleInfo {
66   Module *CurrentModule;
67   std::map<const Type *, ValueList> Values; // Module level numbered definitions
68   std::map<const Type *,ValueList> LateResolveValues;
69   std::vector<PATypeHolder>    Types;
70   std::map<ValID, PATypeHolder> LateResolveTypes;
71
72   // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
73   // references to global values.  Global values may be referenced before they
74   // are defined, and if so, the temporary object that they represent is held
75   // here.  This is used for forward references of ConstantPointerRefs.
76   //
77   typedef std::map<std::pair<const PointerType *,
78                              ValID>, GlobalValue*> GlobalRefsType;
79   GlobalRefsType GlobalRefs;
80
81   void ModuleDone() {
82     // If we could not resolve some functions at function compilation time
83     // (calls to functions before they are defined), resolve them now...  Types
84     // are resolved when the constant pool has been completely parsed.
85     //
86     ResolveDefinitions(LateResolveValues);
87
88     // Check to make sure that all global value forward references have been
89     // resolved!
90     //
91     if (!GlobalRefs.empty()) {
92       std::string UndefinedReferences = "Unresolved global references exist:\n";
93       
94       for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
95            I != E; ++I) {
96         UndefinedReferences += "  " + I->first.first->getDescription() + " " +
97                                I->first.second.getName() + "\n";
98       }
99       ThrowException(UndefinedReferences);
100     }
101
102     Values.clear();         // Clear out function local definitions
103     Types.clear();
104     CurrentModule = 0;
105   }
106
107
108   // DeclareNewGlobalValue - Called every time a new GV has been defined.  This
109   // is used to remove things from the forward declaration map, resolving them
110   // to the correct thing as needed.
111   //
112   void DeclareNewGlobalValue(GlobalValue *GV, ValID D) {
113     // Check to see if there is a forward reference to this global variable...
114     // if there is, eliminate it and patch the reference to use the new def'n.
115     GlobalRefsType::iterator I =
116       GlobalRefs.find(std::make_pair(GV->getType(), D));
117
118     if (I != GlobalRefs.end()) {
119       GlobalValue *OldGV = I->second;   // Get the placeholder...
120       I->first.second.destroy();  // Free string memory if necessary
121
122       // Replace all uses of the placeholder with the new GV
123       OldGV->replaceAllUsesWith(GV); 
124       
125       // Remove OldGV from the module...
126       if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(OldGV))
127         CurrentModule->getGlobalList().erase(GVar);
128       else
129         CurrentModule->getFunctionList().erase(cast<Function>(OldGV));
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 function being created
140
141   std::map<const Type*, ValueList> Values;   // Keep track of #'d definitions
142   std::map<const Type*, ValueList> LateResolveValues;
143   std::vector<PATypeHolder> Types;
144   std::map<ValID, PATypeHolder> LateResolveTypes;
145   SymbolTable LocalSymtab;
146   bool isDeclare;                // Is this function a forward declararation?
147
148   inline PerFunctionInfo() {
149     CurrentFunction = 0;
150     isDeclare = false;
151   }
152
153   inline void FunctionStart(Function *M) {
154     CurrentFunction = M;
155   }
156
157   void FunctionDone() {
158     // If we could not resolve some blocks at parsing time (forward branches)
159     // resolve the branches now...
160     ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
161
162     // Make sure to resolve any constant expr references that might exist within
163     // the function we just declared itself.
164     ValID FID;
165     if (CurrentFunction->hasName()) {
166       FID = ValID::create((char*)CurrentFunction->getName().c_str());
167     } else {
168       // Figure out which slot number if is...
169       ValueList &List = CurModule.Values[CurrentFunction->getType()];
170       for (unsigned i = 0; ; ++i) {
171         assert(i < List.size() && "Function not found!");
172         if (List[i] == CurrentFunction) {
173           FID = ValID::create((int)i);
174           break;
175         }
176       }
177     }
178     CurModule.DeclareNewGlobalValue(CurrentFunction, FID);
179
180     Values.clear();         // Clear out function local definitions
181     Types.clear();          // Clear out function local types
182     LocalSymtab.clear();    // Clear out function local symbol table
183     CurrentFunction = 0;
184     isDeclare = false;
185   }
186 } CurFun;  // Info for the current function...
187
188 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
189
190
191 //===----------------------------------------------------------------------===//
192 //               Code to handle definitions of all the types
193 //===----------------------------------------------------------------------===//
194
195 static int InsertValue(Value *V,
196                   std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
197   if (V->hasName()) return -1;           // Is this a numbered definition?
198
199   // Yes, insert the value into the value table...
200   ValueList &List = ValueTab[V->getType()];
201   List.push_back(V);
202   return List.size()-1;
203 }
204
205 // TODO: FIXME when Type are not const
206 static void InsertType(const Type *Ty, std::vector<PATypeHolder> &Types) {
207   Types.push_back(Ty);
208 }
209
210 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
211   switch (D.Type) {
212   case ValID::NumberVal: {                 // Is it a numbered definition?
213     unsigned Num = (unsigned)D.Num;
214
215     // Module constants occupy the lowest numbered slots...
216     if (Num < CurModule.Types.size()) 
217       return CurModule.Types[Num];
218
219     Num -= CurModule.Types.size();
220
221     // Check that the number is within bounds...
222     if (Num <= CurFun.Types.size())
223       return CurFun.Types[Num];
224     break;
225   }
226   case ValID::NameVal: {                // Is it a named definition?
227     std::string Name(D.Name);
228     SymbolTable *SymTab = 0;
229     Type *N = 0;
230     if (inFunctionScope()) {
231       SymTab = &CurFun.CurrentFunction->getSymbolTable();
232       N = SymTab->lookupType(Name);
233     }
234
235     if (N == 0) {
236       // Symbol table doesn't automatically chain yet... because the function
237       // hasn't been added to the module...
238       //
239       SymTab = &CurModule.CurrentModule->getSymbolTable();
240       N = SymTab->lookupType(Name);
241       if (N == 0) break;
242     }
243
244     D.destroy();  // Free old strdup'd memory...
245     return cast<Type>(N);
246   }
247   default:
248     ThrowException("Internal parser error: Invalid symbol type reference!");
249   }
250
251   // If we reached here, we referenced either a symbol that we don't know about
252   // or an id number that hasn't been read yet.  We may be referencing something
253   // forward, so just create an entry to be resolved later and get to it...
254   //
255   if (DoNotImprovise) return 0;  // Do we just want a null to be returned?
256
257   std::map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ? 
258     CurFun.LateResolveTypes : CurModule.LateResolveTypes;
259   
260   std::map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
261   if (I != LateResolver.end()) {
262     return I->second;
263   }
264
265   Type *Typ = OpaqueType::get();
266   LateResolver.insert(std::make_pair(D, Typ));
267   return Typ;
268 }
269
270 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
271   SymbolTable &SymTab = 
272     inFunctionScope() ? CurFun.CurrentFunction->getSymbolTable() :
273                         CurModule.CurrentModule->getSymbolTable();
274   return SymTab.lookup(Ty, Name);
275 }
276
277 // getValNonImprovising - Look up the value specified by the provided type and
278 // the provided ValID.  If the value exists and has already been defined, return
279 // it.  Otherwise return null.
280 //
281 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
282   if (isa<FunctionType>(Ty))
283     ThrowException("Functions are not values and "
284                    "must be referenced as pointers");
285
286   switch (D.Type) {
287   case ValID::NumberVal: {                 // Is it a numbered definition?
288     unsigned Num = (unsigned)D.Num;
289
290     // Module constants occupy the lowest numbered slots...
291     std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
292     if (VI != CurModule.Values.end()) {
293       if (Num < VI->second.size()) 
294         return VI->second[Num];
295       Num -= VI->second.size();
296     }
297
298     // Make sure that our type is within bounds
299     VI = CurFun.Values.find(Ty);
300     if (VI == CurFun.Values.end()) return 0;
301
302     // Check that the number is within bounds...
303     if (VI->second.size() <= Num) return 0;
304   
305     return VI->second[Num];
306   }
307
308   case ValID::NameVal: {                // Is it a named definition?
309     Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
310     if (N == 0) return 0;
311
312     D.destroy();  // Free old strdup'd memory...
313     return N;
314   }
315
316   // Check to make sure that "Ty" is an integral type, and that our 
317   // value will fit into the specified type...
318   case ValID::ConstSIntVal:    // Is it a constant pool reference??
319     if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64))
320       ThrowException("Signed integral constant '" +
321                      itostr(D.ConstPool64) + "' is invalid for type '" + 
322                      Ty->getDescription() + "'!");
323     return ConstantSInt::get(Ty, D.ConstPool64);
324
325   case ValID::ConstUIntVal:     // Is it an unsigned const pool reference?
326     if (!ConstantUInt::isValueValidForType(Ty, D.UConstPool64)) {
327       if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64)) {
328         ThrowException("Integral constant '" + utostr(D.UConstPool64) +
329                        "' is invalid or out of range!");
330       } else {     // This is really a signed reference.  Transmogrify.
331         return ConstantSInt::get(Ty, D.ConstPool64);
332       }
333     } else {
334       return ConstantUInt::get(Ty, D.UConstPool64);
335     }
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 (!isa<PointerType>(Ty))
344       ThrowException("Cannot create a a non pointer null!");
345     return ConstantPointerNull::get(cast<PointerType>(Ty));
346     
347   case ValID::ConstantVal:       // Fully resolved constant?
348     if (D.ConstantValue->getType() != Ty)
349       ThrowException("Constant expression type different from required type!");
350     return D.ConstantValue;
351
352   default:
353     assert(0 && "Unhandled case!");
354     return 0;
355   }   // End of switch
356
357   assert(0 && "Unhandled case!");
358   return 0;
359 }
360
361
362 // getVal - This function is identical to getValNonImprovising, except that if a
363 // value is not already defined, it "improvises" by creating a placeholder var
364 // that looks and acts just like the requested variable.  When the value is
365 // defined later, all uses of the placeholder variable are replaced with the
366 // real thing.
367 //
368 static Value *getVal(const Type *Ty, const ValID &D) {
369
370   // See if the value has already been defined...
371   Value *V = getValNonImprovising(Ty, D);
372   if (V) return V;
373
374   // If we reached here, we referenced either a symbol that we don't know about
375   // or an id number that hasn't been read yet.  We may be referencing something
376   // forward, so just create an entry to be resolved later and get to it...
377   //
378   Value *d = 0;
379   switch (Ty->getTypeID()) {
380   case Type::LabelTyID:  d = new   BBPlaceHolder(Ty, D); break;
381   default:               d = new ValuePlaceHolder(Ty, D); break;
382   }
383
384   assert(d != 0 && "How did we not make something?");
385   if (inFunctionScope())
386     InsertValue(d, CurFun.LateResolveValues);
387   else 
388     InsertValue(d, CurModule.LateResolveValues);
389   return d;
390 }
391
392
393 //===----------------------------------------------------------------------===//
394 //              Code to handle forward references in instructions
395 //===----------------------------------------------------------------------===//
396 //
397 // This code handles the late binding needed with statements that reference
398 // values not defined yet... for example, a forward branch, or the PHI node for
399 // a loop body.
400 //
401 // This keeps a table (CurFun.LateResolveValues) of all such forward references
402 // and back patchs after we are done.
403 //
404
405 // ResolveDefinitions - If we could not resolve some defs at parsing 
406 // time (forward branches, phi functions for loops, etc...) resolve the 
407 // defs now...
408 //
409 static void ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
410                                std::map<const Type*,ValueList> *FutureLateResolvers) {
411   // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
412   for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
413          E = LateResolvers.end(); LRI != E; ++LRI) {
414     ValueList &List = LRI->second;
415     while (!List.empty()) {
416       Value *V = List.back();
417       List.pop_back();
418       ValID &DID = getValIDFromPlaceHolder(V);
419
420       Value *TheRealValue = getValNonImprovising(LRI->first, DID);
421       if (TheRealValue) {
422         V->replaceAllUsesWith(TheRealValue);
423         delete V;
424       } else if (FutureLateResolvers) {
425         // Functions have their unresolved items forwarded to the module late
426         // resolver table
427         InsertValue(V, *FutureLateResolvers);
428       } else {
429         if (DID.Type == ValID::NameVal)
430           ThrowException("Reference to an invalid definition: '" +DID.getName()+
431                          "' of type '" + V->getType()->getDescription() + "'",
432                          getLineNumFromPlaceHolder(V));
433         else
434           ThrowException("Reference to an invalid definition: #" +
435                          itostr(DID.Num) + " of type '" + 
436                          V->getType()->getDescription() + "'",
437                          getLineNumFromPlaceHolder(V));
438       }
439     }
440   }
441
442   LateResolvers.clear();
443 }
444
445 // ResolveTypeTo - A brand new type was just declared.  This means that (if
446 // name is not null) things referencing Name can be resolved.  Otherwise, things
447 // refering to the number can be resolved.  Do this now.
448 //
449 static void ResolveTypeTo(char *Name, const Type *ToTy) {
450   std::vector<PATypeHolder> &Types = inFunctionScope() ? 
451      CurFun.Types : CurModule.Types;
452
453    ValID D;
454    if (Name) D = ValID::create(Name);
455    else      D = ValID::create((int)Types.size());
456
457    std::map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ? 
458      CurFun.LateResolveTypes : CurModule.LateResolveTypes;
459   
460    std::map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
461    if (I != LateResolver.end()) {
462      ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
463      LateResolver.erase(I);
464    }
465 }
466
467 // ResolveTypes - At this point, all types should be resolved.  Any that aren't
468 // are errors.
469 //
470 static void ResolveTypes(std::map<ValID, PATypeHolder> &LateResolveTypes) {
471   if (!LateResolveTypes.empty()) {
472     const ValID &DID = LateResolveTypes.begin()->first;
473
474     if (DID.Type == ValID::NameVal)
475       ThrowException("Reference to an invalid type: '" +DID.getName() + "'");
476     else
477       ThrowException("Reference to an invalid type: #" + itostr(DID.Num));
478   }
479 }
480
481
482 // setValueName - Set the specified value to the name given.  The name may be
483 // null potentially, in which case this is a noop.  The string passed in is
484 // assumed to be a malloc'd string buffer, and is freed by this function.
485 //
486 // This function returns true if the value has already been defined, but is
487 // allowed to be redefined in the specified context.  If the name is a new name
488 // for the typeplane, false is returned.
489 //
490 static bool setValueName(Value *V, char *NameStr) {
491   if (NameStr == 0) return false;
492   
493   std::string Name(NameStr);      // Copy string
494   free(NameStr);                  // Free old string
495
496   if (V->getType() == Type::VoidTy) 
497     ThrowException("Can't assign name '" + Name + 
498                    "' to a null valued instruction!");
499
500   SymbolTable &ST = inFunctionScope() ? 
501     CurFun.CurrentFunction->getSymbolTable() : 
502     CurModule.CurrentModule->getSymbolTable();
503
504   Value *Existing = ST.lookup(V->getType(), Name);
505
506   if (Existing) {    // Inserting a name that is already defined???
507     // We are a simple redefinition of a value, check to see if it
508     // is defined the same as the old one...
509     if (const Constant *C = dyn_cast<Constant>(Existing)) {
510       if (C == V) return true;      // Constants are equal to themselves
511     } else if (GlobalVariable *EGV = dyn_cast<GlobalVariable>(Existing)) {
512       // We are allowed to redefine a global variable in two circumstances:
513       // 1. If at least one of the globals is uninitialized or 
514       // 2. If both initializers have the same value.
515       //
516       if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
517         if (!EGV->hasInitializer() || !GV->hasInitializer() ||
518              EGV->getInitializer() == GV->getInitializer()) {
519
520           // Make sure the existing global version gets the initializer!  Make
521           // sure that it also gets marked const if the new version is.
522           if (GV->hasInitializer() && !EGV->hasInitializer())
523             EGV->setInitializer(GV->getInitializer());
524           if (GV->isConstant())
525             EGV->setConstant(true);
526           EGV->setLinkage(GV->getLinkage());
527           
528           delete GV;     // Destroy the duplicate!
529           return true;   // They are equivalent!
530         }
531       }
532     }
533
534     ThrowException("Redefinition of value named '" + Name + "' in the '" +
535                    V->getType()->getDescription() + "' type plane!");
536   }
537
538   // Set the name
539   V->setName(Name, &ST);
540
541   // If we're in function scope
542   if (inFunctionScope()) {
543     // Look up the symbol in the function's local symboltable
544     Existing = CurFun.LocalSymtab.lookup(V->getType(),Name);
545
546     // If it already exists
547     if (Existing) {
548       // Bail
549       ThrowException("Redefinition of value named '" + Name + "' in the '" +
550                    V->getType()->getDescription() + "' type plane!");
551
552     // otherwise, since it doesn't exist
553     } else {
554       // Insert it.
555       CurFun.LocalSymtab.insert(V);
556     }
557   }
558   return false;
559 }
560
561 // setTypeName - Set the specified type to the name given.  The name may be
562 // null potentially, in which case this is a noop.  The string passed in is
563 // assumed to be a malloc'd string buffer, and is freed by this function.
564 //
565 // This function returns true if the type has already been defined, but is
566 // allowed to be redefined in the specified context.  If the name is a new name
567 // for the type plane, it is inserted and false is returned.
568 static bool setTypeName(Type *T, char *NameStr) {
569   if (NameStr == 0) return false;
570   
571   std::string Name(NameStr);      // Copy string
572   free(NameStr);                  // Free old string
573
574   // We don't allow assigning names to void type
575   if (T == Type::VoidTy) 
576     ThrowException("Can't assign name '" + Name + "' to the null type!");
577
578   SymbolTable &ST = inFunctionScope() ? 
579     CurFun.CurrentFunction->getSymbolTable() : 
580     CurModule.CurrentModule->getSymbolTable();
581
582   Type *Existing = ST.lookupType(Name);
583
584   if (Existing) {    // Inserting a name that is already defined???
585     // There is only one case where this is allowed: when we are refining an
586     // opaque type.  In this case, Existing will be an opaque type.
587     if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
588       // We ARE replacing an opaque type!
589       ((OpaqueType*)OpTy)->refineAbstractTypeTo(T);
590       return true;
591     }
592
593     // Otherwise, this is an attempt to redefine a type. That's okay if
594     // the redefinition is identical to the original. This will be so if
595     // Existing and T point to the same Type object. In this one case we
596     // allow the equivalent redefinition.
597     if (Existing == T) return true;  // Yes, it's equal.
598
599     // Any other kind of (non-equivalent) redefinition is an error.
600     ThrowException("Redefinition of type named '" + Name + "' in the '" +
601                    T->getDescription() + "' type plane!");
602   }
603
604   // Okay, its a newly named type. Set its name.
605   if (!Name.empty()) ST.insert(Name, T);
606
607   // If we're in function scope
608   if (inFunctionScope()) {
609     // Look up the symbol in the function's local symboltable
610     Existing = CurFun.LocalSymtab.lookupType(Name);
611
612     // If it already exists
613     if (Existing) {
614       // Bail
615       ThrowException("Redefinition of type named '" + Name + "' in the '" +
616                    T->getDescription() + "' type plane in function scope!");
617
618     // otherwise, since it doesn't exist
619     } else {
620       // Insert it.
621       CurFun.LocalSymtab.insert(Name,T);
622     }
623   }
624   return false;
625 }
626
627 //===----------------------------------------------------------------------===//
628 // Code for handling upreferences in type names...
629 //
630
631 // TypeContains - Returns true if Ty directly contains E in it.
632 //
633 static bool TypeContains(const Type *Ty, const Type *E) {
634   return find(Ty->subtype_begin(), Ty->subtype_end(), E) != Ty->subtype_end();
635 }
636
637 namespace {
638   struct UpRefRecord {
639     // NestingLevel - The number of nesting levels that need to be popped before
640     // this type is resolved.
641     unsigned NestingLevel;
642     
643     // LastContainedTy - This is the type at the current binding level for the
644     // type.  Every time we reduce the nesting level, this gets updated.
645     const Type *LastContainedTy;
646
647     // UpRefTy - This is the actual opaque type that the upreference is
648     // represented with.
649     OpaqueType *UpRefTy;
650
651     UpRefRecord(unsigned NL, OpaqueType *URTy)
652       : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
653   };
654 }
655
656 // UpRefs - A list of the outstanding upreferences that need to be resolved.
657 static std::vector<UpRefRecord> UpRefs;
658
659 /// HandleUpRefs - Every time we finish a new layer of types, this function is
660 /// called.  It loops through the UpRefs vector, which is a list of the
661 /// currently active types.  For each type, if the up reference is contained in
662 /// the newly completed type, we decrement the level count.  When the level
663 /// count reaches zero, the upreferenced type is the type that is passed in:
664 /// thus we can complete the cycle.
665 ///
666 static PATypeHolder HandleUpRefs(const Type *ty) {
667   if (!ty->isAbstract()) return ty;
668   PATypeHolder Ty(ty);
669   UR_OUT("Type '" << Ty->getDescription() << 
670          "' newly formed.  Resolving upreferences.\n" <<
671          UpRefs.size() << " upreferences active!\n");
672
673   // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
674   // to zero), we resolve them all together before we resolve them to Ty.  At
675   // the end of the loop, if there is anything to resolve to Ty, it will be in
676   // this variable.
677   OpaqueType *TypeToResolve = 0;
678
679   for (unsigned i = 0; i != UpRefs.size(); ++i) {
680     UR_OUT("  UR#" << i << " - TypeContains(" << Ty->getDescription() << ", " 
681            << UpRefs[i].second->getDescription() << ") = " 
682            << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
683     if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
684       // Decrement level of upreference
685       unsigned Level = --UpRefs[i].NestingLevel;
686       UpRefs[i].LastContainedTy = Ty;
687       UR_OUT("  Uplevel Ref Level = " << Level << "\n");
688       if (Level == 0) {                     // Upreference should be resolved! 
689         if (!TypeToResolve) {
690           TypeToResolve = UpRefs[i].UpRefTy;
691         } else {
692           UR_OUT("  * Resolving upreference for "
693                  << UpRefs[i].second->getDescription() << "\n";
694                  std::string OldName = UpRefs[i].UpRefTy->getDescription());
695           UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
696           UR_OUT("  * Type '" << OldName << "' refined upreference to: "
697                  << (const void*)Ty << ", " << Ty->getDescription() << "\n");
698         }
699         UpRefs.erase(UpRefs.begin()+i);     // Remove from upreference list...
700         --i;                                // Do not skip the next element...
701       }
702     }
703   }
704
705   if (TypeToResolve) {
706     UR_OUT("  * Resolving upreference for "
707            << UpRefs[i].second->getDescription() << "\n";
708            std::string OldName = TypeToResolve->getDescription());
709     TypeToResolve->refineAbstractTypeTo(Ty);
710   }
711
712   return Ty;
713 }
714
715
716 //===----------------------------------------------------------------------===//
717 //            RunVMAsmParser - Define an interface to this parser
718 //===----------------------------------------------------------------------===//
719 //
720 Module *RunVMAsmParser(const std::string &Filename, FILE *F) {
721   llvmAsmin = F;
722   CurFilename = Filename;
723   llvmAsmlineno = 1;      // Reset the current line number...
724   ObsoleteVarArgs = false;
725
726   // Allocate a new module to read
727   CurModule.CurrentModule = new Module(Filename);
728
729   try {
730     yyparse();       // Parse the file.
731   } catch (...) {
732     // Clear the symbol table so it doesn't complain when it
733     // gets destructed
734     CurFun.LocalSymtab.clear();
735     throw;
736   }
737
738   Module *Result = ParserResult;
739
740   // Check to see if they called va_start but not va_arg..
741   if (!ObsoleteVarArgs)
742     if (Function *F = Result->getNamedFunction("llvm.va_start"))
743       if (F->asize() == 1) {
744         std::cerr << "WARNING: this file uses obsolete features.  "
745                   << "Assemble and disassemble to update it.\n";
746         ObsoleteVarArgs = true;
747       }
748
749
750   if (ObsoleteVarArgs) {
751     // If the user is making use of obsolete varargs intrinsics, adjust them for
752     // the user.
753     if (Function *F = Result->getNamedFunction("llvm.va_start")) {
754       assert(F->asize() == 1 && "Obsolete va_start takes 1 argument!");
755
756       const Type *RetTy = F->getFunctionType()->getParamType(0);
757       RetTy = cast<PointerType>(RetTy)->getElementType();
758       Function *NF = Result->getOrInsertFunction("llvm.va_start", RetTy, 0);
759       
760       while (!F->use_empty()) {
761         CallInst *CI = cast<CallInst>(F->use_back());
762         Value *V = new CallInst(NF, "", CI);
763         new StoreInst(V, CI->getOperand(1), CI);
764         CI->getParent()->getInstList().erase(CI);
765       }
766       Result->getFunctionList().erase(F);
767     }
768     
769     if (Function *F = Result->getNamedFunction("llvm.va_end")) {
770       assert(F->asize() == 1 && "Obsolete va_end takes 1 argument!");
771       const Type *ArgTy = F->getFunctionType()->getParamType(0);
772       ArgTy = cast<PointerType>(ArgTy)->getElementType();
773       Function *NF = Result->getOrInsertFunction("llvm.va_end", Type::VoidTy,
774                                                  ArgTy, 0);
775
776       while (!F->use_empty()) {
777         CallInst *CI = cast<CallInst>(F->use_back());
778         Value *V = new LoadInst(CI->getOperand(1), "", CI);
779         new CallInst(NF, V, "", CI);
780         CI->getParent()->getInstList().erase(CI);
781       }
782       Result->getFunctionList().erase(F);
783     }
784
785     if (Function *F = Result->getNamedFunction("llvm.va_copy")) {
786       assert(F->asize() == 2 && "Obsolete va_copy takes 2 argument!");
787       const Type *ArgTy = F->getFunctionType()->getParamType(0);
788       ArgTy = cast<PointerType>(ArgTy)->getElementType();
789       Function *NF = Result->getOrInsertFunction("llvm.va_copy", ArgTy,
790                                                  ArgTy, 0);
791
792       while (!F->use_empty()) {
793         CallInst *CI = cast<CallInst>(F->use_back());
794         Value *V = new CallInst(NF, CI->getOperand(2), "", CI);
795         new StoreInst(V, CI->getOperand(1), CI);
796         CI->getParent()->getInstList().erase(CI);
797       }
798       Result->getFunctionList().erase(F);
799     }
800   }
801
802   llvmAsmin = stdin;    // F is about to go away, don't use it anymore...
803   ParserResult = 0;
804
805   return Result;
806 }
807
808 } // End llvm namespace
809
810 using namespace llvm;
811
812 %}
813
814 %union {
815   llvm::Module                           *ModuleVal;
816   llvm::Function                         *FunctionVal;
817   std::pair<llvm::PATypeHolder*, char*>  *ArgVal;
818   llvm::BasicBlock                       *BasicBlockVal;
819   llvm::TerminatorInst                   *TermInstVal;
820   llvm::Instruction                      *InstVal;
821   llvm::Constant                         *ConstVal;
822
823   const llvm::Type                       *PrimType;
824   llvm::PATypeHolder                     *TypeVal;
825   llvm::Value                            *ValueVal;
826
827   std::vector<std::pair<llvm::PATypeHolder*,char*> > *ArgList;
828   std::vector<llvm::Value*>              *ValueList;
829   std::list<llvm::PATypeHolder>          *TypeList;
830   std::list<std::pair<llvm::Value*,
831                       llvm::BasicBlock*> > *PHIList; // Represent the RHS of PHI node
832   std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
833   std::vector<llvm::Constant*>           *ConstVector;
834
835   llvm::GlobalValue::LinkageTypes         Linkage;
836   int64_t                           SInt64Val;
837   uint64_t                          UInt64Val;
838   int                               SIntVal;
839   unsigned                          UIntVal;
840   double                            FPVal;
841   bool                              BoolVal;
842
843   char                             *StrVal;   // This memory is strdup'd!
844   llvm::ValID                             ValIDVal; // strdup'd memory maybe!
845
846   llvm::Instruction::BinaryOps            BinaryOpVal;
847   llvm::Instruction::TermOps              TermOpVal;
848   llvm::Instruction::MemoryOps            MemOpVal;
849   llvm::Instruction::OtherOps             OtherOpVal;
850   llvm::Module::Endianness                Endianness;
851 }
852
853 %type <ModuleVal>     Module FunctionList
854 %type <FunctionVal>   Function FunctionProto FunctionHeader BasicBlockList
855 %type <BasicBlockVal> BasicBlock InstructionList
856 %type <TermInstVal>   BBTerminatorInst
857 %type <InstVal>       Inst InstVal MemoryInst
858 %type <ConstVal>      ConstVal ConstExpr
859 %type <ConstVector>   ConstVector
860 %type <ArgList>       ArgList ArgListH
861 %type <ArgVal>        ArgVal
862 %type <PHIList>       PHIList
863 %type <ValueList>     ValueRefList ValueRefListE  // For call param lists
864 %type <ValueList>     IndexList                   // For GEP derived indices
865 %type <TypeList>      TypeListI ArgTypeListI
866 %type <JumpTable>     JumpTable
867 %type <BoolVal>       GlobalType                  // GLOBAL or CONSTANT?
868 %type <BoolVal>       OptVolatile                 // 'volatile' or not
869 %type <Linkage>       OptLinkage
870 %type <Endianness>    BigOrLittle
871
872 // ValueRef - Unresolved reference to a definition or BB
873 %type <ValIDVal>      ValueRef ConstValueRef SymbolicValueRef
874 %type <ValueVal>      ResolvedVal            // <type> <valref> pair
875 // Tokens and types for handling constant integer values
876 //
877 // ESINT64VAL - A negative number within long long range
878 %token <SInt64Val> ESINT64VAL
879
880 // EUINT64VAL - A positive number within uns. long long range
881 %token <UInt64Val> EUINT64VAL
882 %type  <SInt64Val> EINT64VAL
883
884 %token  <SIntVal>   SINTVAL   // Signed 32 bit ints...
885 %token  <UIntVal>   UINTVAL   // Unsigned 32 bit ints...
886 %type   <SIntVal>   INTVAL
887 %token  <FPVal>     FPVAL     // Float or Double constant
888
889 // Built in types...
890 %type  <TypeVal> Types TypesV UpRTypes UpRTypesV
891 %type  <PrimType> SIntType UIntType IntType FPType PrimType   // Classifications
892 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
893 %token <PrimType> FLOAT DOUBLE TYPE LABEL
894
895 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
896 %type  <StrVal> Name OptName OptAssign
897
898
899 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
900 %token DECLARE GLOBAL CONSTANT VOLATILE
901 %token TO DOTDOTDOT NULL_TOK CONST INTERNAL LINKONCE WEAK  APPENDING
902 %token OPAQUE NOT EXTERNAL TARGET ENDIAN POINTERSIZE LITTLE BIG
903
904 // Basic Block Terminating Operators 
905 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND
906
907 // Binary Operators 
908 %type  <BinaryOpVal> BinaryOps  // all the binary operators
909 %type  <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
910 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
911 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE  // Binary Comarators
912
913 // Memory Instructions
914 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
915
916 // Other Operators
917 %type  <OtherOpVal> ShiftOps
918 %token <OtherOpVal> PHI_TOK CALL CAST SELECT SHL SHR VAARG VANEXT
919 %token VA_ARG // FIXME: OBSOLETE
920
921 %start Module
922 %%
923
924 // Handle constant integer size restriction and conversion...
925 //
926 INTVAL : SINTVAL;
927 INTVAL : UINTVAL {
928   if ($1 > (uint32_t)INT32_MAX)     // Outside of my range!
929     ThrowException("Value too large for type!");
930   $$ = (int32_t)$1;
931 };
932
933
934 EINT64VAL : ESINT64VAL;      // These have same type and can't cause problems...
935 EINT64VAL : EUINT64VAL {
936   if ($1 > (uint64_t)INT64_MAX)     // Outside of my range!
937     ThrowException("Value too large for type!");
938   $$ = (int64_t)$1;
939 };
940
941 // Operations that are notably excluded from this list include: 
942 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
943 //
944 ArithmeticOps: ADD | SUB | MUL | DIV | REM;
945 LogicalOps   : AND | OR | XOR;
946 SetCondOps   : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
947 BinaryOps : ArithmeticOps | LogicalOps | SetCondOps;
948
949 ShiftOps  : SHL | SHR;
950
951 // These are some types that allow classification if we only want a particular 
952 // thing... for example, only a signed, unsigned, or integral type.
953 SIntType :  LONG |  INT |  SHORT | SBYTE;
954 UIntType : ULONG | UINT | USHORT | UBYTE;
955 IntType  : SIntType | UIntType;
956 FPType   : FLOAT | DOUBLE;
957
958 // OptAssign - Value producing statements have an optional assignment component
959 OptAssign : Name '=' {
960     $$ = $1;
961   }
962   | /*empty*/ { 
963     $$ = 0; 
964   };
965
966 OptLinkage : INTERNAL  { $$ = GlobalValue::InternalLinkage; } |
967              LINKONCE  { $$ = GlobalValue::LinkOnceLinkage; } |
968              WEAK      { $$ = GlobalValue::WeakLinkage; } |
969              APPENDING { $$ = GlobalValue::AppendingLinkage; } |
970              /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
971
972 //===----------------------------------------------------------------------===//
973 // Types includes all predefined types... except void, because it can only be
974 // used in specific contexts (function returning void for example).  To have
975 // access to it, a user must explicitly use TypesV.
976 //
977
978 // TypesV includes all of 'Types', but it also includes the void type.
979 TypesV    : Types    | VOID { $$ = new PATypeHolder($1); };
980 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
981
982 Types     : UpRTypes {
983     if (!UpRefs.empty())
984       ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
985     $$ = $1;
986   };
987
988
989 // Derived types are added later...
990 //
991 PrimType : BOOL | SBYTE | UBYTE | SHORT  | USHORT | INT   | UINT ;
992 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE   | LABEL;
993 UpRTypes : OPAQUE {
994     $$ = new PATypeHolder(OpaqueType::get());
995   }
996   | PrimType {
997     $$ = new PATypeHolder($1);
998   };
999 UpRTypes : SymbolicValueRef {            // Named types are also simple types...
1000   $$ = new PATypeHolder(getTypeVal($1));
1001 };
1002
1003 // Include derived types in the Types production.
1004 //
1005 UpRTypes : '\\' EUINT64VAL {                   // Type UpReference
1006     if ($2 > (uint64_t)~0U) ThrowException("Value out of range!");
1007     OpaqueType *OT = OpaqueType::get();        // Use temporary placeholder
1008     UpRefs.push_back(UpRefRecord((unsigned)$2, OT));  // Add to vector...
1009     $$ = new PATypeHolder(OT);
1010     UR_OUT("New Upreference!\n");
1011   }
1012   | UpRTypesV '(' ArgTypeListI ')' {           // Function derived type?
1013     std::vector<const Type*> Params;
1014     mapto($3->begin(), $3->end(), std::back_inserter(Params), 
1015           std::mem_fun_ref(&PATypeHolder::get));
1016     bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1017     if (isVarArg) Params.pop_back();
1018
1019     $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
1020     delete $3;      // Delete the argument list
1021     delete $1;      // Delete the return type handle
1022   }
1023   | '[' EUINT64VAL 'x' UpRTypes ']' {          // Sized array type?
1024     $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1025     delete $4;
1026   }
1027   | '{' TypeListI '}' {                        // Structure type?
1028     std::vector<const Type*> Elements;
1029     mapto($2->begin(), $2->end(), std::back_inserter(Elements), 
1030         std::mem_fun_ref(&PATypeHolder::get));
1031
1032     $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1033     delete $2;
1034   }
1035   | '{' '}' {                                  // Empty structure type?
1036     $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1037   }
1038   | UpRTypes '*' {                             // Pointer type?
1039     $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1040     delete $1;
1041   };
1042
1043 // TypeList - Used for struct declarations and as a basis for function type 
1044 // declaration type lists
1045 //
1046 TypeListI : UpRTypes {
1047     $$ = new std::list<PATypeHolder>();
1048     $$->push_back(*$1); delete $1;
1049   }
1050   | TypeListI ',' UpRTypes {
1051     ($$=$1)->push_back(*$3); delete $3;
1052   };
1053
1054 // ArgTypeList - List of types for a function type declaration...
1055 ArgTypeListI : TypeListI
1056   | TypeListI ',' DOTDOTDOT {
1057     ($$=$1)->push_back(Type::VoidTy);
1058   }
1059   | DOTDOTDOT {
1060     ($$ = new std::list<PATypeHolder>())->push_back(Type::VoidTy);
1061   }
1062   | /*empty*/ {
1063     $$ = new std::list<PATypeHolder>();
1064   };
1065
1066 // ConstVal - The various declarations that go into the constant pool.  This
1067 // production is used ONLY to represent constants that show up AFTER a 'const',
1068 // 'constant' or 'global' token at global scope.  Constants that can be inlined
1069 // into other expressions (such as integers and constexprs) are handled by the
1070 // ResolvedVal, ValueRef and ConstValueRef productions.
1071 //
1072 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1073     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1074     if (ATy == 0)
1075       ThrowException("Cannot make array constant with type: '" + 
1076                      (*$1)->getDescription() + "'!");
1077     const Type *ETy = ATy->getElementType();
1078     int NumElements = ATy->getNumElements();
1079
1080     // Verify that we have the correct size...
1081     if (NumElements != -1 && NumElements != (int)$3->size())
1082       ThrowException("Type mismatch: constant sized array initialized with " +
1083                      utostr($3->size()) +  " arguments, but has size of " + 
1084                      itostr(NumElements) + "!");
1085
1086     // Verify all elements are correct type!
1087     for (unsigned i = 0; i < $3->size(); i++) {
1088       if (ETy != (*$3)[i]->getType())
1089         ThrowException("Element #" + utostr(i) + " is not of type '" + 
1090                        ETy->getDescription() +"' as required!\nIt is of type '"+
1091                        (*$3)[i]->getType()->getDescription() + "'.");
1092     }
1093
1094     $$ = ConstantArray::get(ATy, *$3);
1095     delete $1; delete $3;
1096   }
1097   | Types '[' ']' {
1098     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1099     if (ATy == 0)
1100       ThrowException("Cannot make array constant with type: '" + 
1101                      (*$1)->getDescription() + "'!");
1102
1103     int NumElements = ATy->getNumElements();
1104     if (NumElements != -1 && NumElements != 0) 
1105       ThrowException("Type mismatch: constant sized array initialized with 0"
1106                      " arguments, but has size of " + itostr(NumElements) +"!");
1107     $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1108     delete $1;
1109   }
1110   | Types 'c' STRINGCONSTANT {
1111     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1112     if (ATy == 0)
1113       ThrowException("Cannot make array constant with type: '" + 
1114                      (*$1)->getDescription() + "'!");
1115
1116     int NumElements = ATy->getNumElements();
1117     const Type *ETy = ATy->getElementType();
1118     char *EndStr = UnEscapeLexed($3, true);
1119     if (NumElements != -1 && NumElements != (EndStr-$3))
1120       ThrowException("Can't build string constant of size " + 
1121                      itostr((int)(EndStr-$3)) +
1122                      " when array has size " + itostr(NumElements) + "!");
1123     std::vector<Constant*> Vals;
1124     if (ETy == Type::SByteTy) {
1125       for (char *C = $3; C != EndStr; ++C)
1126         Vals.push_back(ConstantSInt::get(ETy, *C));
1127     } else if (ETy == Type::UByteTy) {
1128       for (char *C = $3; C != EndStr; ++C)
1129         Vals.push_back(ConstantUInt::get(ETy, (unsigned char)*C));
1130     } else {
1131       free($3);
1132       ThrowException("Cannot build string arrays of non byte sized elements!");
1133     }
1134     free($3);
1135     $$ = ConstantArray::get(ATy, Vals);
1136     delete $1;
1137   }
1138   | Types '{' ConstVector '}' {
1139     const StructType *STy = dyn_cast<StructType>($1->get());
1140     if (STy == 0)
1141       ThrowException("Cannot make struct constant with type: '" + 
1142                      (*$1)->getDescription() + "'!");
1143
1144     if ($3->size() != STy->getNumContainedTypes())
1145       ThrowException("Illegal number of initializers for structure type!");
1146
1147     // Check to ensure that constants are compatible with the type initializer!
1148     for (unsigned i = 0, e = $3->size(); i != e; ++i)
1149       if ((*$3)[i]->getType() != STy->getElementType(i))
1150         ThrowException("Expected type '" +
1151                        STy->getElementType(i)->getDescription() +
1152                        "' for element #" + utostr(i) +
1153                        " of structure initializer!");
1154
1155     $$ = ConstantStruct::get(STy, *$3);
1156     delete $1; delete $3;
1157   }
1158   | Types '{' '}' {
1159     const StructType *STy = dyn_cast<StructType>($1->get());
1160     if (STy == 0)
1161       ThrowException("Cannot make struct constant with type: '" + 
1162                      (*$1)->getDescription() + "'!");
1163
1164     if (STy->getNumContainedTypes() != 0)
1165       ThrowException("Illegal number of initializers for structure type!");
1166
1167     $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1168     delete $1;
1169   }
1170   | Types NULL_TOK {
1171     const PointerType *PTy = dyn_cast<PointerType>($1->get());
1172     if (PTy == 0)
1173       ThrowException("Cannot make null pointer constant with type: '" + 
1174                      (*$1)->getDescription() + "'!");
1175
1176     $$ = ConstantPointerNull::get(PTy);
1177     delete $1;
1178   }
1179   | Types SymbolicValueRef {
1180     const PointerType *Ty = dyn_cast<PointerType>($1->get());
1181     if (Ty == 0)
1182       ThrowException("Global const reference must be a pointer type!");
1183
1184     // ConstExprs can exist in the body of a function, thus creating
1185     // ConstantPointerRefs whenever they refer to a variable.  Because we are in
1186     // the context of a function, getValNonImprovising will search the functions
1187     // symbol table instead of the module symbol table for the global symbol,
1188     // which throws things all off.  To get around this, we just tell
1189     // getValNonImprovising that we are at global scope here.
1190     //
1191     Function *SavedCurFn = CurFun.CurrentFunction;
1192     CurFun.CurrentFunction = 0;
1193
1194     Value *V = getValNonImprovising(Ty, $2);
1195
1196     CurFun.CurrentFunction = SavedCurFn;
1197
1198     // If this is an initializer for a constant pointer, which is referencing a
1199     // (currently) undefined variable, create a stub now that shall be replaced
1200     // in the future with the right type of variable.
1201     //
1202     if (V == 0) {
1203       assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1204       const PointerType *PT = cast<PointerType>(Ty);
1205
1206       // First check to see if the forward references value is already created!
1207       PerModuleInfo::GlobalRefsType::iterator I =
1208         CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1209     
1210       if (I != CurModule.GlobalRefs.end()) {
1211         V = I->second;             // Placeholder already exists, use it...
1212         $2.destroy();
1213       } else {
1214         // Create a placeholder for the global variable reference...
1215         GlobalVariable *GV = new GlobalVariable(PT->getElementType(),
1216                                                 false,
1217                                                 GlobalValue::ExternalLinkage);
1218         // Keep track of the fact that we have a forward ref to recycle it
1219         CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1220
1221         // Must temporarily push this value into the module table...
1222         CurModule.CurrentModule->getGlobalList().push_back(GV);
1223         V = GV;
1224       }
1225     }
1226
1227     GlobalValue *GV = cast<GlobalValue>(V);
1228     $$ = ConstantPointerRef::get(GV);
1229     delete $1;            // Free the type handle
1230   }
1231   | Types ConstExpr {
1232     if ($1->get() != $2->getType())
1233       ThrowException("Mismatched types for constant expression!");
1234     $$ = $2;
1235     delete $1;
1236   }
1237   | Types ZEROINITIALIZER {
1238     $$ = Constant::getNullValue($1->get());
1239     delete $1;
1240   };
1241
1242 ConstVal : SIntType EINT64VAL {      // integral constants
1243     if (!ConstantSInt::isValueValidForType($1, $2))
1244       ThrowException("Constant value doesn't fit in type!");
1245     $$ = ConstantSInt::get($1, $2);
1246   }
1247   | UIntType EUINT64VAL {            // integral constants
1248     if (!ConstantUInt::isValueValidForType($1, $2))
1249       ThrowException("Constant value doesn't fit in type!");
1250     $$ = ConstantUInt::get($1, $2);
1251   }
1252   | BOOL TRUETOK {                      // Boolean constants
1253     $$ = ConstantBool::True;
1254   }
1255   | BOOL FALSETOK {                     // Boolean constants
1256     $$ = ConstantBool::False;
1257   }
1258   | FPType FPVAL {                   // Float & Double constants
1259     $$ = ConstantFP::get($1, $2);
1260   };
1261
1262
1263 ConstExpr: CAST '(' ConstVal TO Types ')' {
1264     if (!$3->getType()->isFirstClassType())
1265       ThrowException("cast constant expression from a non-primitive type: '" +
1266                      $3->getType()->getDescription() + "'!");
1267     if (!$5->get()->isFirstClassType())
1268       ThrowException("cast constant expression to a non-primitive type: '" +
1269                      $5->get()->getDescription() + "'!");
1270     $$ = ConstantExpr::getCast($3, $5->get());
1271     delete $5;
1272   }
1273   | GETELEMENTPTR '(' ConstVal IndexList ')' {
1274     if (!isa<PointerType>($3->getType()))
1275       ThrowException("GetElementPtr requires a pointer operand!");
1276
1277     // LLVM 1.2 and earlier used ubyte struct indices.  Convert any ubyte struct
1278     // indices to uint struct indices for compatibility.
1279     generic_gep_type_iterator<std::vector<Value*>::iterator>
1280       GTI = gep_type_begin($3->getType(), $4->begin(), $4->end()),
1281       GTE = gep_type_end($3->getType(), $4->begin(), $4->end());
1282     for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
1283       if (isa<StructType>(*GTI))        // Only change struct indices
1284         if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
1285           if (CUI->getType() == Type::UByteTy)
1286             (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
1287
1288     const Type *IdxTy =
1289       GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1290     if (!IdxTy)
1291       ThrowException("Index list invalid for constant getelementptr!");
1292
1293     std::vector<Constant*> IdxVec;
1294     for (unsigned i = 0, e = $4->size(); i != e; ++i)
1295       if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1296         IdxVec.push_back(C);
1297       else
1298         ThrowException("Indices to constant getelementptr must be constants!");
1299
1300     delete $4;
1301
1302     $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1303   }
1304   | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1305     if ($3->getType() != Type::BoolTy)
1306       ThrowException("Select condition must be of boolean type!");
1307     if ($5->getType() != $7->getType())
1308       ThrowException("Select operand types must match!");
1309     $$ = ConstantExpr::getSelect($3, $5, $7);
1310   }
1311   | BinaryOps '(' ConstVal ',' ConstVal ')' {
1312     if ($3->getType() != $5->getType())
1313       ThrowException("Binary operator types must match!");
1314     $$ = ConstantExpr::get($1, $3, $5);
1315   }
1316   | ShiftOps '(' ConstVal ',' ConstVal ')' {
1317     if ($5->getType() != Type::UByteTy)
1318       ThrowException("Shift count for shift constant must be unsigned byte!");
1319     if (!$3->getType()->isInteger())
1320       ThrowException("Shift constant expression requires integer operand!");
1321     $$ = ConstantExpr::get($1, $3, $5);
1322   };
1323
1324
1325 // ConstVector - A list of comma separated constants.
1326 ConstVector : ConstVector ',' ConstVal {
1327     ($$ = $1)->push_back($3);
1328   }
1329   | ConstVal {
1330     $$ = new std::vector<Constant*>();
1331     $$->push_back($1);
1332   };
1333
1334
1335 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1336 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1337
1338
1339 //===----------------------------------------------------------------------===//
1340 //                             Rules to match Modules
1341 //===----------------------------------------------------------------------===//
1342
1343 // Module rule: Capture the result of parsing the whole file into a result
1344 // variable...
1345 //
1346 Module : FunctionList {
1347   $$ = ParserResult = $1;
1348   CurModule.ModuleDone();
1349 };
1350
1351 // FunctionList - A list of functions, preceeded by a constant pool.
1352 //
1353 FunctionList : FunctionList Function {
1354     $$ = $1;
1355     CurFun.FunctionDone();
1356   } 
1357   | FunctionList FunctionProto {
1358     $$ = $1;
1359   }
1360   | FunctionList IMPLEMENTATION {
1361     $$ = $1;
1362   }
1363   | ConstPool {
1364     $$ = CurModule.CurrentModule;
1365     // Resolve circular types before we parse the body of the module
1366     ResolveTypes(CurModule.LateResolveTypes);
1367   };
1368
1369 // ConstPool - Constants with optional names assigned to them.
1370 ConstPool : ConstPool OptAssign CONST ConstVal { 
1371     if (!setValueName($4, $2))
1372       InsertValue($4);
1373   }
1374   | ConstPool OptAssign TYPE TypesV {  // Types can be defined in the const pool
1375     // Eagerly resolve types.  This is not an optimization, this is a
1376     // requirement that is due to the fact that we could have this:
1377     //
1378     // %list = type { %list * }
1379     // %list = type { %list * }    ; repeated type decl
1380     //
1381     // If types are not resolved eagerly, then the two types will not be
1382     // determined to be the same type!
1383     //
1384     ResolveTypeTo($2, $4->get());
1385
1386     // TODO: FIXME when Type are not const
1387     if (!setTypeName(const_cast<Type*>($4->get()), $2)) {
1388       // If this is not a redefinition of a type...
1389       if (!$2) {
1390         InsertType($4->get(),
1391                    inFunctionScope() ? CurFun.Types : CurModule.Types);
1392       }
1393     }
1394
1395     delete $4;
1396   }
1397   | ConstPool FunctionProto {       // Function prototypes can be in const pool
1398   }
1399   | ConstPool OptAssign OptLinkage GlobalType ConstVal {
1400     const Type *Ty = $5->getType();
1401     // Global declarations appear in Constant Pool
1402     Constant *Initializer = $5;
1403     if (Initializer == 0)
1404       ThrowException("Global value initializer is not a constant!");
1405     
1406     GlobalVariable *GV = new GlobalVariable(Ty, $4, $3, Initializer);
1407     if (!setValueName(GV, $2)) {   // If not redefining...
1408       CurModule.CurrentModule->getGlobalList().push_back(GV);
1409       int Slot = InsertValue(GV, CurModule.Values);
1410
1411       if (Slot != -1) {
1412         CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1413       } else {
1414         CurModule.DeclareNewGlobalValue(GV, ValID::create(
1415                                                 (char*)GV->getName().c_str()));
1416       }
1417     }
1418   }
1419   | ConstPool OptAssign EXTERNAL GlobalType Types {
1420     const Type *Ty = *$5;
1421     // Global declarations appear in Constant Pool
1422     GlobalVariable *GV = new GlobalVariable(Ty,$4,GlobalValue::ExternalLinkage);
1423     if (!setValueName(GV, $2)) {   // If not redefining...
1424       CurModule.CurrentModule->getGlobalList().push_back(GV);
1425       int Slot = InsertValue(GV, CurModule.Values);
1426
1427       if (Slot != -1) {
1428         CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1429       } else {
1430         assert(GV->hasName() && "Not named and not numbered!?");
1431         CurModule.DeclareNewGlobalValue(GV, ValID::create(
1432                                                 (char*)GV->getName().c_str()));
1433       }
1434     }
1435     delete $5;
1436   }
1437   | ConstPool TARGET TargetDefinition { 
1438   }
1439   | /* empty: end of list */ { 
1440   };
1441
1442
1443
1444 BigOrLittle : BIG    { $$ = Module::BigEndian; };
1445 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1446
1447 TargetDefinition : ENDIAN '=' BigOrLittle {
1448     CurModule.CurrentModule->setEndianness($3);
1449   }
1450   | POINTERSIZE '=' EUINT64VAL {
1451     if ($3 == 32)
1452       CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1453     else if ($3 == 64)
1454       CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1455     else
1456       ThrowException("Invalid pointer size: '" + utostr($3) + "'!");
1457   };
1458
1459
1460 //===----------------------------------------------------------------------===//
1461 //                       Rules to match Function Headers
1462 //===----------------------------------------------------------------------===//
1463
1464 Name : VAR_ID | STRINGCONSTANT;
1465 OptName : Name | /*empty*/ { $$ = 0; };
1466
1467 ArgVal : Types OptName {
1468   if (*$1 == Type::VoidTy)
1469     ThrowException("void typed arguments are invalid!");
1470   $$ = new std::pair<PATypeHolder*, char*>($1, $2);
1471 };
1472
1473 ArgListH : ArgListH ',' ArgVal {
1474     $$ = $1;
1475     $1->push_back(*$3);
1476     delete $3;
1477   }
1478   | ArgVal {
1479     $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1480     $$->push_back(*$1);
1481     delete $1;
1482   };
1483
1484 ArgList : ArgListH {
1485     $$ = $1;
1486   }
1487   | ArgListH ',' DOTDOTDOT {
1488     $$ = $1;
1489     $$->push_back(std::pair<PATypeHolder*,
1490                             char*>(new PATypeHolder(Type::VoidTy), 0));
1491   }
1492   | DOTDOTDOT {
1493     $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1494     $$->push_back(std::make_pair(new PATypeHolder(Type::VoidTy), (char*)0));
1495   }
1496   | /* empty */ {
1497     $$ = 0;
1498   };
1499
1500 FunctionHeaderH : TypesV Name '(' ArgList ')' {
1501   UnEscapeLexed($2);
1502   std::string FunctionName($2);
1503   
1504   if (!(*$1)->isFirstClassType() && *$1 != Type::VoidTy)
1505     ThrowException("LLVM functions cannot return aggregate types!");
1506
1507   std::vector<const Type*> ParamTypeList;
1508   if ($4) {   // If there are arguments...
1509     for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $4->begin();
1510          I != $4->end(); ++I)
1511       ParamTypeList.push_back(I->first->get());
1512   }
1513
1514   bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1515   if (isVarArg) ParamTypeList.pop_back();
1516
1517   const FunctionType *FT = FunctionType::get(*$1, ParamTypeList, isVarArg);
1518   const PointerType *PFT = PointerType::get(FT);
1519   delete $1;
1520
1521   Function *Fn = 0;
1522   // Is the function already in symtab?
1523   if ((Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
1524     // Yes it is.  If this is the case, either we need to be a forward decl,
1525     // or it needs to be.
1526     if (!CurFun.isDeclare && !Fn->isExternal())
1527       ThrowException("Redefinition of function '" + FunctionName + "'!");
1528     
1529     // Make sure to strip off any argument names so we can't get conflicts...
1530     for (Function::aiterator AI = Fn->abegin(), AE = Fn->aend(); AI != AE; ++AI)
1531       AI->setName("");
1532
1533   } else  {  // Not already defined?
1534     Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
1535                       CurModule.CurrentModule);
1536     InsertValue(Fn, CurModule.Values);
1537     CurModule.DeclareNewGlobalValue(Fn, ValID::create($2));
1538   }
1539   free($2);  // Free strdup'd memory!
1540
1541   CurFun.FunctionStart(Fn);
1542
1543   // Add all of the arguments we parsed to the function...
1544   if ($4) {                     // Is null if empty...
1545     if (isVarArg) {  // Nuke the last entry
1546       assert($4->back().first->get() == Type::VoidTy && $4->back().second == 0&&
1547              "Not a varargs marker!");
1548       delete $4->back().first;
1549       $4->pop_back();  // Delete the last entry
1550     }
1551     Function::aiterator ArgIt = Fn->abegin();
1552     for (std::vector<std::pair<PATypeHolder*, char*> >::iterator I =$4->begin();
1553          I != $4->end(); ++I, ++ArgIt) {
1554       delete I->first;                          // Delete the typeholder...
1555
1556       if (setValueName(ArgIt, I->second))       // Insert arg into symtab...
1557         assert(0 && "No arg redef allowed!");
1558       
1559       InsertValue(ArgIt);
1560     }
1561
1562     delete $4;                     // We're now done with the argument list
1563   }
1564 };
1565
1566 BEGIN : BEGINTOK | '{';                // Allow BEGIN or '{' to start a function
1567
1568 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
1569   $$ = CurFun.CurrentFunction;
1570
1571   // Make sure that we keep track of the linkage type even if there was a
1572   // previous "declare".
1573   $$->setLinkage($1);
1574
1575   // Resolve circular types before we parse the body of the function.
1576   ResolveTypes(CurFun.LateResolveTypes);
1577 };
1578
1579 END : ENDTOK | '}';                    // Allow end of '}' to end a function
1580
1581 Function : BasicBlockList END {
1582   $$ = $1;
1583 };
1584
1585 FunctionProto : DECLARE { CurFun.isDeclare = true; } FunctionHeaderH {
1586   $$ = CurFun.CurrentFunction;
1587   CurFun.FunctionDone();
1588 };
1589
1590 //===----------------------------------------------------------------------===//
1591 //                        Rules to match Basic Blocks
1592 //===----------------------------------------------------------------------===//
1593
1594 ConstValueRef : ESINT64VAL {    // A reference to a direct constant
1595     $$ = ValID::create($1);
1596   }
1597   | EUINT64VAL {
1598     $$ = ValID::create($1);
1599   }
1600   | FPVAL {                     // Perhaps it's an FP constant?
1601     $$ = ValID::create($1);
1602   }
1603   | TRUETOK {
1604     $$ = ValID::create(ConstantBool::True);
1605   } 
1606   | FALSETOK {
1607     $$ = ValID::create(ConstantBool::False);
1608   }
1609   | NULL_TOK {
1610     $$ = ValID::createNull();
1611   }
1612   | ConstExpr {
1613     $$ = ValID::create($1);
1614   };
1615
1616 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1617 // another value.
1618 //
1619 SymbolicValueRef : INTVAL {  // Is it an integer reference...?
1620     $$ = ValID::create($1);
1621   }
1622   | Name {                   // Is it a named reference...?
1623     $$ = ValID::create($1);
1624   };
1625
1626 // ValueRef - A reference to a definition... either constant or symbolic
1627 ValueRef : SymbolicValueRef | ConstValueRef;
1628
1629
1630 // ResolvedVal - a <type> <value> pair.  This is used only in cases where the
1631 // type immediately preceeds the value reference, and allows complex constant
1632 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1633 ResolvedVal : Types ValueRef {
1634     $$ = getVal(*$1, $2); delete $1;
1635   };
1636
1637 BasicBlockList : BasicBlockList BasicBlock {
1638     ($$ = $1)->getBasicBlockList().push_back($2);
1639   }
1640   | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks   
1641     ($$ = $1)->getBasicBlockList().push_back($2);
1642   };
1643
1644
1645 // Basic blocks are terminated by branching instructions: 
1646 // br, br/cc, switch, ret
1647 //
1648 BasicBlock : InstructionList OptAssign BBTerminatorInst  {
1649     if (setValueName($3, $2)) { assert(0 && "No redefn allowed!"); }
1650     InsertValue($3);
1651
1652     $1->getInstList().push_back($3);
1653     InsertValue($1);
1654     $$ = $1;
1655   }
1656   | LABELSTR InstructionList OptAssign BBTerminatorInst  {
1657     if (setValueName($4, $3)) { assert(0 && "No redefn allowed!"); }
1658     InsertValue($4);
1659
1660     $2->getInstList().push_back($4);
1661     if (setValueName($2, $1)) { assert(0 && "No label redef allowed!"); }
1662
1663     InsertValue($2);
1664     $$ = $2;
1665   };
1666
1667 InstructionList : InstructionList Inst {
1668     $1->getInstList().push_back($2);
1669     $$ = $1;
1670   }
1671   | /* empty */ {
1672     $$ = CurBB = new BasicBlock();
1673   };
1674
1675 BBTerminatorInst : RET ResolvedVal {              // Return with a result...
1676     $$ = new ReturnInst($2);
1677   }
1678   | RET VOID {                                       // Return with no result...
1679     $$ = new ReturnInst();
1680   }
1681   | BR LABEL ValueRef {                         // Unconditional Branch...
1682     $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $3)));
1683   }                                                  // Conditional Branch...
1684   | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {  
1685     $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $6)), 
1686                         cast<BasicBlock>(getVal(Type::LabelTy, $9)),
1687                         getVal(Type::BoolTy, $3));
1688   }
1689   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1690     SwitchInst *S = new SwitchInst(getVal($2, $3), 
1691                                    cast<BasicBlock>(getVal(Type::LabelTy, $6)));
1692     $$ = S;
1693
1694     std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
1695       E = $8->end();
1696     for (; I != E; ++I)
1697       S->addCase(I->first, I->second);
1698     delete $8;
1699   }
1700   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
1701     SwitchInst *S = new SwitchInst(getVal($2, $3), 
1702                                    cast<BasicBlock>(getVal(Type::LabelTy, $6)));
1703     $$ = S;
1704   }
1705   | INVOKE TypesV ValueRef '(' ValueRefListE ')' TO ResolvedVal 
1706     UNWIND ResolvedVal {
1707     const PointerType *PFTy;
1708     const FunctionType *Ty;
1709
1710     if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
1711         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1712       // Pull out the types of all of the arguments...
1713       std::vector<const Type*> ParamTypes;
1714       if ($5) {
1715         for (std::vector<Value*>::iterator I = $5->begin(), E = $5->end();
1716              I != E; ++I)
1717           ParamTypes.push_back((*I)->getType());
1718       }
1719
1720       bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1721       if (isVarArg) ParamTypes.pop_back();
1722
1723       Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1724       PFTy = PointerType::get(Ty);
1725     }
1726
1727     Value *V = getVal(PFTy, $3);   // Get the function we're calling...
1728
1729     BasicBlock *Normal = dyn_cast<BasicBlock>($8);
1730     BasicBlock *Except = dyn_cast<BasicBlock>($10);
1731
1732     if (Normal == 0 || Except == 0)
1733       ThrowException("Invoke instruction without label destinations!");
1734
1735     // Create the call node...
1736     if (!$5) {                                   // Has no arguments?
1737       $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
1738     } else {                                     // Has arguments?
1739       // Loop through FunctionType's arguments and ensure they are specified
1740       // correctly!
1741       //
1742       FunctionType::param_iterator I = Ty->param_begin();
1743       FunctionType::param_iterator E = Ty->param_end();
1744       std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1745
1746       for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1747         if ((*ArgI)->getType() != *I)
1748           ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1749                          (*I)->getDescription() + "'!");
1750
1751       if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1752         ThrowException("Invalid number of parameters detected!");
1753
1754       $$ = new InvokeInst(V, Normal, Except, *$5);
1755     }
1756     delete $2;
1757     delete $5;
1758   }
1759   | UNWIND {
1760     $$ = new UnwindInst();
1761   };
1762
1763
1764
1765 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1766     $$ = $1;
1767     Constant *V = cast<Constant>(getValNonImprovising($2, $3));
1768     if (V == 0)
1769       ThrowException("May only switch on a constant pool value!");
1770
1771     $$->push_back(std::make_pair(V, cast<BasicBlock>(getVal($5, $6))));
1772   }
1773   | IntType ConstValueRef ',' LABEL ValueRef {
1774     $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
1775     Constant *V = cast<Constant>(getValNonImprovising($1, $2));
1776
1777     if (V == 0)
1778       ThrowException("May only switch on a constant pool value!");
1779
1780     $$->push_back(std::make_pair(V, cast<BasicBlock>(getVal($4, $5))));
1781   };
1782
1783 Inst : OptAssign InstVal {
1784   // Is this definition named?? if so, assign the name...
1785   if (setValueName($2, $1)) { assert(0 && "No redefin allowed!"); }
1786   InsertValue($2);
1787   $$ = $2;
1788 };
1789
1790 PHIList : Types '[' ValueRef ',' ValueRef ']' {    // Used for PHI nodes
1791     $$ = new std::list<std::pair<Value*, BasicBlock*> >();
1792     $$->push_back(std::make_pair(getVal(*$1, $3), 
1793                                  cast<BasicBlock>(getVal(Type::LabelTy, $5))));
1794     delete $1;
1795   }
1796   | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1797     $$ = $1;
1798     $1->push_back(std::make_pair(getVal($1->front().first->getType(), $4),
1799                                  cast<BasicBlock>(getVal(Type::LabelTy, $6))));
1800   };
1801
1802
1803 ValueRefList : ResolvedVal {    // Used for call statements, and memory insts...
1804     $$ = new std::vector<Value*>();
1805     $$->push_back($1);
1806   }
1807   | ValueRefList ',' ResolvedVal {
1808     $$ = $1;
1809     $1->push_back($3);
1810   };
1811
1812 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1813 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
1814
1815 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
1816     if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint())
1817       ThrowException("Arithmetic operator requires integer or FP operands!");
1818     $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1819     if ($$ == 0)
1820       ThrowException("binary operator returned null!");
1821     delete $2;
1822   }
1823   | LogicalOps Types ValueRef ',' ValueRef {
1824     if (!(*$2)->isIntegral())
1825       ThrowException("Logical operator requires integral operands!");
1826     $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1827     if ($$ == 0)
1828       ThrowException("binary operator returned null!");
1829     delete $2;
1830   }
1831   | SetCondOps Types ValueRef ',' ValueRef {
1832     $$ = new SetCondInst($1, getVal(*$2, $3), getVal(*$2, $5));
1833     if ($$ == 0)
1834       ThrowException("binary operator returned null!");
1835     delete $2;
1836   }
1837   | NOT ResolvedVal {
1838     std::cerr << "WARNING: Use of eliminated 'not' instruction:"
1839               << " Replacing with 'xor'.\n";
1840
1841     Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
1842     if (Ones == 0)
1843       ThrowException("Expected integral type for not instruction!");
1844
1845     $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
1846     if ($$ == 0)
1847       ThrowException("Could not create a xor instruction!");
1848   }
1849   | ShiftOps ResolvedVal ',' ResolvedVal {
1850     if ($4->getType() != Type::UByteTy)
1851       ThrowException("Shift amount must be ubyte!");
1852     if (!$2->getType()->isInteger())
1853       ThrowException("Shift constant expression requires integer operand!");
1854     $$ = new ShiftInst($1, $2, $4);
1855   }
1856   | CAST ResolvedVal TO Types {
1857     if (!$4->get()->isFirstClassType())
1858       ThrowException("cast instruction to a non-primitive type: '" +
1859                      $4->get()->getDescription() + "'!");
1860     $$ = new CastInst($2, *$4);
1861     delete $4;
1862   }
1863   | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
1864     if ($2->getType() != Type::BoolTy)
1865       ThrowException("select condition must be boolean!");
1866     if ($4->getType() != $6->getType())
1867       ThrowException("select value types should match!");
1868     $$ = new SelectInst($2, $4, $6);
1869   }
1870   | VA_ARG ResolvedVal ',' Types {
1871     // FIXME: This is emulation code for an obsolete syntax.  This should be
1872     // removed at some point.
1873     if (!ObsoleteVarArgs) {
1874       std::cerr << "WARNING: this file uses obsolete features.  "
1875                 << "Assemble and disassemble to update it.\n";
1876       ObsoleteVarArgs = true;
1877     }
1878
1879     // First, load the valist...
1880     Instruction *CurVAList = new LoadInst($2, "");
1881     CurBB->getInstList().push_back(CurVAList);
1882
1883     // Emit the vaarg instruction.
1884     $$ = new VAArgInst(CurVAList, *$4);
1885     
1886     // Now we must advance the pointer and update it in memory.
1887     Instruction *TheVANext = new VANextInst(CurVAList, *$4);
1888     CurBB->getInstList().push_back(TheVANext);
1889
1890     CurBB->getInstList().push_back(new StoreInst(TheVANext, $2));
1891     delete $4;
1892   }
1893   | VAARG ResolvedVal ',' Types {
1894     $$ = new VAArgInst($2, *$4);
1895     delete $4;
1896   }
1897   | VANEXT ResolvedVal ',' Types {
1898     $$ = new VANextInst($2, *$4);
1899     delete $4;
1900   }
1901   | PHI_TOK PHIList {
1902     const Type *Ty = $2->front().first->getType();
1903     if (!Ty->isFirstClassType())
1904       ThrowException("PHI node operands must be of first class type!");
1905     $$ = new PHINode(Ty);
1906     $$->op_reserve($2->size()*2);
1907     while ($2->begin() != $2->end()) {
1908       if ($2->front().first->getType() != Ty) 
1909         ThrowException("All elements of a PHI node must be of the same type!");
1910       cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
1911       $2->pop_front();
1912     }
1913     delete $2;  // Free the list...
1914   } 
1915   | CALL TypesV ValueRef '(' ValueRefListE ')' {
1916     const PointerType *PFTy;
1917     const FunctionType *Ty;
1918
1919     if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
1920         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1921       // Pull out the types of all of the arguments...
1922       std::vector<const Type*> ParamTypes;
1923       if ($5) {
1924         for (std::vector<Value*>::iterator I = $5->begin(), E = $5->end();
1925              I != E; ++I)
1926           ParamTypes.push_back((*I)->getType());
1927       }
1928
1929       bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1930       if (isVarArg) ParamTypes.pop_back();
1931
1932       Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1933       PFTy = PointerType::get(Ty);
1934     }
1935
1936     Value *V = getVal(PFTy, $3);   // Get the function we're calling...
1937
1938     // Create the call node...
1939     if (!$5) {                                   // Has no arguments?
1940       // Make sure no arguments is a good thing!
1941       if (Ty->getNumParams() != 0)
1942         ThrowException("No arguments passed to a function that "
1943                        "expects arguments!");
1944
1945       $$ = new CallInst(V, std::vector<Value*>());
1946     } else {                                     // Has arguments?
1947       // Loop through FunctionType's arguments and ensure they are specified
1948       // correctly!
1949       //
1950       FunctionType::param_iterator I = Ty->param_begin();
1951       FunctionType::param_iterator E = Ty->param_end();
1952       std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1953
1954       for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1955         if ((*ArgI)->getType() != *I)
1956           ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1957                          (*I)->getDescription() + "'!");
1958
1959       if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1960         ThrowException("Invalid number of parameters detected!");
1961
1962       $$ = new CallInst(V, *$5);
1963     }
1964     delete $2;
1965     delete $5;
1966   }
1967   | MemoryInst {
1968     $$ = $1;
1969   };
1970
1971
1972 // IndexList - List of indices for GEP based instructions...
1973 IndexList : ',' ValueRefList { 
1974     $$ = $2; 
1975   } | /* empty */ { 
1976     $$ = new std::vector<Value*>(); 
1977   };
1978
1979 OptVolatile : VOLATILE {
1980     $$ = true;
1981   }
1982   | /* empty */ {
1983     $$ = false;
1984   };
1985
1986
1987 MemoryInst : MALLOC Types {
1988     $$ = new MallocInst(*$2);
1989     delete $2;
1990   }
1991   | MALLOC Types ',' UINT ValueRef {
1992     $$ = new MallocInst(*$2, getVal($4, $5));
1993     delete $2;
1994   }
1995   | ALLOCA Types {
1996     $$ = new AllocaInst(*$2);
1997     delete $2;
1998   }
1999   | ALLOCA Types ',' UINT ValueRef {
2000     $$ = new AllocaInst(*$2, getVal($4, $5));
2001     delete $2;
2002   }
2003   | FREE ResolvedVal {
2004     if (!isa<PointerType>($2->getType()))
2005       ThrowException("Trying to free nonpointer type " + 
2006                      $2->getType()->getDescription() + "!");
2007     $$ = new FreeInst($2);
2008   }
2009
2010   | OptVolatile LOAD Types ValueRef {
2011     if (!isa<PointerType>($3->get()))
2012       ThrowException("Can't load from nonpointer type: " +
2013                      (*$3)->getDescription());
2014     $$ = new LoadInst(getVal(*$3, $4), "", $1);
2015     delete $3;
2016   }
2017   | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2018     const PointerType *PT = dyn_cast<PointerType>($5->get());
2019     if (!PT)
2020       ThrowException("Can't store to a nonpointer type: " +
2021                      (*$5)->getDescription());
2022     const Type *ElTy = PT->getElementType();
2023     if (ElTy != $3->getType())
2024       ThrowException("Can't store '" + $3->getType()->getDescription() +
2025                      "' into space of type '" + ElTy->getDescription() + "'!");
2026
2027     $$ = new StoreInst($3, getVal(*$5, $6), $1);
2028     delete $5;
2029   }
2030   | GETELEMENTPTR Types ValueRef IndexList {
2031     if (!isa<PointerType>($2->get()))
2032       ThrowException("getelementptr insn requires pointer operand!");
2033
2034     // LLVM 1.2 and earlier used ubyte struct indices.  Convert any ubyte struct
2035     // indices to uint struct indices for compatibility.
2036     generic_gep_type_iterator<std::vector<Value*>::iterator>
2037       GTI = gep_type_begin($2->get(), $4->begin(), $4->end()),
2038       GTE = gep_type_end($2->get(), $4->begin(), $4->end());
2039     for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
2040       if (isa<StructType>(*GTI))        // Only change struct indices
2041         if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
2042           if (CUI->getType() == Type::UByteTy)
2043             (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
2044
2045     if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2046       ThrowException("Invalid getelementptr indices for type '" +
2047                      (*$2)->getDescription()+ "'!");
2048     $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
2049     delete $2; delete $4;
2050   };
2051
2052
2053 %%
2054 int yyerror(const char *ErrorMsg) {
2055   std::string where 
2056     = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2057                   + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2058   std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2059   if (yychar == YYEMPTY || yychar == 0)
2060     errMsg += "end-of-file.";
2061   else
2062     errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2063   ThrowException(errMsg);
2064   return 0;
2065 }