Add a comment about the mechanisms used to rid AsmParser of exceptions.
[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->isAbstract()) return ty;
718   PATypeHolder Ty(ty);
719   UR_OUT("Type '" << Ty->getDescription() <<
720          "' newly formed.  Resolving upreferences.\n" <<
721          UpRefs.size() << " upreferences active!\n");
722
723   // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
724   // to zero), we resolve them all together before we resolve them to Ty.  At
725   // the end of the loop, if there is anything to resolve to Ty, it will be in
726   // this variable.
727   OpaqueType *TypeToResolve = 0;
728
729   for (unsigned i = 0; i != UpRefs.size(); ++i) {
730     UR_OUT("  UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
731            << UpRefs[i].second->getDescription() << ") = "
732            << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
733     if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
734       // Decrement level of upreference
735       unsigned Level = --UpRefs[i].NestingLevel;
736       UpRefs[i].LastContainedTy = Ty;
737       UR_OUT("  Uplevel Ref Level = " << Level << "\n");
738       if (Level == 0) {                     // Upreference should be resolved!
739         if (!TypeToResolve) {
740           TypeToResolve = UpRefs[i].UpRefTy;
741         } else {
742           UR_OUT("  * Resolving upreference for "
743                  << UpRefs[i].second->getDescription() << "\n";
744                  std::string OldName = UpRefs[i].UpRefTy->getDescription());
745           UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
746           UR_OUT("  * Type '" << OldName << "' refined upreference to: "
747                  << (const void*)Ty << ", " << Ty->getDescription() << "\n");
748         }
749         UpRefs.erase(UpRefs.begin()+i);     // Remove from upreference list...
750         --i;                                // Do not skip the next element...
751       }
752     }
753   }
754
755   if (TypeToResolve) {
756     UR_OUT("  * Resolving upreference for "
757            << UpRefs[i].second->getDescription() << "\n";
758            std::string OldName = TypeToResolve->getDescription());
759     TypeToResolve->refineAbstractTypeTo(Ty);
760   }
761
762   return Ty;
763 }
764
765
766 // common code from the two 'RunVMAsmParser' functions
767  static Module * RunParser(Module * M) {
768
769   llvmAsmlineno = 1;      // Reset the current line number...
770   ObsoleteVarArgs = false;
771   NewVarArgs = false;
772
773   CurModule.CurrentModule = M;
774   yyparse();       // Parse the file, potentially throwing exception
775   if (!ParserResult)
776     return 0;
777
778   Module *Result = ParserResult;
779   ParserResult = 0;
780
781   //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
782   {
783     Function* F;
784     if ((F = Result->getNamedFunction("llvm.va_start"))
785         && F->getFunctionType()->getNumParams() == 0)
786       ObsoleteVarArgs = true;
787     if((F = Result->getNamedFunction("llvm.va_copy"))
788        && F->getFunctionType()->getNumParams() == 1)
789       ObsoleteVarArgs = true;
790   }
791
792   if (ObsoleteVarArgs && NewVarArgs)
793     GenerateError("This file is corrupt: it uses both new and old style varargs");
794
795   if(ObsoleteVarArgs) {
796     if(Function* F = Result->getNamedFunction("llvm.va_start")) {
797       if (F->arg_size() != 0)
798         GenerateError("Obsolete va_start takes 0 argument!");
799       
800       //foo = va_start()
801       // ->
802       //bar = alloca typeof(foo)
803       //va_start(bar)
804       //foo = load bar
805
806       const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
807       const Type* ArgTy = F->getFunctionType()->getReturnType();
808       const Type* ArgTyPtr = PointerType::get(ArgTy);
809       Function* NF = Result->getOrInsertFunction("llvm.va_start", 
810                                                  RetTy, ArgTyPtr, (Type *)0);
811
812       while (!F->use_empty()) {
813         CallInst* CI = cast<CallInst>(F->use_back());
814         AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
815         new CallInst(NF, bar, "", CI);
816         Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
817         CI->replaceAllUsesWith(foo);
818         CI->getParent()->getInstList().erase(CI);
819       }
820       Result->getFunctionList().erase(F);
821     }
822     
823     if(Function* F = Result->getNamedFunction("llvm.va_end")) {
824       if(F->arg_size() != 1)
825         GenerateError("Obsolete va_end takes 1 argument!");
826
827       //vaend foo
828       // ->
829       //bar = alloca 1 of typeof(foo)
830       //vaend bar
831       const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
832       const Type* ArgTy = F->getFunctionType()->getParamType(0);
833       const Type* ArgTyPtr = PointerType::get(ArgTy);
834       Function* NF = Result->getOrInsertFunction("llvm.va_end", 
835                                                  RetTy, ArgTyPtr, (Type *)0);
836
837       while (!F->use_empty()) {
838         CallInst* CI = cast<CallInst>(F->use_back());
839         AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
840         new StoreInst(CI->getOperand(1), bar, CI);
841         new CallInst(NF, bar, "", CI);
842         CI->getParent()->getInstList().erase(CI);
843       }
844       Result->getFunctionList().erase(F);
845     }
846
847     if(Function* F = Result->getNamedFunction("llvm.va_copy")) {
848       if(F->arg_size() != 1)
849         GenerateError("Obsolete va_copy takes 1 argument!");
850       //foo = vacopy(bar)
851       // ->
852       //a = alloca 1 of typeof(foo)
853       //b = alloca 1 of typeof(foo)
854       //store bar -> b
855       //vacopy(a, b)
856       //foo = load a
857       
858       const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
859       const Type* ArgTy = F->getFunctionType()->getReturnType();
860       const Type* ArgTyPtr = PointerType::get(ArgTy);
861       Function* NF = Result->getOrInsertFunction("llvm.va_copy", 
862                                                  RetTy, ArgTyPtr, ArgTyPtr,
863                                                  (Type *)0);
864
865       while (!F->use_empty()) {
866         CallInst* CI = cast<CallInst>(F->use_back());
867         AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
868         AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
869         new StoreInst(CI->getOperand(1), b, CI);
870         new CallInst(NF, a, b, "", CI);
871         Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
872         CI->replaceAllUsesWith(foo);
873         CI->getParent()->getInstList().erase(CI);
874       }
875       Result->getFunctionList().erase(F);
876     }
877   }
878
879   return Result;
880
881  }
882
883 //===----------------------------------------------------------------------===//
884 //            RunVMAsmParser - Define an interface to this parser
885 //===----------------------------------------------------------------------===//
886 //
887 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
888   set_scan_file(F);
889
890   CurFilename = Filename;
891   return RunParser(new Module(CurFilename));
892 }
893
894 Module *llvm::RunVMAsmParser(const char * AsmString, Module * M) {
895   set_scan_string(AsmString);
896
897   CurFilename = "from_memory";
898   if (M == NULL) {
899     return RunParser(new Module (CurFilename));
900   } else {
901     return RunParser(M);
902   }
903 }
904
905 %}
906
907 %union {
908   llvm::Module                           *ModuleVal;
909   llvm::Function                         *FunctionVal;
910   std::pair<llvm::PATypeHolder*, char*>  *ArgVal;
911   llvm::BasicBlock                       *BasicBlockVal;
912   llvm::TerminatorInst                   *TermInstVal;
913   llvm::Instruction                      *InstVal;
914   llvm::Constant                         *ConstVal;
915
916   const llvm::Type                       *PrimType;
917   llvm::PATypeHolder                     *TypeVal;
918   llvm::Value                            *ValueVal;
919
920   std::vector<std::pair<llvm::PATypeHolder*,char*> > *ArgList;
921   std::vector<llvm::Value*>              *ValueList;
922   std::list<llvm::PATypeHolder>          *TypeList;
923   // Represent the RHS of PHI node
924   std::list<std::pair<llvm::Value*,
925                       llvm::BasicBlock*> > *PHIList;
926   std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
927   std::vector<llvm::Constant*>           *ConstVector;
928
929   llvm::GlobalValue::LinkageTypes         Linkage;
930   int64_t                           SInt64Val;
931   uint64_t                          UInt64Val;
932   int                               SIntVal;
933   unsigned                          UIntVal;
934   double                            FPVal;
935   bool                              BoolVal;
936
937   char                             *StrVal;   // This memory is strdup'd!
938   llvm::ValID                             ValIDVal; // strdup'd memory maybe!
939
940   llvm::Instruction::BinaryOps            BinaryOpVal;
941   llvm::Instruction::TermOps              TermOpVal;
942   llvm::Instruction::MemoryOps            MemOpVal;
943   llvm::Instruction::OtherOps             OtherOpVal;
944   llvm::Module::Endianness                Endianness;
945 }
946
947 %type <ModuleVal>     Module FunctionList
948 %type <FunctionVal>   Function FunctionProto FunctionHeader BasicBlockList
949 %type <BasicBlockVal> BasicBlock InstructionList
950 %type <TermInstVal>   BBTerminatorInst
951 %type <InstVal>       Inst InstVal MemoryInst
952 %type <ConstVal>      ConstVal ConstExpr
953 %type <ConstVector>   ConstVector
954 %type <ArgList>       ArgList ArgListH
955 %type <ArgVal>        ArgVal
956 %type <PHIList>       PHIList
957 %type <ValueList>     ValueRefList ValueRefListE  // For call param lists
958 %type <ValueList>     IndexList                   // For GEP derived indices
959 %type <TypeList>      TypeListI ArgTypeListI
960 %type <JumpTable>     JumpTable
961 %type <BoolVal>       GlobalType                  // GLOBAL or CONSTANT?
962 %type <BoolVal>       OptVolatile                 // 'volatile' or not
963 %type <BoolVal>       OptTailCall                 // TAIL CALL or plain CALL.
964 %type <BoolVal>       OptSideEffect               // 'sideeffect' or not.
965 %type <Linkage>       OptLinkage
966 %type <Endianness>    BigOrLittle
967
968 // ValueRef - Unresolved reference to a definition or BB
969 %type <ValIDVal>      ValueRef ConstValueRef SymbolicValueRef
970 %type <ValueVal>      ResolvedVal            // <type> <valref> pair
971 // Tokens and types for handling constant integer values
972 //
973 // ESINT64VAL - A negative number within long long range
974 %token <SInt64Val> ESINT64VAL
975
976 // EUINT64VAL - A positive number within uns. long long range
977 %token <UInt64Val> EUINT64VAL
978 %type  <SInt64Val> EINT64VAL
979
980 %token  <SIntVal>   SINTVAL   // Signed 32 bit ints...
981 %token  <UIntVal>   UINTVAL   // Unsigned 32 bit ints...
982 %type   <SIntVal>   INTVAL
983 %token  <FPVal>     FPVAL     // Float or Double constant
984
985 // Built in types...
986 %type  <TypeVal> Types TypesV UpRTypes UpRTypesV
987 %type  <PrimType> SIntType UIntType IntType FPType PrimType   // Classifications
988 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
989 %token <PrimType> FLOAT DOUBLE TYPE LABEL
990
991 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
992 %type  <StrVal> Name OptName OptAssign
993 %type  <UIntVal> OptAlign OptCAlign
994 %type <StrVal> OptSection SectionString
995
996 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
997 %token DECLARE GLOBAL CONSTANT SECTION VOLATILE
998 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK  APPENDING
999 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
1000 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1001 %token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
1002 %type <UIntVal> OptCallingConv
1003
1004 // Basic Block Terminating Operators
1005 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1006
1007 // Binary Operators
1008 %type  <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
1009 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
1010 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE  // Binary Comarators
1011
1012 // Memory Instructions
1013 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1014
1015 // Other Operators
1016 %type  <OtherOpVal> ShiftOps
1017 %token <OtherOpVal> PHI_TOK CAST SELECT SHL SHR VAARG
1018 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1019 %token VAARG_old VANEXT_old //OBSOLETE
1020
1021
1022 %start Module
1023 %%
1024
1025 // Handle constant integer size restriction and conversion...
1026 //
1027 INTVAL : SINTVAL;
1028 INTVAL : UINTVAL {
1029   if ($1 > (uint32_t)INT32_MAX)     // Outside of my range!
1030     GEN_ERROR("Value too large for type!");
1031   $$ = (int32_t)$1;
1032   CHECK_FOR_ERROR
1033 };
1034
1035
1036 EINT64VAL : ESINT64VAL;      // These have same type and can't cause problems...
1037 EINT64VAL : EUINT64VAL {
1038   if ($1 > (uint64_t)INT64_MAX)     // Outside of my range!
1039     GEN_ERROR("Value too large for type!");
1040   $$ = (int64_t)$1;
1041   CHECK_FOR_ERROR
1042 };
1043
1044 // Operations that are notably excluded from this list include:
1045 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1046 //
1047 ArithmeticOps: ADD | SUB | MUL | DIV | REM;
1048 LogicalOps   : AND | OR | XOR;
1049 SetCondOps   : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
1050
1051 ShiftOps  : SHL | SHR;
1052
1053 // These are some types that allow classification if we only want a particular 
1054 // thing... for example, only a signed, unsigned, or integral type.
1055 SIntType :  LONG |  INT |  SHORT | SBYTE;
1056 UIntType : ULONG | UINT | USHORT | UBYTE;
1057 IntType  : SIntType | UIntType;
1058 FPType   : FLOAT | DOUBLE;
1059
1060 // OptAssign - Value producing statements have an optional assignment component
1061 OptAssign : Name '=' {
1062     $$ = $1;
1063     CHECK_FOR_ERROR
1064   }
1065   | /*empty*/ {
1066     $$ = 0;
1067     CHECK_FOR_ERROR
1068   };
1069
1070 OptLinkage : INTERNAL  { $$ = GlobalValue::InternalLinkage; } |
1071              LINKONCE  { $$ = GlobalValue::LinkOnceLinkage; } |
1072              WEAK      { $$ = GlobalValue::WeakLinkage; } |
1073              APPENDING { $$ = GlobalValue::AppendingLinkage; } |
1074              /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
1075
1076 OptCallingConv : /*empty*/      { $$ = CallingConv::C; } |
1077                  CCC_TOK        { $$ = CallingConv::C; } |
1078                  CSRETCC_TOK    { $$ = CallingConv::CSRet; } |
1079                  FASTCC_TOK     { $$ = CallingConv::Fast; } |
1080                  COLDCC_TOK     { $$ = CallingConv::Cold; } |
1081                  CC_TOK EUINT64VAL {
1082                    if ((unsigned)$2 != $2)
1083                      GEN_ERROR("Calling conv too large!");
1084                    $$ = $2;
1085                   CHECK_FOR_ERROR
1086                  };
1087
1088 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1089 // a comma before it.
1090 OptAlign : /*empty*/        { $$ = 0; } |
1091            ALIGN EUINT64VAL {
1092   $$ = $2;
1093   if ($$ != 0 && !isPowerOf2_32($$))
1094     GEN_ERROR("Alignment must be a power of two!");
1095   CHECK_FOR_ERROR
1096 };
1097 OptCAlign : /*empty*/            { $$ = 0; } |
1098             ',' ALIGN EUINT64VAL {
1099   $$ = $3;
1100   if ($$ != 0 && !isPowerOf2_32($$))
1101     GEN_ERROR("Alignment must be a power of two!");
1102   CHECK_FOR_ERROR
1103 };
1104
1105
1106 SectionString : SECTION STRINGCONSTANT {
1107   for (unsigned i = 0, e = strlen($2); i != e; ++i)
1108     if ($2[i] == '"' || $2[i] == '\\')
1109       GEN_ERROR("Invalid character in section name!");
1110   $$ = $2;
1111   CHECK_FOR_ERROR
1112 };
1113
1114 OptSection : /*empty*/ { $$ = 0; } |
1115              SectionString { $$ = $1; };
1116
1117 // GlobalVarAttributes - Used to pass the attributes string on a global.  CurGV
1118 // is set to be the global we are processing.
1119 //
1120 GlobalVarAttributes : /* empty */ {} |
1121                      ',' GlobalVarAttribute GlobalVarAttributes {};
1122 GlobalVarAttribute : SectionString {
1123     CurGV->setSection($1);
1124     free($1);
1125     CHECK_FOR_ERROR
1126   } 
1127   | ALIGN EUINT64VAL {
1128     if ($2 != 0 && !isPowerOf2_32($2))
1129       GEN_ERROR("Alignment must be a power of two!");
1130     CurGV->setAlignment($2);
1131     CHECK_FOR_ERROR
1132   };
1133
1134 //===----------------------------------------------------------------------===//
1135 // Types includes all predefined types... except void, because it can only be
1136 // used in specific contexts (function returning void for example).  To have
1137 // access to it, a user must explicitly use TypesV.
1138 //
1139
1140 // TypesV includes all of 'Types', but it also includes the void type.
1141 TypesV    : Types    | VOID { $$ = new PATypeHolder($1); };
1142 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
1143
1144 Types     : UpRTypes {
1145     if (!UpRefs.empty())
1146       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1147     $$ = $1;
1148     CHECK_FOR_ERROR
1149   };
1150
1151
1152 // Derived types are added later...
1153 //
1154 PrimType : BOOL | SBYTE | UBYTE | SHORT  | USHORT | INT   | UINT ;
1155 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE   | LABEL;
1156 UpRTypes : OPAQUE {
1157     $$ = new PATypeHolder(OpaqueType::get());
1158     CHECK_FOR_ERROR
1159   }
1160   | PrimType {
1161     $$ = new PATypeHolder($1);
1162     CHECK_FOR_ERROR
1163   };
1164 UpRTypes : SymbolicValueRef {            // Named types are also simple types...
1165   $$ = new PATypeHolder(getTypeVal($1));
1166   CHECK_FOR_ERROR
1167 };
1168
1169 // Include derived types in the Types production.
1170 //
1171 UpRTypes : '\\' EUINT64VAL {                   // Type UpReference
1172     if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range!");
1173     OpaqueType *OT = OpaqueType::get();        // Use temporary placeholder
1174     UpRefs.push_back(UpRefRecord((unsigned)$2, OT));  // Add to vector...
1175     $$ = new PATypeHolder(OT);
1176     UR_OUT("New Upreference!\n");
1177     CHECK_FOR_ERROR
1178   }
1179   | UpRTypesV '(' ArgTypeListI ')' {           // Function derived type?
1180     std::vector<const Type*> Params;
1181     for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1182            E = $3->end(); I != E; ++I)
1183       Params.push_back(*I);
1184     bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1185     if (isVarArg) Params.pop_back();
1186
1187     $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
1188     delete $3;      // Delete the argument list
1189     delete $1;      // Delete the return type handle
1190     CHECK_FOR_ERROR
1191   }
1192   | '[' EUINT64VAL 'x' UpRTypes ']' {          // Sized array type?
1193     $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1194     delete $4;
1195     CHECK_FOR_ERROR
1196   }
1197   | '<' EUINT64VAL 'x' UpRTypes '>' {          // Packed array type?
1198      const llvm::Type* ElemTy = $4->get();
1199      if ((unsigned)$2 != $2)
1200         GEN_ERROR("Unsigned result not equal to signed result");
1201      if (!ElemTy->isPrimitiveType())
1202         GEN_ERROR("Elemental type of a PackedType must be primitive");
1203      if (!isPowerOf2_32($2))
1204        GEN_ERROR("Vector length should be a power of 2!");
1205      $$ = new PATypeHolder(HandleUpRefs(PackedType::get(*$4, (unsigned)$2)));
1206      delete $4;
1207      CHECK_FOR_ERROR
1208   }
1209   | '{' TypeListI '}' {                        // Structure type?
1210     std::vector<const Type*> Elements;
1211     for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1212            E = $2->end(); I != E; ++I)
1213       Elements.push_back(*I);
1214
1215     $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1216     delete $2;
1217     CHECK_FOR_ERROR
1218   }
1219   | '{' '}' {                                  // Empty structure type?
1220     $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1221     CHECK_FOR_ERROR
1222   }
1223   | UpRTypes '*' {                             // Pointer type?
1224     $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1225     delete $1;
1226     CHECK_FOR_ERROR
1227   };
1228
1229 // TypeList - Used for struct declarations and as a basis for function type 
1230 // declaration type lists
1231 //
1232 TypeListI : UpRTypes {
1233     $$ = new std::list<PATypeHolder>();
1234     $$->push_back(*$1); delete $1;
1235     CHECK_FOR_ERROR
1236   }
1237   | TypeListI ',' UpRTypes {
1238     ($$=$1)->push_back(*$3); delete $3;
1239     CHECK_FOR_ERROR
1240   };
1241
1242 // ArgTypeList - List of types for a function type declaration...
1243 ArgTypeListI : TypeListI
1244   | TypeListI ',' DOTDOTDOT {
1245     ($$=$1)->push_back(Type::VoidTy);
1246     CHECK_FOR_ERROR
1247   }
1248   | DOTDOTDOT {
1249     ($$ = new std::list<PATypeHolder>())->push_back(Type::VoidTy);
1250     CHECK_FOR_ERROR
1251   }
1252   | /*empty*/ {
1253     $$ = new std::list<PATypeHolder>();
1254     CHECK_FOR_ERROR
1255   };
1256
1257 // ConstVal - The various declarations that go into the constant pool.  This
1258 // production is used ONLY to represent constants that show up AFTER a 'const',
1259 // 'constant' or 'global' token at global scope.  Constants that can be inlined
1260 // into other expressions (such as integers and constexprs) are handled by the
1261 // ResolvedVal, ValueRef and ConstValueRef productions.
1262 //
1263 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1264     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1265     if (ATy == 0)
1266       GEN_ERROR("Cannot make array constant with type: '" + 
1267                      (*$1)->getDescription() + "'!");
1268     const Type *ETy = ATy->getElementType();
1269     int NumElements = ATy->getNumElements();
1270
1271     // Verify that we have the correct size...
1272     if (NumElements != -1 && NumElements != (int)$3->size())
1273       GEN_ERROR("Type mismatch: constant sized array initialized with " +
1274                      utostr($3->size()) +  " arguments, but has size of " + 
1275                      itostr(NumElements) + "!");
1276
1277     // Verify all elements are correct type!
1278     for (unsigned i = 0; i < $3->size(); i++) {
1279       if (ETy != (*$3)[i]->getType())
1280         GEN_ERROR("Element #" + utostr(i) + " is not of type '" + 
1281                        ETy->getDescription() +"' as required!\nIt is of type '"+
1282                        (*$3)[i]->getType()->getDescription() + "'.");
1283     }
1284
1285     $$ = ConstantArray::get(ATy, *$3);
1286     delete $1; delete $3;
1287     CHECK_FOR_ERROR
1288   }
1289   | Types '[' ']' {
1290     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1291     if (ATy == 0)
1292       GEN_ERROR("Cannot make array constant with type: '" + 
1293                      (*$1)->getDescription() + "'!");
1294
1295     int NumElements = ATy->getNumElements();
1296     if (NumElements != -1 && NumElements != 0) 
1297       GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1298                      " arguments, but has size of " + itostr(NumElements) +"!");
1299     $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1300     delete $1;
1301     CHECK_FOR_ERROR
1302   }
1303   | Types 'c' STRINGCONSTANT {
1304     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1305     if (ATy == 0)
1306       GEN_ERROR("Cannot make array constant with type: '" + 
1307                      (*$1)->getDescription() + "'!");
1308
1309     int NumElements = ATy->getNumElements();
1310     const Type *ETy = ATy->getElementType();
1311     char *EndStr = UnEscapeLexed($3, true);
1312     if (NumElements != -1 && NumElements != (EndStr-$3))
1313       GEN_ERROR("Can't build string constant of size " + 
1314                      itostr((int)(EndStr-$3)) +
1315                      " when array has size " + itostr(NumElements) + "!");
1316     std::vector<Constant*> Vals;
1317     if (ETy == Type::SByteTy) {
1318       for (signed char *C = (signed char *)$3; C != (signed char *)EndStr; ++C)
1319         Vals.push_back(ConstantSInt::get(ETy, *C));
1320     } else if (ETy == Type::UByteTy) {
1321       for (unsigned char *C = (unsigned char *)$3; 
1322            C != (unsigned char*)EndStr; ++C)
1323         Vals.push_back(ConstantUInt::get(ETy, *C));
1324     } else {
1325       free($3);
1326       GEN_ERROR("Cannot build string arrays of non byte sized elements!");
1327     }
1328     free($3);
1329     $$ = ConstantArray::get(ATy, Vals);
1330     delete $1;
1331     CHECK_FOR_ERROR
1332   }
1333   | Types '<' ConstVector '>' { // Nonempty unsized arr
1334     const PackedType *PTy = dyn_cast<PackedType>($1->get());
1335     if (PTy == 0)
1336       GEN_ERROR("Cannot make packed constant with type: '" + 
1337                      (*$1)->getDescription() + "'!");
1338     const Type *ETy = PTy->getElementType();
1339     int NumElements = PTy->getNumElements();
1340
1341     // Verify that we have the correct size...
1342     if (NumElements != -1 && NumElements != (int)$3->size())
1343       GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1344                      utostr($3->size()) +  " arguments, but has size of " + 
1345                      itostr(NumElements) + "!");
1346
1347     // Verify all elements are correct type!
1348     for (unsigned i = 0; i < $3->size(); i++) {
1349       if (ETy != (*$3)[i]->getType())
1350         GEN_ERROR("Element #" + utostr(i) + " is not of type '" + 
1351            ETy->getDescription() +"' as required!\nIt is of type '"+
1352            (*$3)[i]->getType()->getDescription() + "'.");
1353     }
1354
1355     $$ = ConstantPacked::get(PTy, *$3);
1356     delete $1; delete $3;
1357     CHECK_FOR_ERROR
1358   }
1359   | Types '{' ConstVector '}' {
1360     const StructType *STy = dyn_cast<StructType>($1->get());
1361     if (STy == 0)
1362       GEN_ERROR("Cannot make struct constant with type: '" + 
1363                      (*$1)->getDescription() + "'!");
1364
1365     if ($3->size() != STy->getNumContainedTypes())
1366       GEN_ERROR("Illegal number of initializers for structure type!");
1367
1368     // Check to ensure that constants are compatible with the type initializer!
1369     for (unsigned i = 0, e = $3->size(); i != e; ++i)
1370       if ((*$3)[i]->getType() != STy->getElementType(i))
1371         GEN_ERROR("Expected type '" +
1372                        STy->getElementType(i)->getDescription() +
1373                        "' for element #" + utostr(i) +
1374                        " of structure initializer!");
1375
1376     $$ = ConstantStruct::get(STy, *$3);
1377     delete $1; delete $3;
1378     CHECK_FOR_ERROR
1379   }
1380   | Types '{' '}' {
1381     const StructType *STy = dyn_cast<StructType>($1->get());
1382     if (STy == 0)
1383       GEN_ERROR("Cannot make struct constant with type: '" + 
1384                      (*$1)->getDescription() + "'!");
1385
1386     if (STy->getNumContainedTypes() != 0)
1387       GEN_ERROR("Illegal number of initializers for structure type!");
1388
1389     $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1390     delete $1;
1391     CHECK_FOR_ERROR
1392   }
1393   | Types NULL_TOK {
1394     const PointerType *PTy = dyn_cast<PointerType>($1->get());
1395     if (PTy == 0)
1396       GEN_ERROR("Cannot make null pointer constant with type: '" + 
1397                      (*$1)->getDescription() + "'!");
1398
1399     $$ = ConstantPointerNull::get(PTy);
1400     delete $1;
1401     CHECK_FOR_ERROR
1402   }
1403   | Types UNDEF {
1404     $$ = UndefValue::get($1->get());
1405     delete $1;
1406     CHECK_FOR_ERROR
1407   }
1408   | Types SymbolicValueRef {
1409     const PointerType *Ty = dyn_cast<PointerType>($1->get());
1410     if (Ty == 0)
1411       GEN_ERROR("Global const reference must be a pointer type!");
1412
1413     // ConstExprs can exist in the body of a function, thus creating
1414     // GlobalValues whenever they refer to a variable.  Because we are in
1415     // the context of a function, getValNonImprovising will search the functions
1416     // symbol table instead of the module symbol table for the global symbol,
1417     // which throws things all off.  To get around this, we just tell
1418     // getValNonImprovising that we are at global scope here.
1419     //
1420     Function *SavedCurFn = CurFun.CurrentFunction;
1421     CurFun.CurrentFunction = 0;
1422
1423     Value *V = getValNonImprovising(Ty, $2);
1424
1425     CurFun.CurrentFunction = SavedCurFn;
1426
1427     // If this is an initializer for a constant pointer, which is referencing a
1428     // (currently) undefined variable, create a stub now that shall be replaced
1429     // in the future with the right type of variable.
1430     //
1431     if (V == 0) {
1432       assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1433       const PointerType *PT = cast<PointerType>(Ty);
1434
1435       // First check to see if the forward references value is already created!
1436       PerModuleInfo::GlobalRefsType::iterator I =
1437         CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1438     
1439       if (I != CurModule.GlobalRefs.end()) {
1440         V = I->second;             // Placeholder already exists, use it...
1441         $2.destroy();
1442       } else {
1443         std::string Name;
1444         if ($2.Type == ValID::NameVal) Name = $2.Name;
1445
1446         // Create the forward referenced global.
1447         GlobalValue *GV;
1448         if (const FunctionType *FTy = 
1449                  dyn_cast<FunctionType>(PT->getElementType())) {
1450           GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1451                             CurModule.CurrentModule);
1452         } else {
1453           GV = new GlobalVariable(PT->getElementType(), false,
1454                                   GlobalValue::ExternalLinkage, 0,
1455                                   Name, CurModule.CurrentModule);
1456         }
1457
1458         // Keep track of the fact that we have a forward ref to recycle it
1459         CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1460         V = GV;
1461       }
1462     }
1463
1464     $$ = cast<GlobalValue>(V);
1465     delete $1;            // Free the type handle
1466     CHECK_FOR_ERROR
1467   }
1468   | Types ConstExpr {
1469     if ($1->get() != $2->getType())
1470       GEN_ERROR("Mismatched types for constant expression!");
1471     $$ = $2;
1472     delete $1;
1473     CHECK_FOR_ERROR
1474   }
1475   | Types ZEROINITIALIZER {
1476     const Type *Ty = $1->get();
1477     if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1478       GEN_ERROR("Cannot create a null initialized value of this type!");
1479     $$ = Constant::getNullValue(Ty);
1480     delete $1;
1481     CHECK_FOR_ERROR
1482   };
1483
1484 ConstVal : SIntType EINT64VAL {      // integral constants
1485     if (!ConstantSInt::isValueValidForType($1, $2))
1486       GEN_ERROR("Constant value doesn't fit in type!");
1487     $$ = ConstantSInt::get($1, $2);
1488     CHECK_FOR_ERROR
1489   }
1490   | UIntType EUINT64VAL {            // integral constants
1491     if (!ConstantUInt::isValueValidForType($1, $2))
1492       GEN_ERROR("Constant value doesn't fit in type!");
1493     $$ = ConstantUInt::get($1, $2);
1494     CHECK_FOR_ERROR
1495   }
1496   | BOOL TRUETOK {                      // Boolean constants
1497     $$ = ConstantBool::True;
1498     CHECK_FOR_ERROR
1499   }
1500   | BOOL FALSETOK {                     // Boolean constants
1501     $$ = ConstantBool::False;
1502     CHECK_FOR_ERROR
1503   }
1504   | FPType FPVAL {                   // Float & Double constants
1505     if (!ConstantFP::isValueValidForType($1, $2))
1506       GEN_ERROR("Floating point constant invalid for type!!");
1507     $$ = ConstantFP::get($1, $2);
1508     CHECK_FOR_ERROR
1509   };
1510
1511
1512 ConstExpr: CAST '(' ConstVal TO Types ')' {
1513     if (!$3->getType()->isFirstClassType())
1514       GEN_ERROR("cast constant expression from a non-primitive type: '" +
1515                      $3->getType()->getDescription() + "'!");
1516     if (!$5->get()->isFirstClassType())
1517       GEN_ERROR("cast constant expression to a non-primitive type: '" +
1518                      $5->get()->getDescription() + "'!");
1519     $$ = ConstantExpr::getCast($3, $5->get());
1520     delete $5;
1521     CHECK_FOR_ERROR
1522   }
1523   | GETELEMENTPTR '(' ConstVal IndexList ')' {
1524     if (!isa<PointerType>($3->getType()))
1525       GEN_ERROR("GetElementPtr requires a pointer operand!");
1526
1527     // LLVM 1.2 and earlier used ubyte struct indices.  Convert any ubyte struct
1528     // indices to uint struct indices for compatibility.
1529     generic_gep_type_iterator<std::vector<Value*>::iterator>
1530       GTI = gep_type_begin($3->getType(), $4->begin(), $4->end()),
1531       GTE = gep_type_end($3->getType(), $4->begin(), $4->end());
1532     for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
1533       if (isa<StructType>(*GTI))        // Only change struct indices
1534         if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
1535           if (CUI->getType() == Type::UByteTy)
1536             (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
1537
1538     const Type *IdxTy =
1539       GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1540     if (!IdxTy)
1541       GEN_ERROR("Index list invalid for constant getelementptr!");
1542
1543     std::vector<Constant*> IdxVec;
1544     for (unsigned i = 0, e = $4->size(); i != e; ++i)
1545       if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1546         IdxVec.push_back(C);
1547       else
1548         GEN_ERROR("Indices to constant getelementptr must be constants!");
1549
1550     delete $4;
1551
1552     $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1553     CHECK_FOR_ERROR
1554   }
1555   | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1556     if ($3->getType() != Type::BoolTy)
1557       GEN_ERROR("Select condition must be of boolean type!");
1558     if ($5->getType() != $7->getType())
1559       GEN_ERROR("Select operand types must match!");
1560     $$ = ConstantExpr::getSelect($3, $5, $7);
1561     CHECK_FOR_ERROR
1562   }
1563   | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1564     if ($3->getType() != $5->getType())
1565       GEN_ERROR("Binary operator types must match!");
1566     // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
1567     // To retain backward compatibility with these early compilers, we emit a
1568     // cast to the appropriate integer type automatically if we are in the
1569     // broken case.  See PR424 for more information.
1570     if (!isa<PointerType>($3->getType())) {
1571       $$ = ConstantExpr::get($1, $3, $5);
1572     } else {
1573       const Type *IntPtrTy = 0;
1574       switch (CurModule.CurrentModule->getPointerSize()) {
1575       case Module::Pointer32: IntPtrTy = Type::IntTy; break;
1576       case Module::Pointer64: IntPtrTy = Type::LongTy; break;
1577       default: GEN_ERROR("invalid pointer binary constant expr!");
1578       }
1579       $$ = ConstantExpr::get($1, ConstantExpr::getCast($3, IntPtrTy),
1580                              ConstantExpr::getCast($5, IntPtrTy));
1581       $$ = ConstantExpr::getCast($$, $3->getType());
1582     }
1583     CHECK_FOR_ERROR
1584   }
1585   | LogicalOps '(' ConstVal ',' ConstVal ')' {
1586     if ($3->getType() != $5->getType())
1587       GEN_ERROR("Logical operator types must match!");
1588     if (!$3->getType()->isIntegral()) {
1589       if (!isa<PackedType>($3->getType()) || 
1590           !cast<PackedType>($3->getType())->getElementType()->isIntegral())
1591         GEN_ERROR("Logical operator requires integral operands!");
1592     }
1593     $$ = ConstantExpr::get($1, $3, $5);
1594     CHECK_FOR_ERROR
1595   }
1596   | SetCondOps '(' ConstVal ',' ConstVal ')' {
1597     if ($3->getType() != $5->getType())
1598       GEN_ERROR("setcc operand types must match!");
1599     $$ = ConstantExpr::get($1, $3, $5);
1600     CHECK_FOR_ERROR
1601   }
1602   | ShiftOps '(' ConstVal ',' ConstVal ')' {
1603     if ($5->getType() != Type::UByteTy)
1604       GEN_ERROR("Shift count for shift constant must be unsigned byte!");
1605     if (!$3->getType()->isInteger())
1606       GEN_ERROR("Shift constant expression requires integer operand!");
1607     $$ = ConstantExpr::get($1, $3, $5);
1608     CHECK_FOR_ERROR
1609   }
1610   | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1611     if (!ExtractElementInst::isValidOperands($3, $5))
1612       GEN_ERROR("Invalid extractelement operands!");
1613     $$ = ConstantExpr::getExtractElement($3, $5);
1614     CHECK_FOR_ERROR
1615   }
1616   | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1617     if (!InsertElementInst::isValidOperands($3, $5, $7))
1618       GEN_ERROR("Invalid insertelement operands!");
1619     $$ = ConstantExpr::getInsertElement($3, $5, $7);
1620     CHECK_FOR_ERROR
1621   }
1622   | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1623     if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1624       GEN_ERROR("Invalid shufflevector operands!");
1625     $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1626     CHECK_FOR_ERROR
1627   };
1628
1629
1630 // ConstVector - A list of comma separated constants.
1631 ConstVector : ConstVector ',' ConstVal {
1632     ($$ = $1)->push_back($3);
1633     CHECK_FOR_ERROR
1634   }
1635   | ConstVal {
1636     $$ = new std::vector<Constant*>();
1637     $$->push_back($1);
1638     CHECK_FOR_ERROR
1639   };
1640
1641
1642 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1643 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1644
1645
1646 //===----------------------------------------------------------------------===//
1647 //                             Rules to match Modules
1648 //===----------------------------------------------------------------------===//
1649
1650 // Module rule: Capture the result of parsing the whole file into a result
1651 // variable...
1652 //
1653 Module : FunctionList {
1654   $$ = ParserResult = $1;
1655   CurModule.ModuleDone();
1656   CHECK_FOR_ERROR
1657 };
1658
1659 // FunctionList - A list of functions, preceeded by a constant pool.
1660 //
1661 FunctionList : FunctionList Function {
1662     $$ = $1;
1663     CurFun.FunctionDone();
1664     CHECK_FOR_ERROR
1665   } 
1666   | FunctionList FunctionProto {
1667     $$ = $1;
1668     CHECK_FOR_ERROR
1669   }
1670   | FunctionList MODULE ASM_TOK AsmBlock {
1671     $$ = $1;
1672     CHECK_FOR_ERROR
1673   }  
1674   | FunctionList IMPLEMENTATION {
1675     $$ = $1;
1676     CHECK_FOR_ERROR
1677   }
1678   | ConstPool {
1679     $$ = CurModule.CurrentModule;
1680     // Emit an error if there are any unresolved types left.
1681     if (!CurModule.LateResolveTypes.empty()) {
1682       const ValID &DID = CurModule.LateResolveTypes.begin()->first;
1683       if (DID.Type == ValID::NameVal) {
1684         GEN_ERROR("Reference to an undefined type: '"+DID.getName() + "'");
1685       } else {
1686         GEN_ERROR("Reference to an undefined type: #" + itostr(DID.Num));
1687       }
1688     }
1689     CHECK_FOR_ERROR
1690   };
1691
1692 // ConstPool - Constants with optional names assigned to them.
1693 ConstPool : ConstPool OptAssign TYPE TypesV {
1694     // Eagerly resolve types.  This is not an optimization, this is a
1695     // requirement that is due to the fact that we could have this:
1696     //
1697     // %list = type { %list * }
1698     // %list = type { %list * }    ; repeated type decl
1699     //
1700     // If types are not resolved eagerly, then the two types will not be
1701     // determined to be the same type!
1702     //
1703     ResolveTypeTo($2, *$4);
1704
1705     if (!setTypeName(*$4, $2) && !$2) {
1706       // If this is a named type that is not a redefinition, add it to the slot
1707       // table.
1708       CurModule.Types.push_back(*$4);
1709     }
1710
1711     delete $4;
1712     CHECK_FOR_ERROR
1713   }
1714   | ConstPool FunctionProto {       // Function prototypes can be in const pool
1715     CHECK_FOR_ERROR
1716   }
1717   | ConstPool MODULE ASM_TOK AsmBlock {  // Asm blocks can be in the const pool
1718     CHECK_FOR_ERROR
1719   }
1720   | ConstPool OptAssign OptLinkage GlobalType ConstVal {
1721     if ($5 == 0) GEN_ERROR("Global value initializer is not a constant!");
1722     CurGV = ParseGlobalVariable($2, $3, $4, $5->getType(), $5);
1723                                                        } GlobalVarAttributes {
1724     CurGV = 0;
1725     CHECK_FOR_ERROR
1726   }
1727   | ConstPool OptAssign EXTERNAL GlobalType Types {
1728     CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage,
1729                                              $4, *$5, 0);
1730     delete $5;
1731                                                    } GlobalVarAttributes {
1732     CurGV = 0;
1733     CHECK_FOR_ERROR
1734   }
1735   | ConstPool TARGET TargetDefinition { 
1736     CHECK_FOR_ERROR
1737   }
1738   | ConstPool DEPLIBS '=' LibrariesDefinition {
1739     CHECK_FOR_ERROR
1740   }
1741   | /* empty: end of list */ { 
1742   };
1743
1744
1745 AsmBlock : STRINGCONSTANT {
1746   const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
1747   char *EndStr = UnEscapeLexed($1, true);
1748   std::string NewAsm($1, EndStr);
1749   free($1);
1750
1751   if (AsmSoFar.empty())
1752     CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
1753   else
1754     CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
1755   CHECK_FOR_ERROR
1756 };
1757
1758 BigOrLittle : BIG    { $$ = Module::BigEndian; };
1759 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1760
1761 TargetDefinition : ENDIAN '=' BigOrLittle {
1762     CurModule.CurrentModule->setEndianness($3);
1763     CHECK_FOR_ERROR
1764   }
1765   | POINTERSIZE '=' EUINT64VAL {
1766     if ($3 == 32)
1767       CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1768     else if ($3 == 64)
1769       CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1770     else
1771       GEN_ERROR("Invalid pointer size: '" + utostr($3) + "'!");
1772     CHECK_FOR_ERROR
1773   }
1774   | TRIPLE '=' STRINGCONSTANT {
1775     CurModule.CurrentModule->setTargetTriple($3);
1776     free($3);
1777     CHECK_FOR_ERROR
1778   };
1779
1780 LibrariesDefinition : '[' LibList ']';
1781
1782 LibList : LibList ',' STRINGCONSTANT {
1783           CurModule.CurrentModule->addLibrary($3);
1784           free($3);
1785           CHECK_FOR_ERROR
1786         }
1787         | STRINGCONSTANT {
1788           CurModule.CurrentModule->addLibrary($1);
1789           free($1);
1790           CHECK_FOR_ERROR
1791         }
1792         | /* empty: end of list */ {
1793           CHECK_FOR_ERROR
1794         }
1795         ;
1796
1797 //===----------------------------------------------------------------------===//
1798 //                       Rules to match Function Headers
1799 //===----------------------------------------------------------------------===//
1800
1801 Name : VAR_ID | STRINGCONSTANT;
1802 OptName : Name | /*empty*/ { $$ = 0; };
1803
1804 ArgVal : Types OptName {
1805   if (*$1 == Type::VoidTy)
1806     GEN_ERROR("void typed arguments are invalid!");
1807   $$ = new std::pair<PATypeHolder*, char*>($1, $2);
1808   CHECK_FOR_ERROR
1809 };
1810
1811 ArgListH : ArgListH ',' ArgVal {
1812     $$ = $1;
1813     $1->push_back(*$3);
1814     delete $3;
1815     CHECK_FOR_ERROR
1816   }
1817   | ArgVal {
1818     $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1819     $$->push_back(*$1);
1820     delete $1;
1821     CHECK_FOR_ERROR
1822   };
1823
1824 ArgList : ArgListH {
1825     $$ = $1;
1826     CHECK_FOR_ERROR
1827   }
1828   | ArgListH ',' DOTDOTDOT {
1829     $$ = $1;
1830     $$->push_back(std::pair<PATypeHolder*,
1831                             char*>(new PATypeHolder(Type::VoidTy), 0));
1832     CHECK_FOR_ERROR
1833   }
1834   | DOTDOTDOT {
1835     $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1836     $$->push_back(std::make_pair(new PATypeHolder(Type::VoidTy), (char*)0));
1837     CHECK_FOR_ERROR
1838   }
1839   | /* empty */ {
1840     $$ = 0;
1841     CHECK_FOR_ERROR
1842   };
1843
1844 FunctionHeaderH : OptCallingConv TypesV Name '(' ArgList ')' 
1845                   OptSection OptAlign {
1846   UnEscapeLexed($3);
1847   std::string FunctionName($3);
1848   free($3);  // Free strdup'd memory!
1849   
1850   if (!(*$2)->isFirstClassType() && *$2 != Type::VoidTy)
1851     GEN_ERROR("LLVM functions cannot return aggregate types!");
1852
1853   std::vector<const Type*> ParamTypeList;
1854   if ($5) {   // If there are arguments...
1855     for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
1856          I != $5->end(); ++I)
1857       ParamTypeList.push_back(I->first->get());
1858   }
1859
1860   bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1861   if (isVarArg) ParamTypeList.pop_back();
1862
1863   const FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
1864   const PointerType *PFT = PointerType::get(FT);
1865   delete $2;
1866
1867   ValID ID;
1868   if (!FunctionName.empty()) {
1869     ID = ValID::create((char*)FunctionName.c_str());
1870   } else {
1871     ID = ValID::create((int)CurModule.Values[PFT].size());
1872   }
1873
1874   Function *Fn = 0;
1875   // See if this function was forward referenced.  If so, recycle the object.
1876   if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
1877     // Move the function to the end of the list, from whereever it was 
1878     // previously inserted.
1879     Fn = cast<Function>(FWRef);
1880     CurModule.CurrentModule->getFunctionList().remove(Fn);
1881     CurModule.CurrentModule->getFunctionList().push_back(Fn);
1882   } else if (!FunctionName.empty() &&     // Merge with an earlier prototype?
1883              (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
1884     // If this is the case, either we need to be a forward decl, or it needs 
1885     // to be.
1886     if (!CurFun.isDeclare && !Fn->isExternal())
1887       GEN_ERROR("Redefinition of function '" + FunctionName + "'!");
1888     
1889     // Make sure to strip off any argument names so we can't get conflicts.
1890     if (Fn->isExternal())
1891       for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
1892            AI != AE; ++AI)
1893         AI->setName("");
1894
1895   } else  {  // Not already defined?
1896     Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
1897                       CurModule.CurrentModule);
1898     InsertValue(Fn, CurModule.Values);
1899   }
1900
1901   CurFun.FunctionStart(Fn);
1902   Fn->setCallingConv($1);
1903   Fn->setAlignment($8);
1904   if ($7) {
1905     Fn->setSection($7);
1906     free($7);
1907   }
1908
1909   // Add all of the arguments we parsed to the function...
1910   if ($5) {                     // Is null if empty...
1911     if (isVarArg) {  // Nuke the last entry
1912       assert($5->back().first->get() == Type::VoidTy && $5->back().second == 0&&
1913              "Not a varargs marker!");
1914       delete $5->back().first;
1915       $5->pop_back();  // Delete the last entry
1916     }
1917     Function::arg_iterator ArgIt = Fn->arg_begin();
1918     for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
1919          I != $5->end(); ++I, ++ArgIt) {
1920       delete I->first;                          // Delete the typeholder...
1921
1922       setValueName(ArgIt, I->second);           // Insert arg into symtab...
1923       InsertValue(ArgIt);
1924     }
1925
1926     delete $5;                     // We're now done with the argument list
1927   }
1928   CHECK_FOR_ERROR
1929 };
1930
1931 BEGIN : BEGINTOK | '{';                // Allow BEGIN or '{' to start a function
1932
1933 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
1934   $$ = CurFun.CurrentFunction;
1935
1936   // Make sure that we keep track of the linkage type even if there was a
1937   // previous "declare".
1938   $$->setLinkage($1);
1939 };
1940
1941 END : ENDTOK | '}';                    // Allow end of '}' to end a function
1942
1943 Function : BasicBlockList END {
1944   $$ = $1;
1945   CHECK_FOR_ERROR
1946 };
1947
1948 FunctionProto : DECLARE { CurFun.isDeclare = true; } FunctionHeaderH {
1949   $$ = CurFun.CurrentFunction;
1950   CurFun.FunctionDone();
1951   CHECK_FOR_ERROR
1952 };
1953
1954 //===----------------------------------------------------------------------===//
1955 //                        Rules to match Basic Blocks
1956 //===----------------------------------------------------------------------===//
1957
1958 OptSideEffect : /* empty */ {
1959     $$ = false;
1960     CHECK_FOR_ERROR
1961   }
1962   | SIDEEFFECT {
1963     $$ = true;
1964     CHECK_FOR_ERROR
1965   };
1966
1967 ConstValueRef : ESINT64VAL {    // A reference to a direct constant
1968     $$ = ValID::create($1);
1969     CHECK_FOR_ERROR
1970   }
1971   | EUINT64VAL {
1972     $$ = ValID::create($1);
1973     CHECK_FOR_ERROR
1974   }
1975   | FPVAL {                     // Perhaps it's an FP constant?
1976     $$ = ValID::create($1);
1977     CHECK_FOR_ERROR
1978   }
1979   | TRUETOK {
1980     $$ = ValID::create(ConstantBool::True);
1981     CHECK_FOR_ERROR
1982   } 
1983   | FALSETOK {
1984     $$ = ValID::create(ConstantBool::False);
1985     CHECK_FOR_ERROR
1986   }
1987   | NULL_TOK {
1988     $$ = ValID::createNull();
1989     CHECK_FOR_ERROR
1990   }
1991   | UNDEF {
1992     $$ = ValID::createUndef();
1993     CHECK_FOR_ERROR
1994   }
1995   | ZEROINITIALIZER {     // A vector zero constant.
1996     $$ = ValID::createZeroInit();
1997     CHECK_FOR_ERROR
1998   }
1999   | '<' ConstVector '>' { // Nonempty unsized packed vector
2000     const Type *ETy = (*$2)[0]->getType();
2001     int NumElements = $2->size(); 
2002     
2003     PackedType* pt = PackedType::get(ETy, NumElements);
2004     PATypeHolder* PTy = new PATypeHolder(
2005                                          HandleUpRefs(
2006                                             PackedType::get(
2007                                                 ETy, 
2008                                                 NumElements)
2009                                             )
2010                                          );
2011     
2012     // Verify all elements are correct type!
2013     for (unsigned i = 0; i < $2->size(); i++) {
2014       if (ETy != (*$2)[i]->getType())
2015         GEN_ERROR("Element #" + utostr(i) + " is not of type '" + 
2016                      ETy->getDescription() +"' as required!\nIt is of type '" +
2017                      (*$2)[i]->getType()->getDescription() + "'.");
2018     }
2019
2020     $$ = ValID::create(ConstantPacked::get(pt, *$2));
2021     delete PTy; delete $2;
2022     CHECK_FOR_ERROR
2023   }
2024   | ConstExpr {
2025     $$ = ValID::create($1);
2026     CHECK_FOR_ERROR
2027   }
2028   | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2029     char *End = UnEscapeLexed($3, true);
2030     std::string AsmStr = std::string($3, End);
2031     End = UnEscapeLexed($5, true);
2032     std::string Constraints = std::string($5, End);
2033     $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2034     free($3);
2035     free($5);
2036     CHECK_FOR_ERROR
2037   };
2038
2039 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2040 // another value.
2041 //
2042 SymbolicValueRef : INTVAL {  // Is it an integer reference...?
2043     $$ = ValID::create($1);
2044     CHECK_FOR_ERROR
2045   }
2046   | Name {                   // Is it a named reference...?
2047     $$ = ValID::create($1);
2048     CHECK_FOR_ERROR
2049   };
2050
2051 // ValueRef - A reference to a definition... either constant or symbolic
2052 ValueRef : SymbolicValueRef | ConstValueRef;
2053
2054
2055 // ResolvedVal - a <type> <value> pair.  This is used only in cases where the
2056 // type immediately preceeds the value reference, and allows complex constant
2057 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2058 ResolvedVal : Types ValueRef {
2059     $$ = getVal(*$1, $2); delete $1;
2060     CHECK_FOR_ERROR
2061   };
2062
2063 BasicBlockList : BasicBlockList BasicBlock {
2064     $$ = $1;
2065     CHECK_FOR_ERROR
2066   }
2067   | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks   
2068     $$ = $1;
2069     CHECK_FOR_ERROR
2070   };
2071
2072
2073 // Basic blocks are terminated by branching instructions: 
2074 // br, br/cc, switch, ret
2075 //
2076 BasicBlock : InstructionList OptAssign BBTerminatorInst  {
2077     setValueName($3, $2);
2078     InsertValue($3);
2079
2080     $1->getInstList().push_back($3);
2081     InsertValue($1);
2082     $$ = $1;
2083     CHECK_FOR_ERROR
2084   };
2085
2086 InstructionList : InstructionList Inst {
2087     $1->getInstList().push_back($2);
2088     $$ = $1;
2089     CHECK_FOR_ERROR
2090   }
2091   | /* empty */ {
2092     $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
2093
2094     // Make sure to move the basic block to the correct location in the
2095     // function, instead of leaving it inserted wherever it was first
2096     // referenced.
2097     Function::BasicBlockListType &BBL = 
2098       CurFun.CurrentFunction->getBasicBlockList();
2099     BBL.splice(BBL.end(), BBL, $$);
2100     CHECK_FOR_ERROR
2101   }
2102   | LABELSTR {
2103     $$ = CurBB = getBBVal(ValID::create($1), true);
2104
2105     // Make sure to move the basic block to the correct location in the
2106     // function, instead of leaving it inserted wherever it was first
2107     // referenced.
2108     Function::BasicBlockListType &BBL = 
2109       CurFun.CurrentFunction->getBasicBlockList();
2110     BBL.splice(BBL.end(), BBL, $$);
2111     CHECK_FOR_ERROR
2112   };
2113
2114 BBTerminatorInst : RET ResolvedVal {              // Return with a result...
2115     $$ = new ReturnInst($2);
2116     CHECK_FOR_ERROR
2117   }
2118   | RET VOID {                                       // Return with no result...
2119     $$ = new ReturnInst();
2120     CHECK_FOR_ERROR
2121   }
2122   | BR LABEL ValueRef {                         // Unconditional Branch...
2123     $$ = new BranchInst(getBBVal($3));
2124     CHECK_FOR_ERROR
2125   }                                                  // Conditional Branch...
2126   | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {  
2127     $$ = new BranchInst(getBBVal($6), getBBVal($9), getVal(Type::BoolTy, $3));
2128     CHECK_FOR_ERROR
2129   }
2130   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2131     SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6), $8->size());
2132     $$ = S;
2133
2134     std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2135       E = $8->end();
2136     for (; I != E; ++I) {
2137       if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2138           S->addCase(CI, I->second);
2139       else
2140         GEN_ERROR("Switch case is constant, but not a simple integer!");
2141     }
2142     delete $8;
2143     CHECK_FOR_ERROR
2144   }
2145   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2146     SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6), 0);
2147     $$ = S;
2148     CHECK_FOR_ERROR
2149   }
2150   | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
2151     TO LABEL ValueRef UNWIND LABEL ValueRef {
2152     const PointerType *PFTy;
2153     const FunctionType *Ty;
2154
2155     if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2156         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2157       // Pull out the types of all of the arguments...
2158       std::vector<const Type*> ParamTypes;
2159       if ($6) {
2160         for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
2161              I != E; ++I)
2162           ParamTypes.push_back((*I)->getType());
2163       }
2164
2165       bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2166       if (isVarArg) ParamTypes.pop_back();
2167
2168       Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
2169       PFTy = PointerType::get(Ty);
2170     }
2171
2172     Value *V = getVal(PFTy, $4);   // Get the function we're calling...
2173
2174     BasicBlock *Normal = getBBVal($10);
2175     BasicBlock *Except = getBBVal($13);
2176
2177     // Create the call node...
2178     if (!$6) {                                   // Has no arguments?
2179       $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
2180     } else {                                     // Has arguments?
2181       // Loop through FunctionType's arguments and ensure they are specified
2182       // correctly!
2183       //
2184       FunctionType::param_iterator I = Ty->param_begin();
2185       FunctionType::param_iterator E = Ty->param_end();
2186       std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
2187
2188       for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2189         if ((*ArgI)->getType() != *I)
2190           GEN_ERROR("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2191                          (*I)->getDescription() + "'!");
2192
2193       if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2194         GEN_ERROR("Invalid number of parameters detected!");
2195
2196       $$ = new InvokeInst(V, Normal, Except, *$6);
2197     }
2198     cast<InvokeInst>($$)->setCallingConv($2);
2199   
2200     delete $3;
2201     delete $6;
2202     CHECK_FOR_ERROR
2203   }
2204   | UNWIND {
2205     $$ = new UnwindInst();
2206     CHECK_FOR_ERROR
2207   }
2208   | UNREACHABLE {
2209     $$ = new UnreachableInst();
2210     CHECK_FOR_ERROR
2211   };
2212
2213
2214
2215 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2216     $$ = $1;
2217     Constant *V = cast<Constant>(getValNonImprovising($2, $3));
2218     if (V == 0)
2219       GEN_ERROR("May only switch on a constant pool value!");
2220
2221     $$->push_back(std::make_pair(V, getBBVal($6)));
2222     CHECK_FOR_ERROR
2223   }
2224   | IntType ConstValueRef ',' LABEL ValueRef {
2225     $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2226     Constant *V = cast<Constant>(getValNonImprovising($1, $2));
2227
2228     if (V == 0)
2229       GEN_ERROR("May only switch on a constant pool value!");
2230
2231     $$->push_back(std::make_pair(V, getBBVal($5)));
2232     CHECK_FOR_ERROR
2233   };
2234
2235 Inst : OptAssign InstVal {
2236   // Is this definition named?? if so, assign the name...
2237   setValueName($2, $1);
2238   InsertValue($2);
2239   $$ = $2;
2240   CHECK_FOR_ERROR
2241 };
2242
2243 PHIList : Types '[' ValueRef ',' ValueRef ']' {    // Used for PHI nodes
2244     $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2245     $$->push_back(std::make_pair(getVal(*$1, $3), getBBVal($5)));
2246     delete $1;
2247     CHECK_FOR_ERROR
2248   }
2249   | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2250     $$ = $1;
2251     $1->push_back(std::make_pair(getVal($1->front().first->getType(), $4),
2252                                  getBBVal($6)));
2253     CHECK_FOR_ERROR
2254   };
2255
2256
2257 ValueRefList : ResolvedVal {    // Used for call statements, and memory insts...
2258     $$ = new std::vector<Value*>();
2259     $$->push_back($1);
2260     CHECK_FOR_ERROR
2261   }
2262   | ValueRefList ',' ResolvedVal {
2263     $$ = $1;
2264     $1->push_back($3);
2265     CHECK_FOR_ERROR
2266   };
2267
2268 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
2269 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
2270
2271 OptTailCall : TAIL CALL {
2272     $$ = true;
2273     CHECK_FOR_ERROR
2274   }
2275   | CALL {
2276     $$ = false;
2277     CHECK_FOR_ERROR
2278   };
2279
2280
2281
2282 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2283     if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() && 
2284         !isa<PackedType>((*$2).get()))
2285       GEN_ERROR(
2286         "Arithmetic operator requires integer, FP, or packed operands!");
2287     if (isa<PackedType>((*$2).get()) && $1 == Instruction::Rem)
2288       GEN_ERROR("Rem not supported on packed types!");
2289     $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
2290     if ($$ == 0)
2291       GEN_ERROR("binary operator returned null!");
2292     delete $2;
2293     CHECK_FOR_ERROR
2294   }
2295   | LogicalOps Types ValueRef ',' ValueRef {
2296     if (!(*$2)->isIntegral()) {
2297       if (!isa<PackedType>($2->get()) ||
2298           !cast<PackedType>($2->get())->getElementType()->isIntegral())
2299         GEN_ERROR("Logical operator requires integral operands!");
2300     }
2301     $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
2302     if ($$ == 0)
2303       GEN_ERROR("binary operator returned null!");
2304     delete $2;
2305     CHECK_FOR_ERROR
2306   }
2307   | SetCondOps Types ValueRef ',' ValueRef {
2308     if(isa<PackedType>((*$2).get())) {
2309       GEN_ERROR(
2310         "PackedTypes currently not supported in setcc instructions!");
2311     }
2312     $$ = new SetCondInst($1, getVal(*$2, $3), getVal(*$2, $5));
2313     if ($$ == 0)
2314       GEN_ERROR("binary operator returned null!");
2315     delete $2;
2316     CHECK_FOR_ERROR
2317   }
2318   | NOT ResolvedVal {
2319     std::cerr << "WARNING: Use of eliminated 'not' instruction:"
2320               << " Replacing with 'xor'.\n";
2321
2322     Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
2323     if (Ones == 0)
2324       GEN_ERROR("Expected integral type for not instruction!");
2325
2326     $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
2327     if ($$ == 0)
2328       GEN_ERROR("Could not create a xor instruction!");
2329     CHECK_FOR_ERROR
2330   }
2331   | ShiftOps ResolvedVal ',' ResolvedVal {
2332     if ($4->getType() != Type::UByteTy)
2333       GEN_ERROR("Shift amount must be ubyte!");
2334     if (!$2->getType()->isInteger())
2335       GEN_ERROR("Shift constant expression requires integer operand!");
2336     $$ = new ShiftInst($1, $2, $4);
2337     CHECK_FOR_ERROR
2338   }
2339   | CAST ResolvedVal TO Types {
2340     if (!$4->get()->isFirstClassType())
2341       GEN_ERROR("cast instruction to a non-primitive type: '" +
2342                      $4->get()->getDescription() + "'!");
2343     $$ = new CastInst($2, *$4);
2344     delete $4;
2345     CHECK_FOR_ERROR
2346   }
2347   | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2348     if ($2->getType() != Type::BoolTy)
2349       GEN_ERROR("select condition must be boolean!");
2350     if ($4->getType() != $6->getType())
2351       GEN_ERROR("select value types should match!");
2352     $$ = new SelectInst($2, $4, $6);
2353     CHECK_FOR_ERROR
2354   }
2355   | VAARG ResolvedVal ',' Types {
2356     NewVarArgs = true;
2357     $$ = new VAArgInst($2, *$4);
2358     delete $4;
2359     CHECK_FOR_ERROR
2360   }
2361   | VAARG_old ResolvedVal ',' Types {
2362     ObsoleteVarArgs = true;
2363     const Type* ArgTy = $2->getType();
2364     Function* NF = CurModule.CurrentModule->
2365       getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0);
2366
2367     //b = vaarg a, t -> 
2368     //foo = alloca 1 of t
2369     //bar = vacopy a 
2370     //store bar -> foo
2371     //b = vaarg foo, t
2372     AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
2373     CurBB->getInstList().push_back(foo);
2374     CallInst* bar = new CallInst(NF, $2);
2375     CurBB->getInstList().push_back(bar);
2376     CurBB->getInstList().push_back(new StoreInst(bar, foo));
2377     $$ = new VAArgInst(foo, *$4);
2378     delete $4;
2379     CHECK_FOR_ERROR
2380   }
2381   | VANEXT_old ResolvedVal ',' Types {
2382     ObsoleteVarArgs = true;
2383     const Type* ArgTy = $2->getType();
2384     Function* NF = CurModule.CurrentModule->
2385       getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0);
2386
2387     //b = vanext a, t ->
2388     //foo = alloca 1 of t
2389     //bar = vacopy a
2390     //store bar -> foo
2391     //tmp = vaarg foo, t
2392     //b = load foo
2393     AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
2394     CurBB->getInstList().push_back(foo);
2395     CallInst* bar = new CallInst(NF, $2);
2396     CurBB->getInstList().push_back(bar);
2397     CurBB->getInstList().push_back(new StoreInst(bar, foo));
2398     Instruction* tmp = new VAArgInst(foo, *$4);
2399     CurBB->getInstList().push_back(tmp);
2400     $$ = new LoadInst(foo);
2401     delete $4;
2402     CHECK_FOR_ERROR
2403   }
2404   | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2405     if (!ExtractElementInst::isValidOperands($2, $4))
2406       GEN_ERROR("Invalid extractelement operands!");
2407     $$ = new ExtractElementInst($2, $4);
2408     CHECK_FOR_ERROR
2409   }
2410   | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2411     if (!InsertElementInst::isValidOperands($2, $4, $6))
2412       GEN_ERROR("Invalid insertelement operands!");
2413     $$ = new InsertElementInst($2, $4, $6);
2414     CHECK_FOR_ERROR
2415   }
2416   | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2417     if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
2418       GEN_ERROR("Invalid shufflevector operands!");
2419     $$ = new ShuffleVectorInst($2, $4, $6);
2420     CHECK_FOR_ERROR
2421   }
2422   | PHI_TOK PHIList {
2423     const Type *Ty = $2->front().first->getType();
2424     if (!Ty->isFirstClassType())
2425       GEN_ERROR("PHI node operands must be of first class type!");
2426     $$ = new PHINode(Ty);
2427     ((PHINode*)$$)->reserveOperandSpace($2->size());
2428     while ($2->begin() != $2->end()) {
2429       if ($2->front().first->getType() != Ty) 
2430         GEN_ERROR("All elements of a PHI node must be of the same type!");
2431       cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2432       $2->pop_front();
2433     }
2434     delete $2;  // Free the list...
2435     CHECK_FOR_ERROR
2436   }
2437   | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')'  {
2438     const PointerType *PFTy;
2439     const FunctionType *Ty;
2440
2441     if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2442         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2443       // Pull out the types of all of the arguments...
2444       std::vector<const Type*> ParamTypes;
2445       if ($6) {
2446         for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
2447              I != E; ++I)
2448           ParamTypes.push_back((*I)->getType());
2449       }
2450
2451       bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2452       if (isVarArg) ParamTypes.pop_back();
2453
2454       if (!(*$3)->isFirstClassType() && *$3 != Type::VoidTy)
2455         GEN_ERROR("LLVM functions cannot return aggregate types!");
2456
2457       Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
2458       PFTy = PointerType::get(Ty);
2459     }
2460
2461     Value *V = getVal(PFTy, $4);   // Get the function we're calling...
2462
2463     // Create the call node...
2464     if (!$6) {                                   // Has no arguments?
2465       // Make sure no arguments is a good thing!
2466       if (Ty->getNumParams() != 0)
2467         GEN_ERROR("No arguments passed to a function that "
2468                        "expects arguments!");
2469
2470       $$ = new CallInst(V, std::vector<Value*>());
2471     } else {                                     // Has arguments?
2472       // Loop through FunctionType's arguments and ensure they are specified
2473       // correctly!
2474       //
2475       FunctionType::param_iterator I = Ty->param_begin();
2476       FunctionType::param_iterator E = Ty->param_end();
2477       std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
2478
2479       for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2480         if ((*ArgI)->getType() != *I)
2481           GEN_ERROR("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2482                          (*I)->getDescription() + "'!");
2483
2484       if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2485         GEN_ERROR("Invalid number of parameters detected!");
2486
2487       $$ = new CallInst(V, *$6);
2488     }
2489     cast<CallInst>($$)->setTailCall($1);
2490     cast<CallInst>($$)->setCallingConv($2);
2491     delete $3;
2492     delete $6;
2493     CHECK_FOR_ERROR
2494   }
2495   | MemoryInst {
2496     $$ = $1;
2497     CHECK_FOR_ERROR
2498   };
2499
2500
2501 // IndexList - List of indices for GEP based instructions...
2502 IndexList : ',' ValueRefList { 
2503     $$ = $2; 
2504     CHECK_FOR_ERROR
2505   } | /* empty */ { 
2506     $$ = new std::vector<Value*>(); 
2507     CHECK_FOR_ERROR
2508   };
2509
2510 OptVolatile : VOLATILE {
2511     $$ = true;
2512     CHECK_FOR_ERROR
2513   }
2514   | /* empty */ {
2515     $$ = false;
2516     CHECK_FOR_ERROR
2517   };
2518
2519
2520
2521 MemoryInst : MALLOC Types OptCAlign {
2522     $$ = new MallocInst(*$2, 0, $3);
2523     delete $2;
2524     CHECK_FOR_ERROR
2525   }
2526   | MALLOC Types ',' UINT ValueRef OptCAlign {
2527     $$ = new MallocInst(*$2, getVal($4, $5), $6);
2528     delete $2;
2529     CHECK_FOR_ERROR
2530   }
2531   | ALLOCA Types OptCAlign {
2532     $$ = new AllocaInst(*$2, 0, $3);
2533     delete $2;
2534     CHECK_FOR_ERROR
2535   }
2536   | ALLOCA Types ',' UINT ValueRef OptCAlign {
2537     $$ = new AllocaInst(*$2, getVal($4, $5), $6);
2538     delete $2;
2539     CHECK_FOR_ERROR
2540   }
2541   | FREE ResolvedVal {
2542     if (!isa<PointerType>($2->getType()))
2543       GEN_ERROR("Trying to free nonpointer type " + 
2544                      $2->getType()->getDescription() + "!");
2545     $$ = new FreeInst($2);
2546     CHECK_FOR_ERROR
2547   }
2548
2549   | OptVolatile LOAD Types ValueRef {
2550     if (!isa<PointerType>($3->get()))
2551       GEN_ERROR("Can't load from nonpointer type: " +
2552                      (*$3)->getDescription());
2553     if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
2554       GEN_ERROR("Can't load from pointer of non-first-class type: " +
2555                      (*$3)->getDescription());
2556     $$ = new LoadInst(getVal(*$3, $4), "", $1);
2557     delete $3;
2558     CHECK_FOR_ERROR
2559   }
2560   | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2561     const PointerType *PT = dyn_cast<PointerType>($5->get());
2562     if (!PT)
2563       GEN_ERROR("Can't store to a nonpointer type: " +
2564                      (*$5)->getDescription());
2565     const Type *ElTy = PT->getElementType();
2566     if (ElTy != $3->getType())
2567       GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
2568                      "' into space of type '" + ElTy->getDescription() + "'!");
2569
2570     $$ = new StoreInst($3, getVal(*$5, $6), $1);
2571     delete $5;
2572     CHECK_FOR_ERROR
2573   }
2574   | GETELEMENTPTR Types ValueRef IndexList {
2575     if (!isa<PointerType>($2->get()))
2576       GEN_ERROR("getelementptr insn requires pointer operand!");
2577
2578     // LLVM 1.2 and earlier used ubyte struct indices.  Convert any ubyte struct
2579     // indices to uint struct indices for compatibility.
2580     generic_gep_type_iterator<std::vector<Value*>::iterator>
2581       GTI = gep_type_begin($2->get(), $4->begin(), $4->end()),
2582       GTE = gep_type_end($2->get(), $4->begin(), $4->end());
2583     for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
2584       if (isa<StructType>(*GTI))        // Only change struct indices
2585         if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
2586           if (CUI->getType() == Type::UByteTy)
2587             (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
2588
2589     if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2590       GEN_ERROR("Invalid getelementptr indices for type '" +
2591                      (*$2)->getDescription()+ "'!");
2592     $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
2593     delete $2; delete $4;
2594     CHECK_FOR_ERROR
2595   };
2596
2597
2598 %%
2599
2600 void llvm::GenerateError(const std::string &message, int LineNo) {
2601   if (LineNo == -1) LineNo = llvmAsmlineno;
2602   // TODO: column number in exception
2603   if (TheParseError)
2604     TheParseError->setError(CurFilename, message, LineNo);
2605   TriggerError = 1;
2606 }
2607
2608 int yyerror(const char *ErrorMsg) {
2609   std::string where 
2610     = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2611                   + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2612   std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2613   if (yychar == YYEMPTY || yychar == 0)
2614     errMsg += "end-of-file.";
2615   else
2616     errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2617   GenerateError(errMsg);
2618   return 0;
2619 }