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