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