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