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