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