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