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