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