1 //===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file implements the bison parser for LLVM assembly languages files.
12 //===----------------------------------------------------------------------===//
15 #include "ParserInternals.h"
16 #include "llvm/SymbolTable.h"
17 #include "llvm/Module.h"
18 #include "llvm/iTerminators.h"
19 #include "llvm/iMemory.h"
20 #include "llvm/iOperators.h"
21 #include "llvm/iPHINode.h"
22 #include "llvm/Support/GetElementPtrTypeIterator.h"
23 #include "Support/STLExtras.h"
29 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
30 int yylex(); // declaration" of xxx warnings.
34 std::string CurFilename;
38 static Module *ParserResult;
40 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
41 // relating to upreferences in the input stream.
43 //#define DEBUG_UPREFS 1
45 #define UR_OUT(X) std::cerr << X
50 #define YYERROR_VERBOSE 1
52 // HACK ALERT: This variable is used to implement the automatic conversion of
53 // variable argument instructions from their old to new forms. When this
54 // compatiblity "Feature" is removed, this should be too.
56 static BasicBlock *CurBB;
57 static bool ObsoleteVarArgs;
60 // This contains info used when building the body of a function. It is
61 // destroyed when the function is completed.
63 typedef std::vector<Value *> ValueList; // Numbered defs
64 static void ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
65 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
67 static struct PerModuleInfo {
68 Module *CurrentModule;
69 std::map<const Type *, ValueList> Values; // Module level numbered definitions
70 std::map<const Type *,ValueList> LateResolveValues;
71 std::vector<PATypeHolder> Types;
72 std::map<ValID, PATypeHolder> LateResolveTypes;
74 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
75 /// how they were referenced and one which line of the input they came from so
76 /// that we can resolve them later and print error messages as appropriate.
77 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
79 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
80 // references to global values. Global values may be referenced before they
81 // are defined, and if so, the temporary object that they represent is held
82 // here. This is used for forward references of ConstantPointerRefs.
84 typedef std::map<std::pair<const PointerType *,
85 ValID>, GlobalValue*> GlobalRefsType;
86 GlobalRefsType GlobalRefs;
89 // If we could not resolve some functions at function compilation time
90 // (calls to functions before they are defined), resolve them now... Types
91 // are resolved when the constant pool has been completely parsed.
93 ResolveDefinitions(LateResolveValues);
95 // Check to make sure that all global value forward references have been
98 if (!GlobalRefs.empty()) {
99 std::string UndefinedReferences = "Unresolved global references exist:\n";
101 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
103 UndefinedReferences += " " + I->first.first->getDescription() + " " +
104 I->first.second.getName() + "\n";
106 ThrowException(UndefinedReferences);
109 Values.clear(); // Clear out function local definitions
115 // GetForwardRefForGlobal - Check to see if there is a forward reference
116 // for this global. If so, remove it from the GlobalRefs map and return it.
117 // If not, just return null.
118 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
119 // Check to see if there is a forward reference to this global variable...
120 // if there is, eliminate it and patch the reference to use the new def'n.
121 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
122 GlobalValue *Ret = 0;
123 if (I != GlobalRefs.end()) {
130 // DeclareNewGlobalValue - Called every time a new GV has been defined. This
131 // is used to remove things from the forward declaration map, resolving them
132 // to the correct thing as needed.
134 void DeclareNewGlobalValue(GlobalValue *GV, ValID D) {
135 // Check to see if there is a forward reference to this global variable...
136 // if there is, eliminate it and patch the reference to use the new def'n.
137 GlobalRefsType::iterator I =
138 GlobalRefs.find(std::make_pair(GV->getType(), D));
140 if (I != GlobalRefs.end()) {
141 GlobalValue *OldGV = I->second; // Get the placeholder...
142 I->first.second.destroy(); // Free string memory if necessary
144 // Replace all uses of the placeholder with the new GV
145 OldGV->replaceAllUsesWith(GV);
147 // Remove OldGV from the module...
148 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(OldGV))
149 CurrentModule->getGlobalList().erase(GVar);
151 CurrentModule->getFunctionList().erase(cast<Function>(OldGV));
153 // Remove the map entry for the global now that it has been created...
160 static struct PerFunctionInfo {
161 Function *CurrentFunction; // Pointer to current function being created
163 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
164 std::map<const Type*, ValueList> LateResolveValues;
165 std::vector<PATypeHolder> Types;
166 std::map<ValID, PATypeHolder> LateResolveTypes;
167 bool isDeclare; // Is this function a forward declararation?
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;
175 inline PerFunctionInfo() {
180 inline void FunctionStart(Function *M) {
185 void FunctionDone() {
186 NumberedBlocks.clear();
188 // Any forward referenced blocks left?
189 if (!BBForwardRefs.empty())
190 ThrowException("Undefined reference to label " +
191 BBForwardRefs.begin()->second.first.getName());
193 // Resolve all forward references now.
194 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
196 // Make sure to resolve any constant expr references that might exist within
197 // the function we just declared itself.
199 if (CurrentFunction->hasName()) {
200 FID = ValID::create((char*)CurrentFunction->getName().c_str());
202 // Figure out which slot number if is...
203 ValueList &List = CurModule.Values[CurrentFunction->getType()];
204 for (unsigned i = 0; ; ++i) {
205 assert(i < List.size() && "Function not found!");
206 if (List[i] == CurrentFunction) {
207 FID = ValID::create((int)i);
212 CurModule.DeclareNewGlobalValue(CurrentFunction, FID);
214 Values.clear(); // Clear out function local definitions
215 Types.clear(); // Clear out function local types
219 } CurFun; // Info for the current function...
221 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
224 //===----------------------------------------------------------------------===//
225 // Code to handle definitions of all the types
226 //===----------------------------------------------------------------------===//
228 static int InsertValue(Value *V,
229 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
230 if (V->hasName()) return -1; // Is this a numbered definition?
232 // Yes, insert the value into the value table...
233 ValueList &List = ValueTab[V->getType()];
235 return List.size()-1;
238 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
240 case ValID::NumberVal: { // Is it a numbered definition?
241 unsigned Num = (unsigned)D.Num;
243 // Module constants occupy the lowest numbered slots...
244 if (Num < CurModule.Types.size())
245 return CurModule.Types[Num];
247 Num -= CurModule.Types.size();
249 // Check that the number is within bounds...
250 if (Num <= CurFun.Types.size())
251 return CurFun.Types[Num];
254 case ValID::NameVal: { // Is it a named definition?
255 std::string Name(D.Name);
256 SymbolTable *SymTab = 0;
258 if (inFunctionScope()) {
259 SymTab = &CurFun.CurrentFunction->getSymbolTable();
260 N = SymTab->lookupType(Name);
264 // Symbol table doesn't automatically chain yet... because the function
265 // hasn't been added to the module...
267 SymTab = &CurModule.CurrentModule->getSymbolTable();
268 N = SymTab->lookupType(Name);
272 D.destroy(); // Free old strdup'd memory...
273 return cast<Type>(N);
276 ThrowException("Internal parser error: Invalid symbol type reference!");
279 // If we reached here, we referenced either a symbol that we don't know about
280 // or an id number that hasn't been read yet. We may be referencing something
281 // forward, so just create an entry to be resolved later and get to it...
283 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
285 std::map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ?
286 CurFun.LateResolveTypes : CurModule.LateResolveTypes;
288 std::map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
289 if (I != LateResolver.end()) {
293 Type *Typ = OpaqueType::get();
294 LateResolver.insert(std::make_pair(D, Typ));
298 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
299 SymbolTable &SymTab =
300 inFunctionScope() ? CurFun.CurrentFunction->getSymbolTable() :
301 CurModule.CurrentModule->getSymbolTable();
302 return SymTab.lookup(Ty, Name);
305 // getValNonImprovising - Look up the value specified by the provided type and
306 // the provided ValID. If the value exists and has already been defined, return
307 // it. Otherwise return null.
309 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
310 if (isa<FunctionType>(Ty))
311 ThrowException("Functions are not values and "
312 "must be referenced as pointers");
315 case ValID::NumberVal: { // Is it a numbered definition?
316 unsigned Num = (unsigned)D.Num;
318 // Module constants occupy the lowest numbered slots...
319 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
320 if (VI != CurModule.Values.end()) {
321 if (Num < VI->second.size())
322 return VI->second[Num];
323 Num -= VI->second.size();
326 // Make sure that our type is within bounds
327 VI = CurFun.Values.find(Ty);
328 if (VI == CurFun.Values.end()) return 0;
330 // Check that the number is within bounds...
331 if (VI->second.size() <= Num) return 0;
333 return VI->second[Num];
336 case ValID::NameVal: { // Is it a named definition?
337 Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
338 if (N == 0) return 0;
340 D.destroy(); // Free old strdup'd memory...
344 // Check to make sure that "Ty" is an integral type, and that our
345 // value will fit into the specified type...
346 case ValID::ConstSIntVal: // Is it a constant pool reference??
347 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64))
348 ThrowException("Signed integral constant '" +
349 itostr(D.ConstPool64) + "' is invalid for type '" +
350 Ty->getDescription() + "'!");
351 return ConstantSInt::get(Ty, D.ConstPool64);
353 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
354 if (!ConstantUInt::isValueValidForType(Ty, D.UConstPool64)) {
355 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64)) {
356 ThrowException("Integral constant '" + utostr(D.UConstPool64) +
357 "' is invalid or out of range!");
358 } else { // This is really a signed reference. Transmogrify.
359 return ConstantSInt::get(Ty, D.ConstPool64);
362 return ConstantUInt::get(Ty, D.UConstPool64);
365 case ValID::ConstFPVal: // Is it a floating point const pool reference?
366 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
367 ThrowException("FP constant invalid for type!!");
368 return ConstantFP::get(Ty, D.ConstPoolFP);
370 case ValID::ConstNullVal: // Is it a null value?
371 if (!isa<PointerType>(Ty))
372 ThrowException("Cannot create a a non pointer null!");
373 return ConstantPointerNull::get(cast<PointerType>(Ty));
375 case ValID::ConstantVal: // Fully resolved constant?
376 if (D.ConstantValue->getType() != Ty)
377 ThrowException("Constant expression type different from required type!");
378 return D.ConstantValue;
381 assert(0 && "Unhandled case!");
385 assert(0 && "Unhandled case!");
389 // getVal - This function is identical to getValNonImprovising, except that if a
390 // value is not already defined, it "improvises" by creating a placeholder var
391 // that looks and acts just like the requested variable. When the value is
392 // defined later, all uses of the placeholder variable are replaced with the
395 static Value *getVal(const Type *Ty, const ValID &ID) {
396 if (Ty == Type::LabelTy)
397 ThrowException("Cannot use a basic block here");
399 // See if the value has already been defined.
400 Value *V = getValNonImprovising(Ty, ID);
403 // If we reached here, we referenced either a symbol that we don't know about
404 // or an id number that hasn't been read yet. We may be referencing something
405 // forward, so just create an entry to be resolved later and get to it...
407 V = new Argument(Ty);
409 // Remember where this forward reference came from. FIXME, shouldn't we try
410 // to recycle these things??
411 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
414 if (inFunctionScope())
415 InsertValue(V, CurFun.LateResolveValues);
417 InsertValue(V, CurModule.LateResolveValues);
421 /// getBBVal - This is used for two purposes:
422 /// * If isDefinition is true, a new basic block with the specified ID is being
424 /// * If isDefinition is true, this is a reference to a basic block, which may
425 /// or may not be a forward reference.
427 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
428 assert(inFunctionScope() && "Can't get basic block at global scope!");
433 default: ThrowException("Illegal label reference " + ID.getName());
434 case ValID::NumberVal: // Is it a numbered definition?
435 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
436 CurFun.NumberedBlocks.resize(ID.Num+1);
437 BB = CurFun.NumberedBlocks[ID.Num];
439 case ValID::NameVal: // Is it a named definition?
441 if (Value *N = lookupInSymbolTable(Type::LabelTy, Name))
442 BB = cast<BasicBlock>(N);
446 // See if the block has already been defined.
448 // If this is the definition of the block, make sure the existing value was
449 // just a forward reference. If it was a forward reference, there will be
450 // an entry for it in the PlaceHolderInfo map.
451 if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
452 // The existing value was a definition, not a forward reference.
453 ThrowException("Redefinition of label " + ID.getName());
455 ID.destroy(); // Free strdup'd memory.
459 // Otherwise this block has not been seen before.
460 BB = new BasicBlock("", CurFun.CurrentFunction);
461 if (ID.Type == ValID::NameVal) {
462 BB->setName(ID.Name);
464 CurFun.NumberedBlocks[ID.Num] = BB;
467 // If this is not a definition, keep track of it so we can use it as a forward
470 // Remember where this forward reference came from.
471 CurFun.BBForwardRefs[BB] = std::make_pair(ID, llvmAsmlineno);
473 // The forward declaration could have been inserted anywhere in the
474 // function: insert it into the correct place now.
475 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
476 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
483 //===----------------------------------------------------------------------===//
484 // Code to handle forward references in instructions
485 //===----------------------------------------------------------------------===//
487 // This code handles the late binding needed with statements that reference
488 // values not defined yet... for example, a forward branch, or the PHI node for
491 // This keeps a table (CurFun.LateResolveValues) of all such forward references
492 // and back patchs after we are done.
495 // ResolveDefinitions - If we could not resolve some defs at parsing
496 // time (forward branches, phi functions for loops, etc...) resolve the
499 static void ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
500 std::map<const Type*,ValueList> *FutureLateResolvers) {
501 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
502 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
503 E = LateResolvers.end(); LRI != E; ++LRI) {
504 ValueList &List = LRI->second;
505 while (!List.empty()) {
506 Value *V = List.back();
509 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
510 CurModule.PlaceHolderInfo.find(V);
511 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
513 ValID &DID = PHI->second.first;
515 Value *TheRealValue = getValNonImprovising(LRI->first, DID);
517 V->replaceAllUsesWith(TheRealValue);
519 CurModule.PlaceHolderInfo.erase(PHI);
520 } else if (FutureLateResolvers) {
521 // Functions have their unresolved items forwarded to the module late
523 InsertValue(V, *FutureLateResolvers);
525 if (DID.Type == ValID::NameVal)
526 ThrowException("Reference to an invalid definition: '" +DID.getName()+
527 "' of type '" + V->getType()->getDescription() + "'",
530 ThrowException("Reference to an invalid definition: #" +
531 itostr(DID.Num) + " of type '" +
532 V->getType()->getDescription() + "'",
538 LateResolvers.clear();
541 // ResolveTypeTo - A brand new type was just declared. This means that (if
542 // name is not null) things referencing Name can be resolved. Otherwise, things
543 // refering to the number can be resolved. Do this now.
545 static void ResolveTypeTo(char *Name, const Type *ToTy) {
546 std::vector<PATypeHolder> &Types = inFunctionScope() ?
547 CurFun.Types : CurModule.Types;
550 if (Name) D = ValID::create(Name);
551 else D = ValID::create((int)Types.size());
553 std::map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ?
554 CurFun.LateResolveTypes : CurModule.LateResolveTypes;
556 std::map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
557 if (I != LateResolver.end()) {
558 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
559 LateResolver.erase(I);
563 // ResolveTypes - At this point, all types should be resolved. Any that aren't
566 static void ResolveTypes(std::map<ValID, PATypeHolder> &LateResolveTypes) {
567 if (!LateResolveTypes.empty()) {
568 const ValID &DID = LateResolveTypes.begin()->first;
570 if (DID.Type == ValID::NameVal)
571 ThrowException("Reference to an invalid type: '" +DID.getName() + "'");
573 ThrowException("Reference to an invalid type: #" + itostr(DID.Num));
577 // setValueName - Set the specified value to the name given. The name may be
578 // null potentially, in which case this is a noop. The string passed in is
579 // assumed to be a malloc'd string buffer, and is free'd by this function.
581 static void setValueName(Value *V, char *NameStr) {
583 std::string Name(NameStr); // Copy string
584 free(NameStr); // Free old string
586 if (V->getType() == Type::VoidTy)
587 ThrowException("Can't assign name '" + Name+"' to value with void type!");
589 assert(inFunctionScope() && "Must be in function scope!");
590 SymbolTable &ST = CurFun.CurrentFunction->getSymbolTable();
591 if (ST.lookup(V->getType(), Name))
592 ThrowException("Redefinition of value named '" + Name + "' in the '" +
593 V->getType()->getDescription() + "' type plane!");
596 V->setName(Name, &ST);
600 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
601 /// this is a declaration, otherwise it is a definition.
602 static void ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
603 bool isConstantGlobal, const Type *Ty,
604 Constant *Initializer) {
605 if (isa<FunctionType>(Ty))
606 ThrowException("Cannot declare global vars of function type!");
608 // If this global has a name, check to see if there is already a definition
609 // of this global in the module. If so, merge as appropriate. Note that
610 // this is really just a hack around problems in the CFE. :(
613 Name = NameStr; // Copy string
614 free(NameStr); // Free old string
616 SymbolTable &ST = CurModule.CurrentModule->getSymbolTable();
617 if (Value *Existing = ST.lookup(Ty, Name)) {
618 // We are a simple redefinition of a value, check to see if it is defined
619 // the same as the old one...
620 GlobalVariable *EGV = cast<GlobalVariable>(Existing);
622 // We are allowed to redefine a global variable in two circumstances:
623 // 1. If at least one of the globals is uninitialized or
624 // 2. If both initializers have the same value.
626 if (!EGV->hasInitializer() || !Initializer ||
627 EGV->getInitializer() == Initializer) {
629 // Make sure the existing global version gets the initializer! Make
630 // sure that it also gets marked const if the new version is.
631 if (Initializer && !EGV->hasInitializer())
632 EGV->setInitializer(Initializer);
633 if (isConstantGlobal)
634 EGV->setConstant(true);
635 EGV->setLinkage(Linkage);
639 ThrowException("Redefinition of value named '" + Name + "' in the '" +
640 Ty->getDescription() + "' type plane!");
644 const PointerType *PTy = PointerType::get(Ty);
646 // See if this global value was forward referenced. If so, recycle the
650 ID = ValID::create((char*)Name.c_str());
652 ID = ValID::create((int)CurModule.Values[PTy].size());
655 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
656 // Move the global to the end of the list, from whereever it was
657 // previously inserted.
658 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
659 CurModule.CurrentModule->getGlobalList().remove(GV);
660 CurModule.CurrentModule->getGlobalList().push_back(GV);
661 GV->setInitializer(Initializer);
662 GV->setLinkage(Linkage);
663 GV->setConstant(isConstantGlobal);
665 // Otherwise there is no existing GV to use, create one now.
666 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
667 CurModule.CurrentModule);
671 // setTypeName - Set the specified type to the name given. The name may be
672 // null potentially, in which case this is a noop. The string passed in is
673 // assumed to be a malloc'd string buffer, and is freed by this function.
675 // This function returns true if the type has already been defined, but is
676 // allowed to be redefined in the specified context. If the name is a new name
677 // for the type plane, it is inserted and false is returned.
678 static bool setTypeName(const Type *T, char *NameStr) {
679 if (NameStr == 0) return false;
681 std::string Name(NameStr); // Copy string
682 free(NameStr); // Free old string
684 // We don't allow assigning names to void type
685 if (T == Type::VoidTy)
686 ThrowException("Can't assign name '" + Name + "' to the void type!");
688 SymbolTable &ST = inFunctionScope() ?
689 CurFun.CurrentFunction->getSymbolTable() :
690 CurModule.CurrentModule->getSymbolTable();
692 // Inserting a name that is already defined???
693 if (Type *Existing = ST.lookupType(Name)) {
694 // There is only one case where this is allowed: when we are refining an
695 // opaque type. In this case, Existing will be an opaque type.
696 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
697 // We ARE replacing an opaque type!
698 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
702 // Otherwise, this is an attempt to redefine a type. That's okay if
703 // the redefinition is identical to the original. This will be so if
704 // Existing and T point to the same Type object. In this one case we
705 // allow the equivalent redefinition.
706 if (Existing == T) return true; // Yes, it's equal.
708 // Any other kind of (non-equivalent) redefinition is an error.
709 ThrowException("Redefinition of type named '" + Name + "' in the '" +
710 T->getDescription() + "' type plane!");
713 // Okay, its a newly named type. Set its name.
714 if (!Name.empty()) ST.insert(Name, T);
719 //===----------------------------------------------------------------------===//
720 // Code for handling upreferences in type names...
723 // TypeContains - Returns true if Ty directly contains E in it.
725 static bool TypeContains(const Type *Ty, const Type *E) {
726 return find(Ty->subtype_begin(), Ty->subtype_end(), E) != Ty->subtype_end();
731 // NestingLevel - The number of nesting levels that need to be popped before
732 // this type is resolved.
733 unsigned NestingLevel;
735 // LastContainedTy - This is the type at the current binding level for the
736 // type. Every time we reduce the nesting level, this gets updated.
737 const Type *LastContainedTy;
739 // UpRefTy - This is the actual opaque type that the upreference is
743 UpRefRecord(unsigned NL, OpaqueType *URTy)
744 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
748 // UpRefs - A list of the outstanding upreferences that need to be resolved.
749 static std::vector<UpRefRecord> UpRefs;
751 /// HandleUpRefs - Every time we finish a new layer of types, this function is
752 /// called. It loops through the UpRefs vector, which is a list of the
753 /// currently active types. For each type, if the up reference is contained in
754 /// the newly completed type, we decrement the level count. When the level
755 /// count reaches zero, the upreferenced type is the type that is passed in:
756 /// thus we can complete the cycle.
758 static PATypeHolder HandleUpRefs(const Type *ty) {
759 if (!ty->isAbstract()) return ty;
761 UR_OUT("Type '" << Ty->getDescription() <<
762 "' newly formed. Resolving upreferences.\n" <<
763 UpRefs.size() << " upreferences active!\n");
765 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
766 // to zero), we resolve them all together before we resolve them to Ty. At
767 // the end of the loop, if there is anything to resolve to Ty, it will be in
769 OpaqueType *TypeToResolve = 0;
771 for (unsigned i = 0; i != UpRefs.size(); ++i) {
772 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
773 << UpRefs[i].second->getDescription() << ") = "
774 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
775 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
776 // Decrement level of upreference
777 unsigned Level = --UpRefs[i].NestingLevel;
778 UpRefs[i].LastContainedTy = Ty;
779 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
780 if (Level == 0) { // Upreference should be resolved!
781 if (!TypeToResolve) {
782 TypeToResolve = UpRefs[i].UpRefTy;
784 UR_OUT(" * Resolving upreference for "
785 << UpRefs[i].second->getDescription() << "\n";
786 std::string OldName = UpRefs[i].UpRefTy->getDescription());
787 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
788 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
789 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
791 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
792 --i; // Do not skip the next element...
798 UR_OUT(" * Resolving upreference for "
799 << UpRefs[i].second->getDescription() << "\n";
800 std::string OldName = TypeToResolve->getDescription());
801 TypeToResolve->refineAbstractTypeTo(Ty);
808 //===----------------------------------------------------------------------===//
809 // RunVMAsmParser - Define an interface to this parser
810 //===----------------------------------------------------------------------===//
812 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
814 CurFilename = Filename;
815 llvmAsmlineno = 1; // Reset the current line number...
816 ObsoleteVarArgs = false;
818 // Allocate a new module to read
819 CurModule.CurrentModule = new Module(Filename);
821 yyparse(); // Parse the file, potentially throwing exception
823 Module *Result = ParserResult;
825 // Check to see if they called va_start but not va_arg..
826 if (!ObsoleteVarArgs)
827 if (Function *F = Result->getNamedFunction("llvm.va_start"))
828 if (F->asize() == 1) {
829 std::cerr << "WARNING: this file uses obsolete features. "
830 << "Assemble and disassemble to update it.\n";
831 ObsoleteVarArgs = true;
834 if (ObsoleteVarArgs) {
835 // If the user is making use of obsolete varargs intrinsics, adjust them for
837 if (Function *F = Result->getNamedFunction("llvm.va_start")) {
838 assert(F->asize() == 1 && "Obsolete va_start takes 1 argument!");
840 const Type *RetTy = F->getFunctionType()->getParamType(0);
841 RetTy = cast<PointerType>(RetTy)->getElementType();
842 Function *NF = Result->getOrInsertFunction("llvm.va_start", RetTy, 0);
844 while (!F->use_empty()) {
845 CallInst *CI = cast<CallInst>(F->use_back());
846 Value *V = new CallInst(NF, "", CI);
847 new StoreInst(V, CI->getOperand(1), CI);
848 CI->getParent()->getInstList().erase(CI);
850 Result->getFunctionList().erase(F);
853 if (Function *F = Result->getNamedFunction("llvm.va_end")) {
854 assert(F->asize() == 1 && "Obsolete va_end takes 1 argument!");
855 const Type *ArgTy = F->getFunctionType()->getParamType(0);
856 ArgTy = cast<PointerType>(ArgTy)->getElementType();
857 Function *NF = Result->getOrInsertFunction("llvm.va_end", Type::VoidTy,
860 while (!F->use_empty()) {
861 CallInst *CI = cast<CallInst>(F->use_back());
862 Value *V = new LoadInst(CI->getOperand(1), "", CI);
863 new CallInst(NF, V, "", CI);
864 CI->getParent()->getInstList().erase(CI);
866 Result->getFunctionList().erase(F);
869 if (Function *F = Result->getNamedFunction("llvm.va_copy")) {
870 assert(F->asize() == 2 && "Obsolete va_copy takes 2 argument!");
871 const Type *ArgTy = F->getFunctionType()->getParamType(0);
872 ArgTy = cast<PointerType>(ArgTy)->getElementType();
873 Function *NF = Result->getOrInsertFunction("llvm.va_copy", ArgTy,
876 while (!F->use_empty()) {
877 CallInst *CI = cast<CallInst>(F->use_back());
878 Value *V = new CallInst(NF, CI->getOperand(2), "", CI);
879 new StoreInst(V, CI->getOperand(1), CI);
880 CI->getParent()->getInstList().erase(CI);
882 Result->getFunctionList().erase(F);
886 llvmAsmin = stdin; // F is about to go away, don't use it anymore...
895 llvm::Module *ModuleVal;
896 llvm::Function *FunctionVal;
897 std::pair<llvm::PATypeHolder*, char*> *ArgVal;
898 llvm::BasicBlock *BasicBlockVal;
899 llvm::TerminatorInst *TermInstVal;
900 llvm::Instruction *InstVal;
901 llvm::Constant *ConstVal;
903 const llvm::Type *PrimType;
904 llvm::PATypeHolder *TypeVal;
905 llvm::Value *ValueVal;
907 std::vector<std::pair<llvm::PATypeHolder*,char*> > *ArgList;
908 std::vector<llvm::Value*> *ValueList;
909 std::list<llvm::PATypeHolder> *TypeList;
910 std::list<std::pair<llvm::Value*,
911 llvm::BasicBlock*> > *PHIList; // Represent the RHS of PHI node
912 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
913 std::vector<llvm::Constant*> *ConstVector;
915 llvm::GlobalValue::LinkageTypes Linkage;
923 char *StrVal; // This memory is strdup'd!
924 llvm::ValID ValIDVal; // strdup'd memory maybe!
926 llvm::Instruction::BinaryOps BinaryOpVal;
927 llvm::Instruction::TermOps TermOpVal;
928 llvm::Instruction::MemoryOps MemOpVal;
929 llvm::Instruction::OtherOps OtherOpVal;
930 llvm::Module::Endianness Endianness;
933 %type <ModuleVal> Module FunctionList
934 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
935 %type <BasicBlockVal> BasicBlock InstructionList
936 %type <TermInstVal> BBTerminatorInst
937 %type <InstVal> Inst InstVal MemoryInst
938 %type <ConstVal> ConstVal ConstExpr
939 %type <ConstVector> ConstVector
940 %type <ArgList> ArgList ArgListH
941 %type <ArgVal> ArgVal
942 %type <PHIList> PHIList
943 %type <ValueList> ValueRefList ValueRefListE // For call param lists
944 %type <ValueList> IndexList // For GEP derived indices
945 %type <TypeList> TypeListI ArgTypeListI
946 %type <JumpTable> JumpTable
947 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
948 %type <BoolVal> OptVolatile // 'volatile' or not
949 %type <Linkage> OptLinkage
950 %type <Endianness> BigOrLittle
952 // ValueRef - Unresolved reference to a definition or BB
953 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
954 %type <ValueVal> ResolvedVal // <type> <valref> pair
955 // Tokens and types for handling constant integer values
957 // ESINT64VAL - A negative number within long long range
958 %token <SInt64Val> ESINT64VAL
960 // EUINT64VAL - A positive number within uns. long long range
961 %token <UInt64Val> EUINT64VAL
962 %type <SInt64Val> EINT64VAL
964 %token <SIntVal> SINTVAL // Signed 32 bit ints...
965 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
966 %type <SIntVal> INTVAL
967 %token <FPVal> FPVAL // Float or Double constant
970 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
971 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
972 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
973 %token <PrimType> FLOAT DOUBLE TYPE LABEL
975 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
976 %type <StrVal> Name OptName OptAssign
979 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
980 %token DECLARE GLOBAL CONSTANT VOLATILE
981 %token TO DOTDOTDOT NULL_TOK CONST INTERNAL LINKONCE WEAK APPENDING
982 %token OPAQUE NOT EXTERNAL TARGET ENDIAN POINTERSIZE LITTLE BIG
984 // Basic Block Terminating Operators
985 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND
988 %type <BinaryOpVal> BinaryOps // all the binary operators
989 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
990 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
991 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comarators
993 // Memory Instructions
994 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
997 %type <OtherOpVal> ShiftOps
998 %token <OtherOpVal> PHI_TOK CALL CAST SELECT SHL SHR VAARG VANEXT
999 %token VA_ARG // FIXME: OBSOLETE
1004 // Handle constant integer size restriction and conversion...
1008 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
1009 ThrowException("Value too large for type!");
1014 EINT64VAL : ESINT64VAL; // These have same type and can't cause problems...
1015 EINT64VAL : EUINT64VAL {
1016 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
1017 ThrowException("Value too large for type!");
1021 // Operations that are notably excluded from this list include:
1022 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1024 ArithmeticOps: ADD | SUB | MUL | DIV | REM;
1025 LogicalOps : AND | OR | XOR;
1026 SetCondOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
1027 BinaryOps : ArithmeticOps | LogicalOps | SetCondOps;
1029 ShiftOps : SHL | SHR;
1031 // These are some types that allow classification if we only want a particular
1032 // thing... for example, only a signed, unsigned, or integral type.
1033 SIntType : LONG | INT | SHORT | SBYTE;
1034 UIntType : ULONG | UINT | USHORT | UBYTE;
1035 IntType : SIntType | UIntType;
1036 FPType : FLOAT | DOUBLE;
1038 // OptAssign - Value producing statements have an optional assignment component
1039 OptAssign : Name '=' {
1046 OptLinkage : INTERNAL { $$ = GlobalValue::InternalLinkage; } |
1047 LINKONCE { $$ = GlobalValue::LinkOnceLinkage; } |
1048 WEAK { $$ = GlobalValue::WeakLinkage; } |
1049 APPENDING { $$ = GlobalValue::AppendingLinkage; } |
1050 /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
1052 //===----------------------------------------------------------------------===//
1053 // Types includes all predefined types... except void, because it can only be
1054 // used in specific contexts (function returning void for example). To have
1055 // access to it, a user must explicitly use TypesV.
1058 // TypesV includes all of 'Types', but it also includes the void type.
1059 TypesV : Types | VOID { $$ = new PATypeHolder($1); };
1060 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
1063 if (!UpRefs.empty())
1064 ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
1069 // Derived types are added later...
1071 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT ;
1072 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL;
1074 $$ = new PATypeHolder(OpaqueType::get());
1077 $$ = new PATypeHolder($1);
1079 UpRTypes : SymbolicValueRef { // Named types are also simple types...
1080 $$ = new PATypeHolder(getTypeVal($1));
1083 // Include derived types in the Types production.
1085 UpRTypes : '\\' EUINT64VAL { // Type UpReference
1086 if ($2 > (uint64_t)~0U) ThrowException("Value out of range!");
1087 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1088 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1089 $$ = new PATypeHolder(OT);
1090 UR_OUT("New Upreference!\n");
1092 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
1093 std::vector<const Type*> Params;
1094 mapto($3->begin(), $3->end(), std::back_inserter(Params),
1095 std::mem_fun_ref(&PATypeHolder::get));
1096 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1097 if (isVarArg) Params.pop_back();
1099 $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
1100 delete $3; // Delete the argument list
1101 delete $1; // Delete the return type handle
1103 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
1104 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1107 | '{' TypeListI '}' { // Structure type?
1108 std::vector<const Type*> Elements;
1109 mapto($2->begin(), $2->end(), std::back_inserter(Elements),
1110 std::mem_fun_ref(&PATypeHolder::get));
1112 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1115 | '{' '}' { // Empty structure type?
1116 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1118 | UpRTypes '*' { // Pointer type?
1119 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1123 // TypeList - Used for struct declarations and as a basis for function type
1124 // declaration type lists
1126 TypeListI : UpRTypes {
1127 $$ = new std::list<PATypeHolder>();
1128 $$->push_back(*$1); delete $1;
1130 | TypeListI ',' UpRTypes {
1131 ($$=$1)->push_back(*$3); delete $3;
1134 // ArgTypeList - List of types for a function type declaration...
1135 ArgTypeListI : TypeListI
1136 | TypeListI ',' DOTDOTDOT {
1137 ($$=$1)->push_back(Type::VoidTy);
1140 ($$ = new std::list<PATypeHolder>())->push_back(Type::VoidTy);
1143 $$ = new std::list<PATypeHolder>();
1146 // ConstVal - The various declarations that go into the constant pool. This
1147 // production is used ONLY to represent constants that show up AFTER a 'const',
1148 // 'constant' or 'global' token at global scope. Constants that can be inlined
1149 // into other expressions (such as integers and constexprs) are handled by the
1150 // ResolvedVal, ValueRef and ConstValueRef productions.
1152 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1153 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1155 ThrowException("Cannot make array constant with type: '" +
1156 (*$1)->getDescription() + "'!");
1157 const Type *ETy = ATy->getElementType();
1158 int NumElements = ATy->getNumElements();
1160 // Verify that we have the correct size...
1161 if (NumElements != -1 && NumElements != (int)$3->size())
1162 ThrowException("Type mismatch: constant sized array initialized with " +
1163 utostr($3->size()) + " arguments, but has size of " +
1164 itostr(NumElements) + "!");
1166 // Verify all elements are correct type!
1167 for (unsigned i = 0; i < $3->size(); i++) {
1168 if (ETy != (*$3)[i]->getType())
1169 ThrowException("Element #" + utostr(i) + " is not of type '" +
1170 ETy->getDescription() +"' as required!\nIt is of type '"+
1171 (*$3)[i]->getType()->getDescription() + "'.");
1174 $$ = ConstantArray::get(ATy, *$3);
1175 delete $1; delete $3;
1178 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1180 ThrowException("Cannot make array constant with type: '" +
1181 (*$1)->getDescription() + "'!");
1183 int NumElements = ATy->getNumElements();
1184 if (NumElements != -1 && NumElements != 0)
1185 ThrowException("Type mismatch: constant sized array initialized with 0"
1186 " arguments, but has size of " + itostr(NumElements) +"!");
1187 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1190 | Types 'c' STRINGCONSTANT {
1191 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1193 ThrowException("Cannot make array constant with type: '" +
1194 (*$1)->getDescription() + "'!");
1196 int NumElements = ATy->getNumElements();
1197 const Type *ETy = ATy->getElementType();
1198 char *EndStr = UnEscapeLexed($3, true);
1199 if (NumElements != -1 && NumElements != (EndStr-$3))
1200 ThrowException("Can't build string constant of size " +
1201 itostr((int)(EndStr-$3)) +
1202 " when array has size " + itostr(NumElements) + "!");
1203 std::vector<Constant*> Vals;
1204 if (ETy == Type::SByteTy) {
1205 for (char *C = $3; C != EndStr; ++C)
1206 Vals.push_back(ConstantSInt::get(ETy, *C));
1207 } else if (ETy == Type::UByteTy) {
1208 for (char *C = $3; C != EndStr; ++C)
1209 Vals.push_back(ConstantUInt::get(ETy, (unsigned char)*C));
1212 ThrowException("Cannot build string arrays of non byte sized elements!");
1215 $$ = ConstantArray::get(ATy, Vals);
1218 | Types '{' ConstVector '}' {
1219 const StructType *STy = dyn_cast<StructType>($1->get());
1221 ThrowException("Cannot make struct constant with type: '" +
1222 (*$1)->getDescription() + "'!");
1224 if ($3->size() != STy->getNumContainedTypes())
1225 ThrowException("Illegal number of initializers for structure type!");
1227 // Check to ensure that constants are compatible with the type initializer!
1228 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1229 if ((*$3)[i]->getType() != STy->getElementType(i))
1230 ThrowException("Expected type '" +
1231 STy->getElementType(i)->getDescription() +
1232 "' for element #" + utostr(i) +
1233 " of structure initializer!");
1235 $$ = ConstantStruct::get(STy, *$3);
1236 delete $1; delete $3;
1239 const StructType *STy = dyn_cast<StructType>($1->get());
1241 ThrowException("Cannot make struct constant with type: '" +
1242 (*$1)->getDescription() + "'!");
1244 if (STy->getNumContainedTypes() != 0)
1245 ThrowException("Illegal number of initializers for structure type!");
1247 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1251 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1253 ThrowException("Cannot make null pointer constant with type: '" +
1254 (*$1)->getDescription() + "'!");
1256 $$ = ConstantPointerNull::get(PTy);
1259 | Types SymbolicValueRef {
1260 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1262 ThrowException("Global const reference must be a pointer type!");
1264 // ConstExprs can exist in the body of a function, thus creating
1265 // ConstantPointerRefs whenever they refer to a variable. Because we are in
1266 // the context of a function, getValNonImprovising will search the functions
1267 // symbol table instead of the module symbol table for the global symbol,
1268 // which throws things all off. To get around this, we just tell
1269 // getValNonImprovising that we are at global scope here.
1271 Function *SavedCurFn = CurFun.CurrentFunction;
1272 CurFun.CurrentFunction = 0;
1274 Value *V = getValNonImprovising(Ty, $2);
1276 CurFun.CurrentFunction = SavedCurFn;
1278 // If this is an initializer for a constant pointer, which is referencing a
1279 // (currently) undefined variable, create a stub now that shall be replaced
1280 // in the future with the right type of variable.
1283 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1284 const PointerType *PT = cast<PointerType>(Ty);
1286 // First check to see if the forward references value is already created!
1287 PerModuleInfo::GlobalRefsType::iterator I =
1288 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1290 if (I != CurModule.GlobalRefs.end()) {
1291 V = I->second; // Placeholder already exists, use it...
1296 /// FIXME: We shouldn't be creating global vars as forward refs for
1297 /// functions at all here!
1298 if (!isa<FunctionType>(PT->getElementType()))
1299 if ($2.Type == ValID::NameVal) Name = $2.Name;
1301 // Create a placeholder for the global variable reference...
1302 GlobalVariable *GV = new GlobalVariable(PT->getElementType(), false,
1303 GlobalValue::ExternalLinkage,0,
1304 Name, CurModule.CurrentModule);
1306 // Keep track of the fact that we have a forward ref to recycle it
1307 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1312 GlobalValue *GV = cast<GlobalValue>(V);
1313 $$ = ConstantPointerRef::get(GV);
1314 delete $1; // Free the type handle
1317 if ($1->get() != $2->getType())
1318 ThrowException("Mismatched types for constant expression!");
1322 | Types ZEROINITIALIZER {
1323 $$ = Constant::getNullValue($1->get());
1327 ConstVal : SIntType EINT64VAL { // integral constants
1328 if (!ConstantSInt::isValueValidForType($1, $2))
1329 ThrowException("Constant value doesn't fit in type!");
1330 $$ = ConstantSInt::get($1, $2);
1332 | UIntType EUINT64VAL { // integral constants
1333 if (!ConstantUInt::isValueValidForType($1, $2))
1334 ThrowException("Constant value doesn't fit in type!");
1335 $$ = ConstantUInt::get($1, $2);
1337 | BOOL TRUETOK { // Boolean constants
1338 $$ = ConstantBool::True;
1340 | BOOL FALSETOK { // Boolean constants
1341 $$ = ConstantBool::False;
1343 | FPType FPVAL { // Float & Double constants
1344 $$ = ConstantFP::get($1, $2);
1348 ConstExpr: CAST '(' ConstVal TO Types ')' {
1349 if (!$3->getType()->isFirstClassType())
1350 ThrowException("cast constant expression from a non-primitive type: '" +
1351 $3->getType()->getDescription() + "'!");
1352 if (!$5->get()->isFirstClassType())
1353 ThrowException("cast constant expression to a non-primitive type: '" +
1354 $5->get()->getDescription() + "'!");
1355 $$ = ConstantExpr::getCast($3, $5->get());
1358 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1359 if (!isa<PointerType>($3->getType()))
1360 ThrowException("GetElementPtr requires a pointer operand!");
1362 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
1363 // indices to uint struct indices for compatibility.
1364 generic_gep_type_iterator<std::vector<Value*>::iterator>
1365 GTI = gep_type_begin($3->getType(), $4->begin(), $4->end()),
1366 GTE = gep_type_end($3->getType(), $4->begin(), $4->end());
1367 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
1368 if (isa<StructType>(*GTI)) // Only change struct indices
1369 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
1370 if (CUI->getType() == Type::UByteTy)
1371 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
1374 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1376 ThrowException("Index list invalid for constant getelementptr!");
1378 std::vector<Constant*> IdxVec;
1379 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1380 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1381 IdxVec.push_back(C);
1383 ThrowException("Indices to constant getelementptr must be constants!");
1387 $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1389 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1390 if ($3->getType() != Type::BoolTy)
1391 ThrowException("Select condition must be of boolean type!");
1392 if ($5->getType() != $7->getType())
1393 ThrowException("Select operand types must match!");
1394 $$ = ConstantExpr::getSelect($3, $5, $7);
1396 | BinaryOps '(' ConstVal ',' ConstVal ')' {
1397 if ($3->getType() != $5->getType())
1398 ThrowException("Binary operator types must match!");
1399 $$ = ConstantExpr::get($1, $3, $5);
1401 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1402 if ($5->getType() != Type::UByteTy)
1403 ThrowException("Shift count for shift constant must be unsigned byte!");
1404 if (!$3->getType()->isInteger())
1405 ThrowException("Shift constant expression requires integer operand!");
1406 $$ = ConstantExpr::get($1, $3, $5);
1410 // ConstVector - A list of comma separated constants.
1411 ConstVector : ConstVector ',' ConstVal {
1412 ($$ = $1)->push_back($3);
1415 $$ = new std::vector<Constant*>();
1420 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1421 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1424 //===----------------------------------------------------------------------===//
1425 // Rules to match Modules
1426 //===----------------------------------------------------------------------===//
1428 // Module rule: Capture the result of parsing the whole file into a result
1431 Module : FunctionList {
1432 $$ = ParserResult = $1;
1433 CurModule.ModuleDone();
1436 // FunctionList - A list of functions, preceeded by a constant pool.
1438 FunctionList : FunctionList Function {
1440 CurFun.FunctionDone();
1442 | FunctionList FunctionProto {
1445 | FunctionList IMPLEMENTATION {
1449 $$ = CurModule.CurrentModule;
1450 // Resolve circular types before we parse the body of the module
1451 ResolveTypes(CurModule.LateResolveTypes);
1454 // ConstPool - Constants with optional names assigned to them.
1455 ConstPool : ConstPool OptAssign TYPE TypesV { // Types can be defined in the const pool
1456 // Eagerly resolve types. This is not an optimization, this is a
1457 // requirement that is due to the fact that we could have this:
1459 // %list = type { %list * }
1460 // %list = type { %list * } ; repeated type decl
1462 // If types are not resolved eagerly, then the two types will not be
1463 // determined to be the same type!
1465 ResolveTypeTo($2, *$4);
1467 if (!setTypeName(*$4, $2) && !$2) {
1468 // If this is a named type that is not a redefinition, add it to the slot
1470 if (inFunctionScope())
1471 CurFun.Types.push_back(*$4);
1473 CurModule.Types.push_back(*$4);
1478 | ConstPool FunctionProto { // Function prototypes can be in const pool
1480 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
1481 if ($5 == 0) ThrowException("Global value initializer is not a constant!");
1482 ParseGlobalVariable($2, $3, $4, $5->getType(), $5);
1484 | ConstPool OptAssign EXTERNAL GlobalType Types {
1485 ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, *$5, 0);
1488 | ConstPool TARGET TargetDefinition {
1490 | /* empty: end of list */ {
1495 BigOrLittle : BIG { $$ = Module::BigEndian; };
1496 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1498 TargetDefinition : ENDIAN '=' BigOrLittle {
1499 CurModule.CurrentModule->setEndianness($3);
1501 | POINTERSIZE '=' EUINT64VAL {
1503 CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1505 CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1507 ThrowException("Invalid pointer size: '" + utostr($3) + "'!");
1511 //===----------------------------------------------------------------------===//
1512 // Rules to match Function Headers
1513 //===----------------------------------------------------------------------===//
1515 Name : VAR_ID | STRINGCONSTANT;
1516 OptName : Name | /*empty*/ { $$ = 0; };
1518 ArgVal : Types OptName {
1519 if (*$1 == Type::VoidTy)
1520 ThrowException("void typed arguments are invalid!");
1521 $$ = new std::pair<PATypeHolder*, char*>($1, $2);
1524 ArgListH : ArgListH ',' ArgVal {
1530 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1535 ArgList : ArgListH {
1538 | ArgListH ',' DOTDOTDOT {
1540 $$->push_back(std::pair<PATypeHolder*,
1541 char*>(new PATypeHolder(Type::VoidTy), 0));
1544 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1545 $$->push_back(std::make_pair(new PATypeHolder(Type::VoidTy), (char*)0));
1551 FunctionHeaderH : TypesV Name '(' ArgList ')' {
1553 std::string FunctionName($2);
1555 if (!(*$1)->isFirstClassType() && *$1 != Type::VoidTy)
1556 ThrowException("LLVM functions cannot return aggregate types!");
1558 std::vector<const Type*> ParamTypeList;
1559 if ($4) { // If there are arguments...
1560 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $4->begin();
1561 I != $4->end(); ++I)
1562 ParamTypeList.push_back(I->first->get());
1565 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1566 if (isVarArg) ParamTypeList.pop_back();
1568 const FunctionType *FT = FunctionType::get(*$1, ParamTypeList, isVarArg);
1569 const PointerType *PFT = PointerType::get(FT);
1573 // Is the function already in symtab?
1574 if ((Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
1575 // Yes it is. If this is the case, either we need to be a forward decl,
1576 // or it needs to be.
1577 if (!CurFun.isDeclare && !Fn->isExternal())
1578 ThrowException("Redefinition of function '" + FunctionName + "'!");
1580 // Make sure to strip off any argument names so we can't get conflicts...
1581 for (Function::aiterator AI = Fn->abegin(), AE = Fn->aend(); AI != AE; ++AI)
1584 } else { // Not already defined?
1585 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
1586 CurModule.CurrentModule);
1587 InsertValue(Fn, CurModule.Values);
1588 CurModule.DeclareNewGlobalValue(Fn, ValID::create($2));
1590 free($2); // Free strdup'd memory!
1592 CurFun.FunctionStart(Fn);
1594 // Add all of the arguments we parsed to the function...
1595 if ($4) { // Is null if empty...
1596 if (isVarArg) { // Nuke the last entry
1597 assert($4->back().first->get() == Type::VoidTy && $4->back().second == 0&&
1598 "Not a varargs marker!");
1599 delete $4->back().first;
1600 $4->pop_back(); // Delete the last entry
1602 Function::aiterator ArgIt = Fn->abegin();
1603 for (std::vector<std::pair<PATypeHolder*, char*> >::iterator I =$4->begin();
1604 I != $4->end(); ++I, ++ArgIt) {
1605 delete I->first; // Delete the typeholder...
1607 setValueName(ArgIt, I->second); // Insert arg into symtab...
1611 delete $4; // We're now done with the argument list
1615 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
1617 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
1618 $$ = CurFun.CurrentFunction;
1620 // Make sure that we keep track of the linkage type even if there was a
1621 // previous "declare".
1624 // Resolve circular types before we parse the body of the function.
1625 ResolveTypes(CurFun.LateResolveTypes);
1628 END : ENDTOK | '}'; // Allow end of '}' to end a function
1630 Function : BasicBlockList END {
1634 FunctionProto : DECLARE { CurFun.isDeclare = true; } FunctionHeaderH {
1635 $$ = CurFun.CurrentFunction;
1636 CurFun.FunctionDone();
1639 //===----------------------------------------------------------------------===//
1640 // Rules to match Basic Blocks
1641 //===----------------------------------------------------------------------===//
1643 ConstValueRef : ESINT64VAL { // A reference to a direct constant
1644 $$ = ValID::create($1);
1647 $$ = ValID::create($1);
1649 | FPVAL { // Perhaps it's an FP constant?
1650 $$ = ValID::create($1);
1653 $$ = ValID::create(ConstantBool::True);
1656 $$ = ValID::create(ConstantBool::False);
1659 $$ = ValID::createNull();
1662 $$ = ValID::create($1);
1665 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1668 SymbolicValueRef : INTVAL { // Is it an integer reference...?
1669 $$ = ValID::create($1);
1671 | Name { // Is it a named reference...?
1672 $$ = ValID::create($1);
1675 // ValueRef - A reference to a definition... either constant or symbolic
1676 ValueRef : SymbolicValueRef | ConstValueRef;
1679 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
1680 // type immediately preceeds the value reference, and allows complex constant
1681 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1682 ResolvedVal : Types ValueRef {
1683 $$ = getVal(*$1, $2); delete $1;
1686 BasicBlockList : BasicBlockList BasicBlock {
1689 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
1694 // Basic blocks are terminated by branching instructions:
1695 // br, br/cc, switch, ret
1697 BasicBlock : InstructionList OptAssign BBTerminatorInst {
1698 setValueName($3, $2);
1701 $1->getInstList().push_back($3);
1706 InstructionList : InstructionList Inst {
1707 $1->getInstList().push_back($2);
1711 $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
1714 $$ = CurBB = getBBVal(ValID::create($1), true);
1717 BBTerminatorInst : RET ResolvedVal { // Return with a result...
1718 $$ = new ReturnInst($2);
1720 | RET VOID { // Return with no result...
1721 $$ = new ReturnInst();
1723 | BR LABEL ValueRef { // Unconditional Branch...
1724 $$ = new BranchInst(getBBVal($3));
1725 } // Conditional Branch...
1726 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
1727 $$ = new BranchInst(getBBVal($6), getBBVal($9), getVal(Type::BoolTy, $3));
1729 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1730 SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6));
1733 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
1736 S->addCase(I->first, I->second);
1739 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
1740 SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6));
1743 | INVOKE TypesV ValueRef '(' ValueRefListE ')' TO LABEL ValueRef
1744 UNWIND LABEL ValueRef {
1745 const PointerType *PFTy;
1746 const FunctionType *Ty;
1748 if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
1749 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1750 // Pull out the types of all of the arguments...
1751 std::vector<const Type*> ParamTypes;
1753 for (std::vector<Value*>::iterator I = $5->begin(), E = $5->end();
1755 ParamTypes.push_back((*I)->getType());
1758 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1759 if (isVarArg) ParamTypes.pop_back();
1761 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1762 PFTy = PointerType::get(Ty);
1765 Value *V = getVal(PFTy, $3); // Get the function we're calling...
1767 BasicBlock *Normal = getBBVal($9);
1768 BasicBlock *Except = getBBVal($12);
1770 // Create the call node...
1771 if (!$5) { // Has no arguments?
1772 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
1773 } else { // Has arguments?
1774 // Loop through FunctionType's arguments and ensure they are specified
1777 FunctionType::param_iterator I = Ty->param_begin();
1778 FunctionType::param_iterator E = Ty->param_end();
1779 std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1781 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1782 if ((*ArgI)->getType() != *I)
1783 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1784 (*I)->getDescription() + "'!");
1786 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1787 ThrowException("Invalid number of parameters detected!");
1789 $$ = new InvokeInst(V, Normal, Except, *$5);
1795 $$ = new UnwindInst();
1800 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1802 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
1804 ThrowException("May only switch on a constant pool value!");
1806 $$->push_back(std::make_pair(V, getBBVal($6)));
1808 | IntType ConstValueRef ',' LABEL ValueRef {
1809 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
1810 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
1813 ThrowException("May only switch on a constant pool value!");
1815 $$->push_back(std::make_pair(V, getBBVal($5)));
1818 Inst : OptAssign InstVal {
1819 // Is this definition named?? if so, assign the name...
1820 setValueName($2, $1);
1825 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
1826 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
1827 $$->push_back(std::make_pair(getVal(*$1, $3), getBBVal($5)));
1830 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1832 $1->push_back(std::make_pair(getVal($1->front().first->getType(), $4),
1837 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
1838 $$ = new std::vector<Value*>();
1841 | ValueRefList ',' ResolvedVal {
1846 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1847 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
1849 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
1850 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint())
1851 ThrowException("Arithmetic operator requires integer or FP operands!");
1852 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1854 ThrowException("binary operator returned null!");
1857 | LogicalOps Types ValueRef ',' ValueRef {
1858 if (!(*$2)->isIntegral())
1859 ThrowException("Logical operator requires integral operands!");
1860 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1862 ThrowException("binary operator returned null!");
1865 | SetCondOps Types ValueRef ',' ValueRef {
1866 $$ = new SetCondInst($1, getVal(*$2, $3), getVal(*$2, $5));
1868 ThrowException("binary operator returned null!");
1872 std::cerr << "WARNING: Use of eliminated 'not' instruction:"
1873 << " Replacing with 'xor'.\n";
1875 Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
1877 ThrowException("Expected integral type for not instruction!");
1879 $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
1881 ThrowException("Could not create a xor instruction!");
1883 | ShiftOps ResolvedVal ',' ResolvedVal {
1884 if ($4->getType() != Type::UByteTy)
1885 ThrowException("Shift amount must be ubyte!");
1886 if (!$2->getType()->isInteger())
1887 ThrowException("Shift constant expression requires integer operand!");
1888 $$ = new ShiftInst($1, $2, $4);
1890 | CAST ResolvedVal TO Types {
1891 if (!$4->get()->isFirstClassType())
1892 ThrowException("cast instruction to a non-primitive type: '" +
1893 $4->get()->getDescription() + "'!");
1894 $$ = new CastInst($2, *$4);
1897 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
1898 if ($2->getType() != Type::BoolTy)
1899 ThrowException("select condition must be boolean!");
1900 if ($4->getType() != $6->getType())
1901 ThrowException("select value types should match!");
1902 $$ = new SelectInst($2, $4, $6);
1904 | VA_ARG ResolvedVal ',' Types {
1905 // FIXME: This is emulation code for an obsolete syntax. This should be
1906 // removed at some point.
1907 if (!ObsoleteVarArgs) {
1908 std::cerr << "WARNING: this file uses obsolete features. "
1909 << "Assemble and disassemble to update it.\n";
1910 ObsoleteVarArgs = true;
1913 // First, load the valist...
1914 Instruction *CurVAList = new LoadInst($2, "");
1915 CurBB->getInstList().push_back(CurVAList);
1917 // Emit the vaarg instruction.
1918 $$ = new VAArgInst(CurVAList, *$4);
1920 // Now we must advance the pointer and update it in memory.
1921 Instruction *TheVANext = new VANextInst(CurVAList, *$4);
1922 CurBB->getInstList().push_back(TheVANext);
1924 CurBB->getInstList().push_back(new StoreInst(TheVANext, $2));
1927 | VAARG ResolvedVal ',' Types {
1928 $$ = new VAArgInst($2, *$4);
1931 | VANEXT ResolvedVal ',' Types {
1932 $$ = new VANextInst($2, *$4);
1936 const Type *Ty = $2->front().first->getType();
1937 if (!Ty->isFirstClassType())
1938 ThrowException("PHI node operands must be of first class type!");
1939 $$ = new PHINode(Ty);
1940 $$->op_reserve($2->size()*2);
1941 while ($2->begin() != $2->end()) {
1942 if ($2->front().first->getType() != Ty)
1943 ThrowException("All elements of a PHI node must be of the same type!");
1944 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
1947 delete $2; // Free the list...
1949 | CALL TypesV ValueRef '(' ValueRefListE ')' {
1950 const PointerType *PFTy;
1951 const FunctionType *Ty;
1953 if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
1954 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1955 // Pull out the types of all of the arguments...
1956 std::vector<const Type*> ParamTypes;
1958 for (std::vector<Value*>::iterator I = $5->begin(), E = $5->end();
1960 ParamTypes.push_back((*I)->getType());
1963 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1964 if (isVarArg) ParamTypes.pop_back();
1966 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1967 PFTy = PointerType::get(Ty);
1970 Value *V = getVal(PFTy, $3); // Get the function we're calling...
1972 // Create the call node...
1973 if (!$5) { // Has no arguments?
1974 // Make sure no arguments is a good thing!
1975 if (Ty->getNumParams() != 0)
1976 ThrowException("No arguments passed to a function that "
1977 "expects arguments!");
1979 $$ = new CallInst(V, std::vector<Value*>());
1980 } else { // Has arguments?
1981 // Loop through FunctionType's arguments and ensure they are specified
1984 FunctionType::param_iterator I = Ty->param_begin();
1985 FunctionType::param_iterator E = Ty->param_end();
1986 std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1988 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1989 if ((*ArgI)->getType() != *I)
1990 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1991 (*I)->getDescription() + "'!");
1993 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1994 ThrowException("Invalid number of parameters detected!");
1996 $$ = new CallInst(V, *$5);
2006 // IndexList - List of indices for GEP based instructions...
2007 IndexList : ',' ValueRefList {
2010 $$ = new std::vector<Value*>();
2013 OptVolatile : VOLATILE {
2021 MemoryInst : MALLOC Types {
2022 $$ = new MallocInst(*$2);
2025 | MALLOC Types ',' UINT ValueRef {
2026 $$ = new MallocInst(*$2, getVal($4, $5));
2030 $$ = new AllocaInst(*$2);
2033 | ALLOCA Types ',' UINT ValueRef {
2034 $$ = new AllocaInst(*$2, getVal($4, $5));
2037 | FREE ResolvedVal {
2038 if (!isa<PointerType>($2->getType()))
2039 ThrowException("Trying to free nonpointer type " +
2040 $2->getType()->getDescription() + "!");
2041 $$ = new FreeInst($2);
2044 | OptVolatile LOAD Types ValueRef {
2045 if (!isa<PointerType>($3->get()))
2046 ThrowException("Can't load from nonpointer type: " +
2047 (*$3)->getDescription());
2048 $$ = new LoadInst(getVal(*$3, $4), "", $1);
2051 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2052 const PointerType *PT = dyn_cast<PointerType>($5->get());
2054 ThrowException("Can't store to a nonpointer type: " +
2055 (*$5)->getDescription());
2056 const Type *ElTy = PT->getElementType();
2057 if (ElTy != $3->getType())
2058 ThrowException("Can't store '" + $3->getType()->getDescription() +
2059 "' into space of type '" + ElTy->getDescription() + "'!");
2061 $$ = new StoreInst($3, getVal(*$5, $6), $1);
2064 | GETELEMENTPTR Types ValueRef IndexList {
2065 if (!isa<PointerType>($2->get()))
2066 ThrowException("getelementptr insn requires pointer operand!");
2068 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
2069 // indices to uint struct indices for compatibility.
2070 generic_gep_type_iterator<std::vector<Value*>::iterator>
2071 GTI = gep_type_begin($2->get(), $4->begin(), $4->end()),
2072 GTE = gep_type_end($2->get(), $4->begin(), $4->end());
2073 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
2074 if (isa<StructType>(*GTI)) // Only change struct indices
2075 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
2076 if (CUI->getType() == Type::UByteTy)
2077 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
2079 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2080 ThrowException("Invalid getelementptr indices for type '" +
2081 (*$2)->getDescription()+ "'!");
2082 $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
2083 delete $2; delete $4;
2088 int yyerror(const char *ErrorMsg) {
2090 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2091 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2092 std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2093 if (yychar == YYEMPTY || yychar == 0)
2094 errMsg += "end-of-file.";
2096 errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2097 ThrowException(errMsg);