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