When a function takes a variable number of pointer arguments, with a zero
[oota-llvm.git] / lib / AsmParser / llvmAsmParser.y
1 //===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements the bison parser for LLVM assembly languages files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 %{
15 #include "ParserInternals.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Module.h"
19 #include "llvm/SymbolTable.h"
20 #include "llvm/Support/GetElementPtrTypeIterator.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include <algorithm>
23 #include <iostream>
24 #include <list>
25 #include <utility>
26
27 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
28 int yylex();                       // declaration" of xxx warnings.
29 int yyparse();
30
31 namespace llvm {
32   std::string CurFilename;
33 }
34 using namespace llvm;
35
36 static Module *ParserResult;
37
38 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
39 // relating to upreferences in the input stream.
40 //
41 //#define DEBUG_UPREFS 1
42 #ifdef DEBUG_UPREFS
43 #define UR_OUT(X) std::cerr << X
44 #else
45 #define UR_OUT(X)
46 #endif
47
48 #define YYERROR_VERBOSE 1
49
50 static bool ObsoleteVarArgs;
51 static bool NewVarArgs;
52 static BasicBlock* CurBB;
53
54
55 // This contains info used when building the body of a function.  It is
56 // destroyed when the function is completed.
57 //
58 typedef std::vector<Value *> ValueList;           // Numbered defs
59 static void 
60 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
61                    std::map<const Type *,ValueList> *FutureLateResolvers = 0);
62
63 static struct PerModuleInfo {
64   Module *CurrentModule;
65   std::map<const Type *, ValueList> Values; // Module level numbered definitions
66   std::map<const Type *,ValueList> LateResolveValues;
67   std::vector<PATypeHolder>    Types;
68   std::map<ValID, PATypeHolder> LateResolveTypes;
69
70   /// PlaceHolderInfo - When temporary placeholder objects are created, remember
71   /// how they were referenced and one which line of the input they came from so
72   /// that we can resolve them later and print error messages as appropriate.
73   std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
74
75   // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
76   // references to global values.  Global values may be referenced before they
77   // are defined, and if so, the temporary object that they represent is held
78   // here.  This is used for forward references of GlobalValues.
79   //
80   typedef std::map<std::pair<const PointerType *,
81                              ValID>, GlobalValue*> GlobalRefsType;
82   GlobalRefsType GlobalRefs;
83
84   void ModuleDone() {
85     // If we could not resolve some functions at function compilation time
86     // (calls to functions before they are defined), resolve them now...  Types
87     // are resolved when the constant pool has been completely parsed.
88     //
89     ResolveDefinitions(LateResolveValues);
90
91     // Check to make sure that all global value forward references have been
92     // resolved!
93     //
94     if (!GlobalRefs.empty()) {
95       std::string UndefinedReferences = "Unresolved global references exist:\n";
96
97       for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
98            I != E; ++I) {
99         UndefinedReferences += "  " + I->first.first->getDescription() + " " +
100                                I->first.second.getName() + "\n";
101       }
102       ThrowException(UndefinedReferences);
103     }
104
105     Values.clear();         // Clear out function local definitions
106     Types.clear();
107     CurrentModule = 0;
108   }
109
110
111   // GetForwardRefForGlobal - Check to see if there is a forward reference
112   // for this global.  If so, remove it from the GlobalRefs map and return it.
113   // If not, just return null.
114   GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
115     // Check to see if there is a forward reference to this global variable...
116     // if there is, eliminate it and patch the reference to use the new def'n.
117     GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
118     GlobalValue *Ret = 0;
119     if (I != GlobalRefs.end()) {
120       Ret = I->second;
121       GlobalRefs.erase(I);
122     }
123     return Ret;
124   }
125 } CurModule;
126
127 static struct PerFunctionInfo {
128   Function *CurrentFunction;     // Pointer to current function being created
129
130   std::map<const Type*, ValueList> Values;   // Keep track of #'d definitions
131   std::map<const Type*, ValueList> LateResolveValues;
132   bool isDeclare;                // Is this function a forward declararation?
133
134   /// BBForwardRefs - When we see forward references to basic blocks, keep
135   /// track of them here.
136   std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
137   std::vector<BasicBlock*> NumberedBlocks;
138   unsigned NextBBNum;
139
140   inline PerFunctionInfo() {
141     CurrentFunction = 0;
142     isDeclare = false;
143   }
144
145   inline void FunctionStart(Function *M) {
146     CurrentFunction = M;
147     NextBBNum = 0;
148   }
149
150   void FunctionDone() {
151     NumberedBlocks.clear();
152
153     // Any forward referenced blocks left?
154     if (!BBForwardRefs.empty())
155       ThrowException("Undefined reference to label " +
156                      BBForwardRefs.begin()->first->getName());
157
158     // Resolve all forward references now.
159     ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
160
161     Values.clear();         // Clear out function local definitions
162     CurrentFunction = 0;
163     isDeclare = false;
164   }
165 } CurFun;  // Info for the current function...
166
167 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
168
169
170 //===----------------------------------------------------------------------===//
171 //               Code to handle definitions of all the types
172 //===----------------------------------------------------------------------===//
173
174 static int InsertValue(Value *V,
175                   std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
176   if (V->hasName()) return -1;           // Is this a numbered definition?
177
178   // Yes, insert the value into the value table...
179   ValueList &List = ValueTab[V->getType()];
180   List.push_back(V);
181   return List.size()-1;
182 }
183
184 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
185   switch (D.Type) {
186   case ValID::NumberVal:               // Is it a numbered definition?
187     // Module constants occupy the lowest numbered slots...
188     if ((unsigned)D.Num < CurModule.Types.size())
189       return CurModule.Types[(unsigned)D.Num];
190     break;
191   case ValID::NameVal:                 // Is it a named definition?
192     if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
193       D.destroy();  // Free old strdup'd memory...
194       return N;
195     }
196     break;
197   default:
198     ThrowException("Internal parser error: Invalid symbol type reference!");
199   }
200
201   // If we reached here, we referenced either a symbol that we don't know about
202   // or an id number that hasn't been read yet.  We may be referencing something
203   // forward, so just create an entry to be resolved later and get to it...
204   //
205   if (DoNotImprovise) return 0;  // Do we just want a null to be returned?
206
207
208   if (inFunctionScope()) {
209     if (D.Type == ValID::NameVal)
210       ThrowException("Reference to an undefined type: '" + D.getName() + "'");
211     else
212       ThrowException("Reference to an undefined type: #" + itostr(D.Num));
213   }
214
215   std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
216   if (I != CurModule.LateResolveTypes.end())
217     return I->second;
218
219   Type *Typ = OpaqueType::get();
220   CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
221   return Typ;
222  }
223
224 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
225   SymbolTable &SymTab =
226     inFunctionScope() ? CurFun.CurrentFunction->getSymbolTable() :
227                         CurModule.CurrentModule->getSymbolTable();
228   return SymTab.lookup(Ty, Name);
229 }
230
231 // getValNonImprovising - Look up the value specified by the provided type and
232 // the provided ValID.  If the value exists and has already been defined, return
233 // it.  Otherwise return null.
234 //
235 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
236   if (isa<FunctionType>(Ty))
237     ThrowException("Functions are not values and "
238                    "must be referenced as pointers");
239
240   switch (D.Type) {
241   case ValID::NumberVal: {                 // Is it a numbered definition?
242     unsigned Num = (unsigned)D.Num;
243
244     // Module constants occupy the lowest numbered slots...
245     std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
246     if (VI != CurModule.Values.end()) {
247       if (Num < VI->second.size())
248         return VI->second[Num];
249       Num -= VI->second.size();
250     }
251
252     // Make sure that our type is within bounds
253     VI = CurFun.Values.find(Ty);
254     if (VI == CurFun.Values.end()) return 0;
255
256     // Check that the number is within bounds...
257     if (VI->second.size() <= Num) return 0;
258
259     return VI->second[Num];
260   }
261
262   case ValID::NameVal: {                // Is it a named definition?
263     Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
264     if (N == 0) return 0;
265
266     D.destroy();  // Free old strdup'd memory...
267     return N;
268   }
269
270   // Check to make sure that "Ty" is an integral type, and that our
271   // value will fit into the specified type...
272   case ValID::ConstSIntVal:    // Is it a constant pool reference??
273     if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64))
274       ThrowException("Signed integral constant '" +
275                      itostr(D.ConstPool64) + "' is invalid for type '" +
276                      Ty->getDescription() + "'!");
277     return ConstantSInt::get(Ty, D.ConstPool64);
278
279   case ValID::ConstUIntVal:     // Is it an unsigned const pool reference?
280     if (!ConstantUInt::isValueValidForType(Ty, D.UConstPool64)) {
281       if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64)) {
282         ThrowException("Integral constant '" + utostr(D.UConstPool64) +
283                        "' is invalid or out of range!");
284       } else {     // This is really a signed reference.  Transmogrify.
285         return ConstantSInt::get(Ty, D.ConstPool64);
286       }
287     } else {
288       return ConstantUInt::get(Ty, D.UConstPool64);
289     }
290
291   case ValID::ConstFPVal:        // Is it a floating point const pool reference?
292     if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
293       ThrowException("FP constant invalid for type!!");
294     return ConstantFP::get(Ty, D.ConstPoolFP);
295
296   case ValID::ConstNullVal:      // Is it a null value?
297     if (!isa<PointerType>(Ty))
298       ThrowException("Cannot create a a non pointer null!");
299     return ConstantPointerNull::get(cast<PointerType>(Ty));
300
301   case ValID::ConstUndefVal:      // Is it an undef value?
302     return UndefValue::get(Ty);
303
304   case ValID::ConstantVal:       // Fully resolved constant?
305     if (D.ConstantValue->getType() != Ty)
306       ThrowException("Constant expression type different from required type!");
307     return D.ConstantValue;
308
309   default:
310     assert(0 && "Unhandled case!");
311     return 0;
312   }   // End of switch
313
314   assert(0 && "Unhandled case!");
315   return 0;
316 }
317
318 // getVal - This function is identical to getValNonImprovising, except that if a
319 // value is not already defined, it "improvises" by creating a placeholder var
320 // that looks and acts just like the requested variable.  When the value is
321 // defined later, all uses of the placeholder variable are replaced with the
322 // real thing.
323 //
324 static Value *getVal(const Type *Ty, const ValID &ID) {
325   if (Ty == Type::LabelTy)
326     ThrowException("Cannot use a basic block here");
327
328   // See if the value has already been defined.
329   Value *V = getValNonImprovising(Ty, ID);
330   if (V) return V;
331
332   if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty))
333     ThrowException("Invalid use of a composite type!");
334
335   // If we reached here, we referenced either a symbol that we don't know about
336   // or an id number that hasn't been read yet.  We may be referencing something
337   // forward, so just create an entry to be resolved later and get to it...
338   //
339   V = new Argument(Ty);
340
341   // Remember where this forward reference came from.  FIXME, shouldn't we try
342   // to recycle these things??
343   CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
344                                                                llvmAsmlineno)));
345
346   if (inFunctionScope())
347     InsertValue(V, CurFun.LateResolveValues);
348   else
349     InsertValue(V, CurModule.LateResolveValues);
350   return V;
351 }
352
353 /// getBBVal - This is used for two purposes:
354 ///  * If isDefinition is true, a new basic block with the specified ID is being
355 ///    defined.
356 ///  * If isDefinition is true, this is a reference to a basic block, which may
357 ///    or may not be a forward reference.
358 ///
359 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
360   assert(inFunctionScope() && "Can't get basic block at global scope!");
361
362   std::string Name;
363   BasicBlock *BB = 0;
364   switch (ID.Type) {
365   default: ThrowException("Illegal label reference " + ID.getName());
366   case ValID::NumberVal:                // Is it a numbered definition?
367     if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
368       CurFun.NumberedBlocks.resize(ID.Num+1);
369     BB = CurFun.NumberedBlocks[ID.Num];
370     break;
371   case ValID::NameVal:                  // Is it a named definition?
372     Name = ID.Name;
373     if (Value *N = CurFun.CurrentFunction->
374                    getSymbolTable().lookup(Type::LabelTy, Name))
375       BB = cast<BasicBlock>(N);
376     break;
377   }
378
379   // See if the block has already been defined.
380   if (BB) {
381     // If this is the definition of the block, make sure the existing value was
382     // just a forward reference.  If it was a forward reference, there will be
383     // an entry for it in the PlaceHolderInfo map.
384     if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
385       // The existing value was a definition, not a forward reference.
386       ThrowException("Redefinition of label " + ID.getName());
387
388     ID.destroy();                       // Free strdup'd memory.
389     return BB;
390   }
391
392   // Otherwise this block has not been seen before.
393   BB = new BasicBlock("", CurFun.CurrentFunction);
394   if (ID.Type == ValID::NameVal) {
395     BB->setName(ID.Name);
396   } else {
397     CurFun.NumberedBlocks[ID.Num] = BB;
398   }
399
400   // If this is not a definition, keep track of it so we can use it as a forward
401   // reference.
402   if (!isDefinition) {
403     // Remember where this forward reference came from.
404     CurFun.BBForwardRefs[BB] = std::make_pair(ID, llvmAsmlineno);
405   } else {
406     // The forward declaration could have been inserted anywhere in the
407     // function: insert it into the correct place now.
408     CurFun.CurrentFunction->getBasicBlockList().remove(BB);
409     CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
410   }
411   ID.destroy();
412   return BB;
413 }
414
415
416 //===----------------------------------------------------------------------===//
417 //              Code to handle forward references in instructions
418 //===----------------------------------------------------------------------===//
419 //
420 // This code handles the late binding needed with statements that reference
421 // values not defined yet... for example, a forward branch, or the PHI node for
422 // a loop body.
423 //
424 // This keeps a table (CurFun.LateResolveValues) of all such forward references
425 // and back patchs after we are done.
426 //
427
428 // ResolveDefinitions - If we could not resolve some defs at parsing
429 // time (forward branches, phi functions for loops, etc...) resolve the
430 // defs now...
431 //
432 static void 
433 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
434                    std::map<const Type*,ValueList> *FutureLateResolvers) {
435   // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
436   for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
437          E = LateResolvers.end(); LRI != E; ++LRI) {
438     ValueList &List = LRI->second;
439     while (!List.empty()) {
440       Value *V = List.back();
441       List.pop_back();
442
443       std::map<Value*, std::pair<ValID, int> >::iterator PHI =
444         CurModule.PlaceHolderInfo.find(V);
445       assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
446
447       ValID &DID = PHI->second.first;
448
449       Value *TheRealValue = getValNonImprovising(LRI->first, DID);
450       if (TheRealValue) {
451         V->replaceAllUsesWith(TheRealValue);
452         delete V;
453         CurModule.PlaceHolderInfo.erase(PHI);
454       } else if (FutureLateResolvers) {
455         // Functions have their unresolved items forwarded to the module late
456         // resolver table
457         InsertValue(V, *FutureLateResolvers);
458       } else {
459         if (DID.Type == ValID::NameVal)
460           ThrowException("Reference to an invalid definition: '" +DID.getName()+
461                          "' of type '" + V->getType()->getDescription() + "'",
462                          PHI->second.second);
463         else
464           ThrowException("Reference to an invalid definition: #" +
465                          itostr(DID.Num) + " of type '" +
466                          V->getType()->getDescription() + "'",
467                          PHI->second.second);
468       }
469     }
470   }
471
472   LateResolvers.clear();
473 }
474
475 // ResolveTypeTo - A brand new type was just declared.  This means that (if
476 // name is not null) things referencing Name can be resolved.  Otherwise, things
477 // refering to the number can be resolved.  Do this now.
478 //
479 static void ResolveTypeTo(char *Name, const Type *ToTy) {
480   ValID D;
481   if (Name) D = ValID::create(Name);
482   else      D = ValID::create((int)CurModule.Types.size());
483
484   std::map<ValID, PATypeHolder>::iterator I =
485     CurModule.LateResolveTypes.find(D);
486   if (I != CurModule.LateResolveTypes.end()) {
487     ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
488     CurModule.LateResolveTypes.erase(I);
489   }
490 }
491
492 // setValueName - Set the specified value to the name given.  The name may be
493 // null potentially, in which case this is a noop.  The string passed in is
494 // assumed to be a malloc'd string buffer, and is free'd by this function.
495 //
496 static void setValueName(Value *V, char *NameStr) {
497   if (NameStr) {
498     std::string Name(NameStr);      // Copy string
499     free(NameStr);                  // Free old string
500
501     if (V->getType() == Type::VoidTy)
502       ThrowException("Can't assign name '" + Name+"' to value with void type!");
503
504     assert(inFunctionScope() && "Must be in function scope!");
505     SymbolTable &ST = CurFun.CurrentFunction->getSymbolTable();
506     if (ST.lookup(V->getType(), Name))
507       ThrowException("Redefinition of value named '" + Name + "' in the '" +
508                      V->getType()->getDescription() + "' type plane!");
509
510     // Set the name.
511     V->setName(Name);
512   }
513 }
514
515 /// ParseGlobalVariable - Handle parsing of a global.  If Initializer is null,
516 /// this is a declaration, otherwise it is a definition.
517 static void ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
518                                 bool isConstantGlobal, const Type *Ty,
519                                 Constant *Initializer) {
520   if (isa<FunctionType>(Ty))
521     ThrowException("Cannot declare global vars of function type!");
522
523   const PointerType *PTy = PointerType::get(Ty);
524
525   std::string Name;
526   if (NameStr) {
527     Name = NameStr;      // Copy string
528     free(NameStr);       // Free old string
529   }
530
531   // See if this global value was forward referenced.  If so, recycle the
532   // object.
533   ValID ID;
534   if (!Name.empty()) {
535     ID = ValID::create((char*)Name.c_str());
536   } else {
537     ID = ValID::create((int)CurModule.Values[PTy].size());
538   }
539
540   if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
541     // Move the global to the end of the list, from whereever it was
542     // previously inserted.
543     GlobalVariable *GV = cast<GlobalVariable>(FWGV);
544     CurModule.CurrentModule->getGlobalList().remove(GV);
545     CurModule.CurrentModule->getGlobalList().push_back(GV);
546     GV->setInitializer(Initializer);
547     GV->setLinkage(Linkage);
548     GV->setConstant(isConstantGlobal);
549     InsertValue(GV, CurModule.Values);
550     return;
551   }
552
553   // If this global has a name, check to see if there is already a definition
554   // of this global in the module.  If so, merge as appropriate.  Note that
555   // this is really just a hack around problems in the CFE.  :(
556   if (!Name.empty()) {
557     // We are a simple redefinition of a value, check to see if it is defined
558     // the same as the old one.
559     if (GlobalVariable *EGV =
560                 CurModule.CurrentModule->getGlobalVariable(Name, Ty)) {
561       // We are allowed to redefine a global variable in two circumstances:
562       // 1. If at least one of the globals is uninitialized or
563       // 2. If both initializers have the same value.
564       //
565       if (!EGV->hasInitializer() || !Initializer ||
566           EGV->getInitializer() == Initializer) {
567
568         // Make sure the existing global version gets the initializer!  Make
569         // sure that it also gets marked const if the new version is.
570         if (Initializer && !EGV->hasInitializer())
571           EGV->setInitializer(Initializer);
572         if (isConstantGlobal)
573           EGV->setConstant(true);
574         EGV->setLinkage(Linkage);
575         return;
576       }
577
578       ThrowException("Redefinition of global variable named '" + Name +
579                      "' in the '" + Ty->getDescription() + "' type plane!");
580     }
581   }
582
583   // Otherwise there is no existing GV to use, create one now.
584   GlobalVariable *GV =
585     new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
586                        CurModule.CurrentModule);
587   InsertValue(GV, CurModule.Values);
588 }
589
590 // setTypeName - Set the specified type to the name given.  The name may be
591 // null potentially, in which case this is a noop.  The string passed in is
592 // assumed to be a malloc'd string buffer, and is freed by this function.
593 //
594 // This function returns true if the type has already been defined, but is
595 // allowed to be redefined in the specified context.  If the name is a new name
596 // for the type plane, it is inserted and false is returned.
597 static bool setTypeName(const Type *T, char *NameStr) {
598   assert(!inFunctionScope() && "Can't give types function-local names!");
599   if (NameStr == 0) return false;
600  
601   std::string Name(NameStr);      // Copy string
602   free(NameStr);                  // Free old string
603
604   // We don't allow assigning names to void type
605   if (T == Type::VoidTy)
606     ThrowException("Can't assign name '" + Name + "' to the void type!");
607
608   // Set the type name, checking for conflicts as we do so.
609   bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
610
611   if (AlreadyExists) {   // Inserting a name that is already defined???
612     const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
613     assert(Existing && "Conflict but no matching type?");
614
615     // There is only one case where this is allowed: when we are refining an
616     // opaque type.  In this case, Existing will be an opaque type.
617     if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
618       // We ARE replacing an opaque type!
619       const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
620       return true;
621     }
622
623     // Otherwise, this is an attempt to redefine a type. That's okay if
624     // the redefinition is identical to the original. This will be so if
625     // Existing and T point to the same Type object. In this one case we
626     // allow the equivalent redefinition.
627     if (Existing == T) return true;  // Yes, it's equal.
628
629     // Any other kind of (non-equivalent) redefinition is an error.
630     ThrowException("Redefinition of type named '" + Name + "' in the '" +
631                    T->getDescription() + "' type plane!");
632   }
633
634   return false;
635 }
636
637 //===----------------------------------------------------------------------===//
638 // Code for handling upreferences in type names...
639 //
640
641 // TypeContains - Returns true if Ty directly contains E in it.
642 //
643 static bool TypeContains(const Type *Ty, const Type *E) {
644   return std::find(Ty->subtype_begin(), Ty->subtype_end(),
645                    E) != Ty->subtype_end();
646 }
647
648 namespace {
649   struct UpRefRecord {
650     // NestingLevel - The number of nesting levels that need to be popped before
651     // this type is resolved.
652     unsigned NestingLevel;
653
654     // LastContainedTy - This is the type at the current binding level for the
655     // type.  Every time we reduce the nesting level, this gets updated.
656     const Type *LastContainedTy;
657
658     // UpRefTy - This is the actual opaque type that the upreference is
659     // represented with.
660     OpaqueType *UpRefTy;
661
662     UpRefRecord(unsigned NL, OpaqueType *URTy)
663       : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
664   };
665 }
666
667 // UpRefs - A list of the outstanding upreferences that need to be resolved.
668 static std::vector<UpRefRecord> UpRefs;
669
670 /// HandleUpRefs - Every time we finish a new layer of types, this function is
671 /// called.  It loops through the UpRefs vector, which is a list of the
672 /// currently active types.  For each type, if the up reference is contained in
673 /// the newly completed type, we decrement the level count.  When the level
674 /// count reaches zero, the upreferenced type is the type that is passed in:
675 /// thus we can complete the cycle.
676 ///
677 static PATypeHolder HandleUpRefs(const Type *ty) {
678   if (!ty->isAbstract()) return ty;
679   PATypeHolder Ty(ty);
680   UR_OUT("Type '" << Ty->getDescription() <<
681          "' newly formed.  Resolving upreferences.\n" <<
682          UpRefs.size() << " upreferences active!\n");
683
684   // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
685   // to zero), we resolve them all together before we resolve them to Ty.  At
686   // the end of the loop, if there is anything to resolve to Ty, it will be in
687   // this variable.
688   OpaqueType *TypeToResolve = 0;
689
690   for (unsigned i = 0; i != UpRefs.size(); ++i) {
691     UR_OUT("  UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
692            << UpRefs[i].second->getDescription() << ") = "
693            << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
694     if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
695       // Decrement level of upreference
696       unsigned Level = --UpRefs[i].NestingLevel;
697       UpRefs[i].LastContainedTy = Ty;
698       UR_OUT("  Uplevel Ref Level = " << Level << "\n");
699       if (Level == 0) {                     // Upreference should be resolved!
700         if (!TypeToResolve) {
701           TypeToResolve = UpRefs[i].UpRefTy;
702         } else {
703           UR_OUT("  * Resolving upreference for "
704                  << UpRefs[i].second->getDescription() << "\n";
705                  std::string OldName = UpRefs[i].UpRefTy->getDescription());
706           UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
707           UR_OUT("  * Type '" << OldName << "' refined upreference to: "
708                  << (const void*)Ty << ", " << Ty->getDescription() << "\n");
709         }
710         UpRefs.erase(UpRefs.begin()+i);     // Remove from upreference list...
711         --i;                                // Do not skip the next element...
712       }
713     }
714   }
715
716   if (TypeToResolve) {
717     UR_OUT("  * Resolving upreference for "
718            << UpRefs[i].second->getDescription() << "\n";
719            std::string OldName = TypeToResolve->getDescription());
720     TypeToResolve->refineAbstractTypeTo(Ty);
721   }
722
723   return Ty;
724 }
725
726
727 // common code from the two 'RunVMAsmParser' functions
728  static Module * RunParser(Module * M) {
729
730   llvmAsmlineno = 1;      // Reset the current line number...
731   ObsoleteVarArgs = false;
732   NewVarArgs = false;
733
734   CurModule.CurrentModule = M;
735   yyparse();       // Parse the file, potentially throwing exception
736
737   Module *Result = ParserResult;
738   ParserResult = 0;
739
740   //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
741   {
742     Function* F;
743     if ((F = Result->getNamedFunction("llvm.va_start"))
744         && F->getFunctionType()->getNumParams() == 0)
745       ObsoleteVarArgs = true;
746     if((F = Result->getNamedFunction("llvm.va_copy"))
747        && F->getFunctionType()->getNumParams() == 1)
748       ObsoleteVarArgs = true;
749   }
750
751   if (ObsoleteVarArgs && NewVarArgs)
752     ThrowException("This file is corrupt: it uses both new and old style varargs");
753
754   if(ObsoleteVarArgs) {
755     if(Function* F = Result->getNamedFunction("llvm.va_start")) {
756       if (F->arg_size() != 0)
757         ThrowException("Obsolete va_start takes 0 argument!");
758       
759       //foo = va_start()
760       // ->
761       //bar = alloca typeof(foo)
762       //va_start(bar)
763       //foo = load bar
764
765       const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
766       const Type* ArgTy = F->getFunctionType()->getReturnType();
767       const Type* ArgTyPtr = PointerType::get(ArgTy);
768       Function* NF = Result->getOrInsertFunction("llvm.va_start", 
769                                                  RetTy, ArgTyPtr, (Type *)0);
770
771       while (!F->use_empty()) {
772         CallInst* CI = cast<CallInst>(F->use_back());
773         AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
774         new CallInst(NF, bar, "", CI);
775         Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
776         CI->replaceAllUsesWith(foo);
777         CI->getParent()->getInstList().erase(CI);
778       }
779       Result->getFunctionList().erase(F);
780     }
781     
782     if(Function* F = Result->getNamedFunction("llvm.va_end")) {
783       if(F->arg_size() != 1)
784         ThrowException("Obsolete va_end takes 1 argument!");
785
786       //vaend foo
787       // ->
788       //bar = alloca 1 of typeof(foo)
789       //vaend bar
790       const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
791       const Type* ArgTy = F->getFunctionType()->getParamType(0);
792       const Type* ArgTyPtr = PointerType::get(ArgTy);
793       Function* NF = Result->getOrInsertFunction("llvm.va_end", 
794                                                  RetTy, ArgTyPtr, (Type *)0);
795
796       while (!F->use_empty()) {
797         CallInst* CI = cast<CallInst>(F->use_back());
798         AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
799         new StoreInst(CI->getOperand(1), bar, CI);
800         new CallInst(NF, bar, "", CI);
801         CI->getParent()->getInstList().erase(CI);
802       }
803       Result->getFunctionList().erase(F);
804     }
805
806     if(Function* F = Result->getNamedFunction("llvm.va_copy")) {
807       if(F->arg_size() != 1)
808         ThrowException("Obsolete va_copy takes 1 argument!");
809       //foo = vacopy(bar)
810       // ->
811       //a = alloca 1 of typeof(foo)
812       //b = alloca 1 of typeof(foo)
813       //store bar -> b
814       //vacopy(a, b)
815       //foo = load a
816       
817       const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
818       const Type* ArgTy = F->getFunctionType()->getReturnType();
819       const Type* ArgTyPtr = PointerType::get(ArgTy);
820       Function* NF = Result->getOrInsertFunction("llvm.va_copy", 
821                                                  RetTy, ArgTyPtr, ArgTyPtr,
822                                                  (Type *)0);
823
824       while (!F->use_empty()) {
825         CallInst* CI = cast<CallInst>(F->use_back());
826         AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
827         AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
828         new StoreInst(CI->getOperand(1), b, CI);
829         new CallInst(NF, a, b, "", CI);
830         Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
831         CI->replaceAllUsesWith(foo);
832         CI->getParent()->getInstList().erase(CI);
833       }
834       Result->getFunctionList().erase(F);
835     }
836   }
837
838   return Result;
839
840  }
841
842 //===----------------------------------------------------------------------===//
843 //            RunVMAsmParser - Define an interface to this parser
844 //===----------------------------------------------------------------------===//
845 //
846 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
847   set_scan_file(F);
848
849   CurFilename = Filename;
850   return RunParser(new Module(CurFilename));
851 }
852
853 Module *llvm::RunVMAsmParser(const char * AsmString, Module * M) {
854   set_scan_string(AsmString);
855
856   CurFilename = "from_memory";
857   if (M == NULL) {
858     return RunParser(new Module (CurFilename));
859   } else {
860     return RunParser(M);
861   }
862 }
863
864 %}
865
866 %union {
867   llvm::Module                           *ModuleVal;
868   llvm::Function                         *FunctionVal;
869   std::pair<llvm::PATypeHolder*, char*>  *ArgVal;
870   llvm::BasicBlock                       *BasicBlockVal;
871   llvm::TerminatorInst                   *TermInstVal;
872   llvm::Instruction                      *InstVal;
873   llvm::Constant                         *ConstVal;
874
875   const llvm::Type                       *PrimType;
876   llvm::PATypeHolder                     *TypeVal;
877   llvm::Value                            *ValueVal;
878
879   std::vector<std::pair<llvm::PATypeHolder*,char*> > *ArgList;
880   std::vector<llvm::Value*>              *ValueList;
881   std::list<llvm::PATypeHolder>          *TypeList;
882   // Represent the RHS of PHI node
883   std::list<std::pair<llvm::Value*,
884                       llvm::BasicBlock*> > *PHIList;
885   std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
886   std::vector<llvm::Constant*>           *ConstVector;
887
888   llvm::GlobalValue::LinkageTypes         Linkage;
889   int64_t                           SInt64Val;
890   uint64_t                          UInt64Val;
891   int                               SIntVal;
892   unsigned                          UIntVal;
893   double                            FPVal;
894   bool                              BoolVal;
895
896   char                             *StrVal;   // This memory is strdup'd!
897   llvm::ValID                             ValIDVal; // strdup'd memory maybe!
898
899   llvm::Instruction::BinaryOps            BinaryOpVal;
900   llvm::Instruction::TermOps              TermOpVal;
901   llvm::Instruction::MemoryOps            MemOpVal;
902   llvm::Instruction::OtherOps             OtherOpVal;
903   llvm::Module::Endianness                Endianness;
904 }
905
906 %type <ModuleVal>     Module FunctionList
907 %type <FunctionVal>   Function FunctionProto FunctionHeader BasicBlockList
908 %type <BasicBlockVal> BasicBlock InstructionList
909 %type <TermInstVal>   BBTerminatorInst
910 %type <InstVal>       Inst InstVal MemoryInst
911 %type <ConstVal>      ConstVal ConstExpr
912 %type <ConstVector>   ConstVector
913 %type <ArgList>       ArgList ArgListH
914 %type <ArgVal>        ArgVal
915 %type <PHIList>       PHIList
916 %type <ValueList>     ValueRefList ValueRefListE  // For call param lists
917 %type <ValueList>     IndexList                   // For GEP derived indices
918 %type <TypeList>      TypeListI ArgTypeListI
919 %type <JumpTable>     JumpTable
920 %type <BoolVal>       GlobalType                  // GLOBAL or CONSTANT?
921 %type <BoolVal>       OptVolatile                 // 'volatile' or not
922 %type <BoolVal>       OptTailCall                 // TAIL CALL or plain CALL.
923 %type <Linkage>       OptLinkage
924 %type <Endianness>    BigOrLittle
925
926 // ValueRef - Unresolved reference to a definition or BB
927 %type <ValIDVal>      ValueRef ConstValueRef SymbolicValueRef
928 %type <ValueVal>      ResolvedVal            // <type> <valref> pair
929 // Tokens and types for handling constant integer values
930 //
931 // ESINT64VAL - A negative number within long long range
932 %token <SInt64Val> ESINT64VAL
933
934 // EUINT64VAL - A positive number within uns. long long range
935 %token <UInt64Val> EUINT64VAL
936 %type  <SInt64Val> EINT64VAL
937
938 %token  <SIntVal>   SINTVAL   // Signed 32 bit ints...
939 %token  <UIntVal>   UINTVAL   // Unsigned 32 bit ints...
940 %type   <SIntVal>   INTVAL
941 %token  <FPVal>     FPVAL     // Float or Double constant
942
943 // Built in types...
944 %type  <TypeVal> Types TypesV UpRTypes UpRTypesV
945 %type  <PrimType> SIntType UIntType IntType FPType PrimType   // Classifications
946 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
947 %token <PrimType> FLOAT DOUBLE TYPE LABEL
948
949 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
950 %type  <StrVal> Name OptName OptAssign
951
952
953 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
954 %token DECLARE GLOBAL CONSTANT VOLATILE
955 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK  APPENDING
956 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG
957 %token DEPLIBS CALL TAIL
958 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK
959 %type <UIntVal> OptCallingConv
960
961 // Basic Block Terminating Operators
962 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
963
964 // Binary Operators
965 %type  <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
966 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
967 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE  // Binary Comarators
968
969 // Memory Instructions
970 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
971
972 // Other Operators
973 %type  <OtherOpVal> ShiftOps
974 %token <OtherOpVal> PHI_TOK CAST SELECT SHL SHR VAARG
975 %token VAARG_old VANEXT_old //OBSOLETE
976
977
978 %start Module
979 %%
980
981 // Handle constant integer size restriction and conversion...
982 //
983 INTVAL : SINTVAL;
984 INTVAL : UINTVAL {
985   if ($1 > (uint32_t)INT32_MAX)     // Outside of my range!
986     ThrowException("Value too large for type!");
987   $$ = (int32_t)$1;
988 };
989
990
991 EINT64VAL : ESINT64VAL;      // These have same type and can't cause problems...
992 EINT64VAL : EUINT64VAL {
993   if ($1 > (uint64_t)INT64_MAX)     // Outside of my range!
994     ThrowException("Value too large for type!");
995   $$ = (int64_t)$1;
996 };
997
998 // Operations that are notably excluded from this list include:
999 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1000 //
1001 ArithmeticOps: ADD | SUB | MUL | DIV | REM;
1002 LogicalOps   : AND | OR | XOR;
1003 SetCondOps   : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
1004
1005 ShiftOps  : SHL | SHR;
1006
1007 // These are some types that allow classification if we only want a particular 
1008 // thing... for example, only a signed, unsigned, or integral type.
1009 SIntType :  LONG |  INT |  SHORT | SBYTE;
1010 UIntType : ULONG | UINT | USHORT | UBYTE;
1011 IntType  : SIntType | UIntType;
1012 FPType   : FLOAT | DOUBLE;
1013
1014 // OptAssign - Value producing statements have an optional assignment component
1015 OptAssign : Name '=' {
1016     $$ = $1;
1017   }
1018   | /*empty*/ {
1019     $$ = 0;
1020   };
1021
1022 OptLinkage : INTERNAL  { $$ = GlobalValue::InternalLinkage; } |
1023              LINKONCE  { $$ = GlobalValue::LinkOnceLinkage; } |
1024              WEAK      { $$ = GlobalValue::WeakLinkage; } |
1025              APPENDING { $$ = GlobalValue::AppendingLinkage; } |
1026              /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
1027
1028 OptCallingConv : /*empty*/      { $$ = CallingConv::C; } |
1029                  CCC_TOK        { $$ = CallingConv::C; } |
1030                  FASTCC_TOK     { $$ = CallingConv::Fast; } |
1031                  COLDCC_TOK     { $$ = CallingConv::Cold; } |
1032                  CC_TOK EUINT64VAL {
1033                    if ((unsigned)$2 != $2)
1034                      ThrowException("Calling conv too large!");
1035                    $$ = $2;
1036                  };
1037
1038 //===----------------------------------------------------------------------===//
1039 // Types includes all predefined types... except void, because it can only be
1040 // used in specific contexts (function returning void for example).  To have
1041 // access to it, a user must explicitly use TypesV.
1042 //
1043
1044 // TypesV includes all of 'Types', but it also includes the void type.
1045 TypesV    : Types    | VOID { $$ = new PATypeHolder($1); };
1046 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
1047
1048 Types     : UpRTypes {
1049     if (!UpRefs.empty())
1050       ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
1051     $$ = $1;
1052   };
1053
1054
1055 // Derived types are added later...
1056 //
1057 PrimType : BOOL | SBYTE | UBYTE | SHORT  | USHORT | INT   | UINT ;
1058 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE   | LABEL;
1059 UpRTypes : OPAQUE {
1060     $$ = new PATypeHolder(OpaqueType::get());
1061   }
1062   | PrimType {
1063     $$ = new PATypeHolder($1);
1064   };
1065 UpRTypes : SymbolicValueRef {            // Named types are also simple types...
1066   $$ = new PATypeHolder(getTypeVal($1));
1067 };
1068
1069 // Include derived types in the Types production.
1070 //
1071 UpRTypes : '\\' EUINT64VAL {                   // Type UpReference
1072     if ($2 > (uint64_t)~0U) ThrowException("Value out of range!");
1073     OpaqueType *OT = OpaqueType::get();        // Use temporary placeholder
1074     UpRefs.push_back(UpRefRecord((unsigned)$2, OT));  // Add to vector...
1075     $$ = new PATypeHolder(OT);
1076     UR_OUT("New Upreference!\n");
1077   }
1078   | UpRTypesV '(' ArgTypeListI ')' {           // Function derived type?
1079     std::vector<const Type*> Params;
1080     for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1081            E = $3->end(); I != E; ++I)
1082       Params.push_back(*I);
1083     bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1084     if (isVarArg) Params.pop_back();
1085
1086     $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
1087     delete $3;      // Delete the argument list
1088     delete $1;      // Delete the return type handle
1089   }
1090   | '[' EUINT64VAL 'x' UpRTypes ']' {          // Sized array type?
1091     $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1092     delete $4;
1093   }
1094   | '<' EUINT64VAL 'x' UpRTypes '>' {          // Packed array type?
1095      const llvm::Type* ElemTy = $4->get();
1096      if ((unsigned)$2 != $2) {
1097         ThrowException("Unsigned result not equal to signed result");
1098      }
1099      if(!ElemTy->isPrimitiveType()) {
1100         ThrowException("Elemental type of a PackedType must be primitive");
1101      }
1102      $$ = new PATypeHolder(HandleUpRefs(PackedType::get(*$4, (unsigned)$2)));
1103      delete $4;
1104   }
1105   | '{' TypeListI '}' {                        // Structure type?
1106     std::vector<const Type*> Elements;
1107     for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1108            E = $2->end(); I != E; ++I)
1109       Elements.push_back(*I);
1110
1111     $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1112     delete $2;
1113   }
1114   | '{' '}' {                                  // Empty structure type?
1115     $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1116   }
1117   | UpRTypes '*' {                             // Pointer type?
1118     $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1119     delete $1;
1120   };
1121
1122 // TypeList - Used for struct declarations and as a basis for function type 
1123 // declaration type lists
1124 //
1125 TypeListI : UpRTypes {
1126     $$ = new std::list<PATypeHolder>();
1127     $$->push_back(*$1); delete $1;
1128   }
1129   | TypeListI ',' UpRTypes {
1130     ($$=$1)->push_back(*$3); delete $3;
1131   };
1132
1133 // ArgTypeList - List of types for a function type declaration...
1134 ArgTypeListI : TypeListI
1135   | TypeListI ',' DOTDOTDOT {
1136     ($$=$1)->push_back(Type::VoidTy);
1137   }
1138   | DOTDOTDOT {
1139     ($$ = new std::list<PATypeHolder>())->push_back(Type::VoidTy);
1140   }
1141   | /*empty*/ {
1142     $$ = new std::list<PATypeHolder>();
1143   };
1144
1145 // ConstVal - The various declarations that go into the constant pool.  This
1146 // production is used ONLY to represent constants that show up AFTER a 'const',
1147 // 'constant' or 'global' token at global scope.  Constants that can be inlined
1148 // into other expressions (such as integers and constexprs) are handled by the
1149 // ResolvedVal, ValueRef and ConstValueRef productions.
1150 //
1151 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1152     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1153     if (ATy == 0)
1154       ThrowException("Cannot make array constant with type: '" + 
1155                      (*$1)->getDescription() + "'!");
1156     const Type *ETy = ATy->getElementType();
1157     int NumElements = ATy->getNumElements();
1158
1159     // Verify that we have the correct size...
1160     if (NumElements != -1 && NumElements != (int)$3->size())
1161       ThrowException("Type mismatch: constant sized array initialized with " +
1162                      utostr($3->size()) +  " arguments, but has size of " + 
1163                      itostr(NumElements) + "!");
1164
1165     // Verify all elements are correct type!
1166     for (unsigned i = 0; i < $3->size(); i++) {
1167       if (ETy != (*$3)[i]->getType())
1168         ThrowException("Element #" + utostr(i) + " is not of type '" + 
1169                        ETy->getDescription() +"' as required!\nIt is of type '"+
1170                        (*$3)[i]->getType()->getDescription() + "'.");
1171     }
1172
1173     $$ = ConstantArray::get(ATy, *$3);
1174     delete $1; delete $3;
1175   }
1176   | Types '[' ']' {
1177     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1178     if (ATy == 0)
1179       ThrowException("Cannot make array constant with type: '" + 
1180                      (*$1)->getDescription() + "'!");
1181
1182     int NumElements = ATy->getNumElements();
1183     if (NumElements != -1 && NumElements != 0) 
1184       ThrowException("Type mismatch: constant sized array initialized with 0"
1185                      " arguments, but has size of " + itostr(NumElements) +"!");
1186     $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1187     delete $1;
1188   }
1189   | Types 'c' STRINGCONSTANT {
1190     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1191     if (ATy == 0)
1192       ThrowException("Cannot make array constant with type: '" + 
1193                      (*$1)->getDescription() + "'!");
1194
1195     int NumElements = ATy->getNumElements();
1196     const Type *ETy = ATy->getElementType();
1197     char *EndStr = UnEscapeLexed($3, true);
1198     if (NumElements != -1 && NumElements != (EndStr-$3))
1199       ThrowException("Can't build string constant of size " + 
1200                      itostr((int)(EndStr-$3)) +
1201                      " when array has size " + itostr(NumElements) + "!");
1202     std::vector<Constant*> Vals;
1203     if (ETy == Type::SByteTy) {
1204       for (char *C = $3; C != EndStr; ++C)
1205         Vals.push_back(ConstantSInt::get(ETy, *C));
1206     } else if (ETy == Type::UByteTy) {
1207       for (char *C = $3; C != EndStr; ++C)
1208         Vals.push_back(ConstantUInt::get(ETy, (unsigned char)*C));
1209     } else {
1210       free($3);
1211       ThrowException("Cannot build string arrays of non byte sized elements!");
1212     }
1213     free($3);
1214     $$ = ConstantArray::get(ATy, Vals);
1215     delete $1;
1216   }
1217   | Types '<' ConstVector '>' { // Nonempty unsized arr
1218     const PackedType *PTy = dyn_cast<PackedType>($1->get());
1219     if (PTy == 0)
1220       ThrowException("Cannot make packed constant with type: '" + 
1221                      (*$1)->getDescription() + "'!");
1222     const Type *ETy = PTy->getElementType();
1223     int NumElements = PTy->getNumElements();
1224
1225     // Verify that we have the correct size...
1226     if (NumElements != -1 && NumElements != (int)$3->size())
1227       ThrowException("Type mismatch: constant sized packed initialized with " +
1228                      utostr($3->size()) +  " arguments, but has size of " + 
1229                      itostr(NumElements) + "!");
1230
1231     // Verify all elements are correct type!
1232     for (unsigned i = 0; i < $3->size(); i++) {
1233       if (ETy != (*$3)[i]->getType())
1234         ThrowException("Element #" + utostr(i) + " is not of type '" + 
1235            ETy->getDescription() +"' as required!\nIt is of type '"+
1236            (*$3)[i]->getType()->getDescription() + "'.");
1237     }
1238
1239     $$ = ConstantPacked::get(PTy, *$3);
1240     delete $1; delete $3;
1241   }
1242   | Types '{' ConstVector '}' {
1243     const StructType *STy = dyn_cast<StructType>($1->get());
1244     if (STy == 0)
1245       ThrowException("Cannot make struct constant with type: '" + 
1246                      (*$1)->getDescription() + "'!");
1247
1248     if ($3->size() != STy->getNumContainedTypes())
1249       ThrowException("Illegal number of initializers for structure type!");
1250
1251     // Check to ensure that constants are compatible with the type initializer!
1252     for (unsigned i = 0, e = $3->size(); i != e; ++i)
1253       if ((*$3)[i]->getType() != STy->getElementType(i))
1254         ThrowException("Expected type '" +
1255                        STy->getElementType(i)->getDescription() +
1256                        "' for element #" + utostr(i) +
1257                        " of structure initializer!");
1258
1259     $$ = ConstantStruct::get(STy, *$3);
1260     delete $1; delete $3;
1261   }
1262   | Types '{' '}' {
1263     const StructType *STy = dyn_cast<StructType>($1->get());
1264     if (STy == 0)
1265       ThrowException("Cannot make struct constant with type: '" + 
1266                      (*$1)->getDescription() + "'!");
1267
1268     if (STy->getNumContainedTypes() != 0)
1269       ThrowException("Illegal number of initializers for structure type!");
1270
1271     $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1272     delete $1;
1273   }
1274   | Types NULL_TOK {
1275     const PointerType *PTy = dyn_cast<PointerType>($1->get());
1276     if (PTy == 0)
1277       ThrowException("Cannot make null pointer constant with type: '" + 
1278                      (*$1)->getDescription() + "'!");
1279
1280     $$ = ConstantPointerNull::get(PTy);
1281     delete $1;
1282   }
1283   | Types UNDEF {
1284     $$ = UndefValue::get($1->get());
1285     delete $1;
1286   }
1287   | Types SymbolicValueRef {
1288     const PointerType *Ty = dyn_cast<PointerType>($1->get());
1289     if (Ty == 0)
1290       ThrowException("Global const reference must be a pointer type!");
1291
1292     // ConstExprs can exist in the body of a function, thus creating
1293     // GlobalValues whenever they refer to a variable.  Because we are in
1294     // the context of a function, getValNonImprovising will search the functions
1295     // symbol table instead of the module symbol table for the global symbol,
1296     // which throws things all off.  To get around this, we just tell
1297     // getValNonImprovising that we are at global scope here.
1298     //
1299     Function *SavedCurFn = CurFun.CurrentFunction;
1300     CurFun.CurrentFunction = 0;
1301
1302     Value *V = getValNonImprovising(Ty, $2);
1303
1304     CurFun.CurrentFunction = SavedCurFn;
1305
1306     // If this is an initializer for a constant pointer, which is referencing a
1307     // (currently) undefined variable, create a stub now that shall be replaced
1308     // in the future with the right type of variable.
1309     //
1310     if (V == 0) {
1311       assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1312       const PointerType *PT = cast<PointerType>(Ty);
1313
1314       // First check to see if the forward references value is already created!
1315       PerModuleInfo::GlobalRefsType::iterator I =
1316         CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1317     
1318       if (I != CurModule.GlobalRefs.end()) {
1319         V = I->second;             // Placeholder already exists, use it...
1320         $2.destroy();
1321       } else {
1322         std::string Name;
1323         if ($2.Type == ValID::NameVal) Name = $2.Name;
1324
1325         // Create the forward referenced global.
1326         GlobalValue *GV;
1327         if (const FunctionType *FTy = 
1328                  dyn_cast<FunctionType>(PT->getElementType())) {
1329           GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1330                             CurModule.CurrentModule);
1331         } else {
1332           GV = new GlobalVariable(PT->getElementType(), false,
1333                                   GlobalValue::ExternalLinkage, 0,
1334                                   Name, CurModule.CurrentModule);
1335         }
1336
1337         // Keep track of the fact that we have a forward ref to recycle it
1338         CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1339         V = GV;
1340       }
1341     }
1342
1343     $$ = cast<GlobalValue>(V);
1344     delete $1;            // Free the type handle
1345   }
1346   | Types ConstExpr {
1347     if ($1->get() != $2->getType())
1348       ThrowException("Mismatched types for constant expression!");
1349     $$ = $2;
1350     delete $1;
1351   }
1352   | Types ZEROINITIALIZER {
1353     const Type *Ty = $1->get();
1354     if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1355       ThrowException("Cannot create a null initialized value of this type!");
1356     $$ = Constant::getNullValue(Ty);
1357     delete $1;
1358   };
1359
1360 ConstVal : SIntType EINT64VAL {      // integral constants
1361     if (!ConstantSInt::isValueValidForType($1, $2))
1362       ThrowException("Constant value doesn't fit in type!");
1363     $$ = ConstantSInt::get($1, $2);
1364   }
1365   | UIntType EUINT64VAL {            // integral constants
1366     if (!ConstantUInt::isValueValidForType($1, $2))
1367       ThrowException("Constant value doesn't fit in type!");
1368     $$ = ConstantUInt::get($1, $2);
1369   }
1370   | BOOL TRUETOK {                      // Boolean constants
1371     $$ = ConstantBool::True;
1372   }
1373   | BOOL FALSETOK {                     // Boolean constants
1374     $$ = ConstantBool::False;
1375   }
1376   | FPType FPVAL {                   // Float & Double constants
1377     if (!ConstantFP::isValueValidForType($1, $2))
1378       ThrowException("Floating point constant invalid for type!!");
1379     $$ = ConstantFP::get($1, $2);
1380   };
1381
1382
1383 ConstExpr: CAST '(' ConstVal TO Types ')' {
1384     if (!$3->getType()->isFirstClassType())
1385       ThrowException("cast constant expression from a non-primitive type: '" +
1386                      $3->getType()->getDescription() + "'!");
1387     if (!$5->get()->isFirstClassType())
1388       ThrowException("cast constant expression to a non-primitive type: '" +
1389                      $5->get()->getDescription() + "'!");
1390     $$ = ConstantExpr::getCast($3, $5->get());
1391     delete $5;
1392   }
1393   | GETELEMENTPTR '(' ConstVal IndexList ')' {
1394     if (!isa<PointerType>($3->getType()))
1395       ThrowException("GetElementPtr requires a pointer operand!");
1396
1397     // LLVM 1.2 and earlier used ubyte struct indices.  Convert any ubyte struct
1398     // indices to uint struct indices for compatibility.
1399     generic_gep_type_iterator<std::vector<Value*>::iterator>
1400       GTI = gep_type_begin($3->getType(), $4->begin(), $4->end()),
1401       GTE = gep_type_end($3->getType(), $4->begin(), $4->end());
1402     for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
1403       if (isa<StructType>(*GTI))        // Only change struct indices
1404         if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
1405           if (CUI->getType() == Type::UByteTy)
1406             (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
1407
1408     const Type *IdxTy =
1409       GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1410     if (!IdxTy)
1411       ThrowException("Index list invalid for constant getelementptr!");
1412
1413     std::vector<Constant*> IdxVec;
1414     for (unsigned i = 0, e = $4->size(); i != e; ++i)
1415       if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1416         IdxVec.push_back(C);
1417       else
1418         ThrowException("Indices to constant getelementptr must be constants!");
1419
1420     delete $4;
1421
1422     $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1423   }
1424   | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1425     if ($3->getType() != Type::BoolTy)
1426       ThrowException("Select condition must be of boolean type!");
1427     if ($5->getType() != $7->getType())
1428       ThrowException("Select operand types must match!");
1429     $$ = ConstantExpr::getSelect($3, $5, $7);
1430   }
1431   | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1432     if ($3->getType() != $5->getType())
1433       ThrowException("Binary operator types must match!");
1434     // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
1435     // To retain backward compatibility with these early compilers, we emit a
1436     // cast to the appropriate integer type automatically if we are in the
1437     // broken case.  See PR424 for more information.
1438     if (!isa<PointerType>($3->getType())) {
1439       $$ = ConstantExpr::get($1, $3, $5);
1440     } else {
1441       const Type *IntPtrTy = 0;
1442       switch (CurModule.CurrentModule->getPointerSize()) {
1443       case Module::Pointer32: IntPtrTy = Type::IntTy; break;
1444       case Module::Pointer64: IntPtrTy = Type::LongTy; break;
1445       default: ThrowException("invalid pointer binary constant expr!");
1446       }
1447       $$ = ConstantExpr::get($1, ConstantExpr::getCast($3, IntPtrTy),
1448                              ConstantExpr::getCast($5, IntPtrTy));
1449       $$ = ConstantExpr::getCast($$, $3->getType());
1450     }
1451   }
1452   | LogicalOps '(' ConstVal ',' ConstVal ')' {
1453     if ($3->getType() != $5->getType())
1454       ThrowException("Logical operator types must match!");
1455     if (!$3->getType()->isIntegral())
1456       ThrowException("Logical operands must have integral types!");
1457     $$ = ConstantExpr::get($1, $3, $5);
1458   }
1459   | SetCondOps '(' ConstVal ',' ConstVal ')' {
1460     if ($3->getType() != $5->getType())
1461       ThrowException("setcc operand types must match!");
1462     $$ = ConstantExpr::get($1, $3, $5);
1463   }
1464   | ShiftOps '(' ConstVal ',' ConstVal ')' {
1465     if ($5->getType() != Type::UByteTy)
1466       ThrowException("Shift count for shift constant must be unsigned byte!");
1467     if (!$3->getType()->isInteger())
1468       ThrowException("Shift constant expression requires integer operand!");
1469     $$ = ConstantExpr::get($1, $3, $5);
1470   };
1471
1472
1473 // ConstVector - A list of comma separated constants.
1474 ConstVector : ConstVector ',' ConstVal {
1475     ($$ = $1)->push_back($3);
1476   }
1477   | ConstVal {
1478     $$ = new std::vector<Constant*>();
1479     $$->push_back($1);
1480   };
1481
1482
1483 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1484 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1485
1486
1487 //===----------------------------------------------------------------------===//
1488 //                             Rules to match Modules
1489 //===----------------------------------------------------------------------===//
1490
1491 // Module rule: Capture the result of parsing the whole file into a result
1492 // variable...
1493 //
1494 Module : FunctionList {
1495   $$ = ParserResult = $1;
1496   CurModule.ModuleDone();
1497 };
1498
1499 // FunctionList - A list of functions, preceeded by a constant pool.
1500 //
1501 FunctionList : FunctionList Function {
1502     $$ = $1;
1503     CurFun.FunctionDone();
1504   } 
1505   | FunctionList FunctionProto {
1506     $$ = $1;
1507   }
1508   | FunctionList IMPLEMENTATION {
1509     $$ = $1;
1510   }
1511   | ConstPool {
1512     $$ = CurModule.CurrentModule;
1513     // Emit an error if there are any unresolved types left.
1514     if (!CurModule.LateResolveTypes.empty()) {
1515       const ValID &DID = CurModule.LateResolveTypes.begin()->first;
1516       if (DID.Type == ValID::NameVal)
1517         ThrowException("Reference to an undefined type: '"+DID.getName() + "'");
1518       else
1519         ThrowException("Reference to an undefined type: #" + itostr(DID.Num));
1520     }
1521   };
1522
1523 // ConstPool - Constants with optional names assigned to them.
1524 ConstPool : ConstPool OptAssign TYPE TypesV {
1525     // Eagerly resolve types.  This is not an optimization, this is a
1526     // requirement that is due to the fact that we could have this:
1527     //
1528     // %list = type { %list * }
1529     // %list = type { %list * }    ; repeated type decl
1530     //
1531     // If types are not resolved eagerly, then the two types will not be
1532     // determined to be the same type!
1533     //
1534     ResolveTypeTo($2, *$4);
1535
1536     if (!setTypeName(*$4, $2) && !$2) {
1537       // If this is a named type that is not a redefinition, add it to the slot
1538       // table.
1539       CurModule.Types.push_back(*$4);
1540     }
1541
1542     delete $4;
1543   }
1544   | ConstPool FunctionProto {       // Function prototypes can be in const pool
1545   }
1546   | ConstPool OptAssign OptLinkage GlobalType ConstVal {
1547     if ($5 == 0) ThrowException("Global value initializer is not a constant!");
1548     ParseGlobalVariable($2, $3, $4, $5->getType(), $5);
1549   }
1550   | ConstPool OptAssign EXTERNAL GlobalType Types {
1551     ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, *$5, 0);
1552     delete $5;
1553   }
1554   | ConstPool TARGET TargetDefinition { 
1555   }
1556   | ConstPool DEPLIBS '=' LibrariesDefinition {
1557   }
1558   | /* empty: end of list */ { 
1559   };
1560
1561
1562
1563 BigOrLittle : BIG    { $$ = Module::BigEndian; };
1564 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1565
1566 TargetDefinition : ENDIAN '=' BigOrLittle {
1567     CurModule.CurrentModule->setEndianness($3);
1568   }
1569   | POINTERSIZE '=' EUINT64VAL {
1570     if ($3 == 32)
1571       CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1572     else if ($3 == 64)
1573       CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1574     else
1575       ThrowException("Invalid pointer size: '" + utostr($3) + "'!");
1576   }
1577   | TRIPLE '=' STRINGCONSTANT {
1578     CurModule.CurrentModule->setTargetTriple($3);
1579     free($3);
1580   };
1581
1582 LibrariesDefinition : '[' LibList ']';
1583
1584 LibList : LibList ',' STRINGCONSTANT {
1585           CurModule.CurrentModule->addLibrary($3);
1586           free($3);
1587         }
1588         | STRINGCONSTANT {
1589           CurModule.CurrentModule->addLibrary($1);
1590           free($1);
1591         }
1592         | /* empty: end of list */ {
1593         }
1594         ;
1595
1596 //===----------------------------------------------------------------------===//
1597 //                       Rules to match Function Headers
1598 //===----------------------------------------------------------------------===//
1599
1600 Name : VAR_ID | STRINGCONSTANT;
1601 OptName : Name | /*empty*/ { $$ = 0; };
1602
1603 ArgVal : Types OptName {
1604   if (*$1 == Type::VoidTy)
1605     ThrowException("void typed arguments are invalid!");
1606   $$ = new std::pair<PATypeHolder*, char*>($1, $2);
1607 };
1608
1609 ArgListH : ArgListH ',' ArgVal {
1610     $$ = $1;
1611     $1->push_back(*$3);
1612     delete $3;
1613   }
1614   | ArgVal {
1615     $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1616     $$->push_back(*$1);
1617     delete $1;
1618   };
1619
1620 ArgList : ArgListH {
1621     $$ = $1;
1622   }
1623   | ArgListH ',' DOTDOTDOT {
1624     $$ = $1;
1625     $$->push_back(std::pair<PATypeHolder*,
1626                             char*>(new PATypeHolder(Type::VoidTy), 0));
1627   }
1628   | DOTDOTDOT {
1629     $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1630     $$->push_back(std::make_pair(new PATypeHolder(Type::VoidTy), (char*)0));
1631   }
1632   | /* empty */ {
1633     $$ = 0;
1634   };
1635
1636 FunctionHeaderH : OptCallingConv TypesV Name '(' ArgList ')' {
1637   UnEscapeLexed($3);
1638   std::string FunctionName($3);
1639   free($3);  // Free strdup'd memory!
1640   
1641   if (!(*$2)->isFirstClassType() && *$2 != Type::VoidTy)
1642     ThrowException("LLVM functions cannot return aggregate types!");
1643
1644   std::vector<const Type*> ParamTypeList;
1645   if ($5) {   // If there are arguments...
1646     for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
1647          I != $5->end(); ++I)
1648       ParamTypeList.push_back(I->first->get());
1649   }
1650
1651   bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1652   if (isVarArg) ParamTypeList.pop_back();
1653
1654   const FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
1655   const PointerType *PFT = PointerType::get(FT);
1656   delete $2;
1657
1658   ValID ID;
1659   if (!FunctionName.empty()) {
1660     ID = ValID::create((char*)FunctionName.c_str());
1661   } else {
1662     ID = ValID::create((int)CurModule.Values[PFT].size());
1663   }
1664
1665   Function *Fn = 0;
1666   // See if this function was forward referenced.  If so, recycle the object.
1667   if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
1668     // Move the function to the end of the list, from whereever it was 
1669     // previously inserted.
1670     Fn = cast<Function>(FWRef);
1671     CurModule.CurrentModule->getFunctionList().remove(Fn);
1672     CurModule.CurrentModule->getFunctionList().push_back(Fn);
1673   } else if (!FunctionName.empty() &&     // Merge with an earlier prototype?
1674              (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
1675     // If this is the case, either we need to be a forward decl, or it needs 
1676     // to be.
1677     if (!CurFun.isDeclare && !Fn->isExternal())
1678       ThrowException("Redefinition of function '" + FunctionName + "'!");
1679     
1680     // Make sure to strip off any argument names so we can't get conflicts.
1681     if (Fn->isExternal())
1682       for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
1683            AI != AE; ++AI)
1684         AI->setName("");
1685
1686   } else  {  // Not already defined?
1687     Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
1688                       CurModule.CurrentModule);
1689     InsertValue(Fn, CurModule.Values);
1690   }
1691
1692   CurFun.FunctionStart(Fn);
1693   Fn->setCallingConv($1);
1694
1695   // Add all of the arguments we parsed to the function...
1696   if ($5) {                     // Is null if empty...
1697     if (isVarArg) {  // Nuke the last entry
1698       assert($5->back().first->get() == Type::VoidTy && $5->back().second == 0&&
1699              "Not a varargs marker!");
1700       delete $5->back().first;
1701       $5->pop_back();  // Delete the last entry
1702     }
1703     Function::arg_iterator ArgIt = Fn->arg_begin();
1704     for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
1705          I != $5->end(); ++I, ++ArgIt) {
1706       delete I->first;                          // Delete the typeholder...
1707
1708       setValueName(ArgIt, I->second);           // Insert arg into symtab...
1709       InsertValue(ArgIt);
1710     }
1711
1712     delete $5;                     // We're now done with the argument list
1713   }
1714 };
1715
1716 BEGIN : BEGINTOK | '{';                // Allow BEGIN or '{' to start a function
1717
1718 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
1719   $$ = CurFun.CurrentFunction;
1720
1721   // Make sure that we keep track of the linkage type even if there was a
1722   // previous "declare".
1723   $$->setLinkage($1);
1724 };
1725
1726 END : ENDTOK | '}';                    // Allow end of '}' to end a function
1727
1728 Function : BasicBlockList END {
1729   $$ = $1;
1730 };
1731
1732 FunctionProto : DECLARE { CurFun.isDeclare = true; } FunctionHeaderH {
1733   $$ = CurFun.CurrentFunction;
1734   CurFun.FunctionDone();
1735 };
1736
1737 //===----------------------------------------------------------------------===//
1738 //                        Rules to match Basic Blocks
1739 //===----------------------------------------------------------------------===//
1740
1741 ConstValueRef : ESINT64VAL {    // A reference to a direct constant
1742     $$ = ValID::create($1);
1743   }
1744   | EUINT64VAL {
1745     $$ = ValID::create($1);
1746   }
1747   | FPVAL {                     // Perhaps it's an FP constant?
1748     $$ = ValID::create($1);
1749   }
1750   | TRUETOK {
1751     $$ = ValID::create(ConstantBool::True);
1752   } 
1753   | FALSETOK {
1754     $$ = ValID::create(ConstantBool::False);
1755   }
1756   | NULL_TOK {
1757     $$ = ValID::createNull();
1758   }
1759   | UNDEF {
1760     $$ = ValID::createUndef();
1761   }
1762   | '<' ConstVector '>' { // Nonempty unsized packed vector
1763     const Type *ETy = (*$2)[0]->getType();
1764     int NumElements = $2->size(); 
1765     
1766     PackedType* pt = PackedType::get(ETy, NumElements);
1767     PATypeHolder* PTy = new PATypeHolder(
1768                                          HandleUpRefs(
1769                                             PackedType::get(
1770                                                 ETy, 
1771                                                 NumElements)
1772                                             )
1773                                          );
1774     
1775     // Verify all elements are correct type!
1776     for (unsigned i = 0; i < $2->size(); i++) {
1777       if (ETy != (*$2)[i]->getType())
1778         ThrowException("Element #" + utostr(i) + " is not of type '" + 
1779                      ETy->getDescription() +"' as required!\nIt is of type '" +
1780                      (*$2)[i]->getType()->getDescription() + "'.");
1781     }
1782
1783     $$ = ValID::create(ConstantPacked::get(pt, *$2));
1784     delete PTy; delete $2;
1785   }
1786   | ConstExpr {
1787     $$ = ValID::create($1);
1788   };
1789
1790 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1791 // another value.
1792 //
1793 SymbolicValueRef : INTVAL {  // Is it an integer reference...?
1794     $$ = ValID::create($1);
1795   }
1796   | Name {                   // Is it a named reference...?
1797     $$ = ValID::create($1);
1798   };
1799
1800 // ValueRef - A reference to a definition... either constant or symbolic
1801 ValueRef : SymbolicValueRef | ConstValueRef;
1802
1803
1804 // ResolvedVal - a <type> <value> pair.  This is used only in cases where the
1805 // type immediately preceeds the value reference, and allows complex constant
1806 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1807 ResolvedVal : Types ValueRef {
1808     $$ = getVal(*$1, $2); delete $1;
1809   };
1810
1811 BasicBlockList : BasicBlockList BasicBlock {
1812     $$ = $1;
1813   }
1814   | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks   
1815     $$ = $1;
1816   };
1817
1818
1819 // Basic blocks are terminated by branching instructions: 
1820 // br, br/cc, switch, ret
1821 //
1822 BasicBlock : InstructionList OptAssign BBTerminatorInst  {
1823     setValueName($3, $2);
1824     InsertValue($3);
1825
1826     $1->getInstList().push_back($3);
1827     InsertValue($1);
1828     $$ = $1;
1829   };
1830
1831 InstructionList : InstructionList Inst {
1832     $1->getInstList().push_back($2);
1833     $$ = $1;
1834   }
1835   | /* empty */ {
1836     $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
1837
1838     // Make sure to move the basic block to the correct location in the
1839     // function, instead of leaving it inserted wherever it was first
1840     // referenced.
1841     Function::BasicBlockListType &BBL = 
1842       CurFun.CurrentFunction->getBasicBlockList();
1843     BBL.splice(BBL.end(), BBL, $$);
1844   }
1845   | LABELSTR {
1846     $$ = CurBB = getBBVal(ValID::create($1), true);
1847
1848     // Make sure to move the basic block to the correct location in the
1849     // function, instead of leaving it inserted wherever it was first
1850     // referenced.
1851     Function::BasicBlockListType &BBL = 
1852       CurFun.CurrentFunction->getBasicBlockList();
1853     BBL.splice(BBL.end(), BBL, $$);
1854   };
1855
1856 BBTerminatorInst : RET ResolvedVal {              // Return with a result...
1857     $$ = new ReturnInst($2);
1858   }
1859   | RET VOID {                                       // Return with no result...
1860     $$ = new ReturnInst();
1861   }
1862   | BR LABEL ValueRef {                         // Unconditional Branch...
1863     $$ = new BranchInst(getBBVal($3));
1864   }                                                  // Conditional Branch...
1865   | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {  
1866     $$ = new BranchInst(getBBVal($6), getBBVal($9), getVal(Type::BoolTy, $3));
1867   }
1868   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1869     SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6), $8->size());
1870     $$ = S;
1871
1872     std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
1873       E = $8->end();
1874     for (; I != E; ++I) {
1875       if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
1876           S->addCase(CI, I->second);
1877       else
1878         ThrowException("Switch case is constant, but not a simple integer!");
1879     }
1880     delete $8;
1881   }
1882   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
1883     SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6), 0);
1884     $$ = S;
1885   }
1886   | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
1887     TO LABEL ValueRef UNWIND LABEL ValueRef {
1888     const PointerType *PFTy;
1889     const FunctionType *Ty;
1890
1891     if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
1892         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1893       // Pull out the types of all of the arguments...
1894       std::vector<const Type*> ParamTypes;
1895       if ($6) {
1896         for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
1897              I != E; ++I)
1898           ParamTypes.push_back((*I)->getType());
1899       }
1900
1901       bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1902       if (isVarArg) ParamTypes.pop_back();
1903
1904       Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
1905       PFTy = PointerType::get(Ty);
1906     }
1907
1908     Value *V = getVal(PFTy, $4);   // Get the function we're calling...
1909
1910     BasicBlock *Normal = getBBVal($10);
1911     BasicBlock *Except = getBBVal($13);
1912
1913     // Create the call node...
1914     if (!$6) {                                   // Has no arguments?
1915       $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
1916     } else {                                     // Has arguments?
1917       // Loop through FunctionType's arguments and ensure they are specified
1918       // correctly!
1919       //
1920       FunctionType::param_iterator I = Ty->param_begin();
1921       FunctionType::param_iterator E = Ty->param_end();
1922       std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
1923
1924       for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1925         if ((*ArgI)->getType() != *I)
1926           ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1927                          (*I)->getDescription() + "'!");
1928
1929       if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1930         ThrowException("Invalid number of parameters detected!");
1931
1932       $$ = new InvokeInst(V, Normal, Except, *$6);
1933     }
1934     cast<InvokeInst>($$)->setCallingConv($2);
1935   
1936     delete $3;
1937     delete $6;
1938   }
1939   | UNWIND {
1940     $$ = new UnwindInst();
1941   }
1942   | UNREACHABLE {
1943     $$ = new UnreachableInst();
1944   };
1945
1946
1947
1948 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1949     $$ = $1;
1950     Constant *V = cast<Constant>(getValNonImprovising($2, $3));
1951     if (V == 0)
1952       ThrowException("May only switch on a constant pool value!");
1953
1954     $$->push_back(std::make_pair(V, getBBVal($6)));
1955   }
1956   | IntType ConstValueRef ',' LABEL ValueRef {
1957     $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
1958     Constant *V = cast<Constant>(getValNonImprovising($1, $2));
1959
1960     if (V == 0)
1961       ThrowException("May only switch on a constant pool value!");
1962
1963     $$->push_back(std::make_pair(V, getBBVal($5)));
1964   };
1965
1966 Inst : OptAssign InstVal {
1967   // Is this definition named?? if so, assign the name...
1968   setValueName($2, $1);
1969   InsertValue($2);
1970   $$ = $2;
1971 };
1972
1973 PHIList : Types '[' ValueRef ',' ValueRef ']' {    // Used for PHI nodes
1974     $$ = new std::list<std::pair<Value*, BasicBlock*> >();
1975     $$->push_back(std::make_pair(getVal(*$1, $3), getBBVal($5)));
1976     delete $1;
1977   }
1978   | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1979     $$ = $1;
1980     $1->push_back(std::make_pair(getVal($1->front().first->getType(), $4),
1981                                  getBBVal($6)));
1982   };
1983
1984
1985 ValueRefList : ResolvedVal {    // Used for call statements, and memory insts...
1986     $$ = new std::vector<Value*>();
1987     $$->push_back($1);
1988   }
1989   | ValueRefList ',' ResolvedVal {
1990     $$ = $1;
1991     $1->push_back($3);
1992   };
1993
1994 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1995 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
1996
1997 OptTailCall : TAIL CALL {
1998     $$ = true;
1999   }
2000   | CALL {
2001     $$ = false;
2002   };
2003
2004
2005
2006 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2007     if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() && 
2008         !isa<PackedType>((*$2).get()))
2009       ThrowException(
2010         "Arithmetic operator requires integer, FP, or packed operands!");
2011     if (isa<PackedType>((*$2).get()) && $1 == Instruction::Rem)
2012       ThrowException("Rem not supported on packed types!");
2013     $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
2014     if ($$ == 0)
2015       ThrowException("binary operator returned null!");
2016     delete $2;
2017   }
2018   | LogicalOps Types ValueRef ',' ValueRef {
2019     if (!(*$2)->isIntegral())
2020       ThrowException("Logical operator requires integral operands!");
2021     $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
2022     if ($$ == 0)
2023       ThrowException("binary operator returned null!");
2024     delete $2;
2025   }
2026   | SetCondOps Types ValueRef ',' ValueRef {
2027     if(isa<PackedType>((*$2).get())) {
2028       ThrowException(
2029         "PackedTypes currently not supported in setcc instructions!");
2030     }
2031     $$ = new SetCondInst($1, getVal(*$2, $3), getVal(*$2, $5));
2032     if ($$ == 0)
2033       ThrowException("binary operator returned null!");
2034     delete $2;
2035   }
2036   | NOT ResolvedVal {
2037     std::cerr << "WARNING: Use of eliminated 'not' instruction:"
2038               << " Replacing with 'xor'.\n";
2039
2040     Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
2041     if (Ones == 0)
2042       ThrowException("Expected integral type for not instruction!");
2043
2044     $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
2045     if ($$ == 0)
2046       ThrowException("Could not create a xor instruction!");
2047   }
2048   | ShiftOps ResolvedVal ',' ResolvedVal {
2049     if ($4->getType() != Type::UByteTy)
2050       ThrowException("Shift amount must be ubyte!");
2051     if (!$2->getType()->isInteger())
2052       ThrowException("Shift constant expression requires integer operand!");
2053     $$ = new ShiftInst($1, $2, $4);
2054   }
2055   | CAST ResolvedVal TO Types {
2056     if (!$4->get()->isFirstClassType())
2057       ThrowException("cast instruction to a non-primitive type: '" +
2058                      $4->get()->getDescription() + "'!");
2059     $$ = new CastInst($2, *$4);
2060     delete $4;
2061   }
2062   | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2063     if ($2->getType() != Type::BoolTy)
2064       ThrowException("select condition must be boolean!");
2065     if ($4->getType() != $6->getType())
2066       ThrowException("select value types should match!");
2067     $$ = new SelectInst($2, $4, $6);
2068   }
2069   | VAARG ResolvedVal ',' Types {
2070     NewVarArgs = true;
2071     $$ = new VAArgInst($2, *$4);
2072     delete $4;
2073   }
2074   | VAARG_old ResolvedVal ',' Types {
2075     ObsoleteVarArgs = true;
2076     const Type* ArgTy = $2->getType();
2077     Function* NF = CurModule.CurrentModule->
2078       getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0);
2079
2080     //b = vaarg a, t -> 
2081     //foo = alloca 1 of t
2082     //bar = vacopy a 
2083     //store bar -> foo
2084     //b = vaarg foo, t
2085     AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
2086     CurBB->getInstList().push_back(foo);
2087     CallInst* bar = new CallInst(NF, $2);
2088     CurBB->getInstList().push_back(bar);
2089     CurBB->getInstList().push_back(new StoreInst(bar, foo));
2090     $$ = new VAArgInst(foo, *$4);
2091     delete $4;
2092   }
2093   | VANEXT_old ResolvedVal ',' Types {
2094     ObsoleteVarArgs = true;
2095     const Type* ArgTy = $2->getType();
2096     Function* NF = CurModule.CurrentModule->
2097       getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0);
2098
2099     //b = vanext a, t ->
2100     //foo = alloca 1 of t
2101     //bar = vacopy a
2102     //store bar -> foo
2103     //tmp = vaarg foo, t
2104     //b = load foo
2105     AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
2106     CurBB->getInstList().push_back(foo);
2107     CallInst* bar = new CallInst(NF, $2);
2108     CurBB->getInstList().push_back(bar);
2109     CurBB->getInstList().push_back(new StoreInst(bar, foo));
2110     Instruction* tmp = new VAArgInst(foo, *$4);
2111     CurBB->getInstList().push_back(tmp);
2112     $$ = new LoadInst(foo);
2113     delete $4;
2114   }
2115   | PHI_TOK PHIList {
2116     const Type *Ty = $2->front().first->getType();
2117     if (!Ty->isFirstClassType())
2118       ThrowException("PHI node operands must be of first class type!");
2119     $$ = new PHINode(Ty);
2120     ((PHINode*)$$)->reserveOperandSpace($2->size());
2121     while ($2->begin() != $2->end()) {
2122       if ($2->front().first->getType() != Ty) 
2123         ThrowException("All elements of a PHI node must be of the same type!");
2124       cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2125       $2->pop_front();
2126     }
2127     delete $2;  // Free the list...
2128   }
2129   | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')'  {
2130     const PointerType *PFTy;
2131     const FunctionType *Ty;
2132
2133     if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2134         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2135       // Pull out the types of all of the arguments...
2136       std::vector<const Type*> ParamTypes;
2137       if ($6) {
2138         for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
2139              I != E; ++I)
2140           ParamTypes.push_back((*I)->getType());
2141       }
2142
2143       bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2144       if (isVarArg) ParamTypes.pop_back();
2145
2146       if (!(*$3)->isFirstClassType() && *$3 != Type::VoidTy)
2147         ThrowException("LLVM functions cannot return aggregate types!");
2148
2149       Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
2150       PFTy = PointerType::get(Ty);
2151     }
2152
2153     Value *V = getVal(PFTy, $4);   // Get the function we're calling...
2154
2155     // Create the call node...
2156     if (!$6) {                                   // Has no arguments?
2157       // Make sure no arguments is a good thing!
2158       if (Ty->getNumParams() != 0)
2159         ThrowException("No arguments passed to a function that "
2160                        "expects arguments!");
2161
2162       $$ = new CallInst(V, std::vector<Value*>());
2163     } else {                                     // Has arguments?
2164       // Loop through FunctionType's arguments and ensure they are specified
2165       // correctly!
2166       //
2167       FunctionType::param_iterator I = Ty->param_begin();
2168       FunctionType::param_iterator E = Ty->param_end();
2169       std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
2170
2171       for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2172         if ((*ArgI)->getType() != *I)
2173           ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2174                          (*I)->getDescription() + "'!");
2175
2176       if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2177         ThrowException("Invalid number of parameters detected!");
2178
2179       $$ = new CallInst(V, *$6);
2180     }
2181     cast<CallInst>($$)->setTailCall($1);
2182     cast<CallInst>($$)->setCallingConv($2);
2183     delete $3;
2184     delete $6;
2185   }
2186   | MemoryInst {
2187     $$ = $1;
2188   };
2189
2190
2191 // IndexList - List of indices for GEP based instructions...
2192 IndexList : ',' ValueRefList { 
2193     $$ = $2; 
2194   } | /* empty */ { 
2195     $$ = new std::vector<Value*>(); 
2196   };
2197
2198 OptVolatile : VOLATILE {
2199     $$ = true;
2200   }
2201   | /* empty */ {
2202     $$ = false;
2203   };
2204
2205
2206
2207 MemoryInst : MALLOC Types {
2208     $$ = new MallocInst(*$2);
2209     delete $2;
2210   }
2211   | MALLOC Types ',' UINT ValueRef {
2212     $$ = new MallocInst(*$2, getVal($4, $5));
2213     delete $2;
2214   }
2215   | ALLOCA Types {
2216     $$ = new AllocaInst(*$2);
2217     delete $2;
2218   }
2219   | ALLOCA Types ',' UINT ValueRef {
2220     $$ = new AllocaInst(*$2, getVal($4, $5));
2221     delete $2;
2222   }
2223   | FREE ResolvedVal {
2224     if (!isa<PointerType>($2->getType()))
2225       ThrowException("Trying to free nonpointer type " + 
2226                      $2->getType()->getDescription() + "!");
2227     $$ = new FreeInst($2);
2228   }
2229
2230   | OptVolatile LOAD Types ValueRef {
2231     if (!isa<PointerType>($3->get()))
2232       ThrowException("Can't load from nonpointer type: " +
2233                      (*$3)->getDescription());
2234     if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
2235       ThrowException("Can't load from pointer of non-first-class type: " +
2236                      (*$3)->getDescription());
2237     $$ = new LoadInst(getVal(*$3, $4), "", $1);
2238     delete $3;
2239   }
2240   | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2241     const PointerType *PT = dyn_cast<PointerType>($5->get());
2242     if (!PT)
2243       ThrowException("Can't store to a nonpointer type: " +
2244                      (*$5)->getDescription());
2245     const Type *ElTy = PT->getElementType();
2246     if (ElTy != $3->getType())
2247       ThrowException("Can't store '" + $3->getType()->getDescription() +
2248                      "' into space of type '" + ElTy->getDescription() + "'!");
2249
2250     $$ = new StoreInst($3, getVal(*$5, $6), $1);
2251     delete $5;
2252   }
2253   | GETELEMENTPTR Types ValueRef IndexList {
2254     if (!isa<PointerType>($2->get()))
2255       ThrowException("getelementptr insn requires pointer operand!");
2256
2257     // LLVM 1.2 and earlier used ubyte struct indices.  Convert any ubyte struct
2258     // indices to uint struct indices for compatibility.
2259     generic_gep_type_iterator<std::vector<Value*>::iterator>
2260       GTI = gep_type_begin($2->get(), $4->begin(), $4->end()),
2261       GTE = gep_type_end($2->get(), $4->begin(), $4->end());
2262     for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
2263       if (isa<StructType>(*GTI))        // Only change struct indices
2264         if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
2265           if (CUI->getType() == Type::UByteTy)
2266             (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
2267
2268     if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2269       ThrowException("Invalid getelementptr indices for type '" +
2270                      (*$2)->getDescription()+ "'!");
2271     $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
2272     delete $2; delete $4;
2273   };
2274
2275
2276 %%
2277 int yyerror(const char *ErrorMsg) {
2278   std::string where 
2279     = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2280                   + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2281   std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2282   if (yychar == YYEMPTY || yychar == 0)
2283     errMsg += "end-of-file.";
2284   else
2285     errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2286   ThrowException(errMsg);
2287   return 0;
2288 }