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