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