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