fix memleak in GetForwardRefForGlobal()
[oota-llvm.git] / lib / AsmParser / llvmAsmParser.y
1 //===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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/ValueSymbolTable.h"
21 #include "llvm/AutoUpgrade.h"
22 #include "llvm/Support/GetElementPtrTypeIterator.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Support/Streams.h"
28 #include <algorithm>
29 #include <list>
30 #include <map>
31 #include <utility>
32
33 // The following is a gross hack. In order to rid the libAsmParser library of
34 // exceptions, we have to have a way of getting the yyparse function to go into
35 // an error situation. So, whenever we want an error to occur, the GenerateError
36 // function (see bottom of file) sets TriggerError. Then, at the end of each
37 // production in the grammer we use CHECK_FOR_ERROR which will invoke YYERROR
38 // (a goto) to put YACC in error state. Furthermore, several calls to
39 // GenerateError are made from inside productions and they must simulate the
40 // previous exception behavior by exiting the production immediately. We have
41 // replaced these with the GEN_ERROR macro which calls GeneratError and then
42 // immediately invokes YYERROR. This would be so much cleaner if it was a
43 // recursive descent parser.
44 static bool TriggerError = false;
45 #define CHECK_FOR_ERROR { if (TriggerError) { TriggerError = false; YYABORT; } }
46 #define GEN_ERROR(msg) { GenerateError(msg); YYERROR; }
47
48 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
49 int yylex();                       // declaration" of xxx warnings.
50 int yyparse();
51 using namespace llvm;
52
53 static Module *ParserResult;
54
55 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
56 // relating to upreferences in the input stream.
57 //
58 //#define DEBUG_UPREFS 1
59 #ifdef DEBUG_UPREFS
60 #define UR_OUT(X) cerr << X
61 #else
62 #define UR_OUT(X)
63 #endif
64
65 #define YYERROR_VERBOSE 1
66
67 static GlobalVariable *CurGV;
68
69
70 // This contains info used when building the body of a function.  It is
71 // destroyed when the function is completed.
72 //
73 typedef std::vector<Value *> ValueList;           // Numbered defs
74
75 static void
76 ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers=0);
77
78 static struct PerModuleInfo {
79   Module *CurrentModule;
80   ValueList Values; // Module level numbered definitions
81   ValueList LateResolveValues;
82   std::vector<PATypeHolder>    Types;
83   std::map<ValID, PATypeHolder> LateResolveTypes;
84
85   /// PlaceHolderInfo - When temporary placeholder objects are created, remember
86   /// how they were referenced and on which line of the input they came from so
87   /// that we can resolve them later and print error messages as appropriate.
88   std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
89
90   // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
91   // references to global values.  Global values may be referenced before they
92   // are defined, and if so, the temporary object that they represent is held
93   // here.  This is used for forward references of GlobalValues.
94   //
95   typedef std::map<std::pair<const PointerType *,
96                              ValID>, GlobalValue*> GlobalRefsType;
97   GlobalRefsType GlobalRefs;
98
99   void ModuleDone() {
100     // If we could not resolve some functions at function compilation time
101     // (calls to functions before they are defined), resolve them now...  Types
102     // are resolved when the constant pool has been completely parsed.
103     //
104     ResolveDefinitions(LateResolveValues);
105     if (TriggerError)
106       return;
107
108     // Check to make sure that all global value forward references have been
109     // resolved!
110     //
111     if (!GlobalRefs.empty()) {
112       std::string UndefinedReferences = "Unresolved global references exist:\n";
113
114       for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
115            I != E; ++I) {
116         UndefinedReferences += "  " + I->first.first->getDescription() + " " +
117                                I->first.second.getName() + "\n";
118       }
119       GenerateError(UndefinedReferences);
120       return;
121     }
122
123     // Look for intrinsic functions and CallInst that need to be upgraded
124     for (Module::iterator FI = CurrentModule->begin(),
125          FE = CurrentModule->end(); FI != FE; )
126       UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
127
128     Values.clear();         // Clear out function local definitions
129     Types.clear();
130     CurrentModule = 0;
131   }
132
133   // GetForwardRefForGlobal - Check to see if there is a forward reference
134   // for this global.  If so, remove it from the GlobalRefs map and return it.
135   // If not, just return null.
136   GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
137     // Check to see if there is a forward reference to this global variable...
138     // if there is, eliminate it and patch the reference to use the new def'n.
139     GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
140     GlobalValue *Ret = 0;
141     if (I != GlobalRefs.end()) {
142       Ret = I->second;
143       I->first.second.destroy();
144       GlobalRefs.erase(I);
145     }
146     return Ret;
147   }
148
149   bool TypeIsUnresolved(PATypeHolder* PATy) {
150     // If it isn't abstract, its resolved
151     const Type* Ty = PATy->get();
152     if (!Ty->isAbstract())
153       return false;
154     // Traverse the type looking for abstract types. If it isn't abstract then
155     // we don't need to traverse that leg of the type.
156     std::vector<const Type*> WorkList, SeenList;
157     WorkList.push_back(Ty);
158     while (!WorkList.empty()) {
159       const Type* Ty = WorkList.back();
160       SeenList.push_back(Ty);
161       WorkList.pop_back();
162       if (const OpaqueType* OpTy = dyn_cast<OpaqueType>(Ty)) {
163         // Check to see if this is an unresolved type
164         std::map<ValID, PATypeHolder>::iterator I = LateResolveTypes.begin();
165         std::map<ValID, PATypeHolder>::iterator E = LateResolveTypes.end();
166         for ( ; I != E; ++I) {
167           if (I->second.get() == OpTy)
168             return true;
169         }
170       } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(Ty)) {
171         const Type* TheTy = SeqTy->getElementType();
172         if (TheTy->isAbstract() && TheTy != Ty) {
173           std::vector<const Type*>::iterator I = SeenList.begin(),
174                                              E = SeenList.end();
175           for ( ; I != E; ++I)
176             if (*I == TheTy)
177               break;
178           if (I == E)
179             WorkList.push_back(TheTy);
180         }
181       } else if (const StructType* StrTy = dyn_cast<StructType>(Ty)) {
182         for (unsigned i = 0; i < StrTy->getNumElements(); ++i) {
183           const Type* TheTy = StrTy->getElementType(i);
184           if (TheTy->isAbstract() && TheTy != Ty) {
185             std::vector<const Type*>::iterator I = SeenList.begin(),
186                                                E = SeenList.end();
187             for ( ; I != E; ++I)
188               if (*I == TheTy)
189                 break;
190             if (I == E)
191               WorkList.push_back(TheTy);
192           }
193         }
194       }
195     }
196     return false;
197   }
198 } CurModule;
199
200 static struct PerFunctionInfo {
201   Function *CurrentFunction;     // Pointer to current function being created
202
203   ValueList Values; // Keep track of #'d definitions
204   unsigned NextValNum;
205   ValueList LateResolveValues;
206   bool isDeclare;                   // Is this function a forward declararation?
207   GlobalValue::LinkageTypes Linkage; // Linkage for forward declaration.
208   GlobalValue::VisibilityTypes Visibility;
209
210   /// BBForwardRefs - When we see forward references to basic blocks, keep
211   /// track of them here.
212   std::map<ValID, BasicBlock*> BBForwardRefs;
213
214   inline PerFunctionInfo() {
215     CurrentFunction = 0;
216     isDeclare = false;
217     Linkage = GlobalValue::ExternalLinkage;
218     Visibility = GlobalValue::DefaultVisibility;
219   }
220
221   inline void FunctionStart(Function *M) {
222     CurrentFunction = M;
223     NextValNum = 0;
224   }
225
226   void FunctionDone() {
227     // Any forward referenced blocks left?
228     if (!BBForwardRefs.empty()) {
229       GenerateError("Undefined reference to label " +
230                      BBForwardRefs.begin()->second->getName());
231       return;
232     }
233
234     // Resolve all forward references now.
235     ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
236
237     Values.clear();         // Clear out function local definitions
238     BBForwardRefs.clear();
239     CurrentFunction = 0;
240     isDeclare = false;
241     Linkage = GlobalValue::ExternalLinkage;
242     Visibility = GlobalValue::DefaultVisibility;
243   }
244 } CurFun;  // Info for the current function...
245
246 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
247
248
249 //===----------------------------------------------------------------------===//
250 //               Code to handle definitions of all the types
251 //===----------------------------------------------------------------------===//
252
253 /// InsertValue - Insert a value into the value table.  If it is named, this
254 /// returns -1, otherwise it returns the slot number for the value.
255 static int InsertValue(Value *V, ValueList &ValueTab = CurFun.Values) {
256   // Things that have names or are void typed don't get slot numbers
257   if (V->hasName() || (V->getType() == Type::VoidTy))
258     return -1;
259
260   // In the case of function values, we have to allow for the forward reference
261   // of basic blocks, which are included in the numbering. Consequently, we keep
262   // track of the next insertion location with NextValNum. When a BB gets
263   // inserted, it could change the size of the CurFun.Values vector.
264   if (&ValueTab == &CurFun.Values) {
265     if (ValueTab.size() <= CurFun.NextValNum)
266       ValueTab.resize(CurFun.NextValNum+1);
267     ValueTab[CurFun.NextValNum++] = V;
268     return CurFun.NextValNum-1;
269   }
270   // For all other lists, its okay to just tack it on the back of the vector.
271   ValueTab.push_back(V);
272   return ValueTab.size()-1;
273 }
274
275 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
276   switch (D.Type) {
277   case ValID::LocalID:               // Is it a numbered definition?
278     // Module constants occupy the lowest numbered slots...
279     if (D.Num < CurModule.Types.size())
280       return CurModule.Types[D.Num];
281     break;
282   case ValID::LocalName:                 // Is it a named definition?
283     if (const Type *N = CurModule.CurrentModule->getTypeByName(D.getName())) {
284       D.destroy();  // Free old strdup'd memory...
285       return N;
286     }
287     break;
288   default:
289     GenerateError("Internal parser error: Invalid symbol type reference");
290     return 0;
291   }
292
293   // If we reached here, we referenced either a symbol that we don't know about
294   // or an id number that hasn't been read yet.  We may be referencing something
295   // forward, so just create an entry to be resolved later and get to it...
296   //
297   if (DoNotImprovise) return 0;  // Do we just want a null to be returned?
298
299
300   if (inFunctionScope()) {
301     if (D.Type == ValID::LocalName) {
302       GenerateError("Reference to an undefined type: '" + D.getName() + "'");
303       return 0;
304     } else {
305       GenerateError("Reference to an undefined type: #" + utostr(D.Num));
306       return 0;
307     }
308   }
309
310   std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
311   if (I != CurModule.LateResolveTypes.end()) {
312     D.destroy();
313     return I->second;
314   }
315
316   Type *Typ = OpaqueType::get();
317   CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
318   return Typ;
319  }
320
321 // getExistingVal - Look up the value specified by the provided type and
322 // the provided ValID.  If the value exists and has already been defined, return
323 // it.  Otherwise return null.
324 //
325 static Value *getExistingVal(const Type *Ty, const ValID &D) {
326   if (isa<FunctionType>(Ty)) {
327     GenerateError("Functions are not values and "
328                    "must be referenced as pointers");
329     return 0;
330   }
331
332   switch (D.Type) {
333   case ValID::LocalID: {                 // Is it a numbered definition?
334     // Check that the number is within bounds.
335     if (D.Num >= CurFun.Values.size())
336       return 0;
337     Value *Result = CurFun.Values[D.Num];
338     if (Ty != Result->getType()) {
339       GenerateError("Numbered value (%" + utostr(D.Num) + ") of type '" +
340                     Result->getType()->getDescription() + "' does not match "
341                     "expected type, '" + Ty->getDescription() + "'");
342       return 0;
343     }
344     return Result;
345   }
346   case ValID::GlobalID: {                 // Is it a numbered definition?
347     if (D.Num >= CurModule.Values.size())
348       return 0;
349     Value *Result = CurModule.Values[D.Num];
350     if (Ty != Result->getType()) {
351       GenerateError("Numbered value (@" + utostr(D.Num) + ") of type '" +
352                     Result->getType()->getDescription() + "' does not match "
353                     "expected type, '" + Ty->getDescription() + "'");
354       return 0;
355     }
356     return Result;
357   }
358
359   case ValID::LocalName: {                // Is it a named definition?
360     if (!inFunctionScope())
361       return 0;
362     ValueSymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
363     Value *N = SymTab.lookup(D.getName());
364     if (N == 0)
365       return 0;
366     if (N->getType() != Ty)
367       return 0;
368
369     D.destroy();  // Free old strdup'd memory...
370     return N;
371   }
372   case ValID::GlobalName: {                // Is it a named definition?
373     ValueSymbolTable &SymTab = CurModule.CurrentModule->getValueSymbolTable();
374     Value *N = SymTab.lookup(D.getName());
375     if (N == 0)
376       return 0;
377     if (N->getType() != Ty)
378       return 0;
379
380     D.destroy();  // Free old strdup'd memory...
381     return N;
382   }
383
384   // Check to make sure that "Ty" is an integral type, and that our
385   // value will fit into the specified type...
386   case ValID::ConstSIntVal:    // Is it a constant pool reference??
387     if (!isa<IntegerType>(Ty) ||
388         !ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
389       GenerateError("Signed integral constant '" +
390                      itostr(D.ConstPool64) + "' is invalid for type '" +
391                      Ty->getDescription() + "'");
392       return 0;
393     }
394     return ConstantInt::get(Ty, D.ConstPool64, true);
395
396   case ValID::ConstUIntVal:     // Is it an unsigned const pool reference?
397     if (isa<IntegerType>(Ty) &&
398         ConstantInt::isValueValidForType(Ty, D.UConstPool64))
399       return ConstantInt::get(Ty, D.UConstPool64);
400
401     if (!isa<IntegerType>(Ty) ||
402         !ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
403       GenerateError("Integral constant '" + utostr(D.UConstPool64) +
404                     "' is invalid or out of range for type '" +
405                     Ty->getDescription() + "'");
406       return 0;
407     }
408     // This is really a signed reference.  Transmogrify.
409     return ConstantInt::get(Ty, D.ConstPool64, true);
410
411   case ValID::ConstAPInt:     // Is it an unsigned const pool reference?
412     if (!isa<IntegerType>(Ty)) {
413       GenerateError("Integral constant '" + D.getName() +
414                     "' is invalid or out of range for type '" +
415                     Ty->getDescription() + "'");
416       return 0;
417     }
418
419     {
420       APSInt Tmp = *D.ConstPoolInt;
421       Tmp.extOrTrunc(Ty->getPrimitiveSizeInBits());
422       return ConstantInt::get(Tmp);
423     }
424
425   case ValID::ConstFPVal:        // Is it a floating point const pool reference?
426     if (!Ty->isFloatingPoint() ||
427         !ConstantFP::isValueValidForType(Ty, *D.ConstPoolFP)) {
428       GenerateError("FP constant invalid for type");
429       return 0;
430     }
431     // Lexer has no type info, so builds all float and double FP constants
432     // as double.  Fix this here.  Long double does not need this.
433     if (&D.ConstPoolFP->getSemantics() == &APFloat::IEEEdouble &&
434         Ty==Type::FloatTy) {
435       bool ignored;
436       D.ConstPoolFP->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
437                              &ignored);
438     }
439     return ConstantFP::get(*D.ConstPoolFP);
440
441   case ValID::ConstNullVal:      // Is it a null value?
442     if (!isa<PointerType>(Ty)) {
443       GenerateError("Cannot create a a non pointer null");
444       return 0;
445     }
446     return ConstantPointerNull::get(cast<PointerType>(Ty));
447
448   case ValID::ConstUndefVal:      // Is it an undef value?
449     return UndefValue::get(Ty);
450
451   case ValID::ConstZeroVal:      // Is it a zero value?
452     return Constant::getNullValue(Ty);
453
454   case ValID::ConstantVal:       // Fully resolved constant?
455     if (D.ConstantValue->getType() != Ty) {
456       GenerateError("Constant expression type different from required type");
457       return 0;
458     }
459     return D.ConstantValue;
460
461   case ValID::InlineAsmVal: {    // Inline asm expression
462     const PointerType *PTy = dyn_cast<PointerType>(Ty);
463     const FunctionType *FTy =
464       PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
465     if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
466       GenerateError("Invalid type for asm constraint string");
467       return 0;
468     }
469     InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
470                                    D.IAD->HasSideEffects);
471     D.destroy();   // Free InlineAsmDescriptor.
472     return IA;
473   }
474   default:
475     assert(0 && "Unhandled case!");
476     return 0;
477   }   // End of switch
478
479   assert(0 && "Unhandled case!");
480   return 0;
481 }
482
483 // getVal - This function is identical to getExistingVal, except that if a
484 // value is not already defined, it "improvises" by creating a placeholder var
485 // that looks and acts just like the requested variable.  When the value is
486 // defined later, all uses of the placeholder variable are replaced with the
487 // real thing.
488 //
489 static Value *getVal(const Type *Ty, const ValID &ID) {
490   if (Ty == Type::LabelTy) {
491     GenerateError("Cannot use a basic block here");
492     return 0;
493   }
494
495   // See if the value has already been defined.
496   Value *V = getExistingVal(Ty, ID);
497   if (V) return V;
498   if (TriggerError) return 0;
499
500   if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
501     GenerateError("Invalid use of a non-first-class type");
502     return 0;
503   }
504
505   // If we reached here, we referenced either a symbol that we don't know about
506   // or an id number that hasn't been read yet.  We may be referencing something
507   // forward, so just create an entry to be resolved later and get to it...
508   //
509   switch (ID.Type) {
510   case ValID::GlobalName:
511   case ValID::GlobalID: {
512    const PointerType *PTy = dyn_cast<PointerType>(Ty);
513    if (!PTy) {
514      GenerateError("Invalid type for reference to global" );
515      return 0;
516    }
517    const Type* ElTy = PTy->getElementType();
518    if (const FunctionType *FTy = dyn_cast<FunctionType>(ElTy))
519      V = Function::Create(FTy, GlobalValue::ExternalLinkage);
520    else
521      V = new GlobalVariable(ElTy, false, GlobalValue::ExternalLinkage, 0, "",
522                             (Module*)0, false, PTy->getAddressSpace());
523    break;
524   }
525   default:
526    V = new Argument(Ty);
527   }
528
529   // Remember where this forward reference came from.  FIXME, shouldn't we try
530   // to recycle these things??
531   CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
532                                                               LLLgetLineNo())));
533
534   if (inFunctionScope())
535     InsertValue(V, CurFun.LateResolveValues);
536   else
537     InsertValue(V, CurModule.LateResolveValues);
538   return V;
539 }
540
541 /// defineBBVal - This is a definition of a new basic block with the specified
542 /// identifier which must be the same as CurFun.NextValNum, if its numeric.
543 static BasicBlock *defineBBVal(const ValID &ID) {
544   assert(inFunctionScope() && "Can't get basic block at global scope!");
545
546   BasicBlock *BB = 0;
547
548   // First, see if this was forward referenced
549
550   std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
551   if (BBI != CurFun.BBForwardRefs.end()) {
552     BB = BBI->second;
553     // The forward declaration could have been inserted anywhere in the
554     // function: insert it into the correct place now.
555     CurFun.CurrentFunction->getBasicBlockList().remove(BB);
556     CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
557
558     // We're about to erase the entry, save the key so we can clean it up.
559     ValID Tmp = BBI->first;
560
561     // Erase the forward ref from the map as its no longer "forward"
562     CurFun.BBForwardRefs.erase(ID);
563
564     // The key has been removed from the map but so we don't want to leave
565     // strdup'd memory around so destroy it too.
566     Tmp.destroy();
567
568     // If its a numbered definition, bump the number and set the BB value.
569     if (ID.Type == ValID::LocalID) {
570       assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
571       InsertValue(BB);
572     }
573   } else {
574     // We haven't seen this BB before and its first mention is a definition.
575     // Just create it and return it.
576     std::string Name (ID.Type == ValID::LocalName ? ID.getName() : "");
577     BB = BasicBlock::Create(Name, CurFun.CurrentFunction);
578     if (ID.Type == ValID::LocalID) {
579       assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
580       InsertValue(BB);
581     }
582   }
583
584   ID.destroy();
585   return BB;
586 }
587
588 /// getBBVal - get an existing BB value or create a forward reference for it.
589 ///
590 static BasicBlock *getBBVal(const ValID &ID) {
591   assert(inFunctionScope() && "Can't get basic block at global scope!");
592
593   BasicBlock *BB =  0;
594
595   std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
596   if (BBI != CurFun.BBForwardRefs.end()) {
597     BB = BBI->second;
598   } if (ID.Type == ValID::LocalName) {
599     std::string Name = ID.getName();
600     Value *N = CurFun.CurrentFunction->getValueSymbolTable().lookup(Name);
601     if (N) {
602       if (N->getType()->getTypeID() == Type::LabelTyID)
603         BB = cast<BasicBlock>(N);
604       else
605         GenerateError("Reference to label '" + Name + "' is actually of type '"+
606           N->getType()->getDescription() + "'");
607     }
608   } else if (ID.Type == ValID::LocalID) {
609     if (ID.Num < CurFun.NextValNum && ID.Num < CurFun.Values.size()) {
610       if (CurFun.Values[ID.Num]->getType()->getTypeID() == Type::LabelTyID)
611         BB = cast<BasicBlock>(CurFun.Values[ID.Num]);
612       else
613         GenerateError("Reference to label '%" + utostr(ID.Num) +
614           "' is actually of type '"+
615           CurFun.Values[ID.Num]->getType()->getDescription() + "'");
616     }
617   } else {
618     GenerateError("Illegal label reference " + ID.getName());
619     return 0;
620   }
621
622   // If its already been defined, return it now.
623   if (BB) {
624     ID.destroy(); // Free strdup'd memory.
625     return BB;
626   }
627
628   // Otherwise, this block has not been seen before, create it.
629   std::string Name;
630   if (ID.Type == ValID::LocalName)
631     Name = ID.getName();
632   BB = BasicBlock::Create(Name, CurFun.CurrentFunction);
633
634   // Insert it in the forward refs map.
635   CurFun.BBForwardRefs[ID] = BB;
636
637   return BB;
638 }
639
640
641 //===----------------------------------------------------------------------===//
642 //              Code to handle forward references in instructions
643 //===----------------------------------------------------------------------===//
644 //
645 // This code handles the late binding needed with statements that reference
646 // values not defined yet... for example, a forward branch, or the PHI node for
647 // a loop body.
648 //
649 // This keeps a table (CurFun.LateResolveValues) of all such forward references
650 // and back patchs after we are done.
651 //
652
653 // ResolveDefinitions - If we could not resolve some defs at parsing
654 // time (forward branches, phi functions for loops, etc...) resolve the
655 // defs now...
656 //
657 static void
658 ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers) {
659   // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
660   while (!LateResolvers.empty()) {
661     Value *V = LateResolvers.back();
662     LateResolvers.pop_back();
663
664     std::map<Value*, std::pair<ValID, int> >::iterator PHI =
665       CurModule.PlaceHolderInfo.find(V);
666     assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
667
668     ValID &DID = PHI->second.first;
669
670     Value *TheRealValue = getExistingVal(V->getType(), DID);
671     if (TriggerError)
672       return;
673     if (TheRealValue) {
674       V->replaceAllUsesWith(TheRealValue);
675       delete V;
676       CurModule.PlaceHolderInfo.erase(PHI);
677     } else if (FutureLateResolvers) {
678       // Functions have their unresolved items forwarded to the module late
679       // resolver table
680       InsertValue(V, *FutureLateResolvers);
681     } else {
682       if (DID.Type == ValID::LocalName || DID.Type == ValID::GlobalName) {
683         GenerateError("Reference to an invalid definition: '" +DID.getName()+
684                        "' of type '" + V->getType()->getDescription() + "'",
685                        PHI->second.second);
686         return;
687       } else {
688         GenerateError("Reference to an invalid definition: #" +
689                        itostr(DID.Num) + " of type '" +
690                        V->getType()->getDescription() + "'",
691                        PHI->second.second);
692         return;
693       }
694     }
695   }
696   LateResolvers.clear();
697 }
698
699 // ResolveTypeTo - A brand new type was just declared.  This means that (if
700 // name is not null) things referencing Name can be resolved.  Otherwise, things
701 // refering to the number can be resolved.  Do this now.
702 //
703 static void ResolveTypeTo(std::string *Name, const Type *ToTy) {
704   ValID D;
705   if (Name)
706     D = ValID::createLocalName(*Name);
707   else
708     D = ValID::createLocalID(CurModule.Types.size());
709
710   std::map<ValID, PATypeHolder>::iterator I =
711     CurModule.LateResolveTypes.find(D);
712   if (I != CurModule.LateResolveTypes.end()) {
713     ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
714     I->first.destroy();
715     CurModule.LateResolveTypes.erase(I);
716   }
717   D.destroy();
718 }
719
720 // setValueName - Set the specified value to the name given.  The name may be
721 // null potentially, in which case this is a noop.  The string passed in is
722 // assumed to be a malloc'd string buffer, and is free'd by this function.
723 //
724 static void setValueName(Value *V, std::string *NameStr) {
725   if (!NameStr) return;
726   std::string Name(*NameStr);      // Copy string
727   delete NameStr;                  // Free old string
728
729   if (V->getType() == Type::VoidTy) {
730     GenerateError("Can't assign name '" + Name+"' to value with void type");
731     return;
732   }
733
734   assert(inFunctionScope() && "Must be in function scope!");
735   ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
736   if (ST.lookup(Name)) {
737     GenerateError("Redefinition of value '" + Name + "' of type '" +
738                    V->getType()->getDescription() + "'");
739     return;
740   }
741
742   // Set the name.
743   V->setName(Name);
744 }
745
746 /// ParseGlobalVariable - Handle parsing of a global.  If Initializer is null,
747 /// this is a declaration, otherwise it is a definition.
748 static GlobalVariable *
749 ParseGlobalVariable(std::string *NameStr,
750                     GlobalValue::LinkageTypes Linkage,
751                     GlobalValue::VisibilityTypes Visibility,
752                     bool isConstantGlobal, const Type *Ty,
753                     Constant *Initializer, bool IsThreadLocal,
754                     unsigned AddressSpace = 0) {
755   if (isa<FunctionType>(Ty)) {
756     GenerateError("Cannot declare global vars of function type");
757     return 0;
758   }
759   if (Ty == Type::LabelTy) {
760     GenerateError("Cannot declare global vars of label type");
761     return 0;
762   }
763
764   const PointerType *PTy = PointerType::get(Ty, AddressSpace);
765
766   std::string Name;
767   if (NameStr) {
768     Name = *NameStr;      // Copy string
769     delete NameStr;       // Free old string
770   }
771
772   // See if this global value was forward referenced.  If so, recycle the
773   // object.
774   ValID ID;
775   if (!Name.empty()) {
776     ID = ValID::createGlobalName(Name);
777   } else {
778     ID = ValID::createGlobalID(CurModule.Values.size());
779   }
780
781   if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
782     // Move the global to the end of the list, from whereever it was
783     // previously inserted.
784     GlobalVariable *GV = cast<GlobalVariable>(FWGV);
785     CurModule.CurrentModule->getGlobalList().remove(GV);
786     CurModule.CurrentModule->getGlobalList().push_back(GV);
787     GV->setInitializer(Initializer);
788     GV->setLinkage(Linkage);
789     GV->setVisibility(Visibility);
790     GV->setConstant(isConstantGlobal);
791     GV->setThreadLocal(IsThreadLocal);
792     InsertValue(GV, CurModule.Values);
793     ID.destroy();
794     return GV;
795   }
796
797   ID.destroy();
798
799   // If this global has a name
800   if (!Name.empty()) {
801     // if the global we're parsing has an initializer (is a definition) and
802     // has external linkage.
803     if (Initializer && Linkage != GlobalValue::InternalLinkage)
804       // If there is already a global with external linkage with this name
805       if (CurModule.CurrentModule->getGlobalVariable(Name, false)) {
806         // If we allow this GVar to get created, it will be renamed in the
807         // symbol table because it conflicts with an existing GVar. We can't
808         // allow redefinition of GVars whose linking indicates that their name
809         // must stay the same. Issue the error.
810         GenerateError("Redefinition of global variable named '" + Name +
811                        "' of type '" + Ty->getDescription() + "'");
812         return 0;
813       }
814   }
815
816   // Otherwise there is no existing GV to use, create one now.
817   GlobalVariable *GV =
818     new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
819                        CurModule.CurrentModule, IsThreadLocal, AddressSpace);
820   GV->setVisibility(Visibility);
821   InsertValue(GV, CurModule.Values);
822   return GV;
823 }
824
825 // setTypeName - Set the specified type to the name given.  The name may be
826 // null potentially, in which case this is a noop.  The string passed in is
827 // assumed to be a malloc'd string buffer, and is freed by this function.
828 //
829 // This function returns true if the type has already been defined, but is
830 // allowed to be redefined in the specified context.  If the name is a new name
831 // for the type plane, it is inserted and false is returned.
832 static bool setTypeName(const Type *T, std::string *NameStr) {
833   assert(!inFunctionScope() && "Can't give types function-local names!");
834   if (NameStr == 0) return false;
835
836   std::string Name(*NameStr);      // Copy string
837   delete NameStr;                  // Free old string
838
839   // We don't allow assigning names to void type
840   if (T == Type::VoidTy) {
841     GenerateError("Can't assign name '" + Name + "' to the void type");
842     return false;
843   }
844
845   // Set the type name, checking for conflicts as we do so.
846   bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
847
848   if (AlreadyExists) {   // Inserting a name that is already defined???
849     const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
850     assert(Existing && "Conflict but no matching type?!");
851
852     // There is only one case where this is allowed: when we are refining an
853     // opaque type.  In this case, Existing will be an opaque type.
854     if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
855       // We ARE replacing an opaque type!
856       const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
857       return true;
858     }
859
860     // Otherwise, this is an attempt to redefine a type. That's okay if
861     // the redefinition is identical to the original. This will be so if
862     // Existing and T point to the same Type object. In this one case we
863     // allow the equivalent redefinition.
864     if (Existing == T) return true;  // Yes, it's equal.
865
866     // Any other kind of (non-equivalent) redefinition is an error.
867     GenerateError("Redefinition of type named '" + Name + "' of type '" +
868                    T->getDescription() + "'");
869   }
870
871   return false;
872 }
873
874 //===----------------------------------------------------------------------===//
875 // Code for handling upreferences in type names...
876 //
877
878 // TypeContains - Returns true if Ty directly contains E in it.
879 //
880 static bool TypeContains(const Type *Ty, const Type *E) {
881   return std::find(Ty->subtype_begin(), Ty->subtype_end(),
882                    E) != Ty->subtype_end();
883 }
884
885 namespace {
886   struct UpRefRecord {
887     // NestingLevel - The number of nesting levels that need to be popped before
888     // this type is resolved.
889     unsigned NestingLevel;
890
891     // LastContainedTy - This is the type at the current binding level for the
892     // type.  Every time we reduce the nesting level, this gets updated.
893     const Type *LastContainedTy;
894
895     // UpRefTy - This is the actual opaque type that the upreference is
896     // represented with.
897     OpaqueType *UpRefTy;
898
899     UpRefRecord(unsigned NL, OpaqueType *URTy)
900       : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
901   };
902 }
903
904 // UpRefs - A list of the outstanding upreferences that need to be resolved.
905 static std::vector<UpRefRecord> UpRefs;
906
907 /// HandleUpRefs - Every time we finish a new layer of types, this function is
908 /// called.  It loops through the UpRefs vector, which is a list of the
909 /// currently active types.  For each type, if the up reference is contained in
910 /// the newly completed type, we decrement the level count.  When the level
911 /// count reaches zero, the upreferenced type is the type that is passed in:
912 /// thus we can complete the cycle.
913 ///
914 static PATypeHolder HandleUpRefs(const Type *ty) {
915   // If Ty isn't abstract, or if there are no up-references in it, then there is
916   // nothing to resolve here.
917   if (!ty->isAbstract() || UpRefs.empty()) return ty;
918
919   PATypeHolder Ty(ty);
920   UR_OUT("Type '" << Ty->getDescription() <<
921          "' newly formed.  Resolving upreferences.\n" <<
922          UpRefs.size() << " upreferences active!\n");
923
924   // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
925   // to zero), we resolve them all together before we resolve them to Ty.  At
926   // the end of the loop, if there is anything to resolve to Ty, it will be in
927   // this variable.
928   OpaqueType *TypeToResolve = 0;
929
930   for (unsigned i = 0; i != UpRefs.size(); ++i) {
931     UR_OUT("  UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
932            << UpRefs[i].second->getDescription() << ") = "
933            << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
934     if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
935       // Decrement level of upreference
936       unsigned Level = --UpRefs[i].NestingLevel;
937       UpRefs[i].LastContainedTy = Ty;
938       UR_OUT("  Uplevel Ref Level = " << Level << "\n");
939       if (Level == 0) {                     // Upreference should be resolved!
940         if (!TypeToResolve) {
941           TypeToResolve = UpRefs[i].UpRefTy;
942         } else {
943           UR_OUT("  * Resolving upreference for "
944                  << UpRefs[i].second->getDescription() << "\n";
945                  std::string OldName = UpRefs[i].UpRefTy->getDescription());
946           UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
947           UR_OUT("  * Type '" << OldName << "' refined upreference to: "
948                  << (const void*)Ty << ", " << Ty->getDescription() << "\n");
949         }
950         UpRefs.erase(UpRefs.begin()+i);     // Remove from upreference list...
951         --i;                                // Do not skip the next element...
952       }
953     }
954   }
955
956   if (TypeToResolve) {
957     UR_OUT("  * Resolving upreference for "
958            << UpRefs[i].second->getDescription() << "\n";
959            std::string OldName = TypeToResolve->getDescription());
960     TypeToResolve->refineAbstractTypeTo(Ty);
961   }
962
963   return Ty;
964 }
965
966 //===----------------------------------------------------------------------===//
967 //            RunVMAsmParser - Define an interface to this parser
968 //===----------------------------------------------------------------------===//
969 //
970 static Module* RunParser(Module * M);
971
972 Module *llvm::RunVMAsmParser(llvm::MemoryBuffer *MB) {
973   InitLLLexer(MB);
974   Module *M = RunParser(new Module(LLLgetFilename()));
975   FreeLexer();
976   return M;
977 }
978
979 %}
980
981 %union {
982   llvm::Module                           *ModuleVal;
983   llvm::Function                         *FunctionVal;
984   llvm::BasicBlock                       *BasicBlockVal;
985   llvm::TerminatorInst                   *TermInstVal;
986   llvm::Instruction                      *InstVal;
987   llvm::Constant                         *ConstVal;
988
989   const llvm::Type                       *PrimType;
990   std::list<llvm::PATypeHolder>          *TypeList;
991   llvm::PATypeHolder                     *TypeVal;
992   llvm::Value                            *ValueVal;
993   std::vector<llvm::Value*>              *ValueList;
994   std::vector<unsigned>                  *ConstantList;
995   llvm::ArgListType                      *ArgList;
996   llvm::TypeWithAttrs                     TypeWithAttrs;
997   llvm::TypeWithAttrsList                *TypeWithAttrsList;
998   llvm::ParamList                        *ParamList;
999
1000   // Represent the RHS of PHI node
1001   std::list<std::pair<llvm::Value*,
1002                       llvm::BasicBlock*> > *PHIList;
1003   std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
1004   std::vector<llvm::Constant*>           *ConstVector;
1005
1006   llvm::GlobalValue::LinkageTypes         Linkage;
1007   llvm::GlobalValue::VisibilityTypes      Visibility;
1008   llvm::Attributes                  Attributes;
1009   llvm::APInt                       *APIntVal;
1010   int64_t                           SInt64Val;
1011   uint64_t                          UInt64Val;
1012   int                               SIntVal;
1013   unsigned                          UIntVal;
1014   llvm::APFloat                    *FPVal;
1015   bool                              BoolVal;
1016
1017   std::string                      *StrVal;   // This memory must be deleted
1018   llvm::ValID                       ValIDVal;
1019
1020   llvm::Instruction::BinaryOps      BinaryOpVal;
1021   llvm::Instruction::TermOps        TermOpVal;
1022   llvm::Instruction::MemoryOps      MemOpVal;
1023   llvm::Instruction::CastOps        CastOpVal;
1024   llvm::Instruction::OtherOps       OtherOpVal;
1025   llvm::ICmpInst::Predicate         IPredicate;
1026   llvm::FCmpInst::Predicate         FPredicate;
1027 }
1028
1029 %type <ModuleVal>     Module
1030 %type <FunctionVal>   Function FunctionProto FunctionHeader BasicBlockList
1031 %type <BasicBlockVal> BasicBlock InstructionList
1032 %type <TermInstVal>   BBTerminatorInst
1033 %type <InstVal>       Inst InstVal MemoryInst
1034 %type <ConstVal>      ConstVal ConstExpr AliaseeRef
1035 %type <ConstVector>   ConstVector
1036 %type <ArgList>       ArgList ArgListH
1037 %type <PHIList>       PHIList
1038 %type <ParamList>     ParamList      // For call param lists & GEP indices
1039 %type <ValueList>     IndexList         // For GEP indices
1040 %type <ConstantList>  ConstantIndexList // For insertvalue/extractvalue indices
1041 %type <TypeList>      TypeListI
1042 %type <TypeWithAttrsList> ArgTypeList ArgTypeListI
1043 %type <TypeWithAttrs> ArgType
1044 %type <JumpTable>     JumpTable
1045 %type <BoolVal>       GlobalType                  // GLOBAL or CONSTANT?
1046 %type <BoolVal>       ThreadLocal                 // 'thread_local' or not
1047 %type <BoolVal>       OptVolatile                 // 'volatile' or not
1048 %type <BoolVal>       OptTailCall                 // TAIL CALL or plain CALL.
1049 %type <BoolVal>       OptSideEffect               // 'sideeffect' or not.
1050 %type <Linkage>       GVInternalLinkage GVExternalLinkage
1051 %type <Linkage>       FunctionDefineLinkage FunctionDeclareLinkage
1052 %type <Linkage>       AliasLinkage
1053 %type <Visibility>    GVVisibilityStyle
1054
1055 // ValueRef - Unresolved reference to a definition or BB
1056 %type <ValIDVal>      ValueRef ConstValueRef SymbolicValueRef
1057 %type <ValueVal>      ResolvedVal            // <type> <valref> pair
1058 %type <ValueList>     ReturnedVal
1059 // Tokens and types for handling constant integer values
1060 //
1061 // ESINT64VAL - A negative number within long long range
1062 %token <SInt64Val> ESINT64VAL
1063
1064 // EUINT64VAL - A positive number within uns. long long range
1065 %token <UInt64Val> EUINT64VAL
1066
1067 // ESAPINTVAL - A negative number with arbitrary precision
1068 %token <APIntVal>  ESAPINTVAL
1069
1070 // EUAPINTVAL - A positive number with arbitrary precision
1071 %token <APIntVal>  EUAPINTVAL
1072
1073 %token  <UIntVal>   LOCALVAL_ID GLOBALVAL_ID  // %123 @123
1074 %token  <FPVal>     FPVAL     // Float or Double constant
1075
1076 // Built in types...
1077 %type  <TypeVal> Types ResultTypes
1078 %type  <PrimType> PrimType           // Classifications
1079 %token <PrimType> VOID INTTYPE
1080 %token <PrimType> FLOAT DOUBLE X86_FP80 FP128 PPC_FP128 LABEL
1081 %token TYPE
1082
1083
1084 %token<StrVal> LOCALVAR GLOBALVAR LABELSTR
1085 %token<StrVal> STRINGCONSTANT ATSTRINGCONSTANT PCTSTRINGCONSTANT
1086 %type <StrVal> LocalName OptLocalName OptLocalAssign
1087 %type <StrVal> GlobalName OptGlobalAssign GlobalAssign
1088 %type <StrVal> OptSection SectionString OptGC
1089
1090 %type <UIntVal> OptAlign OptCAlign OptAddrSpace
1091
1092 %token ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1093 %token DECLARE DEFINE GLOBAL CONSTANT SECTION ALIAS VOLATILE THREAD_LOCAL
1094 %token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
1095 %token DLLIMPORT DLLEXPORT EXTERN_WEAK COMMON
1096 %token OPAQUE EXTERNAL TARGET TRIPLE ALIGN ADDRSPACE
1097 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1098 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1099 %token DATALAYOUT
1100 %type <UIntVal> OptCallingConv LocalNumber
1101 %type <Attributes> OptAttributes Attribute
1102 %type <Attributes> OptFuncAttrs  FuncAttr
1103 %type <Attributes> OptRetAttrs  RetAttr
1104
1105 // Basic Block Terminating Operators
1106 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1107
1108 // Binary Operators
1109 %type  <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
1110 %token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1111 %token <BinaryOpVal> SHL LSHR ASHR
1112
1113 %token <OtherOpVal> ICMP FCMP VICMP VFCMP
1114 %type  <IPredicate> IPredicates
1115 %type  <FPredicate> FPredicates
1116 %token  EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1117 %token  OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1118
1119 // Memory Instructions
1120 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1121
1122 // Cast Operators
1123 %type <CastOpVal> CastOps
1124 %token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1125 %token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1126
1127 // Other Operators
1128 %token <OtherOpVal> PHI_TOK SELECT VAARG
1129 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1130 %token <OtherOpVal> GETRESULT
1131 %token <OtherOpVal> EXTRACTVALUE INSERTVALUE
1132
1133 // Function Attributes
1134 %token SIGNEXT ZEROEXT NORETURN INREG SRET NOUNWIND NOALIAS BYVAL NEST
1135 %token READNONE READONLY GC OPTSIZE NOINLINE ALWAYSINLINE
1136
1137 // Visibility Styles
1138 %token DEFAULT HIDDEN PROTECTED
1139
1140 %start Module
1141 %%
1142
1143
1144 // Operations that are notably excluded from this list include:
1145 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1146 //
1147 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1148 LogicalOps   : SHL | LSHR | ASHR | AND | OR | XOR;
1149 CastOps      : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1150                UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1151
1152 IPredicates
1153   : EQ   { $$ = ICmpInst::ICMP_EQ; }  | NE   { $$ = ICmpInst::ICMP_NE; }
1154   | SLT  { $$ = ICmpInst::ICMP_SLT; } | SGT  { $$ = ICmpInst::ICMP_SGT; }
1155   | SLE  { $$ = ICmpInst::ICMP_SLE; } | SGE  { $$ = ICmpInst::ICMP_SGE; }
1156   | ULT  { $$ = ICmpInst::ICMP_ULT; } | UGT  { $$ = ICmpInst::ICMP_UGT; }
1157   | ULE  { $$ = ICmpInst::ICMP_ULE; } | UGE  { $$ = ICmpInst::ICMP_UGE; }
1158   ;
1159
1160 FPredicates
1161   : OEQ  { $$ = FCmpInst::FCMP_OEQ; } | ONE  { $$ = FCmpInst::FCMP_ONE; }
1162   | OLT  { $$ = FCmpInst::FCMP_OLT; } | OGT  { $$ = FCmpInst::FCMP_OGT; }
1163   | OLE  { $$ = FCmpInst::FCMP_OLE; } | OGE  { $$ = FCmpInst::FCMP_OGE; }
1164   | ORD  { $$ = FCmpInst::FCMP_ORD; } | UNO  { $$ = FCmpInst::FCMP_UNO; }
1165   | UEQ  { $$ = FCmpInst::FCMP_UEQ; } | UNE  { $$ = FCmpInst::FCMP_UNE; }
1166   | ULT  { $$ = FCmpInst::FCMP_ULT; } | UGT  { $$ = FCmpInst::FCMP_UGT; }
1167   | ULE  { $$ = FCmpInst::FCMP_ULE; } | UGE  { $$ = FCmpInst::FCMP_UGE; }
1168   | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1169   | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1170   ;
1171
1172 LocalName : LOCALVAR | STRINGCONSTANT | PCTSTRINGCONSTANT ;
1173 OptLocalName : LocalName | /*empty*/ { $$ = 0; };
1174
1175 OptAddrSpace : ADDRSPACE '(' EUINT64VAL ')' { $$=$3; }
1176              | /*empty*/                    { $$=0; };
1177
1178 /// OptLocalAssign - Value producing statements have an optional assignment
1179 /// component.
1180 OptLocalAssign : LocalName '=' {
1181     $$ = $1;
1182     CHECK_FOR_ERROR
1183   }
1184   | /*empty*/ {
1185     $$ = 0;
1186     CHECK_FOR_ERROR
1187   };
1188
1189 LocalNumber : LOCALVAL_ID '=' {
1190   $$ = $1;
1191   CHECK_FOR_ERROR
1192 };
1193
1194
1195 GlobalName : GLOBALVAR | ATSTRINGCONSTANT ;
1196
1197 OptGlobalAssign : GlobalAssign
1198   | /*empty*/ {
1199     $$ = 0;
1200     CHECK_FOR_ERROR
1201   };
1202
1203 GlobalAssign : GlobalName '=' {
1204     $$ = $1;
1205     CHECK_FOR_ERROR
1206   };
1207
1208 GVInternalLinkage
1209   : INTERNAL    { $$ = GlobalValue::InternalLinkage; }
1210   | WEAK        { $$ = GlobalValue::WeakLinkage; }
1211   | LINKONCE    { $$ = GlobalValue::LinkOnceLinkage; }
1212   | APPENDING   { $$ = GlobalValue::AppendingLinkage; }
1213   | DLLEXPORT   { $$ = GlobalValue::DLLExportLinkage; }
1214   | COMMON      { $$ = GlobalValue::CommonLinkage; }
1215   ;
1216
1217 GVExternalLinkage
1218   : DLLIMPORT   { $$ = GlobalValue::DLLImportLinkage; }
1219   | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1220   | EXTERNAL    { $$ = GlobalValue::ExternalLinkage; }
1221   ;
1222
1223 GVVisibilityStyle
1224   : /*empty*/ { $$ = GlobalValue::DefaultVisibility;   }
1225   | DEFAULT   { $$ = GlobalValue::DefaultVisibility;   }
1226   | HIDDEN    { $$ = GlobalValue::HiddenVisibility;    }
1227   | PROTECTED { $$ = GlobalValue::ProtectedVisibility; }
1228   ;
1229
1230 FunctionDeclareLinkage
1231   : /*empty*/   { $$ = GlobalValue::ExternalLinkage; }
1232   | DLLIMPORT   { $$ = GlobalValue::DLLImportLinkage; }
1233   | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1234   ;
1235
1236 FunctionDefineLinkage
1237   : /*empty*/   { $$ = GlobalValue::ExternalLinkage; }
1238   | INTERNAL    { $$ = GlobalValue::InternalLinkage; }
1239   | LINKONCE    { $$ = GlobalValue::LinkOnceLinkage; }
1240   | WEAK        { $$ = GlobalValue::WeakLinkage; }
1241   | DLLEXPORT   { $$ = GlobalValue::DLLExportLinkage; }
1242   ;
1243
1244 AliasLinkage
1245   : /*empty*/   { $$ = GlobalValue::ExternalLinkage; }
1246   | WEAK        { $$ = GlobalValue::WeakLinkage; }
1247   | INTERNAL    { $$ = GlobalValue::InternalLinkage; }
1248   ;
1249
1250 OptCallingConv : /*empty*/          { $$ = CallingConv::C; } |
1251                  CCC_TOK            { $$ = CallingConv::C; } |
1252                  FASTCC_TOK         { $$ = CallingConv::Fast; } |
1253                  COLDCC_TOK         { $$ = CallingConv::Cold; } |
1254                  X86_STDCALLCC_TOK  { $$ = CallingConv::X86_StdCall; } |
1255                  X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1256                  CC_TOK EUINT64VAL  {
1257                    if ((unsigned)$2 != $2)
1258                      GEN_ERROR("Calling conv too large");
1259                    $$ = $2;
1260                   CHECK_FOR_ERROR
1261                  };
1262
1263 Attribute     : ZEROEXT { $$ = Attribute::ZExt;      }
1264               | ZEXT    { $$ = Attribute::ZExt;      }
1265               | SIGNEXT { $$ = Attribute::SExt;      }
1266               | SEXT    { $$ = Attribute::SExt;      }
1267               | INREG   { $$ = Attribute::InReg;     }
1268               | SRET    { $$ = Attribute::StructRet; }
1269               | NOALIAS { $$ = Attribute::NoAlias;   }
1270               | BYVAL   { $$ = Attribute::ByVal;     }
1271               | NEST    { $$ = Attribute::Nest;      }
1272               | ALIGN EUINT64VAL { $$ =
1273                           Attribute::constructAlignmentFromInt($2);    }
1274               ;
1275
1276 OptAttributes : /* empty */  { $$ = Attribute::None; }
1277               | OptAttributes Attribute {
1278                 $$ = $1 | $2;
1279               }
1280               ;
1281
1282 RetAttr       : INREG    { $$ = Attribute::InReg;     }
1283               | ZEROEXT  { $$ = Attribute::ZExt;     }
1284               | SIGNEXT  { $$ = Attribute::SExt;     }
1285               ;
1286
1287 OptRetAttrs  : /* empty */ { $$ = Attribute::None; }
1288              | OptRetAttrs RetAttr {
1289                $$ = $1 | $2;
1290              }
1291              ;
1292
1293
1294 FuncAttr      : NORETURN { $$ = Attribute::NoReturn; }
1295               | NOUNWIND { $$ = Attribute::NoUnwind; }
1296               | INREG    { $$ = Attribute::InReg;     }
1297               | ZEROEXT  { $$ = Attribute::ZExt;     }
1298               | SIGNEXT  { $$ = Attribute::SExt;     }
1299               | READNONE { $$ = Attribute::ReadNone; }
1300               | READONLY { $$ = Attribute::ReadOnly; }
1301               | NOINLINE { $$ = Attribute::NoInline; }
1302               | ALWAYSINLINE { $$ = Attribute::AlwaysInline; }
1303               | OPTSIZE { $$ = Attribute::OptimizeForSize; }
1304               ;
1305
1306 OptFuncAttrs  : /* empty */ { $$ = Attribute::None; }
1307               | OptFuncAttrs FuncAttr {
1308                 $$ = $1 | $2;
1309               }
1310               ;
1311
1312
1313 OptGC         : /* empty */ { $$ = 0; }
1314               | GC STRINGCONSTANT {
1315                 $$ = $2;
1316               }
1317               ;
1318
1319 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1320 // a comma before it.
1321 OptAlign : /*empty*/        { $$ = 0; } |
1322            ALIGN EUINT64VAL {
1323   $$ = $2;
1324   if ($$ != 0 && !isPowerOf2_32($$))
1325     GEN_ERROR("Alignment must be a power of two");
1326   CHECK_FOR_ERROR
1327 };
1328 OptCAlign : /*empty*/            { $$ = 0; } |
1329             ',' ALIGN EUINT64VAL {
1330   $$ = $3;
1331   if ($$ != 0 && !isPowerOf2_32($$))
1332     GEN_ERROR("Alignment must be a power of two");
1333   CHECK_FOR_ERROR
1334 };
1335
1336
1337
1338 SectionString : SECTION STRINGCONSTANT {
1339   for (unsigned i = 0, e = $2->length(); i != e; ++i)
1340     if ((*$2)[i] == '"' || (*$2)[i] == '\\')
1341       GEN_ERROR("Invalid character in section name");
1342   $$ = $2;
1343   CHECK_FOR_ERROR
1344 };
1345
1346 OptSection : /*empty*/ { $$ = 0; } |
1347              SectionString { $$ = $1; };
1348
1349 // GlobalVarAttributes - Used to pass the attributes string on a global.  CurGV
1350 // is set to be the global we are processing.
1351 //
1352 GlobalVarAttributes : /* empty */ {} |
1353                      ',' GlobalVarAttribute GlobalVarAttributes {};
1354 GlobalVarAttribute : SectionString {
1355     CurGV->setSection(*$1);
1356     delete $1;
1357     CHECK_FOR_ERROR
1358   }
1359   | ALIGN EUINT64VAL {
1360     if ($2 != 0 && !isPowerOf2_32($2))
1361       GEN_ERROR("Alignment must be a power of two");
1362     CurGV->setAlignment($2);
1363     CHECK_FOR_ERROR
1364   };
1365
1366 //===----------------------------------------------------------------------===//
1367 // Types includes all predefined types... except void, because it can only be
1368 // used in specific contexts (function returning void for example).
1369
1370 // Derived types are added later...
1371 //
1372 PrimType : INTTYPE | FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80 | LABEL ;
1373
1374 Types
1375   : OPAQUE {
1376     $$ = new PATypeHolder(OpaqueType::get());
1377     CHECK_FOR_ERROR
1378   }
1379   | PrimType {
1380     $$ = new PATypeHolder($1);
1381     CHECK_FOR_ERROR
1382   }
1383   | Types OptAddrSpace '*' {                             // Pointer type?
1384     if (*$1 == Type::LabelTy)
1385       GEN_ERROR("Cannot form a pointer to a basic block");
1386     $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1, $2)));
1387     delete $1;
1388     CHECK_FOR_ERROR
1389   }
1390   | SymbolicValueRef {            // Named types are also simple types...
1391     const Type* tmp = getTypeVal($1);
1392     CHECK_FOR_ERROR
1393     $$ = new PATypeHolder(tmp);
1394   }
1395   | '\\' EUINT64VAL {                   // Type UpReference
1396     if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range");
1397     OpaqueType *OT = OpaqueType::get();        // Use temporary placeholder
1398     UpRefs.push_back(UpRefRecord((unsigned)$2, OT));  // Add to vector...
1399     $$ = new PATypeHolder(OT);
1400     UR_OUT("New Upreference!\n");
1401     CHECK_FOR_ERROR
1402   }
1403   | Types '(' ArgTypeListI ')' OptFuncAttrs {
1404     // Allow but ignore attributes on function types; this permits auto-upgrade.
1405     // FIXME: remove in LLVM 3.0.
1406     const Type *RetTy = *$1;
1407     if (!FunctionType::isValidReturnType(RetTy))
1408       GEN_ERROR("Invalid result type for LLVM function");
1409
1410     std::vector<const Type*> Params;
1411     TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1412     for (; I != E; ++I ) {
1413       const Type *Ty = I->Ty->get();
1414       Params.push_back(Ty);
1415     }
1416
1417     bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1418     if (isVarArg) Params.pop_back();
1419
1420     for (unsigned i = 0; i != Params.size(); ++i)
1421       if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1422         GEN_ERROR("Function arguments must be value types!");
1423
1424     CHECK_FOR_ERROR
1425
1426     FunctionType *FT = FunctionType::get(RetTy, Params, isVarArg);
1427     delete $1;   // Delete the return type handle
1428     $$ = new PATypeHolder(HandleUpRefs(FT));
1429
1430     // Delete the argument list
1431     for (I = $3->begin() ; I != E; ++I ) {
1432       delete I->Ty;
1433     }
1434     delete $3;
1435
1436     CHECK_FOR_ERROR
1437   }
1438   | VOID '(' ArgTypeListI ')' OptFuncAttrs {
1439     // Allow but ignore attributes on function types; this permits auto-upgrade.
1440     // FIXME: remove in LLVM 3.0.
1441     std::vector<const Type*> Params;
1442     TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1443     for ( ; I != E; ++I ) {
1444       const Type* Ty = I->Ty->get();
1445       Params.push_back(Ty);
1446     }
1447
1448     bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1449     if (isVarArg) Params.pop_back();
1450
1451     for (unsigned i = 0; i != Params.size(); ++i)
1452       if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1453         GEN_ERROR("Function arguments must be value types!");
1454
1455     CHECK_FOR_ERROR
1456
1457     FunctionType *FT = FunctionType::get($1, Params, isVarArg);
1458     $$ = new PATypeHolder(HandleUpRefs(FT));
1459
1460     // Delete the argument list
1461     for (I = $3->begin() ; I != E; ++I ) {
1462       delete I->Ty;
1463     }
1464     delete $3;
1465
1466     CHECK_FOR_ERROR
1467   }
1468
1469   | '[' EUINT64VAL 'x' Types ']' {          // Sized array type?
1470     $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, $2)));
1471     delete $4;
1472     CHECK_FOR_ERROR
1473   }
1474   | '<' EUINT64VAL 'x' Types '>' {          // Vector type?
1475      const llvm::Type* ElemTy = $4->get();
1476      if ((unsigned)$2 != $2)
1477         GEN_ERROR("Unsigned result not equal to signed result");
1478      if (!ElemTy->isFloatingPoint() && !ElemTy->isInteger())
1479         GEN_ERROR("Element type of a VectorType must be primitive");
1480      $$ = new PATypeHolder(HandleUpRefs(VectorType::get(*$4, (unsigned)$2)));
1481      delete $4;
1482      CHECK_FOR_ERROR
1483   }
1484   | '{' TypeListI '}' {                        // Structure type?
1485     std::vector<const Type*> Elements;
1486     for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1487            E = $2->end(); I != E; ++I)
1488       Elements.push_back(*I);
1489
1490     $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1491     delete $2;
1492     CHECK_FOR_ERROR
1493   }
1494   | '{' '}' {                                  // Empty structure type?
1495     $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1496     CHECK_FOR_ERROR
1497   }
1498   | '<' '{' TypeListI '}' '>' {
1499     std::vector<const Type*> Elements;
1500     for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1501            E = $3->end(); I != E; ++I)
1502       Elements.push_back(*I);
1503
1504     $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1505     delete $3;
1506     CHECK_FOR_ERROR
1507   }
1508   | '<' '{' '}' '>' {                         // Empty structure type?
1509     $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1510     CHECK_FOR_ERROR
1511   }
1512   ;
1513
1514 ArgType
1515   : Types OptAttributes {
1516     // Allow but ignore attributes on function types; this permits auto-upgrade.
1517     // FIXME: remove in LLVM 3.0.
1518     $$.Ty = $1;
1519     $$.Attrs = Attribute::None;
1520   }
1521   ;
1522
1523 ResultTypes
1524   : Types {
1525     if (!UpRefs.empty())
1526       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1527     if (!(*$1)->isFirstClassType() && !isa<StructType>($1->get()))
1528       GEN_ERROR("LLVM functions cannot return aggregate types");
1529     $$ = $1;
1530   }
1531   | VOID {
1532     $$ = new PATypeHolder(Type::VoidTy);
1533   }
1534   ;
1535
1536 ArgTypeList : ArgType {
1537     $$ = new TypeWithAttrsList();
1538     $$->push_back($1);
1539     CHECK_FOR_ERROR
1540   }
1541   | ArgTypeList ',' ArgType {
1542     ($$=$1)->push_back($3);
1543     CHECK_FOR_ERROR
1544   }
1545   ;
1546
1547 ArgTypeListI
1548   : ArgTypeList
1549   | ArgTypeList ',' DOTDOTDOT {
1550     $$=$1;
1551     TypeWithAttrs TWA; TWA.Attrs = Attribute::None;
1552     TWA.Ty = new PATypeHolder(Type::VoidTy);
1553     $$->push_back(TWA);
1554     CHECK_FOR_ERROR
1555   }
1556   | DOTDOTDOT {
1557     $$ = new TypeWithAttrsList;
1558     TypeWithAttrs TWA; TWA.Attrs = Attribute::None;
1559     TWA.Ty = new PATypeHolder(Type::VoidTy);
1560     $$->push_back(TWA);
1561     CHECK_FOR_ERROR
1562   }
1563   | /*empty*/ {
1564     $$ = new TypeWithAttrsList();
1565     CHECK_FOR_ERROR
1566   };
1567
1568 // TypeList - Used for struct declarations and as a basis for function type
1569 // declaration type lists
1570 //
1571 TypeListI : Types {
1572     $$ = new std::list<PATypeHolder>();
1573     $$->push_back(*$1);
1574     delete $1;
1575     CHECK_FOR_ERROR
1576   }
1577   | TypeListI ',' Types {
1578     ($$=$1)->push_back(*$3);
1579     delete $3;
1580     CHECK_FOR_ERROR
1581   };
1582
1583 // ConstVal - The various declarations that go into the constant pool.  This
1584 // production is used ONLY to represent constants that show up AFTER a 'const',
1585 // 'constant' or 'global' token at global scope.  Constants that can be inlined
1586 // into other expressions (such as integers and constexprs) are handled by the
1587 // ResolvedVal, ValueRef and ConstValueRef productions.
1588 //
1589 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1590     if (!UpRefs.empty())
1591       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1592     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1593     if (ATy == 0)
1594       GEN_ERROR("Cannot make array constant with type: '" +
1595                      (*$1)->getDescription() + "'");
1596     const Type *ETy = ATy->getElementType();
1597     uint64_t NumElements = ATy->getNumElements();
1598
1599     // Verify that we have the correct size...
1600     if (NumElements != uint64_t(-1) && NumElements != $3->size())
1601       GEN_ERROR("Type mismatch: constant sized array initialized with " +
1602                      utostr($3->size()) +  " arguments, but has size of " +
1603                      utostr(NumElements) + "");
1604
1605     // Verify all elements are correct type!
1606     for (unsigned i = 0; i < $3->size(); i++) {
1607       if (ETy != (*$3)[i]->getType())
1608         GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1609                        ETy->getDescription() +"' as required!\nIt is of type '"+
1610                        (*$3)[i]->getType()->getDescription() + "'.");
1611     }
1612
1613     $$ = ConstantArray::get(ATy, *$3);
1614     delete $1; delete $3;
1615     CHECK_FOR_ERROR
1616   }
1617   | Types '[' ']' {
1618     if (!UpRefs.empty())
1619       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1620     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1621     if (ATy == 0)
1622       GEN_ERROR("Cannot make array constant with type: '" +
1623                      (*$1)->getDescription() + "'");
1624
1625     uint64_t NumElements = ATy->getNumElements();
1626     if (NumElements != uint64_t(-1) && NumElements != 0)
1627       GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1628                      " arguments, but has size of " + utostr(NumElements) +"");
1629     $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1630     delete $1;
1631     CHECK_FOR_ERROR
1632   }
1633   | Types 'c' STRINGCONSTANT {
1634     if (!UpRefs.empty())
1635       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1636     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1637     if (ATy == 0)
1638       GEN_ERROR("Cannot make array constant with type: '" +
1639                      (*$1)->getDescription() + "'");
1640
1641     uint64_t NumElements = ATy->getNumElements();
1642     const Type *ETy = ATy->getElementType();
1643     if (NumElements != uint64_t(-1) && NumElements != $3->length())
1644       GEN_ERROR("Can't build string constant of size " +
1645                      utostr($3->length()) +
1646                      " when array has size " + utostr(NumElements) + "");
1647     std::vector<Constant*> Vals;
1648     if (ETy == Type::Int8Ty) {
1649       for (uint64_t i = 0; i < $3->length(); ++i)
1650         Vals.push_back(ConstantInt::get(ETy, (*$3)[i]));
1651     } else {
1652       delete $3;
1653       GEN_ERROR("Cannot build string arrays of non byte sized elements");
1654     }
1655     delete $3;
1656     $$ = ConstantArray::get(ATy, Vals);
1657     delete $1;
1658     CHECK_FOR_ERROR
1659   }
1660   | Types '<' ConstVector '>' { // Nonempty unsized arr
1661     if (!UpRefs.empty())
1662       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1663     const VectorType *PTy = dyn_cast<VectorType>($1->get());
1664     if (PTy == 0)
1665       GEN_ERROR("Cannot make packed constant with type: '" +
1666                      (*$1)->getDescription() + "'");
1667     const Type *ETy = PTy->getElementType();
1668     unsigned NumElements = PTy->getNumElements();
1669
1670     // Verify that we have the correct size...
1671     if (NumElements != unsigned(-1) && NumElements != (unsigned)$3->size())
1672       GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1673                      utostr($3->size()) +  " arguments, but has size of " +
1674                      utostr(NumElements) + "");
1675
1676     // Verify all elements are correct type!
1677     for (unsigned i = 0; i < $3->size(); i++) {
1678       if (ETy != (*$3)[i]->getType())
1679         GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1680            ETy->getDescription() +"' as required!\nIt is of type '"+
1681            (*$3)[i]->getType()->getDescription() + "'.");
1682     }
1683
1684     $$ = ConstantVector::get(PTy, *$3);
1685     delete $1; delete $3;
1686     CHECK_FOR_ERROR
1687   }
1688   | Types '{' ConstVector '}' {
1689     const StructType *STy = dyn_cast<StructType>($1->get());
1690     if (STy == 0)
1691       GEN_ERROR("Cannot make struct constant with type: '" +
1692                      (*$1)->getDescription() + "'");
1693
1694     if ($3->size() != STy->getNumContainedTypes())
1695       GEN_ERROR("Illegal number of initializers for structure type");
1696
1697     // Check to ensure that constants are compatible with the type initializer!
1698     for (unsigned i = 0, e = $3->size(); i != e; ++i)
1699       if ((*$3)[i]->getType() != STy->getElementType(i))
1700         GEN_ERROR("Expected type '" +
1701                        STy->getElementType(i)->getDescription() +
1702                        "' for element #" + utostr(i) +
1703                        " of structure initializer");
1704
1705     // Check to ensure that Type is not packed
1706     if (STy->isPacked())
1707       GEN_ERROR("Unpacked Initializer to vector type '" +
1708                 STy->getDescription() + "'");
1709
1710     $$ = ConstantStruct::get(STy, *$3);
1711     delete $1; delete $3;
1712     CHECK_FOR_ERROR
1713   }
1714   | Types '{' '}' {
1715     if (!UpRefs.empty())
1716       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1717     const StructType *STy = dyn_cast<StructType>($1->get());
1718     if (STy == 0)
1719       GEN_ERROR("Cannot make struct constant with type: '" +
1720                      (*$1)->getDescription() + "'");
1721
1722     if (STy->getNumContainedTypes() != 0)
1723       GEN_ERROR("Illegal number of initializers for structure type");
1724
1725     // Check to ensure that Type is not packed
1726     if (STy->isPacked())
1727       GEN_ERROR("Unpacked Initializer to vector type '" +
1728                 STy->getDescription() + "'");
1729
1730     $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1731     delete $1;
1732     CHECK_FOR_ERROR
1733   }
1734   | Types '<' '{' ConstVector '}' '>' {
1735     const StructType *STy = dyn_cast<StructType>($1->get());
1736     if (STy == 0)
1737       GEN_ERROR("Cannot make struct constant with type: '" +
1738                      (*$1)->getDescription() + "'");
1739
1740     if ($4->size() != STy->getNumContainedTypes())
1741       GEN_ERROR("Illegal number of initializers for structure type");
1742
1743     // Check to ensure that constants are compatible with the type initializer!
1744     for (unsigned i = 0, e = $4->size(); i != e; ++i)
1745       if ((*$4)[i]->getType() != STy->getElementType(i))
1746         GEN_ERROR("Expected type '" +
1747                        STy->getElementType(i)->getDescription() +
1748                        "' for element #" + utostr(i) +
1749                        " of structure initializer");
1750
1751     // Check to ensure that Type is packed
1752     if (!STy->isPacked())
1753       GEN_ERROR("Vector initializer to non-vector type '" +
1754                 STy->getDescription() + "'");
1755
1756     $$ = ConstantStruct::get(STy, *$4);
1757     delete $1; delete $4;
1758     CHECK_FOR_ERROR
1759   }
1760   | Types '<' '{' '}' '>' {
1761     if (!UpRefs.empty())
1762       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1763     const StructType *STy = dyn_cast<StructType>($1->get());
1764     if (STy == 0)
1765       GEN_ERROR("Cannot make struct constant with type: '" +
1766                      (*$1)->getDescription() + "'");
1767
1768     if (STy->getNumContainedTypes() != 0)
1769       GEN_ERROR("Illegal number of initializers for structure type");
1770
1771     // Check to ensure that Type is packed
1772     if (!STy->isPacked())
1773       GEN_ERROR("Vector initializer to non-vector type '" +
1774                 STy->getDescription() + "'");
1775
1776     $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1777     delete $1;
1778     CHECK_FOR_ERROR
1779   }
1780   | Types NULL_TOK {
1781     if (!UpRefs.empty())
1782       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1783     const PointerType *PTy = dyn_cast<PointerType>($1->get());
1784     if (PTy == 0)
1785       GEN_ERROR("Cannot make null pointer constant with type: '" +
1786                      (*$1)->getDescription() + "'");
1787
1788     $$ = ConstantPointerNull::get(PTy);
1789     delete $1;
1790     CHECK_FOR_ERROR
1791   }
1792   | Types UNDEF {
1793     if (!UpRefs.empty())
1794       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1795     $$ = UndefValue::get($1->get());
1796     delete $1;
1797     CHECK_FOR_ERROR
1798   }
1799   | Types SymbolicValueRef {
1800     if (!UpRefs.empty())
1801       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1802     const PointerType *Ty = dyn_cast<PointerType>($1->get());
1803     if (Ty == 0)
1804       GEN_ERROR("Global const reference must be a pointer type " + (*$1)->getDescription());
1805
1806     // ConstExprs can exist in the body of a function, thus creating
1807     // GlobalValues whenever they refer to a variable.  Because we are in
1808     // the context of a function, getExistingVal will search the functions
1809     // symbol table instead of the module symbol table for the global symbol,
1810     // which throws things all off.  To get around this, we just tell
1811     // getExistingVal that we are at global scope here.
1812     //
1813     Function *SavedCurFn = CurFun.CurrentFunction;
1814     CurFun.CurrentFunction = 0;
1815
1816     Value *V = getExistingVal(Ty, $2);
1817     CHECK_FOR_ERROR
1818
1819     CurFun.CurrentFunction = SavedCurFn;
1820
1821     // If this is an initializer for a constant pointer, which is referencing a
1822     // (currently) undefined variable, create a stub now that shall be replaced
1823     // in the future with the right type of variable.
1824     //
1825     if (V == 0) {
1826       assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1827       const PointerType *PT = cast<PointerType>(Ty);
1828
1829       // First check to see if the forward references value is already created!
1830       PerModuleInfo::GlobalRefsType::iterator I =
1831         CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1832
1833       if (I != CurModule.GlobalRefs.end()) {
1834         V = I->second;             // Placeholder already exists, use it...
1835         $2.destroy();
1836       } else {
1837         std::string Name;
1838         if ($2.Type == ValID::GlobalName)
1839           Name = $2.getName();
1840         else if ($2.Type != ValID::GlobalID)
1841           GEN_ERROR("Invalid reference to global");
1842
1843         // Create the forward referenced global.
1844         GlobalValue *GV;
1845         if (const FunctionType *FTy =
1846                  dyn_cast<FunctionType>(PT->getElementType())) {
1847           GV = Function::Create(FTy, GlobalValue::ExternalWeakLinkage, Name,
1848                                 CurModule.CurrentModule);
1849         } else {
1850           GV = new GlobalVariable(PT->getElementType(), false,
1851                                   GlobalValue::ExternalWeakLinkage, 0,
1852                                   Name, CurModule.CurrentModule);
1853         }
1854
1855         // Keep track of the fact that we have a forward ref to recycle it
1856         CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1857         V = GV;
1858       }
1859     }
1860
1861     $$ = cast<GlobalValue>(V);
1862     delete $1;            // Free the type handle
1863     CHECK_FOR_ERROR
1864   }
1865   | Types ConstExpr {
1866     if (!UpRefs.empty())
1867       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1868     if ($1->get() != $2->getType())
1869       GEN_ERROR("Mismatched types for constant expression: " +
1870         (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1871     $$ = $2;
1872     delete $1;
1873     CHECK_FOR_ERROR
1874   }
1875   | Types ZEROINITIALIZER {
1876     if (!UpRefs.empty())
1877       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1878     const Type *Ty = $1->get();
1879     if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1880       GEN_ERROR("Cannot create a null initialized value of this type");
1881     $$ = Constant::getNullValue(Ty);
1882     delete $1;
1883     CHECK_FOR_ERROR
1884   }
1885   | Types ESINT64VAL {      // integral constants
1886     if (IntegerType *IT = dyn_cast<IntegerType>($1->get())) {
1887       if (!ConstantInt::isValueValidForType(IT, $2))
1888         GEN_ERROR("Constant value doesn't fit in type");
1889       $$ = ConstantInt::get(IT, $2, true);
1890     } else {
1891       GEN_ERROR("integer constant must have integer type");
1892     }
1893     delete $1;
1894     CHECK_FOR_ERROR
1895   }
1896   | Types ESAPINTVAL {      // arbitrary precision integer constants
1897     if (IntegerType *IT = dyn_cast<IntegerType>($1->get())) {
1898       if ($2->getBitWidth() > IT->getBitWidth())
1899         GEN_ERROR("Constant value does not fit in type");
1900       $2->sextOrTrunc(IT->getBitWidth());
1901       $$ = ConstantInt::get(*$2);
1902     } else {
1903       GEN_ERROR("integer constant must have integer type");
1904     }
1905     delete $1;
1906     delete $2;
1907     CHECK_FOR_ERROR
1908   }
1909   | Types EUINT64VAL {      // integral constants
1910     if (IntegerType *IT = dyn_cast<IntegerType>($1->get())) {
1911       if (!ConstantInt::isValueValidForType(IT, $2))
1912         GEN_ERROR("Constant value doesn't fit in type");
1913       $$ = ConstantInt::get(IT, $2, false);
1914     } else {
1915       GEN_ERROR("integer constant must have integer type");
1916     }
1917     delete $1;
1918     CHECK_FOR_ERROR
1919   }
1920   | Types EUAPINTVAL {      // arbitrary precision integer constants
1921     if (IntegerType *IT = dyn_cast<IntegerType>($1->get())) {
1922       if ($2->getBitWidth() > IT->getBitWidth())
1923         GEN_ERROR("Constant value does not fit in type");
1924       $2->zextOrTrunc(IT->getBitWidth());
1925       $$ = ConstantInt::get(*$2);
1926     } else {
1927       GEN_ERROR("integer constant must have integer type");
1928     }
1929
1930     delete $2;
1931     delete $1;
1932     CHECK_FOR_ERROR
1933   }
1934   | Types TRUETOK {                      // Boolean constants
1935     if ($1->get() != Type::Int1Ty)
1936       GEN_ERROR("Constant true must have type i1");
1937     $$ = ConstantInt::getTrue();
1938     delete $1;
1939     CHECK_FOR_ERROR
1940   }
1941   | Types FALSETOK {                     // Boolean constants
1942     if ($1->get() != Type::Int1Ty)
1943       GEN_ERROR("Constant false must have type i1");
1944     $$ = ConstantInt::getFalse();
1945     delete $1;
1946     CHECK_FOR_ERROR
1947   }
1948   | Types FPVAL {                   // Floating point constants
1949     if (!ConstantFP::isValueValidForType($1->get(), *$2))
1950       GEN_ERROR("Floating point constant invalid for type");
1951       
1952     // Lexer has no type info, so builds all float and double FP constants
1953     // as double.  Fix this here.  Long double is done right.
1954     if (&$2->getSemantics()==&APFloat::IEEEdouble && $1->get()==Type::FloatTy) {
1955       bool ignored;
1956       $2->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
1957                   &ignored);
1958     }
1959     $$ = ConstantFP::get(*$2);
1960     delete $1;
1961     delete $2;
1962     CHECK_FOR_ERROR
1963   };
1964
1965
1966 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1967     if (!UpRefs.empty())
1968       GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1969     Constant *Val = $3;
1970     const Type *DestTy = $5->get();
1971     if (!CastInst::castIsValid($1, $3, DestTy))
1972       GEN_ERROR("invalid cast opcode for cast from '" +
1973                 Val->getType()->getDescription() + "' to '" +
1974                 DestTy->getDescription() + "'");
1975     $$ = ConstantExpr::getCast($1, $3, DestTy);
1976     delete $5;
1977   }
1978   | GETELEMENTPTR '(' ConstVal IndexList ')' {
1979     if (!isa<PointerType>($3->getType()))
1980       GEN_ERROR("GetElementPtr requires a pointer operand");
1981
1982     const Type *IdxTy =
1983       GetElementPtrInst::getIndexedType($3->getType(), $4->begin(), $4->end());
1984     if (!IdxTy)
1985       GEN_ERROR("Index list invalid for constant getelementptr");
1986
1987     SmallVector<Constant*, 8> IdxVec;
1988     for (unsigned i = 0, e = $4->size(); i != e; ++i)
1989       if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1990         IdxVec.push_back(C);
1991       else
1992         GEN_ERROR("Indices to constant getelementptr must be constants");
1993
1994     delete $4;
1995
1996     $$ = ConstantExpr::getGetElementPtr($3, &IdxVec[0], IdxVec.size());
1997     CHECK_FOR_ERROR
1998   }
1999   | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2000     if ($3->getType() != Type::Int1Ty)
2001       GEN_ERROR("Select condition must be of boolean type");
2002     if ($5->getType() != $7->getType())
2003       GEN_ERROR("Select operand types must match");
2004     $$ = ConstantExpr::getSelect($3, $5, $7);
2005     CHECK_FOR_ERROR
2006   }
2007   | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
2008     if ($3->getType() != $5->getType())
2009       GEN_ERROR("Binary operator types must match");
2010     CHECK_FOR_ERROR;
2011     $$ = ConstantExpr::get($1, $3, $5);
2012   }
2013   | LogicalOps '(' ConstVal ',' ConstVal ')' {
2014     if ($3->getType() != $5->getType())
2015       GEN_ERROR("Logical operator types must match");
2016     if (!$3->getType()->isInteger()) {
2017       if (!isa<VectorType>($3->getType()) ||
2018           !cast<VectorType>($3->getType())->getElementType()->isInteger())
2019         GEN_ERROR("Logical operator requires integral operands");
2020     }
2021     $$ = ConstantExpr::get($1, $3, $5);
2022     CHECK_FOR_ERROR
2023   }
2024   | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
2025     if ($4->getType() != $6->getType())
2026       GEN_ERROR("icmp operand types must match");
2027     $$ = ConstantExpr::getICmp($2, $4, $6);
2028   }
2029   | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
2030     if ($4->getType() != $6->getType())
2031       GEN_ERROR("fcmp operand types must match");
2032     $$ = ConstantExpr::getFCmp($2, $4, $6);
2033   }
2034   | VICMP IPredicates '(' ConstVal ',' ConstVal ')' {
2035     if ($4->getType() != $6->getType())
2036       GEN_ERROR("vicmp operand types must match");
2037     $$ = ConstantExpr::getVICmp($2, $4, $6);
2038   }
2039   | VFCMP FPredicates '(' ConstVal ',' ConstVal ')' {
2040     if ($4->getType() != $6->getType())
2041       GEN_ERROR("vfcmp operand types must match");
2042     $$ = ConstantExpr::getVFCmp($2, $4, $6);
2043   }
2044   | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
2045     if (!ExtractElementInst::isValidOperands($3, $5))
2046       GEN_ERROR("Invalid extractelement operands");
2047     $$ = ConstantExpr::getExtractElement($3, $5);
2048     CHECK_FOR_ERROR
2049   }
2050   | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2051     if (!InsertElementInst::isValidOperands($3, $5, $7))
2052       GEN_ERROR("Invalid insertelement operands");
2053     $$ = ConstantExpr::getInsertElement($3, $5, $7);
2054     CHECK_FOR_ERROR
2055   }
2056   | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2057     if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
2058       GEN_ERROR("Invalid shufflevector operands");
2059     $$ = ConstantExpr::getShuffleVector($3, $5, $7);
2060     CHECK_FOR_ERROR
2061   }
2062   | EXTRACTVALUE '(' ConstVal ConstantIndexList ')' {
2063     if (!isa<StructType>($3->getType()) && !isa<ArrayType>($3->getType()))
2064       GEN_ERROR("ExtractValue requires an aggregate operand");
2065
2066     $$ = ConstantExpr::getExtractValue($3, &(*$4)[0], $4->size());
2067     delete $4;
2068     CHECK_FOR_ERROR
2069   }
2070   | INSERTVALUE '(' ConstVal ',' ConstVal ConstantIndexList ')' {
2071     if (!isa<StructType>($3->getType()) && !isa<ArrayType>($3->getType()))
2072       GEN_ERROR("InsertValue requires an aggregate operand");
2073
2074     $$ = ConstantExpr::getInsertValue($3, $5, &(*$6)[0], $6->size());
2075     delete $6;
2076     CHECK_FOR_ERROR
2077   };
2078
2079
2080 // ConstVector - A list of comma separated constants.
2081 ConstVector : ConstVector ',' ConstVal {
2082     ($$ = $1)->push_back($3);
2083     CHECK_FOR_ERROR
2084   }
2085   | ConstVal {
2086     $$ = new std::vector<Constant*>();
2087     $$->push_back($1);
2088     CHECK_FOR_ERROR
2089   };
2090
2091
2092 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
2093 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
2094
2095 // ThreadLocal
2096 ThreadLocal : THREAD_LOCAL { $$ = true; } | { $$ = false; };
2097
2098 // AliaseeRef - Match either GlobalValue or bitcast to GlobalValue.
2099 AliaseeRef : ResultTypes SymbolicValueRef {
2100     const Type* VTy = $1->get();
2101     Value *V = getVal(VTy, $2);
2102     CHECK_FOR_ERROR
2103     GlobalValue* Aliasee = dyn_cast<GlobalValue>(V);
2104     if (!Aliasee)
2105       GEN_ERROR("Aliases can be created only to global values");
2106
2107     $$ = Aliasee;
2108     CHECK_FOR_ERROR
2109     delete $1;
2110    }
2111    | BITCAST '(' AliaseeRef TO Types ')' {
2112     Constant *Val = $3;
2113     const Type *DestTy = $5->get();
2114     if (!CastInst::castIsValid($1, $3, DestTy))
2115       GEN_ERROR("invalid cast opcode for cast from '" +
2116                 Val->getType()->getDescription() + "' to '" +
2117                 DestTy->getDescription() + "'");
2118
2119     $$ = ConstantExpr::getCast($1, $3, DestTy);
2120     CHECK_FOR_ERROR
2121     delete $5;
2122    };
2123
2124 //===----------------------------------------------------------------------===//
2125 //                             Rules to match Modules
2126 //===----------------------------------------------------------------------===//
2127
2128 // Module rule: Capture the result of parsing the whole file into a result
2129 // variable...
2130 //
2131 Module
2132   : DefinitionList {
2133     $$ = ParserResult = CurModule.CurrentModule;
2134     CurModule.ModuleDone();
2135     CHECK_FOR_ERROR;
2136   }
2137   | /*empty*/ {
2138     $$ = ParserResult = CurModule.CurrentModule;
2139     CurModule.ModuleDone();
2140     CHECK_FOR_ERROR;
2141   }
2142   ;
2143
2144 DefinitionList
2145   : Definition
2146   | DefinitionList Definition
2147   ;
2148
2149 Definition
2150   : DEFINE { CurFun.isDeclare = false; } Function {
2151     CurFun.FunctionDone();
2152     CHECK_FOR_ERROR
2153   }
2154   | DECLARE { CurFun.isDeclare = true; } FunctionProto {
2155     CHECK_FOR_ERROR
2156   }
2157   | MODULE ASM_TOK AsmBlock {
2158     CHECK_FOR_ERROR
2159   }
2160   | OptLocalAssign TYPE Types {
2161     if (!UpRefs.empty())
2162       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2163     // Eagerly resolve types.  This is not an optimization, this is a
2164     // requirement that is due to the fact that we could have this:
2165     //
2166     // %list = type { %list * }
2167     // %list = type { %list * }    ; repeated type decl
2168     //
2169     // If types are not resolved eagerly, then the two types will not be
2170     // determined to be the same type!
2171     //
2172     ResolveTypeTo($1, *$3);
2173
2174     if (!setTypeName(*$3, $1) && !$1) {
2175       CHECK_FOR_ERROR
2176       // If this is a named type that is not a redefinition, add it to the slot
2177       // table.
2178       CurModule.Types.push_back(*$3);
2179     }
2180
2181     delete $3;
2182     CHECK_FOR_ERROR
2183   }
2184   | OptLocalAssign TYPE VOID {
2185     ResolveTypeTo($1, $3);
2186
2187     if (!setTypeName($3, $1) && !$1) {
2188       CHECK_FOR_ERROR
2189       // If this is a named type that is not a redefinition, add it to the slot
2190       // table.
2191       CurModule.Types.push_back($3);
2192     }
2193     CHECK_FOR_ERROR
2194   }
2195   | OptGlobalAssign GVVisibilityStyle ThreadLocal GlobalType ConstVal
2196     OptAddrSpace {
2197     /* "Externally Visible" Linkage */
2198     if ($5 == 0)
2199       GEN_ERROR("Global value initializer is not a constant");
2200     CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
2201                                 $2, $4, $5->getType(), $5, $3, $6);
2202     CHECK_FOR_ERROR
2203   } GlobalVarAttributes {
2204     CurGV = 0;
2205   }
2206   | OptGlobalAssign GVInternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2207     ConstVal OptAddrSpace {
2208     if ($6 == 0)
2209       GEN_ERROR("Global value initializer is not a constant");
2210     CurGV = ParseGlobalVariable($1, $2, $3, $5, $6->getType(), $6, $4, $7);
2211     CHECK_FOR_ERROR
2212   } GlobalVarAttributes {
2213     CurGV = 0;
2214   }
2215   | OptGlobalAssign GVExternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2216     Types OptAddrSpace {
2217     if (!UpRefs.empty())
2218       GEN_ERROR("Invalid upreference in type: " + (*$6)->getDescription());
2219     CurGV = ParseGlobalVariable($1, $2, $3, $5, *$6, 0, $4, $7);
2220     CHECK_FOR_ERROR
2221     delete $6;
2222   } GlobalVarAttributes {
2223     CurGV = 0;
2224     CHECK_FOR_ERROR
2225   }
2226   | OptGlobalAssign GVVisibilityStyle ALIAS AliasLinkage AliaseeRef {
2227     std::string Name;
2228     if ($1) {
2229       Name = *$1;
2230       delete $1;
2231     }
2232     if (Name.empty())
2233       GEN_ERROR("Alias name cannot be empty");
2234
2235     Constant* Aliasee = $5;
2236     if (Aliasee == 0)
2237       GEN_ERROR(std::string("Invalid aliasee for alias: ") + Name);
2238
2239     GlobalAlias* GA = new GlobalAlias(Aliasee->getType(), $4, Name, Aliasee,
2240                                       CurModule.CurrentModule);
2241     GA->setVisibility($2);
2242     InsertValue(GA, CurModule.Values);
2243
2244
2245     // If there was a forward reference of this alias, resolve it now.
2246
2247     ValID ID;
2248     if (!Name.empty())
2249       ID = ValID::createGlobalName(Name);
2250     else
2251       ID = ValID::createGlobalID(CurModule.Values.size()-1);
2252
2253     if (GlobalValue *FWGV =
2254           CurModule.GetForwardRefForGlobal(GA->getType(), ID)) {
2255       // Replace uses of the fwdref with the actual alias.
2256       FWGV->replaceAllUsesWith(GA);
2257       if (GlobalVariable *GV = dyn_cast<GlobalVariable>(FWGV))
2258         GV->eraseFromParent();
2259       else
2260         cast<Function>(FWGV)->eraseFromParent();
2261     }
2262     ID.destroy();
2263
2264     CHECK_FOR_ERROR
2265   }
2266   | TARGET TargetDefinition {
2267     CHECK_FOR_ERROR
2268   }
2269   | DEPLIBS '=' LibrariesDefinition {
2270     CHECK_FOR_ERROR
2271   }
2272   ;
2273
2274
2275 AsmBlock : STRINGCONSTANT {
2276   const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2277   if (AsmSoFar.empty())
2278     CurModule.CurrentModule->setModuleInlineAsm(*$1);
2279   else
2280     CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+*$1);
2281   delete $1;
2282   CHECK_FOR_ERROR
2283 };
2284
2285 TargetDefinition : TRIPLE '=' STRINGCONSTANT {
2286     CurModule.CurrentModule->setTargetTriple(*$3);
2287     delete $3;
2288   }
2289   | DATALAYOUT '=' STRINGCONSTANT {
2290     CurModule.CurrentModule->setDataLayout(*$3);
2291     delete $3;
2292   };
2293
2294 LibrariesDefinition : '[' LibList ']';
2295
2296 LibList : LibList ',' STRINGCONSTANT {
2297           CurModule.CurrentModule->addLibrary(*$3);
2298           delete $3;
2299           CHECK_FOR_ERROR
2300         }
2301         | STRINGCONSTANT {
2302           CurModule.CurrentModule->addLibrary(*$1);
2303           delete $1;
2304           CHECK_FOR_ERROR
2305         }
2306         | /* empty: end of list */ {
2307           CHECK_FOR_ERROR
2308         }
2309         ;
2310
2311 //===----------------------------------------------------------------------===//
2312 //                       Rules to match Function Headers
2313 //===----------------------------------------------------------------------===//
2314
2315 ArgListH : ArgListH ',' Types OptAttributes OptLocalName {
2316     if (!UpRefs.empty())
2317       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2318     if (!(*$3)->isFirstClassType())
2319       GEN_ERROR("Argument types must be first-class");
2320     ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
2321     $$ = $1;
2322     $1->push_back(E);
2323     CHECK_FOR_ERROR
2324   }
2325   | Types OptAttributes OptLocalName {
2326     if (!UpRefs.empty())
2327       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2328     if (!(*$1)->isFirstClassType())
2329       GEN_ERROR("Argument types must be first-class");
2330     ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2331     $$ = new ArgListType;
2332     $$->push_back(E);
2333     CHECK_FOR_ERROR
2334   };
2335
2336 ArgList : ArgListH {
2337     $$ = $1;
2338     CHECK_FOR_ERROR
2339   }
2340   | ArgListH ',' DOTDOTDOT {
2341     $$ = $1;
2342     struct ArgListEntry E;
2343     E.Ty = new PATypeHolder(Type::VoidTy);
2344     E.Name = 0;
2345     E.Attrs = Attribute::None;
2346     $$->push_back(E);
2347     CHECK_FOR_ERROR
2348   }
2349   | DOTDOTDOT {
2350     $$ = new ArgListType;
2351     struct ArgListEntry E;
2352     E.Ty = new PATypeHolder(Type::VoidTy);
2353     E.Name = 0;
2354     E.Attrs = Attribute::None;
2355     $$->push_back(E);
2356     CHECK_FOR_ERROR
2357   }
2358   | /* empty */ {
2359     $$ = 0;
2360     CHECK_FOR_ERROR
2361   };
2362
2363 FunctionHeaderH : OptCallingConv OptRetAttrs ResultTypes GlobalName '(' ArgList ')'
2364                   OptFuncAttrs OptSection OptAlign OptGC {
2365   std::string FunctionName(*$4);
2366   delete $4;  // Free strdup'd memory!
2367
2368   // Check the function result for abstractness if this is a define. We should
2369   // have no abstract types at this point
2370   if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($3))
2371     GEN_ERROR("Reference to abstract result: "+ $3->get()->getDescription());
2372
2373   if (!FunctionType::isValidReturnType(*$3))
2374     GEN_ERROR("Invalid result type for LLVM function");
2375
2376   std::vector<const Type*> ParamTypeList;
2377   SmallVector<AttributeWithIndex, 8> Attrs;
2378   //FIXME : In 3.0, stop accepting zext, sext and inreg as optional function 
2379   //attributes.
2380   Attributes RetAttrs = $2;
2381   if ($8 != Attribute::None) {
2382     if ($8 & Attribute::ZExt) {
2383       RetAttrs = RetAttrs | Attribute::ZExt;
2384       $8 = $8 ^ Attribute::ZExt;
2385     }
2386     if ($8 & Attribute::SExt) {
2387       RetAttrs = RetAttrs | Attribute::SExt;
2388       $8 = $8 ^ Attribute::SExt;
2389     }
2390     if ($8 & Attribute::InReg) {
2391       RetAttrs = RetAttrs | Attribute::InReg;
2392       $8 = $8 ^ Attribute::InReg;
2393     }
2394   }
2395   if (RetAttrs != Attribute::None)
2396     Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2397   if ($6) {   // If there are arguments...
2398     unsigned index = 1;
2399     for (ArgListType::iterator I = $6->begin(); I != $6->end(); ++I, ++index) {
2400       const Type* Ty = I->Ty->get();
2401       if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2402         GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2403       ParamTypeList.push_back(Ty);
2404       if (Ty != Type::VoidTy && I->Attrs != Attribute::None)
2405         Attrs.push_back(AttributeWithIndex::get(index, I->Attrs));
2406     }
2407   }
2408   if ($8 != Attribute::None)
2409     Attrs.push_back(AttributeWithIndex::get(~0, $8));
2410
2411   bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2412   if (isVarArg) ParamTypeList.pop_back();
2413
2414   AttrListPtr PAL;
2415   if (!Attrs.empty())
2416     PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2417
2418   FunctionType *FT = FunctionType::get(*$3, ParamTypeList, isVarArg);
2419   const PointerType *PFT = PointerType::getUnqual(FT);
2420   delete $3;
2421
2422   ValID ID;
2423   if (!FunctionName.empty()) {
2424     ID = ValID::createGlobalName((char*)FunctionName.c_str());
2425   } else {
2426     ID = ValID::createGlobalID(CurModule.Values.size());
2427   }
2428
2429   Function *Fn = 0;
2430   // See if this function was forward referenced.  If so, recycle the object.
2431   if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2432     // Move the function to the end of the list, from whereever it was
2433     // previously inserted.
2434     Fn = cast<Function>(FWRef);
2435     assert(Fn->getAttributes().isEmpty() &&
2436            "Forward reference has parameter attributes!");
2437     CurModule.CurrentModule->getFunctionList().remove(Fn);
2438     CurModule.CurrentModule->getFunctionList().push_back(Fn);
2439   } else if (!FunctionName.empty() &&     // Merge with an earlier prototype?
2440              (Fn = CurModule.CurrentModule->getFunction(FunctionName))) {
2441     if (Fn->getFunctionType() != FT ) {
2442       // The existing function doesn't have the same type. This is an overload
2443       // error.
2444       GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2445     } else if (Fn->getAttributes() != PAL) {
2446       // The existing function doesn't have the same parameter attributes.
2447       // This is an overload error.
2448       GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2449     } else if (!CurFun.isDeclare && !Fn->isDeclaration()) {
2450       // Neither the existing or the current function is a declaration and they
2451       // have the same name and same type. Clearly this is a redefinition.
2452       GEN_ERROR("Redefinition of function '" + FunctionName + "'");
2453     } else if (Fn->isDeclaration()) {
2454       // Make sure to strip off any argument names so we can't get conflicts.
2455       for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2456            AI != AE; ++AI)
2457         AI->setName("");
2458     }
2459   } else  {  // Not already defined?
2460     Fn = Function::Create(FT, GlobalValue::ExternalWeakLinkage, FunctionName,
2461                           CurModule.CurrentModule);
2462     InsertValue(Fn, CurModule.Values);
2463   }
2464
2465   ID.destroy();
2466   CurFun.FunctionStart(Fn);
2467
2468   if (CurFun.isDeclare) {
2469     // If we have declaration, always overwrite linkage.  This will allow us to
2470     // correctly handle cases, when pointer to function is passed as argument to
2471     // another function.
2472     Fn->setLinkage(CurFun.Linkage);
2473     Fn->setVisibility(CurFun.Visibility);
2474   }
2475   Fn->setCallingConv($1);
2476   Fn->setAttributes(PAL);
2477   Fn->setAlignment($10);
2478   if ($9) {
2479     Fn->setSection(*$9);
2480     delete $9;
2481   }
2482   if ($11) {
2483     Fn->setGC($11->c_str());
2484     delete $11;
2485   }
2486
2487   // Add all of the arguments we parsed to the function...
2488   if ($6) {                     // Is null if empty...
2489     if (isVarArg) {  // Nuke the last entry
2490       assert($6->back().Ty->get() == Type::VoidTy && $6->back().Name == 0 &&
2491              "Not a varargs marker!");
2492       delete $6->back().Ty;
2493       $6->pop_back();  // Delete the last entry
2494     }
2495     Function::arg_iterator ArgIt = Fn->arg_begin();
2496     Function::arg_iterator ArgEnd = Fn->arg_end();
2497     unsigned Idx = 1;
2498     for (ArgListType::iterator I = $6->begin();
2499          I != $6->end() && ArgIt != ArgEnd; ++I, ++ArgIt) {
2500       delete I->Ty;                          // Delete the typeholder...
2501       setValueName(ArgIt, I->Name);       // Insert arg into symtab...
2502       CHECK_FOR_ERROR
2503       InsertValue(ArgIt);
2504       Idx++;
2505     }
2506
2507     delete $6;                     // We're now done with the argument list
2508   }
2509   CHECK_FOR_ERROR
2510 };
2511
2512 BEGIN : BEGINTOK | '{';                // Allow BEGIN or '{' to start a function
2513
2514 FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2515   $$ = CurFun.CurrentFunction;
2516
2517   // Make sure that we keep track of the linkage type even if there was a
2518   // previous "declare".
2519   $$->setLinkage($1);
2520   $$->setVisibility($2);
2521 };
2522
2523 END : ENDTOK | '}';                    // Allow end of '}' to end a function
2524
2525 Function : BasicBlockList END {
2526   $$ = $1;
2527   CHECK_FOR_ERROR
2528 };
2529
2530 FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2531     CurFun.CurrentFunction->setLinkage($1);
2532     CurFun.CurrentFunction->setVisibility($2);
2533     $$ = CurFun.CurrentFunction;
2534     CurFun.FunctionDone();
2535     CHECK_FOR_ERROR
2536   };
2537
2538 //===----------------------------------------------------------------------===//
2539 //                        Rules to match Basic Blocks
2540 //===----------------------------------------------------------------------===//
2541
2542 OptSideEffect : /* empty */ {
2543     $$ = false;
2544     CHECK_FOR_ERROR
2545   }
2546   | SIDEEFFECT {
2547     $$ = true;
2548     CHECK_FOR_ERROR
2549   };
2550
2551 ConstValueRef : ESINT64VAL {    // A reference to a direct constant
2552     $$ = ValID::create($1);
2553     CHECK_FOR_ERROR
2554   }
2555   | EUINT64VAL {
2556     $$ = ValID::create($1);
2557     CHECK_FOR_ERROR
2558   }
2559   | ESAPINTVAL {      // arbitrary precision integer constants
2560     $$ = ValID::create(*$1, true);
2561     delete $1;
2562     CHECK_FOR_ERROR
2563   }
2564   | EUAPINTVAL {      // arbitrary precision integer constants
2565     $$ = ValID::create(*$1, false);
2566     delete $1;
2567     CHECK_FOR_ERROR
2568   }
2569   | FPVAL {                     // Perhaps it's an FP constant?
2570     $$ = ValID::create($1);
2571     CHECK_FOR_ERROR
2572   }
2573   | TRUETOK {
2574     $$ = ValID::create(ConstantInt::getTrue());
2575     CHECK_FOR_ERROR
2576   }
2577   | FALSETOK {
2578     $$ = ValID::create(ConstantInt::getFalse());
2579     CHECK_FOR_ERROR
2580   }
2581   | NULL_TOK {
2582     $$ = ValID::createNull();
2583     CHECK_FOR_ERROR
2584   }
2585   | UNDEF {
2586     $$ = ValID::createUndef();
2587     CHECK_FOR_ERROR
2588   }
2589   | ZEROINITIALIZER {     // A vector zero constant.
2590     $$ = ValID::createZeroInit();
2591     CHECK_FOR_ERROR
2592   }
2593   | '<' ConstVector '>' { // Nonempty unsized packed vector
2594     const Type *ETy = (*$2)[0]->getType();
2595     unsigned NumElements = $2->size();
2596
2597     if (!ETy->isInteger() && !ETy->isFloatingPoint())
2598       GEN_ERROR("Invalid vector element type: " + ETy->getDescription());
2599
2600     VectorType* pt = VectorType::get(ETy, NumElements);
2601     PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(pt));
2602
2603     // Verify all elements are correct type!
2604     for (unsigned i = 0; i < $2->size(); i++) {
2605       if (ETy != (*$2)[i]->getType())
2606         GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2607                      ETy->getDescription() +"' as required!\nIt is of type '" +
2608                      (*$2)[i]->getType()->getDescription() + "'.");
2609     }
2610
2611     $$ = ValID::create(ConstantVector::get(pt, *$2));
2612     delete PTy; delete $2;
2613     CHECK_FOR_ERROR
2614   }
2615   | '[' ConstVector ']' { // Nonempty unsized arr
2616     const Type *ETy = (*$2)[0]->getType();
2617     uint64_t NumElements = $2->size();
2618
2619     if (!ETy->isFirstClassType())
2620       GEN_ERROR("Invalid array element type: " + ETy->getDescription());
2621
2622     ArrayType *ATy = ArrayType::get(ETy, NumElements);
2623     PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(ATy));
2624
2625     // Verify all elements are correct type!
2626     for (unsigned i = 0; i < $2->size(); i++) {
2627       if (ETy != (*$2)[i]->getType())
2628         GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2629                        ETy->getDescription() +"' as required!\nIt is of type '"+
2630                        (*$2)[i]->getType()->getDescription() + "'.");
2631     }
2632
2633     $$ = ValID::create(ConstantArray::get(ATy, *$2));
2634     delete PTy; delete $2;
2635     CHECK_FOR_ERROR
2636   }
2637   | '[' ']' {
2638     // Use undef instead of an array because it's inconvenient to determine
2639     // the element type at this point, there being no elements to examine.
2640     $$ = ValID::createUndef();
2641     CHECK_FOR_ERROR
2642   }
2643   | 'c' STRINGCONSTANT {
2644     uint64_t NumElements = $2->length();
2645     const Type *ETy = Type::Int8Ty;
2646
2647     ArrayType *ATy = ArrayType::get(ETy, NumElements);
2648
2649     std::vector<Constant*> Vals;
2650     for (unsigned i = 0; i < $2->length(); ++i)
2651       Vals.push_back(ConstantInt::get(ETy, (*$2)[i]));
2652     delete $2;
2653     $$ = ValID::create(ConstantArray::get(ATy, Vals));
2654     CHECK_FOR_ERROR
2655   }
2656   | '{' ConstVector '}' {
2657     std::vector<const Type*> Elements($2->size());
2658     for (unsigned i = 0, e = $2->size(); i != e; ++i)
2659       Elements[i] = (*$2)[i]->getType();
2660
2661     const StructType *STy = StructType::get(Elements);
2662     PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(STy));
2663
2664     $$ = ValID::create(ConstantStruct::get(STy, *$2));
2665     delete PTy; delete $2;
2666     CHECK_FOR_ERROR
2667   }
2668   | '{' '}' {
2669     const StructType *STy = StructType::get(std::vector<const Type*>());
2670     $$ = ValID::create(ConstantStruct::get(STy, std::vector<Constant*>()));
2671     CHECK_FOR_ERROR
2672   }
2673   | '<' '{' ConstVector '}' '>' {
2674     std::vector<const Type*> Elements($3->size());
2675     for (unsigned i = 0, e = $3->size(); i != e; ++i)
2676       Elements[i] = (*$3)[i]->getType();
2677
2678     const StructType *STy = StructType::get(Elements, /*isPacked=*/true);
2679     PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(STy));
2680
2681     $$ = ValID::create(ConstantStruct::get(STy, *$3));
2682     delete PTy; delete $3;
2683     CHECK_FOR_ERROR
2684   }
2685   | '<' '{' '}' '>' {
2686     const StructType *STy = StructType::get(std::vector<const Type*>(),
2687                                             /*isPacked=*/true);
2688     $$ = ValID::create(ConstantStruct::get(STy, std::vector<Constant*>()));
2689     CHECK_FOR_ERROR
2690   }
2691   | ConstExpr {
2692     $$ = ValID::create($1);
2693     CHECK_FOR_ERROR
2694   }
2695   | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2696     $$ = ValID::createInlineAsm(*$3, *$5, $2);
2697     delete $3;
2698     delete $5;
2699     CHECK_FOR_ERROR
2700   };
2701
2702 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2703 // another value.
2704 //
2705 SymbolicValueRef : LOCALVAL_ID {  // Is it an integer reference...?
2706     $$ = ValID::createLocalID($1);
2707     CHECK_FOR_ERROR
2708   }
2709   | GLOBALVAL_ID {
2710     $$ = ValID::createGlobalID($1);
2711     CHECK_FOR_ERROR
2712   }
2713   | LocalName {                   // Is it a named reference...?
2714     $$ = ValID::createLocalName(*$1);
2715     delete $1;
2716     CHECK_FOR_ERROR
2717   }
2718   | GlobalName {                   // Is it a named reference...?
2719     $$ = ValID::createGlobalName(*$1);
2720     delete $1;
2721     CHECK_FOR_ERROR
2722   };
2723
2724 // ValueRef - A reference to a definition... either constant or symbolic
2725 ValueRef : SymbolicValueRef | ConstValueRef;
2726
2727
2728 // ResolvedVal - a <type> <value> pair.  This is used only in cases where the
2729 // type immediately preceeds the value reference, and allows complex constant
2730 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2731 ResolvedVal : Types ValueRef {
2732     if (!UpRefs.empty())
2733       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2734     $$ = getVal(*$1, $2);
2735     delete $1;
2736     CHECK_FOR_ERROR
2737   }
2738   ;
2739
2740 ReturnedVal : ResolvedVal {
2741     $$ = new std::vector<Value *>();
2742     $$->push_back($1);
2743     CHECK_FOR_ERROR
2744   }
2745   | ReturnedVal ',' ResolvedVal {
2746     ($$=$1)->push_back($3);
2747     CHECK_FOR_ERROR
2748   };
2749
2750 BasicBlockList : BasicBlockList BasicBlock {
2751     $$ = $1;
2752     CHECK_FOR_ERROR
2753   }
2754   | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2755     $$ = $1;
2756     CHECK_FOR_ERROR
2757   };
2758
2759
2760 // Basic blocks are terminated by branching instructions:
2761 // br, br/cc, switch, ret
2762 //
2763 BasicBlock : InstructionList OptLocalAssign BBTerminatorInst {
2764     setValueName($3, $2);
2765     CHECK_FOR_ERROR
2766     InsertValue($3);
2767     $1->getInstList().push_back($3);
2768     $$ = $1;
2769     CHECK_FOR_ERROR
2770   };
2771
2772 BasicBlock : InstructionList LocalNumber BBTerminatorInst {
2773   CHECK_FOR_ERROR
2774   int ValNum = InsertValue($3);
2775   if (ValNum != (int)$2)
2776     GEN_ERROR("Result value number %" + utostr($2) +
2777               " is incorrect, expected %" + utostr((unsigned)ValNum));
2778
2779   $1->getInstList().push_back($3);
2780   $$ = $1;
2781   CHECK_FOR_ERROR
2782 };
2783
2784
2785 InstructionList : InstructionList Inst {
2786     if (CastInst *CI1 = dyn_cast<CastInst>($2))
2787       if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2788         if (CI2->getParent() == 0)
2789           $1->getInstList().push_back(CI2);
2790     $1->getInstList().push_back($2);
2791     $$ = $1;
2792     CHECK_FOR_ERROR
2793   }
2794   | /* empty */ {          // Empty space between instruction lists
2795     $$ = defineBBVal(ValID::createLocalID(CurFun.NextValNum));
2796     CHECK_FOR_ERROR
2797   }
2798   | LABELSTR {             // Labelled (named) basic block
2799     $$ = defineBBVal(ValID::createLocalName(*$1));
2800     delete $1;
2801     CHECK_FOR_ERROR
2802
2803   };
2804
2805 BBTerminatorInst :
2806   RET ReturnedVal  { // Return with a result...
2807     ValueList &VL = *$2;
2808     assert(!VL.empty() && "Invalid ret operands!");
2809     const Type *ReturnType = CurFun.CurrentFunction->getReturnType();
2810     if (VL.size() > 1 ||
2811         (isa<StructType>(ReturnType) &&
2812          (VL.empty() || VL[0]->getType() != ReturnType))) {
2813       Value *RV = UndefValue::get(ReturnType);
2814       for (unsigned i = 0, e = VL.size(); i != e; ++i) {
2815         Instruction *I = InsertValueInst::Create(RV, VL[i], i, "mrv");
2816         ($<BasicBlockVal>-1)->getInstList().push_back(I);
2817         RV = I;
2818       }
2819       $$ = ReturnInst::Create(RV);
2820     } else {
2821       $$ = ReturnInst::Create(VL[0]);
2822     }
2823     delete $2;
2824     CHECK_FOR_ERROR
2825   }
2826   | RET VOID {                                    // Return with no result...
2827     $$ = ReturnInst::Create();
2828     CHECK_FOR_ERROR
2829   }
2830   | BR LABEL ValueRef {                           // Unconditional Branch...
2831     BasicBlock* tmpBB = getBBVal($3);
2832     CHECK_FOR_ERROR
2833     $$ = BranchInst::Create(tmpBB);
2834   }                                               // Conditional Branch...
2835   | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2836     if (cast<IntegerType>($2)->getBitWidth() != 1)
2837       GEN_ERROR("Branch condition must have type i1");
2838     BasicBlock* tmpBBA = getBBVal($6);
2839     CHECK_FOR_ERROR
2840     BasicBlock* tmpBBB = getBBVal($9);
2841     CHECK_FOR_ERROR
2842     Value* tmpVal = getVal(Type::Int1Ty, $3);
2843     CHECK_FOR_ERROR
2844     $$ = BranchInst::Create(tmpBBA, tmpBBB, tmpVal);
2845   }
2846   | SWITCH INTTYPE ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2847     Value* tmpVal = getVal($2, $3);
2848     CHECK_FOR_ERROR
2849     BasicBlock* tmpBB = getBBVal($6);
2850     CHECK_FOR_ERROR
2851     SwitchInst *S = SwitchInst::Create(tmpVal, tmpBB, $8->size());
2852     $$ = S;
2853
2854     std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2855       E = $8->end();
2856     for (; I != E; ++I) {
2857       if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2858           S->addCase(CI, I->second);
2859       else
2860         GEN_ERROR("Switch case is constant, but not a simple integer");
2861     }
2862     delete $8;
2863     CHECK_FOR_ERROR
2864   }
2865   | SWITCH INTTYPE ValueRef ',' LABEL ValueRef '[' ']' {
2866     Value* tmpVal = getVal($2, $3);
2867     CHECK_FOR_ERROR
2868     BasicBlock* tmpBB = getBBVal($6);
2869     CHECK_FOR_ERROR
2870     SwitchInst *S = SwitchInst::Create(tmpVal, tmpBB, 0);
2871     $$ = S;
2872     CHECK_FOR_ERROR
2873   }
2874   | INVOKE OptCallingConv OptRetAttrs ResultTypes ValueRef '(' ParamList ')' 
2875     OptFuncAttrs TO LABEL ValueRef UNWIND LABEL ValueRef {
2876
2877     // Handle the short syntax
2878     const PointerType *PFTy = 0;
2879     const FunctionType *Ty = 0;
2880     if (!(PFTy = dyn_cast<PointerType>($4->get())) ||
2881         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2882       // Pull out the types of all of the arguments...
2883       std::vector<const Type*> ParamTypes;
2884       ParamList::iterator I = $7->begin(), E = $7->end();
2885       for (; I != E; ++I) {
2886         const Type *Ty = I->Val->getType();
2887         if (Ty == Type::VoidTy)
2888           GEN_ERROR("Short call syntax cannot be used with varargs");
2889         ParamTypes.push_back(Ty);
2890       }
2891
2892       if (!FunctionType::isValidReturnType(*$4))
2893         GEN_ERROR("Invalid result type for LLVM function");
2894
2895       Ty = FunctionType::get($4->get(), ParamTypes, false);
2896       PFTy = PointerType::getUnqual(Ty);
2897     }
2898
2899     delete $4;
2900
2901     Value *V = getVal(PFTy, $5);   // Get the function we're calling...
2902     CHECK_FOR_ERROR
2903     BasicBlock *Normal = getBBVal($12);
2904     CHECK_FOR_ERROR
2905     BasicBlock *Except = getBBVal($15);
2906     CHECK_FOR_ERROR
2907
2908     SmallVector<AttributeWithIndex, 8> Attrs;
2909     //FIXME : In 3.0, stop accepting zext, sext and inreg as optional function 
2910     //attributes.
2911     Attributes RetAttrs = $3;
2912     if ($9 != Attribute::None) {
2913       if ($9 & Attribute::ZExt) {
2914         RetAttrs = RetAttrs | Attribute::ZExt;
2915         $9 = $9 ^ Attribute::ZExt;
2916       }
2917       if ($9 & Attribute::SExt) {
2918         RetAttrs = RetAttrs | Attribute::SExt;
2919         $9 = $9 ^ Attribute::SExt;
2920       }
2921       if ($9 & Attribute::InReg) {
2922         RetAttrs = RetAttrs | Attribute::InReg;
2923         $9 = $9 ^ Attribute::InReg;
2924       }
2925     }
2926     if (RetAttrs != Attribute::None)
2927       Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2928     
2929     // Check the arguments
2930     ValueList Args;
2931     if ($7->empty()) {                                   // Has no arguments?
2932       // Make sure no arguments is a good thing!
2933       if (Ty->getNumParams() != 0)
2934         GEN_ERROR("No arguments passed to a function that "
2935                        "expects arguments");
2936     } else {                                     // Has arguments?
2937       // Loop through FunctionType's arguments and ensure they are specified
2938       // correctly!
2939       FunctionType::param_iterator I = Ty->param_begin();
2940       FunctionType::param_iterator E = Ty->param_end();
2941       ParamList::iterator ArgI = $7->begin(), ArgE = $7->end();
2942       unsigned index = 1;
2943
2944       for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
2945         if (ArgI->Val->getType() != *I)
2946           GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2947                          (*I)->getDescription() + "'");
2948         Args.push_back(ArgI->Val);
2949         if (ArgI->Attrs != Attribute::None)
2950           Attrs.push_back(AttributeWithIndex::get(index, ArgI->Attrs));
2951       }
2952
2953       if (Ty->isVarArg()) {
2954         if (I == E)
2955           for (; ArgI != ArgE; ++ArgI, ++index) {
2956             Args.push_back(ArgI->Val); // push the remaining varargs
2957             if (ArgI->Attrs != Attribute::None)
2958               Attrs.push_back(AttributeWithIndex::get(index, ArgI->Attrs));
2959           }
2960       } else if (I != E || ArgI != ArgE)
2961         GEN_ERROR("Invalid number of parameters detected");
2962     }
2963     if ($9 != Attribute::None)
2964       Attrs.push_back(AttributeWithIndex::get(~0, $9));
2965     AttrListPtr PAL;
2966     if (!Attrs.empty())
2967       PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2968
2969     // Create the InvokeInst
2970     InvokeInst *II = InvokeInst::Create(V, Normal, Except,
2971                                         Args.begin(), Args.end());
2972     II->setCallingConv($2);
2973     II->setAttributes(PAL);
2974     $$ = II;
2975     delete $7;
2976     CHECK_FOR_ERROR
2977   }
2978   | UNWIND {
2979     $$ = new UnwindInst();
2980     CHECK_FOR_ERROR
2981   }
2982   | UNREACHABLE {
2983     $$ = new UnreachableInst();
2984     CHECK_FOR_ERROR
2985   };
2986
2987
2988
2989 JumpTable : JumpTable INTTYPE ConstValueRef ',' LABEL ValueRef {
2990     $$ = $1;
2991     Constant *V = cast<Constant>(getExistingVal($2, $3));
2992     CHECK_FOR_ERROR
2993     if (V == 0)
2994       GEN_ERROR("May only switch on a constant pool value");
2995
2996     BasicBlock* tmpBB = getBBVal($6);
2997     CHECK_FOR_ERROR
2998     $$->push_back(std::make_pair(V, tmpBB));
2999   }
3000   | INTTYPE ConstValueRef ',' LABEL ValueRef {
3001     $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
3002     Constant *V = cast<Constant>(getExistingVal($1, $2));
3003     CHECK_FOR_ERROR
3004
3005     if (V == 0)
3006       GEN_ERROR("May only switch on a constant pool value");
3007
3008     BasicBlock* tmpBB = getBBVal($5);
3009     CHECK_FOR_ERROR
3010     $$->push_back(std::make_pair(V, tmpBB));
3011   };
3012
3013 Inst : OptLocalAssign InstVal {
3014     // Is this definition named?? if so, assign the name...
3015     setValueName($2, $1);
3016     CHECK_FOR_ERROR
3017     InsertValue($2);
3018     $$ = $2;
3019     CHECK_FOR_ERROR
3020   };
3021
3022 Inst : LocalNumber InstVal {
3023     CHECK_FOR_ERROR
3024     int ValNum = InsertValue($2);
3025
3026     if (ValNum != (int)$1)
3027       GEN_ERROR("Result value number %" + utostr($1) +
3028                 " is incorrect, expected %" + utostr((unsigned)ValNum));
3029
3030     $$ = $2;
3031     CHECK_FOR_ERROR
3032   };
3033
3034
3035 PHIList : Types '[' ValueRef ',' ValueRef ']' {    // Used for PHI nodes
3036     if (!UpRefs.empty())
3037       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
3038     $$ = new std::list<std::pair<Value*, BasicBlock*> >();
3039     Value* tmpVal = getVal(*$1, $3);
3040     CHECK_FOR_ERROR
3041     BasicBlock* tmpBB = getBBVal($5);
3042     CHECK_FOR_ERROR
3043     $$->push_back(std::make_pair(tmpVal, tmpBB));
3044     delete $1;
3045   }
3046   | PHIList ',' '[' ValueRef ',' ValueRef ']' {
3047     $$ = $1;
3048     Value* tmpVal = getVal($1->front().first->getType(), $4);
3049     CHECK_FOR_ERROR
3050     BasicBlock* tmpBB = getBBVal($6);
3051     CHECK_FOR_ERROR
3052     $1->push_back(std::make_pair(tmpVal, tmpBB));
3053   };
3054
3055
3056 ParamList : Types OptAttributes ValueRef OptAttributes {
3057     // FIXME: Remove trailing OptAttributes in LLVM 3.0, it was a mistake in 2.0
3058     if (!UpRefs.empty())
3059       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
3060     // Used for call and invoke instructions
3061     $$ = new ParamList();
3062     ParamListEntry E; E.Attrs = $2 | $4; E.Val = getVal($1->get(), $3);
3063     $$->push_back(E);
3064     delete $1;
3065     CHECK_FOR_ERROR
3066   }
3067   | LABEL OptAttributes ValueRef OptAttributes {
3068     // FIXME: Remove trailing OptAttributes in LLVM 3.0, it was a mistake in 2.0
3069     // Labels are only valid in ASMs
3070     $$ = new ParamList();
3071     ParamListEntry E; E.Attrs = $2 | $4; E.Val = getBBVal($3);
3072     $$->push_back(E);
3073     CHECK_FOR_ERROR
3074   }
3075   | ParamList ',' Types OptAttributes ValueRef OptAttributes {
3076     // FIXME: Remove trailing OptAttributes in LLVM 3.0, it was a mistake in 2.0
3077     if (!UpRefs.empty())
3078       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3079     $$ = $1;
3080     ParamListEntry E; E.Attrs = $4 | $6; E.Val = getVal($3->get(), $5);
3081     $$->push_back(E);
3082     delete $3;
3083     CHECK_FOR_ERROR
3084   }
3085   | ParamList ',' LABEL OptAttributes ValueRef OptAttributes {
3086     // FIXME: Remove trailing OptAttributes in LLVM 3.0, it was a mistake in 2.0
3087     $$ = $1;
3088     ParamListEntry E; E.Attrs = $4 | $6; E.Val = getBBVal($5);
3089     $$->push_back(E);
3090     CHECK_FOR_ERROR
3091   }
3092   | /*empty*/ { $$ = new ParamList(); };
3093
3094 IndexList       // Used for gep instructions and constant expressions
3095   : /*empty*/ { $$ = new std::vector<Value*>(); }
3096   | IndexList ',' ResolvedVal {
3097     $$ = $1;
3098     $$->push_back($3);
3099     CHECK_FOR_ERROR
3100   }
3101   ;
3102
3103 ConstantIndexList       // Used for insertvalue and extractvalue instructions
3104   : ',' EUINT64VAL {
3105     $$ = new std::vector<unsigned>();
3106     if ((unsigned)$2 != $2)
3107       GEN_ERROR("Index " + utostr($2) + " is not valid for insertvalue or extractvalue.");
3108     $$->push_back($2);
3109   }
3110   | ConstantIndexList ',' EUINT64VAL {
3111     $$ = $1;
3112     if ((unsigned)$3 != $3)
3113       GEN_ERROR("Index " + utostr($3) + " is not valid for insertvalue or extractvalue.");
3114     $$->push_back($3);
3115     CHECK_FOR_ERROR
3116   }
3117   ;
3118
3119 OptTailCall : TAIL CALL {
3120     $$ = true;
3121     CHECK_FOR_ERROR
3122   }
3123   | CALL {
3124     $$ = false;
3125     CHECK_FOR_ERROR
3126   };
3127
3128 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
3129     if (!UpRefs.empty())
3130       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3131     if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
3132         !isa<VectorType>((*$2).get()))
3133       GEN_ERROR(
3134         "Arithmetic operator requires integer, FP, or packed operands");
3135     Value* val1 = getVal(*$2, $3);
3136     CHECK_FOR_ERROR
3137     Value* val2 = getVal(*$2, $5);
3138     CHECK_FOR_ERROR
3139     $$ = BinaryOperator::Create($1, val1, val2);
3140     if ($$ == 0)
3141       GEN_ERROR("binary operator returned null");
3142     delete $2;
3143   }
3144   | LogicalOps Types ValueRef ',' ValueRef {
3145     if (!UpRefs.empty())
3146       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3147     if (!(*$2)->isInteger()) {
3148       if (!isa<VectorType>($2->get()) ||
3149           !cast<VectorType>($2->get())->getElementType()->isInteger())
3150         GEN_ERROR("Logical operator requires integral operands");
3151     }
3152     Value* tmpVal1 = getVal(*$2, $3);
3153     CHECK_FOR_ERROR
3154     Value* tmpVal2 = getVal(*$2, $5);
3155     CHECK_FOR_ERROR
3156     $$ = BinaryOperator::Create($1, tmpVal1, tmpVal2);
3157     if ($$ == 0)
3158       GEN_ERROR("binary operator returned null");
3159     delete $2;
3160   }
3161   | ICMP IPredicates Types ValueRef ',' ValueRef  {
3162     if (!UpRefs.empty())
3163       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3164     Value* tmpVal1 = getVal(*$3, $4);
3165     CHECK_FOR_ERROR
3166     Value* tmpVal2 = getVal(*$3, $6);
3167     CHECK_FOR_ERROR
3168     $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3169     if ($$ == 0)
3170       GEN_ERROR("icmp operator returned null");
3171     delete $3;
3172   }
3173   | FCMP FPredicates Types ValueRef ',' ValueRef  {
3174     if (!UpRefs.empty())
3175       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3176     Value* tmpVal1 = getVal(*$3, $4);
3177     CHECK_FOR_ERROR
3178     Value* tmpVal2 = getVal(*$3, $6);
3179     CHECK_FOR_ERROR
3180     $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3181     if ($$ == 0)
3182       GEN_ERROR("fcmp operator returned null");
3183     delete $3;
3184   }
3185   | VICMP IPredicates Types ValueRef ',' ValueRef  {
3186     if (!UpRefs.empty())
3187       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3188     if (!isa<VectorType>((*$3).get()))
3189       GEN_ERROR("Scalar types not supported by vicmp instruction");
3190     Value* tmpVal1 = getVal(*$3, $4);
3191     CHECK_FOR_ERROR
3192     Value* tmpVal2 = getVal(*$3, $6);
3193     CHECK_FOR_ERROR
3194     $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3195     if ($$ == 0)
3196       GEN_ERROR("vicmp operator returned null");
3197     delete $3;
3198   }
3199   | VFCMP FPredicates Types ValueRef ',' ValueRef  {
3200     if (!UpRefs.empty())
3201       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3202     if (!isa<VectorType>((*$3).get()))
3203       GEN_ERROR("Scalar types not supported by vfcmp instruction");
3204     Value* tmpVal1 = getVal(*$3, $4);
3205     CHECK_FOR_ERROR
3206     Value* tmpVal2 = getVal(*$3, $6);
3207     CHECK_FOR_ERROR
3208     $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3209     if ($$ == 0)
3210       GEN_ERROR("vfcmp operator returned null");
3211     delete $3;
3212   }
3213   | CastOps ResolvedVal TO Types {
3214     if (!UpRefs.empty())
3215       GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
3216     Value* Val = $2;
3217     const Type* DestTy = $4->get();
3218     if (!CastInst::castIsValid($1, Val, DestTy))
3219       GEN_ERROR("invalid cast opcode for cast from '" +
3220                 Val->getType()->getDescription() + "' to '" +
3221                 DestTy->getDescription() + "'");
3222     $$ = CastInst::Create($1, Val, DestTy);
3223     delete $4;
3224   }
3225   | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3226     if (isa<VectorType>($2->getType())) {
3227       // vector select
3228       if (!isa<VectorType>($4->getType())
3229       || !isa<VectorType>($6->getType()) )
3230         GEN_ERROR("vector select value types must be vector types");
3231       const VectorType* cond_type = cast<VectorType>($2->getType());
3232       const VectorType* select_type = cast<VectorType>($4->getType());
3233       if (cond_type->getElementType() != Type::Int1Ty)
3234         GEN_ERROR("vector select condition element type must be boolean");
3235       if (cond_type->getNumElements() != select_type->getNumElements())
3236         GEN_ERROR("vector select number of elements must be the same");
3237     } else {
3238       if ($2->getType() != Type::Int1Ty)
3239         GEN_ERROR("select condition must be boolean");
3240     }
3241     if ($4->getType() != $6->getType())
3242       GEN_ERROR("select value types must match");
3243     $$ = SelectInst::Create($2, $4, $6);
3244     CHECK_FOR_ERROR
3245   }
3246   | VAARG ResolvedVal ',' Types {
3247     if (!UpRefs.empty())
3248       GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
3249     $$ = new VAArgInst($2, *$4);
3250     delete $4;
3251     CHECK_FOR_ERROR
3252   }
3253   | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
3254     if (!ExtractElementInst::isValidOperands($2, $4))
3255       GEN_ERROR("Invalid extractelement operands");
3256     $$ = new ExtractElementInst($2, $4);
3257     CHECK_FOR_ERROR
3258   }
3259   | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3260     if (!InsertElementInst::isValidOperands($2, $4, $6))
3261       GEN_ERROR("Invalid insertelement operands");
3262     $$ = InsertElementInst::Create($2, $4, $6);
3263     CHECK_FOR_ERROR
3264   }
3265   | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3266     if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
3267       GEN_ERROR("Invalid shufflevector operands");
3268     $$ = new ShuffleVectorInst($2, $4, $6);
3269     CHECK_FOR_ERROR
3270   }
3271   | PHI_TOK PHIList {
3272     const Type *Ty = $2->front().first->getType();
3273     if (!Ty->isFirstClassType())
3274       GEN_ERROR("PHI node operands must be of first class type");
3275     $$ = PHINode::Create(Ty);
3276     ((PHINode*)$$)->reserveOperandSpace($2->size());
3277     while ($2->begin() != $2->end()) {
3278       if ($2->front().first->getType() != Ty)
3279         GEN_ERROR("All elements of a PHI node must be of the same type");
3280       cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
3281       $2->pop_front();
3282     }
3283     delete $2;  // Free the list...
3284     CHECK_FOR_ERROR
3285   }
3286   | OptTailCall OptCallingConv OptRetAttrs ResultTypes ValueRef '(' ParamList ')'
3287     OptFuncAttrs {
3288
3289     // Handle the short syntax
3290     const PointerType *PFTy = 0;
3291     const FunctionType *Ty = 0;
3292     if (!(PFTy = dyn_cast<PointerType>($4->get())) ||
3293         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3294       // Pull out the types of all of the arguments...
3295       std::vector<const Type*> ParamTypes;
3296       ParamList::iterator I = $7->begin(), E = $7->end();
3297       for (; I != E; ++I) {
3298         const Type *Ty = I->Val->getType();
3299         if (Ty == Type::VoidTy)
3300           GEN_ERROR("Short call syntax cannot be used with varargs");
3301         ParamTypes.push_back(Ty);
3302       }
3303
3304       if (!FunctionType::isValidReturnType(*$4))
3305         GEN_ERROR("Invalid result type for LLVM function");
3306
3307       Ty = FunctionType::get($4->get(), ParamTypes, false);
3308       PFTy = PointerType::getUnqual(Ty);
3309     }
3310
3311     Value *V = getVal(PFTy, $5);   // Get the function we're calling...
3312     CHECK_FOR_ERROR
3313
3314     // Check for call to invalid intrinsic to avoid crashing later.
3315     if (Function *theF = dyn_cast<Function>(V)) {
3316       if (theF->hasName() && (theF->getValueName()->getKeyLength() >= 5) &&
3317           (0 == strncmp(theF->getValueName()->getKeyData(), "llvm.", 5)) &&
3318           !theF->getIntrinsicID(true))
3319         GEN_ERROR("Call to invalid LLVM intrinsic function '" +
3320                   theF->getName() + "'");
3321     }
3322
3323     // Set up the Attributes for the function
3324     SmallVector<AttributeWithIndex, 8> Attrs;
3325     //FIXME : In 3.0, stop accepting zext, sext and inreg as optional function 
3326     //attributes.
3327     Attributes RetAttrs = $3;
3328     if ($9 != Attribute::None) {
3329       if ($9 & Attribute::ZExt) {
3330         RetAttrs = RetAttrs | Attribute::ZExt;
3331         $9 = $9 ^ Attribute::ZExt;
3332       }
3333       if ($9 & Attribute::SExt) {
3334         RetAttrs = RetAttrs | Attribute::SExt;
3335         $9 = $9 ^ Attribute::SExt;
3336       }
3337       if ($9 & Attribute::InReg) {
3338         RetAttrs = RetAttrs | Attribute::InReg;
3339         $9 = $9 ^ Attribute::InReg;
3340       }
3341     }
3342     if (RetAttrs != Attribute::None)
3343       Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3344     
3345     // Check the arguments
3346     ValueList Args;
3347     if ($7->empty()) {                                   // Has no arguments?
3348       // Make sure no arguments is a good thing!
3349       if (Ty->getNumParams() != 0)
3350         GEN_ERROR("No arguments passed to a function that "
3351                        "expects arguments");
3352     } else {                                     // Has arguments?
3353       // Loop through FunctionType's arguments and ensure they are specified
3354       // correctly.  Also, gather any parameter attributes.
3355       FunctionType::param_iterator I = Ty->param_begin();
3356       FunctionType::param_iterator E = Ty->param_end();
3357       ParamList::iterator ArgI = $7->begin(), ArgE = $7->end();
3358       unsigned index = 1;
3359
3360       for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
3361         if (ArgI->Val->getType() != *I)
3362           GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
3363                          (*I)->getDescription() + "'");
3364         Args.push_back(ArgI->Val);
3365         if (ArgI->Attrs != Attribute::None)
3366           Attrs.push_back(AttributeWithIndex::get(index, ArgI->Attrs));
3367       }
3368       if (Ty->isVarArg()) {
3369         if (I == E)
3370           for (; ArgI != ArgE; ++ArgI, ++index) {
3371             Args.push_back(ArgI->Val); // push the remaining varargs
3372             if (ArgI->Attrs != Attribute::None)
3373               Attrs.push_back(AttributeWithIndex::get(index, ArgI->Attrs));
3374           }
3375       } else if (I != E || ArgI != ArgE)
3376         GEN_ERROR("Invalid number of parameters detected");
3377     }
3378     if ($9 != Attribute::None)
3379       Attrs.push_back(AttributeWithIndex::get(~0, $9));
3380
3381     // Finish off the Attributes and check them
3382     AttrListPtr PAL;
3383     if (!Attrs.empty())
3384       PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3385
3386     // Create the call node
3387     CallInst *CI = CallInst::Create(V, Args.begin(), Args.end());
3388     CI->setTailCall($1);
3389     CI->setCallingConv($2);
3390     CI->setAttributes(PAL);
3391     $$ = CI;
3392     delete $7;
3393     delete $4;
3394     CHECK_FOR_ERROR
3395   }
3396   | MemoryInst {
3397     $$ = $1;
3398     CHECK_FOR_ERROR
3399   };
3400
3401 OptVolatile : VOLATILE {
3402     $$ = true;
3403     CHECK_FOR_ERROR
3404   }
3405   | /* empty */ {
3406     $$ = false;
3407     CHECK_FOR_ERROR
3408   };
3409
3410
3411
3412 MemoryInst : MALLOC Types OptCAlign {
3413     if (!UpRefs.empty())
3414       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3415     $$ = new MallocInst(*$2, 0, $3);
3416     delete $2;
3417     CHECK_FOR_ERROR
3418   }
3419   | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
3420     if (!UpRefs.empty())
3421       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3422     if ($4 != Type::Int32Ty)
3423       GEN_ERROR("Malloc array size is not a 32-bit integer!");
3424     Value* tmpVal = getVal($4, $5);
3425     CHECK_FOR_ERROR
3426     $$ = new MallocInst(*$2, tmpVal, $6);
3427     delete $2;
3428   }
3429   | ALLOCA Types OptCAlign {
3430     if (!UpRefs.empty())
3431       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3432     $$ = new AllocaInst(*$2, 0, $3);
3433     delete $2;
3434     CHECK_FOR_ERROR
3435   }
3436   | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
3437     if (!UpRefs.empty())
3438       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3439     if ($4 != Type::Int32Ty)
3440       GEN_ERROR("Alloca array size is not a 32-bit integer!");
3441     Value* tmpVal = getVal($4, $5);
3442     CHECK_FOR_ERROR
3443     $$ = new AllocaInst(*$2, tmpVal, $6);
3444     delete $2;
3445   }
3446   | FREE ResolvedVal {
3447     if (!isa<PointerType>($2->getType()))
3448       GEN_ERROR("Trying to free nonpointer type " +
3449                      $2->getType()->getDescription() + "");
3450     $$ = new FreeInst($2);
3451     CHECK_FOR_ERROR
3452   }
3453
3454   | OptVolatile LOAD Types ValueRef OptCAlign {
3455     if (!UpRefs.empty())
3456       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3457     if (!isa<PointerType>($3->get()))
3458       GEN_ERROR("Can't load from nonpointer type: " +
3459                      (*$3)->getDescription());
3460     if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
3461       GEN_ERROR("Can't load from pointer of non-first-class type: " +
3462                      (*$3)->getDescription());
3463     Value* tmpVal = getVal(*$3, $4);
3464     CHECK_FOR_ERROR
3465     $$ = new LoadInst(tmpVal, "", $1, $5);
3466     delete $3;
3467   }
3468   | OptVolatile STORE ResolvedVal ',' Types ValueRef OptCAlign {
3469     if (!UpRefs.empty())
3470       GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
3471     const PointerType *PT = dyn_cast<PointerType>($5->get());
3472     if (!PT)
3473       GEN_ERROR("Can't store to a nonpointer type: " +
3474                      (*$5)->getDescription());
3475     const Type *ElTy = PT->getElementType();
3476     if (ElTy != $3->getType())
3477       GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
3478                      "' into space of type '" + ElTy->getDescription() + "'");
3479
3480     Value* tmpVal = getVal(*$5, $6);
3481     CHECK_FOR_ERROR
3482     $$ = new StoreInst($3, tmpVal, $1, $7);
3483     delete $5;
3484   }
3485   | GETRESULT Types ValueRef ',' EUINT64VAL  {
3486     if (!UpRefs.empty())
3487       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3488     if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3489       GEN_ERROR("getresult insn requires an aggregate operand");
3490     if (!ExtractValueInst::getIndexedType(*$2, $5))
3491       GEN_ERROR("Invalid getresult index for type '" +
3492                      (*$2)->getDescription()+ "'");
3493
3494     Value *tmpVal = getVal(*$2, $3);
3495     CHECK_FOR_ERROR
3496     $$ = ExtractValueInst::Create(tmpVal, $5);
3497     delete $2;
3498   }
3499   | GETELEMENTPTR Types ValueRef IndexList {
3500     if (!UpRefs.empty())
3501       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3502     if (!isa<PointerType>($2->get()))
3503       GEN_ERROR("getelementptr insn requires pointer operand");
3504
3505     if (!GetElementPtrInst::getIndexedType(*$2, $4->begin(), $4->end()))
3506       GEN_ERROR("Invalid getelementptr indices for type '" +
3507                      (*$2)->getDescription()+ "'");
3508     Value* tmpVal = getVal(*$2, $3);
3509     CHECK_FOR_ERROR
3510     $$ = GetElementPtrInst::Create(tmpVal, $4->begin(), $4->end());
3511     delete $2;
3512     delete $4;
3513   }
3514   | EXTRACTVALUE Types ValueRef ConstantIndexList {
3515     if (!UpRefs.empty())
3516       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3517     if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3518       GEN_ERROR("extractvalue insn requires an aggregate operand");
3519
3520     if (!ExtractValueInst::getIndexedType(*$2, $4->begin(), $4->end()))
3521       GEN_ERROR("Invalid extractvalue indices for type '" +
3522                      (*$2)->getDescription()+ "'");
3523     Value* tmpVal = getVal(*$2, $3);
3524     CHECK_FOR_ERROR
3525     $$ = ExtractValueInst::Create(tmpVal, $4->begin(), $4->end());
3526     delete $2;
3527     delete $4;
3528   }
3529   | INSERTVALUE Types ValueRef ',' Types ValueRef ConstantIndexList {
3530     if (!UpRefs.empty())
3531       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3532     if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3533       GEN_ERROR("extractvalue insn requires an aggregate operand");
3534
3535     if (ExtractValueInst::getIndexedType(*$2, $7->begin(), $7->end()) != $5->get())
3536       GEN_ERROR("Invalid insertvalue indices for type '" +
3537                      (*$2)->getDescription()+ "'");
3538     Value* aggVal = getVal(*$2, $3);
3539     Value* tmpVal = getVal(*$5, $6);
3540     CHECK_FOR_ERROR
3541     $$ = InsertValueInst::Create(aggVal, tmpVal, $7->begin(), $7->end());
3542     delete $2;
3543     delete $5;
3544     delete $7;
3545   };
3546
3547
3548 %%
3549
3550 // common code from the two 'RunVMAsmParser' functions
3551 static Module* RunParser(Module * M) {
3552   CurModule.CurrentModule = M;
3553   // Check to make sure the parser succeeded
3554   if (yyparse()) {
3555     if (ParserResult)
3556       delete ParserResult;
3557     return 0;
3558   }
3559
3560   // Emit an error if there are any unresolved types left.
3561   if (!CurModule.LateResolveTypes.empty()) {
3562     const ValID &DID = CurModule.LateResolveTypes.begin()->first;
3563     if (DID.Type == ValID::LocalName) {
3564       GenerateError("Undefined type remains at eof: '"+DID.getName() + "'");
3565     } else {
3566       GenerateError("Undefined type remains at eof: #" + itostr(DID.Num));
3567     }
3568     if (ParserResult)
3569       delete ParserResult;
3570     return 0;
3571   }
3572
3573   // Emit an error if there are any unresolved values left.
3574   if (!CurModule.LateResolveValues.empty()) {
3575     Value *V = CurModule.LateResolveValues.back();
3576     std::map<Value*, std::pair<ValID, int> >::iterator I =
3577       CurModule.PlaceHolderInfo.find(V);
3578
3579     if (I != CurModule.PlaceHolderInfo.end()) {
3580       ValID &DID = I->second.first;
3581       if (DID.Type == ValID::LocalName) {
3582         GenerateError("Undefined value remains at eof: "+DID.getName() + "'");
3583       } else {
3584         GenerateError("Undefined value remains at eof: #" + itostr(DID.Num));
3585       }
3586       if (ParserResult)
3587         delete ParserResult;
3588       return 0;
3589     }
3590   }
3591
3592   // Check to make sure that parsing produced a result
3593   if (!ParserResult)
3594     return 0;
3595
3596   // Reset ParserResult variable while saving its value for the result.
3597   Module *Result = ParserResult;
3598   ParserResult = 0;
3599
3600   return Result;
3601 }
3602
3603 void llvm::GenerateError(const std::string &message, int LineNo) {
3604   if (LineNo == -1) LineNo = LLLgetLineNo();
3605   // TODO: column number in exception
3606   if (TheParseError)
3607     TheParseError->setError(LLLgetFilename(), message, LineNo);
3608   TriggerError = 1;
3609 }
3610
3611 int yyerror(const char *ErrorMsg) {
3612   std::string where = LLLgetFilename() + ":" + utostr(LLLgetLineNo()) + ": ";
3613   std::string errMsg = where + "error: " + std::string(ErrorMsg);
3614   if (yychar != YYEMPTY && yychar != 0) {
3615     errMsg += " while reading token: '";
3616     errMsg += std::string(LLLgetTokenStart(),
3617                           LLLgetTokenStart()+LLLgetTokenLength()) + "'";
3618   }
3619   GenerateError(errMsg);
3620   return 0;
3621 }