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