The sign information was not propagating into the rename map so only the
[oota-llvm.git] / tools / llvm-upgrade / UpgradeParser.y
1 //===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements the bison parser for LLVM assembly languages files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 %{
15 #include "UpgradeInternals.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/InlineAsm.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/ValueSymbolTable.h"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/Support/MathExtras.h"
24 #include <algorithm>
25 #include <iostream>
26 #include <map>
27 #include <list>
28 #include <utility>
29
30 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
31 // relating to upreferences in the input stream.
32 //
33 //#define DEBUG_UPREFS 1
34 #ifdef DEBUG_UPREFS
35 #define UR_OUT(X) std::cerr << X
36 #else
37 #define UR_OUT(X)
38 #endif
39
40 #define YYERROR_VERBOSE 1
41 #define YYINCLUDED_STDLIB_H
42 #define YYDEBUG 1
43
44 int yylex();
45 int yyparse();
46
47 int yyerror(const char*);
48 static void warning(const std::string& WarningMsg);
49
50 namespace llvm {
51
52 std::istream* LexInput;
53 static std::string CurFilename;
54
55 // This bool controls whether attributes are ever added to function declarations
56 // definitions and calls.
57 static bool AddAttributes = false;
58
59 static Module *ParserResult;
60 static bool ObsoleteVarArgs;
61 static bool NewVarArgs;
62 static BasicBlock *CurBB;
63 static GlobalVariable *CurGV;
64
65 // This contains info used when building the body of a function.  It is
66 // destroyed when the function is completed.
67 //
68 typedef std::vector<Value *> ValueList;           // Numbered defs
69
70 typedef std::pair<std::string,TypeInfo> RenameMapKey;
71 typedef std::map<RenameMapKey,std::string> RenameMapType;
72
73 static void 
74 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
75                    std::map<const Type *,ValueList> *FutureLateResolvers = 0);
76
77 static struct PerModuleInfo {
78   Module *CurrentModule;
79   std::map<const Type *, ValueList> Values; // Module level numbered definitions
80   std::map<const Type *,ValueList> LateResolveValues;
81   std::vector<PATypeHolder>    Types;
82   std::map<ValID, PATypeHolder> LateResolveTypes;
83   static Module::Endianness Endian;
84   static Module::PointerSize PointerSize;
85   RenameMapType RenameMap;
86
87   /// PlaceHolderInfo - When temporary placeholder objects are created, remember
88   /// how they were referenced and on which line of the input they came from so
89   /// that we can resolve them later and print error messages as appropriate.
90   std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
91
92   // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
93   // references to global values.  Global values may be referenced before they
94   // are defined, and if so, the temporary object that they represent is held
95   // here.  This is used for forward references of GlobalValues.
96   //
97   typedef std::map<std::pair<const PointerType *, ValID>, GlobalValue*> 
98     GlobalRefsType;
99   GlobalRefsType GlobalRefs;
100
101   void ModuleDone() {
102     // If we could not resolve some functions at function compilation time
103     // (calls to functions before they are defined), resolve them now...  Types
104     // are resolved when the constant pool has been completely parsed.
105     //
106     ResolveDefinitions(LateResolveValues);
107
108     // Check to make sure that all global value forward references have been
109     // resolved!
110     //
111     if (!GlobalRefs.empty()) {
112       std::string UndefinedReferences = "Unresolved global references exist:\n";
113
114       for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
115            I != E; ++I) {
116         UndefinedReferences += "  " + I->first.first->getDescription() + " " +
117                                I->first.second.getName() + "\n";
118       }
119       error(UndefinedReferences);
120       return;
121     }
122
123     if (CurrentModule->getDataLayout().empty()) {
124       std::string dataLayout;
125       if (Endian != Module::AnyEndianness)
126         dataLayout.append(Endian == Module::BigEndian ? "E" : "e");
127       if (PointerSize != Module::AnyPointerSize) {
128         if (!dataLayout.empty())
129           dataLayout += "-";
130         dataLayout.append(PointerSize == Module::Pointer64 ? 
131                           "p:64:64" : "p:32:32");
132       }
133       CurrentModule->setDataLayout(dataLayout);
134     }
135
136     Values.clear();         // Clear out function local definitions
137     Types.clear();
138     CurrentModule = 0;
139   }
140
141   // GetForwardRefForGlobal - Check to see if there is a forward reference
142   // for this global.  If so, remove it from the GlobalRefs map and return it.
143   // If not, just return null.
144   GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
145     // Check to see if there is a forward reference to this global variable...
146     // if there is, eliminate it and patch the reference to use the new def'n.
147     GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
148     GlobalValue *Ret = 0;
149     if (I != GlobalRefs.end()) {
150       Ret = I->second;
151       GlobalRefs.erase(I);
152     }
153     return Ret;
154   }
155   void setEndianness(Module::Endianness E) { Endian = E; }
156   void setPointerSize(Module::PointerSize sz) { PointerSize = sz; }
157 } CurModule;
158
159 Module::Endianness  PerModuleInfo::Endian = Module::AnyEndianness;
160 Module::PointerSize PerModuleInfo::PointerSize = Module::AnyPointerSize;
161
162 static struct PerFunctionInfo {
163   Function *CurrentFunction;     // Pointer to current function being created
164
165   std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
166   std::map<const Type*, ValueList> LateResolveValues;
167   bool isDeclare;                   // Is this function a forward declararation?
168   GlobalValue::LinkageTypes Linkage;// Linkage for forward declaration.
169
170   /// BBForwardRefs - When we see forward references to basic blocks, keep
171   /// track of them here.
172   std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
173   std::vector<BasicBlock*> NumberedBlocks;
174   RenameMapType RenameMap;
175   unsigned NextBBNum;
176
177   inline PerFunctionInfo() {
178     CurrentFunction = 0;
179     isDeclare = false;
180     Linkage = GlobalValue::ExternalLinkage;    
181   }
182
183   inline void FunctionStart(Function *M) {
184     CurrentFunction = M;
185     NextBBNum = 0;
186   }
187
188   void FunctionDone() {
189     NumberedBlocks.clear();
190
191     // Any forward referenced blocks left?
192     if (!BBForwardRefs.empty()) {
193       error("Undefined reference to label " + 
194             BBForwardRefs.begin()->first->getName());
195       return;
196     }
197
198     // Resolve all forward references now.
199     ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
200
201     Values.clear();         // Clear out function local definitions
202     RenameMap.clear();
203     CurrentFunction = 0;
204     isDeclare = false;
205     Linkage = GlobalValue::ExternalLinkage;
206   }
207 } CurFun;  // Info for the current function...
208
209 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
210
211
212 //===----------------------------------------------------------------------===//
213 //               Code to handle definitions of all the types
214 //===----------------------------------------------------------------------===//
215
216 static int InsertValue(Value *V,
217                   std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
218   if (V->hasName()) return -1;           // Is this a numbered definition?
219
220   // Yes, insert the value into the value table...
221   ValueList &List = ValueTab[V->getType()];
222   List.push_back(V);
223   return List.size()-1;
224 }
225
226 static const Type *getType(const ValID &D, bool DoNotImprovise = false) {
227   switch (D.Type) {
228   case ValID::NumberVal:               // Is it a numbered definition?
229     // Module constants occupy the lowest numbered slots...
230     if ((unsigned)D.Num < CurModule.Types.size()) {
231       return CurModule.Types[(unsigned)D.Num];
232     }
233     break;
234   case ValID::NameVal:                 // Is it a named definition?
235     if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
236       D.destroy();  // Free old strdup'd memory...
237       return N;
238     }
239     break;
240   default:
241     error("Internal parser error: Invalid symbol type reference");
242     return 0;
243   }
244
245   // If we reached here, we referenced either a symbol that we don't know about
246   // or an id number that hasn't been read yet.  We may be referencing something
247   // forward, so just create an entry to be resolved later and get to it...
248   //
249   if (DoNotImprovise) return 0;  // Do we just want a null to be returned?
250
251
252   if (inFunctionScope()) {
253     if (D.Type == ValID::NameVal) {
254       error("Reference to an undefined type: '" + D.getName() + "'");
255       return 0;
256     } else {
257       error("Reference to an undefined type: #" + itostr(D.Num));
258       return 0;
259     }
260   }
261
262   std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
263   if (I != CurModule.LateResolveTypes.end())
264     return I->second;
265
266   Type *Typ = OpaqueType::get();
267   CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
268   return Typ;
269  }
270
271 /// This function determines if two function types differ only in their use of
272 /// the sret parameter attribute in the first argument. If they are identical 
273 /// in all other respects, it returns true. Otherwise, it returns false.
274 bool FuncTysDifferOnlyBySRet(const FunctionType *F1, 
275                                    const FunctionType *F2) {
276   if (F1->getReturnType() != F2->getReturnType() ||
277       F1->getNumParams() != F2->getNumParams() ||
278       F1->getParamAttrs(0) != F2->getParamAttrs(0))
279     return false;
280   unsigned SRetMask = ~unsigned(FunctionType::StructRetAttribute);
281   for (unsigned i = 0; i < F1->getNumParams(); ++i) {
282     if (F1->getParamType(i) != F2->getParamType(i) ||
283         unsigned(F1->getParamAttrs(i+1)) & SRetMask !=
284         unsigned(F2->getParamAttrs(i+1)) & SRetMask)
285       return false;
286   }
287   return true;
288 }
289 bool TypesDifferOnlyBySRet(Value *V, const Type* Ty) {
290   if (V->getType() == Ty)
291     return true;
292   const PointerType *PF1 = dyn_cast<PointerType>(Ty);
293   const PointerType *PF2 = dyn_cast<PointerType>(V->getType());
294   if (PF1 && PF2) {
295     const FunctionType* FT1 = dyn_cast<FunctionType>(PF1->getElementType());
296     const FunctionType* FT2 = dyn_cast<FunctionType>(PF2->getElementType());
297     if (FT1 && FT2)
298       return FuncTysDifferOnlyBySRet(FT1, FT2);
299   }
300   return false;
301 }
302
303 // The upgrade of csretcc to sret param attribute may have caused a function 
304 // to not be found because the param attribute changed the type of the called 
305 // function. This helper function, used in getExistingValue, detects that
306 // situation and bitcasts the function to the correct type.
307 static Value* handleSRetFuncTypeMerge(Value *V, const Type* Ty) {
308   // Handle degenerate cases
309   if (!V)
310     return 0;
311   if (V->getType() == Ty)
312     return V;
313
314   Value* Result = 0;
315   const PointerType *PF1 = dyn_cast<PointerType>(Ty);
316   const PointerType *PF2 = dyn_cast<PointerType>(V->getType());
317   if (PF1 && PF2) {
318     const FunctionType *FT1 = dyn_cast<FunctionType>(PF1->getElementType());
319     const FunctionType *FT2 = dyn_cast<FunctionType>(PF2->getElementType());
320     if (FT1 && FT2 && FuncTysDifferOnlyBySRet(FT1, FT2))
321       if (FT2->paramHasAttr(1, FunctionType::StructRetAttribute))
322         Result = V;
323       else if (Constant *C = dyn_cast<Constant>(V))
324         Result = ConstantExpr::getBitCast(C, PF1);
325       else
326         Result = new BitCastInst(V, PF1, "upgrd.cast", CurBB);
327   }
328   return Result;
329 }
330
331 // getExistingValue - Look up the value specified by the provided type and
332 // the provided ValID.  If the value exists and has already been defined, return
333 // it.  Otherwise return null.
334 //
335 static Value *getExistingValue(const Type *Ty, const ValID &D) {
336   if (isa<FunctionType>(Ty)) {
337     error("Functions are not values and must be referenced as pointers");
338   }
339
340   switch (D.Type) {
341   case ValID::NumberVal: {                 // Is it a numbered definition?
342     unsigned Num = (unsigned)D.Num;
343
344     // Module constants occupy the lowest numbered slots...
345     std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
346     if (VI != CurModule.Values.end()) {
347       if (Num < VI->second.size())
348         return VI->second[Num];
349       Num -= VI->second.size();
350     }
351
352     // Make sure that our type is within bounds
353     VI = CurFun.Values.find(Ty);
354     if (VI == CurFun.Values.end()) return 0;
355
356     // Check that the number is within bounds...
357     if (VI->second.size() <= Num) return 0;
358
359     return VI->second[Num];
360   }
361
362   case ValID::NameVal: {                // Is it a named definition?
363     // Get the name out of the ID
364     std::string Name(D.Name);
365     Value* V = 0;
366     TypeInfo TI; TI.T = Ty; TI.S = D.S;
367     RenameMapKey Key = std::make_pair(Name, TI);
368     if (inFunctionScope()) {
369       // See if the name was renamed
370       RenameMapType::const_iterator I = CurFun.RenameMap.find(Key);
371       std::string LookupName;
372       if (I != CurFun.RenameMap.end())
373         LookupName = I->second;
374       else
375         LookupName = Name;
376       ValueSymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
377       V = SymTab.lookup(LookupName);
378       V = handleSRetFuncTypeMerge(V, Ty);
379       assert((!V || TypesDifferOnlyBySRet(V, Ty)) && "Found wrong type!");
380     }
381     if (!V) {
382       RenameMapType::const_iterator I = CurModule.RenameMap.find(Key);
383       std::string LookupName;
384       if (I != CurModule.RenameMap.end())
385         LookupName = I->second;
386       else
387         LookupName = Name;
388       V = CurModule.CurrentModule->getValueSymbolTable().lookup(LookupName);
389       V = handleSRetFuncTypeMerge(V, Ty);
390       assert((!V || TypesDifferOnlyBySRet(V, Ty)) && "Found wrong type!");
391     }
392     if (!V) 
393       return 0;
394
395     D.destroy();  // Free old strdup'd memory...
396     return V;
397   }
398
399   // Check to make sure that "Ty" is an integral type, and that our
400   // value will fit into the specified type...
401   case ValID::ConstSIntVal:    // Is it a constant pool reference??
402     if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
403       error("Signed integral constant '" + itostr(D.ConstPool64) + 
404             "' is invalid for type '" + Ty->getDescription() + "'");
405     }
406     return ConstantInt::get(Ty, D.ConstPool64);
407
408   case ValID::ConstUIntVal:     // Is it an unsigned const pool reference?
409     if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
410       if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64))
411         error("Integral constant '" + utostr(D.UConstPool64) + 
412               "' is invalid or out of range");
413       else     // This is really a signed reference.  Transmogrify.
414         return ConstantInt::get(Ty, D.ConstPool64);
415     } else
416       return ConstantInt::get(Ty, D.UConstPool64);
417
418   case ValID::ConstFPVal:        // Is it a floating point const pool reference?
419     if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
420       error("FP constant invalid for type");
421     return ConstantFP::get(Ty, D.ConstPoolFP);
422
423   case ValID::ConstNullVal:      // Is it a null value?
424     if (!isa<PointerType>(Ty))
425       error("Cannot create a a non pointer null");
426     return ConstantPointerNull::get(cast<PointerType>(Ty));
427
428   case ValID::ConstUndefVal:      // Is it an undef value?
429     return UndefValue::get(Ty);
430
431   case ValID::ConstZeroVal:      // Is it a zero value?
432     return Constant::getNullValue(Ty);
433     
434   case ValID::ConstantVal:       // Fully resolved constant?
435     if (D.ConstantValue->getType() != Ty) 
436       error("Constant expression type different from required type");
437     return D.ConstantValue;
438
439   case ValID::InlineAsmVal: {    // Inline asm expression
440     const PointerType *PTy = dyn_cast<PointerType>(Ty);
441     const FunctionType *FTy =
442       PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
443     if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints))
444       error("Invalid type for asm constraint string");
445     InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
446                                    D.IAD->HasSideEffects);
447     D.destroy();   // Free InlineAsmDescriptor.
448     return IA;
449   }
450   default:
451     assert(0 && "Unhandled case");
452     return 0;
453   }   // End of switch
454
455   assert(0 && "Unhandled case");
456   return 0;
457 }
458
459 // getVal - This function is identical to getExistingValue, except that if a
460 // value is not already defined, it "improvises" by creating a placeholder var
461 // that looks and acts just like the requested variable.  When the value is
462 // defined later, all uses of the placeholder variable are replaced with the
463 // real thing.
464 //
465 static Value *getVal(const Type *Ty, const ValID &ID) {
466   if (Ty == Type::LabelTy)
467     error("Cannot use a basic block here");
468
469   // See if the value has already been defined.
470   Value *V = getExistingValue(Ty, ID);
471   if (V) return V;
472
473   if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty))
474     error("Invalid use of a composite type");
475
476   // If we reached here, we referenced either a symbol that we don't know about
477   // or an id number that hasn't been read yet.  We may be referencing something
478   // forward, so just create an entry to be resolved later and get to it...
479   V = new Argument(Ty);
480
481   // Remember where this forward reference came from.  FIXME, shouldn't we try
482   // to recycle these things??
483   CurModule.PlaceHolderInfo.insert(
484     std::make_pair(V, std::make_pair(ID, Upgradelineno)));
485
486   if (inFunctionScope())
487     InsertValue(V, CurFun.LateResolveValues);
488   else
489     InsertValue(V, CurModule.LateResolveValues);
490   return V;
491 }
492
493 /// @brief This just makes any name given to it unique, up to MAX_UINT times.
494 static std::string makeNameUnique(const std::string& Name) {
495   static unsigned UniqueNameCounter = 1;
496   std::string Result(Name);
497   Result += ".upgrd." + llvm::utostr(UniqueNameCounter++);
498   return Result;
499 }
500
501 /// getBBVal - This is used for two purposes:
502 ///  * If isDefinition is true, a new basic block with the specified ID is being
503 ///    defined.
504 ///  * If isDefinition is true, this is a reference to a basic block, which may
505 ///    or may not be a forward reference.
506 ///
507 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
508   assert(inFunctionScope() && "Can't get basic block at global scope");
509
510   std::string Name;
511   BasicBlock *BB = 0;
512   switch (ID.Type) {
513   default: 
514     error("Illegal label reference " + ID.getName());
515     break;
516   case ValID::NumberVal:                // Is it a numbered definition?
517     if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
518       CurFun.NumberedBlocks.resize(ID.Num+1);
519     BB = CurFun.NumberedBlocks[ID.Num];
520     break;
521   case ValID::NameVal:                  // Is it a named definition?
522     Name = ID.Name;
523     if (Value *N = CurFun.CurrentFunction->
524                    getValueSymbolTable().lookup(Name)) {
525       if (N->getType() != Type::LabelTy) {
526         // Register names didn't use to conflict with basic block names
527         // because of type planes. Now they all have to be unique. So, we just
528         // rename the register and treat this name as if no basic block
529         // had been found.
530         TypeInfo TI; TI.T = N->getType(); TI.S = ID.S;
531         RenameMapKey Key = std::make_pair(N->getName(),TI);
532         N->setName(makeNameUnique(N->getName()));
533         CurModule.RenameMap[Key] = N->getName();
534         BB = 0;
535       } else {
536         BB = cast<BasicBlock>(N);
537       }
538     }
539     break;
540   }
541
542   // See if the block has already been defined.
543   if (BB) {
544     // If this is the definition of the block, make sure the existing value was
545     // just a forward reference.  If it was a forward reference, there will be
546     // an entry for it in the PlaceHolderInfo map.
547     if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
548       // The existing value was a definition, not a forward reference.
549       error("Redefinition of label " + ID.getName());
550
551     ID.destroy();                       // Free strdup'd memory.
552     return BB;
553   }
554
555   // Otherwise this block has not been seen before.
556   BB = new BasicBlock("", CurFun.CurrentFunction);
557   if (ID.Type == ValID::NameVal) {
558     BB->setName(ID.Name);
559   } else {
560     CurFun.NumberedBlocks[ID.Num] = BB;
561   }
562
563   // If this is not a definition, keep track of it so we can use it as a forward
564   // reference.
565   if (!isDefinition) {
566     // Remember where this forward reference came from.
567     CurFun.BBForwardRefs[BB] = std::make_pair(ID, Upgradelineno);
568   } else {
569     // The forward declaration could have been inserted anywhere in the
570     // function: insert it into the correct place now.
571     CurFun.CurrentFunction->getBasicBlockList().remove(BB);
572     CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
573   }
574   ID.destroy();
575   return BB;
576 }
577
578
579 //===----------------------------------------------------------------------===//
580 //              Code to handle forward references in instructions
581 //===----------------------------------------------------------------------===//
582 //
583 // This code handles the late binding needed with statements that reference
584 // values not defined yet... for example, a forward branch, or the PHI node for
585 // a loop body.
586 //
587 // This keeps a table (CurFun.LateResolveValues) of all such forward references
588 // and back patchs after we are done.
589 //
590
591 // ResolveDefinitions - If we could not resolve some defs at parsing
592 // time (forward branches, phi functions for loops, etc...) resolve the
593 // defs now...
594 //
595 static void 
596 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
597                    std::map<const Type*,ValueList> *FutureLateResolvers) {
598
599   // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
600   for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
601          E = LateResolvers.end(); LRI != E; ++LRI) {
602     const Type* Ty = LRI->first;
603     ValueList &List = LRI->second;
604     while (!List.empty()) {
605       Value *V = List.back();
606       List.pop_back();
607
608       std::map<Value*, std::pair<ValID, int> >::iterator PHI =
609         CurModule.PlaceHolderInfo.find(V);
610       assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error");
611
612       ValID &DID = PHI->second.first;
613
614       Value *TheRealValue = getExistingValue(Ty, DID);
615       if (TheRealValue) {
616         V->replaceAllUsesWith(TheRealValue);
617         delete V;
618         CurModule.PlaceHolderInfo.erase(PHI);
619       } else if (FutureLateResolvers) {
620         // Functions have their unresolved items forwarded to the module late
621         // resolver table
622         InsertValue(V, *FutureLateResolvers);
623       } else {
624         if (DID.Type == ValID::NameVal) {
625           error("Reference to an invalid definition: '" + DID.getName() +
626                 "' of type '" + V->getType()->getDescription() + "'",
627                 PHI->second.second);
628             return;
629         } else {
630           error("Reference to an invalid definition: #" +
631                 itostr(DID.Num) + " of type '" + 
632                 V->getType()->getDescription() + "'", PHI->second.second);
633           return;
634         }
635       }
636     }
637   }
638
639   LateResolvers.clear();
640 }
641
642 // ResolveTypeTo - A brand new type was just declared.  This means that (if
643 // name is not null) things referencing Name can be resolved.  Otherwise, things
644 // refering to the number can be resolved.  Do this now.
645 //
646 static void ResolveTypeTo(char *Name, const Type *ToTy, Signedness Sign) {
647   ValID D;
648   if (Name) 
649     D = ValID::create(Name, Sign);
650   else      
651     D = ValID::create((int)CurModule.Types.size(), Sign);
652
653   std::map<ValID, PATypeHolder>::iterator I =
654     CurModule.LateResolveTypes.find(D);
655   if (I != CurModule.LateResolveTypes.end()) {
656     ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
657     CurModule.LateResolveTypes.erase(I);
658   }
659 }
660
661 /// This is the implementation portion of TypeHasInteger. It traverses the
662 /// type given, avoiding recursive types, and returns true as soon as it finds
663 /// an integer type. If no integer type is found, it returns false.
664 static bool TypeHasIntegerI(const Type *Ty, std::vector<const Type*> Stack) {
665   // Handle some easy cases
666   if (Ty->isPrimitiveType() || (Ty->getTypeID() == Type::OpaqueTyID))
667     return false;
668   if (Ty->isInteger())
669     return true;
670   if (const SequentialType *STy = dyn_cast<SequentialType>(Ty))
671     return STy->getElementType()->isInteger();
672
673   // Avoid type structure recursion
674   for (std::vector<const Type*>::iterator I = Stack.begin(), E = Stack.end();
675        I != E; ++I)
676     if (Ty == *I)
677       return false;
678
679   // Push us on the type stack
680   Stack.push_back(Ty);
681
682   if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
683     if (TypeHasIntegerI(FTy->getReturnType(), Stack)) 
684       return true;
685     FunctionType::param_iterator I = FTy->param_begin();
686     FunctionType::param_iterator E = FTy->param_end();
687     for (; I != E; ++I)
688       if (TypeHasIntegerI(*I, Stack))
689         return true;
690     return false;
691   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
692     StructType::element_iterator I = STy->element_begin();
693     StructType::element_iterator E = STy->element_end();
694     for (; I != E; ++I) {
695       if (TypeHasIntegerI(*I, Stack))
696         return true;
697     }
698     return false;
699   }
700   // There shouldn't be anything else, but its definitely not integer
701   assert(0 && "What type is this?");
702   return false;
703 }
704
705 /// This is the interface to TypeHasIntegerI. It just provides the type stack,
706 /// to avoid recursion, and then calls TypeHasIntegerI.
707 static inline bool TypeHasInteger(const Type *Ty) {
708   std::vector<const Type*> TyStack;
709   return TypeHasIntegerI(Ty, TyStack);
710 }
711
712 // setValueName - Set the specified value to the name given.  The name may be
713 // null potentially, in which case this is a noop.  The string passed in is
714 // assumed to be a malloc'd string buffer, and is free'd by this function.
715 //
716 static void setValueName(const ValueInfo &V, char *NameStr) {
717   if (NameStr) {
718     std::string Name(NameStr);      // Copy string
719     free(NameStr);                  // Free old string
720
721     if (V.V->getType() == Type::VoidTy) {
722       error("Can't assign name '" + Name + "' to value with void type");
723       return;
724     }
725
726     assert(inFunctionScope() && "Must be in function scope");
727
728     // Search the function's symbol table for an existing value of this name
729     ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
730     Value* Existing = ST.lookup(Name);
731     if (Existing) {
732       // An existing value of the same name was found. This might have happened
733       // because of the integer type planes collapsing in LLVM 2.0. 
734       if (Existing->getType() == V.V->getType() &&
735           !TypeHasInteger(Existing->getType())) {
736         // If the type does not contain any integers in them then this can't be
737         // a type plane collapsing issue. It truly is a redefinition and we 
738         // should error out as the assembly is invalid.
739         error("Redefinition of value named '" + Name + "' of type '" +
740               V.V->getType()->getDescription() + "'");
741         return;
742       } 
743       // In LLVM 2.0 we don't allow names to be re-used for any values in a 
744       // function, regardless of Type. Previously re-use of names was okay as 
745       // long as they were distinct types. With type planes collapsing because
746       // of the signedness change and because of PR411, this can no longer be
747       // supported. We must search the entire symbol table for a conflicting
748       // name and make the name unique. No warning is needed as this can't 
749       // cause a problem.
750       std::string NewName = makeNameUnique(Name);
751       // We're changing the name but it will probably be used by other 
752       // instructions as operands later on. Consequently we have to retain
753       // a mapping of the renaming that we're doing.
754       TypeInfo TI;
755       TI.T = V.V->getType();
756       TI.S = V.S;
757       RenameMapKey Key = std::make_pair(Name,TI);
758       CurFun.RenameMap[Key] = NewName;
759       Name = NewName;
760     }
761
762     // Set the name.
763     V.V->setName(Name);
764   }
765 }
766
767 /// ParseGlobalVariable - Handle parsing of a global.  If Initializer is null,
768 /// this is a declaration, otherwise it is a definition.
769 static GlobalVariable *
770 ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
771                     bool isConstantGlobal, const Type *Ty,
772                     Constant *Initializer,
773                     Signedness Sign) {
774   if (isa<FunctionType>(Ty))
775     error("Cannot declare global vars of function type");
776
777   const PointerType *PTy = PointerType::get(Ty);
778
779   std::string Name;
780   if (NameStr) {
781     Name = NameStr;      // Copy string
782     free(NameStr);       // Free old string
783   }
784
785   // See if this global value was forward referenced.  If so, recycle the
786   // object.
787   ValID ID;
788   if (!Name.empty()) {
789     ID = ValID::create((char*)Name.c_str(), Sign);
790   } else {
791     ID = ValID::create((int)CurModule.Values[PTy].size(), Sign);
792   }
793
794   if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
795     // Move the global to the end of the list, from whereever it was
796     // previously inserted.
797     GlobalVariable *GV = cast<GlobalVariable>(FWGV);
798     CurModule.CurrentModule->getGlobalList().remove(GV);
799     CurModule.CurrentModule->getGlobalList().push_back(GV);
800     GV->setInitializer(Initializer);
801     GV->setLinkage(Linkage);
802     GV->setConstant(isConstantGlobal);
803     InsertValue(GV, CurModule.Values);
804     return GV;
805   }
806
807   // If this global has a name, check to see if there is already a definition
808   // of this global in the module and emit warnings if there are conflicts.
809   if (!Name.empty()) {
810     // The global has a name. See if there's an existing one of the same name.
811     if (CurModule.CurrentModule->getNamedGlobal(Name)) {
812       // We found an existing global ov the same name. This isn't allowed 
813       // in LLVM 2.0. Consequently, we must alter the name of the global so it
814       // can at least compile. This can happen because of type planes 
815       // There is alread a global of the same name which means there is a
816       // conflict. Let's see what we can do about it.
817       std::string NewName(makeNameUnique(Name));
818       if (Linkage == GlobalValue::InternalLinkage) {
819         // The linkage type is internal so just warn about the rename without
820         // invoking "scarey language" about linkage failures. GVars with
821         // InternalLinkage can be renamed at will.
822         warning("Global variable '" + Name + "' was renamed to '"+ 
823                 NewName + "'");
824       } else {
825         // The linkage of this gval is external so we can't reliably rename 
826         // it because it could potentially create a linking problem.  
827         // However, we can't leave the name conflict in the output either or 
828         // it won't assemble with LLVM 2.0.  So, all we can do is rename 
829         // this one to something unique and emit a warning about the problem.
830         warning("Renaming global variable '" + Name + "' to '" + NewName + 
831                   "' may cause linkage errors");
832       }
833
834       // Put the renaming in the global rename map
835       TypeInfo TI; TI.T = PointerType::get(Ty); TI.S = Signless;
836       RenameMapKey Key = std::make_pair(Name,TI);
837       CurModule.RenameMap[Key] = NewName;
838
839       // Rename it
840       Name = NewName;
841     }
842   }
843
844   // Otherwise there is no existing GV to use, create one now.
845   GlobalVariable *GV =
846     new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
847                        CurModule.CurrentModule);
848   InsertValue(GV, CurModule.Values);
849   return GV;
850 }
851
852 // setTypeName - Set the specified type to the name given.  The name may be
853 // null potentially, in which case this is a noop.  The string passed in is
854 // assumed to be a malloc'd string buffer, and is freed by this function.
855 //
856 // This function returns true if the type has already been defined, but is
857 // allowed to be redefined in the specified context.  If the name is a new name
858 // for the type plane, it is inserted and false is returned.
859 static bool setTypeName(const Type *T, char *NameStr) {
860   assert(!inFunctionScope() && "Can't give types function-local names");
861   if (NameStr == 0) return false;
862  
863   std::string Name(NameStr);      // Copy string
864   free(NameStr);                  // Free old string
865
866   // We don't allow assigning names to void type
867   if (T == Type::VoidTy) {
868     error("Can't assign name '" + Name + "' to the void type");
869     return false;
870   }
871
872   // Set the type name, checking for conflicts as we do so.
873   bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
874
875   if (AlreadyExists) {   // Inserting a name that is already defined???
876     const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
877     assert(Existing && "Conflict but no matching type?");
878
879     // There is only one case where this is allowed: when we are refining an
880     // opaque type.  In this case, Existing will be an opaque type.
881     if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
882       // We ARE replacing an opaque type!
883       const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
884       return true;
885     }
886
887     // Otherwise, this is an attempt to redefine a type. That's okay if
888     // the redefinition is identical to the original. This will be so if
889     // Existing and T point to the same Type object. In this one case we
890     // allow the equivalent redefinition.
891     if (Existing == T) return true;  // Yes, it's equal.
892
893     // Any other kind of (non-equivalent) redefinition is an error.
894     error("Redefinition of type named '" + Name + "' in the '" +
895           T->getDescription() + "' type plane");
896   }
897
898   return false;
899 }
900
901 //===----------------------------------------------------------------------===//
902 // Code for handling upreferences in type names...
903 //
904
905 // TypeContains - Returns true if Ty directly contains E in it.
906 //
907 static bool TypeContains(const Type *Ty, const Type *E) {
908   return std::find(Ty->subtype_begin(), Ty->subtype_end(),
909                    E) != Ty->subtype_end();
910 }
911
912 namespace {
913   struct UpRefRecord {
914     // NestingLevel - The number of nesting levels that need to be popped before
915     // this type is resolved.
916     unsigned NestingLevel;
917
918     // LastContainedTy - This is the type at the current binding level for the
919     // type.  Every time we reduce the nesting level, this gets updated.
920     const Type *LastContainedTy;
921
922     // UpRefTy - This is the actual opaque type that the upreference is
923     // represented with.
924     OpaqueType *UpRefTy;
925
926     UpRefRecord(unsigned NL, OpaqueType *URTy)
927       : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
928   };
929 }
930
931 // UpRefs - A list of the outstanding upreferences that need to be resolved.
932 static std::vector<UpRefRecord> UpRefs;
933
934 /// HandleUpRefs - Every time we finish a new layer of types, this function is
935 /// called.  It loops through the UpRefs vector, which is a list of the
936 /// currently active types.  For each type, if the up reference is contained in
937 /// the newly completed type, we decrement the level count.  When the level
938 /// count reaches zero, the upreferenced type is the type that is passed in:
939 /// thus we can complete the cycle.
940 ///
941 static PATypeHolder HandleUpRefs(const Type *ty) {
942   // If Ty isn't abstract, or if there are no up-references in it, then there is
943   // nothing to resolve here.
944   if (!ty->isAbstract() || UpRefs.empty()) return ty;
945   
946   PATypeHolder Ty(ty);
947   UR_OUT("Type '" << Ty->getDescription() <<
948          "' newly formed.  Resolving upreferences.\n" <<
949          UpRefs.size() << " upreferences active!\n");
950
951   // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
952   // to zero), we resolve them all together before we resolve them to Ty.  At
953   // the end of the loop, if there is anything to resolve to Ty, it will be in
954   // this variable.
955   OpaqueType *TypeToResolve = 0;
956
957   for (unsigned i = 0; i != UpRefs.size(); ++i) {
958     UR_OUT("  UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
959            << UpRefs[i].second->getDescription() << ") = "
960            << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
961     if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
962       // Decrement level of upreference
963       unsigned Level = --UpRefs[i].NestingLevel;
964       UpRefs[i].LastContainedTy = Ty;
965       UR_OUT("  Uplevel Ref Level = " << Level << "\n");
966       if (Level == 0) {                     // Upreference should be resolved!
967         if (!TypeToResolve) {
968           TypeToResolve = UpRefs[i].UpRefTy;
969         } else {
970           UR_OUT("  * Resolving upreference for "
971                  << UpRefs[i].second->getDescription() << "\n";
972                  std::string OldName = UpRefs[i].UpRefTy->getDescription());
973           UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
974           UR_OUT("  * Type '" << OldName << "' refined upreference to: "
975                  << (const void*)Ty << ", " << Ty->getDescription() << "\n");
976         }
977         UpRefs.erase(UpRefs.begin()+i);     // Remove from upreference list...
978         --i;                                // Do not skip the next element...
979       }
980     }
981   }
982
983   if (TypeToResolve) {
984     UR_OUT("  * Resolving upreference for "
985            << UpRefs[i].second->getDescription() << "\n";
986            std::string OldName = TypeToResolve->getDescription());
987     TypeToResolve->refineAbstractTypeTo(Ty);
988   }
989
990   return Ty;
991 }
992
993 static inline Instruction::TermOps 
994 getTermOp(TermOps op) {
995   switch (op) {
996     default           : assert(0 && "Invalid OldTermOp");
997     case RetOp        : return Instruction::Ret;
998     case BrOp         : return Instruction::Br;
999     case SwitchOp     : return Instruction::Switch;
1000     case InvokeOp     : return Instruction::Invoke;
1001     case UnwindOp     : return Instruction::Unwind;
1002     case UnreachableOp: return Instruction::Unreachable;
1003   }
1004 }
1005
1006 static inline Instruction::BinaryOps 
1007 getBinaryOp(BinaryOps op, const Type *Ty, Signedness Sign) {
1008   switch (op) {
1009     default     : assert(0 && "Invalid OldBinaryOps");
1010     case SetEQ  : 
1011     case SetNE  : 
1012     case SetLE  :
1013     case SetGE  :
1014     case SetLT  :
1015     case SetGT  : assert(0 && "Should use getCompareOp");
1016     case AddOp  : return Instruction::Add;
1017     case SubOp  : return Instruction::Sub;
1018     case MulOp  : return Instruction::Mul;
1019     case DivOp  : {
1020       // This is an obsolete instruction so we must upgrade it based on the
1021       // types of its operands.
1022       bool isFP = Ty->isFloatingPoint();
1023       if (const VectorType* PTy = dyn_cast<VectorType>(Ty))
1024         // If its a vector type we want to use the element type
1025         isFP = PTy->getElementType()->isFloatingPoint();
1026       if (isFP)
1027         return Instruction::FDiv;
1028       else if (Sign == Signed)
1029         return Instruction::SDiv;
1030       return Instruction::UDiv;
1031     }
1032     case UDivOp : return Instruction::UDiv;
1033     case SDivOp : return Instruction::SDiv;
1034     case FDivOp : return Instruction::FDiv;
1035     case RemOp  : {
1036       // This is an obsolete instruction so we must upgrade it based on the
1037       // types of its operands.
1038       bool isFP = Ty->isFloatingPoint();
1039       if (const VectorType* PTy = dyn_cast<VectorType>(Ty))
1040         // If its a vector type we want to use the element type
1041         isFP = PTy->getElementType()->isFloatingPoint();
1042       // Select correct opcode
1043       if (isFP)
1044         return Instruction::FRem;
1045       else if (Sign == Signed)
1046         return Instruction::SRem;
1047       return Instruction::URem;
1048     }
1049     case URemOp : return Instruction::URem;
1050     case SRemOp : return Instruction::SRem;
1051     case FRemOp : return Instruction::FRem;
1052     case LShrOp : return Instruction::LShr;
1053     case AShrOp : return Instruction::AShr;
1054     case ShlOp  : return Instruction::Shl;
1055     case ShrOp  : 
1056       if (Sign == Signed)
1057         return Instruction::AShr;
1058       return Instruction::LShr;
1059     case AndOp  : return Instruction::And;
1060     case OrOp   : return Instruction::Or;
1061     case XorOp  : return Instruction::Xor;
1062   }
1063 }
1064
1065 static inline Instruction::OtherOps 
1066 getCompareOp(BinaryOps op, unsigned short &predicate, const Type* &Ty,
1067              Signedness Sign) {
1068   bool isSigned = Sign == Signed;
1069   bool isFP = Ty->isFloatingPoint();
1070   switch (op) {
1071     default     : assert(0 && "Invalid OldSetCC");
1072     case SetEQ  : 
1073       if (isFP) {
1074         predicate = FCmpInst::FCMP_OEQ;
1075         return Instruction::FCmp;
1076       } else {
1077         predicate = ICmpInst::ICMP_EQ;
1078         return Instruction::ICmp;
1079       }
1080     case SetNE  : 
1081       if (isFP) {
1082         predicate = FCmpInst::FCMP_UNE;
1083         return Instruction::FCmp;
1084       } else {
1085         predicate = ICmpInst::ICMP_NE;
1086         return Instruction::ICmp;
1087       }
1088     case SetLE  : 
1089       if (isFP) {
1090         predicate = FCmpInst::FCMP_OLE;
1091         return Instruction::FCmp;
1092       } else {
1093         if (isSigned)
1094           predicate = ICmpInst::ICMP_SLE;
1095         else
1096           predicate = ICmpInst::ICMP_ULE;
1097         return Instruction::ICmp;
1098       }
1099     case SetGE  : 
1100       if (isFP) {
1101         predicate = FCmpInst::FCMP_OGE;
1102         return Instruction::FCmp;
1103       } else {
1104         if (isSigned)
1105           predicate = ICmpInst::ICMP_SGE;
1106         else
1107           predicate = ICmpInst::ICMP_UGE;
1108         return Instruction::ICmp;
1109       }
1110     case SetLT  : 
1111       if (isFP) {
1112         predicate = FCmpInst::FCMP_OLT;
1113         return Instruction::FCmp;
1114       } else {
1115         if (isSigned)
1116           predicate = ICmpInst::ICMP_SLT;
1117         else
1118           predicate = ICmpInst::ICMP_ULT;
1119         return Instruction::ICmp;
1120       }
1121     case SetGT  : 
1122       if (isFP) {
1123         predicate = FCmpInst::FCMP_OGT;
1124         return Instruction::FCmp;
1125       } else {
1126         if (isSigned)
1127           predicate = ICmpInst::ICMP_SGT;
1128         else
1129           predicate = ICmpInst::ICMP_UGT;
1130         return Instruction::ICmp;
1131       }
1132   }
1133 }
1134
1135 static inline Instruction::MemoryOps getMemoryOp(MemoryOps op) {
1136   switch (op) {
1137     default              : assert(0 && "Invalid OldMemoryOps");
1138     case MallocOp        : return Instruction::Malloc;
1139     case FreeOp          : return Instruction::Free;
1140     case AllocaOp        : return Instruction::Alloca;
1141     case LoadOp          : return Instruction::Load;
1142     case StoreOp         : return Instruction::Store;
1143     case GetElementPtrOp : return Instruction::GetElementPtr;
1144   }
1145 }
1146
1147 static inline Instruction::OtherOps 
1148 getOtherOp(OtherOps op, Signedness Sign) {
1149   switch (op) {
1150     default               : assert(0 && "Invalid OldOtherOps");
1151     case PHIOp            : return Instruction::PHI;
1152     case CallOp           : return Instruction::Call;
1153     case SelectOp         : return Instruction::Select;
1154     case UserOp1          : return Instruction::UserOp1;
1155     case UserOp2          : return Instruction::UserOp2;
1156     case VAArg            : return Instruction::VAArg;
1157     case ExtractElementOp : return Instruction::ExtractElement;
1158     case InsertElementOp  : return Instruction::InsertElement;
1159     case ShuffleVectorOp  : return Instruction::ShuffleVector;
1160     case ICmpOp           : return Instruction::ICmp;
1161     case FCmpOp           : return Instruction::FCmp;
1162   };
1163 }
1164
1165 static inline Value*
1166 getCast(CastOps op, Value *Src, Signedness SrcSign, const Type *DstTy, 
1167         Signedness DstSign, bool ForceInstruction = false) {
1168   Instruction::CastOps Opcode;
1169   const Type* SrcTy = Src->getType();
1170   if (op == CastOp) {
1171     if (SrcTy->isFloatingPoint() && isa<PointerType>(DstTy)) {
1172       // fp -> ptr cast is no longer supported but we must upgrade this
1173       // by doing a double cast: fp -> int -> ptr
1174       SrcTy = Type::Int64Ty;
1175       Opcode = Instruction::IntToPtr;
1176       if (isa<Constant>(Src)) {
1177         Src = ConstantExpr::getCast(Instruction::FPToUI, 
1178                                      cast<Constant>(Src), SrcTy);
1179       } else {
1180         std::string NewName(makeNameUnique(Src->getName()));
1181         Src = new FPToUIInst(Src, SrcTy, NewName, CurBB);
1182       }
1183     } else if (isa<IntegerType>(DstTy) &&
1184                cast<IntegerType>(DstTy)->getBitWidth() == 1) {
1185       // cast type %x to bool was previously defined as setne type %x, null
1186       // The cast semantic is now to truncate, not compare so we must retain
1187       // the original intent by replacing the cast with a setne
1188       Constant* Null = Constant::getNullValue(SrcTy);
1189       Instruction::OtherOps Opcode = Instruction::ICmp;
1190       unsigned short predicate = ICmpInst::ICMP_NE;
1191       if (SrcTy->isFloatingPoint()) {
1192         Opcode = Instruction::FCmp;
1193         predicate = FCmpInst::FCMP_ONE;
1194       } else if (!SrcTy->isInteger() && !isa<PointerType>(SrcTy)) {
1195         error("Invalid cast to bool");
1196       }
1197       if (isa<Constant>(Src) && !ForceInstruction)
1198         return ConstantExpr::getCompare(predicate, cast<Constant>(Src), Null);
1199       else
1200         return CmpInst::create(Opcode, predicate, Src, Null);
1201     }
1202     // Determine the opcode to use by calling CastInst::getCastOpcode
1203     Opcode = 
1204       CastInst::getCastOpcode(Src, SrcSign == Signed, DstTy, DstSign == Signed);
1205
1206   } else switch (op) {
1207     default: assert(0 && "Invalid cast token");
1208     case TruncOp:    Opcode = Instruction::Trunc; break;
1209     case ZExtOp:     Opcode = Instruction::ZExt; break;
1210     case SExtOp:     Opcode = Instruction::SExt; break;
1211     case FPTruncOp:  Opcode = Instruction::FPTrunc; break;
1212     case FPExtOp:    Opcode = Instruction::FPExt; break;
1213     case FPToUIOp:   Opcode = Instruction::FPToUI; break;
1214     case FPToSIOp:   Opcode = Instruction::FPToSI; break;
1215     case UIToFPOp:   Opcode = Instruction::UIToFP; break;
1216     case SIToFPOp:   Opcode = Instruction::SIToFP; break;
1217     case PtrToIntOp: Opcode = Instruction::PtrToInt; break;
1218     case IntToPtrOp: Opcode = Instruction::IntToPtr; break;
1219     case BitCastOp:  Opcode = Instruction::BitCast; break;
1220   }
1221
1222   if (isa<Constant>(Src) && !ForceInstruction)
1223     return ConstantExpr::getCast(Opcode, cast<Constant>(Src), DstTy);
1224   return CastInst::create(Opcode, Src, DstTy);
1225 }
1226
1227 static Instruction *
1228 upgradeIntrinsicCall(const Type* RetTy, const ValID &ID, 
1229                      std::vector<Value*>& Args) {
1230
1231   std::string Name = ID.Type == ValID::NameVal ? ID.Name : "";
1232   if (Name == "llvm.isunordered.f32" || Name == "llvm.isunordered.f64") {
1233     if (Args.size() != 2)
1234       error("Invalid prototype for " + Name + " prototype");
1235     return new FCmpInst(FCmpInst::FCMP_UNO, Args[0], Args[1]);
1236   } else {
1237     const Type* PtrTy = PointerType::get(Type::Int8Ty);
1238     std::vector<const Type*> Params;
1239     if (Name == "llvm.va_start" || Name == "llvm.va_end") {
1240       if (Args.size() != 1)
1241         error("Invalid prototype for " + Name + " prototype");
1242       Params.push_back(PtrTy);
1243       const FunctionType *FTy = FunctionType::get(Type::VoidTy, Params, false);
1244       const PointerType *PFTy = PointerType::get(FTy);
1245       Value* Func = getVal(PFTy, ID);
1246       Args[0] = new BitCastInst(Args[0], PtrTy, makeNameUnique("va"), CurBB);
1247       return new CallInst(Func, &Args[0], Args.size());
1248     } else if (Name == "llvm.va_copy") {
1249       if (Args.size() != 2)
1250         error("Invalid prototype for " + Name + " prototype");
1251       Params.push_back(PtrTy);
1252       Params.push_back(PtrTy);
1253       const FunctionType *FTy = FunctionType::get(Type::VoidTy, Params, false);
1254       const PointerType *PFTy = PointerType::get(FTy);
1255       Value* Func = getVal(PFTy, ID);
1256       std::string InstName0(makeNameUnique("va0"));
1257       std::string InstName1(makeNameUnique("va1"));
1258       Args[0] = new BitCastInst(Args[0], PtrTy, InstName0, CurBB);
1259       Args[1] = new BitCastInst(Args[1], PtrTy, InstName1, CurBB);
1260       return new CallInst(Func, &Args[0], Args.size());
1261     }
1262   }
1263   return 0;
1264 }
1265
1266 const Type* upgradeGEPIndices(const Type* PTy, 
1267                        std::vector<ValueInfo> *Indices, 
1268                        std::vector<Value*>    &VIndices, 
1269                        std::vector<Constant*> *CIndices = 0) {
1270   // Traverse the indices with a gep_type_iterator so we can build the list
1271   // of constant and value indices for use later. Also perform upgrades
1272   VIndices.clear();
1273   if (CIndices) CIndices->clear();
1274   for (unsigned i = 0, e = Indices->size(); i != e; ++i)
1275     VIndices.push_back((*Indices)[i].V);
1276   generic_gep_type_iterator<std::vector<Value*>::iterator>
1277     GTI = gep_type_begin(PTy, VIndices.begin(),  VIndices.end()),
1278     GTE = gep_type_end(PTy,  VIndices.begin(),  VIndices.end());
1279   for (unsigned i = 0, e = Indices->size(); i != e && GTI != GTE; ++i, ++GTI) {
1280     Value *Index = VIndices[i];
1281     if (CIndices && !isa<Constant>(Index))
1282       error("Indices to constant getelementptr must be constants");
1283     // LLVM 1.2 and earlier used ubyte struct indices.  Convert any ubyte 
1284     // struct indices to i32 struct indices with ZExt for compatibility.
1285     else if (isa<StructType>(*GTI)) {        // Only change struct indices
1286       if (ConstantInt *CUI = dyn_cast<ConstantInt>(Index))
1287         if (CUI->getType()->getBitWidth() == 8)
1288           Index = 
1289             ConstantExpr::getCast(Instruction::ZExt, CUI, Type::Int32Ty);
1290     } else {
1291       // Make sure that unsigned SequentialType indices are zext'd to 
1292       // 64-bits if they were smaller than that because LLVM 2.0 will sext 
1293       // all indices for SequentialType elements. We must retain the same 
1294       // semantic (zext) for unsigned types.
1295       if (const IntegerType *Ity = dyn_cast<IntegerType>(Index->getType()))
1296         if (Ity->getBitWidth() < 64 && (*Indices)[i].S == Unsigned) {
1297           if (CIndices)
1298             Index = ConstantExpr::getCast(Instruction::ZExt, 
1299               cast<Constant>(Index), Type::Int64Ty);
1300           else
1301             Index = CastInst::create(Instruction::ZExt, Index, Type::Int64Ty,
1302               makeNameUnique("gep"), CurBB);
1303           VIndices[i] = Index;
1304         }
1305     }
1306     // Add to the CIndices list, if requested.
1307     if (CIndices)
1308       CIndices->push_back(cast<Constant>(Index));
1309   }
1310
1311   const Type *IdxTy =
1312     GetElementPtrInst::getIndexedType(PTy, &VIndices[0], VIndices.size(), true);
1313     if (!IdxTy)
1314       error("Index list invalid for constant getelementptr");
1315   return IdxTy;
1316 }
1317
1318 unsigned upgradeCallingConv(unsigned CC) {
1319   switch (CC) {
1320     case OldCallingConv::C           : return CallingConv::C;
1321     case OldCallingConv::CSRet       : return CallingConv::C;
1322     case OldCallingConv::Fast        : return CallingConv::Fast;
1323     case OldCallingConv::Cold        : return CallingConv::Cold;
1324     case OldCallingConv::X86_StdCall : return CallingConv::X86_StdCall;
1325     case OldCallingConv::X86_FastCall: return CallingConv::X86_FastCall;
1326     default:
1327       return CC;
1328   }
1329 }
1330
1331 Module* UpgradeAssembly(const std::string &infile, std::istream& in, 
1332                               bool debug, bool addAttrs)
1333 {
1334   Upgradelineno = 1; 
1335   CurFilename = infile;
1336   LexInput = &in;
1337   yydebug = debug;
1338   AddAttributes = addAttrs;
1339   ObsoleteVarArgs = false;
1340   NewVarArgs = false;
1341
1342   CurModule.CurrentModule = new Module(CurFilename);
1343
1344   // Check to make sure the parser succeeded
1345   if (yyparse()) {
1346     if (ParserResult)
1347       delete ParserResult;
1348     std::cerr << "llvm-upgrade: parse failed.\n";
1349     return 0;
1350   }
1351
1352   // Check to make sure that parsing produced a result
1353   if (!ParserResult) {
1354     std::cerr << "llvm-upgrade: no parse result.\n";
1355     return 0;
1356   }
1357
1358   // Reset ParserResult variable while saving its value for the result.
1359   Module *Result = ParserResult;
1360   ParserResult = 0;
1361
1362   //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
1363   {
1364     Function* F;
1365     if ((F = Result->getFunction("llvm.va_start"))
1366         && F->getFunctionType()->getNumParams() == 0)
1367       ObsoleteVarArgs = true;
1368     if((F = Result->getFunction("llvm.va_copy"))
1369        && F->getFunctionType()->getNumParams() == 1)
1370       ObsoleteVarArgs = true;
1371   }
1372
1373   if (ObsoleteVarArgs && NewVarArgs) {
1374     error("This file is corrupt: it uses both new and old style varargs");
1375     return 0;
1376   }
1377
1378   if(ObsoleteVarArgs) {
1379     if(Function* F = Result->getFunction("llvm.va_start")) {
1380       if (F->arg_size() != 0) {
1381         error("Obsolete va_start takes 0 argument");
1382         return 0;
1383       }
1384       
1385       //foo = va_start()
1386       // ->
1387       //bar = alloca typeof(foo)
1388       //va_start(bar)
1389       //foo = load bar
1390
1391       const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1392       const Type* ArgTy = F->getFunctionType()->getReturnType();
1393       const Type* ArgTyPtr = PointerType::get(ArgTy);
1394       Function* NF = cast<Function>(Result->getOrInsertFunction(
1395         "llvm.va_start", RetTy, ArgTyPtr, (Type *)0));
1396
1397       while (!F->use_empty()) {
1398         CallInst* CI = cast<CallInst>(F->use_back());
1399         AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
1400         new CallInst(NF, bar, "", CI);
1401         Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
1402         CI->replaceAllUsesWith(foo);
1403         CI->getParent()->getInstList().erase(CI);
1404       }
1405       Result->getFunctionList().erase(F);
1406     }
1407     
1408     if(Function* F = Result->getFunction("llvm.va_end")) {
1409       if(F->arg_size() != 1) {
1410         error("Obsolete va_end takes 1 argument");
1411         return 0;
1412       }
1413
1414       //vaend foo
1415       // ->
1416       //bar = alloca 1 of typeof(foo)
1417       //vaend bar
1418       const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1419       const Type* ArgTy = F->getFunctionType()->getParamType(0);
1420       const Type* ArgTyPtr = PointerType::get(ArgTy);
1421       Function* NF = cast<Function>(Result->getOrInsertFunction(
1422         "llvm.va_end", RetTy, ArgTyPtr, (Type *)0));
1423
1424       while (!F->use_empty()) {
1425         CallInst* CI = cast<CallInst>(F->use_back());
1426         AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
1427         new StoreInst(CI->getOperand(1), bar, CI);
1428         new CallInst(NF, bar, "", CI);
1429         CI->getParent()->getInstList().erase(CI);
1430       }
1431       Result->getFunctionList().erase(F);
1432     }
1433
1434     if(Function* F = Result->getFunction("llvm.va_copy")) {
1435       if(F->arg_size() != 1) {
1436         error("Obsolete va_copy takes 1 argument");
1437         return 0;
1438       }
1439       //foo = vacopy(bar)
1440       // ->
1441       //a = alloca 1 of typeof(foo)
1442       //b = alloca 1 of typeof(foo)
1443       //store bar -> b
1444       //vacopy(a, b)
1445       //foo = load a
1446       
1447       const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1448       const Type* ArgTy = F->getFunctionType()->getReturnType();
1449       const Type* ArgTyPtr = PointerType::get(ArgTy);
1450       Function* NF = cast<Function>(Result->getOrInsertFunction(
1451         "llvm.va_copy", RetTy, ArgTyPtr, ArgTyPtr, (Type *)0));
1452
1453       while (!F->use_empty()) {
1454         CallInst* CI = cast<CallInst>(F->use_back());
1455         AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
1456         AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
1457         new StoreInst(CI->getOperand(1), b, CI);
1458         new CallInst(NF, a, b, "", CI);
1459         Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
1460         CI->replaceAllUsesWith(foo);
1461         CI->getParent()->getInstList().erase(CI);
1462       }
1463       Result->getFunctionList().erase(F);
1464     }
1465   }
1466
1467   return Result;
1468 }
1469
1470 } // end llvm namespace
1471
1472 using namespace llvm;
1473
1474 %}
1475
1476 %union {
1477   llvm::Module                           *ModuleVal;
1478   llvm::Function                         *FunctionVal;
1479   std::pair<llvm::PATypeInfo, char*>     *ArgVal;
1480   llvm::BasicBlock                       *BasicBlockVal;
1481   llvm::TerminatorInst                   *TermInstVal;
1482   llvm::InstrInfo                        InstVal;
1483   llvm::ConstInfo                        ConstVal;
1484   llvm::ValueInfo                        ValueVal;
1485   llvm::PATypeInfo                       TypeVal;
1486   llvm::TypeInfo                         PrimType;
1487   llvm::PHIListInfo                      PHIList;
1488   std::list<llvm::PATypeInfo>            *TypeList;
1489   std::vector<llvm::ValueInfo>           *ValueList;
1490   std::vector<llvm::ConstInfo>           *ConstVector;
1491
1492
1493   std::vector<std::pair<llvm::PATypeInfo,char*> > *ArgList;
1494   // Represent the RHS of PHI node
1495   std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
1496
1497   llvm::GlobalValue::LinkageTypes         Linkage;
1498   int64_t                           SInt64Val;
1499   uint64_t                          UInt64Val;
1500   int                               SIntVal;
1501   unsigned                          UIntVal;
1502   double                            FPVal;
1503   bool                              BoolVal;
1504
1505   char                             *StrVal;   // This memory is strdup'd!
1506   llvm::ValID                       ValIDVal; // strdup'd memory maybe!
1507
1508   llvm::BinaryOps                   BinaryOpVal;
1509   llvm::TermOps                     TermOpVal;
1510   llvm::MemoryOps                   MemOpVal;
1511   llvm::OtherOps                    OtherOpVal;
1512   llvm::CastOps                     CastOpVal;
1513   llvm::ICmpInst::Predicate         IPred;
1514   llvm::FCmpInst::Predicate         FPred;
1515   llvm::Module::Endianness          Endianness;
1516 }
1517
1518 %type <ModuleVal>     Module FunctionList
1519 %type <FunctionVal>   Function FunctionProto FunctionHeader BasicBlockList
1520 %type <BasicBlockVal> BasicBlock InstructionList
1521 %type <TermInstVal>   BBTerminatorInst
1522 %type <InstVal>       Inst InstVal MemoryInst
1523 %type <ConstVal>      ConstVal ConstExpr
1524 %type <ConstVector>   ConstVector
1525 %type <ArgList>       ArgList ArgListH
1526 %type <ArgVal>        ArgVal
1527 %type <PHIList>       PHIList
1528 %type <ValueList>     ValueRefList ValueRefListE  // For call param lists
1529 %type <ValueList>     IndexList                   // For GEP derived indices
1530 %type <TypeList>      TypeListI ArgTypeListI
1531 %type <JumpTable>     JumpTable
1532 %type <BoolVal>       GlobalType                  // GLOBAL or CONSTANT?
1533 %type <BoolVal>       OptVolatile                 // 'volatile' or not
1534 %type <BoolVal>       OptTailCall                 // TAIL CALL or plain CALL.
1535 %type <BoolVal>       OptSideEffect               // 'sideeffect' or not.
1536 %type <Linkage>       OptLinkage FnDeclareLinkage
1537 %type <Endianness>    BigOrLittle
1538
1539 // ValueRef - Unresolved reference to a definition or BB
1540 %type <ValIDVal>      ValueRef ConstValueRef SymbolicValueRef
1541 %type <ValueVal>      ResolvedVal            // <type> <valref> pair
1542
1543 // Tokens and types for handling constant integer values
1544 //
1545 // ESINT64VAL - A negative number within long long range
1546 %token <SInt64Val> ESINT64VAL
1547
1548 // EUINT64VAL - A positive number within uns. long long range
1549 %token <UInt64Val> EUINT64VAL
1550 %type  <SInt64Val> EINT64VAL
1551
1552 %token  <SIntVal>   SINTVAL   // Signed 32 bit ints...
1553 %token  <UIntVal>   UINTVAL   // Unsigned 32 bit ints...
1554 %type   <SIntVal>   INTVAL
1555 %token  <FPVal>     FPVAL     // Float or Double constant
1556
1557 // Built in types...
1558 %type  <TypeVal> Types TypesV UpRTypes UpRTypesV
1559 %type  <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
1560 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
1561 %token <PrimType> FLOAT DOUBLE TYPE LABEL
1562
1563 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
1564 %type  <StrVal> Name OptName OptAssign
1565 %type  <UIntVal> OptAlign OptCAlign
1566 %type <StrVal> OptSection SectionString
1567
1568 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1569 %token DECLARE GLOBAL CONSTANT SECTION VOLATILE
1570 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
1571 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
1572 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
1573 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1574 %token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
1575 %token X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1576 %token DATALAYOUT
1577 %type <UIntVal> OptCallingConv
1578
1579 // Basic Block Terminating Operators
1580 %token <TermOpVal> RET BR SWITCH INVOKE UNREACHABLE
1581 %token UNWIND EXCEPT
1582
1583 // Binary Operators
1584 %type  <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
1585 %type  <BinaryOpVal> ShiftOps
1586 %token <BinaryOpVal> ADD SUB MUL DIV UDIV SDIV FDIV REM UREM SREM FREM 
1587 %token <BinaryOpVal> AND OR XOR SHL SHR ASHR LSHR 
1588 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE  // Binary Comparators
1589 %token <OtherOpVal> ICMP FCMP
1590
1591 // Memory Instructions
1592 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1593
1594 // Other Operators
1595 %token <OtherOpVal> PHI_TOK SELECT VAARG
1596 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1597 %token VAARG_old VANEXT_old //OBSOLETE
1598
1599 // Support for ICmp/FCmp Predicates, which is 1.9++ but not 2.0
1600 %type  <IPred> IPredicates
1601 %type  <FPred> FPredicates
1602 %token  EQ NE SLT SGT SLE SGE ULT UGT ULE UGE 
1603 %token  OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1604
1605 %token <CastOpVal> CAST TRUNC ZEXT SEXT FPTRUNC FPEXT FPTOUI FPTOSI 
1606 %token <CastOpVal> UITOFP SITOFP PTRTOINT INTTOPTR BITCAST 
1607 %type  <CastOpVal> CastOps
1608
1609 %start Module
1610
1611 %%
1612
1613 // Handle constant integer size restriction and conversion...
1614 //
1615 INTVAL 
1616   : SINTVAL
1617   | UINTVAL {
1618     if ($1 > (uint32_t)INT32_MAX)     // Outside of my range!
1619       error("Value too large for type");
1620     $$ = (int32_t)$1;
1621   }
1622   ;
1623
1624 EINT64VAL 
1625   : ESINT64VAL       // These have same type and can't cause problems...
1626   | EUINT64VAL {
1627     if ($1 > (uint64_t)INT64_MAX)     // Outside of my range!
1628       error("Value too large for type");
1629     $$ = (int64_t)$1;
1630   };
1631
1632 // Operations that are notably excluded from this list include:
1633 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1634 //
1635 ArithmeticOps
1636   : ADD | SUB | MUL | DIV | UDIV | SDIV | FDIV | REM | UREM | SREM | FREM
1637   ;
1638
1639 LogicalOps   
1640   : AND | OR | XOR
1641   ;
1642
1643 SetCondOps   
1644   : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
1645   ;
1646
1647 IPredicates  
1648   : EQ   { $$ = ICmpInst::ICMP_EQ; }  | NE   { $$ = ICmpInst::ICMP_NE; }
1649   | SLT  { $$ = ICmpInst::ICMP_SLT; } | SGT  { $$ = ICmpInst::ICMP_SGT; }
1650   | SLE  { $$ = ICmpInst::ICMP_SLE; } | SGE  { $$ = ICmpInst::ICMP_SGE; }
1651   | ULT  { $$ = ICmpInst::ICMP_ULT; } | UGT  { $$ = ICmpInst::ICMP_UGT; }
1652   | ULE  { $$ = ICmpInst::ICMP_ULE; } | UGE  { $$ = ICmpInst::ICMP_UGE; } 
1653   ;
1654
1655 FPredicates  
1656   : OEQ  { $$ = FCmpInst::FCMP_OEQ; } | ONE  { $$ = FCmpInst::FCMP_ONE; }
1657   | OLT  { $$ = FCmpInst::FCMP_OLT; } | OGT  { $$ = FCmpInst::FCMP_OGT; }
1658   | OLE  { $$ = FCmpInst::FCMP_OLE; } | OGE  { $$ = FCmpInst::FCMP_OGE; }
1659   | ORD  { $$ = FCmpInst::FCMP_ORD; } | UNO  { $$ = FCmpInst::FCMP_UNO; }
1660   | UEQ  { $$ = FCmpInst::FCMP_UEQ; } | UNE  { $$ = FCmpInst::FCMP_UNE; }
1661   | ULT  { $$ = FCmpInst::FCMP_ULT; } | UGT  { $$ = FCmpInst::FCMP_UGT; }
1662   | ULE  { $$ = FCmpInst::FCMP_ULE; } | UGE  { $$ = FCmpInst::FCMP_UGE; }
1663   | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1664   | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1665   ;
1666 ShiftOps  
1667   : SHL | SHR | ASHR | LSHR
1668   ;
1669
1670 CastOps      
1671   : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | FPTOUI | FPTOSI 
1672   | UITOFP | SITOFP | PTRTOINT | INTTOPTR | BITCAST | CAST
1673   ;
1674
1675 // These are some types that allow classification if we only want a particular 
1676 // thing... for example, only a signed, unsigned, or integral type.
1677 SIntType 
1678   :  LONG |  INT |  SHORT | SBYTE
1679   ;
1680
1681 UIntType 
1682   : ULONG | UINT | USHORT | UBYTE
1683   ;
1684
1685 IntType  
1686   : SIntType | UIntType
1687   ;
1688
1689 FPType   
1690   : FLOAT | DOUBLE
1691   ;
1692
1693 // OptAssign - Value producing statements have an optional assignment component
1694 OptAssign 
1695   : Name '=' {
1696     $$ = $1;
1697   }
1698   | /*empty*/ {
1699     $$ = 0;
1700   };
1701
1702 OptLinkage 
1703   : INTERNAL    { $$ = GlobalValue::InternalLinkage; }
1704   | LINKONCE    { $$ = GlobalValue::LinkOnceLinkage; } 
1705   | WEAK        { $$ = GlobalValue::WeakLinkage; } 
1706   | APPENDING   { $$ = GlobalValue::AppendingLinkage; } 
1707   | DLLIMPORT   { $$ = GlobalValue::DLLImportLinkage; } 
1708   | DLLEXPORT   { $$ = GlobalValue::DLLExportLinkage; } 
1709   | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1710   | /*empty*/   { $$ = GlobalValue::ExternalLinkage; }
1711   ;
1712
1713 OptCallingConv 
1714   : /*empty*/          { $$ = OldCallingConv::C; } 
1715   | CCC_TOK            { $$ = OldCallingConv::C; } 
1716   | CSRETCC_TOK        { $$ = OldCallingConv::CSRet; } 
1717   | FASTCC_TOK         { $$ = OldCallingConv::Fast; } 
1718   | COLDCC_TOK         { $$ = OldCallingConv::Cold; } 
1719   | X86_STDCALLCC_TOK  { $$ = OldCallingConv::X86_StdCall; } 
1720   | X86_FASTCALLCC_TOK { $$ = OldCallingConv::X86_FastCall; } 
1721   | CC_TOK EUINT64VAL  {
1722     if ((unsigned)$2 != $2)
1723       error("Calling conv too large");
1724     $$ = $2;
1725   }
1726   ;
1727
1728 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1729 // a comma before it.
1730 OptAlign 
1731   : /*empty*/        { $$ = 0; } 
1732   | ALIGN EUINT64VAL {
1733     $$ = $2;
1734     if ($$ != 0 && !isPowerOf2_32($$))
1735       error("Alignment must be a power of two");
1736   }
1737   ;
1738
1739 OptCAlign 
1740   : /*empty*/ { $$ = 0; } 
1741   | ',' ALIGN EUINT64VAL {
1742     $$ = $3;
1743     if ($$ != 0 && !isPowerOf2_32($$))
1744       error("Alignment must be a power of two");
1745   }
1746   ;
1747
1748 SectionString 
1749   : SECTION STRINGCONSTANT {
1750     for (unsigned i = 0, e = strlen($2); i != e; ++i)
1751       if ($2[i] == '"' || $2[i] == '\\')
1752         error("Invalid character in section name");
1753     $$ = $2;
1754   }
1755   ;
1756
1757 OptSection 
1758   : /*empty*/ { $$ = 0; } 
1759   | SectionString { $$ = $1; }
1760   ;
1761
1762 // GlobalVarAttributes - Used to pass the attributes string on a global.  CurGV
1763 // is set to be the global we are processing.
1764 //
1765 GlobalVarAttributes 
1766   : /* empty */ {} 
1767   | ',' GlobalVarAttribute GlobalVarAttributes {}
1768   ;
1769
1770 GlobalVarAttribute
1771   : SectionString {
1772     CurGV->setSection($1);
1773     free($1);
1774   } 
1775   | ALIGN EUINT64VAL {
1776     if ($2 != 0 && !isPowerOf2_32($2))
1777       error("Alignment must be a power of two");
1778     CurGV->setAlignment($2);
1779     
1780   }
1781   ;
1782
1783 //===----------------------------------------------------------------------===//
1784 // Types includes all predefined types... except void, because it can only be
1785 // used in specific contexts (function returning void for example).  To have
1786 // access to it, a user must explicitly use TypesV.
1787 //
1788
1789 // TypesV includes all of 'Types', but it also includes the void type.
1790 TypesV    
1791   : Types
1792   | VOID { 
1793     $$.PAT = new PATypeHolder($1.T); 
1794     $$.S = Signless;
1795   }
1796   ;
1797
1798 UpRTypesV 
1799   : UpRTypes 
1800   | VOID { 
1801     $$.PAT = new PATypeHolder($1.T); 
1802     $$.S = Signless;
1803   }
1804   ;
1805
1806 Types
1807   : UpRTypes {
1808     if (!UpRefs.empty())
1809       error("Invalid upreference in type: " + (*$1.PAT)->getDescription());
1810     $$ = $1;
1811   }
1812   ;
1813
1814 PrimType
1815   : BOOL | SBYTE | UBYTE | SHORT  | USHORT | INT   | UINT 
1816   | LONG | ULONG | FLOAT | DOUBLE | LABEL
1817   ;
1818
1819 // Derived types are added later...
1820 UpRTypes 
1821   : PrimType { 
1822     $$.PAT = new PATypeHolder($1.T);
1823     $$.S = $1.S;
1824   }
1825   | OPAQUE {
1826     $$.PAT = new PATypeHolder(OpaqueType::get());
1827     $$.S = Signless;
1828   }
1829   | SymbolicValueRef {            // Named types are also simple types...
1830     const Type* tmp = getType($1);
1831     $$.PAT = new PATypeHolder(tmp);
1832     $$.S = $1.S; // FIXME: what if its signed?
1833   }
1834   | '\\' EUINT64VAL {                   // Type UpReference
1835     if ($2 > (uint64_t)~0U) 
1836       error("Value out of range");
1837     OpaqueType *OT = OpaqueType::get();        // Use temporary placeholder
1838     UpRefs.push_back(UpRefRecord((unsigned)$2, OT));  // Add to vector...
1839     $$.PAT = new PATypeHolder(OT);
1840     $$.S = Signless;
1841     UR_OUT("New Upreference!\n");
1842   }
1843   | UpRTypesV '(' ArgTypeListI ')' {           // Function derived type?
1844     std::vector<const Type*> Params;
1845     for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
1846            E = $3->end(); I != E; ++I) {
1847       Params.push_back(I->PAT->get());
1848     }
1849     FunctionType::ParamAttrsList ParamAttrs;
1850     bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1851     if (isVarArg) Params.pop_back();
1852
1853     $$.PAT = new PATypeHolder(
1854       HandleUpRefs(FunctionType::get($1.PAT->get(), Params, isVarArg, 
1855                    ParamAttrs)));
1856     $$.S = $1.S;
1857     delete $1.PAT;    // Delete the return type handle
1858     delete $3;      // Delete the argument list
1859   }
1860   | '[' EUINT64VAL 'x' UpRTypes ']' {          // Sized array type?
1861     $$.PAT = new PATypeHolder(HandleUpRefs(ArrayType::get($4.PAT->get(), 
1862                                                         (unsigned)$2)));
1863     $$.S = $4.S;
1864     delete $4.PAT;
1865   }
1866   | '<' EUINT64VAL 'x' UpRTypes '>' {          // Vector type?
1867      const llvm::Type* ElemTy = $4.PAT->get();
1868      if ((unsigned)$2 != $2)
1869         error("Unsigned result not equal to signed result");
1870      if (!(ElemTy->isInteger() || ElemTy->isFloatingPoint()))
1871         error("Elements of a VectorType must be integer or floating point");
1872      if (!isPowerOf2_32($2))
1873        error("VectorType length should be a power of 2");
1874      $$.PAT = new PATypeHolder(HandleUpRefs(VectorType::get(ElemTy, 
1875                                           (unsigned)$2)));
1876      $$.S = $4.S;
1877      delete $4.PAT;
1878   }
1879   | '{' TypeListI '}' {                        // Structure type?
1880     std::vector<const Type*> Elements;
1881     for (std::list<llvm::PATypeInfo>::iterator I = $2->begin(),
1882            E = $2->end(); I != E; ++I)
1883       Elements.push_back(I->PAT->get());
1884     $$.PAT = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1885     $$.S = Signless;
1886     delete $2;
1887   }
1888   | '{' '}' {                                  // Empty structure type?
1889     $$.PAT = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1890     $$.S = Signless;
1891   }
1892   | '<' '{' TypeListI '}' '>' {                // Packed Structure type?
1893     std::vector<const Type*> Elements;
1894     for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
1895            E = $3->end(); I != E; ++I) {
1896       Elements.push_back(I->PAT->get());
1897       delete I->PAT;
1898     }
1899     $$.PAT = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1900     $$.S = Signless;
1901     delete $3;
1902   }
1903   | '<' '{' '}' '>' {                          // Empty packed structure type?
1904     $$.PAT = new PATypeHolder(StructType::get(std::vector<const Type*>(),true));
1905     $$.S = Signless;
1906   }
1907   | UpRTypes '*' {                             // Pointer type?
1908     if ($1.PAT->get() == Type::LabelTy)
1909       error("Cannot form a pointer to a basic block");
1910     $$.PAT = new PATypeHolder(HandleUpRefs(PointerType::get($1.PAT->get())));
1911     $$.S = $1.S;
1912     delete $1.PAT;
1913   }
1914   ;
1915
1916 // TypeList - Used for struct declarations and as a basis for function type 
1917 // declaration type lists
1918 //
1919 TypeListI 
1920   : UpRTypes {
1921     $$ = new std::list<PATypeInfo>();
1922     $$->push_back($1); 
1923   }
1924   | TypeListI ',' UpRTypes {
1925     ($$=$1)->push_back($3);
1926   }
1927   ;
1928
1929 // ArgTypeList - List of types for a function type declaration...
1930 ArgTypeListI 
1931   : TypeListI
1932   | TypeListI ',' DOTDOTDOT {
1933     PATypeInfo VoidTI;
1934     VoidTI.PAT = new PATypeHolder(Type::VoidTy);
1935     VoidTI.S = Signless;
1936     ($$=$1)->push_back(VoidTI);
1937   }
1938   | DOTDOTDOT {
1939     $$ = new std::list<PATypeInfo>();
1940     PATypeInfo VoidTI;
1941     VoidTI.PAT = new PATypeHolder(Type::VoidTy);
1942     VoidTI.S = Signless;
1943     $$->push_back(VoidTI);
1944   }
1945   | /*empty*/ {
1946     $$ = new std::list<PATypeInfo>();
1947   }
1948   ;
1949
1950 // ConstVal - The various declarations that go into the constant pool.  This
1951 // production is used ONLY to represent constants that show up AFTER a 'const',
1952 // 'constant' or 'global' token at global scope.  Constants that can be inlined
1953 // into other expressions (such as integers and constexprs) are handled by the
1954 // ResolvedVal, ValueRef and ConstValueRef productions.
1955 //
1956 ConstVal
1957   : Types '[' ConstVector ']' { // Nonempty unsized arr
1958     const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
1959     if (ATy == 0)
1960       error("Cannot make array constant with type: '" + 
1961             $1.PAT->get()->getDescription() + "'");
1962     const Type *ETy = ATy->getElementType();
1963     int NumElements = ATy->getNumElements();
1964
1965     // Verify that we have the correct size...
1966     if (NumElements != -1 && NumElements != (int)$3->size())
1967       error("Type mismatch: constant sized array initialized with " +
1968             utostr($3->size()) +  " arguments, but has size of " + 
1969             itostr(NumElements) + "");
1970
1971     // Verify all elements are correct type!
1972     std::vector<Constant*> Elems;
1973     for (unsigned i = 0; i < $3->size(); i++) {
1974       Constant *C = (*$3)[i].C;
1975       const Type* ValTy = C->getType();
1976       if (ETy != ValTy)
1977         error("Element #" + utostr(i) + " is not of type '" + 
1978               ETy->getDescription() +"' as required!\nIt is of type '"+
1979               ValTy->getDescription() + "'");
1980       Elems.push_back(C);
1981     }
1982     $$.C = ConstantArray::get(ATy, Elems);
1983     $$.S = $1.S;
1984     delete $1.PAT; 
1985     delete $3;
1986   }
1987   | Types '[' ']' {
1988     const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
1989     if (ATy == 0)
1990       error("Cannot make array constant with type: '" + 
1991             $1.PAT->get()->getDescription() + "'");
1992     int NumElements = ATy->getNumElements();
1993     if (NumElements != -1 && NumElements != 0) 
1994       error("Type mismatch: constant sized array initialized with 0"
1995             " arguments, but has size of " + itostr(NumElements) +"");
1996     $$.C = ConstantArray::get(ATy, std::vector<Constant*>());
1997     $$.S = $1.S;
1998     delete $1.PAT;
1999   }
2000   | Types 'c' STRINGCONSTANT {
2001     const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
2002     if (ATy == 0)
2003       error("Cannot make array constant with type: '" + 
2004             $1.PAT->get()->getDescription() + "'");
2005     int NumElements = ATy->getNumElements();
2006     const Type *ETy = dyn_cast<IntegerType>(ATy->getElementType());
2007     if (!ETy || cast<IntegerType>(ETy)->getBitWidth() != 8)
2008       error("String arrays require type i8, not '" + ETy->getDescription() + 
2009             "'");
2010     char *EndStr = UnEscapeLexed($3, true);
2011     if (NumElements != -1 && NumElements != (EndStr-$3))
2012       error("Can't build string constant of size " + 
2013             itostr((int)(EndStr-$3)) + " when array has size " + 
2014             itostr(NumElements) + "");
2015     std::vector<Constant*> Vals;
2016     for (char *C = (char *)$3; C != (char *)EndStr; ++C)
2017       Vals.push_back(ConstantInt::get(ETy, *C));
2018     free($3);
2019     $$.C = ConstantArray::get(ATy, Vals);
2020     $$.S = $1.S;
2021     delete $1.PAT;
2022   }
2023   | Types '<' ConstVector '>' { // Nonempty unsized arr
2024     const VectorType *PTy = dyn_cast<VectorType>($1.PAT->get());
2025     if (PTy == 0)
2026       error("Cannot make packed constant with type: '" + 
2027             $1.PAT->get()->getDescription() + "'");
2028     const Type *ETy = PTy->getElementType();
2029     int NumElements = PTy->getNumElements();
2030     // Verify that we have the correct size...
2031     if (NumElements != -1 && NumElements != (int)$3->size())
2032       error("Type mismatch: constant sized packed initialized with " +
2033             utostr($3->size()) +  " arguments, but has size of " + 
2034             itostr(NumElements) + "");
2035     // Verify all elements are correct type!
2036     std::vector<Constant*> Elems;
2037     for (unsigned i = 0; i < $3->size(); i++) {
2038       Constant *C = (*$3)[i].C;
2039       const Type* ValTy = C->getType();
2040       if (ETy != ValTy)
2041         error("Element #" + utostr(i) + " is not of type '" + 
2042               ETy->getDescription() +"' as required!\nIt is of type '"+
2043               ValTy->getDescription() + "'");
2044       Elems.push_back(C);
2045     }
2046     $$.C = ConstantVector::get(PTy, Elems);
2047     $$.S = $1.S;
2048     delete $1.PAT;
2049     delete $3;
2050   }
2051   | Types '{' ConstVector '}' {
2052     const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2053     if (STy == 0)
2054       error("Cannot make struct constant with type: '" + 
2055             $1.PAT->get()->getDescription() + "'");
2056     if ($3->size() != STy->getNumContainedTypes())
2057       error("Illegal number of initializers for structure type");
2058
2059     // Check to ensure that constants are compatible with the type initializer!
2060     std::vector<Constant*> Fields;
2061     for (unsigned i = 0, e = $3->size(); i != e; ++i) {
2062       Constant *C = (*$3)[i].C;
2063       if (C->getType() != STy->getElementType(i))
2064         error("Expected type '" + STy->getElementType(i)->getDescription() +
2065               "' for element #" + utostr(i) + " of structure initializer");
2066       Fields.push_back(C);
2067     }
2068     $$.C = ConstantStruct::get(STy, Fields);
2069     $$.S = $1.S;
2070     delete $1.PAT;
2071     delete $3;
2072   }
2073   | Types '{' '}' {
2074     const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2075     if (STy == 0)
2076       error("Cannot make struct constant with type: '" + 
2077               $1.PAT->get()->getDescription() + "'");
2078     if (STy->getNumContainedTypes() != 0)
2079       error("Illegal number of initializers for structure type");
2080     $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2081     $$.S = $1.S;
2082     delete $1.PAT;
2083   }
2084   | Types '<' '{' ConstVector '}' '>' {
2085     const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2086     if (STy == 0)
2087       error("Cannot make packed struct constant with type: '" + 
2088             $1.PAT->get()->getDescription() + "'");
2089     if ($4->size() != STy->getNumContainedTypes())
2090       error("Illegal number of initializers for packed structure type");
2091
2092     // Check to ensure that constants are compatible with the type initializer!
2093     std::vector<Constant*> Fields;
2094     for (unsigned i = 0, e = $4->size(); i != e; ++i) {
2095       Constant *C = (*$4)[i].C;
2096       if (C->getType() != STy->getElementType(i))
2097         error("Expected type '" + STy->getElementType(i)->getDescription() +
2098               "' for element #" + utostr(i) + " of packed struct initializer");
2099       Fields.push_back(C);
2100     }
2101     $$.C = ConstantStruct::get(STy, Fields);
2102     $$.S = $1.S;
2103     delete $1.PAT; 
2104     delete $4;
2105   }
2106   | Types '<' '{' '}' '>' {
2107     const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2108     if (STy == 0)
2109       error("Cannot make packed struct constant with type: '" + 
2110               $1.PAT->get()->getDescription() + "'");
2111     if (STy->getNumContainedTypes() != 0)
2112       error("Illegal number of initializers for packed structure type");
2113     $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2114     $$.S = $1.S;
2115     delete $1.PAT;
2116   }
2117   | Types NULL_TOK {
2118     const PointerType *PTy = dyn_cast<PointerType>($1.PAT->get());
2119     if (PTy == 0)
2120       error("Cannot make null pointer constant with type: '" + 
2121             $1.PAT->get()->getDescription() + "'");
2122     $$.C = ConstantPointerNull::get(PTy);
2123     $$.S = $1.S;
2124     delete $1.PAT;
2125   }
2126   | Types UNDEF {
2127     $$.C = UndefValue::get($1.PAT->get());
2128     $$.S = $1.S;
2129     delete $1.PAT;
2130   }
2131   | Types SymbolicValueRef {
2132     const PointerType *Ty = dyn_cast<PointerType>($1.PAT->get());
2133     if (Ty == 0)
2134       error("Global const reference must be a pointer type, not" +
2135             $1.PAT->get()->getDescription());
2136
2137     // ConstExprs can exist in the body of a function, thus creating
2138     // GlobalValues whenever they refer to a variable.  Because we are in
2139     // the context of a function, getExistingValue will search the functions
2140     // symbol table instead of the module symbol table for the global symbol,
2141     // which throws things all off.  To get around this, we just tell
2142     // getExistingValue that we are at global scope here.
2143     //
2144     Function *SavedCurFn = CurFun.CurrentFunction;
2145     CurFun.CurrentFunction = 0;
2146     Value *V = getExistingValue(Ty, $2);
2147     CurFun.CurrentFunction = SavedCurFn;
2148
2149     // If this is an initializer for a constant pointer, which is referencing a
2150     // (currently) undefined variable, create a stub now that shall be replaced
2151     // in the future with the right type of variable.
2152     //
2153     if (V == 0) {
2154       assert(isa<PointerType>(Ty) && "Globals may only be used as pointers");
2155       const PointerType *PT = cast<PointerType>(Ty);
2156
2157       // First check to see if the forward references value is already created!
2158       PerModuleInfo::GlobalRefsType::iterator I =
2159         CurModule.GlobalRefs.find(std::make_pair(PT, $2));
2160     
2161       if (I != CurModule.GlobalRefs.end()) {
2162         V = I->second;             // Placeholder already exists, use it...
2163         $2.destroy();
2164       } else {
2165         std::string Name;
2166         if ($2.Type == ValID::NameVal) Name = $2.Name;
2167
2168         // Create the forward referenced global.
2169         GlobalValue *GV;
2170         if (const FunctionType *FTy = 
2171                  dyn_cast<FunctionType>(PT->getElementType())) {
2172           GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
2173                             CurModule.CurrentModule);
2174         } else {
2175           GV = new GlobalVariable(PT->getElementType(), false,
2176                                   GlobalValue::ExternalLinkage, 0,
2177                                   Name, CurModule.CurrentModule);
2178         }
2179
2180         // Keep track of the fact that we have a forward ref to recycle it
2181         CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
2182         V = GV;
2183       }
2184     }
2185     $$.C = cast<GlobalValue>(V);
2186     $$.S = $1.S;
2187     delete $1.PAT;            // Free the type handle
2188   }
2189   | Types ConstExpr {
2190     if ($1.PAT->get() != $2.C->getType())
2191       error("Mismatched types for constant expression");
2192     $$ = $2;
2193     $$.S = $1.S;
2194     delete $1.PAT;
2195   }
2196   | Types ZEROINITIALIZER {
2197     const Type *Ty = $1.PAT->get();
2198     if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
2199       error("Cannot create a null initialized value of this type");
2200     $$.C = Constant::getNullValue(Ty);
2201     $$.S = $1.S;
2202     delete $1.PAT;
2203   }
2204   | SIntType EINT64VAL {      // integral constants
2205     const Type *Ty = $1.T;
2206     if (!ConstantInt::isValueValidForType(Ty, $2))
2207       error("Constant value doesn't fit in type");
2208     $$.C = ConstantInt::get(Ty, $2);
2209     $$.S = Signed;
2210   }
2211   | UIntType EUINT64VAL {            // integral constants
2212     const Type *Ty = $1.T;
2213     if (!ConstantInt::isValueValidForType(Ty, $2))
2214       error("Constant value doesn't fit in type");
2215     $$.C = ConstantInt::get(Ty, $2);
2216     $$.S = Unsigned;
2217   }
2218   | BOOL TRUETOK {                      // Boolean constants
2219     $$.C = ConstantInt::get(Type::Int1Ty, true);
2220     $$.S = Unsigned;
2221   }
2222   | BOOL FALSETOK {                     // Boolean constants
2223     $$.C = ConstantInt::get(Type::Int1Ty, false);
2224     $$.S = Unsigned;
2225   }
2226   | FPType FPVAL {                   // Float & Double constants
2227     if (!ConstantFP::isValueValidForType($1.T, $2))
2228       error("Floating point constant invalid for type");
2229     $$.C = ConstantFP::get($1.T, $2);
2230     $$.S = Signless;
2231   }
2232   ;
2233
2234 ConstExpr
2235   : CastOps '(' ConstVal TO Types ')' {
2236     const Type* SrcTy = $3.C->getType();
2237     const Type* DstTy = $5.PAT->get();
2238     Signedness SrcSign = $3.S;
2239     Signedness DstSign = $5.S;
2240     if (!SrcTy->isFirstClassType())
2241       error("cast constant expression from a non-primitive type: '" +
2242             SrcTy->getDescription() + "'");
2243     if (!DstTy->isFirstClassType())
2244       error("cast constant expression to a non-primitive type: '" +
2245             DstTy->getDescription() + "'");
2246     $$.C = cast<Constant>(getCast($1, $3.C, SrcSign, DstTy, DstSign));
2247     $$.S = DstSign;
2248     delete $5.PAT;
2249   }
2250   | GETELEMENTPTR '(' ConstVal IndexList ')' {
2251     const Type *Ty = $3.C->getType();
2252     if (!isa<PointerType>(Ty))
2253       error("GetElementPtr requires a pointer operand");
2254
2255     std::vector<Value*> VIndices;
2256     std::vector<Constant*> CIndices;
2257     upgradeGEPIndices($3.C->getType(), $4, VIndices, &CIndices);
2258
2259     delete $4;
2260     $$.C = ConstantExpr::getGetElementPtr($3.C, &CIndices[0], CIndices.size());
2261     $$.S = Signless;
2262   }
2263   | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2264     if (!$3.C->getType()->isInteger() ||
2265         cast<IntegerType>($3.C->getType())->getBitWidth() != 1)
2266       error("Select condition must be bool type");
2267     if ($5.C->getType() != $7.C->getType())
2268       error("Select operand types must match");
2269     $$.C = ConstantExpr::getSelect($3.C, $5.C, $7.C);
2270     $$.S = Unsigned;
2271   }
2272   | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
2273     const Type *Ty = $3.C->getType();
2274     if (Ty != $5.C->getType())
2275       error("Binary operator types must match");
2276     // First, make sure we're dealing with the right opcode by upgrading from
2277     // obsolete versions.
2278     Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2279
2280     // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
2281     // To retain backward compatibility with these early compilers, we emit a
2282     // cast to the appropriate integer type automatically if we are in the
2283     // broken case.  See PR424 for more information.
2284     if (!isa<PointerType>(Ty)) {
2285       $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2286     } else {
2287       const Type *IntPtrTy = 0;
2288       switch (CurModule.CurrentModule->getPointerSize()) {
2289       case Module::Pointer32: IntPtrTy = Type::Int32Ty; break;
2290       case Module::Pointer64: IntPtrTy = Type::Int64Ty; break;
2291       default: error("invalid pointer binary constant expr");
2292       }
2293       $$.C = ConstantExpr::get(Opcode, 
2294              ConstantExpr::getCast(Instruction::PtrToInt, $3.C, IntPtrTy),
2295              ConstantExpr::getCast(Instruction::PtrToInt, $5.C, IntPtrTy));
2296       $$.C = ConstantExpr::getCast(Instruction::IntToPtr, $$.C, Ty);
2297     }
2298     $$.S = $3.S; 
2299   }
2300   | LogicalOps '(' ConstVal ',' ConstVal ')' {
2301     const Type* Ty = $3.C->getType();
2302     if (Ty != $5.C->getType())
2303       error("Logical operator types must match");
2304     if (!Ty->isInteger()) {
2305       if (!isa<VectorType>(Ty) || 
2306           !cast<VectorType>(Ty)->getElementType()->isInteger())
2307         error("Logical operator requires integer operands");
2308     }
2309     Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2310     $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2311     $$.S = $3.S;
2312   }
2313   | SetCondOps '(' ConstVal ',' ConstVal ')' {
2314     const Type* Ty = $3.C->getType();
2315     if (Ty != $5.C->getType())
2316       error("setcc operand types must match");
2317     unsigned short pred;
2318     Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $3.S);
2319     $$.C = ConstantExpr::getCompare(Opcode, $3.C, $5.C);
2320     $$.S = Unsigned;
2321   }
2322   | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
2323     if ($4.C->getType() != $6.C->getType()) 
2324       error("icmp operand types must match");
2325     $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2326     $$.S = Unsigned;
2327   }
2328   | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
2329     if ($4.C->getType() != $6.C->getType()) 
2330       error("fcmp operand types must match");
2331     $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2332     $$.S = Unsigned;
2333   }
2334   | ShiftOps '(' ConstVal ',' ConstVal ')' {
2335     if (!$5.C->getType()->isInteger() ||
2336         cast<IntegerType>($5.C->getType())->getBitWidth() != 8)
2337       error("Shift count for shift constant must be unsigned byte");
2338     const Type* Ty = $3.C->getType();
2339     if (!$3.C->getType()->isInteger())
2340       error("Shift constant expression requires integer operand");
2341     Constant *ShiftAmt = ConstantExpr::getZExt($5.C, Ty);
2342     $$.C = ConstantExpr::get(getBinaryOp($1, Ty, $3.S), $3.C, ShiftAmt);
2343     $$.S = $3.S;
2344   }
2345   | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
2346     if (!ExtractElementInst::isValidOperands($3.C, $5.C))
2347       error("Invalid extractelement operands");
2348     $$.C = ConstantExpr::getExtractElement($3.C, $5.C);
2349     $$.S = $3.S;
2350   }
2351   | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2352     if (!InsertElementInst::isValidOperands($3.C, $5.C, $7.C))
2353       error("Invalid insertelement operands");
2354     $$.C = ConstantExpr::getInsertElement($3.C, $5.C, $7.C);
2355     $$.S = $3.S;
2356   }
2357   | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2358     if (!ShuffleVectorInst::isValidOperands($3.C, $5.C, $7.C))
2359       error("Invalid shufflevector operands");
2360     $$.C = ConstantExpr::getShuffleVector($3.C, $5.C, $7.C);
2361     $$.S = $3.S;
2362   }
2363   ;
2364
2365
2366 // ConstVector - A list of comma separated constants.
2367 ConstVector 
2368   : ConstVector ',' ConstVal { ($$ = $1)->push_back($3); }
2369   | ConstVal {
2370     $$ = new std::vector<ConstInfo>();
2371     $$->push_back($1);
2372   }
2373   ;
2374
2375
2376 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
2377 GlobalType 
2378   : GLOBAL { $$ = false; } 
2379   | CONSTANT { $$ = true; }
2380   ;
2381
2382
2383 //===----------------------------------------------------------------------===//
2384 //                             Rules to match Modules
2385 //===----------------------------------------------------------------------===//
2386
2387 // Module rule: Capture the result of parsing the whole file into a result
2388 // variable...
2389 //
2390 Module 
2391   : FunctionList {
2392     $$ = ParserResult = $1;
2393     CurModule.ModuleDone();
2394   }
2395   ;
2396
2397 // FunctionList - A list of functions, preceeded by a constant pool.
2398 //
2399 FunctionList 
2400   : FunctionList Function { $$ = $1; CurFun.FunctionDone(); } 
2401   | FunctionList FunctionProto { $$ = $1; }
2402   | FunctionList MODULE ASM_TOK AsmBlock { $$ = $1; }  
2403   | FunctionList IMPLEMENTATION { $$ = $1; }
2404   | ConstPool {
2405     $$ = CurModule.CurrentModule;
2406     // Emit an error if there are any unresolved types left.
2407     if (!CurModule.LateResolveTypes.empty()) {
2408       const ValID &DID = CurModule.LateResolveTypes.begin()->first;
2409       if (DID.Type == ValID::NameVal) {
2410         error("Reference to an undefined type: '"+DID.getName() + "'");
2411       } else {
2412         error("Reference to an undefined type: #" + itostr(DID.Num));
2413       }
2414     }
2415   }
2416   ;
2417
2418 // ConstPool - Constants with optional names assigned to them.
2419 ConstPool 
2420   : ConstPool OptAssign TYPE TypesV {
2421     // Eagerly resolve types.  This is not an optimization, this is a
2422     // requirement that is due to the fact that we could have this:
2423     //
2424     // %list = type { %list * }
2425     // %list = type { %list * }    ; repeated type decl
2426     //
2427     // If types are not resolved eagerly, then the two types will not be
2428     // determined to be the same type!
2429     //
2430     const Type* Ty = $4.PAT->get();
2431     ResolveTypeTo($2, Ty, $4.S);
2432
2433     if (!setTypeName(Ty, $2) && !$2) {
2434       // If this is a named type that is not a redefinition, add it to the slot
2435       // table.
2436       CurModule.Types.push_back(Ty);
2437     }
2438     delete $4.PAT;
2439   }
2440   | ConstPool FunctionProto {       // Function prototypes can be in const pool
2441   }
2442   | ConstPool MODULE ASM_TOK AsmBlock {  // Asm blocks can be in the const pool
2443   }
2444   | ConstPool OptAssign OptLinkage GlobalType ConstVal {
2445     if ($5.C == 0) 
2446       error("Global value initializer is not a constant");
2447     CurGV = ParseGlobalVariable($2, $3, $4, $5.C->getType(), $5.C, $5.S);
2448   } GlobalVarAttributes {
2449     CurGV = 0;
2450   }
2451   | ConstPool OptAssign EXTERNAL GlobalType Types {
2452     const Type *Ty = $5.PAT->get();
2453     CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, Ty, 0,
2454                                 $5.S);
2455     delete $5.PAT;
2456   } GlobalVarAttributes {
2457     CurGV = 0;
2458   }
2459   | ConstPool OptAssign DLLIMPORT GlobalType Types {
2460     const Type *Ty = $5.PAT->get();
2461     CurGV = ParseGlobalVariable($2, GlobalValue::DLLImportLinkage, $4, Ty, 0,
2462                                 $5.S);
2463     delete $5.PAT;
2464   } GlobalVarAttributes {
2465     CurGV = 0;
2466   }
2467   | ConstPool OptAssign EXTERN_WEAK GlobalType Types {
2468     const Type *Ty = $5.PAT->get();
2469     CurGV = 
2470       ParseGlobalVariable($2, GlobalValue::ExternalWeakLinkage, $4, Ty, 0, 
2471                           $5.S);
2472     delete $5.PAT;
2473   } GlobalVarAttributes {
2474     CurGV = 0;
2475   }
2476   | ConstPool TARGET TargetDefinition { 
2477   }
2478   | ConstPool DEPLIBS '=' LibrariesDefinition {
2479   }
2480   | /* empty: end of list */ { 
2481   }
2482   ;
2483
2484 AsmBlock 
2485   : STRINGCONSTANT {
2486     const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2487     char *EndStr = UnEscapeLexed($1, true);
2488     std::string NewAsm($1, EndStr);
2489     free($1);
2490
2491     if (AsmSoFar.empty())
2492       CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
2493     else
2494       CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
2495   }
2496   ;
2497
2498 BigOrLittle 
2499   : BIG    { $$ = Module::BigEndian; }
2500   | LITTLE { $$ = Module::LittleEndian; }
2501   ;
2502
2503 TargetDefinition 
2504   : ENDIAN '=' BigOrLittle {
2505     CurModule.setEndianness($3);
2506   }
2507   | POINTERSIZE '=' EUINT64VAL {
2508     if ($3 == 32)
2509       CurModule.setPointerSize(Module::Pointer32);
2510     else if ($3 == 64)
2511       CurModule.setPointerSize(Module::Pointer64);
2512     else
2513       error("Invalid pointer size: '" + utostr($3) + "'");
2514   }
2515   | TRIPLE '=' STRINGCONSTANT {
2516     CurModule.CurrentModule->setTargetTriple($3);
2517     free($3);
2518   }
2519   | DATALAYOUT '=' STRINGCONSTANT {
2520     CurModule.CurrentModule->setDataLayout($3);
2521     free($3);
2522   }
2523   ;
2524
2525 LibrariesDefinition 
2526   : '[' LibList ']'
2527   ;
2528
2529 LibList 
2530   : LibList ',' STRINGCONSTANT {
2531       CurModule.CurrentModule->addLibrary($3);
2532       free($3);
2533   }
2534   | STRINGCONSTANT {
2535     CurModule.CurrentModule->addLibrary($1);
2536     free($1);
2537   }
2538   | /* empty: end of list */ { }
2539   ;
2540
2541 //===----------------------------------------------------------------------===//
2542 //                       Rules to match Function Headers
2543 //===----------------------------------------------------------------------===//
2544
2545 Name 
2546   : VAR_ID | STRINGCONSTANT
2547   ;
2548
2549 OptName 
2550   : Name 
2551   | /*empty*/ { $$ = 0; }
2552   ;
2553
2554 ArgVal 
2555   : Types OptName {
2556     if ($1.PAT->get() == Type::VoidTy)
2557       error("void typed arguments are invalid");
2558     $$ = new std::pair<PATypeInfo, char*>($1, $2);
2559   }
2560   ;
2561
2562 ArgListH 
2563   : ArgListH ',' ArgVal {
2564     $$ = $1;
2565     $$->push_back(*$3);
2566     delete $3;
2567   }
2568   | ArgVal {
2569     $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2570     $$->push_back(*$1);
2571     delete $1;
2572   }
2573   ;
2574
2575 ArgList 
2576   : ArgListH { $$ = $1; }
2577   | ArgListH ',' DOTDOTDOT {
2578     $$ = $1;
2579     PATypeInfo VoidTI;
2580     VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2581     VoidTI.S = Signless;
2582     $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2583   }
2584   | DOTDOTDOT {
2585     $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2586     PATypeInfo VoidTI;
2587     VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2588     VoidTI.S = Signless;
2589     $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2590   }
2591   | /* empty */ { $$ = 0; }
2592   ;
2593
2594 FunctionHeaderH 
2595   : OptCallingConv TypesV Name '(' ArgList ')' OptSection OptAlign {
2596     UnEscapeLexed($3);
2597     std::string FunctionName($3);
2598     free($3);  // Free strdup'd memory!
2599
2600     const Type* RetTy = $2.PAT->get();
2601     
2602     if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
2603       error("LLVM functions cannot return aggregate types");
2604
2605     std::vector<const Type*> ParamTyList;
2606
2607     // In LLVM 2.0 the signatures of three varargs intrinsics changed to take
2608     // i8*. We check here for those names and override the parameter list
2609     // types to ensure the prototype is correct.
2610     if (FunctionName == "llvm.va_start" || FunctionName == "llvm.va_end") {
2611       ParamTyList.push_back(PointerType::get(Type::Int8Ty));
2612     } else if (FunctionName == "llvm.va_copy") {
2613       ParamTyList.push_back(PointerType::get(Type::Int8Ty));
2614       ParamTyList.push_back(PointerType::get(Type::Int8Ty));
2615     } else if ($5) {   // If there are arguments...
2616       for (std::vector<std::pair<PATypeInfo,char*> >::iterator 
2617            I = $5->begin(), E = $5->end(); I != E; ++I) {
2618         const Type *Ty = I->first.PAT->get();
2619         ParamTyList.push_back(Ty);
2620       }
2621     }
2622
2623     bool isVarArg = ParamTyList.size() && ParamTyList.back() == Type::VoidTy;
2624     if (isVarArg) 
2625       ParamTyList.pop_back();
2626
2627     // Convert the CSRet calling convention into the corresponding parameter
2628     // attribute.
2629     FunctionType::ParamAttrsList ParamAttrs;
2630     if ($1 == OldCallingConv::CSRet) {
2631       ParamAttrs.push_back(FunctionType::NoAttributeSet);     // result
2632       ParamAttrs.push_back(FunctionType::StructRetAttribute); // first arg
2633     }
2634
2635     const FunctionType *FT = FunctionType::get(RetTy, ParamTyList, isVarArg,
2636                                                ParamAttrs);
2637     const PointerType *PFT = PointerType::get(FT);
2638     delete $2.PAT;
2639
2640     ValID ID;
2641     if (!FunctionName.empty()) {
2642       ID = ValID::create((char*)FunctionName.c_str(), $2.S);
2643     } else {
2644       ID = ValID::create((int)CurModule.Values[PFT].size(), $2.S);
2645     }
2646
2647     Function *Fn = 0;
2648     Module* M = CurModule.CurrentModule;
2649
2650     // See if this function was forward referenced.  If so, recycle the object.
2651     if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2652       // Move the function to the end of the list, from whereever it was 
2653       // previously inserted.
2654       Fn = cast<Function>(FWRef);
2655       M->getFunctionList().remove(Fn);
2656       M->getFunctionList().push_back(Fn);
2657     } else if (!FunctionName.empty()) {
2658       GlobalValue *Conflict = M->getFunction(FunctionName);
2659       if (!Conflict)
2660         Conflict = M->getNamedGlobal(FunctionName);
2661       if (Conflict && PFT == Conflict->getType()) {
2662         if (!CurFun.isDeclare && !Conflict->isDeclaration()) {
2663           // We have two function definitions that conflict, same type, same
2664           // name. We should really check to make sure that this is the result
2665           // of integer type planes collapsing and generate an error if it is
2666           // not, but we'll just rename on the assumption that it is. However,
2667           // let's do it intelligently and rename the internal linkage one
2668           // if there is one.
2669           std::string NewName(makeNameUnique(FunctionName));
2670           if (Conflict->hasInternalLinkage()) {
2671             Conflict->setName(NewName);
2672             TypeInfo TI; TI.T = Conflict->getType(); TI.S = ID.S;
2673             RenameMapKey Key = std::make_pair(FunctionName,TI);
2674             CurModule.RenameMap[Key] = NewName;
2675             Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2676             InsertValue(Fn, CurModule.Values);
2677           } else {
2678             Fn = new Function(FT, CurFun.Linkage, NewName, M);
2679             InsertValue(Fn, CurModule.Values);
2680             TypeInfo TI; TI.T = PFT; TI.S = ID.S;
2681             RenameMapKey Key = std::make_pair(FunctionName,TI);
2682             CurModule.RenameMap[Key] = NewName;
2683           }
2684         } else {
2685           // If they are not both definitions, then just use the function we
2686           // found since the types are the same.
2687           Fn = cast<Function>(Conflict);
2688
2689           // Make sure to strip off any argument names so we can't get 
2690           // conflicts.
2691           if (Fn->isDeclaration())
2692             for (Function::arg_iterator AI = Fn->arg_begin(), 
2693                  AE = Fn->arg_end(); AI != AE; ++AI)
2694               AI->setName("");
2695         }
2696       } else if (Conflict) {
2697         // We have two globals with the same name and  different types. 
2698         // Previously, this was permitted because the symbol table had 
2699         // "type planes" and names only needed to be distinct within a 
2700         // type plane. After PR411 was fixed, this is no loner the case. 
2701         // To resolve this we must rename one of the two. 
2702         if (Conflict->hasInternalLinkage()) {
2703           // We can safely renamed the Conflict.
2704           Conflict->setName(makeNameUnique(Conflict->getName()));
2705           TypeInfo TI; TI.T = Conflict->getType(); TI.S = ID.S;
2706           RenameMapKey Key = std::make_pair(FunctionName,TI);
2707           CurModule.RenameMap[Key] = Conflict->getName();
2708           Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2709           InsertValue(Fn, CurModule.Values);
2710         } else if (CurFun.Linkage == GlobalValue::InternalLinkage) {
2711           // We can safely rename the function we're defining
2712           std::string NewName = makeNameUnique(FunctionName);
2713           Fn = new Function(FT, CurFun.Linkage, NewName, M);
2714           InsertValue(Fn, CurModule.Values);
2715           TypeInfo TI; TI.T = PFT; TI.S = ID.S;
2716           RenameMapKey Key = std::make_pair(FunctionName,TI);
2717           CurModule.RenameMap[Key] = NewName;
2718         } else {
2719           // We can't quietly rename either of these things, but we must
2720           // rename one of them. Generate a warning about the renaming and
2721           // elect to rename the thing we're now defining.
2722           std::string NewName = makeNameUnique(FunctionName);
2723           warning("Renaming function '" + FunctionName + "' as '" + NewName +
2724                   "' may cause linkage errors");
2725           Fn = new Function(FT, CurFun.Linkage, NewName, M);
2726           InsertValue(Fn, CurModule.Values);
2727           TypeInfo TI; TI.T = PFT; TI.S = ID.S;
2728           RenameMapKey Key = std::make_pair(FunctionName,TI);
2729           CurModule.RenameMap[Key] = NewName;
2730         }
2731       } else {
2732         // There's no conflict, just define the function
2733         Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2734         InsertValue(Fn, CurModule.Values);
2735       }
2736     }
2737
2738     CurFun.FunctionStart(Fn);
2739
2740     if (CurFun.isDeclare) {
2741       // If we have declaration, always overwrite linkage.  This will allow us 
2742       // to correctly handle cases, when pointer to function is passed as 
2743       // argument to another function.
2744       Fn->setLinkage(CurFun.Linkage);
2745     }
2746     Fn->setCallingConv(upgradeCallingConv($1));
2747     Fn->setAlignment($8);
2748     if ($7) {
2749       Fn->setSection($7);
2750       free($7);
2751     }
2752
2753     // Add all of the arguments we parsed to the function...
2754     if ($5) {                     // Is null if empty...
2755       if (isVarArg) {  // Nuke the last entry
2756         assert($5->back().first.PAT->get() == Type::VoidTy && 
2757                $5->back().second == 0 && "Not a varargs marker");
2758         delete $5->back().first.PAT;
2759         $5->pop_back();  // Delete the last entry
2760       }
2761       Function::arg_iterator ArgIt = Fn->arg_begin();
2762       Function::arg_iterator ArgEnd = Fn->arg_end();
2763       std::vector<std::pair<PATypeInfo,char*> >::iterator I = $5->begin();
2764       std::vector<std::pair<PATypeInfo,char*> >::iterator E = $5->end();
2765       for ( ; I != E && ArgIt != ArgEnd; ++I, ++ArgIt) {
2766         delete I->first.PAT;                      // Delete the typeholder...
2767         ValueInfo VI; VI.V = ArgIt; VI.S = Signless; // FIXME: Sign
2768         setValueName(VI, I->second);           // Insert arg into symtab...
2769         InsertValue(ArgIt);
2770       }
2771       delete $5;                     // We're now done with the argument list
2772     }
2773   }
2774   ;
2775
2776 BEGIN 
2777   : BEGINTOK | '{'                // Allow BEGIN or '{' to start a function
2778   ;
2779
2780 FunctionHeader 
2781   : OptLinkage FunctionHeaderH BEGIN {
2782     $$ = CurFun.CurrentFunction;
2783
2784     // Make sure that we keep track of the linkage type even if there was a
2785     // previous "declare".
2786     $$->setLinkage($1);
2787   }
2788   ;
2789
2790 END 
2791   : ENDTOK | '}'                    // Allow end of '}' to end a function
2792   ;
2793
2794 Function 
2795   : BasicBlockList END {
2796     $$ = $1;
2797   };
2798
2799 FnDeclareLinkage
2800   : /*default*/ { $$ = GlobalValue::ExternalLinkage; }
2801   | DLLIMPORT   { $$ = GlobalValue::DLLImportLinkage; } 
2802   | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
2803   ;
2804   
2805 FunctionProto 
2806   : DECLARE { CurFun.isDeclare = true; } 
2807      FnDeclareLinkage { CurFun.Linkage = $3; } FunctionHeaderH {
2808     $$ = CurFun.CurrentFunction;
2809     CurFun.FunctionDone();
2810     
2811   }
2812   ;
2813
2814 //===----------------------------------------------------------------------===//
2815 //                        Rules to match Basic Blocks
2816 //===----------------------------------------------------------------------===//
2817
2818 OptSideEffect 
2819   : /* empty */ { $$ = false; }
2820   | SIDEEFFECT { $$ = true; }
2821   ;
2822
2823 ConstValueRef 
2824     // A reference to a direct constant
2825   : ESINT64VAL {    $$ = ValID::create($1); }
2826   | EUINT64VAL { $$ = ValID::create($1); }
2827   | FPVAL { $$ = ValID::create($1); } 
2828   | TRUETOK { 
2829     $$ = ValID::create(ConstantInt::get(Type::Int1Ty, true), Signed);
2830   }
2831   | FALSETOK { 
2832     $$ = ValID::create(ConstantInt::get(Type::Int1Ty, false), Unsigned); 
2833   }
2834   | NULL_TOK { $$ = ValID::createNull(); }
2835   | UNDEF { $$ = ValID::createUndef(); }
2836   | ZEROINITIALIZER { $$ = ValID::createZeroInit(); }
2837   | '<' ConstVector '>' { // Nonempty unsized packed vector
2838     const Type *ETy = (*$2)[0].C->getType();
2839     int NumElements = $2->size(); 
2840     VectorType* pt = VectorType::get(ETy, NumElements);
2841     PATypeHolder* PTy = new PATypeHolder(
2842       HandleUpRefs(VectorType::get(ETy, NumElements)));
2843     
2844     // Verify all elements are correct type!
2845     std::vector<Constant*> Elems;
2846     for (unsigned i = 0; i < $2->size(); i++) {
2847       Constant *C = (*$2)[i].C;
2848       const Type *CTy = C->getType();
2849       if (ETy != CTy)
2850         error("Element #" + utostr(i) + " is not of type '" + 
2851               ETy->getDescription() +"' as required!\nIt is of type '" +
2852               CTy->getDescription() + "'");
2853       Elems.push_back(C);
2854     }
2855     $$ = ValID::create(ConstantVector::get(pt, Elems), Signless);
2856     delete PTy; delete $2;
2857   }
2858   | ConstExpr {
2859     $$ = ValID::create($1.C, $1.S);
2860   }
2861   | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2862     char *End = UnEscapeLexed($3, true);
2863     std::string AsmStr = std::string($3, End);
2864     End = UnEscapeLexed($5, true);
2865     std::string Constraints = std::string($5, End);
2866     $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2867     free($3);
2868     free($5);
2869   }
2870   ;
2871
2872 // SymbolicValueRef - Reference to one of two ways of symbolically refering to // another value.
2873 //
2874 SymbolicValueRef 
2875   : INTVAL {  $$ = ValID::create($1,Signless); }
2876   | Name   {  $$ = ValID::create($1,Signless); }
2877   ;
2878
2879 // ValueRef - A reference to a definition... either constant or symbolic
2880 ValueRef 
2881   : SymbolicValueRef | ConstValueRef
2882   ;
2883
2884
2885 // ResolvedVal - a <type> <value> pair.  This is used only in cases where the
2886 // type immediately preceeds the value reference, and allows complex constant
2887 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2888 ResolvedVal 
2889   : Types ValueRef { 
2890     const Type *Ty = $1.PAT->get();
2891     $2.S = $1.S;
2892     $$.V = getVal(Ty, $2); 
2893     $$.S = $1.S;
2894     delete $1.PAT;
2895   }
2896   ;
2897
2898 BasicBlockList 
2899   : BasicBlockList BasicBlock {
2900     $$ = $1;
2901   }
2902   | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks   
2903     $$ = $1;
2904   };
2905
2906
2907 // Basic blocks are terminated by branching instructions: 
2908 // br, br/cc, switch, ret
2909 //
2910 BasicBlock 
2911   : InstructionList OptAssign BBTerminatorInst  {
2912     ValueInfo VI; VI.V = $3; VI.S = Signless;
2913     setValueName(VI, $2);
2914     InsertValue($3);
2915     $1->getInstList().push_back($3);
2916     InsertValue($1);
2917     $$ = $1;
2918   }
2919   ;
2920
2921 InstructionList
2922   : InstructionList Inst {
2923     if ($2.I)
2924       $1->getInstList().push_back($2.I);
2925     $$ = $1;
2926   }
2927   | /* empty */ {
2928     $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++,Signless),true);
2929     // Make sure to move the basic block to the correct location in the
2930     // function, instead of leaving it inserted wherever it was first
2931     // referenced.
2932     Function::BasicBlockListType &BBL = 
2933       CurFun.CurrentFunction->getBasicBlockList();
2934     BBL.splice(BBL.end(), BBL, $$);
2935   }
2936   | LABELSTR {
2937     $$ = CurBB = getBBVal(ValID::create($1,Signless), true);
2938     // Make sure to move the basic block to the correct location in the
2939     // function, instead of leaving it inserted wherever it was first
2940     // referenced.
2941     Function::BasicBlockListType &BBL = 
2942       CurFun.CurrentFunction->getBasicBlockList();
2943     BBL.splice(BBL.end(), BBL, $$);
2944   }
2945   ;
2946
2947 Unwind : UNWIND | EXCEPT;
2948
2949 BBTerminatorInst 
2950   : RET ResolvedVal {              // Return with a result...
2951     $$ = new ReturnInst($2.V);
2952   }
2953   | RET VOID {                                       // Return with no result...
2954     $$ = new ReturnInst();
2955   }
2956   | BR LABEL ValueRef {                         // Unconditional Branch...
2957     BasicBlock* tmpBB = getBBVal($3);
2958     $$ = new BranchInst(tmpBB);
2959   }                                                  // Conditional Branch...
2960   | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {  
2961     BasicBlock* tmpBBA = getBBVal($6);
2962     BasicBlock* tmpBBB = getBBVal($9);
2963     Value* tmpVal = getVal(Type::Int1Ty, $3);
2964     $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2965   }
2966   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2967     $3.S = $2.S;
2968     Value* tmpVal = getVal($2.T, $3);
2969     BasicBlock* tmpBB = getBBVal($6);
2970     SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2971     $$ = S;
2972     std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2973       E = $8->end();
2974     for (; I != E; ++I) {
2975       if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2976           S->addCase(CI, I->second);
2977       else
2978         error("Switch case is constant, but not a simple integer");
2979     }
2980     delete $8;
2981   }
2982   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2983     $3.S = $2.S;
2984     Value* tmpVal = getVal($2.T, $3);
2985     BasicBlock* tmpBB = getBBVal($6);
2986     SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2987     $$ = S;
2988   }
2989   | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
2990     TO LABEL ValueRef Unwind LABEL ValueRef {
2991     const PointerType *PFTy;
2992     const FunctionType *Ty;
2993
2994     if (!(PFTy = dyn_cast<PointerType>($3.PAT->get())) ||
2995         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2996       // Pull out the types of all of the arguments...
2997       std::vector<const Type*> ParamTypes;
2998       if ($6) {
2999         for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
3000              I != E; ++I)
3001           ParamTypes.push_back((*I).V->getType());
3002       }
3003       FunctionType::ParamAttrsList ParamAttrs;
3004       if ($2 == OldCallingConv::CSRet) {
3005         ParamAttrs.push_back(FunctionType::NoAttributeSet);
3006         ParamAttrs.push_back(FunctionType::StructRetAttribute);
3007       }
3008       bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
3009       if (isVarArg) ParamTypes.pop_back();
3010       Ty = FunctionType::get($3.PAT->get(), ParamTypes, isVarArg, ParamAttrs);
3011       PFTy = PointerType::get(Ty);
3012     }
3013     Value *V = getVal(PFTy, $4);   // Get the function we're calling...
3014     BasicBlock *Normal = getBBVal($10);
3015     BasicBlock *Except = getBBVal($13);
3016
3017     // Create the call node...
3018     if (!$6) {                                   // Has no arguments?
3019       $$ = new InvokeInst(V, Normal, Except, 0, 0);
3020     } else {                                     // Has arguments?
3021       // Loop through FunctionType's arguments and ensure they are specified
3022       // correctly!
3023       //
3024       FunctionType::param_iterator I = Ty->param_begin();
3025       FunctionType::param_iterator E = Ty->param_end();
3026       std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
3027
3028       std::vector<Value*> Args;
3029       for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
3030         if ((*ArgI).V->getType() != *I)
3031           error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
3032                 (*I)->getDescription() + "'");
3033         Args.push_back((*ArgI).V);
3034       }
3035
3036       if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
3037         error("Invalid number of parameters detected");
3038
3039       $$ = new InvokeInst(V, Normal, Except, &Args[0], Args.size());
3040     }
3041     cast<InvokeInst>($$)->setCallingConv(upgradeCallingConv($2));
3042     delete $3.PAT;
3043     delete $6;
3044   }
3045   | Unwind {
3046     $$ = new UnwindInst();
3047   }
3048   | UNREACHABLE {
3049     $$ = new UnreachableInst();
3050   }
3051   ;
3052
3053 JumpTable 
3054   : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
3055     $$ = $1;
3056     $3.S = $2.S;
3057     Constant *V = cast<Constant>(getExistingValue($2.T, $3));
3058     
3059     if (V == 0)
3060       error("May only switch on a constant pool value");
3061
3062     BasicBlock* tmpBB = getBBVal($6);
3063     $$->push_back(std::make_pair(V, tmpBB));
3064   }
3065   | IntType ConstValueRef ',' LABEL ValueRef {
3066     $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
3067     $2.S = $1.S;
3068     Constant *V = cast<Constant>(getExistingValue($1.T, $2));
3069
3070     if (V == 0)
3071       error("May only switch on a constant pool value");
3072
3073     BasicBlock* tmpBB = getBBVal($5);
3074     $$->push_back(std::make_pair(V, tmpBB)); 
3075   }
3076   ;
3077
3078 Inst 
3079   : OptAssign InstVal {
3080     bool omit = false;
3081     if ($1)
3082       if (BitCastInst *BCI = dyn_cast<BitCastInst>($2.I))
3083         if (BCI->getSrcTy() == BCI->getDestTy() && 
3084             BCI->getOperand(0)->getName() == $1)
3085           // This is a useless bit cast causing a name redefinition. It is
3086           // a bit cast from a type to the same type of an operand with the
3087           // same name as the name we would give this instruction. Since this
3088           // instruction results in no code generation, it is safe to omit
3089           // the instruction. This situation can occur because of collapsed
3090           // type planes. For example:
3091           //   %X = add int %Y, %Z
3092           //   %X = cast int %Y to uint
3093           // After upgrade, this looks like:
3094           //   %X = add i32 %Y, %Z
3095           //   %X = bitcast i32 to i32
3096           // The bitcast is clearly useless so we omit it.
3097           omit = true;
3098     if (omit) {
3099       $$.I = 0;
3100       $$.S = Signless;
3101     } else {
3102       ValueInfo VI; VI.V = $2.I; VI.S = $2.S;
3103       setValueName(VI, $1);
3104       InsertValue($2.I);
3105       $$ = $2;
3106     }
3107   };
3108
3109 PHIList : Types '[' ValueRef ',' ValueRef ']' {    // Used for PHI nodes
3110     $$.P = new std::list<std::pair<Value*, BasicBlock*> >();
3111     $$.S = $1.S;
3112     $3.S = $1.S;
3113     Value* tmpVal = getVal($1.PAT->get(), $3);
3114     BasicBlock* tmpBB = getBBVal($5);
3115     $$.P->push_back(std::make_pair(tmpVal, tmpBB));
3116     delete $1.PAT;
3117   }
3118   | PHIList ',' '[' ValueRef ',' ValueRef ']' {
3119     $$ = $1;
3120     $4.S = $1.S;
3121     Value* tmpVal = getVal($1.P->front().first->getType(), $4);
3122     BasicBlock* tmpBB = getBBVal($6);
3123     $1.P->push_back(std::make_pair(tmpVal, tmpBB));
3124   }
3125   ;
3126
3127 ValueRefList : ResolvedVal {    // Used for call statements, and memory insts...
3128     $$ = new std::vector<ValueInfo>();
3129     $$->push_back($1);
3130   }
3131   | ValueRefList ',' ResolvedVal {
3132     $$ = $1;
3133     $1->push_back($3);
3134   };
3135
3136 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
3137 ValueRefListE 
3138   : ValueRefList 
3139   | /*empty*/ { $$ = 0; }
3140   ;
3141
3142 OptTailCall 
3143   : TAIL CALL {
3144     $$ = true;
3145   }
3146   | CALL {
3147     $$ = false;
3148   }
3149   ;
3150
3151 InstVal 
3152   : ArithmeticOps Types ValueRef ',' ValueRef {
3153     $3.S = $5.S = $2.S;
3154     const Type* Ty = $2.PAT->get();
3155     if (!Ty->isInteger() && !Ty->isFloatingPoint() && !isa<VectorType>(Ty))
3156       error("Arithmetic operator requires integer, FP, or packed operands");
3157     if (isa<VectorType>(Ty) && 
3158         ($1 == URemOp || $1 == SRemOp || $1 == FRemOp || $1 == RemOp))
3159       error("Remainder not supported on vector types");
3160     // Upgrade the opcode from obsolete versions before we do anything with it.
3161     Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3162     Value* val1 = getVal(Ty, $3); 
3163     Value* val2 = getVal(Ty, $5);
3164     $$.I = BinaryOperator::create(Opcode, val1, val2);
3165     if ($$.I == 0)
3166       error("binary operator returned null");
3167     $$.S = $2.S;
3168     delete $2.PAT;
3169   }
3170   | LogicalOps Types ValueRef ',' ValueRef {
3171     $3.S = $5.S = $2.S;
3172     const Type *Ty = $2.PAT->get();
3173     if (!Ty->isInteger()) {
3174       if (!isa<VectorType>(Ty) ||
3175           !cast<VectorType>(Ty)->getElementType()->isInteger())
3176         error("Logical operator requires integral operands");
3177     }
3178     Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3179     Value* tmpVal1 = getVal(Ty, $3);
3180     Value* tmpVal2 = getVal(Ty, $5);
3181     $$.I = BinaryOperator::create(Opcode, tmpVal1, tmpVal2);
3182     if ($$.I == 0)
3183       error("binary operator returned null");
3184     $$.S = $2.S;
3185     delete $2.PAT;
3186   }
3187   | SetCondOps Types ValueRef ',' ValueRef {
3188     $3.S = $5.S = $2.S;
3189     const Type* Ty = $2.PAT->get();
3190     if(isa<VectorType>(Ty))
3191       error("VectorTypes currently not supported in setcc instructions");
3192     unsigned short pred;
3193     Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $2.S);
3194     Value* tmpVal1 = getVal(Ty, $3);
3195     Value* tmpVal2 = getVal(Ty, $5);
3196     $$.I = CmpInst::create(Opcode, pred, tmpVal1, tmpVal2);
3197     if ($$.I == 0)
3198       error("binary operator returned null");
3199     $$.S = Unsigned;
3200     delete $2.PAT;
3201   }
3202   | ICMP IPredicates Types ValueRef ',' ValueRef {
3203     $4.S = $6.S = $3.S;
3204     const Type *Ty = $3.PAT->get();
3205     if (isa<VectorType>(Ty)) 
3206       error("VectorTypes currently not supported in icmp instructions");
3207     else if (!Ty->isInteger() && !isa<PointerType>(Ty))
3208       error("icmp requires integer or pointer typed operands");
3209     Value* tmpVal1 = getVal(Ty, $4);
3210     Value* tmpVal2 = getVal(Ty, $6);
3211     $$.I = new ICmpInst($2, tmpVal1, tmpVal2);
3212     $$.S = Unsigned;
3213     delete $3.PAT;
3214   }
3215   | FCMP FPredicates Types ValueRef ',' ValueRef {
3216     $4.S = $6.S = $3.S;
3217     const Type *Ty = $3.PAT->get();
3218     if (isa<VectorType>(Ty))
3219       error("VectorTypes currently not supported in fcmp instructions");
3220     else if (!Ty->isFloatingPoint())
3221       error("fcmp instruction requires floating point operands");
3222     Value* tmpVal1 = getVal(Ty, $4);
3223     Value* tmpVal2 = getVal(Ty, $6);
3224     $$.I = new FCmpInst($2, tmpVal1, tmpVal2);
3225     $$.S = Unsigned;
3226     delete $3.PAT;
3227   }
3228   | NOT ResolvedVal {
3229     warning("Use of obsolete 'not' instruction: Replacing with 'xor");
3230     const Type *Ty = $2.V->getType();
3231     Value *Ones = ConstantInt::getAllOnesValue(Ty);
3232     if (Ones == 0)
3233       error("Expected integral type for not instruction");
3234     $$.I = BinaryOperator::create(Instruction::Xor, $2.V, Ones);
3235     if ($$.I == 0)
3236       error("Could not create a xor instruction");
3237     $$.S = $2.S;
3238   }
3239   | ShiftOps ResolvedVal ',' ResolvedVal {
3240     if (!$4.V->getType()->isInteger() ||
3241         cast<IntegerType>($4.V->getType())->getBitWidth() != 8)
3242       error("Shift amount must be int8");
3243     const Type* Ty = $2.V->getType();
3244     if (!Ty->isInteger())
3245       error("Shift constant expression requires integer operand");
3246     Value* ShiftAmt = 0;
3247     if (cast<IntegerType>(Ty)->getBitWidth() > Type::Int8Ty->getBitWidth())
3248       if (Constant *C = dyn_cast<Constant>($4.V))
3249         ShiftAmt = ConstantExpr::getZExt(C, Ty);
3250       else
3251         ShiftAmt = new ZExtInst($4.V, Ty, makeNameUnique("shift"), CurBB);
3252     else
3253       ShiftAmt = $4.V;
3254     $$.I = BinaryOperator::create(getBinaryOp($1, Ty, $2.S), $2.V, ShiftAmt);
3255     $$.S = $2.S;
3256   }
3257   | CastOps ResolvedVal TO Types {
3258     const Type *DstTy = $4.PAT->get();
3259     if (!DstTy->isFirstClassType())
3260       error("cast instruction to a non-primitive type: '" +
3261             DstTy->getDescription() + "'");
3262     $$.I = cast<Instruction>(getCast($1, $2.V, $2.S, DstTy, $4.S, true));
3263     $$.S = $4.S;
3264     delete $4.PAT;
3265   }
3266   | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3267     if (!$2.V->getType()->isInteger() ||
3268         cast<IntegerType>($2.V->getType())->getBitWidth() != 1)
3269       error("select condition must be bool");
3270     if ($4.V->getType() != $6.V->getType())
3271       error("select value types should match");
3272     $$.I = new SelectInst($2.V, $4.V, $6.V);
3273     $$.S = $2.S;
3274   }
3275   | VAARG ResolvedVal ',' Types {
3276     const Type *Ty = $4.PAT->get();
3277     NewVarArgs = true;
3278     $$.I = new VAArgInst($2.V, Ty);
3279     $$.S = $4.S;
3280     delete $4.PAT;
3281   }
3282   | VAARG_old ResolvedVal ',' Types {
3283     const Type* ArgTy = $2.V->getType();
3284     const Type* DstTy = $4.PAT->get();
3285     ObsoleteVarArgs = true;
3286     Function* NF = cast<Function>(CurModule.CurrentModule->
3287       getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3288
3289     //b = vaarg a, t -> 
3290     //foo = alloca 1 of t
3291     //bar = vacopy a 
3292     //store bar -> foo
3293     //b = vaarg foo, t
3294     AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
3295     CurBB->getInstList().push_back(foo);
3296     CallInst* bar = new CallInst(NF, $2.V);
3297     CurBB->getInstList().push_back(bar);
3298     CurBB->getInstList().push_back(new StoreInst(bar, foo));
3299     $$.I = new VAArgInst(foo, DstTy);
3300     $$.S = $4.S;
3301     delete $4.PAT;
3302   }
3303   | VANEXT_old ResolvedVal ',' Types {
3304     const Type* ArgTy = $2.V->getType();
3305     const Type* DstTy = $4.PAT->get();
3306     ObsoleteVarArgs = true;
3307     Function* NF = cast<Function>(CurModule.CurrentModule->
3308       getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3309
3310     //b = vanext a, t ->
3311     //foo = alloca 1 of t
3312     //bar = vacopy a
3313     //store bar -> foo
3314     //tmp = vaarg foo, t
3315     //b = load foo
3316     AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
3317     CurBB->getInstList().push_back(foo);
3318     CallInst* bar = new CallInst(NF, $2.V);
3319     CurBB->getInstList().push_back(bar);
3320     CurBB->getInstList().push_back(new StoreInst(bar, foo));
3321     Instruction* tmp = new VAArgInst(foo, DstTy);
3322     CurBB->getInstList().push_back(tmp);
3323     $$.I = new LoadInst(foo);
3324     $$.S = $4.S;
3325     delete $4.PAT;
3326   }
3327   | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
3328     if (!ExtractElementInst::isValidOperands($2.V, $4.V))
3329       error("Invalid extractelement operands");
3330     $$.I = new ExtractElementInst($2.V, $4.V);
3331     $$.S = $2.S;
3332   }
3333   | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3334     if (!InsertElementInst::isValidOperands($2.V, $4.V, $6.V))
3335       error("Invalid insertelement operands");
3336     $$.I = new InsertElementInst($2.V, $4.V, $6.V);
3337     $$.S = $2.S;
3338   }
3339   | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3340     if (!ShuffleVectorInst::isValidOperands($2.V, $4.V, $6.V))
3341       error("Invalid shufflevector operands");
3342     $$.I = new ShuffleVectorInst($2.V, $4.V, $6.V);
3343     $$.S = $2.S;
3344   }
3345   | PHI_TOK PHIList {
3346     const Type *Ty = $2.P->front().first->getType();
3347     if (!Ty->isFirstClassType())
3348       error("PHI node operands must be of first class type");
3349     PHINode *PHI = new PHINode(Ty);
3350     PHI->reserveOperandSpace($2.P->size());
3351     while ($2.P->begin() != $2.P->end()) {
3352       if ($2.P->front().first->getType() != Ty) 
3353         error("All elements of a PHI node must be of the same type");
3354       PHI->addIncoming($2.P->front().first, $2.P->front().second);
3355       $2.P->pop_front();
3356     }
3357     $$.I = PHI;
3358     $$.S = $2.S;
3359     delete $2.P;  // Free the list...
3360   }
3361   | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')'  {
3362     // Handle the short call syntax
3363     const PointerType *PFTy;
3364     const FunctionType *FTy;
3365     if (!(PFTy = dyn_cast<PointerType>($3.PAT->get())) ||
3366         !(FTy = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3367       // Pull out the types of all of the arguments...
3368       std::vector<const Type*> ParamTypes;
3369       if ($6) {
3370         for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
3371              I != E; ++I)
3372           ParamTypes.push_back((*I).V->getType());
3373       }
3374
3375       FunctionType::ParamAttrsList ParamAttrs;
3376       if ($2 == OldCallingConv::CSRet) {
3377         ParamAttrs.push_back(FunctionType::NoAttributeSet);
3378         ParamAttrs.push_back(FunctionType::StructRetAttribute);
3379       }
3380       bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
3381       if (isVarArg) ParamTypes.pop_back();
3382
3383       const Type *RetTy = $3.PAT->get();
3384       if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
3385         error("Functions cannot return aggregate types");
3386
3387       FTy = FunctionType::get(RetTy, ParamTypes, isVarArg, ParamAttrs);
3388       PFTy = PointerType::get(FTy);
3389     }
3390
3391     // First upgrade any intrinsic calls.
3392     std::vector<Value*> Args;
3393     if ($6)
3394       for (unsigned i = 0, e = $6->size(); i < e; ++i) 
3395         Args.push_back((*$6)[i].V);
3396     Instruction *Inst = upgradeIntrinsicCall(FTy, $4, Args);
3397
3398     // If we got an upgraded intrinsic
3399     if (Inst) {
3400       $$.I = Inst;
3401       $$.S = Signless;
3402     } else {
3403       // Get the function we're calling
3404       Value *V = getVal(PFTy, $4);
3405
3406       // Check the argument values match
3407       if (!$6) {                                   // Has no arguments?
3408         // Make sure no arguments is a good thing!
3409         if (FTy->getNumParams() != 0)
3410           error("No arguments passed to a function that expects arguments");
3411       } else {                                     // Has arguments?
3412         // Loop through FunctionType's arguments and ensure they are specified
3413         // correctly!
3414         //
3415         FunctionType::param_iterator I = FTy->param_begin();
3416         FunctionType::param_iterator E = FTy->param_end();
3417         std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
3418
3419         for (; ArgI != ArgE && I != E; ++ArgI, ++I)
3420           if ((*ArgI).V->getType() != *I)
3421             error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
3422                   (*I)->getDescription() + "'");
3423
3424         if (I != E || (ArgI != ArgE && !FTy->isVarArg()))
3425           error("Invalid number of parameters detected");
3426       }
3427
3428       // Create the call instruction
3429       CallInst *CI = new CallInst(V, &Args[0], Args.size());
3430       CI->setTailCall($1);
3431       CI->setCallingConv(upgradeCallingConv($2));
3432       $$.I = CI;
3433       $$.S = $3.S;
3434     }
3435     delete $3.PAT;
3436     delete $6;
3437   }
3438   | MemoryInst {
3439     $$ = $1;
3440   }
3441   ;
3442
3443
3444 // IndexList - List of indices for GEP based instructions...
3445 IndexList 
3446   : ',' ValueRefList { $$ = $2; } 
3447   | /* empty */ { $$ = new std::vector<ValueInfo>(); }
3448   ;
3449
3450 OptVolatile 
3451   : VOLATILE { $$ = true; }
3452   | /* empty */ { $$ = false; }
3453   ;
3454
3455 MemoryInst 
3456   : MALLOC Types OptCAlign {
3457     const Type *Ty = $2.PAT->get();
3458     $$.S = $2.S;
3459     $$.I = new MallocInst(Ty, 0, $3);
3460     delete $2.PAT;
3461   }
3462   | MALLOC Types ',' UINT ValueRef OptCAlign {
3463     const Type *Ty = $2.PAT->get();
3464     $$.S = $2.S;
3465     $5.S = Unsigned;
3466     $$.I = new MallocInst(Ty, getVal($4.T, $5), $6);
3467     delete $2.PAT;
3468   }
3469   | ALLOCA Types OptCAlign {
3470     const Type *Ty = $2.PAT->get();
3471     $$.S = $2.S;
3472     $$.I = new AllocaInst(Ty, 0, $3);
3473     delete $2.PAT;
3474   }
3475   | ALLOCA Types ',' UINT ValueRef OptCAlign {
3476     const Type *Ty = $2.PAT->get();
3477     $$.S = $2.S;
3478     $5.S = Unsigned;
3479     $$.I = new AllocaInst(Ty, getVal($4.T, $5), $6);
3480     delete $2.PAT;
3481   }
3482   | FREE ResolvedVal {
3483     const Type *PTy = $2.V->getType();
3484     if (!isa<PointerType>(PTy))
3485       error("Trying to free nonpointer type '" + PTy->getDescription() + "'");
3486     $$.I = new FreeInst($2.V);
3487     $$.S = Signless;
3488   }
3489   | OptVolatile LOAD Types ValueRef {
3490     const Type* Ty = $3.PAT->get();
3491     $$.S = $3.S;
3492     $4.S = $3.S;
3493     if (!isa<PointerType>(Ty))
3494       error("Can't load from nonpointer type: " + Ty->getDescription());
3495     if (!cast<PointerType>(Ty)->getElementType()->isFirstClassType())
3496       error("Can't load from pointer of non-first-class type: " +
3497                      Ty->getDescription());
3498     Value* tmpVal = getVal(Ty, $4);
3499     $$.I = new LoadInst(tmpVal, "", $1);
3500     delete $3.PAT;
3501   }
3502   | OptVolatile STORE ResolvedVal ',' Types ValueRef {
3503     $6.S = $5.S;
3504     const PointerType *PTy = dyn_cast<PointerType>($5.PAT->get());
3505     if (!PTy)
3506       error("Can't store to a nonpointer type: " + 
3507              $5.PAT->get()->getDescription());
3508     const Type *ElTy = PTy->getElementType();
3509     Value *StoreVal = $3.V;
3510     Value* tmpVal = getVal(PTy, $6);
3511     if (ElTy != $3.V->getType()) {
3512       StoreVal = handleSRetFuncTypeMerge($3.V, ElTy);
3513       if (!StoreVal)
3514         error("Can't store '" + $3.V->getType()->getDescription() +
3515               "' into space of type '" + ElTy->getDescription() + "'");
3516       else {
3517         PTy = PointerType::get(StoreVal->getType());
3518         if (Constant *C = dyn_cast<Constant>(tmpVal))
3519           tmpVal = ConstantExpr::getBitCast(C, PTy);
3520         else
3521           tmpVal = new BitCastInst(tmpVal, PTy, "upgrd.cast", CurBB);
3522       }
3523     }
3524     $$.I = new StoreInst(StoreVal, tmpVal, $1);
3525     $$.S = Signless;
3526     delete $5.PAT;
3527   }
3528   | GETELEMENTPTR Types ValueRef IndexList {
3529     $3.S = $2.S;
3530     const Type* Ty = $2.PAT->get();
3531     if (!isa<PointerType>(Ty))
3532       error("getelementptr insn requires pointer operand");
3533
3534     std::vector<Value*> VIndices;
3535     upgradeGEPIndices(Ty, $4, VIndices);
3536
3537     Value* tmpVal = getVal(Ty, $3);
3538     $$.I = new GetElementPtrInst(tmpVal, &VIndices[0], VIndices.size());
3539     $$.S = Signless;
3540     delete $2.PAT;
3541     delete $4;
3542   };
3543
3544
3545 %%
3546
3547 int yyerror(const char *ErrorMsg) {
3548   std::string where 
3549     = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3550                   + ":" + llvm::utostr((unsigned) Upgradelineno) + ": ";
3551   std::string errMsg = where + "error: " + std::string(ErrorMsg);
3552   if (yychar != YYEMPTY && yychar != 0)
3553     errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3554               "'.";
3555   std::cerr << "llvm-upgrade: " << errMsg << '\n';
3556   std::cout << "llvm-upgrade: parse failed.\n";
3557   exit(1);
3558 }
3559
3560 void warning(const std::string& ErrorMsg) {
3561   std::string where 
3562     = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3563                   + ":" + llvm::utostr((unsigned) Upgradelineno) + ": ";
3564   std::string errMsg = where + "warning: " + std::string(ErrorMsg);
3565   if (yychar != YYEMPTY && yychar != 0)
3566     errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3567               "'.";
3568   std::cerr << "llvm-upgrade: " << errMsg << '\n';
3569 }
3570
3571 void error(const std::string& ErrorMsg, int LineNo) {
3572   if (LineNo == -1) LineNo = Upgradelineno;
3573   Upgradelineno = LineNo;
3574   yyerror(ErrorMsg.c_str());
3575 }
3576