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