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