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