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