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