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