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