For PR872:
[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 on 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 CSRETCC_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                  CSRETCC_TOK    { $$ = CallingConv::CSRet; } |
1058                  FASTCC_TOK     { $$ = CallingConv::Fast; } |
1059                  COLDCC_TOK     { $$ = CallingConv::Cold; } |
1060                  CC_TOK EUINT64VAL {
1061                    if ((unsigned)$2 != $2)
1062                      ThrowException("Calling conv too large!");
1063                    $$ = $2;
1064                  };
1065
1066 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1067 // a comma before it.
1068 OptAlign : /*empty*/        { $$ = 0; } |
1069            ALIGN EUINT64VAL {
1070   $$ = $2;
1071   if ($$ != 0 && !isPowerOf2_32($$))
1072     ThrowException("Alignment must be a power of two!");
1073 };
1074 OptCAlign : /*empty*/            { $$ = 0; } |
1075             ',' ALIGN EUINT64VAL {
1076   $$ = $3;
1077   if ($$ != 0 && !isPowerOf2_32($$))
1078     ThrowException("Alignment must be a power of two!");
1079 };
1080
1081
1082 SectionString : SECTION STRINGCONSTANT {
1083   for (unsigned i = 0, e = strlen($2); i != e; ++i)
1084     if ($2[i] == '"' || $2[i] == '\\')
1085       ThrowException("Invalid character in section name!");
1086   $$ = $2;
1087 };
1088
1089 OptSection : /*empty*/ { $$ = 0; } |
1090              SectionString { $$ = $1; };
1091
1092 // GlobalVarAttributes - Used to pass the attributes string on a global.  CurGV
1093 // is set to be the global we are processing.
1094 //
1095 GlobalVarAttributes : /* empty */ {} |
1096                      ',' GlobalVarAttribute GlobalVarAttributes {};
1097 GlobalVarAttribute : SectionString {
1098     CurGV->setSection($1);
1099     free($1);
1100   } 
1101   | ALIGN EUINT64VAL {
1102     if ($2 != 0 && !isPowerOf2_32($2))
1103       ThrowException("Alignment must be a power of two!");
1104     CurGV->setAlignment($2);
1105   };
1106
1107 //===----------------------------------------------------------------------===//
1108 // Types includes all predefined types... except void, because it can only be
1109 // used in specific contexts (function returning void for example).  To have
1110 // access to it, a user must explicitly use TypesV.
1111 //
1112
1113 // TypesV includes all of 'Types', but it also includes the void type.
1114 TypesV    : Types    | VOID { $$ = new PATypeHolder($1); };
1115 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
1116
1117 Types     : UpRTypes {
1118     if (!UpRefs.empty())
1119       ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
1120     $$ = $1;
1121   };
1122
1123
1124 // Derived types are added later...
1125 //
1126 PrimType : BOOL | SBYTE | UBYTE | SHORT  | USHORT | INT   | UINT ;
1127 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE   | LABEL;
1128 UpRTypes : OPAQUE {
1129     $$ = new PATypeHolder(OpaqueType::get());
1130   }
1131   | PrimType {
1132     $$ = new PATypeHolder($1);
1133   };
1134 UpRTypes : SymbolicValueRef {            // Named types are also simple types...
1135   $$ = new PATypeHolder(getTypeVal($1));
1136 };
1137
1138 // Include derived types in the Types production.
1139 //
1140 UpRTypes : '\\' EUINT64VAL {                   // Type UpReference
1141     if ($2 > (uint64_t)~0U) ThrowException("Value out of range!");
1142     OpaqueType *OT = OpaqueType::get();        // Use temporary placeholder
1143     UpRefs.push_back(UpRefRecord((unsigned)$2, OT));  // Add to vector...
1144     $$ = new PATypeHolder(OT);
1145     UR_OUT("New Upreference!\n");
1146   }
1147   | UpRTypesV '(' ArgTypeListI ')' {           // Function derived type?
1148     std::vector<const Type*> Params;
1149     for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1150            E = $3->end(); I != E; ++I)
1151       Params.push_back(*I);
1152     bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1153     if (isVarArg) Params.pop_back();
1154
1155     $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
1156     delete $3;      // Delete the argument list
1157     delete $1;      // Delete the return type handle
1158   }
1159   | '[' EUINT64VAL 'x' UpRTypes ']' {          // Sized array type?
1160     $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1161     delete $4;
1162   }
1163   | '<' EUINT64VAL 'x' UpRTypes '>' {          // Packed array type?
1164      const llvm::Type* ElemTy = $4->get();
1165      if ((unsigned)$2 != $2)
1166         ThrowException("Unsigned result not equal to signed result");
1167      if (!ElemTy->isPrimitiveType())
1168         ThrowException("Elemental type of a PackedType must be primitive");
1169      if (!isPowerOf2_32($2))
1170        ThrowException("Vector length should be a power of 2!");
1171      $$ = new PATypeHolder(HandleUpRefs(PackedType::get(*$4, (unsigned)$2)));
1172      delete $4;
1173   }
1174   | '{' TypeListI '}' {                        // Structure type?
1175     std::vector<const Type*> Elements;
1176     for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1177            E = $2->end(); I != E; ++I)
1178       Elements.push_back(*I);
1179
1180     $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1181     delete $2;
1182   }
1183   | '{' '}' {                                  // Empty structure type?
1184     $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1185   }
1186   | UpRTypes '*' {                             // Pointer type?
1187     $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1188     delete $1;
1189   };
1190
1191 // TypeList - Used for struct declarations and as a basis for function type 
1192 // declaration type lists
1193 //
1194 TypeListI : UpRTypes {
1195     $$ = new std::list<PATypeHolder>();
1196     $$->push_back(*$1); delete $1;
1197   }
1198   | TypeListI ',' UpRTypes {
1199     ($$=$1)->push_back(*$3); delete $3;
1200   };
1201
1202 // ArgTypeList - List of types for a function type declaration...
1203 ArgTypeListI : TypeListI
1204   | TypeListI ',' DOTDOTDOT {
1205     ($$=$1)->push_back(Type::VoidTy);
1206   }
1207   | DOTDOTDOT {
1208     ($$ = new std::list<PATypeHolder>())->push_back(Type::VoidTy);
1209   }
1210   | /*empty*/ {
1211     $$ = new std::list<PATypeHolder>();
1212   };
1213
1214 // ConstVal - The various declarations that go into the constant pool.  This
1215 // production is used ONLY to represent constants that show up AFTER a 'const',
1216 // 'constant' or 'global' token at global scope.  Constants that can be inlined
1217 // into other expressions (such as integers and constexprs) are handled by the
1218 // ResolvedVal, ValueRef and ConstValueRef productions.
1219 //
1220 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1221     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1222     if (ATy == 0)
1223       ThrowException("Cannot make array constant with type: '" + 
1224                      (*$1)->getDescription() + "'!");
1225     const Type *ETy = ATy->getElementType();
1226     int NumElements = ATy->getNumElements();
1227
1228     // Verify that we have the correct size...
1229     if (NumElements != -1 && NumElements != (int)$3->size())
1230       ThrowException("Type mismatch: constant sized array initialized with " +
1231                      utostr($3->size()) +  " arguments, but has size of " + 
1232                      itostr(NumElements) + "!");
1233
1234     // Verify all elements are correct type!
1235     for (unsigned i = 0; i < $3->size(); i++) {
1236       if (ETy != (*$3)[i]->getType())
1237         ThrowException("Element #" + utostr(i) + " is not of type '" + 
1238                        ETy->getDescription() +"' as required!\nIt is of type '"+
1239                        (*$3)[i]->getType()->getDescription() + "'.");
1240     }
1241
1242     $$ = ConstantArray::get(ATy, *$3);
1243     delete $1; delete $3;
1244   }
1245   | Types '[' ']' {
1246     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1247     if (ATy == 0)
1248       ThrowException("Cannot make array constant with type: '" + 
1249                      (*$1)->getDescription() + "'!");
1250
1251     int NumElements = ATy->getNumElements();
1252     if (NumElements != -1 && NumElements != 0) 
1253       ThrowException("Type mismatch: constant sized array initialized with 0"
1254                      " arguments, but has size of " + itostr(NumElements) +"!");
1255     $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1256     delete $1;
1257   }
1258   | Types 'c' STRINGCONSTANT {
1259     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1260     if (ATy == 0)
1261       ThrowException("Cannot make array constant with type: '" + 
1262                      (*$1)->getDescription() + "'!");
1263
1264     int NumElements = ATy->getNumElements();
1265     const Type *ETy = ATy->getElementType();
1266     char *EndStr = UnEscapeLexed($3, true);
1267     if (NumElements != -1 && NumElements != (EndStr-$3))
1268       ThrowException("Can't build string constant of size " + 
1269                      itostr((int)(EndStr-$3)) +
1270                      " when array has size " + itostr(NumElements) + "!");
1271     std::vector<Constant*> Vals;
1272     if (ETy == Type::SByteTy) {
1273       for (signed char *C = (signed char *)$3; C != (signed char *)EndStr; ++C)
1274         Vals.push_back(ConstantSInt::get(ETy, *C));
1275     } else if (ETy == Type::UByteTy) {
1276       for (unsigned char *C = (unsigned char *)$3; 
1277            C != (unsigned char*)EndStr; ++C)
1278         Vals.push_back(ConstantUInt::get(ETy, *C));
1279     } else {
1280       free($3);
1281       ThrowException("Cannot build string arrays of non byte sized elements!");
1282     }
1283     free($3);
1284     $$ = ConstantArray::get(ATy, Vals);
1285     delete $1;
1286   }
1287   | Types '<' ConstVector '>' { // Nonempty unsized arr
1288     const PackedType *PTy = dyn_cast<PackedType>($1->get());
1289     if (PTy == 0)
1290       ThrowException("Cannot make packed constant with type: '" + 
1291                      (*$1)->getDescription() + "'!");
1292     const Type *ETy = PTy->getElementType();
1293     int NumElements = PTy->getNumElements();
1294
1295     // Verify that we have the correct size...
1296     if (NumElements != -1 && NumElements != (int)$3->size())
1297       ThrowException("Type mismatch: constant sized packed initialized with " +
1298                      utostr($3->size()) +  " arguments, but has size of " + 
1299                      itostr(NumElements) + "!");
1300
1301     // Verify all elements are correct type!
1302     for (unsigned i = 0; i < $3->size(); i++) {
1303       if (ETy != (*$3)[i]->getType())
1304         ThrowException("Element #" + utostr(i) + " is not of type '" + 
1305            ETy->getDescription() +"' as required!\nIt is of type '"+
1306            (*$3)[i]->getType()->getDescription() + "'.");
1307     }
1308
1309     $$ = ConstantPacked::get(PTy, *$3);
1310     delete $1; delete $3;
1311   }
1312   | Types '{' ConstVector '}' {
1313     const StructType *STy = dyn_cast<StructType>($1->get());
1314     if (STy == 0)
1315       ThrowException("Cannot make struct constant with type: '" + 
1316                      (*$1)->getDescription() + "'!");
1317
1318     if ($3->size() != STy->getNumContainedTypes())
1319       ThrowException("Illegal number of initializers for structure type!");
1320
1321     // Check to ensure that constants are compatible with the type initializer!
1322     for (unsigned i = 0, e = $3->size(); i != e; ++i)
1323       if ((*$3)[i]->getType() != STy->getElementType(i))
1324         ThrowException("Expected type '" +
1325                        STy->getElementType(i)->getDescription() +
1326                        "' for element #" + utostr(i) +
1327                        " of structure initializer!");
1328
1329     $$ = ConstantStruct::get(STy, *$3);
1330     delete $1; delete $3;
1331   }
1332   | Types '{' '}' {
1333     const StructType *STy = dyn_cast<StructType>($1->get());
1334     if (STy == 0)
1335       ThrowException("Cannot make struct constant with type: '" + 
1336                      (*$1)->getDescription() + "'!");
1337
1338     if (STy->getNumContainedTypes() != 0)
1339       ThrowException("Illegal number of initializers for structure type!");
1340
1341     $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1342     delete $1;
1343   }
1344   | Types NULL_TOK {
1345     const PointerType *PTy = dyn_cast<PointerType>($1->get());
1346     if (PTy == 0)
1347       ThrowException("Cannot make null pointer constant with type: '" + 
1348                      (*$1)->getDescription() + "'!");
1349
1350     $$ = ConstantPointerNull::get(PTy);
1351     delete $1;
1352   }
1353   | Types UNDEF {
1354     $$ = UndefValue::get($1->get());
1355     delete $1;
1356   }
1357   | Types SymbolicValueRef {
1358     const PointerType *Ty = dyn_cast<PointerType>($1->get());
1359     if (Ty == 0)
1360       ThrowException("Global const reference must be a pointer type!");
1361
1362     // ConstExprs can exist in the body of a function, thus creating
1363     // GlobalValues whenever they refer to a variable.  Because we are in
1364     // the context of a function, getValNonImprovising will search the functions
1365     // symbol table instead of the module symbol table for the global symbol,
1366     // which throws things all off.  To get around this, we just tell
1367     // getValNonImprovising that we are at global scope here.
1368     //
1369     Function *SavedCurFn = CurFun.CurrentFunction;
1370     CurFun.CurrentFunction = 0;
1371
1372     Value *V = getValNonImprovising(Ty, $2);
1373
1374     CurFun.CurrentFunction = SavedCurFn;
1375
1376     // If this is an initializer for a constant pointer, which is referencing a
1377     // (currently) undefined variable, create a stub now that shall be replaced
1378     // in the future with the right type of variable.
1379     //
1380     if (V == 0) {
1381       assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1382       const PointerType *PT = cast<PointerType>(Ty);
1383
1384       // First check to see if the forward references value is already created!
1385       PerModuleInfo::GlobalRefsType::iterator I =
1386         CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1387     
1388       if (I != CurModule.GlobalRefs.end()) {
1389         V = I->second;             // Placeholder already exists, use it...
1390         $2.destroy();
1391       } else {
1392         std::string Name;
1393         if ($2.Type == ValID::NameVal) Name = $2.Name;
1394
1395         // Create the forward referenced global.
1396         GlobalValue *GV;
1397         if (const FunctionType *FTy = 
1398                  dyn_cast<FunctionType>(PT->getElementType())) {
1399           GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1400                             CurModule.CurrentModule);
1401         } else {
1402           GV = new GlobalVariable(PT->getElementType(), false,
1403                                   GlobalValue::ExternalLinkage, 0,
1404                                   Name, CurModule.CurrentModule);
1405         }
1406
1407         // Keep track of the fact that we have a forward ref to recycle it
1408         CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1409         V = GV;
1410       }
1411     }
1412
1413     $$ = cast<GlobalValue>(V);
1414     delete $1;            // Free the type handle
1415   }
1416   | Types ConstExpr {
1417     if ($1->get() != $2->getType())
1418       ThrowException("Mismatched types for constant expression!");
1419     $$ = $2;
1420     delete $1;
1421   }
1422   | Types ZEROINITIALIZER {
1423     const Type *Ty = $1->get();
1424     if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1425       ThrowException("Cannot create a null initialized value of this type!");
1426     $$ = Constant::getNullValue(Ty);
1427     delete $1;
1428   };
1429
1430 ConstVal : SIntType EINT64VAL {      // integral constants
1431     if (!ConstantSInt::isValueValidForType($1, $2))
1432       ThrowException("Constant value doesn't fit in type!");
1433     $$ = ConstantSInt::get($1, $2);
1434   }
1435   | UIntType EUINT64VAL {            // integral constants
1436     if (!ConstantUInt::isValueValidForType($1, $2))
1437       ThrowException("Constant value doesn't fit in type!");
1438     $$ = ConstantUInt::get($1, $2);
1439   }
1440   | BOOL TRUETOK {                      // Boolean constants
1441     $$ = ConstantBool::True;
1442   }
1443   | BOOL FALSETOK {                     // Boolean constants
1444     $$ = ConstantBool::False;
1445   }
1446   | FPType FPVAL {                   // Float & Double constants
1447     if (!ConstantFP::isValueValidForType($1, $2))
1448       ThrowException("Floating point constant invalid for type!!");
1449     $$ = ConstantFP::get($1, $2);
1450   };
1451
1452
1453 ConstExpr: CAST '(' ConstVal TO Types ')' {
1454     if (!$3->getType()->isFirstClassType())
1455       ThrowException("cast constant expression from a non-primitive type: '" +
1456                      $3->getType()->getDescription() + "'!");
1457     if (!$5->get()->isFirstClassType())
1458       ThrowException("cast constant expression to a non-primitive type: '" +
1459                      $5->get()->getDescription() + "'!");
1460     $$ = ConstantExpr::getCast($3, $5->get());
1461     delete $5;
1462   }
1463   | GETELEMENTPTR '(' ConstVal IndexList ')' {
1464     if (!isa<PointerType>($3->getType()))
1465       ThrowException("GetElementPtr requires a pointer operand!");
1466
1467     // LLVM 1.2 and earlier used ubyte struct indices.  Convert any ubyte struct
1468     // indices to uint struct indices for compatibility.
1469     generic_gep_type_iterator<std::vector<Value*>::iterator>
1470       GTI = gep_type_begin($3->getType(), $4->begin(), $4->end()),
1471       GTE = gep_type_end($3->getType(), $4->begin(), $4->end());
1472     for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
1473       if (isa<StructType>(*GTI))        // Only change struct indices
1474         if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
1475           if (CUI->getType() == Type::UByteTy)
1476             (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
1477
1478     const Type *IdxTy =
1479       GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1480     if (!IdxTy)
1481       ThrowException("Index list invalid for constant getelementptr!");
1482
1483     std::vector<Constant*> IdxVec;
1484     for (unsigned i = 0, e = $4->size(); i != e; ++i)
1485       if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1486         IdxVec.push_back(C);
1487       else
1488         ThrowException("Indices to constant getelementptr must be constants!");
1489
1490     delete $4;
1491
1492     $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1493   }
1494   | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1495     if ($3->getType() != Type::BoolTy)
1496       ThrowException("Select condition must be of boolean type!");
1497     if ($5->getType() != $7->getType())
1498       ThrowException("Select operand types must match!");
1499     $$ = ConstantExpr::getSelect($3, $5, $7);
1500   }
1501   | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1502     if ($3->getType() != $5->getType())
1503       ThrowException("Binary operator types must match!");
1504     // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
1505     // To retain backward compatibility with these early compilers, we emit a
1506     // cast to the appropriate integer type automatically if we are in the
1507     // broken case.  See PR424 for more information.
1508     if (!isa<PointerType>($3->getType())) {
1509       $$ = ConstantExpr::get($1, $3, $5);
1510     } else {
1511       const Type *IntPtrTy = 0;
1512       switch (CurModule.CurrentModule->getPointerSize()) {
1513       case Module::Pointer32: IntPtrTy = Type::IntTy; break;
1514       case Module::Pointer64: IntPtrTy = Type::LongTy; break;
1515       default: ThrowException("invalid pointer binary constant expr!");
1516       }
1517       $$ = ConstantExpr::get($1, ConstantExpr::getCast($3, IntPtrTy),
1518                              ConstantExpr::getCast($5, IntPtrTy));
1519       $$ = ConstantExpr::getCast($$, $3->getType());
1520     }
1521   }
1522   | LogicalOps '(' ConstVal ',' ConstVal ')' {
1523     if ($3->getType() != $5->getType())
1524       ThrowException("Logical operator types must match!");
1525     if (!$3->getType()->isIntegral()) {
1526       if (!isa<PackedType>($3->getType()) || 
1527           !cast<PackedType>($3->getType())->getElementType()->isIntegral())
1528         ThrowException("Logical operator requires integral operands!");
1529     }
1530     $$ = ConstantExpr::get($1, $3, $5);
1531   }
1532   | SetCondOps '(' ConstVal ',' ConstVal ')' {
1533     if ($3->getType() != $5->getType())
1534       ThrowException("setcc operand types must match!");
1535     $$ = ConstantExpr::get($1, $3, $5);
1536   }
1537   | ShiftOps '(' ConstVal ',' ConstVal ')' {
1538     if ($5->getType() != Type::UByteTy)
1539       ThrowException("Shift count for shift constant must be unsigned byte!");
1540     if (!$3->getType()->isInteger())
1541       ThrowException("Shift constant expression requires integer operand!");
1542     $$ = ConstantExpr::get($1, $3, $5);
1543   }
1544   | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1545     if (!ExtractElementInst::isValidOperands($3, $5))
1546       ThrowException("Invalid extractelement operands!");
1547     $$ = ConstantExpr::getExtractElement($3, $5);
1548   }
1549   | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1550     if (!InsertElementInst::isValidOperands($3, $5, $7))
1551       ThrowException("Invalid insertelement operands!");
1552     $$ = ConstantExpr::getInsertElement($3, $5, $7);
1553   }
1554   | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1555     if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1556       ThrowException("Invalid shufflevector operands!");
1557     $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1558   };
1559
1560
1561 // ConstVector - A list of comma separated constants.
1562 ConstVector : ConstVector ',' ConstVal {
1563     ($$ = $1)->push_back($3);
1564   }
1565   | ConstVal {
1566     $$ = new std::vector<Constant*>();
1567     $$->push_back($1);
1568   };
1569
1570
1571 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1572 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1573
1574
1575 //===----------------------------------------------------------------------===//
1576 //                             Rules to match Modules
1577 //===----------------------------------------------------------------------===//
1578
1579 // Module rule: Capture the result of parsing the whole file into a result
1580 // variable...
1581 //
1582 Module : FunctionList {
1583   $$ = ParserResult = $1;
1584   CurModule.ModuleDone();
1585 };
1586
1587 // FunctionList - A list of functions, preceeded by a constant pool.
1588 //
1589 FunctionList : FunctionList Function {
1590     $$ = $1;
1591     CurFun.FunctionDone();
1592   } 
1593   | FunctionList FunctionProto {
1594     $$ = $1;
1595   }
1596   | FunctionList MODULE ASM_TOK AsmBlock {
1597     $$ = $1;
1598   }  
1599   | FunctionList IMPLEMENTATION {
1600     $$ = $1;
1601   }
1602   | ConstPool {
1603     $$ = CurModule.CurrentModule;
1604     // Emit an error if there are any unresolved types left.
1605     if (!CurModule.LateResolveTypes.empty()) {
1606       const ValID &DID = CurModule.LateResolveTypes.begin()->first;
1607       if (DID.Type == ValID::NameVal)
1608         ThrowException("Reference to an undefined type: '"+DID.getName() + "'");
1609       else
1610         ThrowException("Reference to an undefined type: #" + itostr(DID.Num));
1611     }
1612   };
1613
1614 // ConstPool - Constants with optional names assigned to them.
1615 ConstPool : ConstPool OptAssign TYPE TypesV {
1616     // Eagerly resolve types.  This is not an optimization, this is a
1617     // requirement that is due to the fact that we could have this:
1618     //
1619     // %list = type { %list * }
1620     // %list = type { %list * }    ; repeated type decl
1621     //
1622     // If types are not resolved eagerly, then the two types will not be
1623     // determined to be the same type!
1624     //
1625     ResolveTypeTo($2, *$4);
1626
1627     if (!setTypeName(*$4, $2) && !$2) {
1628       // If this is a named type that is not a redefinition, add it to the slot
1629       // table.
1630       CurModule.Types.push_back(*$4);
1631     }
1632
1633     delete $4;
1634   }
1635   | ConstPool FunctionProto {       // Function prototypes can be in const pool
1636   }
1637   | ConstPool MODULE ASM_TOK AsmBlock {  // Asm blocks can be in the const pool
1638   }
1639   | ConstPool OptAssign OptLinkage GlobalType ConstVal {
1640     if ($5 == 0) ThrowException("Global value initializer is not a constant!");
1641     CurGV = ParseGlobalVariable($2, $3, $4, $5->getType(), $5);
1642                                                        } GlobalVarAttributes {
1643     CurGV = 0;
1644   }
1645   | ConstPool OptAssign EXTERNAL GlobalType Types {
1646     CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage,
1647                                              $4, *$5, 0);
1648     delete $5;
1649                                                    } GlobalVarAttributes {
1650     CurGV = 0;
1651   }
1652   | ConstPool TARGET TargetDefinition { 
1653   }
1654   | ConstPool DEPLIBS '=' LibrariesDefinition {
1655   }
1656   | /* empty: end of list */ { 
1657   };
1658
1659
1660 AsmBlock : STRINGCONSTANT {
1661   const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
1662   char *EndStr = UnEscapeLexed($1, true);
1663   std::string NewAsm($1, EndStr);
1664   free($1);
1665
1666   if (AsmSoFar.empty())
1667     CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
1668   else
1669     CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
1670 };
1671
1672 BigOrLittle : BIG    { $$ = Module::BigEndian; };
1673 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1674
1675 TargetDefinition : ENDIAN '=' BigOrLittle {
1676     CurModule.CurrentModule->setEndianness($3);
1677   }
1678   | POINTERSIZE '=' EUINT64VAL {
1679     if ($3 == 32)
1680       CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1681     else if ($3 == 64)
1682       CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1683     else
1684       ThrowException("Invalid pointer size: '" + utostr($3) + "'!");
1685   }
1686   | TRIPLE '=' STRINGCONSTANT {
1687     CurModule.CurrentModule->setTargetTriple($3);
1688     free($3);
1689   };
1690
1691 LibrariesDefinition : '[' LibList ']';
1692
1693 LibList : LibList ',' STRINGCONSTANT {
1694           CurModule.CurrentModule->addLibrary($3);
1695           free($3);
1696         }
1697         | STRINGCONSTANT {
1698           CurModule.CurrentModule->addLibrary($1);
1699           free($1);
1700         }
1701         | /* empty: end of list */ {
1702         }
1703         ;
1704
1705 //===----------------------------------------------------------------------===//
1706 //                       Rules to match Function Headers
1707 //===----------------------------------------------------------------------===//
1708
1709 Name : VAR_ID | STRINGCONSTANT;
1710 OptName : Name | /*empty*/ { $$ = 0; };
1711
1712 ArgVal : Types OptName {
1713   if (*$1 == Type::VoidTy)
1714     ThrowException("void typed arguments are invalid!");
1715   $$ = new std::pair<PATypeHolder*, char*>($1, $2);
1716 };
1717
1718 ArgListH : ArgListH ',' ArgVal {
1719     $$ = $1;
1720     $1->push_back(*$3);
1721     delete $3;
1722   }
1723   | ArgVal {
1724     $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1725     $$->push_back(*$1);
1726     delete $1;
1727   };
1728
1729 ArgList : ArgListH {
1730     $$ = $1;
1731   }
1732   | ArgListH ',' DOTDOTDOT {
1733     $$ = $1;
1734     $$->push_back(std::pair<PATypeHolder*,
1735                             char*>(new PATypeHolder(Type::VoidTy), 0));
1736   }
1737   | DOTDOTDOT {
1738     $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1739     $$->push_back(std::make_pair(new PATypeHolder(Type::VoidTy), (char*)0));
1740   }
1741   | /* empty */ {
1742     $$ = 0;
1743   };
1744
1745 FunctionHeaderH : OptCallingConv TypesV Name '(' ArgList ')' 
1746                   OptSection OptAlign {
1747   UnEscapeLexed($3);
1748   std::string FunctionName($3);
1749   free($3);  // Free strdup'd memory!
1750   
1751   if (!(*$2)->isFirstClassType() && *$2 != Type::VoidTy)
1752     ThrowException("LLVM functions cannot return aggregate types!");
1753
1754   std::vector<const Type*> ParamTypeList;
1755   if ($5) {   // If there are arguments...
1756     for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
1757          I != $5->end(); ++I)
1758       ParamTypeList.push_back(I->first->get());
1759   }
1760
1761   bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1762   if (isVarArg) ParamTypeList.pop_back();
1763
1764   const FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
1765   const PointerType *PFT = PointerType::get(FT);
1766   delete $2;
1767
1768   ValID ID;
1769   if (!FunctionName.empty()) {
1770     ID = ValID::create((char*)FunctionName.c_str());
1771   } else {
1772     ID = ValID::create((int)CurModule.Values[PFT].size());
1773   }
1774
1775   Function *Fn = 0;
1776   // See if this function was forward referenced.  If so, recycle the object.
1777   if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
1778     // Move the function to the end of the list, from whereever it was 
1779     // previously inserted.
1780     Fn = cast<Function>(FWRef);
1781     CurModule.CurrentModule->getFunctionList().remove(Fn);
1782     CurModule.CurrentModule->getFunctionList().push_back(Fn);
1783   } else if (!FunctionName.empty() &&     // Merge with an earlier prototype?
1784              (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
1785     // If this is the case, either we need to be a forward decl, or it needs 
1786     // to be.
1787     if (!CurFun.isDeclare && !Fn->isExternal())
1788       ThrowException("Redefinition of function '" + FunctionName + "'!");
1789     
1790     // Make sure to strip off any argument names so we can't get conflicts.
1791     if (Fn->isExternal())
1792       for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
1793            AI != AE; ++AI)
1794         AI->setName("");
1795
1796   } else  {  // Not already defined?
1797     Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
1798                       CurModule.CurrentModule);
1799     InsertValue(Fn, CurModule.Values);
1800   }
1801
1802   CurFun.FunctionStart(Fn);
1803   Fn->setCallingConv($1);
1804   Fn->setAlignment($8);
1805   if ($7) {
1806     Fn->setSection($7);
1807     free($7);
1808   }
1809
1810   // Add all of the arguments we parsed to the function...
1811   if ($5) {                     // Is null if empty...
1812     if (isVarArg) {  // Nuke the last entry
1813       assert($5->back().first->get() == Type::VoidTy && $5->back().second == 0&&
1814              "Not a varargs marker!");
1815       delete $5->back().first;
1816       $5->pop_back();  // Delete the last entry
1817     }
1818     Function::arg_iterator ArgIt = Fn->arg_begin();
1819     for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
1820          I != $5->end(); ++I, ++ArgIt) {
1821       delete I->first;                          // Delete the typeholder...
1822
1823       setValueName(ArgIt, I->second);           // Insert arg into symtab...
1824       InsertValue(ArgIt);
1825     }
1826
1827     delete $5;                     // We're now done with the argument list
1828   }
1829 };
1830
1831 BEGIN : BEGINTOK | '{';                // Allow BEGIN or '{' to start a function
1832
1833 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
1834   $$ = CurFun.CurrentFunction;
1835
1836   // Make sure that we keep track of the linkage type even if there was a
1837   // previous "declare".
1838   $$->setLinkage($1);
1839 };
1840
1841 END : ENDTOK | '}';                    // Allow end of '}' to end a function
1842
1843 Function : BasicBlockList END {
1844   $$ = $1;
1845 };
1846
1847 FunctionProto : DECLARE { CurFun.isDeclare = true; } FunctionHeaderH {
1848   $$ = CurFun.CurrentFunction;
1849   CurFun.FunctionDone();
1850 };
1851
1852 //===----------------------------------------------------------------------===//
1853 //                        Rules to match Basic Blocks
1854 //===----------------------------------------------------------------------===//
1855
1856 OptSideEffect : /* empty */ {
1857     $$ = false;
1858   }
1859   | SIDEEFFECT {
1860     $$ = true;
1861   };
1862
1863 ConstValueRef : ESINT64VAL {    // A reference to a direct constant
1864     $$ = ValID::create($1);
1865   }
1866   | EUINT64VAL {
1867     $$ = ValID::create($1);
1868   }
1869   | FPVAL {                     // Perhaps it's an FP constant?
1870     $$ = ValID::create($1);
1871   }
1872   | TRUETOK {
1873     $$ = ValID::create(ConstantBool::True);
1874   } 
1875   | FALSETOK {
1876     $$ = ValID::create(ConstantBool::False);
1877   }
1878   | NULL_TOK {
1879     $$ = ValID::createNull();
1880   }
1881   | UNDEF {
1882     $$ = ValID::createUndef();
1883   }
1884   | ZEROINITIALIZER {     // A vector zero constant.
1885     $$ = ValID::createZeroInit();
1886   }
1887   | '<' ConstVector '>' { // Nonempty unsized packed vector
1888     const Type *ETy = (*$2)[0]->getType();
1889     int NumElements = $2->size(); 
1890     
1891     PackedType* pt = PackedType::get(ETy, NumElements);
1892     PATypeHolder* PTy = new PATypeHolder(
1893                                          HandleUpRefs(
1894                                             PackedType::get(
1895                                                 ETy, 
1896                                                 NumElements)
1897                                             )
1898                                          );
1899     
1900     // Verify all elements are correct type!
1901     for (unsigned i = 0; i < $2->size(); i++) {
1902       if (ETy != (*$2)[i]->getType())
1903         ThrowException("Element #" + utostr(i) + " is not of type '" + 
1904                      ETy->getDescription() +"' as required!\nIt is of type '" +
1905                      (*$2)[i]->getType()->getDescription() + "'.");
1906     }
1907
1908     $$ = ValID::create(ConstantPacked::get(pt, *$2));
1909     delete PTy; delete $2;
1910   }
1911   | ConstExpr {
1912     $$ = ValID::create($1);
1913   }
1914   | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
1915     char *End = UnEscapeLexed($3, true);
1916     std::string AsmStr = std::string($3, End);
1917     End = UnEscapeLexed($5, true);
1918     std::string Constraints = std::string($5, End);
1919     $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
1920     free($3);
1921     free($5);
1922   };
1923
1924 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1925 // another value.
1926 //
1927 SymbolicValueRef : INTVAL {  // Is it an integer reference...?
1928     $$ = ValID::create($1);
1929   }
1930   | Name {                   // Is it a named reference...?
1931     $$ = ValID::create($1);
1932   };
1933
1934 // ValueRef - A reference to a definition... either constant or symbolic
1935 ValueRef : SymbolicValueRef | ConstValueRef;
1936
1937
1938 // ResolvedVal - a <type> <value> pair.  This is used only in cases where the
1939 // type immediately preceeds the value reference, and allows complex constant
1940 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1941 ResolvedVal : Types ValueRef {
1942     $$ = getVal(*$1, $2); delete $1;
1943   };
1944
1945 BasicBlockList : BasicBlockList BasicBlock {
1946     $$ = $1;
1947   }
1948   | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks   
1949     $$ = $1;
1950   };
1951
1952
1953 // Basic blocks are terminated by branching instructions: 
1954 // br, br/cc, switch, ret
1955 //
1956 BasicBlock : InstructionList OptAssign BBTerminatorInst  {
1957     setValueName($3, $2);
1958     InsertValue($3);
1959
1960     $1->getInstList().push_back($3);
1961     InsertValue($1);
1962     $$ = $1;
1963   };
1964
1965 InstructionList : InstructionList Inst {
1966     $1->getInstList().push_back($2);
1967     $$ = $1;
1968   }
1969   | /* empty */ {
1970     $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
1971
1972     // Make sure to move the basic block to the correct location in the
1973     // function, instead of leaving it inserted wherever it was first
1974     // referenced.
1975     Function::BasicBlockListType &BBL = 
1976       CurFun.CurrentFunction->getBasicBlockList();
1977     BBL.splice(BBL.end(), BBL, $$);
1978   }
1979   | LABELSTR {
1980     $$ = CurBB = getBBVal(ValID::create($1), true);
1981
1982     // Make sure to move the basic block to the correct location in the
1983     // function, instead of leaving it inserted wherever it was first
1984     // referenced.
1985     Function::BasicBlockListType &BBL = 
1986       CurFun.CurrentFunction->getBasicBlockList();
1987     BBL.splice(BBL.end(), BBL, $$);
1988   };
1989
1990 BBTerminatorInst : RET ResolvedVal {              // Return with a result...
1991     $$ = new ReturnInst($2);
1992   }
1993   | RET VOID {                                       // Return with no result...
1994     $$ = new ReturnInst();
1995   }
1996   | BR LABEL ValueRef {                         // Unconditional Branch...
1997     $$ = new BranchInst(getBBVal($3));
1998   }                                                  // Conditional Branch...
1999   | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {  
2000     $$ = new BranchInst(getBBVal($6), getBBVal($9), getVal(Type::BoolTy, $3));
2001   }
2002   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2003     SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6), $8->size());
2004     $$ = S;
2005
2006     std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2007       E = $8->end();
2008     for (; I != E; ++I) {
2009       if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2010           S->addCase(CI, I->second);
2011       else
2012         ThrowException("Switch case is constant, but not a simple integer!");
2013     }
2014     delete $8;
2015   }
2016   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2017     SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6), 0);
2018     $$ = S;
2019   }
2020   | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
2021     TO LABEL ValueRef UNWIND LABEL ValueRef {
2022     const PointerType *PFTy;
2023     const FunctionType *Ty;
2024
2025     if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2026         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2027       // Pull out the types of all of the arguments...
2028       std::vector<const Type*> ParamTypes;
2029       if ($6) {
2030         for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
2031              I != E; ++I)
2032           ParamTypes.push_back((*I)->getType());
2033       }
2034
2035       bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2036       if (isVarArg) ParamTypes.pop_back();
2037
2038       Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
2039       PFTy = PointerType::get(Ty);
2040     }
2041
2042     Value *V = getVal(PFTy, $4);   // Get the function we're calling...
2043
2044     BasicBlock *Normal = getBBVal($10);
2045     BasicBlock *Except = getBBVal($13);
2046
2047     // Create the call node...
2048     if (!$6) {                                   // Has no arguments?
2049       $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
2050     } else {                                     // Has arguments?
2051       // Loop through FunctionType's arguments and ensure they are specified
2052       // correctly!
2053       //
2054       FunctionType::param_iterator I = Ty->param_begin();
2055       FunctionType::param_iterator E = Ty->param_end();
2056       std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
2057
2058       for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2059         if ((*ArgI)->getType() != *I)
2060           ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2061                          (*I)->getDescription() + "'!");
2062
2063       if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2064         ThrowException("Invalid number of parameters detected!");
2065
2066       $$ = new InvokeInst(V, Normal, Except, *$6);
2067     }
2068     cast<InvokeInst>($$)->setCallingConv($2);
2069   
2070     delete $3;
2071     delete $6;
2072   }
2073   | UNWIND {
2074     $$ = new UnwindInst();
2075   }
2076   | UNREACHABLE {
2077     $$ = new UnreachableInst();
2078   };
2079
2080
2081
2082 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2083     $$ = $1;
2084     Constant *V = cast<Constant>(getValNonImprovising($2, $3));
2085     if (V == 0)
2086       ThrowException("May only switch on a constant pool value!");
2087
2088     $$->push_back(std::make_pair(V, getBBVal($6)));
2089   }
2090   | IntType ConstValueRef ',' LABEL ValueRef {
2091     $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2092     Constant *V = cast<Constant>(getValNonImprovising($1, $2));
2093
2094     if (V == 0)
2095       ThrowException("May only switch on a constant pool value!");
2096
2097     $$->push_back(std::make_pair(V, getBBVal($5)));
2098   };
2099
2100 Inst : OptAssign InstVal {
2101   // Is this definition named?? if so, assign the name...
2102   setValueName($2, $1);
2103   InsertValue($2);
2104   $$ = $2;
2105 };
2106
2107 PHIList : Types '[' ValueRef ',' ValueRef ']' {    // Used for PHI nodes
2108     $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2109     $$->push_back(std::make_pair(getVal(*$1, $3), getBBVal($5)));
2110     delete $1;
2111   }
2112   | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2113     $$ = $1;
2114     $1->push_back(std::make_pair(getVal($1->front().first->getType(), $4),
2115                                  getBBVal($6)));
2116   };
2117
2118
2119 ValueRefList : ResolvedVal {    // Used for call statements, and memory insts...
2120     $$ = new std::vector<Value*>();
2121     $$->push_back($1);
2122   }
2123   | ValueRefList ',' ResolvedVal {
2124     $$ = $1;
2125     $1->push_back($3);
2126   };
2127
2128 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
2129 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
2130
2131 OptTailCall : TAIL CALL {
2132     $$ = true;
2133   }
2134   | CALL {
2135     $$ = false;
2136   };
2137
2138
2139
2140 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2141     if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() && 
2142         !isa<PackedType>((*$2).get()))
2143       ThrowException(
2144         "Arithmetic operator requires integer, FP, or packed operands!");
2145     if (isa<PackedType>((*$2).get()) && $1 == Instruction::Rem)
2146       ThrowException("Rem not supported on packed types!");
2147     $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
2148     if ($$ == 0)
2149       ThrowException("binary operator returned null!");
2150     delete $2;
2151   }
2152   | LogicalOps Types ValueRef ',' ValueRef {
2153     if (!(*$2)->isIntegral()) {
2154       if (!isa<PackedType>($2->get()) ||
2155           !cast<PackedType>($2->get())->getElementType()->isIntegral())
2156         ThrowException("Logical operator requires integral operands!");
2157     }
2158     $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
2159     if ($$ == 0)
2160       ThrowException("binary operator returned null!");
2161     delete $2;
2162   }
2163   | SetCondOps Types ValueRef ',' ValueRef {
2164     if(isa<PackedType>((*$2).get())) {
2165       ThrowException(
2166         "PackedTypes currently not supported in setcc instructions!");
2167     }
2168     $$ = new SetCondInst($1, getVal(*$2, $3), getVal(*$2, $5));
2169     if ($$ == 0)
2170       ThrowException("binary operator returned null!");
2171     delete $2;
2172   }
2173   | NOT ResolvedVal {
2174     std::cerr << "WARNING: Use of eliminated 'not' instruction:"
2175               << " Replacing with 'xor'.\n";
2176
2177     Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
2178     if (Ones == 0)
2179       ThrowException("Expected integral type for not instruction!");
2180
2181     $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
2182     if ($$ == 0)
2183       ThrowException("Could not create a xor instruction!");
2184   }
2185   | ShiftOps ResolvedVal ',' ResolvedVal {
2186     if ($4->getType() != Type::UByteTy)
2187       ThrowException("Shift amount must be ubyte!");
2188     if (!$2->getType()->isInteger())
2189       ThrowException("Shift constant expression requires integer operand!");
2190     $$ = new ShiftInst($1, $2, $4);
2191   }
2192   | CAST ResolvedVal TO Types {
2193     if (!$4->get()->isFirstClassType())
2194       ThrowException("cast instruction to a non-primitive type: '" +
2195                      $4->get()->getDescription() + "'!");
2196     $$ = new CastInst($2, *$4);
2197     delete $4;
2198   }
2199   | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2200     if ($2->getType() != Type::BoolTy)
2201       ThrowException("select condition must be boolean!");
2202     if ($4->getType() != $6->getType())
2203       ThrowException("select value types should match!");
2204     $$ = new SelectInst($2, $4, $6);
2205   }
2206   | VAARG ResolvedVal ',' Types {
2207     NewVarArgs = true;
2208     $$ = new VAArgInst($2, *$4);
2209     delete $4;
2210   }
2211   | VAARG_old ResolvedVal ',' Types {
2212     ObsoleteVarArgs = true;
2213     const Type* ArgTy = $2->getType();
2214     Function* NF = CurModule.CurrentModule->
2215       getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0);
2216
2217     //b = vaarg a, t -> 
2218     //foo = alloca 1 of t
2219     //bar = vacopy a 
2220     //store bar -> foo
2221     //b = vaarg foo, t
2222     AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
2223     CurBB->getInstList().push_back(foo);
2224     CallInst* bar = new CallInst(NF, $2);
2225     CurBB->getInstList().push_back(bar);
2226     CurBB->getInstList().push_back(new StoreInst(bar, foo));
2227     $$ = new VAArgInst(foo, *$4);
2228     delete $4;
2229   }
2230   | VANEXT_old ResolvedVal ',' Types {
2231     ObsoleteVarArgs = true;
2232     const Type* ArgTy = $2->getType();
2233     Function* NF = CurModule.CurrentModule->
2234       getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0);
2235
2236     //b = vanext a, t ->
2237     //foo = alloca 1 of t
2238     //bar = vacopy a
2239     //store bar -> foo
2240     //tmp = vaarg foo, t
2241     //b = load foo
2242     AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
2243     CurBB->getInstList().push_back(foo);
2244     CallInst* bar = new CallInst(NF, $2);
2245     CurBB->getInstList().push_back(bar);
2246     CurBB->getInstList().push_back(new StoreInst(bar, foo));
2247     Instruction* tmp = new VAArgInst(foo, *$4);
2248     CurBB->getInstList().push_back(tmp);
2249     $$ = new LoadInst(foo);
2250     delete $4;
2251   }
2252   | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2253     if (!ExtractElementInst::isValidOperands($2, $4))
2254       ThrowException("Invalid extractelement operands!");
2255     $$ = new ExtractElementInst($2, $4);
2256   }
2257   | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2258     if (!InsertElementInst::isValidOperands($2, $4, $6))
2259       ThrowException("Invalid insertelement operands!");
2260     $$ = new InsertElementInst($2, $4, $6);
2261   }
2262   | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2263     if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
2264       ThrowException("Invalid shufflevector operands!");
2265     $$ = new ShuffleVectorInst($2, $4, $6);
2266   }
2267   | PHI_TOK PHIList {
2268     const Type *Ty = $2->front().first->getType();
2269     if (!Ty->isFirstClassType())
2270       ThrowException("PHI node operands must be of first class type!");
2271     $$ = new PHINode(Ty);
2272     ((PHINode*)$$)->reserveOperandSpace($2->size());
2273     while ($2->begin() != $2->end()) {
2274       if ($2->front().first->getType() != Ty) 
2275         ThrowException("All elements of a PHI node must be of the same type!");
2276       cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2277       $2->pop_front();
2278     }
2279     delete $2;  // Free the list...
2280   }
2281   | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')'  {
2282     const PointerType *PFTy;
2283     const FunctionType *Ty;
2284
2285     if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2286         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2287       // Pull out the types of all of the arguments...
2288       std::vector<const Type*> ParamTypes;
2289       if ($6) {
2290         for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
2291              I != E; ++I)
2292           ParamTypes.push_back((*I)->getType());
2293       }
2294
2295       bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2296       if (isVarArg) ParamTypes.pop_back();
2297
2298       if (!(*$3)->isFirstClassType() && *$3 != Type::VoidTy)
2299         ThrowException("LLVM functions cannot return aggregate types!");
2300
2301       Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
2302       PFTy = PointerType::get(Ty);
2303     }
2304
2305     Value *V = getVal(PFTy, $4);   // Get the function we're calling...
2306
2307     // Create the call node...
2308     if (!$6) {                                   // Has no arguments?
2309       // Make sure no arguments is a good thing!
2310       if (Ty->getNumParams() != 0)
2311         ThrowException("No arguments passed to a function that "
2312                        "expects arguments!");
2313
2314       $$ = new CallInst(V, std::vector<Value*>());
2315     } else {                                     // Has arguments?
2316       // Loop through FunctionType's arguments and ensure they are specified
2317       // correctly!
2318       //
2319       FunctionType::param_iterator I = Ty->param_begin();
2320       FunctionType::param_iterator E = Ty->param_end();
2321       std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
2322
2323       for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2324         if ((*ArgI)->getType() != *I)
2325           ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2326                          (*I)->getDescription() + "'!");
2327
2328       if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2329         ThrowException("Invalid number of parameters detected!");
2330
2331       $$ = new CallInst(V, *$6);
2332     }
2333     cast<CallInst>($$)->setTailCall($1);
2334     cast<CallInst>($$)->setCallingConv($2);
2335     delete $3;
2336     delete $6;
2337   }
2338   | MemoryInst {
2339     $$ = $1;
2340   };
2341
2342
2343 // IndexList - List of indices for GEP based instructions...
2344 IndexList : ',' ValueRefList { 
2345     $$ = $2; 
2346   } | /* empty */ { 
2347     $$ = new std::vector<Value*>(); 
2348   };
2349
2350 OptVolatile : VOLATILE {
2351     $$ = true;
2352   }
2353   | /* empty */ {
2354     $$ = false;
2355   };
2356
2357
2358
2359 MemoryInst : MALLOC Types OptCAlign {
2360     $$ = new MallocInst(*$2, 0, $3);
2361     delete $2;
2362   }
2363   | MALLOC Types ',' UINT ValueRef OptCAlign {
2364     $$ = new MallocInst(*$2, getVal($4, $5), $6);
2365     delete $2;
2366   }
2367   | ALLOCA Types OptCAlign {
2368     $$ = new AllocaInst(*$2, 0, $3);
2369     delete $2;
2370   }
2371   | ALLOCA Types ',' UINT ValueRef OptCAlign {
2372     $$ = new AllocaInst(*$2, getVal($4, $5), $6);
2373     delete $2;
2374   }
2375   | FREE ResolvedVal {
2376     if (!isa<PointerType>($2->getType()))
2377       ThrowException("Trying to free nonpointer type " + 
2378                      $2->getType()->getDescription() + "!");
2379     $$ = new FreeInst($2);
2380   }
2381
2382   | OptVolatile LOAD Types ValueRef {
2383     if (!isa<PointerType>($3->get()))
2384       ThrowException("Can't load from nonpointer type: " +
2385                      (*$3)->getDescription());
2386     if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
2387       ThrowException("Can't load from pointer of non-first-class type: " +
2388                      (*$3)->getDescription());
2389     $$ = new LoadInst(getVal(*$3, $4), "", $1);
2390     delete $3;
2391   }
2392   | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2393     const PointerType *PT = dyn_cast<PointerType>($5->get());
2394     if (!PT)
2395       ThrowException("Can't store to a nonpointer type: " +
2396                      (*$5)->getDescription());
2397     const Type *ElTy = PT->getElementType();
2398     if (ElTy != $3->getType())
2399       ThrowException("Can't store '" + $3->getType()->getDescription() +
2400                      "' into space of type '" + ElTy->getDescription() + "'!");
2401
2402     $$ = new StoreInst($3, getVal(*$5, $6), $1);
2403     delete $5;
2404   }
2405   | GETELEMENTPTR Types ValueRef IndexList {
2406     if (!isa<PointerType>($2->get()))
2407       ThrowException("getelementptr insn requires pointer operand!");
2408
2409     // LLVM 1.2 and earlier used ubyte struct indices.  Convert any ubyte struct
2410     // indices to uint struct indices for compatibility.
2411     generic_gep_type_iterator<std::vector<Value*>::iterator>
2412       GTI = gep_type_begin($2->get(), $4->begin(), $4->end()),
2413       GTE = gep_type_end($2->get(), $4->begin(), $4->end());
2414     for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
2415       if (isa<StructType>(*GTI))        // Only change struct indices
2416         if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
2417           if (CUI->getType() == Type::UByteTy)
2418             (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
2419
2420     if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2421       ThrowException("Invalid getelementptr indices for type '" +
2422                      (*$2)->getDescription()+ "'!");
2423     $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
2424     delete $2; delete $4;
2425   };
2426
2427
2428 %%
2429 int yyerror(const char *ErrorMsg) {
2430   std::string where 
2431     = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2432                   + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2433   std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2434   if (yychar == YYEMPTY || yychar == 0)
2435     errMsg += "end-of-file.";
2436   else
2437     errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2438   ThrowException(errMsg);
2439   return 0;
2440 }