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