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