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