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