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