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