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