Make sure intrinsic auto-upgrade is invoked correctly.
[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/CallingConv.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Module.h"
19 #include "llvm/SymbolTable.h"
20 #include "llvm/Assembly/AutoUpgrade.h"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/Support/MathExtras.h"
24 #include <algorithm>
25 #include <iostream>
26 #include <list>
27 #include <utility>
28
29 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
30 int yylex();                       // declaration" of xxx warnings.
31 int yyparse();
32
33 namespace llvm {
34   std::string CurFilename;
35 }
36 using namespace llvm;
37
38 static Module *ParserResult;
39
40 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
41 // relating to upreferences in the input stream.
42 //
43 //#define DEBUG_UPREFS 1
44 #ifdef DEBUG_UPREFS
45 #define UR_OUT(X) std::cerr << X
46 #else
47 #define UR_OUT(X)
48 #endif
49
50 #define YYERROR_VERBOSE 1
51
52 static bool ObsoleteVarArgs;
53 static bool NewVarArgs;
54 static BasicBlock *CurBB;
55 static GlobalVariable *CurGV;
56
57
58 // This contains info used when building the body of a function.  It is
59 // destroyed when the function is completed.
60 //
61 typedef std::vector<Value *> ValueList;           // Numbered defs
62 static void 
63 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
64                    std::map<const Type *,ValueList> *FutureLateResolvers = 0);
65
66 static struct PerModuleInfo {
67   Module *CurrentModule;
68   std::map<const Type *, ValueList> Values; // Module level numbered definitions
69   std::map<const Type *,ValueList> LateResolveValues;
70   std::vector<PATypeHolder>    Types;
71   std::map<ValID, PATypeHolder> LateResolveTypes;
72
73   /// PlaceHolderInfo - When temporary placeholder objects are created, remember
74   /// how they were referenced and one which line of the input they came from so
75   /// that we can resolve them later and print error messages as appropriate.
76   std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
77
78   // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
79   // references to global values.  Global values may be referenced before they
80   // are defined, and if so, the temporary object that they represent is held
81   // here.  This is used for forward references of GlobalValues.
82   //
83   typedef std::map<std::pair<const PointerType *,
84                              ValID>, GlobalValue*> GlobalRefsType;
85   GlobalRefsType GlobalRefs;
86
87   void ModuleDone() {
88     // If we could not resolve some functions at function compilation time
89     // (calls to functions before they are defined), resolve them now...  Types
90     // are resolved when the constant pool has been completely parsed.
91     //
92     ResolveDefinitions(LateResolveValues);
93
94     // Check to make sure that all global value forward references have been
95     // resolved!
96     //
97     if (!GlobalRefs.empty()) {
98       std::string UndefinedReferences = "Unresolved global references exist:\n";
99
100       for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
101            I != E; ++I) {
102         UndefinedReferences += "  " + I->first.first->getDescription() + " " +
103                                I->first.second.getName() + "\n";
104       }
105       ThrowException(UndefinedReferences);
106     }
107
108     // Look for intrinsic functions and CallInst that need to be upgraded
109     for (Module::iterator FI = CurrentModule->begin(),FE = CurrentModule->end();
110          FI != FE; ++FI)
111       UpgradeCallsToIntrinsic(FI);
112
113     Values.clear();         // Clear out function local definitions
114     Types.clear();
115     CurrentModule = 0;
116   }
117
118   // GetForwardRefForGlobal - Check to see if there is a forward reference
119   // for this global.  If so, remove it from the GlobalRefs map and return it.
120   // If not, just return null.
121   GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
122     // Check to see if there is a forward reference to this global variable...
123     // if there is, eliminate it and patch the reference to use the new def'n.
124     GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
125     GlobalValue *Ret = 0;
126     if (I != GlobalRefs.end()) {
127       Ret = I->second;
128       GlobalRefs.erase(I);
129     }
130     return Ret;
131   }
132 } CurModule;
133
134 static struct PerFunctionInfo {
135   Function *CurrentFunction;     // Pointer to current function being created
136
137   std::map<const Type*, ValueList> Values;   // Keep track of #'d definitions
138   std::map<const Type*, ValueList> LateResolveValues;
139   bool isDeclare;                // Is this function a forward declararation?
140
141   /// BBForwardRefs - When we see forward references to basic blocks, keep
142   /// track of them here.
143   std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
144   std::vector<BasicBlock*> NumberedBlocks;
145   unsigned NextBBNum;
146
147   inline PerFunctionInfo() {
148     CurrentFunction = 0;
149     isDeclare = false;
150   }
151
152   inline void FunctionStart(Function *M) {
153     CurrentFunction = M;
154     NextBBNum = 0;
155   }
156
157   void FunctionDone() {
158     NumberedBlocks.clear();
159
160     // Any forward referenced blocks left?
161     if (!BBForwardRefs.empty())
162       ThrowException("Undefined reference to label " +
163                      BBForwardRefs.begin()->first->getName());
164
165     // Resolve all forward references now.
166     ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
167
168     Values.clear();         // Clear out function local definitions
169     CurrentFunction = 0;
170     isDeclare = false;
171   }
172 } CurFun;  // Info for the current function...
173
174 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
175
176
177 //===----------------------------------------------------------------------===//
178 //               Code to handle definitions of all the types
179 //===----------------------------------------------------------------------===//
180
181 static int InsertValue(Value *V,
182                   std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
183   if (V->hasName()) return -1;           // Is this a numbered definition?
184
185   // Yes, insert the value into the value table...
186   ValueList &List = ValueTab[V->getType()];
187   List.push_back(V);
188   return List.size()-1;
189 }
190
191 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
192   switch (D.Type) {
193   case ValID::NumberVal:               // Is it a numbered definition?
194     // Module constants occupy the lowest numbered slots...
195     if ((unsigned)D.Num < CurModule.Types.size())
196       return CurModule.Types[(unsigned)D.Num];
197     break;
198   case ValID::NameVal:                 // Is it a named definition?
199     if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
200       D.destroy();  // Free old strdup'd memory...
201       return N;
202     }
203     break;
204   default:
205     ThrowException("Internal parser error: Invalid symbol type reference!");
206   }
207
208   // If we reached here, we referenced either a symbol that we don't know about
209   // or an id number that hasn't been read yet.  We may be referencing something
210   // forward, so just create an entry to be resolved later and get to it...
211   //
212   if (DoNotImprovise) return 0;  // Do we just want a null to be returned?
213
214
215   if (inFunctionScope()) {
216     if (D.Type == ValID::NameVal)
217       ThrowException("Reference to an undefined type: '" + D.getName() + "'");
218     else
219       ThrowException("Reference to an undefined type: #" + itostr(D.Num));
220   }
221
222   std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
223   if (I != CurModule.LateResolveTypes.end())
224     return I->second;
225
226   Type *Typ = OpaqueType::get();
227   CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
228   return Typ;
229  }
230
231 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
232   SymbolTable &SymTab =
233     inFunctionScope() ? CurFun.CurrentFunction->getSymbolTable() :
234                         CurModule.CurrentModule->getSymbolTable();
235   return SymTab.lookup(Ty, Name);
236 }
237
238 // getValNonImprovising - Look up the value specified by the provided type and
239 // the provided ValID.  If the value exists and has already been defined, return
240 // it.  Otherwise return null.
241 //
242 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
243   if (isa<FunctionType>(Ty))
244     ThrowException("Functions are not values and "
245                    "must be referenced as pointers");
246
247   switch (D.Type) {
248   case ValID::NumberVal: {                 // Is it a numbered definition?
249     unsigned Num = (unsigned)D.Num;
250
251     // Module constants occupy the lowest numbered slots...
252     std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
253     if (VI != CurModule.Values.end()) {
254       if (Num < VI->second.size())
255         return VI->second[Num];
256       Num -= VI->second.size();
257     }
258
259     // Make sure that our type is within bounds
260     VI = CurFun.Values.find(Ty);
261     if (VI == CurFun.Values.end()) return 0;
262
263     // Check that the number is within bounds...
264     if (VI->second.size() <= Num) return 0;
265
266     return VI->second[Num];
267   }
268
269   case ValID::NameVal: {                // Is it a named definition?
270     Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
271     if (N == 0) return 0;
272
273     D.destroy();  // Free old strdup'd memory...
274     return N;
275   }
276
277   // Check to make sure that "Ty" is an integral type, and that our
278   // value will fit into the specified type...
279   case ValID::ConstSIntVal:    // Is it a constant pool reference??
280     if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64))
281       ThrowException("Signed integral constant '" +
282                      itostr(D.ConstPool64) + "' is invalid for type '" +
283                      Ty->getDescription() + "'!");
284     return ConstantSInt::get(Ty, D.ConstPool64);
285
286   case ValID::ConstUIntVal:     // Is it an unsigned const pool reference?
287     if (!ConstantUInt::isValueValidForType(Ty, D.UConstPool64)) {
288       if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64)) {
289         ThrowException("Integral constant '" + utostr(D.UConstPool64) +
290                        "' is invalid or out of range!");
291       } else {     // This is really a signed reference.  Transmogrify.
292         return ConstantSInt::get(Ty, D.ConstPool64);
293       }
294     } else {
295       return ConstantUInt::get(Ty, D.UConstPool64);
296     }
297
298   case ValID::ConstFPVal:        // Is it a floating point const pool reference?
299     if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
300       ThrowException("FP constant invalid for type!!");
301     return ConstantFP::get(Ty, D.ConstPoolFP);
302
303   case ValID::ConstNullVal:      // Is it a null value?
304     if (!isa<PointerType>(Ty))
305       ThrowException("Cannot create a a non pointer null!");
306     return ConstantPointerNull::get(cast<PointerType>(Ty));
307
308   case ValID::ConstUndefVal:      // Is it an undef value?
309     return UndefValue::get(Ty);
310
311   case ValID::ConstZeroVal:      // Is it a zero value?
312     return Constant::getNullValue(Ty);
313     
314   case ValID::ConstantVal:       // Fully resolved constant?
315     if (D.ConstantValue->getType() != Ty)
316       ThrowException("Constant expression type different from required type!");
317     return D.ConstantValue;
318
319   default:
320     assert(0 && "Unhandled case!");
321     return 0;
322   }   // End of switch
323
324   assert(0 && "Unhandled case!");
325   return 0;
326 }
327
328 // getVal - This function is identical to getValNonImprovising, except that if a
329 // value is not already defined, it "improvises" by creating a placeholder var
330 // that looks and acts just like the requested variable.  When the value is
331 // defined later, all uses of the placeholder variable are replaced with the
332 // real thing.
333 //
334 static Value *getVal(const Type *Ty, const ValID &ID) {
335   if (Ty == Type::LabelTy)
336     ThrowException("Cannot use a basic block here");
337
338   // See if the value has already been defined.
339   Value *V = getValNonImprovising(Ty, ID);
340   if (V) return V;
341
342   if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty))
343     ThrowException("Invalid use of a composite type!");
344
345   // If we reached here, we referenced either a symbol that we don't know about
346   // or an id number that hasn't been read yet.  We may be referencing something
347   // forward, so just create an entry to be resolved later and get to it...
348   //
349   V = new Argument(Ty);
350
351   // Remember where this forward reference came from.  FIXME, shouldn't we try
352   // to recycle these things??
353   CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
354                                                                llvmAsmlineno)));
355
356   if (inFunctionScope())
357     InsertValue(V, CurFun.LateResolveValues);
358   else
359     InsertValue(V, CurModule.LateResolveValues);
360   return V;
361 }
362
363 /// getBBVal - This is used for two purposes:
364 ///  * If isDefinition is true, a new basic block with the specified ID is being
365 ///    defined.
366 ///  * If isDefinition is true, this is a reference to a basic block, which may
367 ///    or may not be a forward reference.
368 ///
369 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
370   assert(inFunctionScope() && "Can't get basic block at global scope!");
371
372   std::string Name;
373   BasicBlock *BB = 0;
374   switch (ID.Type) {
375   default: ThrowException("Illegal label reference " + ID.getName());
376   case ValID::NumberVal:                // Is it a numbered definition?
377     if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
378       CurFun.NumberedBlocks.resize(ID.Num+1);
379     BB = CurFun.NumberedBlocks[ID.Num];
380     break;
381   case ValID::NameVal:                  // Is it a named definition?
382     Name = ID.Name;
383     if (Value *N = CurFun.CurrentFunction->
384                    getSymbolTable().lookup(Type::LabelTy, Name))
385       BB = cast<BasicBlock>(N);
386     break;
387   }
388
389   // See if the block has already been defined.
390   if (BB) {
391     // If this is the definition of the block, make sure the existing value was
392     // just a forward reference.  If it was a forward reference, there will be
393     // an entry for it in the PlaceHolderInfo map.
394     if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
395       // The existing value was a definition, not a forward reference.
396       ThrowException("Redefinition of label " + ID.getName());
397
398     ID.destroy();                       // Free strdup'd memory.
399     return BB;
400   }
401
402   // Otherwise this block has not been seen before.
403   BB = new BasicBlock("", CurFun.CurrentFunction);
404   if (ID.Type == ValID::NameVal) {
405     BB->setName(ID.Name);
406   } else {
407     CurFun.NumberedBlocks[ID.Num] = BB;
408   }
409
410   // If this is not a definition, keep track of it so we can use it as a forward
411   // reference.
412   if (!isDefinition) {
413     // Remember where this forward reference came from.
414     CurFun.BBForwardRefs[BB] = std::make_pair(ID, llvmAsmlineno);
415   } else {
416     // The forward declaration could have been inserted anywhere in the
417     // function: insert it into the correct place now.
418     CurFun.CurrentFunction->getBasicBlockList().remove(BB);
419     CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
420   }
421   ID.destroy();
422   return BB;
423 }
424
425
426 //===----------------------------------------------------------------------===//
427 //              Code to handle forward references in instructions
428 //===----------------------------------------------------------------------===//
429 //
430 // This code handles the late binding needed with statements that reference
431 // values not defined yet... for example, a forward branch, or the PHI node for
432 // a loop body.
433 //
434 // This keeps a table (CurFun.LateResolveValues) of all such forward references
435 // and back patchs after we are done.
436 //
437
438 // ResolveDefinitions - If we could not resolve some defs at parsing
439 // time (forward branches, phi functions for loops, etc...) resolve the
440 // defs now...
441 //
442 static void 
443 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
444                    std::map<const Type*,ValueList> *FutureLateResolvers) {
445   // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
446   for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
447          E = LateResolvers.end(); LRI != E; ++LRI) {
448     ValueList &List = LRI->second;
449     while (!List.empty()) {
450       Value *V = List.back();
451       List.pop_back();
452
453       std::map<Value*, std::pair<ValID, int> >::iterator PHI =
454         CurModule.PlaceHolderInfo.find(V);
455       assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
456
457       ValID &DID = PHI->second.first;
458
459       Value *TheRealValue = getValNonImprovising(LRI->first, DID);
460       if (TheRealValue) {
461         V->replaceAllUsesWith(TheRealValue);
462         delete V;
463         CurModule.PlaceHolderInfo.erase(PHI);
464       } else if (FutureLateResolvers) {
465         // Functions have their unresolved items forwarded to the module late
466         // resolver table
467         InsertValue(V, *FutureLateResolvers);
468       } else {
469         if (DID.Type == ValID::NameVal)
470           ThrowException("Reference to an invalid definition: '" +DID.getName()+
471                          "' of type '" + V->getType()->getDescription() + "'",
472                          PHI->second.second);
473         else
474           ThrowException("Reference to an invalid definition: #" +
475                          itostr(DID.Num) + " of type '" +
476                          V->getType()->getDescription() + "'",
477                          PHI->second.second);
478       }
479     }
480   }
481
482   LateResolvers.clear();
483 }
484
485 // ResolveTypeTo - A brand new type was just declared.  This means that (if
486 // name is not null) things referencing Name can be resolved.  Otherwise, things
487 // refering to the number can be resolved.  Do this now.
488 //
489 static void ResolveTypeTo(char *Name, const Type *ToTy) {
490   ValID D;
491   if (Name) D = ValID::create(Name);
492   else      D = ValID::create((int)CurModule.Types.size());
493
494   std::map<ValID, PATypeHolder>::iterator I =
495     CurModule.LateResolveTypes.find(D);
496   if (I != CurModule.LateResolveTypes.end()) {
497     ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
498     CurModule.LateResolveTypes.erase(I);
499   }
500 }
501
502 // setValueName - Set the specified value to the name given.  The name may be
503 // null potentially, in which case this is a noop.  The string passed in is
504 // assumed to be a malloc'd string buffer, and is free'd by this function.
505 //
506 static void setValueName(Value *V, char *NameStr) {
507   if (NameStr) {
508     std::string Name(NameStr);      // Copy string
509     free(NameStr);                  // Free old string
510
511     if (V->getType() == Type::VoidTy)
512       ThrowException("Can't assign name '" + Name+"' to value with void type!");
513
514     assert(inFunctionScope() && "Must be in function scope!");
515     SymbolTable &ST = CurFun.CurrentFunction->getSymbolTable();
516     if (ST.lookup(V->getType(), Name))
517       ThrowException("Redefinition of value named '" + Name + "' in the '" +
518                      V->getType()->getDescription() + "' type plane!");
519
520     // Set the name.
521     V->setName(Name);
522   }
523 }
524
525 /// ParseGlobalVariable - Handle parsing of a global.  If Initializer is null,
526 /// this is a declaration, otherwise it is a definition.
527 static GlobalVariable *
528 ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
529                     bool isConstantGlobal, const Type *Ty,
530                     Constant *Initializer) {
531   if (isa<FunctionType>(Ty))
532     ThrowException("Cannot declare global vars of function type!");
533
534   const PointerType *PTy = PointerType::get(Ty);
535
536   std::string Name;
537   if (NameStr) {
538     Name = NameStr;      // Copy string
539     free(NameStr);       // Free old string
540   }
541
542   // See if this global value was forward referenced.  If so, recycle the
543   // object.
544   ValID ID;
545   if (!Name.empty()) {
546     ID = ValID::create((char*)Name.c_str());
547   } else {
548     ID = ValID::create((int)CurModule.Values[PTy].size());
549   }
550
551   if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
552     // Move the global to the end of the list, from whereever it was
553     // previously inserted.
554     GlobalVariable *GV = cast<GlobalVariable>(FWGV);
555     CurModule.CurrentModule->getGlobalList().remove(GV);
556     CurModule.CurrentModule->getGlobalList().push_back(GV);
557     GV->setInitializer(Initializer);
558     GV->setLinkage(Linkage);
559     GV->setConstant(isConstantGlobal);
560     InsertValue(GV, CurModule.Values);
561     return GV;
562   }
563
564   // If this global has a name, check to see if there is already a definition
565   // of this global in the module.  If so, merge as appropriate.  Note that
566   // this is really just a hack around problems in the CFE.  :(
567   if (!Name.empty()) {
568     // We are a simple redefinition of a value, check to see if it is defined
569     // the same as the old one.
570     if (GlobalVariable *EGV =
571                 CurModule.CurrentModule->getGlobalVariable(Name, Ty)) {
572       // We are allowed to redefine a global variable in two circumstances:
573       // 1. If at least one of the globals is uninitialized or
574       // 2. If both initializers have the same value.
575       //
576       if (!EGV->hasInitializer() || !Initializer ||
577           EGV->getInitializer() == Initializer) {
578
579         // Make sure the existing global version gets the initializer!  Make
580         // sure that it also gets marked const if the new version is.
581         if (Initializer && !EGV->hasInitializer())
582           EGV->setInitializer(Initializer);
583         if (isConstantGlobal)
584           EGV->setConstant(true);
585         EGV->setLinkage(Linkage);
586         return EGV;
587       }
588
589       ThrowException("Redefinition of global variable named '" + Name +
590                      "' in the '" + Ty->getDescription() + "' type plane!");
591     }
592   }
593
594   // Otherwise there is no existing GV to use, create one now.
595   GlobalVariable *GV =
596     new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
597                        CurModule.CurrentModule);
598   InsertValue(GV, CurModule.Values);
599   return GV;
600 }
601
602 // setTypeName - Set the specified type to the name given.  The name may be
603 // null potentially, in which case this is a noop.  The string passed in is
604 // assumed to be a malloc'd string buffer, and is freed by this function.
605 //
606 // This function returns true if the type has already been defined, but is
607 // allowed to be redefined in the specified context.  If the name is a new name
608 // for the type plane, it is inserted and false is returned.
609 static bool setTypeName(const Type *T, char *NameStr) {
610   assert(!inFunctionScope() && "Can't give types function-local names!");
611   if (NameStr == 0) return false;
612  
613   std::string Name(NameStr);      // Copy string
614   free(NameStr);                  // Free old string
615
616   // We don't allow assigning names to void type
617   if (T == Type::VoidTy)
618     ThrowException("Can't assign name '" + Name + "' to the void type!");
619
620   // Set the type name, checking for conflicts as we do so.
621   bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
622
623   if (AlreadyExists) {   // Inserting a name that is already defined???
624     const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
625     assert(Existing && "Conflict but no matching type?");
626
627     // There is only one case where this is allowed: when we are refining an
628     // opaque type.  In this case, Existing will be an opaque type.
629     if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
630       // We ARE replacing an opaque type!
631       const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
632       return true;
633     }
634
635     // Otherwise, this is an attempt to redefine a type. That's okay if
636     // the redefinition is identical to the original. This will be so if
637     // Existing and T point to the same Type object. In this one case we
638     // allow the equivalent redefinition.
639     if (Existing == T) return true;  // Yes, it's equal.
640
641     // Any other kind of (non-equivalent) redefinition is an error.
642     ThrowException("Redefinition of type named '" + Name + "' in the '" +
643                    T->getDescription() + "' type plane!");
644   }
645
646   return false;
647 }
648
649 //===----------------------------------------------------------------------===//
650 // Code for handling upreferences in type names...
651 //
652
653 // TypeContains - Returns true if Ty directly contains E in it.
654 //
655 static bool TypeContains(const Type *Ty, const Type *E) {
656   return std::find(Ty->subtype_begin(), Ty->subtype_end(),
657                    E) != Ty->subtype_end();
658 }
659
660 namespace {
661   struct UpRefRecord {
662     // NestingLevel - The number of nesting levels that need to be popped before
663     // this type is resolved.
664     unsigned NestingLevel;
665
666     // LastContainedTy - This is the type at the current binding level for the
667     // type.  Every time we reduce the nesting level, this gets updated.
668     const Type *LastContainedTy;
669
670     // UpRefTy - This is the actual opaque type that the upreference is
671     // represented with.
672     OpaqueType *UpRefTy;
673
674     UpRefRecord(unsigned NL, OpaqueType *URTy)
675       : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
676   };
677 }
678
679 // UpRefs - A list of the outstanding upreferences that need to be resolved.
680 static std::vector<UpRefRecord> UpRefs;
681
682 /// HandleUpRefs - Every time we finish a new layer of types, this function is
683 /// called.  It loops through the UpRefs vector, which is a list of the
684 /// currently active types.  For each type, if the up reference is contained in
685 /// the newly completed type, we decrement the level count.  When the level
686 /// count reaches zero, the upreferenced type is the type that is passed in:
687 /// thus we can complete the cycle.
688 ///
689 static PATypeHolder HandleUpRefs(const Type *ty) {
690   if (!ty->isAbstract()) return ty;
691   PATypeHolder Ty(ty);
692   UR_OUT("Type '" << Ty->getDescription() <<
693          "' newly formed.  Resolving upreferences.\n" <<
694          UpRefs.size() << " upreferences active!\n");
695
696   // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
697   // to zero), we resolve them all together before we resolve them to Ty.  At
698   // the end of the loop, if there is anything to resolve to Ty, it will be in
699   // this variable.
700   OpaqueType *TypeToResolve = 0;
701
702   for (unsigned i = 0; i != UpRefs.size(); ++i) {
703     UR_OUT("  UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
704            << UpRefs[i].second->getDescription() << ") = "
705            << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
706     if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
707       // Decrement level of upreference
708       unsigned Level = --UpRefs[i].NestingLevel;
709       UpRefs[i].LastContainedTy = Ty;
710       UR_OUT("  Uplevel Ref Level = " << Level << "\n");
711       if (Level == 0) {                     // Upreference should be resolved!
712         if (!TypeToResolve) {
713           TypeToResolve = UpRefs[i].UpRefTy;
714         } else {
715           UR_OUT("  * Resolving upreference for "
716                  << UpRefs[i].second->getDescription() << "\n";
717                  std::string OldName = UpRefs[i].UpRefTy->getDescription());
718           UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
719           UR_OUT("  * Type '" << OldName << "' refined upreference to: "
720                  << (const void*)Ty << ", " << Ty->getDescription() << "\n");
721         }
722         UpRefs.erase(UpRefs.begin()+i);     // Remove from upreference list...
723         --i;                                // Do not skip the next element...
724       }
725     }
726   }
727
728   if (TypeToResolve) {
729     UR_OUT("  * Resolving upreference for "
730            << UpRefs[i].second->getDescription() << "\n";
731            std::string OldName = TypeToResolve->getDescription());
732     TypeToResolve->refineAbstractTypeTo(Ty);
733   }
734
735   return Ty;
736 }
737
738
739 // common code from the two 'RunVMAsmParser' functions
740  static Module * RunParser(Module * M) {
741
742   llvmAsmlineno = 1;      // Reset the current line number...
743   ObsoleteVarArgs = false;
744   NewVarArgs = false;
745
746   CurModule.CurrentModule = M;
747   yyparse();       // Parse the file, potentially throwing exception
748
749   Module *Result = ParserResult;
750   ParserResult = 0;
751
752   //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
753   {
754     Function* F;
755     if ((F = Result->getNamedFunction("llvm.va_start"))
756         && F->getFunctionType()->getNumParams() == 0)
757       ObsoleteVarArgs = true;
758     if((F = Result->getNamedFunction("llvm.va_copy"))
759        && F->getFunctionType()->getNumParams() == 1)
760       ObsoleteVarArgs = true;
761   }
762
763   if (ObsoleteVarArgs && NewVarArgs)
764     ThrowException("This file is corrupt: it uses both new and old style varargs");
765
766   if(ObsoleteVarArgs) {
767     if(Function* F = Result->getNamedFunction("llvm.va_start")) {
768       if (F->arg_size() != 0)
769         ThrowException("Obsolete va_start takes 0 argument!");
770       
771       //foo = va_start()
772       // ->
773       //bar = alloca typeof(foo)
774       //va_start(bar)
775       //foo = load bar
776
777       const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
778       const Type* ArgTy = F->getFunctionType()->getReturnType();
779       const Type* ArgTyPtr = PointerType::get(ArgTy);
780       Function* NF = Result->getOrInsertFunction("llvm.va_start", 
781                                                  RetTy, ArgTyPtr, (Type *)0);
782
783       while (!F->use_empty()) {
784         CallInst* CI = cast<CallInst>(F->use_back());
785         AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
786         new CallInst(NF, bar, "", CI);
787         Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
788         CI->replaceAllUsesWith(foo);
789         CI->getParent()->getInstList().erase(CI);
790       }
791       Result->getFunctionList().erase(F);
792     }
793     
794     if(Function* F = Result->getNamedFunction("llvm.va_end")) {
795       if(F->arg_size() != 1)
796         ThrowException("Obsolete va_end takes 1 argument!");
797
798       //vaend foo
799       // ->
800       //bar = alloca 1 of typeof(foo)
801       //vaend bar
802       const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
803       const Type* ArgTy = F->getFunctionType()->getParamType(0);
804       const Type* ArgTyPtr = PointerType::get(ArgTy);
805       Function* NF = Result->getOrInsertFunction("llvm.va_end", 
806                                                  RetTy, ArgTyPtr, (Type *)0);
807
808       while (!F->use_empty()) {
809         CallInst* CI = cast<CallInst>(F->use_back());
810         AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
811         new StoreInst(CI->getOperand(1), bar, CI);
812         new CallInst(NF, bar, "", CI);
813         CI->getParent()->getInstList().erase(CI);
814       }
815       Result->getFunctionList().erase(F);
816     }
817
818     if(Function* F = Result->getNamedFunction("llvm.va_copy")) {
819       if(F->arg_size() != 1)
820         ThrowException("Obsolete va_copy takes 1 argument!");
821       //foo = vacopy(bar)
822       // ->
823       //a = alloca 1 of typeof(foo)
824       //b = alloca 1 of typeof(foo)
825       //store bar -> b
826       //vacopy(a, b)
827       //foo = load a
828       
829       const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
830       const Type* ArgTy = F->getFunctionType()->getReturnType();
831       const Type* ArgTyPtr = PointerType::get(ArgTy);
832       Function* NF = Result->getOrInsertFunction("llvm.va_copy", 
833                                                  RetTy, ArgTyPtr, ArgTyPtr,
834                                                  (Type *)0);
835
836       while (!F->use_empty()) {
837         CallInst* CI = cast<CallInst>(F->use_back());
838         AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
839         AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
840         new StoreInst(CI->getOperand(1), b, CI);
841         new CallInst(NF, a, b, "", CI);
842         Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
843         CI->replaceAllUsesWith(foo);
844         CI->getParent()->getInstList().erase(CI);
845       }
846       Result->getFunctionList().erase(F);
847     }
848   }
849
850   return Result;
851
852  }
853
854 //===----------------------------------------------------------------------===//
855 //            RunVMAsmParser - Define an interface to this parser
856 //===----------------------------------------------------------------------===//
857 //
858 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
859   set_scan_file(F);
860
861   CurFilename = Filename;
862   return RunParser(new Module(CurFilename));
863 }
864
865 Module *llvm::RunVMAsmParser(const char * AsmString, Module * M) {
866   set_scan_string(AsmString);
867
868   CurFilename = "from_memory";
869   if (M == NULL) {
870     return RunParser(new Module (CurFilename));
871   } else {
872     return RunParser(M);
873   }
874 }
875
876 %}
877
878 %union {
879   llvm::Module                           *ModuleVal;
880   llvm::Function                         *FunctionVal;
881   std::pair<llvm::PATypeHolder*, char*>  *ArgVal;
882   llvm::BasicBlock                       *BasicBlockVal;
883   llvm::TerminatorInst                   *TermInstVal;
884   llvm::Instruction                      *InstVal;
885   llvm::Constant                         *ConstVal;
886
887   const llvm::Type                       *PrimType;
888   llvm::PATypeHolder                     *TypeVal;
889   llvm::Value                            *ValueVal;
890
891   std::vector<std::pair<llvm::PATypeHolder*,char*> > *ArgList;
892   std::vector<llvm::Value*>              *ValueList;
893   std::list<llvm::PATypeHolder>          *TypeList;
894   // Represent the RHS of PHI node
895   std::list<std::pair<llvm::Value*,
896                       llvm::BasicBlock*> > *PHIList;
897   std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
898   std::vector<llvm::Constant*>           *ConstVector;
899
900   llvm::GlobalValue::LinkageTypes         Linkage;
901   int64_t                           SInt64Val;
902   uint64_t                          UInt64Val;
903   int                               SIntVal;
904   unsigned                          UIntVal;
905   double                            FPVal;
906   bool                              BoolVal;
907
908   char                             *StrVal;   // This memory is strdup'd!
909   llvm::ValID                             ValIDVal; // strdup'd memory maybe!
910
911   llvm::Instruction::BinaryOps            BinaryOpVal;
912   llvm::Instruction::TermOps              TermOpVal;
913   llvm::Instruction::MemoryOps            MemOpVal;
914   llvm::Instruction::OtherOps             OtherOpVal;
915   llvm::Module::Endianness                Endianness;
916 }
917
918 %type <ModuleVal>     Module FunctionList
919 %type <FunctionVal>   Function FunctionProto FunctionHeader BasicBlockList
920 %type <BasicBlockVal> BasicBlock InstructionList
921 %type <TermInstVal>   BBTerminatorInst
922 %type <InstVal>       Inst InstVal MemoryInst
923 %type <ConstVal>      ConstVal ConstExpr
924 %type <ConstVector>   ConstVector
925 %type <ArgList>       ArgList ArgListH
926 %type <ArgVal>        ArgVal
927 %type <PHIList>       PHIList
928 %type <ValueList>     ValueRefList ValueRefListE  // For call param lists
929 %type <ValueList>     IndexList                   // For GEP derived indices
930 %type <TypeList>      TypeListI ArgTypeListI
931 %type <JumpTable>     JumpTable
932 %type <BoolVal>       GlobalType                  // GLOBAL or CONSTANT?
933 %type <BoolVal>       OptVolatile                 // 'volatile' or not
934 %type <BoolVal>       OptTailCall                 // TAIL CALL or plain CALL.
935 %type <Linkage>       OptLinkage
936 %type <Endianness>    BigOrLittle
937
938 // ValueRef - Unresolved reference to a definition or BB
939 %type <ValIDVal>      ValueRef ConstValueRef SymbolicValueRef
940 %type <ValueVal>      ResolvedVal            // <type> <valref> pair
941 // Tokens and types for handling constant integer values
942 //
943 // ESINT64VAL - A negative number within long long range
944 %token <SInt64Val> ESINT64VAL
945
946 // EUINT64VAL - A positive number within uns. long long range
947 %token <UInt64Val> EUINT64VAL
948 %type  <SInt64Val> EINT64VAL
949
950 %token  <SIntVal>   SINTVAL   // Signed 32 bit ints...
951 %token  <UIntVal>   UINTVAL   // Unsigned 32 bit ints...
952 %type   <SIntVal>   INTVAL
953 %token  <FPVal>     FPVAL     // Float or Double constant
954
955 // Built in types...
956 %type  <TypeVal> Types TypesV UpRTypes UpRTypesV
957 %type  <PrimType> SIntType UIntType IntType FPType PrimType   // Classifications
958 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
959 %token <PrimType> FLOAT DOUBLE TYPE LABEL
960
961 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
962 %type  <StrVal> Name OptName OptAssign
963 %type  <UIntVal> OptAlign OptCAlign
964 %type <StrVal> OptSection SectionString
965
966 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
967 %token DECLARE GLOBAL CONSTANT SECTION VOLATILE
968 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK  APPENDING
969 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
970 %token DEPLIBS CALL TAIL
971 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK
972 %type <UIntVal> OptCallingConv
973
974 // Basic Block Terminating Operators
975 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
976
977 // Binary Operators
978 %type  <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
979 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
980 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE  // Binary Comarators
981
982 // Memory Instructions
983 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
984
985 // Other Operators
986 %type  <OtherOpVal> ShiftOps
987 %token <OtherOpVal> PHI_TOK CAST SELECT SHL SHR VAARG
988 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT
989 %token VAARG_old VANEXT_old //OBSOLETE
990
991
992 %start Module
993 %%
994
995 // Handle constant integer size restriction and conversion...
996 //
997 INTVAL : SINTVAL;
998 INTVAL : UINTVAL {
999   if ($1 > (uint32_t)INT32_MAX)     // Outside of my range!
1000     ThrowException("Value too large for type!");
1001   $$ = (int32_t)$1;
1002 };
1003
1004
1005 EINT64VAL : ESINT64VAL;      // These have same type and can't cause problems...
1006 EINT64VAL : EUINT64VAL {
1007   if ($1 > (uint64_t)INT64_MAX)     // Outside of my range!
1008     ThrowException("Value too large for type!");
1009   $$ = (int64_t)$1;
1010 };
1011
1012 // Operations that are notably excluded from this list include:
1013 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1014 //
1015 ArithmeticOps: ADD | SUB | MUL | DIV | REM;
1016 LogicalOps   : AND | OR | XOR;
1017 SetCondOps   : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
1018
1019 ShiftOps  : SHL | SHR;
1020
1021 // These are some types that allow classification if we only want a particular 
1022 // thing... for example, only a signed, unsigned, or integral type.
1023 SIntType :  LONG |  INT |  SHORT | SBYTE;
1024 UIntType : ULONG | UINT | USHORT | UBYTE;
1025 IntType  : SIntType | UIntType;
1026 FPType   : FLOAT | DOUBLE;
1027
1028 // OptAssign - Value producing statements have an optional assignment component
1029 OptAssign : Name '=' {
1030     $$ = $1;
1031   }
1032   | /*empty*/ {
1033     $$ = 0;
1034   };
1035
1036 OptLinkage : INTERNAL  { $$ = GlobalValue::InternalLinkage; } |
1037              LINKONCE  { $$ = GlobalValue::LinkOnceLinkage; } |
1038              WEAK      { $$ = GlobalValue::WeakLinkage; } |
1039              APPENDING { $$ = GlobalValue::AppendingLinkage; } |
1040              /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
1041
1042 OptCallingConv : /*empty*/      { $$ = CallingConv::C; } |
1043                  CCC_TOK        { $$ = CallingConv::C; } |
1044                  FASTCC_TOK     { $$ = CallingConv::Fast; } |
1045                  COLDCC_TOK     { $$ = CallingConv::Cold; } |
1046                  CC_TOK EUINT64VAL {
1047                    if ((unsigned)$2 != $2)
1048                      ThrowException("Calling conv too large!");
1049                    $$ = $2;
1050                  };
1051
1052 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1053 // a comma before it.
1054 OptAlign : /*empty*/        { $$ = 0; } |
1055            ALIGN EUINT64VAL {
1056   $$ = $2;
1057   if ($$ != 0 && !isPowerOf2_32($$))
1058     ThrowException("Alignment must be a power of two!");
1059 };
1060 OptCAlign : /*empty*/            { $$ = 0; } |
1061             ',' ALIGN EUINT64VAL {
1062   $$ = $3;
1063   if ($$ != 0 && !isPowerOf2_32($$))
1064     ThrowException("Alignment must be a power of two!");
1065 };
1066
1067
1068 SectionString : SECTION STRINGCONSTANT {
1069   for (unsigned i = 0, e = strlen($2); i != e; ++i)
1070     if ($2[i] == '"' || $2[i] == '\\')
1071       ThrowException("Invalid character in section name!");
1072   $$ = $2;
1073 };
1074
1075 OptSection : /*empty*/ { $$ = 0; } |
1076              SectionString { $$ = $1; };
1077
1078 // GlobalVarAttributes - Used to pass the attributes string on a global.  CurGV
1079 // is set to be the global we are processing.
1080 //
1081 GlobalVarAttributes : /* empty */ {} |
1082                      ',' GlobalVarAttribute GlobalVarAttributes {};
1083 GlobalVarAttribute : SectionString {
1084     CurGV->setSection($1);
1085     free($1);
1086   } 
1087   | ALIGN EUINT64VAL {
1088     if ($2 != 0 && !isPowerOf2_32($2))
1089       ThrowException("Alignment must be a power of two!");
1090     CurGV->setAlignment($2);
1091   };
1092
1093 //===----------------------------------------------------------------------===//
1094 // Types includes all predefined types... except void, because it can only be
1095 // used in specific contexts (function returning void for example).  To have
1096 // access to it, a user must explicitly use TypesV.
1097 //
1098
1099 // TypesV includes all of 'Types', but it also includes the void type.
1100 TypesV    : Types    | VOID { $$ = new PATypeHolder($1); };
1101 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
1102
1103 Types     : UpRTypes {
1104     if (!UpRefs.empty())
1105       ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
1106     $$ = $1;
1107   };
1108
1109
1110 // Derived types are added later...
1111 //
1112 PrimType : BOOL | SBYTE | UBYTE | SHORT  | USHORT | INT   | UINT ;
1113 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE   | LABEL;
1114 UpRTypes : OPAQUE {
1115     $$ = new PATypeHolder(OpaqueType::get());
1116   }
1117   | PrimType {
1118     $$ = new PATypeHolder($1);
1119   };
1120 UpRTypes : SymbolicValueRef {            // Named types are also simple types...
1121   $$ = new PATypeHolder(getTypeVal($1));
1122 };
1123
1124 // Include derived types in the Types production.
1125 //
1126 UpRTypes : '\\' EUINT64VAL {                   // Type UpReference
1127     if ($2 > (uint64_t)~0U) ThrowException("Value out of range!");
1128     OpaqueType *OT = OpaqueType::get();        // Use temporary placeholder
1129     UpRefs.push_back(UpRefRecord((unsigned)$2, OT));  // Add to vector...
1130     $$ = new PATypeHolder(OT);
1131     UR_OUT("New Upreference!\n");
1132   }
1133   | UpRTypesV '(' ArgTypeListI ')' {           // Function derived type?
1134     std::vector<const Type*> Params;
1135     for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1136            E = $3->end(); I != E; ++I)
1137       Params.push_back(*I);
1138     bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1139     if (isVarArg) Params.pop_back();
1140
1141     $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
1142     delete $3;      // Delete the argument list
1143     delete $1;      // Delete the return type handle
1144   }
1145   | '[' EUINT64VAL 'x' UpRTypes ']' {          // Sized array type?
1146     $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1147     delete $4;
1148   }
1149   | '<' EUINT64VAL 'x' UpRTypes '>' {          // Packed array type?
1150      const llvm::Type* ElemTy = $4->get();
1151      if ((unsigned)$2 != $2)
1152         ThrowException("Unsigned result not equal to signed result");
1153      if (!ElemTy->isPrimitiveType())
1154         ThrowException("Elemental type of a PackedType must be primitive");
1155      if (!isPowerOf2_32($2))
1156        ThrowException("Vector length should be a power of 2!");
1157      $$ = new PATypeHolder(HandleUpRefs(PackedType::get(*$4, (unsigned)$2)));
1158      delete $4;
1159   }
1160   | '{' TypeListI '}' {                        // Structure type?
1161     std::vector<const Type*> Elements;
1162     for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1163            E = $2->end(); I != E; ++I)
1164       Elements.push_back(*I);
1165
1166     $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1167     delete $2;
1168   }
1169   | '{' '}' {                                  // Empty structure type?
1170     $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1171   }
1172   | UpRTypes '*' {                             // Pointer type?
1173     $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1174     delete $1;
1175   };
1176
1177 // TypeList - Used for struct declarations and as a basis for function type 
1178 // declaration type lists
1179 //
1180 TypeListI : UpRTypes {
1181     $$ = new std::list<PATypeHolder>();
1182     $$->push_back(*$1); delete $1;
1183   }
1184   | TypeListI ',' UpRTypes {
1185     ($$=$1)->push_back(*$3); delete $3;
1186   };
1187
1188 // ArgTypeList - List of types for a function type declaration...
1189 ArgTypeListI : TypeListI
1190   | TypeListI ',' DOTDOTDOT {
1191     ($$=$1)->push_back(Type::VoidTy);
1192   }
1193   | DOTDOTDOT {
1194     ($$ = new std::list<PATypeHolder>())->push_back(Type::VoidTy);
1195   }
1196   | /*empty*/ {
1197     $$ = new std::list<PATypeHolder>();
1198   };
1199
1200 // ConstVal - The various declarations that go into the constant pool.  This
1201 // production is used ONLY to represent constants that show up AFTER a 'const',
1202 // 'constant' or 'global' token at global scope.  Constants that can be inlined
1203 // into other expressions (such as integers and constexprs) are handled by the
1204 // ResolvedVal, ValueRef and ConstValueRef productions.
1205 //
1206 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1207     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1208     if (ATy == 0)
1209       ThrowException("Cannot make array constant with type: '" + 
1210                      (*$1)->getDescription() + "'!");
1211     const Type *ETy = ATy->getElementType();
1212     int NumElements = ATy->getNumElements();
1213
1214     // Verify that we have the correct size...
1215     if (NumElements != -1 && NumElements != (int)$3->size())
1216       ThrowException("Type mismatch: constant sized array initialized with " +
1217                      utostr($3->size()) +  " arguments, but has size of " + 
1218                      itostr(NumElements) + "!");
1219
1220     // Verify all elements are correct type!
1221     for (unsigned i = 0; i < $3->size(); i++) {
1222       if (ETy != (*$3)[i]->getType())
1223         ThrowException("Element #" + utostr(i) + " is not of type '" + 
1224                        ETy->getDescription() +"' as required!\nIt is of type '"+
1225                        (*$3)[i]->getType()->getDescription() + "'.");
1226     }
1227
1228     $$ = ConstantArray::get(ATy, *$3);
1229     delete $1; delete $3;
1230   }
1231   | Types '[' ']' {
1232     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1233     if (ATy == 0)
1234       ThrowException("Cannot make array constant with type: '" + 
1235                      (*$1)->getDescription() + "'!");
1236
1237     int NumElements = ATy->getNumElements();
1238     if (NumElements != -1 && NumElements != 0) 
1239       ThrowException("Type mismatch: constant sized array initialized with 0"
1240                      " arguments, but has size of " + itostr(NumElements) +"!");
1241     $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1242     delete $1;
1243   }
1244   | Types 'c' STRINGCONSTANT {
1245     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1246     if (ATy == 0)
1247       ThrowException("Cannot make array constant with type: '" + 
1248                      (*$1)->getDescription() + "'!");
1249
1250     int NumElements = ATy->getNumElements();
1251     const Type *ETy = ATy->getElementType();
1252     char *EndStr = UnEscapeLexed($3, true);
1253     if (NumElements != -1 && NumElements != (EndStr-$3))
1254       ThrowException("Can't build string constant of size " + 
1255                      itostr((int)(EndStr-$3)) +
1256                      " when array has size " + itostr(NumElements) + "!");
1257     std::vector<Constant*> Vals;
1258     if (ETy == Type::SByteTy) {
1259       for (char *C = $3; C != EndStr; ++C)
1260         Vals.push_back(ConstantSInt::get(ETy, *C));
1261     } else if (ETy == Type::UByteTy) {
1262       for (char *C = $3; C != EndStr; ++C)
1263         Vals.push_back(ConstantUInt::get(ETy, (unsigned char)*C));
1264     } else {
1265       free($3);
1266       ThrowException("Cannot build string arrays of non byte sized elements!");
1267     }
1268     free($3);
1269     $$ = ConstantArray::get(ATy, Vals);
1270     delete $1;
1271   }
1272   | Types '<' ConstVector '>' { // Nonempty unsized arr
1273     const PackedType *PTy = dyn_cast<PackedType>($1->get());
1274     if (PTy == 0)
1275       ThrowException("Cannot make packed constant with type: '" + 
1276                      (*$1)->getDescription() + "'!");
1277     const Type *ETy = PTy->getElementType();
1278     int NumElements = PTy->getNumElements();
1279
1280     // Verify that we have the correct size...
1281     if (NumElements != -1 && NumElements != (int)$3->size())
1282       ThrowException("Type mismatch: constant sized packed initialized with " +
1283                      utostr($3->size()) +  " arguments, but has size of " + 
1284                      itostr(NumElements) + "!");
1285
1286     // Verify all elements are correct type!
1287     for (unsigned i = 0; i < $3->size(); i++) {
1288       if (ETy != (*$3)[i]->getType())
1289         ThrowException("Element #" + utostr(i) + " is not of type '" + 
1290            ETy->getDescription() +"' as required!\nIt is of type '"+
1291            (*$3)[i]->getType()->getDescription() + "'.");
1292     }
1293
1294     $$ = ConstantPacked::get(PTy, *$3);
1295     delete $1; delete $3;
1296   }
1297   | Types '{' ConstVector '}' {
1298     const StructType *STy = dyn_cast<StructType>($1->get());
1299     if (STy == 0)
1300       ThrowException("Cannot make struct constant with type: '" + 
1301                      (*$1)->getDescription() + "'!");
1302
1303     if ($3->size() != STy->getNumContainedTypes())
1304       ThrowException("Illegal number of initializers for structure type!");
1305
1306     // Check to ensure that constants are compatible with the type initializer!
1307     for (unsigned i = 0, e = $3->size(); i != e; ++i)
1308       if ((*$3)[i]->getType() != STy->getElementType(i))
1309         ThrowException("Expected type '" +
1310                        STy->getElementType(i)->getDescription() +
1311                        "' for element #" + utostr(i) +
1312                        " of structure initializer!");
1313
1314     $$ = ConstantStruct::get(STy, *$3);
1315     delete $1; delete $3;
1316   }
1317   | Types '{' '}' {
1318     const StructType *STy = dyn_cast<StructType>($1->get());
1319     if (STy == 0)
1320       ThrowException("Cannot make struct constant with type: '" + 
1321                      (*$1)->getDescription() + "'!");
1322
1323     if (STy->getNumContainedTypes() != 0)
1324       ThrowException("Illegal number of initializers for structure type!");
1325
1326     $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1327     delete $1;
1328   }
1329   | Types NULL_TOK {
1330     const PointerType *PTy = dyn_cast<PointerType>($1->get());
1331     if (PTy == 0)
1332       ThrowException("Cannot make null pointer constant with type: '" + 
1333                      (*$1)->getDescription() + "'!");
1334
1335     $$ = ConstantPointerNull::get(PTy);
1336     delete $1;
1337   }
1338   | Types UNDEF {
1339     $$ = UndefValue::get($1->get());
1340     delete $1;
1341   }
1342   | Types SymbolicValueRef {
1343     const PointerType *Ty = dyn_cast<PointerType>($1->get());
1344     if (Ty == 0)
1345       ThrowException("Global const reference must be a pointer type!");
1346
1347     // ConstExprs can exist in the body of a function, thus creating
1348     // GlobalValues whenever they refer to a variable.  Because we are in
1349     // the context of a function, getValNonImprovising will search the functions
1350     // symbol table instead of the module symbol table for the global symbol,
1351     // which throws things all off.  To get around this, we just tell
1352     // getValNonImprovising that we are at global scope here.
1353     //
1354     Function *SavedCurFn = CurFun.CurrentFunction;
1355     CurFun.CurrentFunction = 0;
1356
1357     Value *V = getValNonImprovising(Ty, $2);
1358
1359     CurFun.CurrentFunction = SavedCurFn;
1360
1361     // If this is an initializer for a constant pointer, which is referencing a
1362     // (currently) undefined variable, create a stub now that shall be replaced
1363     // in the future with the right type of variable.
1364     //
1365     if (V == 0) {
1366       assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1367       const PointerType *PT = cast<PointerType>(Ty);
1368
1369       // First check to see if the forward references value is already created!
1370       PerModuleInfo::GlobalRefsType::iterator I =
1371         CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1372     
1373       if (I != CurModule.GlobalRefs.end()) {
1374         V = I->second;             // Placeholder already exists, use it...
1375         $2.destroy();
1376       } else {
1377         std::string Name;
1378         if ($2.Type == ValID::NameVal) Name = $2.Name;
1379
1380         // Create the forward referenced global.
1381         GlobalValue *GV;
1382         if (const FunctionType *FTy = 
1383                  dyn_cast<FunctionType>(PT->getElementType())) {
1384           GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1385                             CurModule.CurrentModule);
1386         } else {
1387           GV = new GlobalVariable(PT->getElementType(), false,
1388                                   GlobalValue::ExternalLinkage, 0,
1389                                   Name, CurModule.CurrentModule);
1390         }
1391
1392         // Keep track of the fact that we have a forward ref to recycle it
1393         CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1394         V = GV;
1395       }
1396     }
1397
1398     $$ = cast<GlobalValue>(V);
1399     delete $1;            // Free the type handle
1400   }
1401   | Types ConstExpr {
1402     if ($1->get() != $2->getType())
1403       ThrowException("Mismatched types for constant expression!");
1404     $$ = $2;
1405     delete $1;
1406   }
1407   | Types ZEROINITIALIZER {
1408     const Type *Ty = $1->get();
1409     if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1410       ThrowException("Cannot create a null initialized value of this type!");
1411     $$ = Constant::getNullValue(Ty);
1412     delete $1;
1413   };
1414
1415 ConstVal : SIntType EINT64VAL {      // integral constants
1416     if (!ConstantSInt::isValueValidForType($1, $2))
1417       ThrowException("Constant value doesn't fit in type!");
1418     $$ = ConstantSInt::get($1, $2);
1419   }
1420   | UIntType EUINT64VAL {            // integral constants
1421     if (!ConstantUInt::isValueValidForType($1, $2))
1422       ThrowException("Constant value doesn't fit in type!");
1423     $$ = ConstantUInt::get($1, $2);
1424   }
1425   | BOOL TRUETOK {                      // Boolean constants
1426     $$ = ConstantBool::True;
1427   }
1428   | BOOL FALSETOK {                     // Boolean constants
1429     $$ = ConstantBool::False;
1430   }
1431   | FPType FPVAL {                   // Float & Double constants
1432     if (!ConstantFP::isValueValidForType($1, $2))
1433       ThrowException("Floating point constant invalid for type!!");
1434     $$ = ConstantFP::get($1, $2);
1435   };
1436
1437
1438 ConstExpr: CAST '(' ConstVal TO Types ')' {
1439     if (!$3->getType()->isFirstClassType())
1440       ThrowException("cast constant expression from a non-primitive type: '" +
1441                      $3->getType()->getDescription() + "'!");
1442     if (!$5->get()->isFirstClassType())
1443       ThrowException("cast constant expression to a non-primitive type: '" +
1444                      $5->get()->getDescription() + "'!");
1445     $$ = ConstantExpr::getCast($3, $5->get());
1446     delete $5;
1447   }
1448   | GETELEMENTPTR '(' ConstVal IndexList ')' {
1449     if (!isa<PointerType>($3->getType()))
1450       ThrowException("GetElementPtr requires a pointer operand!");
1451
1452     // LLVM 1.2 and earlier used ubyte struct indices.  Convert any ubyte struct
1453     // indices to uint struct indices for compatibility.
1454     generic_gep_type_iterator<std::vector<Value*>::iterator>
1455       GTI = gep_type_begin($3->getType(), $4->begin(), $4->end()),
1456       GTE = gep_type_end($3->getType(), $4->begin(), $4->end());
1457     for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
1458       if (isa<StructType>(*GTI))        // Only change struct indices
1459         if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
1460           if (CUI->getType() == Type::UByteTy)
1461             (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
1462
1463     const Type *IdxTy =
1464       GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1465     if (!IdxTy)
1466       ThrowException("Index list invalid for constant getelementptr!");
1467
1468     std::vector<Constant*> IdxVec;
1469     for (unsigned i = 0, e = $4->size(); i != e; ++i)
1470       if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1471         IdxVec.push_back(C);
1472       else
1473         ThrowException("Indices to constant getelementptr must be constants!");
1474
1475     delete $4;
1476
1477     $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1478   }
1479   | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1480     if ($3->getType() != Type::BoolTy)
1481       ThrowException("Select condition must be of boolean type!");
1482     if ($5->getType() != $7->getType())
1483       ThrowException("Select operand types must match!");
1484     $$ = ConstantExpr::getSelect($3, $5, $7);
1485   }
1486   | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1487     if ($3->getType() != $5->getType())
1488       ThrowException("Binary operator types must match!");
1489     // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
1490     // To retain backward compatibility with these early compilers, we emit a
1491     // cast to the appropriate integer type automatically if we are in the
1492     // broken case.  See PR424 for more information.
1493     if (!isa<PointerType>($3->getType())) {
1494       $$ = ConstantExpr::get($1, $3, $5);
1495     } else {
1496       const Type *IntPtrTy = 0;
1497       switch (CurModule.CurrentModule->getPointerSize()) {
1498       case Module::Pointer32: IntPtrTy = Type::IntTy; break;
1499       case Module::Pointer64: IntPtrTy = Type::LongTy; break;
1500       default: ThrowException("invalid pointer binary constant expr!");
1501       }
1502       $$ = ConstantExpr::get($1, ConstantExpr::getCast($3, IntPtrTy),
1503                              ConstantExpr::getCast($5, IntPtrTy));
1504       $$ = ConstantExpr::getCast($$, $3->getType());
1505     }
1506   }
1507   | LogicalOps '(' ConstVal ',' ConstVal ')' {
1508     if ($3->getType() != $5->getType())
1509       ThrowException("Logical operator types must match!");
1510     if (!$3->getType()->isIntegral()) {
1511       if (!isa<PackedType>($3->getType()) || 
1512           !cast<PackedType>($3->getType())->getElementType()->isIntegral())
1513         ThrowException("Logical operator requires integral operands!");
1514     }
1515     $$ = ConstantExpr::get($1, $3, $5);
1516   }
1517   | SetCondOps '(' ConstVal ',' ConstVal ')' {
1518     if ($3->getType() != $5->getType())
1519       ThrowException("setcc operand types must match!");
1520     $$ = ConstantExpr::get($1, $3, $5);
1521   }
1522   | ShiftOps '(' ConstVal ',' ConstVal ')' {
1523     if ($5->getType() != Type::UByteTy)
1524       ThrowException("Shift count for shift constant must be unsigned byte!");
1525     if (!$3->getType()->isInteger())
1526       ThrowException("Shift constant expression requires integer operand!");
1527     $$ = ConstantExpr::get($1, $3, $5);
1528   }
1529   | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1530         if (!isa<PackedType>($3->getType()))
1531       ThrowException("First operand of extractelement must be "
1532                      "packed type!");
1533     if ($5->getType() != Type::UIntTy)
1534       ThrowException("Second operand of extractelement must be uint!");
1535     $$ = ConstantExpr::getExtractElement($3, $5);
1536   };
1537
1538 // ConstVector - A list of comma separated constants.
1539 ConstVector : ConstVector ',' ConstVal {
1540     ($$ = $1)->push_back($3);
1541   }
1542   | ConstVal {
1543     $$ = new std::vector<Constant*>();
1544     $$->push_back($1);
1545   };
1546
1547
1548 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1549 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1550
1551
1552 //===----------------------------------------------------------------------===//
1553 //                             Rules to match Modules
1554 //===----------------------------------------------------------------------===//
1555
1556 // Module rule: Capture the result of parsing the whole file into a result
1557 // variable...
1558 //
1559 Module : FunctionList {
1560   $$ = ParserResult = $1;
1561   CurModule.ModuleDone();
1562 };
1563
1564 // FunctionList - A list of functions, preceeded by a constant pool.
1565 //
1566 FunctionList : FunctionList Function {
1567     $$ = $1;
1568     CurFun.FunctionDone();
1569   } 
1570   | FunctionList FunctionProto {
1571     $$ = $1;
1572   }
1573   | FunctionList IMPLEMENTATION {
1574     $$ = $1;
1575   }
1576   | ConstPool {
1577     $$ = CurModule.CurrentModule;
1578     // Emit an error if there are any unresolved types left.
1579     if (!CurModule.LateResolveTypes.empty()) {
1580       const ValID &DID = CurModule.LateResolveTypes.begin()->first;
1581       if (DID.Type == ValID::NameVal)
1582         ThrowException("Reference to an undefined type: '"+DID.getName() + "'");
1583       else
1584         ThrowException("Reference to an undefined type: #" + itostr(DID.Num));
1585     }
1586   };
1587
1588 // ConstPool - Constants with optional names assigned to them.
1589 ConstPool : ConstPool OptAssign TYPE TypesV {
1590     // Eagerly resolve types.  This is not an optimization, this is a
1591     // requirement that is due to the fact that we could have this:
1592     //
1593     // %list = type { %list * }
1594     // %list = type { %list * }    ; repeated type decl
1595     //
1596     // If types are not resolved eagerly, then the two types will not be
1597     // determined to be the same type!
1598     //
1599     ResolveTypeTo($2, *$4);
1600
1601     if (!setTypeName(*$4, $2) && !$2) {
1602       // If this is a named type that is not a redefinition, add it to the slot
1603       // table.
1604       CurModule.Types.push_back(*$4);
1605     }
1606
1607     delete $4;
1608   }
1609   | ConstPool FunctionProto {       // Function prototypes can be in const pool
1610   }
1611   | ConstPool OptAssign OptLinkage GlobalType ConstVal {
1612     if ($5 == 0) ThrowException("Global value initializer is not a constant!");
1613     CurGV = ParseGlobalVariable($2, $3, $4, $5->getType(), $5);
1614                                                        } GlobalVarAttributes {
1615     CurGV = 0;
1616   }
1617   | ConstPool OptAssign EXTERNAL GlobalType Types {
1618     CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage,
1619                                              $4, *$5, 0);
1620     delete $5;
1621                                                    } GlobalVarAttributes {
1622     CurGV = 0;
1623   }
1624   | ConstPool TARGET TargetDefinition { 
1625   }
1626   | ConstPool DEPLIBS '=' LibrariesDefinition {
1627   }
1628   | /* empty: end of list */ { 
1629   };
1630
1631
1632
1633 BigOrLittle : BIG    { $$ = Module::BigEndian; };
1634 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1635
1636 TargetDefinition : ENDIAN '=' BigOrLittle {
1637     CurModule.CurrentModule->setEndianness($3);
1638   }
1639   | POINTERSIZE '=' EUINT64VAL {
1640     if ($3 == 32)
1641       CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1642     else if ($3 == 64)
1643       CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1644     else
1645       ThrowException("Invalid pointer size: '" + utostr($3) + "'!");
1646   }
1647   | TRIPLE '=' STRINGCONSTANT {
1648     CurModule.CurrentModule->setTargetTriple($3);
1649     free($3);
1650   };
1651
1652 LibrariesDefinition : '[' LibList ']';
1653
1654 LibList : LibList ',' STRINGCONSTANT {
1655           CurModule.CurrentModule->addLibrary($3);
1656           free($3);
1657         }
1658         | STRINGCONSTANT {
1659           CurModule.CurrentModule->addLibrary($1);
1660           free($1);
1661         }
1662         | /* empty: end of list */ {
1663         }
1664         ;
1665
1666 //===----------------------------------------------------------------------===//
1667 //                       Rules to match Function Headers
1668 //===----------------------------------------------------------------------===//
1669
1670 Name : VAR_ID | STRINGCONSTANT;
1671 OptName : Name | /*empty*/ { $$ = 0; };
1672
1673 ArgVal : Types OptName {
1674   if (*$1 == Type::VoidTy)
1675     ThrowException("void typed arguments are invalid!");
1676   $$ = new std::pair<PATypeHolder*, char*>($1, $2);
1677 };
1678
1679 ArgListH : ArgListH ',' ArgVal {
1680     $$ = $1;
1681     $1->push_back(*$3);
1682     delete $3;
1683   }
1684   | ArgVal {
1685     $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1686     $$->push_back(*$1);
1687     delete $1;
1688   };
1689
1690 ArgList : ArgListH {
1691     $$ = $1;
1692   }
1693   | ArgListH ',' DOTDOTDOT {
1694     $$ = $1;
1695     $$->push_back(std::pair<PATypeHolder*,
1696                             char*>(new PATypeHolder(Type::VoidTy), 0));
1697   }
1698   | DOTDOTDOT {
1699     $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1700     $$->push_back(std::make_pair(new PATypeHolder(Type::VoidTy), (char*)0));
1701   }
1702   | /* empty */ {
1703     $$ = 0;
1704   };
1705
1706 FunctionHeaderH : OptCallingConv TypesV Name '(' ArgList ')' 
1707                   OptSection OptAlign {
1708   UnEscapeLexed($3);
1709   std::string FunctionName($3);
1710   free($3);  // Free strdup'd memory!
1711   
1712   if (!(*$2)->isFirstClassType() && *$2 != Type::VoidTy)
1713     ThrowException("LLVM functions cannot return aggregate types!");
1714
1715   std::vector<const Type*> ParamTypeList;
1716   if ($5) {   // If there are arguments...
1717     for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
1718          I != $5->end(); ++I)
1719       ParamTypeList.push_back(I->first->get());
1720   }
1721
1722   bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1723   if (isVarArg) ParamTypeList.pop_back();
1724
1725   const FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
1726   const PointerType *PFT = PointerType::get(FT);
1727   delete $2;
1728
1729   ValID ID;
1730   if (!FunctionName.empty()) {
1731     ID = ValID::create((char*)FunctionName.c_str());
1732   } else {
1733     ID = ValID::create((int)CurModule.Values[PFT].size());
1734   }
1735
1736   Function *Fn = 0;
1737   // See if this function was forward referenced.  If so, recycle the object.
1738   if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
1739     // Move the function to the end of the list, from whereever it was 
1740     // previously inserted.
1741     Fn = cast<Function>(FWRef);
1742     CurModule.CurrentModule->getFunctionList().remove(Fn);
1743     CurModule.CurrentModule->getFunctionList().push_back(Fn);
1744   } else if (!FunctionName.empty() &&     // Merge with an earlier prototype?
1745              (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
1746     // If this is the case, either we need to be a forward decl, or it needs 
1747     // to be.
1748     if (!CurFun.isDeclare && !Fn->isExternal())
1749       ThrowException("Redefinition of function '" + FunctionName + "'!");
1750     
1751     // Make sure to strip off any argument names so we can't get conflicts.
1752     if (Fn->isExternal())
1753       for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
1754            AI != AE; ++AI)
1755         AI->setName("");
1756
1757   } else  {  // Not already defined?
1758     Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
1759                       CurModule.CurrentModule);
1760     InsertValue(Fn, CurModule.Values);
1761   }
1762
1763   CurFun.FunctionStart(Fn);
1764   Fn->setCallingConv($1);
1765   Fn->setAlignment($8);
1766   if ($7) {
1767     Fn->setSection($7);
1768     free($7);
1769   }
1770
1771   // Add all of the arguments we parsed to the function...
1772   if ($5) {                     // Is null if empty...
1773     if (isVarArg) {  // Nuke the last entry
1774       assert($5->back().first->get() == Type::VoidTy && $5->back().second == 0&&
1775              "Not a varargs marker!");
1776       delete $5->back().first;
1777       $5->pop_back();  // Delete the last entry
1778     }
1779     Function::arg_iterator ArgIt = Fn->arg_begin();
1780     for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
1781          I != $5->end(); ++I, ++ArgIt) {
1782       delete I->first;                          // Delete the typeholder...
1783
1784       setValueName(ArgIt, I->second);           // Insert arg into symtab...
1785       InsertValue(ArgIt);
1786     }
1787
1788     delete $5;                     // We're now done with the argument list
1789   }
1790 };
1791
1792 BEGIN : BEGINTOK | '{';                // Allow BEGIN or '{' to start a function
1793
1794 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
1795   $$ = CurFun.CurrentFunction;
1796
1797   // Make sure that we keep track of the linkage type even if there was a
1798   // previous "declare".
1799   $$->setLinkage($1);
1800 };
1801
1802 END : ENDTOK | '}';                    // Allow end of '}' to end a function
1803
1804 Function : BasicBlockList END {
1805   $$ = $1;
1806 };
1807
1808 FunctionProto : DECLARE { CurFun.isDeclare = true; } FunctionHeaderH {
1809   $$ = CurFun.CurrentFunction;
1810   CurFun.FunctionDone();
1811 };
1812
1813 //===----------------------------------------------------------------------===//
1814 //                        Rules to match Basic Blocks
1815 //===----------------------------------------------------------------------===//
1816
1817 ConstValueRef : ESINT64VAL {    // A reference to a direct constant
1818     $$ = ValID::create($1);
1819   }
1820   | EUINT64VAL {
1821     $$ = ValID::create($1);
1822   }
1823   | FPVAL {                     // Perhaps it's an FP constant?
1824     $$ = ValID::create($1);
1825   }
1826   | TRUETOK {
1827     $$ = ValID::create(ConstantBool::True);
1828   } 
1829   | FALSETOK {
1830     $$ = ValID::create(ConstantBool::False);
1831   }
1832   | NULL_TOK {
1833     $$ = ValID::createNull();
1834   }
1835   | UNDEF {
1836     $$ = ValID::createUndef();
1837   }
1838   | ZEROINITIALIZER {     // A vector zero constant.
1839     $$ = ValID::createZeroInit();
1840   }
1841   | '<' ConstVector '>' { // Nonempty unsized packed vector
1842     const Type *ETy = (*$2)[0]->getType();
1843     int NumElements = $2->size(); 
1844     
1845     PackedType* pt = PackedType::get(ETy, NumElements);
1846     PATypeHolder* PTy = new PATypeHolder(
1847                                          HandleUpRefs(
1848                                             PackedType::get(
1849                                                 ETy, 
1850                                                 NumElements)
1851                                             )
1852                                          );
1853     
1854     // Verify all elements are correct type!
1855     for (unsigned i = 0; i < $2->size(); i++) {
1856       if (ETy != (*$2)[i]->getType())
1857         ThrowException("Element #" + utostr(i) + " is not of type '" + 
1858                      ETy->getDescription() +"' as required!\nIt is of type '" +
1859                      (*$2)[i]->getType()->getDescription() + "'.");
1860     }
1861
1862     $$ = ValID::create(ConstantPacked::get(pt, *$2));
1863     delete PTy; delete $2;
1864   }
1865   | ConstExpr {
1866     $$ = ValID::create($1);
1867   };
1868
1869 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1870 // another value.
1871 //
1872 SymbolicValueRef : INTVAL {  // Is it an integer reference...?
1873     $$ = ValID::create($1);
1874   }
1875   | Name {                   // Is it a named reference...?
1876     $$ = ValID::create($1);
1877   };
1878
1879 // ValueRef - A reference to a definition... either constant or symbolic
1880 ValueRef : SymbolicValueRef | ConstValueRef;
1881
1882
1883 // ResolvedVal - a <type> <value> pair.  This is used only in cases where the
1884 // type immediately preceeds the value reference, and allows complex constant
1885 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1886 ResolvedVal : Types ValueRef {
1887     $$ = getVal(*$1, $2); delete $1;
1888   };
1889
1890 BasicBlockList : BasicBlockList BasicBlock {
1891     $$ = $1;
1892   }
1893   | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks   
1894     $$ = $1;
1895   };
1896
1897
1898 // Basic blocks are terminated by branching instructions: 
1899 // br, br/cc, switch, ret
1900 //
1901 BasicBlock : InstructionList OptAssign BBTerminatorInst  {
1902     setValueName($3, $2);
1903     InsertValue($3);
1904
1905     $1->getInstList().push_back($3);
1906     InsertValue($1);
1907     $$ = $1;
1908   };
1909
1910 InstructionList : InstructionList Inst {
1911     $1->getInstList().push_back($2);
1912     $$ = $1;
1913   }
1914   | /* empty */ {
1915     $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
1916
1917     // Make sure to move the basic block to the correct location in the
1918     // function, instead of leaving it inserted wherever it was first
1919     // referenced.
1920     Function::BasicBlockListType &BBL = 
1921       CurFun.CurrentFunction->getBasicBlockList();
1922     BBL.splice(BBL.end(), BBL, $$);
1923   }
1924   | LABELSTR {
1925     $$ = CurBB = getBBVal(ValID::create($1), true);
1926
1927     // Make sure to move the basic block to the correct location in the
1928     // function, instead of leaving it inserted wherever it was first
1929     // referenced.
1930     Function::BasicBlockListType &BBL = 
1931       CurFun.CurrentFunction->getBasicBlockList();
1932     BBL.splice(BBL.end(), BBL, $$);
1933   };
1934
1935 BBTerminatorInst : RET ResolvedVal {              // Return with a result...
1936     $$ = new ReturnInst($2);
1937   }
1938   | RET VOID {                                       // Return with no result...
1939     $$ = new ReturnInst();
1940   }
1941   | BR LABEL ValueRef {                         // Unconditional Branch...
1942     $$ = new BranchInst(getBBVal($3));
1943   }                                                  // Conditional Branch...
1944   | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {  
1945     $$ = new BranchInst(getBBVal($6), getBBVal($9), getVal(Type::BoolTy, $3));
1946   }
1947   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1948     SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6), $8->size());
1949     $$ = S;
1950
1951     std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
1952       E = $8->end();
1953     for (; I != E; ++I) {
1954       if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
1955           S->addCase(CI, I->second);
1956       else
1957         ThrowException("Switch case is constant, but not a simple integer!");
1958     }
1959     delete $8;
1960   }
1961   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
1962     SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6), 0);
1963     $$ = S;
1964   }
1965   | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
1966     TO LABEL ValueRef UNWIND LABEL ValueRef {
1967     const PointerType *PFTy;
1968     const FunctionType *Ty;
1969
1970     if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
1971         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1972       // Pull out the types of all of the arguments...
1973       std::vector<const Type*> ParamTypes;
1974       if ($6) {
1975         for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
1976              I != E; ++I)
1977           ParamTypes.push_back((*I)->getType());
1978       }
1979
1980       bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1981       if (isVarArg) ParamTypes.pop_back();
1982
1983       Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
1984       PFTy = PointerType::get(Ty);
1985     }
1986
1987     Value *V = getVal(PFTy, $4);   // Get the function we're calling...
1988
1989     BasicBlock *Normal = getBBVal($10);
1990     BasicBlock *Except = getBBVal($13);
1991
1992     // Create the call node...
1993     if (!$6) {                                   // Has no arguments?
1994       $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
1995     } else {                                     // Has arguments?
1996       // Loop through FunctionType's arguments and ensure they are specified
1997       // correctly!
1998       //
1999       FunctionType::param_iterator I = Ty->param_begin();
2000       FunctionType::param_iterator E = Ty->param_end();
2001       std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
2002
2003       for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2004         if ((*ArgI)->getType() != *I)
2005           ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2006                          (*I)->getDescription() + "'!");
2007
2008       if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2009         ThrowException("Invalid number of parameters detected!");
2010
2011       $$ = new InvokeInst(V, Normal, Except, *$6);
2012     }
2013     cast<InvokeInst>($$)->setCallingConv($2);
2014   
2015     delete $3;
2016     delete $6;
2017   }
2018   | UNWIND {
2019     $$ = new UnwindInst();
2020   }
2021   | UNREACHABLE {
2022     $$ = new UnreachableInst();
2023   };
2024
2025
2026
2027 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2028     $$ = $1;
2029     Constant *V = cast<Constant>(getValNonImprovising($2, $3));
2030     if (V == 0)
2031       ThrowException("May only switch on a constant pool value!");
2032
2033     $$->push_back(std::make_pair(V, getBBVal($6)));
2034   }
2035   | IntType ConstValueRef ',' LABEL ValueRef {
2036     $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2037     Constant *V = cast<Constant>(getValNonImprovising($1, $2));
2038
2039     if (V == 0)
2040       ThrowException("May only switch on a constant pool value!");
2041
2042     $$->push_back(std::make_pair(V, getBBVal($5)));
2043   };
2044
2045 Inst : OptAssign InstVal {
2046   // Is this definition named?? if so, assign the name...
2047   setValueName($2, $1);
2048   InsertValue($2);
2049   $$ = $2;
2050 };
2051
2052 PHIList : Types '[' ValueRef ',' ValueRef ']' {    // Used for PHI nodes
2053     $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2054     $$->push_back(std::make_pair(getVal(*$1, $3), getBBVal($5)));
2055     delete $1;
2056   }
2057   | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2058     $$ = $1;
2059     $1->push_back(std::make_pair(getVal($1->front().first->getType(), $4),
2060                                  getBBVal($6)));
2061   };
2062
2063
2064 ValueRefList : ResolvedVal {    // Used for call statements, and memory insts...
2065     $$ = new std::vector<Value*>();
2066     $$->push_back($1);
2067   }
2068   | ValueRefList ',' ResolvedVal {
2069     $$ = $1;
2070     $1->push_back($3);
2071   };
2072
2073 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
2074 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
2075
2076 OptTailCall : TAIL CALL {
2077     $$ = true;
2078   }
2079   | CALL {
2080     $$ = false;
2081   };
2082
2083
2084
2085 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2086     if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() && 
2087         !isa<PackedType>((*$2).get()))
2088       ThrowException(
2089         "Arithmetic operator requires integer, FP, or packed operands!");
2090     if (isa<PackedType>((*$2).get()) && $1 == Instruction::Rem)
2091       ThrowException("Rem not supported on packed types!");
2092     $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
2093     if ($$ == 0)
2094       ThrowException("binary operator returned null!");
2095     delete $2;
2096   }
2097   | LogicalOps Types ValueRef ',' ValueRef {
2098     if (!(*$2)->isIntegral()) {
2099       if (!isa<PackedType>($2->get()) ||
2100           !cast<PackedType>($2->get())->getElementType()->isIntegral())
2101         ThrowException("Logical operator requires integral operands!");
2102     }
2103     $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
2104     if ($$ == 0)
2105       ThrowException("binary operator returned null!");
2106     delete $2;
2107   }
2108   | SetCondOps Types ValueRef ',' ValueRef {
2109     if(isa<PackedType>((*$2).get())) {
2110       ThrowException(
2111         "PackedTypes currently not supported in setcc instructions!");
2112     }
2113     $$ = new SetCondInst($1, getVal(*$2, $3), getVal(*$2, $5));
2114     if ($$ == 0)
2115       ThrowException("binary operator returned null!");
2116     delete $2;
2117   }
2118   | NOT ResolvedVal {
2119     std::cerr << "WARNING: Use of eliminated 'not' instruction:"
2120               << " Replacing with 'xor'.\n";
2121
2122     Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
2123     if (Ones == 0)
2124       ThrowException("Expected integral type for not instruction!");
2125
2126     $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
2127     if ($$ == 0)
2128       ThrowException("Could not create a xor instruction!");
2129   }
2130   | ShiftOps ResolvedVal ',' ResolvedVal {
2131     if ($4->getType() != Type::UByteTy)
2132       ThrowException("Shift amount must be ubyte!");
2133     if (!$2->getType()->isInteger())
2134       ThrowException("Shift constant expression requires integer operand!");
2135     $$ = new ShiftInst($1, $2, $4);
2136   }
2137   | CAST ResolvedVal TO Types {
2138     if (!$4->get()->isFirstClassType())
2139       ThrowException("cast instruction to a non-primitive type: '" +
2140                      $4->get()->getDescription() + "'!");
2141     $$ = new CastInst($2, *$4);
2142     delete $4;
2143   }
2144   | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2145     if ($2->getType() != Type::BoolTy)
2146       ThrowException("select condition must be boolean!");
2147     if ($4->getType() != $6->getType())
2148       ThrowException("select value types should match!");
2149     $$ = new SelectInst($2, $4, $6);
2150   }
2151   | VAARG ResolvedVal ',' Types {
2152     NewVarArgs = true;
2153     $$ = new VAArgInst($2, *$4);
2154     delete $4;
2155   }
2156   | VAARG_old ResolvedVal ',' Types {
2157     ObsoleteVarArgs = true;
2158     const Type* ArgTy = $2->getType();
2159     Function* NF = CurModule.CurrentModule->
2160       getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0);
2161
2162     //b = vaarg a, t -> 
2163     //foo = alloca 1 of t
2164     //bar = vacopy a 
2165     //store bar -> foo
2166     //b = vaarg foo, t
2167     AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
2168     CurBB->getInstList().push_back(foo);
2169     CallInst* bar = new CallInst(NF, $2);
2170     CurBB->getInstList().push_back(bar);
2171     CurBB->getInstList().push_back(new StoreInst(bar, foo));
2172     $$ = new VAArgInst(foo, *$4);
2173     delete $4;
2174   }
2175   | VANEXT_old ResolvedVal ',' Types {
2176     ObsoleteVarArgs = true;
2177     const Type* ArgTy = $2->getType();
2178     Function* NF = CurModule.CurrentModule->
2179       getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0);
2180
2181     //b = vanext a, t ->
2182     //foo = alloca 1 of t
2183     //bar = vacopy a
2184     //store bar -> foo
2185     //tmp = vaarg foo, t
2186     //b = load foo
2187     AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
2188     CurBB->getInstList().push_back(foo);
2189     CallInst* bar = new CallInst(NF, $2);
2190     CurBB->getInstList().push_back(bar);
2191     CurBB->getInstList().push_back(new StoreInst(bar, foo));
2192     Instruction* tmp = new VAArgInst(foo, *$4);
2193     CurBB->getInstList().push_back(tmp);
2194     $$ = new LoadInst(foo);
2195     delete $4;
2196   }
2197   | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2198     if (!isa<PackedType>($2->getType()))
2199       ThrowException("First operand of extractelement must be "
2200                      "packed type!");
2201     if ($4->getType() != Type::UIntTy)
2202       ThrowException("Second operand of extractelement must be uint!");
2203     $$ = new ExtractElementInst($2, $4);
2204   }
2205   | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2206     if (!isa<PackedType>($2->getType()))
2207       ThrowException("First operand of insertelement must be "
2208                      "packed type!");
2209     if ($4->getType() != 
2210         cast<PackedType>($2->getType())->getElementType())
2211       ThrowException("Second operand of insertelement must be "
2212                      "packed element type!");
2213     if ($6->getType() != Type::UIntTy)
2214       ThrowException("Third operand of insertelement must be uint!");
2215     $$ = new InsertElementInst($2, $4, $6);
2216   }
2217   | PHI_TOK PHIList {
2218     const Type *Ty = $2->front().first->getType();
2219     if (!Ty->isFirstClassType())
2220       ThrowException("PHI node operands must be of first class type!");
2221     $$ = new PHINode(Ty);
2222     ((PHINode*)$$)->reserveOperandSpace($2->size());
2223     while ($2->begin() != $2->end()) {
2224       if ($2->front().first->getType() != Ty) 
2225         ThrowException("All elements of a PHI node must be of the same type!");
2226       cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2227       $2->pop_front();
2228     }
2229     delete $2;  // Free the list...
2230   }
2231   | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')'  {
2232     const PointerType *PFTy;
2233     const FunctionType *Ty;
2234
2235     if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2236         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2237       // Pull out the types of all of the arguments...
2238       std::vector<const Type*> ParamTypes;
2239       if ($6) {
2240         for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
2241              I != E; ++I)
2242           ParamTypes.push_back((*I)->getType());
2243       }
2244
2245       bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2246       if (isVarArg) ParamTypes.pop_back();
2247
2248       if (!(*$3)->isFirstClassType() && *$3 != Type::VoidTy)
2249         ThrowException("LLVM functions cannot return aggregate types!");
2250
2251       Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
2252       PFTy = PointerType::get(Ty);
2253     }
2254
2255     Value *V = getVal(PFTy, $4);   // Get the function we're calling...
2256
2257     // Create the call node...
2258     if (!$6) {                                   // Has no arguments?
2259       // Make sure no arguments is a good thing!
2260       if (Ty->getNumParams() != 0)
2261         ThrowException("No arguments passed to a function that "
2262                        "expects arguments!");
2263
2264       $$ = new CallInst(V, std::vector<Value*>());
2265     } else {                                     // Has arguments?
2266       // Loop through FunctionType's arguments and ensure they are specified
2267       // correctly!
2268       //
2269       FunctionType::param_iterator I = Ty->param_begin();
2270       FunctionType::param_iterator E = Ty->param_end();
2271       std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
2272
2273       for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2274         if ((*ArgI)->getType() != *I)
2275           ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2276                          (*I)->getDescription() + "'!");
2277
2278       if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2279         ThrowException("Invalid number of parameters detected!");
2280
2281       $$ = new CallInst(V, *$6);
2282     }
2283     cast<CallInst>($$)->setTailCall($1);
2284     cast<CallInst>($$)->setCallingConv($2);
2285     delete $3;
2286     delete $6;
2287   }
2288   | MemoryInst {
2289     $$ = $1;
2290   };
2291
2292
2293 // IndexList - List of indices for GEP based instructions...
2294 IndexList : ',' ValueRefList { 
2295     $$ = $2; 
2296   } | /* empty */ { 
2297     $$ = new std::vector<Value*>(); 
2298   };
2299
2300 OptVolatile : VOLATILE {
2301     $$ = true;
2302   }
2303   | /* empty */ {
2304     $$ = false;
2305   };
2306
2307
2308
2309 MemoryInst : MALLOC Types OptCAlign {
2310     $$ = new MallocInst(*$2, 0, $3);
2311     delete $2;
2312   }
2313   | MALLOC Types ',' UINT ValueRef OptCAlign {
2314     $$ = new MallocInst(*$2, getVal($4, $5), $6);
2315     delete $2;
2316   }
2317   | ALLOCA Types OptCAlign {
2318     $$ = new AllocaInst(*$2, 0, $3);
2319     delete $2;
2320   }
2321   | ALLOCA Types ',' UINT ValueRef OptCAlign {
2322     $$ = new AllocaInst(*$2, getVal($4, $5), $6);
2323     delete $2;
2324   }
2325   | FREE ResolvedVal {
2326     if (!isa<PointerType>($2->getType()))
2327       ThrowException("Trying to free nonpointer type " + 
2328                      $2->getType()->getDescription() + "!");
2329     $$ = new FreeInst($2);
2330   }
2331
2332   | OptVolatile LOAD Types ValueRef {
2333     if (!isa<PointerType>($3->get()))
2334       ThrowException("Can't load from nonpointer type: " +
2335                      (*$3)->getDescription());
2336     if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
2337       ThrowException("Can't load from pointer of non-first-class type: " +
2338                      (*$3)->getDescription());
2339     $$ = new LoadInst(getVal(*$3, $4), "", $1);
2340     delete $3;
2341   }
2342   | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2343     const PointerType *PT = dyn_cast<PointerType>($5->get());
2344     if (!PT)
2345       ThrowException("Can't store to a nonpointer type: " +
2346                      (*$5)->getDescription());
2347     const Type *ElTy = PT->getElementType();
2348     if (ElTy != $3->getType())
2349       ThrowException("Can't store '" + $3->getType()->getDescription() +
2350                      "' into space of type '" + ElTy->getDescription() + "'!");
2351
2352     $$ = new StoreInst($3, getVal(*$5, $6), $1);
2353     delete $5;
2354   }
2355   | GETELEMENTPTR Types ValueRef IndexList {
2356     if (!isa<PointerType>($2->get()))
2357       ThrowException("getelementptr insn requires pointer operand!");
2358
2359     // LLVM 1.2 and earlier used ubyte struct indices.  Convert any ubyte struct
2360     // indices to uint struct indices for compatibility.
2361     generic_gep_type_iterator<std::vector<Value*>::iterator>
2362       GTI = gep_type_begin($2->get(), $4->begin(), $4->end()),
2363       GTE = gep_type_end($2->get(), $4->begin(), $4->end());
2364     for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
2365       if (isa<StructType>(*GTI))        // Only change struct indices
2366         if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
2367           if (CUI->getType() == Type::UByteTy)
2368             (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
2369
2370     if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2371       ThrowException("Invalid getelementptr indices for type '" +
2372                      (*$2)->getDescription()+ "'!");
2373     $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
2374     delete $2; delete $4;
2375   };
2376
2377
2378 %%
2379 int yyerror(const char *ErrorMsg) {
2380   std::string where 
2381     = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2382                   + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2383   std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2384   if (yychar == YYEMPTY || yychar == 0)
2385     errMsg += "end-of-file.";
2386   else
2387     errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2388   ThrowException(errMsg);
2389   return 0;
2390 }