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