For PR1043:
[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/InlineAsm.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/SymbolTable.h"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/Support/Streams.h"
26 #include <algorithm>
27 #include <list>
28 #include <utility>
29 #ifndef NDEBUG
30 #define YYDEBUG 1
31 #endif
32
33 // The following is a gross hack. In order to rid the libAsmParser library of
34 // exceptions, we have to have a way of getting the yyparse function to go into
35 // an error situation. So, whenever we want an error to occur, the GenerateError
36 // function (see bottom of file) sets TriggerError. Then, at the end of each 
37 // production in the grammer we use CHECK_FOR_ERROR which will invoke YYERROR 
38 // (a goto) to put YACC in error state. Furthermore, several calls to 
39 // GenerateError are made from inside productions and they must simulate the
40 // previous exception behavior by exiting the production immediately. We have
41 // replaced these with the GEN_ERROR macro which calls GeneratError and then
42 // immediately invokes YYERROR. This would be so much cleaner if it was a 
43 // recursive descent parser.
44 static bool TriggerError = false;
45 #define CHECK_FOR_ERROR { if (TriggerError) { TriggerError = false; YYABORT; } }
46 #define GEN_ERROR(msg) { GenerateError(msg); YYERROR; }
47
48 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
49 int yylex();                       // declaration" of xxx warnings.
50 int yyparse();
51
52 namespace llvm {
53   std::string CurFilename;
54 #if YYDEBUG
55 static cl::opt<bool>
56 Debug("debug-yacc", cl::desc("Print yacc debug state changes"), 
57       cl::Hidden, cl::init(false));
58 #endif
59 }
60 using namespace llvm;
61
62 static Module *ParserResult;
63
64 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
65 // relating to upreferences in the input stream.
66 //
67 //#define DEBUG_UPREFS 1
68 #ifdef DEBUG_UPREFS
69 #define UR_OUT(X) cerr << X
70 #else
71 #define UR_OUT(X)
72 #endif
73
74 #define YYERROR_VERBOSE 1
75
76 static GlobalVariable *CurGV;
77
78
79 // This contains info used when building the body of a function.  It is
80 // destroyed when the function is completed.
81 //
82 typedef std::vector<Value *> ValueList;           // Numbered defs
83
84 static void 
85 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
86                    std::map<const Type *,ValueList> *FutureLateResolvers = 0);
87
88 static struct PerModuleInfo {
89   Module *CurrentModule;
90   std::map<const Type *, ValueList> Values; // Module level numbered definitions
91   std::map<const Type *,ValueList> LateResolveValues;
92   std::vector<PATypeHolder>    Types;
93   std::map<ValID, PATypeHolder> LateResolveTypes;
94
95   /// PlaceHolderInfo - When temporary placeholder objects are created, remember
96   /// how they were referenced and on which line of the input they came from so
97   /// that we can resolve them later and print error messages as appropriate.
98   std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
99
100   // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
101   // references to global values.  Global values may be referenced before they
102   // are defined, and if so, the temporary object that they represent is held
103   // here.  This is used for forward references of GlobalValues.
104   //
105   typedef std::map<std::pair<const PointerType *,
106                              ValID>, GlobalValue*> GlobalRefsType;
107   GlobalRefsType GlobalRefs;
108
109   void ModuleDone() {
110     // If we could not resolve some functions at function compilation time
111     // (calls to functions before they are defined), resolve them now...  Types
112     // are resolved when the constant pool has been completely parsed.
113     //
114     ResolveDefinitions(LateResolveValues);
115     if (TriggerError)
116       return;
117
118     // Check to make sure that all global value forward references have been
119     // resolved!
120     //
121     if (!GlobalRefs.empty()) {
122       std::string UndefinedReferences = "Unresolved global references exist:\n";
123
124       for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
125            I != E; ++I) {
126         UndefinedReferences += "  " + I->first.first->getDescription() + " " +
127                                I->first.second.getName() + "\n";
128       }
129       GenerateError(UndefinedReferences);
130       return;
131     }
132
133     Values.clear();         // Clear out function local definitions
134     Types.clear();
135     CurrentModule = 0;
136   }
137
138   // GetForwardRefForGlobal - Check to see if there is a forward reference
139   // for this global.  If so, remove it from the GlobalRefs map and return it.
140   // If not, just return null.
141   GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
142     // Check to see if there is a forward reference to this global variable...
143     // if there is, eliminate it and patch the reference to use the new def'n.
144     GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
145     GlobalValue *Ret = 0;
146     if (I != GlobalRefs.end()) {
147       Ret = I->second;
148       GlobalRefs.erase(I);
149     }
150     return Ret;
151   }
152
153   bool TypeIsUnresolved(PATypeHolder* PATy) {
154     // If it isn't abstract, its resolved
155     const Type* Ty = PATy->get();
156     if (!Ty->isAbstract())
157       return false;
158     // Traverse the type looking for abstract types. If it isn't abstract then
159     // we don't need to traverse that leg of the type. 
160     std::vector<const Type*> WorkList, SeenList;
161     WorkList.push_back(Ty);
162     while (!WorkList.empty()) {
163       const Type* Ty = WorkList.back();
164       SeenList.push_back(Ty);
165       WorkList.pop_back();
166       if (const OpaqueType* OpTy = dyn_cast<OpaqueType>(Ty)) {
167         // Check to see if this is an unresolved type
168         std::map<ValID, PATypeHolder>::iterator I = LateResolveTypes.begin();
169         std::map<ValID, PATypeHolder>::iterator E = LateResolveTypes.end();
170         for ( ; I != E; ++I) {
171           if (I->second.get() == OpTy)
172             return true;
173         }
174       } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(Ty)) {
175         const Type* TheTy = SeqTy->getElementType();
176         if (TheTy->isAbstract() && TheTy != Ty) {
177           std::vector<const Type*>::iterator I = SeenList.begin(), 
178                                              E = SeenList.end();
179           for ( ; I != E; ++I)
180             if (*I == TheTy)
181               break;
182           if (I == E)
183             WorkList.push_back(TheTy);
184         }
185       } else if (const StructType* StrTy = dyn_cast<StructType>(Ty)) {
186         for (unsigned i = 0; i < StrTy->getNumElements(); ++i) {
187           const Type* TheTy = StrTy->getElementType(i);
188           if (TheTy->isAbstract() && TheTy != Ty) {
189             std::vector<const Type*>::iterator I = SeenList.begin(), 
190                                                E = SeenList.end();
191             for ( ; I != E; ++I)
192               if (*I == TheTy)
193                 break;
194             if (I == E)
195               WorkList.push_back(TheTy);
196           }
197         }
198       }
199     }
200     return false;
201   }
202
203
204 } CurModule;
205
206 static struct PerFunctionInfo {
207   Function *CurrentFunction;     // Pointer to current function being created
208
209   std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
210   std::map<const Type*, ValueList> LateResolveValues;
211   bool isDeclare;                    // Is this function a forward declararation?
212   GlobalValue::LinkageTypes Linkage; // Linkage for forward declaration.
213
214   /// BBForwardRefs - When we see forward references to basic blocks, keep
215   /// track of them here.
216   std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
217   std::vector<BasicBlock*> NumberedBlocks;
218   unsigned NextBBNum;
219
220   inline PerFunctionInfo() {
221     CurrentFunction = 0;
222     isDeclare = false;
223     Linkage = GlobalValue::ExternalLinkage;    
224   }
225
226   inline void FunctionStart(Function *M) {
227     CurrentFunction = M;
228     NextBBNum = 0;
229   }
230
231   void FunctionDone() {
232     NumberedBlocks.clear();
233
234     // Any forward referenced blocks left?
235     if (!BBForwardRefs.empty()) {
236       GenerateError("Undefined reference to label " +
237                      BBForwardRefs.begin()->first->getName());
238       return;
239     }
240
241     // Resolve all forward references now.
242     ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
243
244     Values.clear();         // Clear out function local definitions
245     CurrentFunction = 0;
246     isDeclare = false;
247     Linkage = GlobalValue::ExternalLinkage;
248   }
249 } CurFun;  // Info for the current function...
250
251 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
252
253
254 //===----------------------------------------------------------------------===//
255 //               Code to handle definitions of all the types
256 //===----------------------------------------------------------------------===//
257
258 static int InsertValue(Value *V,
259                   std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
260   if (V->hasName()) return -1;           // Is this a numbered definition?
261
262   // Yes, insert the value into the value table...
263   ValueList &List = ValueTab[V->getType()];
264   List.push_back(V);
265   return List.size()-1;
266 }
267
268 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
269   switch (D.Type) {
270   case ValID::NumberVal:               // Is it a numbered definition?
271     // Module constants occupy the lowest numbered slots...
272     if ((unsigned)D.Num < CurModule.Types.size())
273       return CurModule.Types[(unsigned)D.Num];
274     break;
275   case ValID::NameVal:                 // Is it a named definition?
276     if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
277       D.destroy();  // Free old strdup'd memory...
278       return N;
279     }
280     break;
281   default:
282     GenerateError("Internal parser error: Invalid symbol type reference!");
283     return 0;
284   }
285
286   // If we reached here, we referenced either a symbol that we don't know about
287   // or an id number that hasn't been read yet.  We may be referencing something
288   // forward, so just create an entry to be resolved later and get to it...
289   //
290   if (DoNotImprovise) return 0;  // Do we just want a null to be returned?
291
292
293   if (inFunctionScope()) {
294     if (D.Type == ValID::NameVal) {
295       GenerateError("Reference to an undefined type: '" + D.getName() + "'");
296       return 0;
297     } else {
298       GenerateError("Reference to an undefined type: #" + itostr(D.Num));
299       return 0;
300     }
301   }
302
303   std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
304   if (I != CurModule.LateResolveTypes.end())
305     return I->second;
306
307   Type *Typ = OpaqueType::get();
308   CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
309   return Typ;
310  }
311
312 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
313   SymbolTable &SymTab =
314     inFunctionScope() ? CurFun.CurrentFunction->getValueSymbolTable() :
315                         CurModule.CurrentModule->getValueSymbolTable();
316   return SymTab.lookup(Ty, Name);
317 }
318
319 // getValNonImprovising - Look up the value specified by the provided type and
320 // the provided ValID.  If the value exists and has already been defined, return
321 // it.  Otherwise return null.
322 //
323 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
324   if (isa<FunctionType>(Ty)) {
325     GenerateError("Functions are not values and "
326                    "must be referenced as pointers");
327     return 0;
328   }
329
330   switch (D.Type) {
331   case ValID::NumberVal: {                 // Is it a numbered definition?
332     unsigned Num = (unsigned)D.Num;
333
334     // Module constants occupy the lowest numbered slots...
335     std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
336     if (VI != CurModule.Values.end()) {
337       if (Num < VI->second.size())
338         return VI->second[Num];
339       Num -= VI->second.size();
340     }
341
342     // Make sure that our type is within bounds
343     VI = CurFun.Values.find(Ty);
344     if (VI == CurFun.Values.end()) return 0;
345
346     // Check that the number is within bounds...
347     if (VI->second.size() <= Num) return 0;
348
349     return VI->second[Num];
350   }
351
352   case ValID::NameVal: {                // Is it a named definition?
353     Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
354     if (N == 0) return 0;
355
356     D.destroy();  // Free old strdup'd memory...
357     return N;
358   }
359
360   // Check to make sure that "Ty" is an integral type, and that our
361   // value will fit into the specified type...
362   case ValID::ConstSIntVal:    // Is it a constant pool reference??
363     if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
364       GenerateError("Signed integral constant '" +
365                      itostr(D.ConstPool64) + "' is invalid for type '" +
366                      Ty->getDescription() + "'!");
367       return 0;
368     }
369     return ConstantInt::get(Ty, D.ConstPool64);
370
371   case ValID::ConstUIntVal:     // Is it an unsigned const pool reference?
372     if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
373       if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
374         GenerateError("Integral constant '" + utostr(D.UConstPool64) +
375                        "' is invalid or out of range!");
376         return 0;
377       } else {     // This is really a signed reference.  Transmogrify.
378         return ConstantInt::get(Ty, D.ConstPool64);
379       }
380     } else {
381       return ConstantInt::get(Ty, D.UConstPool64);
382     }
383
384   case ValID::ConstFPVal:        // Is it a floating point const pool reference?
385     if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP)) {
386       GenerateError("FP constant invalid for type!!");
387       return 0;
388     }
389     return ConstantFP::get(Ty, D.ConstPoolFP);
390
391   case ValID::ConstNullVal:      // Is it a null value?
392     if (!isa<PointerType>(Ty)) {
393       GenerateError("Cannot create a a non pointer null!");
394       return 0;
395     }
396     return ConstantPointerNull::get(cast<PointerType>(Ty));
397
398   case ValID::ConstUndefVal:      // Is it an undef value?
399     return UndefValue::get(Ty);
400
401   case ValID::ConstZeroVal:      // Is it a zero value?
402     return Constant::getNullValue(Ty);
403     
404   case ValID::ConstantVal:       // Fully resolved constant?
405     if (D.ConstantValue->getType() != Ty) {
406       GenerateError("Constant expression type different from required type!");
407       return 0;
408     }
409     return D.ConstantValue;
410
411   case ValID::InlineAsmVal: {    // Inline asm expression
412     const PointerType *PTy = dyn_cast<PointerType>(Ty);
413     const FunctionType *FTy =
414       PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
415     if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
416       GenerateError("Invalid type for asm constraint string!");
417       return 0;
418     }
419     InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
420                                    D.IAD->HasSideEffects);
421     D.destroy();   // Free InlineAsmDescriptor.
422     return IA;
423   }
424   default:
425     assert(0 && "Unhandled case!");
426     return 0;
427   }   // End of switch
428
429   assert(0 && "Unhandled case!");
430   return 0;
431 }
432
433 // getVal - This function is identical to getValNonImprovising, except that if a
434 // value is not already defined, it "improvises" by creating a placeholder var
435 // that looks and acts just like the requested variable.  When the value is
436 // defined later, all uses of the placeholder variable are replaced with the
437 // real thing.
438 //
439 static Value *getVal(const Type *Ty, const ValID &ID) {
440   if (Ty == Type::LabelTy) {
441     GenerateError("Cannot use a basic block here");
442     return 0;
443   }
444
445   // See if the value has already been defined.
446   Value *V = getValNonImprovising(Ty, ID);
447   if (V) return V;
448   if (TriggerError) return 0;
449
450   if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
451     GenerateError("Invalid use of a composite type!");
452     return 0;
453   }
454
455   // If we reached here, we referenced either a symbol that we don't know about
456   // or an id number that hasn't been read yet.  We may be referencing something
457   // forward, so just create an entry to be resolved later and get to it...
458   //
459   V = new Argument(Ty);
460
461   // Remember where this forward reference came from.  FIXME, shouldn't we try
462   // to recycle these things??
463   CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
464                                                                llvmAsmlineno)));
465
466   if (inFunctionScope())
467     InsertValue(V, CurFun.LateResolveValues);
468   else
469     InsertValue(V, CurModule.LateResolveValues);
470   return V;
471 }
472
473 /// getBBVal - This is used for two purposes:
474 ///  * If isDefinition is true, a new basic block with the specified ID is being
475 ///    defined.
476 ///  * If isDefinition is true, this is a reference to a basic block, which may
477 ///    or may not be a forward reference.
478 ///
479 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
480   assert(inFunctionScope() && "Can't get basic block at global scope!");
481
482   std::string Name;
483   BasicBlock *BB = 0;
484   switch (ID.Type) {
485   default: 
486     GenerateError("Illegal label reference " + ID.getName());
487     return 0;
488   case ValID::NumberVal:                // Is it a numbered definition?
489     if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
490       CurFun.NumberedBlocks.resize(ID.Num+1);
491     BB = CurFun.NumberedBlocks[ID.Num];
492     break;
493   case ValID::NameVal:                  // Is it a named definition?
494     Name = ID.Name;
495     if (Value *N = CurFun.CurrentFunction->
496                    getValueSymbolTable().lookup(Type::LabelTy, Name))
497       BB = cast<BasicBlock>(N);
498     break;
499   }
500
501   // See if the block has already been defined.
502   if (BB) {
503     // If this is the definition of the block, make sure the existing value was
504     // just a forward reference.  If it was a forward reference, there will be
505     // an entry for it in the PlaceHolderInfo map.
506     if (isDefinition && !CurFun.BBForwardRefs.erase(BB)) {
507       // The existing value was a definition, not a forward reference.
508       GenerateError("Redefinition of label " + ID.getName());
509       return 0;
510     }
511
512     ID.destroy();                       // Free strdup'd memory.
513     return BB;
514   }
515
516   // Otherwise this block has not been seen before.
517   BB = new BasicBlock("", CurFun.CurrentFunction);
518   if (ID.Type == ValID::NameVal) {
519     BB->setName(ID.Name);
520   } else {
521     CurFun.NumberedBlocks[ID.Num] = BB;
522   }
523
524   // If this is not a definition, keep track of it so we can use it as a forward
525   // reference.
526   if (!isDefinition) {
527     // Remember where this forward reference came from.
528     CurFun.BBForwardRefs[BB] = std::make_pair(ID, llvmAsmlineno);
529   } else {
530     // The forward declaration could have been inserted anywhere in the
531     // function: insert it into the correct place now.
532     CurFun.CurrentFunction->getBasicBlockList().remove(BB);
533     CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
534   }
535   ID.destroy();
536   return BB;
537 }
538
539
540 //===----------------------------------------------------------------------===//
541 //              Code to handle forward references in instructions
542 //===----------------------------------------------------------------------===//
543 //
544 // This code handles the late binding needed with statements that reference
545 // values not defined yet... for example, a forward branch, or the PHI node for
546 // a loop body.
547 //
548 // This keeps a table (CurFun.LateResolveValues) of all such forward references
549 // and back patchs after we are done.
550 //
551
552 // ResolveDefinitions - If we could not resolve some defs at parsing
553 // time (forward branches, phi functions for loops, etc...) resolve the
554 // defs now...
555 //
556 static void 
557 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
558                    std::map<const Type*,ValueList> *FutureLateResolvers) {
559   // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
560   for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
561          E = LateResolvers.end(); LRI != E; ++LRI) {
562     ValueList &List = LRI->second;
563     while (!List.empty()) {
564       Value *V = List.back();
565       List.pop_back();
566
567       std::map<Value*, std::pair<ValID, int> >::iterator PHI =
568         CurModule.PlaceHolderInfo.find(V);
569       assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
570
571       ValID &DID = PHI->second.first;
572
573       Value *TheRealValue = getValNonImprovising(LRI->first, DID);
574       if (TriggerError)
575         return;
576       if (TheRealValue) {
577         V->replaceAllUsesWith(TheRealValue);
578         delete V;
579         CurModule.PlaceHolderInfo.erase(PHI);
580       } else if (FutureLateResolvers) {
581         // Functions have their unresolved items forwarded to the module late
582         // resolver table
583         InsertValue(V, *FutureLateResolvers);
584       } else {
585         if (DID.Type == ValID::NameVal) {
586           GenerateError("Reference to an invalid definition: '" +DID.getName()+
587                          "' of type '" + V->getType()->getDescription() + "'",
588                          PHI->second.second);
589           return;
590         } else {
591           GenerateError("Reference to an invalid definition: #" +
592                          itostr(DID.Num) + " of type '" +
593                          V->getType()->getDescription() + "'",
594                          PHI->second.second);
595           return;
596         }
597       }
598     }
599   }
600
601   LateResolvers.clear();
602 }
603
604 // ResolveTypeTo - A brand new type was just declared.  This means that (if
605 // name is not null) things referencing Name can be resolved.  Otherwise, things
606 // refering to the number can be resolved.  Do this now.
607 //
608 static void ResolveTypeTo(char *Name, const Type *ToTy) {
609   ValID D;
610   if (Name) D = ValID::create(Name);
611   else      D = ValID::create((int)CurModule.Types.size());
612
613   std::map<ValID, PATypeHolder>::iterator I =
614     CurModule.LateResolveTypes.find(D);
615   if (I != CurModule.LateResolveTypes.end()) {
616     ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
617     CurModule.LateResolveTypes.erase(I);
618   }
619 }
620
621 // setValueName - Set the specified value to the name given.  The name may be
622 // null potentially, in which case this is a noop.  The string passed in is
623 // assumed to be a malloc'd string buffer, and is free'd by this function.
624 //
625 static void setValueName(Value *V, char *NameStr) {
626   if (NameStr) {
627     std::string Name(NameStr);      // Copy string
628     free(NameStr);                  // Free old string
629
630     if (V->getType() == Type::VoidTy) {
631       GenerateError("Can't assign name '" + Name+"' to value with void type!");
632       return;
633     }
634
635     assert(inFunctionScope() && "Must be in function scope!");
636     SymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
637     if (ST.lookup(V->getType(), Name)) {
638       GenerateError("Redefinition of value '" + Name + "' of type '" +
639                      V->getType()->getDescription() + "'!");
640       return;
641     }
642
643     // Set the name.
644     V->setName(Name);
645   }
646 }
647
648 /// ParseGlobalVariable - Handle parsing of a global.  If Initializer is null,
649 /// this is a declaration, otherwise it is a definition.
650 static GlobalVariable *
651 ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
652                     bool isConstantGlobal, const Type *Ty,
653                     Constant *Initializer) {
654   if (isa<FunctionType>(Ty)) {
655     GenerateError("Cannot declare global vars of function type!");
656     return 0;
657   }
658
659   const PointerType *PTy = PointerType::get(Ty);
660
661   std::string Name;
662   if (NameStr) {
663     Name = NameStr;      // Copy string
664     free(NameStr);       // Free old string
665   }
666
667   // See if this global value was forward referenced.  If so, recycle the
668   // object.
669   ValID ID;
670   if (!Name.empty()) {
671     ID = ValID::create((char*)Name.c_str());
672   } else {
673     ID = ValID::create((int)CurModule.Values[PTy].size());
674   }
675
676   if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
677     // Move the global to the end of the list, from whereever it was
678     // previously inserted.
679     GlobalVariable *GV = cast<GlobalVariable>(FWGV);
680     CurModule.CurrentModule->getGlobalList().remove(GV);
681     CurModule.CurrentModule->getGlobalList().push_back(GV);
682     GV->setInitializer(Initializer);
683     GV->setLinkage(Linkage);
684     GV->setConstant(isConstantGlobal);
685     InsertValue(GV, CurModule.Values);
686     return GV;
687   }
688
689   // If this global has a name, check to see if there is already a definition
690   // of this global in the module.  If so, it is an error.
691   if (!Name.empty()) {
692     // We are a simple redefinition of a value, check to see if it is defined
693     // the same as the old one.
694     if (CurModule.CurrentModule->getGlobalVariable(Name, Ty)) {
695       GenerateError("Redefinition of global variable named '" + Name +
696                      "' of type '" + Ty->getDescription() + "'!");
697       return 0;
698     }
699   }
700
701   // Otherwise there is no existing GV to use, create one now.
702   GlobalVariable *GV =
703     new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
704                        CurModule.CurrentModule);
705   InsertValue(GV, CurModule.Values);
706   return GV;
707 }
708
709 // setTypeName - Set the specified type to the name given.  The name may be
710 // null potentially, in which case this is a noop.  The string passed in is
711 // assumed to be a malloc'd string buffer, and is freed by this function.
712 //
713 // This function returns true if the type has already been defined, but is
714 // allowed to be redefined in the specified context.  If the name is a new name
715 // for the type plane, it is inserted and false is returned.
716 static bool setTypeName(const Type *T, char *NameStr) {
717   assert(!inFunctionScope() && "Can't give types function-local names!");
718   if (NameStr == 0) return false;
719  
720   std::string Name(NameStr);      // Copy string
721   free(NameStr);                  // Free old string
722
723   // We don't allow assigning names to void type
724   if (T == Type::VoidTy) {
725     GenerateError("Can't assign name '" + Name + "' to the void type!");
726     return false;
727   }
728
729   // Set the type name, checking for conflicts as we do so.
730   bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
731
732   if (AlreadyExists) {   // Inserting a name that is already defined???
733     const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
734     assert(Existing && "Conflict but no matching type?");
735
736     // There is only one case where this is allowed: when we are refining an
737     // opaque type.  In this case, Existing will be an opaque type.
738     if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
739       // We ARE replacing an opaque type!
740       const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
741       return true;
742     }
743
744     // Otherwise, this is an attempt to redefine a type. That's okay if
745     // the redefinition is identical to the original. This will be so if
746     // Existing and T point to the same Type object. In this one case we
747     // allow the equivalent redefinition.
748     if (Existing == T) return true;  // Yes, it's equal.
749
750     // Any other kind of (non-equivalent) redefinition is an error.
751     GenerateError("Redefinition of type named '" + Name + "' of type '" +
752                    T->getDescription() + "'!");
753   }
754
755   return false;
756 }
757
758 //===----------------------------------------------------------------------===//
759 // Code for handling upreferences in type names...
760 //
761
762 // TypeContains - Returns true if Ty directly contains E in it.
763 //
764 static bool TypeContains(const Type *Ty, const Type *E) {
765   return std::find(Ty->subtype_begin(), Ty->subtype_end(),
766                    E) != Ty->subtype_end();
767 }
768
769 namespace {
770   struct UpRefRecord {
771     // NestingLevel - The number of nesting levels that need to be popped before
772     // this type is resolved.
773     unsigned NestingLevel;
774
775     // LastContainedTy - This is the type at the current binding level for the
776     // type.  Every time we reduce the nesting level, this gets updated.
777     const Type *LastContainedTy;
778
779     // UpRefTy - This is the actual opaque type that the upreference is
780     // represented with.
781     OpaqueType *UpRefTy;
782
783     UpRefRecord(unsigned NL, OpaqueType *URTy)
784       : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
785   };
786 }
787
788 // UpRefs - A list of the outstanding upreferences that need to be resolved.
789 static std::vector<UpRefRecord> UpRefs;
790
791 /// HandleUpRefs - Every time we finish a new layer of types, this function is
792 /// called.  It loops through the UpRefs vector, which is a list of the
793 /// currently active types.  For each type, if the up reference is contained in
794 /// the newly completed type, we decrement the level count.  When the level
795 /// count reaches zero, the upreferenced type is the type that is passed in:
796 /// thus we can complete the cycle.
797 ///
798 static PATypeHolder HandleUpRefs(const Type *ty) {
799   // If Ty isn't abstract, or if there are no up-references in it, then there is
800   // nothing to resolve here.
801   if (!ty->isAbstract() || UpRefs.empty()) return ty;
802   
803   PATypeHolder Ty(ty);
804   UR_OUT("Type '" << Ty->getDescription() <<
805          "' newly formed.  Resolving upreferences.\n" <<
806          UpRefs.size() << " upreferences active!\n");
807
808   // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
809   // to zero), we resolve them all together before we resolve them to Ty.  At
810   // the end of the loop, if there is anything to resolve to Ty, it will be in
811   // this variable.
812   OpaqueType *TypeToResolve = 0;
813
814   for (unsigned i = 0; i != UpRefs.size(); ++i) {
815     UR_OUT("  UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
816            << UpRefs[i].second->getDescription() << ") = "
817            << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
818     if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
819       // Decrement level of upreference
820       unsigned Level = --UpRefs[i].NestingLevel;
821       UpRefs[i].LastContainedTy = Ty;
822       UR_OUT("  Uplevel Ref Level = " << Level << "\n");
823       if (Level == 0) {                     // Upreference should be resolved!
824         if (!TypeToResolve) {
825           TypeToResolve = UpRefs[i].UpRefTy;
826         } else {
827           UR_OUT("  * Resolving upreference for "
828                  << UpRefs[i].second->getDescription() << "\n";
829                  std::string OldName = UpRefs[i].UpRefTy->getDescription());
830           UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
831           UR_OUT("  * Type '" << OldName << "' refined upreference to: "
832                  << (const void*)Ty << ", " << Ty->getDescription() << "\n");
833         }
834         UpRefs.erase(UpRefs.begin()+i);     // Remove from upreference list...
835         --i;                                // Do not skip the next element...
836       }
837     }
838   }
839
840   if (TypeToResolve) {
841     UR_OUT("  * Resolving upreference for "
842            << UpRefs[i].second->getDescription() << "\n";
843            std::string OldName = TypeToResolve->getDescription());
844     TypeToResolve->refineAbstractTypeTo(Ty);
845   }
846
847   return Ty;
848 }
849
850 //===----------------------------------------------------------------------===//
851 //            RunVMAsmParser - Define an interface to this parser
852 //===----------------------------------------------------------------------===//
853 //
854 static Module* RunParser(Module * M);
855
856 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
857   set_scan_file(F);
858
859   CurFilename = Filename;
860   return RunParser(new Module(CurFilename));
861 }
862
863 Module *llvm::RunVMAsmParser(const char * AsmString, Module * M) {
864   set_scan_string(AsmString);
865
866   CurFilename = "from_memory";
867   if (M == NULL) {
868     return RunParser(new Module (CurFilename));
869   } else {
870     return RunParser(M);
871   }
872 }
873
874 %}
875
876 %union {
877   llvm::Module                           *ModuleVal;
878   llvm::Function                         *FunctionVal;
879   llvm::BasicBlock                       *BasicBlockVal;
880   llvm::TerminatorInst                   *TermInstVal;
881   llvm::Instruction                      *InstVal;
882   llvm::Constant                         *ConstVal;
883
884   const llvm::Type                       *PrimType;
885   std::list<llvm::PATypeHolder>          *TypeList;
886   llvm::PATypeHolder                     *TypeVal;
887   llvm::Value                            *ValueVal;
888   std::vector<llvm::Value*>              *ValueList;
889   llvm::ArgListType                      *ArgList;
890   llvm::TypeWithAttrs                     TypeWithAttrs;
891   llvm::TypeWithAttrsList                *TypeWithAttrsList;
892   llvm::ValueRefList                     *ValueRefList;
893
894   // Represent the RHS of PHI node
895   std::list<std::pair<llvm::Value*,
896                       llvm::BasicBlock*> > *PHIList;
897   std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
898   std::vector<llvm::Constant*>           *ConstVector;
899
900   llvm::GlobalValue::LinkageTypes         Linkage;
901   llvm::FunctionType::ParameterAttributes ParamAttrs;
902   int64_t                           SInt64Val;
903   uint64_t                          UInt64Val;
904   int                               SIntVal;
905   unsigned                          UIntVal;
906   double                            FPVal;
907   bool                              BoolVal;
908
909   char                             *StrVal;   // This memory is strdup'd!
910   llvm::ValID                       ValIDVal; // strdup'd memory maybe!
911
912   llvm::Instruction::BinaryOps      BinaryOpVal;
913   llvm::Instruction::TermOps        TermOpVal;
914   llvm::Instruction::MemoryOps      MemOpVal;
915   llvm::Instruction::CastOps        CastOpVal;
916   llvm::Instruction::OtherOps       OtherOpVal;
917   llvm::Module::Endianness          Endianness;
918   llvm::ICmpInst::Predicate         IPredicate;
919   llvm::FCmpInst::Predicate         FPredicate;
920 }
921
922 %type <ModuleVal>     Module 
923 %type <FunctionVal>   Function FunctionProto FunctionHeader BasicBlockList
924 %type <BasicBlockVal> BasicBlock InstructionList
925 %type <TermInstVal>   BBTerminatorInst
926 %type <InstVal>       Inst InstVal MemoryInst
927 %type <ConstVal>      ConstVal ConstExpr
928 %type <ConstVector>   ConstVector
929 %type <ArgList>       ArgList ArgListH
930 %type <PHIList>       PHIList
931 %type <ValueRefList>  ValueRefList      // For call param lists & GEP indices
932 %type <ValueList>     IndexList         // For GEP indices
933 %type <TypeList>      TypeListI 
934 %type <TypeWithAttrsList> ArgTypeList ArgTypeListI
935 %type <TypeWithAttrs> ArgType
936 %type <JumpTable>     JumpTable
937 %type <BoolVal>       GlobalType                  // GLOBAL or CONSTANT?
938 %type <BoolVal>       OptVolatile                 // 'volatile' or not
939 %type <BoolVal>       OptTailCall                 // TAIL CALL or plain CALL.
940 %type <BoolVal>       OptSideEffect               // 'sideeffect' or not.
941 %type <Linkage>       GVInternalLinkage GVExternalLinkage
942 %type <Linkage>       FunctionDefineLinkage FunctionDeclareLinkage
943 %type <Endianness>    BigOrLittle
944
945 // ValueRef - Unresolved reference to a definition or BB
946 %type <ValIDVal>      ValueRef ConstValueRef SymbolicValueRef
947 %type <ValueVal>      ResolvedVal            // <type> <valref> pair
948 // Tokens and types for handling constant integer values
949 //
950 // ESINT64VAL - A negative number within long long range
951 %token <SInt64Val> ESINT64VAL
952
953 // EUINT64VAL - A positive number within uns. long long range
954 %token <UInt64Val> EUINT64VAL
955
956 %token  <SIntVal>   SINTVAL   // Signed 32 bit ints...
957 %token  <UIntVal>   UINTVAL   // Unsigned 32 bit ints...
958 %type   <SIntVal>   INTVAL
959 %token  <FPVal>     FPVAL     // Float or Double constant
960
961 // Built in types...
962 %type  <TypeVal> Types ResultTypes
963 %type  <PrimType> IntType FPType PrimType           // Classifications
964 %token <PrimType> VOID BOOL INT8 INT16 INT32 INT64
965 %token <PrimType> FLOAT DOUBLE LABEL
966 %token TYPE
967
968 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
969 %type  <StrVal> Name OptName OptAssign
970 %type  <UIntVal> OptAlign OptCAlign
971 %type <StrVal> OptSection SectionString
972
973 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
974 %token DECLARE DEFINE GLOBAL CONSTANT SECTION VOLATILE
975 %token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
976 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
977 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
978 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
979 %token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
980 %token X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
981 %token DATALAYOUT
982 %type <UIntVal> OptCallingConv
983 %type <ParamAttrs> OptParamAttrs ParamAttr 
984 %type <ParamAttrs> OptFuncAttrs  FuncAttr
985
986 // Basic Block Terminating Operators
987 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
988
989 // Binary Operators
990 %type  <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
991 %token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
992 %token <OtherOpVal> ICMP FCMP
993 %type  <IPredicate> IPredicates
994 %type  <FPredicate> FPredicates
995 %token  EQ NE SLT SGT SLE SGE ULT UGT ULE UGE 
996 %token  OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
997
998 // Memory Instructions
999 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1000
1001 // Cast Operators
1002 %type <CastOpVal> CastOps
1003 %token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1004 %token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1005
1006 // Other Operators
1007 %type  <OtherOpVal> ShiftOps
1008 %token <OtherOpVal> PHI_TOK SELECT SHL LSHR ASHR VAARG
1009 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1010
1011 // Function Attributes
1012 %token NORETURN
1013
1014 %start Module
1015 %%
1016
1017 // Handle constant integer size restriction and conversion...
1018 //
1019 INTVAL : SINTVAL;
1020 INTVAL : UINTVAL {
1021   if ($1 > (uint32_t)INT32_MAX)     // Outside of my range!
1022     GEN_ERROR("Value too large for type!");
1023   $$ = (int32_t)$1;
1024   CHECK_FOR_ERROR
1025 };
1026
1027 // Operations that are notably excluded from this list include:
1028 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1029 //
1030 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1031 LogicalOps   : AND | OR | XOR;
1032 CastOps      : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST | 
1033                UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1034 ShiftOps     : SHL | LSHR | ASHR;
1035 IPredicates  
1036   : EQ   { $$ = ICmpInst::ICMP_EQ; }  | NE   { $$ = ICmpInst::ICMP_NE; }
1037   | SLT  { $$ = ICmpInst::ICMP_SLT; } | SGT  { $$ = ICmpInst::ICMP_SGT; }
1038   | SLE  { $$ = ICmpInst::ICMP_SLE; } | SGE  { $$ = ICmpInst::ICMP_SGE; }
1039   | ULT  { $$ = ICmpInst::ICMP_ULT; } | UGT  { $$ = ICmpInst::ICMP_UGT; }
1040   | ULE  { $$ = ICmpInst::ICMP_ULE; } | UGE  { $$ = ICmpInst::ICMP_UGE; } 
1041   ;
1042
1043 FPredicates  
1044   : OEQ  { $$ = FCmpInst::FCMP_OEQ; } | ONE  { $$ = FCmpInst::FCMP_ONE; }
1045   | OLT  { $$ = FCmpInst::FCMP_OLT; } | OGT  { $$ = FCmpInst::FCMP_OGT; }
1046   | OLE  { $$ = FCmpInst::FCMP_OLE; } | OGE  { $$ = FCmpInst::FCMP_OGE; }
1047   | ORD  { $$ = FCmpInst::FCMP_ORD; } | UNO  { $$ = FCmpInst::FCMP_UNO; }
1048   | UEQ  { $$ = FCmpInst::FCMP_UEQ; } | UNE  { $$ = FCmpInst::FCMP_UNE; }
1049   | ULT  { $$ = FCmpInst::FCMP_ULT; } | UGT  { $$ = FCmpInst::FCMP_UGT; }
1050   | ULE  { $$ = FCmpInst::FCMP_ULE; } | UGE  { $$ = FCmpInst::FCMP_UGE; }
1051   | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1052   | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1053   ;
1054
1055 // These are some types that allow classification if we only want a particular 
1056 // thing... for example, only a signed, unsigned, or integral type.
1057 IntType :  INT64 | INT32 | INT16 | INT8;
1058 FPType   : FLOAT | DOUBLE;
1059
1060 // OptAssign - Value producing statements have an optional assignment component
1061 OptAssign : Name '=' {
1062     $$ = $1;
1063     CHECK_FOR_ERROR
1064   }
1065   | /*empty*/ {
1066     $$ = 0;
1067     CHECK_FOR_ERROR
1068   };
1069
1070 GVInternalLinkage 
1071   : INTERNAL    { $$ = GlobalValue::InternalLinkage; } 
1072   | WEAK        { $$ = GlobalValue::WeakLinkage; } 
1073   | LINKONCE    { $$ = GlobalValue::LinkOnceLinkage; }
1074   | APPENDING   { $$ = GlobalValue::AppendingLinkage; }
1075   | DLLEXPORT   { $$ = GlobalValue::DLLExportLinkage; } 
1076   ;
1077
1078 GVExternalLinkage
1079   : DLLIMPORT   { $$ = GlobalValue::DLLImportLinkage; }
1080   | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1081   | EXTERNAL    { $$ = GlobalValue::ExternalLinkage; }
1082   ;
1083
1084 FunctionDeclareLinkage
1085   : /*empty*/   { $$ = GlobalValue::ExternalLinkage; }
1086   | DLLIMPORT   { $$ = GlobalValue::DLLImportLinkage; } 
1087   | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1088   ;
1089   
1090 FunctionDefineLinkage 
1091   : /*empty*/   { $$ = GlobalValue::ExternalLinkage; }
1092   | INTERNAL    { $$ = GlobalValue::InternalLinkage; }
1093   | LINKONCE    { $$ = GlobalValue::LinkOnceLinkage; }
1094   | WEAK        { $$ = GlobalValue::WeakLinkage; }
1095   | DLLEXPORT   { $$ = GlobalValue::DLLExportLinkage; } 
1096   ; 
1097
1098 OptCallingConv : /*empty*/          { $$ = CallingConv::C; } |
1099                  CCC_TOK            { $$ = CallingConv::C; } |
1100                  CSRETCC_TOK        { $$ = CallingConv::CSRet; } |
1101                  FASTCC_TOK         { $$ = CallingConv::Fast; } |
1102                  COLDCC_TOK         { $$ = CallingConv::Cold; } |
1103                  X86_STDCALLCC_TOK  { $$ = CallingConv::X86_StdCall; } |
1104                  X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1105                  CC_TOK EUINT64VAL  {
1106                    if ((unsigned)$2 != $2)
1107                      GEN_ERROR("Calling conv too large!");
1108                    $$ = $2;
1109                   CHECK_FOR_ERROR
1110                  };
1111
1112 ParamAttr     : ZEXT { $$ = FunctionType::ZExtAttribute; }
1113               | SEXT { $$ = FunctionType::SExtAttribute; }
1114               ;
1115
1116 OptParamAttrs : /* empty */  { $$ = FunctionType::NoAttributeSet; }
1117               | OptParamAttrs ParamAttr {
1118                 $$ = FunctionType::ParameterAttributes($1 | $2);
1119               }
1120               ;
1121
1122 FuncAttr      : NORETURN { $$ = FunctionType::NoReturnAttribute; }
1123               | ParamAttr
1124               ;
1125
1126 OptFuncAttrs  : /* empty */ { $$ = FunctionType::NoAttributeSet; }
1127               | OptFuncAttrs FuncAttr {
1128                 $$ = FunctionType::ParameterAttributes($1 | $2);
1129               }
1130               ;
1131
1132 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1133 // a comma before it.
1134 OptAlign : /*empty*/        { $$ = 0; } |
1135            ALIGN EUINT64VAL {
1136   $$ = $2;
1137   if ($$ != 0 && !isPowerOf2_32($$))
1138     GEN_ERROR("Alignment must be a power of two!");
1139   CHECK_FOR_ERROR
1140 };
1141 OptCAlign : /*empty*/            { $$ = 0; } |
1142             ',' ALIGN EUINT64VAL {
1143   $$ = $3;
1144   if ($$ != 0 && !isPowerOf2_32($$))
1145     GEN_ERROR("Alignment must be a power of two!");
1146   CHECK_FOR_ERROR
1147 };
1148
1149
1150 SectionString : SECTION STRINGCONSTANT {
1151   for (unsigned i = 0, e = strlen($2); i != e; ++i)
1152     if ($2[i] == '"' || $2[i] == '\\')
1153       GEN_ERROR("Invalid character in section name!");
1154   $$ = $2;
1155   CHECK_FOR_ERROR
1156 };
1157
1158 OptSection : /*empty*/ { $$ = 0; } |
1159              SectionString { $$ = $1; };
1160
1161 // GlobalVarAttributes - Used to pass the attributes string on a global.  CurGV
1162 // is set to be the global we are processing.
1163 //
1164 GlobalVarAttributes : /* empty */ {} |
1165                      ',' GlobalVarAttribute GlobalVarAttributes {};
1166 GlobalVarAttribute : SectionString {
1167     CurGV->setSection($1);
1168     free($1);
1169     CHECK_FOR_ERROR
1170   } 
1171   | ALIGN EUINT64VAL {
1172     if ($2 != 0 && !isPowerOf2_32($2))
1173       GEN_ERROR("Alignment must be a power of two!");
1174     CurGV->setAlignment($2);
1175     CHECK_FOR_ERROR
1176   };
1177
1178 //===----------------------------------------------------------------------===//
1179 // Types includes all predefined types... except void, because it can only be
1180 // used in specific contexts (function returning void for example).  
1181
1182 // Derived types are added later...
1183 //
1184 PrimType : BOOL | INT8 | INT16  | INT32 | INT64 | FLOAT | DOUBLE | LABEL ;
1185
1186 Types 
1187   : OPAQUE {
1188     $$ = new PATypeHolder(OpaqueType::get());
1189     CHECK_FOR_ERROR
1190   }
1191   | PrimType {
1192     $$ = new PATypeHolder($1);
1193     CHECK_FOR_ERROR
1194   }
1195   | Types '*' {                             // Pointer type?
1196     if (*$1 == Type::LabelTy)
1197       GEN_ERROR("Cannot form a pointer to a basic block");
1198     $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1199     delete $1;
1200     CHECK_FOR_ERROR
1201   }
1202   | SymbolicValueRef {            // Named types are also simple types...
1203     const Type* tmp = getTypeVal($1);
1204     CHECK_FOR_ERROR
1205     $$ = new PATypeHolder(tmp);
1206   }
1207   | '\\' EUINT64VAL {                   // Type UpReference
1208     if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range!");
1209     OpaqueType *OT = OpaqueType::get();        // Use temporary placeholder
1210     UpRefs.push_back(UpRefRecord((unsigned)$2, OT));  // Add to vector...
1211     $$ = new PATypeHolder(OT);
1212     UR_OUT("New Upreference!\n");
1213     CHECK_FOR_ERROR
1214   }
1215   | Types '(' ArgTypeListI ')' OptFuncAttrs {
1216     std::vector<const Type*> Params;
1217     std::vector<FunctionType::ParameterAttributes> Attrs;
1218     Attrs.push_back($5);
1219     for (TypeWithAttrsList::iterator I=$3->begin(), E=$3->end(); I != E; ++I) {
1220       Params.push_back(I->Ty->get());
1221       if (I->Ty->get() != Type::VoidTy)
1222         Attrs.push_back(I->Attrs);
1223     }
1224     bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1225     if (isVarArg) Params.pop_back();
1226
1227     FunctionType *FT = FunctionType::get(*$1, Params, isVarArg, Attrs);
1228     delete $3;      // Delete the argument list
1229     delete $1;   // Delete the return type handle
1230     $$ = new PATypeHolder(HandleUpRefs(FT)); 
1231     CHECK_FOR_ERROR
1232   }
1233   | VOID '(' ArgTypeListI ')' OptFuncAttrs {
1234     std::vector<const Type*> Params;
1235     std::vector<FunctionType::ParameterAttributes> Attrs;
1236     Attrs.push_back($5);
1237     for (TypeWithAttrsList::iterator I=$3->begin(), E=$3->end(); I != E; ++I) {
1238       Params.push_back(I->Ty->get());
1239       if (I->Ty->get() != Type::VoidTy)
1240         Attrs.push_back(I->Attrs);
1241     }
1242     bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1243     if (isVarArg) Params.pop_back();
1244
1245     FunctionType *FT = FunctionType::get($1, Params, isVarArg, Attrs);
1246     delete $3;      // Delete the argument list
1247     $$ = new PATypeHolder(HandleUpRefs(FT)); 
1248     CHECK_FOR_ERROR
1249   }
1250
1251   | '[' EUINT64VAL 'x' Types ']' {          // Sized array type?
1252     $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1253     delete $4;
1254     CHECK_FOR_ERROR
1255   }
1256   | '<' EUINT64VAL 'x' Types '>' {          // Packed array type?
1257      const llvm::Type* ElemTy = $4->get();
1258      if ((unsigned)$2 != $2)
1259         GEN_ERROR("Unsigned result not equal to signed result");
1260      if (!ElemTy->isPrimitiveType())
1261         GEN_ERROR("Elemental type of a PackedType must be primitive");
1262      if (!isPowerOf2_32($2))
1263        GEN_ERROR("Vector length should be a power of 2!");
1264      $$ = new PATypeHolder(HandleUpRefs(PackedType::get(*$4, (unsigned)$2)));
1265      delete $4;
1266      CHECK_FOR_ERROR
1267   }
1268   | '{' TypeListI '}' {                        // Structure type?
1269     std::vector<const Type*> Elements;
1270     for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1271            E = $2->end(); I != E; ++I)
1272       Elements.push_back(*I);
1273
1274     $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1275     delete $2;
1276     CHECK_FOR_ERROR
1277   }
1278   | '{' '}' {                                  // Empty structure type?
1279     $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1280     CHECK_FOR_ERROR
1281   }
1282   | '<' '{' TypeListI '}' '>' {
1283     std::vector<const Type*> Elements;
1284     for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1285            E = $3->end(); I != E; ++I)
1286       Elements.push_back(*I);
1287
1288     $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1289     delete $3;
1290     CHECK_FOR_ERROR
1291   }
1292   | '<' '{' '}' '>' {                         // Empty structure type?
1293     $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1294     CHECK_FOR_ERROR
1295   }
1296   ;
1297
1298 ArgType 
1299   : Types OptParamAttrs { 
1300     $$.Ty = $1; 
1301     $$.Attrs = $2; 
1302   }
1303   ;
1304
1305 ResultTypes
1306   : Types {
1307     if (!UpRefs.empty())
1308       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1309     if (!(*$1)->isFirstClassType())
1310       GEN_ERROR("LLVM functions cannot return aggregate types!");
1311     $$ = $1;
1312   }
1313   | VOID {
1314     $$ = new PATypeHolder(Type::VoidTy);
1315   }
1316   ;
1317
1318 ArgTypeList : ArgType {
1319     $$ = new TypeWithAttrsList();
1320     $$->push_back($1);
1321     CHECK_FOR_ERROR
1322   }
1323   | ArgTypeList ',' ArgType {
1324     ($$=$1)->push_back($3);
1325     CHECK_FOR_ERROR
1326   }
1327   ;
1328
1329 ArgTypeListI 
1330   : ArgTypeList
1331   | ArgTypeList ',' DOTDOTDOT {
1332     $$=$1;
1333     TypeWithAttrs TWA; TWA.Attrs = FunctionType::NoAttributeSet;
1334     TWA.Ty = new PATypeHolder(Type::VoidTy);
1335     $$->push_back(TWA);
1336     CHECK_FOR_ERROR
1337   }
1338   | DOTDOTDOT {
1339     $$ = new TypeWithAttrsList;
1340     TypeWithAttrs TWA; TWA.Attrs = FunctionType::NoAttributeSet;
1341     TWA.Ty = new PATypeHolder(Type::VoidTy);
1342     $$->push_back(TWA);
1343     CHECK_FOR_ERROR
1344   }
1345   | /*empty*/ {
1346     $$ = new TypeWithAttrsList();
1347     CHECK_FOR_ERROR
1348   };
1349
1350 // TypeList - Used for struct declarations and as a basis for function type 
1351 // declaration type lists
1352 //
1353 TypeListI : Types {
1354     $$ = new std::list<PATypeHolder>();
1355     $$->push_back(*$1); delete $1;
1356     CHECK_FOR_ERROR
1357   }
1358   | TypeListI ',' Types {
1359     ($$=$1)->push_back(*$3); delete $3;
1360     CHECK_FOR_ERROR
1361   };
1362
1363 // ConstVal - The various declarations that go into the constant pool.  This
1364 // production is used ONLY to represent constants that show up AFTER a 'const',
1365 // 'constant' or 'global' token at global scope.  Constants that can be inlined
1366 // into other expressions (such as integers and constexprs) are handled by the
1367 // ResolvedVal, ValueRef and ConstValueRef productions.
1368 //
1369 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1370     if (!UpRefs.empty())
1371       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1372     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1373     if (ATy == 0)
1374       GEN_ERROR("Cannot make array constant with type: '" + 
1375                      (*$1)->getDescription() + "'!");
1376     const Type *ETy = ATy->getElementType();
1377     int NumElements = ATy->getNumElements();
1378
1379     // Verify that we have the correct size...
1380     if (NumElements != -1 && NumElements != (int)$3->size())
1381       GEN_ERROR("Type mismatch: constant sized array initialized with " +
1382                      utostr($3->size()) +  " arguments, but has size of " + 
1383                      itostr(NumElements) + "!");
1384
1385     // Verify all elements are correct type!
1386     for (unsigned i = 0; i < $3->size(); i++) {
1387       if (ETy != (*$3)[i]->getType())
1388         GEN_ERROR("Element #" + utostr(i) + " is not of type '" + 
1389                        ETy->getDescription() +"' as required!\nIt is of type '"+
1390                        (*$3)[i]->getType()->getDescription() + "'.");
1391     }
1392
1393     $$ = ConstantArray::get(ATy, *$3);
1394     delete $1; delete $3;
1395     CHECK_FOR_ERROR
1396   }
1397   | Types '[' ']' {
1398     if (!UpRefs.empty())
1399       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1400     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1401     if (ATy == 0)
1402       GEN_ERROR("Cannot make array constant with type: '" + 
1403                      (*$1)->getDescription() + "'!");
1404
1405     int NumElements = ATy->getNumElements();
1406     if (NumElements != -1 && NumElements != 0) 
1407       GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1408                      " arguments, but has size of " + itostr(NumElements) +"!");
1409     $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1410     delete $1;
1411     CHECK_FOR_ERROR
1412   }
1413   | Types 'c' STRINGCONSTANT {
1414     if (!UpRefs.empty())
1415       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1416     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1417     if (ATy == 0)
1418       GEN_ERROR("Cannot make array constant with type: '" + 
1419                      (*$1)->getDescription() + "'!");
1420
1421     int NumElements = ATy->getNumElements();
1422     const Type *ETy = ATy->getElementType();
1423     char *EndStr = UnEscapeLexed($3, true);
1424     if (NumElements != -1 && NumElements != (EndStr-$3))
1425       GEN_ERROR("Can't build string constant of size " + 
1426                      itostr((int)(EndStr-$3)) +
1427                      " when array has size " + itostr(NumElements) + "!");
1428     std::vector<Constant*> Vals;
1429     if (ETy == Type::Int8Ty) {
1430       for (unsigned char *C = (unsigned char *)$3; 
1431         C != (unsigned char*)EndStr; ++C)
1432       Vals.push_back(ConstantInt::get(ETy, *C));
1433     } else {
1434       free($3);
1435       GEN_ERROR("Cannot build string arrays of non byte sized elements!");
1436     }
1437     free($3);
1438     $$ = ConstantArray::get(ATy, Vals);
1439     delete $1;
1440     CHECK_FOR_ERROR
1441   }
1442   | Types '<' ConstVector '>' { // Nonempty unsized arr
1443     if (!UpRefs.empty())
1444       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1445     const PackedType *PTy = dyn_cast<PackedType>($1->get());
1446     if (PTy == 0)
1447       GEN_ERROR("Cannot make packed constant with type: '" + 
1448                      (*$1)->getDescription() + "'!");
1449     const Type *ETy = PTy->getElementType();
1450     int NumElements = PTy->getNumElements();
1451
1452     // Verify that we have the correct size...
1453     if (NumElements != -1 && NumElements != (int)$3->size())
1454       GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1455                      utostr($3->size()) +  " arguments, but has size of " + 
1456                      itostr(NumElements) + "!");
1457
1458     // Verify all elements are correct type!
1459     for (unsigned i = 0; i < $3->size(); i++) {
1460       if (ETy != (*$3)[i]->getType())
1461         GEN_ERROR("Element #" + utostr(i) + " is not of type '" + 
1462            ETy->getDescription() +"' as required!\nIt is of type '"+
1463            (*$3)[i]->getType()->getDescription() + "'.");
1464     }
1465
1466     $$ = ConstantPacked::get(PTy, *$3);
1467     delete $1; delete $3;
1468     CHECK_FOR_ERROR
1469   }
1470   | Types '{' ConstVector '}' {
1471     const StructType *STy = dyn_cast<StructType>($1->get());
1472     if (STy == 0)
1473       GEN_ERROR("Cannot make struct constant with type: '" + 
1474                      (*$1)->getDescription() + "'!");
1475
1476     if ($3->size() != STy->getNumContainedTypes())
1477       GEN_ERROR("Illegal number of initializers for structure type!");
1478
1479     // Check to ensure that constants are compatible with the type initializer!
1480     for (unsigned i = 0, e = $3->size(); i != e; ++i)
1481       if ((*$3)[i]->getType() != STy->getElementType(i))
1482         GEN_ERROR("Expected type '" +
1483                        STy->getElementType(i)->getDescription() +
1484                        "' for element #" + utostr(i) +
1485                        " of structure initializer!");
1486
1487     // Check to ensure that Type is not packed
1488     if (STy->isPacked())
1489       GEN_ERROR("Unpacked Initializer to packed type '" + STy->getDescription() + "'");
1490
1491     $$ = ConstantStruct::get(STy, *$3);
1492     delete $1; delete $3;
1493     CHECK_FOR_ERROR
1494   }
1495   | Types '{' '}' {
1496     if (!UpRefs.empty())
1497       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1498     const StructType *STy = dyn_cast<StructType>($1->get());
1499     if (STy == 0)
1500       GEN_ERROR("Cannot make struct constant with type: '" + 
1501                      (*$1)->getDescription() + "'!");
1502
1503     if (STy->getNumContainedTypes() != 0)
1504       GEN_ERROR("Illegal number of initializers for structure type!");
1505
1506     // Check to ensure that Type is not packed
1507     if (STy->isPacked())
1508       GEN_ERROR("Unpacked Initializer to packed type '" + STy->getDescription() + "'");
1509
1510     $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1511     delete $1;
1512     CHECK_FOR_ERROR
1513   }
1514   | Types '<' '{' ConstVector '}' '>' {
1515     const StructType *STy = dyn_cast<StructType>($1->get());
1516     if (STy == 0)
1517       GEN_ERROR("Cannot make struct constant with type: '" + 
1518                      (*$1)->getDescription() + "'!");
1519
1520     if ($4->size() != STy->getNumContainedTypes())
1521       GEN_ERROR("Illegal number of initializers for structure type!");
1522
1523     // Check to ensure that constants are compatible with the type initializer!
1524     for (unsigned i = 0, e = $4->size(); i != e; ++i)
1525       if ((*$4)[i]->getType() != STy->getElementType(i))
1526         GEN_ERROR("Expected type '" +
1527                        STy->getElementType(i)->getDescription() +
1528                        "' for element #" + utostr(i) +
1529                        " of structure initializer!");
1530
1531     // Check to ensure that Type is packed
1532     if (!STy->isPacked())
1533       GEN_ERROR("Packed Initializer to unpacked type '" + STy->getDescription() + "'");
1534
1535     $$ = ConstantStruct::get(STy, *$4);
1536     delete $1; delete $4;
1537     CHECK_FOR_ERROR
1538   }
1539   | Types '<' '{' '}' '>' {
1540     if (!UpRefs.empty())
1541       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1542     const StructType *STy = dyn_cast<StructType>($1->get());
1543     if (STy == 0)
1544       GEN_ERROR("Cannot make struct constant with type: '" + 
1545                      (*$1)->getDescription() + "'!");
1546
1547     if (STy->getNumContainedTypes() != 0)
1548       GEN_ERROR("Illegal number of initializers for structure type!");
1549
1550     // Check to ensure that Type is packed
1551     if (!STy->isPacked())
1552       GEN_ERROR("Packed Initializer to unpacked type '" + STy->getDescription() + "'");
1553
1554     $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1555     delete $1;
1556     CHECK_FOR_ERROR
1557   }
1558   | Types NULL_TOK {
1559     if (!UpRefs.empty())
1560       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1561     const PointerType *PTy = dyn_cast<PointerType>($1->get());
1562     if (PTy == 0)
1563       GEN_ERROR("Cannot make null pointer constant with type: '" + 
1564                      (*$1)->getDescription() + "'!");
1565
1566     $$ = ConstantPointerNull::get(PTy);
1567     delete $1;
1568     CHECK_FOR_ERROR
1569   }
1570   | Types UNDEF {
1571     if (!UpRefs.empty())
1572       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1573     $$ = UndefValue::get($1->get());
1574     delete $1;
1575     CHECK_FOR_ERROR
1576   }
1577   | Types SymbolicValueRef {
1578     if (!UpRefs.empty())
1579       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1580     const PointerType *Ty = dyn_cast<PointerType>($1->get());
1581     if (Ty == 0)
1582       GEN_ERROR("Global const reference must be a pointer type!");
1583
1584     // ConstExprs can exist in the body of a function, thus creating
1585     // GlobalValues whenever they refer to a variable.  Because we are in
1586     // the context of a function, getValNonImprovising will search the functions
1587     // symbol table instead of the module symbol table for the global symbol,
1588     // which throws things all off.  To get around this, we just tell
1589     // getValNonImprovising that we are at global scope here.
1590     //
1591     Function *SavedCurFn = CurFun.CurrentFunction;
1592     CurFun.CurrentFunction = 0;
1593
1594     Value *V = getValNonImprovising(Ty, $2);
1595     CHECK_FOR_ERROR
1596
1597     CurFun.CurrentFunction = SavedCurFn;
1598
1599     // If this is an initializer for a constant pointer, which is referencing a
1600     // (currently) undefined variable, create a stub now that shall be replaced
1601     // in the future with the right type of variable.
1602     //
1603     if (V == 0) {
1604       assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1605       const PointerType *PT = cast<PointerType>(Ty);
1606
1607       // First check to see if the forward references value is already created!
1608       PerModuleInfo::GlobalRefsType::iterator I =
1609         CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1610     
1611       if (I != CurModule.GlobalRefs.end()) {
1612         V = I->second;             // Placeholder already exists, use it...
1613         $2.destroy();
1614       } else {
1615         std::string Name;
1616         if ($2.Type == ValID::NameVal) Name = $2.Name;
1617
1618         // Create the forward referenced global.
1619         GlobalValue *GV;
1620         if (const FunctionType *FTy = 
1621                  dyn_cast<FunctionType>(PT->getElementType())) {
1622           GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1623                             CurModule.CurrentModule);
1624         } else {
1625           GV = new GlobalVariable(PT->getElementType(), false,
1626                                   GlobalValue::ExternalLinkage, 0,
1627                                   Name, CurModule.CurrentModule);
1628         }
1629
1630         // Keep track of the fact that we have a forward ref to recycle it
1631         CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1632         V = GV;
1633       }
1634     }
1635
1636     $$ = cast<GlobalValue>(V);
1637     delete $1;            // Free the type handle
1638     CHECK_FOR_ERROR
1639   }
1640   | Types ConstExpr {
1641     if (!UpRefs.empty())
1642       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1643     if ($1->get() != $2->getType())
1644       GEN_ERROR("Mismatched types for constant expression: " + 
1645         (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1646     $$ = $2;
1647     delete $1;
1648     CHECK_FOR_ERROR
1649   }
1650   | Types ZEROINITIALIZER {
1651     if (!UpRefs.empty())
1652       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1653     const Type *Ty = $1->get();
1654     if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1655       GEN_ERROR("Cannot create a null initialized value of this type!");
1656     $$ = Constant::getNullValue(Ty);
1657     delete $1;
1658     CHECK_FOR_ERROR
1659   }
1660   | IntType ESINT64VAL {      // integral constants
1661     if (!ConstantInt::isValueValidForType($1, $2))
1662       GEN_ERROR("Constant value doesn't fit in type!");
1663     $$ = ConstantInt::get($1, $2);
1664     CHECK_FOR_ERROR
1665   }
1666   | IntType EUINT64VAL {      // integral constants
1667     if (!ConstantInt::isValueValidForType($1, $2))
1668       GEN_ERROR("Constant value doesn't fit in type!");
1669     $$ = ConstantInt::get($1, $2);
1670     CHECK_FOR_ERROR
1671   }
1672   | BOOL TRUETOK {                      // Boolean constants
1673     $$ = ConstantInt::getTrue();
1674     CHECK_FOR_ERROR
1675   }
1676   | BOOL FALSETOK {                     // Boolean constants
1677     $$ = ConstantInt::getFalse();
1678     CHECK_FOR_ERROR
1679   }
1680   | FPType FPVAL {                   // Float & Double constants
1681     if (!ConstantFP::isValueValidForType($1, $2))
1682       GEN_ERROR("Floating point constant invalid for type!!");
1683     $$ = ConstantFP::get($1, $2);
1684     CHECK_FOR_ERROR
1685   };
1686
1687
1688 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1689     if (!UpRefs.empty())
1690       GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1691     Constant *Val = $3;
1692     const Type *Ty = $5->get();
1693     if (!Val->getType()->isFirstClassType())
1694       GEN_ERROR("cast constant expression from a non-primitive type: '" +
1695                      Val->getType()->getDescription() + "'!");
1696     if (!Ty->isFirstClassType())
1697       GEN_ERROR("cast constant expression to a non-primitive type: '" +
1698                 Ty->getDescription() + "'!");
1699     $$ = ConstantExpr::getCast($1, $3, $5->get());
1700     delete $5;
1701   }
1702   | GETELEMENTPTR '(' ConstVal IndexList ')' {
1703     if (!isa<PointerType>($3->getType()))
1704       GEN_ERROR("GetElementPtr requires a pointer operand!");
1705
1706     const Type *IdxTy =
1707       GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1708     if (!IdxTy)
1709       GEN_ERROR("Index list invalid for constant getelementptr!");
1710
1711     std::vector<Constant*> IdxVec;
1712     for (unsigned i = 0, e = $4->size(); i != e; ++i)
1713       if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1714         IdxVec.push_back(C);
1715       else
1716         GEN_ERROR("Indices to constant getelementptr must be constants!");
1717
1718     delete $4;
1719
1720     $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1721     CHECK_FOR_ERROR
1722   }
1723   | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1724     if ($3->getType() != Type::BoolTy)
1725       GEN_ERROR("Select condition must be of boolean type!");
1726     if ($5->getType() != $7->getType())
1727       GEN_ERROR("Select operand types must match!");
1728     $$ = ConstantExpr::getSelect($3, $5, $7);
1729     CHECK_FOR_ERROR
1730   }
1731   | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1732     if ($3->getType() != $5->getType())
1733       GEN_ERROR("Binary operator types must match!");
1734     CHECK_FOR_ERROR;
1735     $$ = ConstantExpr::get($1, $3, $5);
1736   }
1737   | LogicalOps '(' ConstVal ',' ConstVal ')' {
1738     if ($3->getType() != $5->getType())
1739       GEN_ERROR("Logical operator types must match!");
1740     if (!$3->getType()->isIntegral()) {
1741       if (!isa<PackedType>($3->getType()) || 
1742           !cast<PackedType>($3->getType())->getElementType()->isIntegral())
1743         GEN_ERROR("Logical operator requires integral operands!");
1744     }
1745     $$ = ConstantExpr::get($1, $3, $5);
1746     CHECK_FOR_ERROR
1747   }
1748   | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1749     if ($4->getType() != $6->getType())
1750       GEN_ERROR("icmp operand types must match!");
1751     $$ = ConstantExpr::getICmp($2, $4, $6);
1752   }
1753   | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1754     if ($4->getType() != $6->getType())
1755       GEN_ERROR("fcmp operand types must match!");
1756     $$ = ConstantExpr::getFCmp($2, $4, $6);
1757   }
1758   | ShiftOps '(' ConstVal ',' ConstVal ')' {
1759     if ($5->getType() != Type::Int8Ty)
1760       GEN_ERROR("Shift count for shift constant must be i8 type!");
1761     if (!$3->getType()->isInteger())
1762       GEN_ERROR("Shift constant expression requires integer operand!");
1763     CHECK_FOR_ERROR;
1764     $$ = ConstantExpr::get($1, $3, $5);
1765     CHECK_FOR_ERROR
1766   }
1767   | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1768     if (!ExtractElementInst::isValidOperands($3, $5))
1769       GEN_ERROR("Invalid extractelement operands!");
1770     $$ = ConstantExpr::getExtractElement($3, $5);
1771     CHECK_FOR_ERROR
1772   }
1773   | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1774     if (!InsertElementInst::isValidOperands($3, $5, $7))
1775       GEN_ERROR("Invalid insertelement operands!");
1776     $$ = ConstantExpr::getInsertElement($3, $5, $7);
1777     CHECK_FOR_ERROR
1778   }
1779   | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1780     if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1781       GEN_ERROR("Invalid shufflevector operands!");
1782     $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1783     CHECK_FOR_ERROR
1784   };
1785
1786
1787 // ConstVector - A list of comma separated constants.
1788 ConstVector : ConstVector ',' ConstVal {
1789     ($$ = $1)->push_back($3);
1790     CHECK_FOR_ERROR
1791   }
1792   | ConstVal {
1793     $$ = new std::vector<Constant*>();
1794     $$->push_back($1);
1795     CHECK_FOR_ERROR
1796   };
1797
1798
1799 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1800 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1801
1802
1803 //===----------------------------------------------------------------------===//
1804 //                             Rules to match Modules
1805 //===----------------------------------------------------------------------===//
1806
1807 // Module rule: Capture the result of parsing the whole file into a result
1808 // variable...
1809 //
1810 Module 
1811   : DefinitionList {
1812     $$ = ParserResult = CurModule.CurrentModule;
1813     CurModule.ModuleDone();
1814     CHECK_FOR_ERROR;
1815   }
1816   | /*empty*/ {
1817     $$ = ParserResult = CurModule.CurrentModule;
1818     CurModule.ModuleDone();
1819     CHECK_FOR_ERROR;
1820   }
1821   ;
1822
1823 DefinitionList
1824   : Definition
1825   | DefinitionList Definition
1826   ;
1827
1828 Definition 
1829   : DEFINE { CurFun.isDeclare = false } Function {
1830     CurFun.FunctionDone();
1831     CHECK_FOR_ERROR
1832   }
1833   | DECLARE { CurFun.isDeclare = true; } FunctionProto {
1834     CHECK_FOR_ERROR
1835   }
1836   | MODULE ASM_TOK AsmBlock {
1837     CHECK_FOR_ERROR
1838   }  
1839   | IMPLEMENTATION {
1840     // Emit an error if there are any unresolved types left.
1841     if (!CurModule.LateResolveTypes.empty()) {
1842       const ValID &DID = CurModule.LateResolveTypes.begin()->first;
1843       if (DID.Type == ValID::NameVal) {
1844         GEN_ERROR("Reference to an undefined type: '"+DID.getName() + "'");
1845       } else {
1846         GEN_ERROR("Reference to an undefined type: #" + itostr(DID.Num));
1847       }
1848     }
1849     CHECK_FOR_ERROR
1850   }
1851   | OptAssign TYPE Types {
1852     if (!UpRefs.empty())
1853       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
1854     // Eagerly resolve types.  This is not an optimization, this is a
1855     // requirement that is due to the fact that we could have this:
1856     //
1857     // %list = type { %list * }
1858     // %list = type { %list * }    ; repeated type decl
1859     //
1860     // If types are not resolved eagerly, then the two types will not be
1861     // determined to be the same type!
1862     //
1863     ResolveTypeTo($1, *$3);
1864
1865     if (!setTypeName(*$3, $1) && !$1) {
1866       CHECK_FOR_ERROR
1867       // If this is a named type that is not a redefinition, add it to the slot
1868       // table.
1869       CurModule.Types.push_back(*$3);
1870     }
1871
1872     delete $3;
1873     CHECK_FOR_ERROR
1874   }
1875   | OptAssign TYPE VOID {
1876     ResolveTypeTo($1, $3);
1877
1878     if (!setTypeName($3, $1) && !$1) {
1879       CHECK_FOR_ERROR
1880       // If this is a named type that is not a redefinition, add it to the slot
1881       // table.
1882       CurModule.Types.push_back($3);
1883     }
1884     CHECK_FOR_ERROR
1885   }
1886   | OptAssign GlobalType ConstVal { /* "Externally Visible" Linkage */
1887     if ($3 == 0) 
1888       GEN_ERROR("Global value initializer is not a constant!");
1889     CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage, $2, 
1890                                 $3->getType(), $3);
1891     CHECK_FOR_ERROR
1892   } GlobalVarAttributes {
1893     CurGV = 0;
1894   }
1895   | OptAssign GVInternalLinkage GlobalType ConstVal {
1896     if ($4 == 0) 
1897       GEN_ERROR("Global value initializer is not a constant!");
1898     CurGV = ParseGlobalVariable($1, $2, $3, $4->getType(), $4);
1899     CHECK_FOR_ERROR
1900   } GlobalVarAttributes {
1901     CurGV = 0;
1902   }
1903   | OptAssign GVExternalLinkage GlobalType Types {
1904     if (!UpRefs.empty())
1905       GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
1906     CurGV = ParseGlobalVariable($1, $2, $3, *$4, 0);
1907     CHECK_FOR_ERROR
1908     delete $4;
1909   } GlobalVarAttributes {
1910     CurGV = 0;
1911     CHECK_FOR_ERROR
1912   }
1913   | TARGET TargetDefinition { 
1914     CHECK_FOR_ERROR
1915   }
1916   | DEPLIBS '=' LibrariesDefinition {
1917     CHECK_FOR_ERROR
1918   }
1919   ;
1920
1921
1922 AsmBlock : STRINGCONSTANT {
1923   const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
1924   char *EndStr = UnEscapeLexed($1, true);
1925   std::string NewAsm($1, EndStr);
1926   free($1);
1927
1928   if (AsmSoFar.empty())
1929     CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
1930   else
1931     CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
1932   CHECK_FOR_ERROR
1933 };
1934
1935 BigOrLittle : BIG    { $$ = Module::BigEndian; };
1936 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1937
1938 TargetDefinition : ENDIAN '=' BigOrLittle {
1939     CurModule.CurrentModule->setEndianness($3);
1940     CHECK_FOR_ERROR
1941   }
1942   | POINTERSIZE '=' EUINT64VAL {
1943     if ($3 == 32)
1944       CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1945     else if ($3 == 64)
1946       CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1947     else
1948       GEN_ERROR("Invalid pointer size: '" + utostr($3) + "'!");
1949     CHECK_FOR_ERROR
1950   }
1951   | TRIPLE '=' STRINGCONSTANT {
1952     CurModule.CurrentModule->setTargetTriple($3);
1953     free($3);
1954   }
1955   | DATALAYOUT '=' STRINGCONSTANT {
1956     CurModule.CurrentModule->setDataLayout($3);
1957     free($3);
1958   };
1959
1960 LibrariesDefinition : '[' LibList ']';
1961
1962 LibList : LibList ',' STRINGCONSTANT {
1963           CurModule.CurrentModule->addLibrary($3);
1964           free($3);
1965           CHECK_FOR_ERROR
1966         }
1967         | STRINGCONSTANT {
1968           CurModule.CurrentModule->addLibrary($1);
1969           free($1);
1970           CHECK_FOR_ERROR
1971         }
1972         | /* empty: end of list */ {
1973           CHECK_FOR_ERROR
1974         }
1975         ;
1976
1977 //===----------------------------------------------------------------------===//
1978 //                       Rules to match Function Headers
1979 //===----------------------------------------------------------------------===//
1980
1981 Name : VAR_ID | STRINGCONSTANT;
1982 OptName : Name | /*empty*/ { $$ = 0; };
1983
1984 ArgListH : ArgListH ',' Types OptParamAttrs OptName {
1985     if (!UpRefs.empty())
1986       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
1987     if (*$3 == Type::VoidTy)
1988       GEN_ERROR("void typed arguments are invalid!");
1989     ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
1990     $$ = $1;
1991     $1->push_back(E);
1992     CHECK_FOR_ERROR
1993   }
1994   | Types OptParamAttrs OptName {
1995     if (!UpRefs.empty())
1996       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1997     if (*$1 == Type::VoidTy)
1998       GEN_ERROR("void typed arguments are invalid!");
1999     ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2000     $$ = new ArgListType;
2001     $$->push_back(E);
2002     CHECK_FOR_ERROR
2003   };
2004
2005 ArgList : ArgListH {
2006     $$ = $1;
2007     CHECK_FOR_ERROR
2008   }
2009   | ArgListH ',' DOTDOTDOT {
2010     $$ = $1;
2011     struct ArgListEntry E;
2012     E.Ty = new PATypeHolder(Type::VoidTy);
2013     E.Name = 0;
2014     E.Attrs = FunctionType::NoAttributeSet;
2015     $$->push_back(E);
2016     CHECK_FOR_ERROR
2017   }
2018   | DOTDOTDOT {
2019     $$ = new ArgListType;
2020     struct ArgListEntry E;
2021     E.Ty = new PATypeHolder(Type::VoidTy);
2022     E.Name = 0;
2023     E.Attrs = FunctionType::NoAttributeSet;
2024     $$->push_back(E);
2025     CHECK_FOR_ERROR
2026   }
2027   | /* empty */ {
2028     $$ = 0;
2029     CHECK_FOR_ERROR
2030   };
2031
2032 FunctionHeaderH : OptCallingConv ResultTypes Name '(' ArgList ')' 
2033                   OptFuncAttrs OptSection OptAlign {
2034   UnEscapeLexed($3);
2035   std::string FunctionName($3);
2036   free($3);  // Free strdup'd memory!
2037   
2038   // Check the function result for abstractness if this is a define. We should
2039   // have no abstract types at this point
2040   if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($2))
2041     GEN_ERROR("Reference to abstract result: "+ $2->get()->getDescription());
2042
2043   std::vector<const Type*> ParamTypeList;
2044   std::vector<FunctionType::ParameterAttributes> ParamAttrs;
2045   ParamAttrs.push_back($7);
2046   if ($5) {   // If there are arguments...
2047     for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I) {
2048       const Type* Ty = I->Ty->get();
2049       if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2050         GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2051       ParamTypeList.push_back(Ty);
2052       if (Ty != Type::VoidTy)
2053         ParamAttrs.push_back(I->Attrs);
2054     }
2055   }
2056
2057   bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2058   if (isVarArg) ParamTypeList.pop_back();
2059
2060   FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg,
2061                                        ParamAttrs);
2062   const PointerType *PFT = PointerType::get(FT);
2063   delete $2;
2064
2065   ValID ID;
2066   if (!FunctionName.empty()) {
2067     ID = ValID::create((char*)FunctionName.c_str());
2068   } else {
2069     ID = ValID::create((int)CurModule.Values[PFT].size());
2070   }
2071
2072   Function *Fn = 0;
2073   // See if this function was forward referenced.  If so, recycle the object.
2074   if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2075     // Move the function to the end of the list, from whereever it was 
2076     // previously inserted.
2077     Fn = cast<Function>(FWRef);
2078     CurModule.CurrentModule->getFunctionList().remove(Fn);
2079     CurModule.CurrentModule->getFunctionList().push_back(Fn);
2080   } else if (!FunctionName.empty() &&     // Merge with an earlier prototype?
2081              (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
2082     // If this is the case, either we need to be a forward decl, or it needs 
2083     // to be.
2084     if (!CurFun.isDeclare && !Fn->isExternal())
2085       GEN_ERROR("Redefinition of function '" + FunctionName + "'!");
2086     
2087     // Make sure to strip off any argument names so we can't get conflicts.
2088     if (Fn->isExternal())
2089       for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2090            AI != AE; ++AI)
2091         AI->setName("");
2092   } else  {  // Not already defined?
2093     Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
2094                       CurModule.CurrentModule);
2095
2096     InsertValue(Fn, CurModule.Values);
2097   }
2098
2099   CurFun.FunctionStart(Fn);
2100
2101   if (CurFun.isDeclare) {
2102     // If we have declaration, always overwrite linkage.  This will allow us to
2103     // correctly handle cases, when pointer to function is passed as argument to
2104     // another function.
2105     Fn->setLinkage(CurFun.Linkage);
2106   }
2107   Fn->setCallingConv($1);
2108   Fn->setAlignment($9);
2109   if ($8) {
2110     Fn->setSection($8);
2111     free($8);
2112   }
2113
2114   // Add all of the arguments we parsed to the function...
2115   if ($5) {                     // Is null if empty...
2116     if (isVarArg) {  // Nuke the last entry
2117       assert($5->back().Ty->get() == Type::VoidTy && $5->back().Name == 0&&
2118              "Not a varargs marker!");
2119       delete $5->back().Ty;
2120       $5->pop_back();  // Delete the last entry
2121     }
2122     Function::arg_iterator ArgIt = Fn->arg_begin();
2123     unsigned Idx = 1;
2124     for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I, ++ArgIt) {
2125       delete I->Ty;                          // Delete the typeholder...
2126       setValueName(ArgIt, I->Name);           // Insert arg into symtab...
2127       CHECK_FOR_ERROR
2128       InsertValue(ArgIt);
2129       Idx++;
2130     }
2131
2132     delete $5;                     // We're now done with the argument list
2133   }
2134   CHECK_FOR_ERROR
2135 };
2136
2137 BEGIN : BEGINTOK | '{';                // Allow BEGIN or '{' to start a function
2138
2139 FunctionHeader : FunctionDefineLinkage FunctionHeaderH BEGIN {
2140   $$ = CurFun.CurrentFunction;
2141
2142   // Make sure that we keep track of the linkage type even if there was a
2143   // previous "declare".
2144   $$->setLinkage($1);
2145 };
2146
2147 END : ENDTOK | '}';                    // Allow end of '}' to end a function
2148
2149 Function : BasicBlockList END {
2150   $$ = $1;
2151   CHECK_FOR_ERROR
2152 };
2153
2154 FunctionProto : FunctionDeclareLinkage FunctionHeaderH {
2155     CurFun.CurrentFunction->setLinkage($1);
2156     $$ = CurFun.CurrentFunction;
2157     CurFun.FunctionDone();
2158     CHECK_FOR_ERROR
2159   };
2160
2161 //===----------------------------------------------------------------------===//
2162 //                        Rules to match Basic Blocks
2163 //===----------------------------------------------------------------------===//
2164
2165 OptSideEffect : /* empty */ {
2166     $$ = false;
2167     CHECK_FOR_ERROR
2168   }
2169   | SIDEEFFECT {
2170     $$ = true;
2171     CHECK_FOR_ERROR
2172   };
2173
2174 ConstValueRef : ESINT64VAL {    // A reference to a direct constant
2175     $$ = ValID::create($1);
2176     CHECK_FOR_ERROR
2177   }
2178   | EUINT64VAL {
2179     $$ = ValID::create($1);
2180     CHECK_FOR_ERROR
2181   }
2182   | FPVAL {                     // Perhaps it's an FP constant?
2183     $$ = ValID::create($1);
2184     CHECK_FOR_ERROR
2185   }
2186   | TRUETOK {
2187     $$ = ValID::create(ConstantInt::getTrue());
2188     CHECK_FOR_ERROR
2189   } 
2190   | FALSETOK {
2191     $$ = ValID::create(ConstantInt::getFalse());
2192     CHECK_FOR_ERROR
2193   }
2194   | NULL_TOK {
2195     $$ = ValID::createNull();
2196     CHECK_FOR_ERROR
2197   }
2198   | UNDEF {
2199     $$ = ValID::createUndef();
2200     CHECK_FOR_ERROR
2201   }
2202   | ZEROINITIALIZER {     // A vector zero constant.
2203     $$ = ValID::createZeroInit();
2204     CHECK_FOR_ERROR
2205   }
2206   | '<' ConstVector '>' { // Nonempty unsized packed vector
2207     const Type *ETy = (*$2)[0]->getType();
2208     int NumElements = $2->size(); 
2209     
2210     PackedType* pt = PackedType::get(ETy, NumElements);
2211     PATypeHolder* PTy = new PATypeHolder(
2212                                          HandleUpRefs(
2213                                             PackedType::get(
2214                                                 ETy, 
2215                                                 NumElements)
2216                                             )
2217                                          );
2218     
2219     // Verify all elements are correct type!
2220     for (unsigned i = 0; i < $2->size(); i++) {
2221       if (ETy != (*$2)[i]->getType())
2222         GEN_ERROR("Element #" + utostr(i) + " is not of type '" + 
2223                      ETy->getDescription() +"' as required!\nIt is of type '" +
2224                      (*$2)[i]->getType()->getDescription() + "'.");
2225     }
2226
2227     $$ = ValID::create(ConstantPacked::get(pt, *$2));
2228     delete PTy; delete $2;
2229     CHECK_FOR_ERROR
2230   }
2231   | ConstExpr {
2232     $$ = ValID::create($1);
2233     CHECK_FOR_ERROR
2234   }
2235   | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2236     char *End = UnEscapeLexed($3, true);
2237     std::string AsmStr = std::string($3, End);
2238     End = UnEscapeLexed($5, true);
2239     std::string Constraints = std::string($5, End);
2240     $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2241     free($3);
2242     free($5);
2243     CHECK_FOR_ERROR
2244   };
2245
2246 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2247 // another value.
2248 //
2249 SymbolicValueRef : INTVAL {  // Is it an integer reference...?
2250     $$ = ValID::create($1);
2251     CHECK_FOR_ERROR
2252   }
2253   | Name {                   // Is it a named reference...?
2254     $$ = ValID::create($1);
2255     CHECK_FOR_ERROR
2256   };
2257
2258 // ValueRef - A reference to a definition... either constant or symbolic
2259 ValueRef : SymbolicValueRef | ConstValueRef;
2260
2261
2262 // ResolvedVal - a <type> <value> pair.  This is used only in cases where the
2263 // type immediately preceeds the value reference, and allows complex constant
2264 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2265 ResolvedVal : Types ValueRef {
2266     if (!UpRefs.empty())
2267       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2268     $$ = getVal(*$1, $2); 
2269     delete $1;
2270     CHECK_FOR_ERROR
2271   }
2272   ;
2273
2274 BasicBlockList : BasicBlockList BasicBlock {
2275     $$ = $1;
2276     CHECK_FOR_ERROR
2277   }
2278   | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks   
2279     $$ = $1;
2280     CHECK_FOR_ERROR
2281   };
2282
2283
2284 // Basic blocks are terminated by branching instructions: 
2285 // br, br/cc, switch, ret
2286 //
2287 BasicBlock : InstructionList OptAssign BBTerminatorInst  {
2288     setValueName($3, $2);
2289     CHECK_FOR_ERROR
2290     InsertValue($3);
2291
2292     $1->getInstList().push_back($3);
2293     InsertValue($1);
2294     $$ = $1;
2295     CHECK_FOR_ERROR
2296   };
2297
2298 InstructionList : InstructionList Inst {
2299     if (CastInst *CI1 = dyn_cast<CastInst>($2))
2300       if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2301         if (CI2->getParent() == 0)
2302           $1->getInstList().push_back(CI2);
2303     $1->getInstList().push_back($2);
2304     $$ = $1;
2305     CHECK_FOR_ERROR
2306   }
2307   | /* empty */ {
2308     $$ = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
2309     CHECK_FOR_ERROR
2310
2311     // Make sure to move the basic block to the correct location in the
2312     // function, instead of leaving it inserted wherever it was first
2313     // referenced.
2314     Function::BasicBlockListType &BBL = 
2315       CurFun.CurrentFunction->getBasicBlockList();
2316     BBL.splice(BBL.end(), BBL, $$);
2317     CHECK_FOR_ERROR
2318   }
2319   | LABELSTR {
2320     $$ = getBBVal(ValID::create($1), true);
2321     CHECK_FOR_ERROR
2322
2323     // Make sure to move the basic block to the correct location in the
2324     // function, instead of leaving it inserted wherever it was first
2325     // referenced.
2326     Function::BasicBlockListType &BBL = 
2327       CurFun.CurrentFunction->getBasicBlockList();
2328     BBL.splice(BBL.end(), BBL, $$);
2329     CHECK_FOR_ERROR
2330   };
2331
2332 BBTerminatorInst : RET ResolvedVal {              // Return with a result...
2333     $$ = new ReturnInst($2);
2334     CHECK_FOR_ERROR
2335   }
2336   | RET VOID {                                       // Return with no result...
2337     $$ = new ReturnInst();
2338     CHECK_FOR_ERROR
2339   }
2340   | BR LABEL ValueRef {                         // Unconditional Branch...
2341     BasicBlock* tmpBB = getBBVal($3);
2342     CHECK_FOR_ERROR
2343     $$ = new BranchInst(tmpBB);
2344   }                                                  // Conditional Branch...
2345   | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {  
2346     BasicBlock* tmpBBA = getBBVal($6);
2347     CHECK_FOR_ERROR
2348     BasicBlock* tmpBBB = getBBVal($9);
2349     CHECK_FOR_ERROR
2350     Value* tmpVal = getVal(Type::BoolTy, $3);
2351     CHECK_FOR_ERROR
2352     $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2353   }
2354   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2355     Value* tmpVal = getVal($2, $3);
2356     CHECK_FOR_ERROR
2357     BasicBlock* tmpBB = getBBVal($6);
2358     CHECK_FOR_ERROR
2359     SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2360     $$ = S;
2361
2362     std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2363       E = $8->end();
2364     for (; I != E; ++I) {
2365       if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2366           S->addCase(CI, I->second);
2367       else
2368         GEN_ERROR("Switch case is constant, but not a simple integer!");
2369     }
2370     delete $8;
2371     CHECK_FOR_ERROR
2372   }
2373   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2374     Value* tmpVal = getVal($2, $3);
2375     CHECK_FOR_ERROR
2376     BasicBlock* tmpBB = getBBVal($6);
2377     CHECK_FOR_ERROR
2378     SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2379     $$ = S;
2380     CHECK_FOR_ERROR
2381   }
2382   | INVOKE OptCallingConv ResultTypes ValueRef '(' ValueRefList ')' OptFuncAttrs
2383     TO LABEL ValueRef UNWIND LABEL ValueRef {
2384
2385     // Handle the short syntax
2386     const PointerType *PFTy = 0;
2387     const FunctionType *Ty = 0;
2388     if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2389         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2390       // Pull out the types of all of the arguments...
2391       std::vector<const Type*> ParamTypes;
2392       FunctionType::ParamAttrsList ParamAttrs;
2393       ParamAttrs.push_back($8);
2394       for (ValueRefList::iterator I = $6->begin(), E = $6->end(); I != E; ++I) {
2395         const Type *Ty = I->Val->getType();
2396         if (Ty == Type::VoidTy)
2397           GEN_ERROR("Short call syntax cannot be used with varargs");
2398         ParamTypes.push_back(Ty);
2399         ParamAttrs.push_back(I->Attrs);
2400       }
2401
2402       Ty = FunctionType::get($3->get(), ParamTypes, false, ParamAttrs);
2403       PFTy = PointerType::get(Ty);
2404     }
2405
2406     Value *V = getVal(PFTy, $4);   // Get the function we're calling...
2407     CHECK_FOR_ERROR
2408     BasicBlock *Normal = getBBVal($11);
2409     CHECK_FOR_ERROR
2410     BasicBlock *Except = getBBVal($14);
2411     CHECK_FOR_ERROR
2412
2413     // Check the arguments
2414     ValueList Args;
2415     if ($6->empty()) {                                   // Has no arguments?
2416       // Make sure no arguments is a good thing!
2417       if (Ty->getNumParams() != 0)
2418         GEN_ERROR("No arguments passed to a function that "
2419                        "expects arguments!");
2420     } else {                                     // Has arguments?
2421       // Loop through FunctionType's arguments and ensure they are specified
2422       // correctly!
2423       FunctionType::param_iterator I = Ty->param_begin();
2424       FunctionType::param_iterator E = Ty->param_end();
2425       ValueRefList::iterator ArgI = $6->begin(), ArgE = $6->end();
2426
2427       for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2428         if (ArgI->Val->getType() != *I)
2429           GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2430                          (*I)->getDescription() + "'!");
2431         Args.push_back(ArgI->Val);
2432       }
2433
2434       if (Ty->isVarArg()) {
2435         if (I == E)
2436           for (; ArgI != ArgE; ++ArgI)
2437             Args.push_back(ArgI->Val); // push the remaining varargs
2438       } else if (I != E || ArgI != ArgE)
2439         GEN_ERROR("Invalid number of parameters detected!");
2440     }
2441
2442     // Create the InvokeInst
2443     InvokeInst *II = new InvokeInst(V, Normal, Except, Args);
2444     II->setCallingConv($2);
2445     $$ = II;
2446     delete $6;
2447     CHECK_FOR_ERROR
2448   }
2449   | UNWIND {
2450     $$ = new UnwindInst();
2451     CHECK_FOR_ERROR
2452   }
2453   | UNREACHABLE {
2454     $$ = new UnreachableInst();
2455     CHECK_FOR_ERROR
2456   };
2457
2458
2459
2460 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2461     $$ = $1;
2462     Constant *V = cast<Constant>(getValNonImprovising($2, $3));
2463     CHECK_FOR_ERROR
2464     if (V == 0)
2465       GEN_ERROR("May only switch on a constant pool value!");
2466
2467     BasicBlock* tmpBB = getBBVal($6);
2468     CHECK_FOR_ERROR
2469     $$->push_back(std::make_pair(V, tmpBB));
2470   }
2471   | IntType ConstValueRef ',' LABEL ValueRef {
2472     $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2473     Constant *V = cast<Constant>(getValNonImprovising($1, $2));
2474     CHECK_FOR_ERROR
2475
2476     if (V == 0)
2477       GEN_ERROR("May only switch on a constant pool value!");
2478
2479     BasicBlock* tmpBB = getBBVal($5);
2480     CHECK_FOR_ERROR
2481     $$->push_back(std::make_pair(V, tmpBB)); 
2482   };
2483
2484 Inst : OptAssign InstVal {
2485   // Is this definition named?? if so, assign the name...
2486   setValueName($2, $1);
2487   CHECK_FOR_ERROR
2488   InsertValue($2);
2489   $$ = $2;
2490   CHECK_FOR_ERROR
2491 };
2492
2493 PHIList : Types '[' ValueRef ',' ValueRef ']' {    // Used for PHI nodes
2494     if (!UpRefs.empty())
2495       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2496     $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2497     Value* tmpVal = getVal(*$1, $3);
2498     CHECK_FOR_ERROR
2499     BasicBlock* tmpBB = getBBVal($5);
2500     CHECK_FOR_ERROR
2501     $$->push_back(std::make_pair(tmpVal, tmpBB));
2502     delete $1;
2503   }
2504   | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2505     $$ = $1;
2506     Value* tmpVal = getVal($1->front().first->getType(), $4);
2507     CHECK_FOR_ERROR
2508     BasicBlock* tmpBB = getBBVal($6);
2509     CHECK_FOR_ERROR
2510     $1->push_back(std::make_pair(tmpVal, tmpBB));
2511   };
2512
2513
2514 ValueRefList : Types ValueRef OptParamAttrs {    
2515     if (!UpRefs.empty())
2516       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2517     // Used for call and invoke instructions
2518     $$ = new ValueRefList();
2519     ValueRefListEntry E; E.Attrs = $3; E.Val = getVal($1->get(), $2);
2520     $$->push_back(E);
2521   }
2522   | ValueRefList ',' Types ValueRef OptParamAttrs {
2523     if (!UpRefs.empty())
2524       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2525     $$ = $1;
2526     ValueRefListEntry E; E.Attrs = $5; E.Val = getVal($3->get(), $4);
2527     $$->push_back(E);
2528     CHECK_FOR_ERROR
2529   }
2530   | /*empty*/ { $$ = new ValueRefList(); };
2531
2532 IndexList       // Used for gep instructions and constant expressions
2533   : /*empty*/ { $$ = new std::vector<Value*>(); }
2534   | IndexList ',' ResolvedVal {
2535     $$ = $1;
2536     $$->push_back($3);
2537     CHECK_FOR_ERROR
2538   }
2539   ;
2540
2541 OptTailCall : TAIL CALL {
2542     $$ = true;
2543     CHECK_FOR_ERROR
2544   }
2545   | CALL {
2546     $$ = false;
2547     CHECK_FOR_ERROR
2548   };
2549
2550 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2551     if (!UpRefs.empty())
2552       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2553     if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() && 
2554         !isa<PackedType>((*$2).get()))
2555       GEN_ERROR(
2556         "Arithmetic operator requires integer, FP, or packed operands!");
2557     if (isa<PackedType>((*$2).get()) && 
2558         ($1 == Instruction::URem || 
2559          $1 == Instruction::SRem ||
2560          $1 == Instruction::FRem))
2561       GEN_ERROR("U/S/FRem not supported on packed types!");
2562     Value* val1 = getVal(*$2, $3); 
2563     CHECK_FOR_ERROR
2564     Value* val2 = getVal(*$2, $5);
2565     CHECK_FOR_ERROR
2566     $$ = BinaryOperator::create($1, val1, val2);
2567     if ($$ == 0)
2568       GEN_ERROR("binary operator returned null!");
2569     delete $2;
2570   }
2571   | LogicalOps Types ValueRef ',' ValueRef {
2572     if (!UpRefs.empty())
2573       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2574     if (!(*$2)->isIntegral()) {
2575       if (!isa<PackedType>($2->get()) ||
2576           !cast<PackedType>($2->get())->getElementType()->isIntegral())
2577         GEN_ERROR("Logical operator requires integral operands!");
2578     }
2579     Value* tmpVal1 = getVal(*$2, $3);
2580     CHECK_FOR_ERROR
2581     Value* tmpVal2 = getVal(*$2, $5);
2582     CHECK_FOR_ERROR
2583     $$ = BinaryOperator::create($1, tmpVal1, tmpVal2);
2584     if ($$ == 0)
2585       GEN_ERROR("binary operator returned null!");
2586     delete $2;
2587   }
2588   | ICMP IPredicates Types ValueRef ',' ValueRef  {
2589     if (!UpRefs.empty())
2590       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2591     if (isa<PackedType>((*$3).get()))
2592       GEN_ERROR("Packed types not supported by icmp instruction");
2593     Value* tmpVal1 = getVal(*$3, $4);
2594     CHECK_FOR_ERROR
2595     Value* tmpVal2 = getVal(*$3, $6);
2596     CHECK_FOR_ERROR
2597     $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2598     if ($$ == 0)
2599       GEN_ERROR("icmp operator returned null!");
2600   }
2601   | FCMP FPredicates Types ValueRef ',' ValueRef  {
2602     if (!UpRefs.empty())
2603       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2604     if (isa<PackedType>((*$3).get()))
2605       GEN_ERROR("Packed types not supported by fcmp instruction");
2606     Value* tmpVal1 = getVal(*$3, $4);
2607     CHECK_FOR_ERROR
2608     Value* tmpVal2 = getVal(*$3, $6);
2609     CHECK_FOR_ERROR
2610     $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2611     if ($$ == 0)
2612       GEN_ERROR("fcmp operator returned null!");
2613   }
2614   | NOT ResolvedVal {
2615     cerr << "WARNING: Use of eliminated 'not' instruction:"
2616          << " Replacing with 'xor'.\n";
2617
2618     Value *Ones = ConstantInt::getAllOnesValue($2->getType());
2619     if (Ones == 0)
2620       GEN_ERROR("Expected integral type for not instruction!");
2621
2622     $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
2623     if ($$ == 0)
2624       GEN_ERROR("Could not create a xor instruction!");
2625     CHECK_FOR_ERROR
2626   }
2627   | ShiftOps ResolvedVal ',' ResolvedVal {
2628     if ($4->getType() != Type::Int8Ty)
2629       GEN_ERROR("Shift amount must be i8 type!");
2630     if (!$2->getType()->isInteger())
2631       GEN_ERROR("Shift constant expression requires integer operand!");
2632     CHECK_FOR_ERROR;
2633     $$ = new ShiftInst($1, $2, $4);
2634     CHECK_FOR_ERROR
2635   }
2636   | CastOps ResolvedVal TO Types {
2637     if (!UpRefs.empty())
2638       GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2639     Value* Val = $2;
2640     const Type* Ty = $4->get();
2641     if (!Val->getType()->isFirstClassType())
2642       GEN_ERROR("cast from a non-primitive type: '" +
2643                 Val->getType()->getDescription() + "'!");
2644     if (!Ty->isFirstClassType())
2645       GEN_ERROR("cast to a non-primitive type: '" + Ty->getDescription() +"'!");
2646     $$ = CastInst::create($1, Val, $4->get());
2647     delete $4;
2648   }
2649   | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2650     if ($2->getType() != Type::BoolTy)
2651       GEN_ERROR("select condition must be boolean!");
2652     if ($4->getType() != $6->getType())
2653       GEN_ERROR("select value types should match!");
2654     $$ = new SelectInst($2, $4, $6);
2655     CHECK_FOR_ERROR
2656   }
2657   | VAARG ResolvedVal ',' Types {
2658     if (!UpRefs.empty())
2659       GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2660     $$ = new VAArgInst($2, *$4);
2661     delete $4;
2662     CHECK_FOR_ERROR
2663   }
2664   | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2665     if (!ExtractElementInst::isValidOperands($2, $4))
2666       GEN_ERROR("Invalid extractelement operands!");
2667     $$ = new ExtractElementInst($2, $4);
2668     CHECK_FOR_ERROR
2669   }
2670   | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2671     if (!InsertElementInst::isValidOperands($2, $4, $6))
2672       GEN_ERROR("Invalid insertelement operands!");
2673     $$ = new InsertElementInst($2, $4, $6);
2674     CHECK_FOR_ERROR
2675   }
2676   | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2677     if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
2678       GEN_ERROR("Invalid shufflevector operands!");
2679     $$ = new ShuffleVectorInst($2, $4, $6);
2680     CHECK_FOR_ERROR
2681   }
2682   | PHI_TOK PHIList {
2683     const Type *Ty = $2->front().first->getType();
2684     if (!Ty->isFirstClassType())
2685       GEN_ERROR("PHI node operands must be of first class type!");
2686     $$ = new PHINode(Ty);
2687     ((PHINode*)$$)->reserveOperandSpace($2->size());
2688     while ($2->begin() != $2->end()) {
2689       if ($2->front().first->getType() != Ty) 
2690         GEN_ERROR("All elements of a PHI node must be of the same type!");
2691       cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2692       $2->pop_front();
2693     }
2694     delete $2;  // Free the list...
2695     CHECK_FOR_ERROR
2696   }
2697   | OptTailCall OptCallingConv ResultTypes ValueRef '(' ValueRefList ')' 
2698     OptFuncAttrs {
2699
2700     // Handle the short syntax
2701     const PointerType *PFTy = 0;
2702     const FunctionType *Ty = 0;
2703     if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2704         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2705       // Pull out the types of all of the arguments...
2706       std::vector<const Type*> ParamTypes;
2707       FunctionType::ParamAttrsList ParamAttrs;
2708       ParamAttrs.push_back($8);
2709       for (ValueRefList::iterator I = $6->begin(), E = $6->end(); I != E; ++I) {
2710         const Type *Ty = I->Val->getType();
2711         if (Ty == Type::VoidTy)
2712           GEN_ERROR("Short call syntax cannot be used with varargs");
2713         ParamTypes.push_back(Ty);
2714         ParamAttrs.push_back(I->Attrs);
2715       }
2716
2717       Ty = FunctionType::get($3->get(), ParamTypes, false, ParamAttrs);
2718       PFTy = PointerType::get(Ty);
2719     }
2720
2721     Value *V = getVal(PFTy, $4);   // Get the function we're calling...
2722     CHECK_FOR_ERROR
2723
2724     // Check the arguments 
2725     ValueList Args;
2726     if ($6->empty()) {                                   // Has no arguments?
2727       // Make sure no arguments is a good thing!
2728       if (Ty->getNumParams() != 0)
2729         GEN_ERROR("No arguments passed to a function that "
2730                        "expects arguments!");
2731     } else {                                     // Has arguments?
2732       // Loop through FunctionType's arguments and ensure they are specified
2733       // correctly!
2734       //
2735       FunctionType::param_iterator I = Ty->param_begin();
2736       FunctionType::param_iterator E = Ty->param_end();
2737       ValueRefList::iterator ArgI = $6->begin(), ArgE = $6->end();
2738
2739       for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2740         if (ArgI->Val->getType() != *I)
2741           GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2742                          (*I)->getDescription() + "'!");
2743         Args.push_back(ArgI->Val);
2744       }
2745       if (Ty->isVarArg()) {
2746         if (I == E)
2747           for (; ArgI != ArgE; ++ArgI)
2748             Args.push_back(ArgI->Val); // push the remaining varargs
2749       } else if (I != E || ArgI != ArgE)
2750         GEN_ERROR("Invalid number of parameters detected!");
2751     }
2752     // Create the call node
2753     CallInst *CI = new CallInst(V, Args);
2754     CI->setTailCall($1);
2755     CI->setCallingConv($2);
2756     $$ = CI;
2757     delete $6;
2758     CHECK_FOR_ERROR
2759   }
2760   | MemoryInst {
2761     $$ = $1;
2762     CHECK_FOR_ERROR
2763   };
2764
2765 OptVolatile : VOLATILE {
2766     $$ = true;
2767     CHECK_FOR_ERROR
2768   }
2769   | /* empty */ {
2770     $$ = false;
2771     CHECK_FOR_ERROR
2772   };
2773
2774
2775
2776 MemoryInst : MALLOC Types OptCAlign {
2777     if (!UpRefs.empty())
2778       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2779     $$ = new MallocInst(*$2, 0, $3);
2780     delete $2;
2781     CHECK_FOR_ERROR
2782   }
2783   | MALLOC Types ',' INT32 ValueRef OptCAlign {
2784     if (!UpRefs.empty())
2785       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2786     Value* tmpVal = getVal($4, $5);
2787     CHECK_FOR_ERROR
2788     $$ = new MallocInst(*$2, tmpVal, $6);
2789     delete $2;
2790   }
2791   | ALLOCA Types OptCAlign {
2792     if (!UpRefs.empty())
2793       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2794     $$ = new AllocaInst(*$2, 0, $3);
2795     delete $2;
2796     CHECK_FOR_ERROR
2797   }
2798   | ALLOCA Types ',' INT32 ValueRef OptCAlign {
2799     if (!UpRefs.empty())
2800       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2801     Value* tmpVal = getVal($4, $5);
2802     CHECK_FOR_ERROR
2803     $$ = new AllocaInst(*$2, tmpVal, $6);
2804     delete $2;
2805   }
2806   | FREE ResolvedVal {
2807     if (!isa<PointerType>($2->getType()))
2808       GEN_ERROR("Trying to free nonpointer type " + 
2809                      $2->getType()->getDescription() + "!");
2810     $$ = new FreeInst($2);
2811     CHECK_FOR_ERROR
2812   }
2813
2814   | OptVolatile LOAD Types ValueRef {
2815     if (!UpRefs.empty())
2816       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2817     if (!isa<PointerType>($3->get()))
2818       GEN_ERROR("Can't load from nonpointer type: " +
2819                      (*$3)->getDescription());
2820     if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
2821       GEN_ERROR("Can't load from pointer of non-first-class type: " +
2822                      (*$3)->getDescription());
2823     Value* tmpVal = getVal(*$3, $4);
2824     CHECK_FOR_ERROR
2825     $$ = new LoadInst(tmpVal, "", $1);
2826     delete $3;
2827   }
2828   | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2829     if (!UpRefs.empty())
2830       GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
2831     const PointerType *PT = dyn_cast<PointerType>($5->get());
2832     if (!PT)
2833       GEN_ERROR("Can't store to a nonpointer type: " +
2834                      (*$5)->getDescription());
2835     const Type *ElTy = PT->getElementType();
2836     if (ElTy != $3->getType())
2837       GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
2838                      "' into space of type '" + ElTy->getDescription() + "'!");
2839
2840     Value* tmpVal = getVal(*$5, $6);
2841     CHECK_FOR_ERROR
2842     $$ = new StoreInst($3, tmpVal, $1);
2843     delete $5;
2844   }
2845   | GETELEMENTPTR Types ValueRef IndexList {
2846     if (!UpRefs.empty())
2847       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2848     if (!isa<PointerType>($2->get()))
2849       GEN_ERROR("getelementptr insn requires pointer operand!");
2850
2851     if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2852       GEN_ERROR("Invalid getelementptr indices for type '" +
2853                      (*$2)->getDescription()+ "'!");
2854     Value* tmpVal = getVal(*$2, $3);
2855     CHECK_FOR_ERROR
2856     $$ = new GetElementPtrInst(tmpVal, *$4);
2857     delete $2; 
2858     delete $4;
2859   };
2860
2861
2862 %%
2863
2864 // common code from the two 'RunVMAsmParser' functions
2865 static Module* RunParser(Module * M) {
2866
2867   llvmAsmlineno = 1;      // Reset the current line number...
2868   CurModule.CurrentModule = M;
2869 #if YYDEBUG
2870   yydebug = Debug;
2871 #endif
2872
2873   // Check to make sure the parser succeeded
2874   if (yyparse()) {
2875     if (ParserResult)
2876       delete ParserResult;
2877     return 0;
2878   }
2879
2880   // Check to make sure that parsing produced a result
2881   if (!ParserResult)
2882     return 0;
2883
2884   // Reset ParserResult variable while saving its value for the result.
2885   Module *Result = ParserResult;
2886   ParserResult = 0;
2887
2888   return Result;
2889 }
2890
2891 void llvm::GenerateError(const std::string &message, int LineNo) {
2892   if (LineNo == -1) LineNo = llvmAsmlineno;
2893   // TODO: column number in exception
2894   if (TheParseError)
2895     TheParseError->setError(CurFilename, message, LineNo);
2896   TriggerError = 1;
2897 }
2898
2899 int yyerror(const char *ErrorMsg) {
2900   std::string where 
2901     = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2902                   + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2903   std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2904   if (yychar == YYEMPTY || yychar == 0)
2905     errMsg += "end-of-file.";
2906   else
2907     errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2908   GenerateError(errMsg);
2909   return 0;
2910 }