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/CallingConv.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Module.h"
19 #include "llvm/SymbolTable.h"
20 #include "llvm/Support/GetElementPtrTypeIterator.h"
21 #include "llvm/ADT/STLExtras.h"
27 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
28 int yylex(); // declaration" of xxx warnings.
32 std::string CurFilename;
36 static Module *ParserResult;
38 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
39 // relating to upreferences in the input stream.
41 //#define DEBUG_UPREFS 1
43 #define UR_OUT(X) std::cerr << X
48 #define YYERROR_VERBOSE 1
50 // This contains info used when building the body of a function. It is
51 // destroyed when the function is completed.
53 typedef std::vector<Value *> ValueList; // Numbered defs
55 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
56 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
58 static struct PerModuleInfo {
59 Module *CurrentModule;
60 std::map<const Type *, ValueList> Values; // Module level numbered definitions
61 std::map<const Type *,ValueList> LateResolveValues;
62 std::vector<PATypeHolder> Types;
63 std::map<ValID, PATypeHolder> LateResolveTypes;
65 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
66 /// how they were referenced and one which line of the input they came from so
67 /// that we can resolve them later and print error messages as appropriate.
68 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
70 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
71 // references to global values. Global values may be referenced before they
72 // are defined, and if so, the temporary object that they represent is held
73 // here. This is used for forward references of GlobalValues.
75 typedef std::map<std::pair<const PointerType *,
76 ValID>, GlobalValue*> GlobalRefsType;
77 GlobalRefsType GlobalRefs;
80 // If we could not resolve some functions at function compilation time
81 // (calls to functions before they are defined), resolve them now... Types
82 // are resolved when the constant pool has been completely parsed.
84 ResolveDefinitions(LateResolveValues);
86 // Check to make sure that all global value forward references have been
89 if (!GlobalRefs.empty()) {
90 std::string UndefinedReferences = "Unresolved global references exist:\n";
92 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
94 UndefinedReferences += " " + I->first.first->getDescription() + " " +
95 I->first.second.getName() + "\n";
97 ThrowException(UndefinedReferences);
100 Values.clear(); // Clear out function local definitions
106 // GetForwardRefForGlobal - Check to see if there is a forward reference
107 // for this global. If so, remove it from the GlobalRefs map and return it.
108 // If not, just return null.
109 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
110 // Check to see if there is a forward reference to this global variable...
111 // if there is, eliminate it and patch the reference to use the new def'n.
112 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
113 GlobalValue *Ret = 0;
114 if (I != GlobalRefs.end()) {
122 static struct PerFunctionInfo {
123 Function *CurrentFunction; // Pointer to current function being created
125 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
126 std::map<const Type*, ValueList> LateResolveValues;
127 bool isDeclare; // Is this function a forward declararation?
129 /// BBForwardRefs - When we see forward references to basic blocks, keep
130 /// track of them here.
131 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
132 std::vector<BasicBlock*> NumberedBlocks;
135 inline PerFunctionInfo() {
140 inline void FunctionStart(Function *M) {
145 void FunctionDone() {
146 NumberedBlocks.clear();
148 // Any forward referenced blocks left?
149 if (!BBForwardRefs.empty())
150 ThrowException("Undefined reference to label " +
151 BBForwardRefs.begin()->first->getName());
153 // Resolve all forward references now.
154 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
156 Values.clear(); // Clear out function local definitions
160 } CurFun; // Info for the current function...
162 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
165 //===----------------------------------------------------------------------===//
166 // Code to handle definitions of all the types
167 //===----------------------------------------------------------------------===//
169 static int InsertValue(Value *V,
170 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
171 if (V->hasName()) return -1; // Is this a numbered definition?
173 // Yes, insert the value into the value table...
174 ValueList &List = ValueTab[V->getType()];
176 return List.size()-1;
179 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
181 case ValID::NumberVal: // Is it a numbered definition?
182 // Module constants occupy the lowest numbered slots...
183 if ((unsigned)D.Num < CurModule.Types.size())
184 return CurModule.Types[(unsigned)D.Num];
186 case ValID::NameVal: // Is it a named definition?
187 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
188 D.destroy(); // Free old strdup'd memory...
193 ThrowException("Internal parser error: Invalid symbol type reference!");
196 // If we reached here, we referenced either a symbol that we don't know about
197 // or an id number that hasn't been read yet. We may be referencing something
198 // forward, so just create an entry to be resolved later and get to it...
200 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
203 if (inFunctionScope()) {
204 if (D.Type == ValID::NameVal)
205 ThrowException("Reference to an undefined type: '" + D.getName() + "'");
207 ThrowException("Reference to an undefined type: #" + itostr(D.Num));
210 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
211 if (I != CurModule.LateResolveTypes.end())
214 Type *Typ = OpaqueType::get();
215 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
219 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
220 SymbolTable &SymTab =
221 inFunctionScope() ? CurFun.CurrentFunction->getSymbolTable() :
222 CurModule.CurrentModule->getSymbolTable();
223 return SymTab.lookup(Ty, Name);
226 // getValNonImprovising - Look up the value specified by the provided type and
227 // the provided ValID. If the value exists and has already been defined, return
228 // it. Otherwise return null.
230 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
231 if (isa<FunctionType>(Ty))
232 ThrowException("Functions are not values and "
233 "must be referenced as pointers");
236 case ValID::NumberVal: { // Is it a numbered definition?
237 unsigned Num = (unsigned)D.Num;
239 // Module constants occupy the lowest numbered slots...
240 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
241 if (VI != CurModule.Values.end()) {
242 if (Num < VI->second.size())
243 return VI->second[Num];
244 Num -= VI->second.size();
247 // Make sure that our type is within bounds
248 VI = CurFun.Values.find(Ty);
249 if (VI == CurFun.Values.end()) return 0;
251 // Check that the number is within bounds...
252 if (VI->second.size() <= Num) return 0;
254 return VI->second[Num];
257 case ValID::NameVal: { // Is it a named definition?
258 Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
259 if (N == 0) return 0;
261 D.destroy(); // Free old strdup'd memory...
265 // Check to make sure that "Ty" is an integral type, and that our
266 // value will fit into the specified type...
267 case ValID::ConstSIntVal: // Is it a constant pool reference??
268 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64))
269 ThrowException("Signed integral constant '" +
270 itostr(D.ConstPool64) + "' is invalid for type '" +
271 Ty->getDescription() + "'!");
272 return ConstantSInt::get(Ty, D.ConstPool64);
274 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
275 if (!ConstantUInt::isValueValidForType(Ty, D.UConstPool64)) {
276 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64)) {
277 ThrowException("Integral constant '" + utostr(D.UConstPool64) +
278 "' is invalid or out of range!");
279 } else { // This is really a signed reference. Transmogrify.
280 return ConstantSInt::get(Ty, D.ConstPool64);
283 return ConstantUInt::get(Ty, D.UConstPool64);
286 case ValID::ConstFPVal: // Is it a floating point const pool reference?
287 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
288 ThrowException("FP constant invalid for type!!");
289 return ConstantFP::get(Ty, D.ConstPoolFP);
291 case ValID::ConstNullVal: // Is it a null value?
292 if (!isa<PointerType>(Ty))
293 ThrowException("Cannot create a a non pointer null!");
294 return ConstantPointerNull::get(cast<PointerType>(Ty));
296 case ValID::ConstUndefVal: // Is it an undef value?
297 return UndefValue::get(Ty);
299 case ValID::ConstantVal: // Fully resolved constant?
300 if (D.ConstantValue->getType() != Ty)
301 ThrowException("Constant expression type different from required type!");
302 return D.ConstantValue;
305 assert(0 && "Unhandled case!");
309 assert(0 && "Unhandled case!");
313 // getVal - This function is identical to getValNonImprovising, except that if a
314 // value is not already defined, it "improvises" by creating a placeholder var
315 // that looks and acts just like the requested variable. When the value is
316 // defined later, all uses of the placeholder variable are replaced with the
319 static Value *getVal(const Type *Ty, const ValID &ID) {
320 if (Ty == Type::LabelTy)
321 ThrowException("Cannot use a basic block here");
323 // See if the value has already been defined.
324 Value *V = getValNonImprovising(Ty, ID);
327 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty))
328 ThrowException("Invalid use of a composite type!");
330 // If we reached here, we referenced either a symbol that we don't know about
331 // or an id number that hasn't been read yet. We may be referencing something
332 // forward, so just create an entry to be resolved later and get to it...
334 V = new Argument(Ty);
336 // Remember where this forward reference came from. FIXME, shouldn't we try
337 // to recycle these things??
338 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
341 if (inFunctionScope())
342 InsertValue(V, CurFun.LateResolveValues);
344 InsertValue(V, CurModule.LateResolveValues);
348 /// getBBVal - This is used for two purposes:
349 /// * If isDefinition is true, a new basic block with the specified ID is being
351 /// * If isDefinition is true, this is a reference to a basic block, which may
352 /// or may not be a forward reference.
354 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
355 assert(inFunctionScope() && "Can't get basic block at global scope!");
360 default: ThrowException("Illegal label reference " + ID.getName());
361 case ValID::NumberVal: // Is it a numbered definition?
362 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
363 CurFun.NumberedBlocks.resize(ID.Num+1);
364 BB = CurFun.NumberedBlocks[ID.Num];
366 case ValID::NameVal: // Is it a named definition?
368 if (Value *N = CurFun.CurrentFunction->
369 getSymbolTable().lookup(Type::LabelTy, Name))
370 BB = cast<BasicBlock>(N);
374 // See if the block has already been defined.
376 // If this is the definition of the block, make sure the existing value was
377 // just a forward reference. If it was a forward reference, there will be
378 // an entry for it in the PlaceHolderInfo map.
379 if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
380 // The existing value was a definition, not a forward reference.
381 ThrowException("Redefinition of label " + ID.getName());
383 ID.destroy(); // Free strdup'd memory.
387 // Otherwise this block has not been seen before.
388 BB = new BasicBlock("", CurFun.CurrentFunction);
389 if (ID.Type == ValID::NameVal) {
390 BB->setName(ID.Name);
392 CurFun.NumberedBlocks[ID.Num] = BB;
395 // If this is not a definition, keep track of it so we can use it as a forward
398 // Remember where this forward reference came from.
399 CurFun.BBForwardRefs[BB] = std::make_pair(ID, llvmAsmlineno);
401 // The forward declaration could have been inserted anywhere in the
402 // function: insert it into the correct place now.
403 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
404 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
411 //===----------------------------------------------------------------------===//
412 // Code to handle forward references in instructions
413 //===----------------------------------------------------------------------===//
415 // This code handles the late binding needed with statements that reference
416 // values not defined yet... for example, a forward branch, or the PHI node for
419 // This keeps a table (CurFun.LateResolveValues) of all such forward references
420 // and back patchs after we are done.
423 // ResolveDefinitions - If we could not resolve some defs at parsing
424 // time (forward branches, phi functions for loops, etc...) resolve the
428 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
429 std::map<const Type*,ValueList> *FutureLateResolvers) {
430 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
431 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
432 E = LateResolvers.end(); LRI != E; ++LRI) {
433 ValueList &List = LRI->second;
434 while (!List.empty()) {
435 Value *V = List.back();
438 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
439 CurModule.PlaceHolderInfo.find(V);
440 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
442 ValID &DID = PHI->second.first;
444 Value *TheRealValue = getValNonImprovising(LRI->first, DID);
446 V->replaceAllUsesWith(TheRealValue);
448 CurModule.PlaceHolderInfo.erase(PHI);
449 } else if (FutureLateResolvers) {
450 // Functions have their unresolved items forwarded to the module late
452 InsertValue(V, *FutureLateResolvers);
454 if (DID.Type == ValID::NameVal)
455 ThrowException("Reference to an invalid definition: '" +DID.getName()+
456 "' of type '" + V->getType()->getDescription() + "'",
459 ThrowException("Reference to an invalid definition: #" +
460 itostr(DID.Num) + " of type '" +
461 V->getType()->getDescription() + "'",
467 LateResolvers.clear();
470 // ResolveTypeTo - A brand new type was just declared. This means that (if
471 // name is not null) things referencing Name can be resolved. Otherwise, things
472 // refering to the number can be resolved. Do this now.
474 static void ResolveTypeTo(char *Name, const Type *ToTy) {
476 if (Name) D = ValID::create(Name);
477 else D = ValID::create((int)CurModule.Types.size());
479 std::map<ValID, PATypeHolder>::iterator I =
480 CurModule.LateResolveTypes.find(D);
481 if (I != CurModule.LateResolveTypes.end()) {
482 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
483 CurModule.LateResolveTypes.erase(I);
487 // setValueName - Set the specified value to the name given. The name may be
488 // null potentially, in which case this is a noop. The string passed in is
489 // assumed to be a malloc'd string buffer, and is free'd by this function.
491 static void setValueName(Value *V, char *NameStr) {
493 std::string Name(NameStr); // Copy string
494 free(NameStr); // Free old string
496 if (V->getType() == Type::VoidTy)
497 ThrowException("Can't assign name '" + Name+"' to value with void type!");
499 assert(inFunctionScope() && "Must be in function scope!");
500 SymbolTable &ST = CurFun.CurrentFunction->getSymbolTable();
501 if (ST.lookup(V->getType(), Name))
502 ThrowException("Redefinition of value named '" + Name + "' in the '" +
503 V->getType()->getDescription() + "' type plane!");
510 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
511 /// this is a declaration, otherwise it is a definition.
512 static void ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
513 bool isConstantGlobal, const Type *Ty,
514 Constant *Initializer) {
515 if (isa<FunctionType>(Ty))
516 ThrowException("Cannot declare global vars of function type!");
518 const PointerType *PTy = PointerType::get(Ty);
522 Name = NameStr; // Copy string
523 free(NameStr); // Free old string
526 // See if this global value was forward referenced. If so, recycle the
530 ID = ValID::create((char*)Name.c_str());
532 ID = ValID::create((int)CurModule.Values[PTy].size());
535 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
536 // Move the global to the end of the list, from whereever it was
537 // previously inserted.
538 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
539 CurModule.CurrentModule->getGlobalList().remove(GV);
540 CurModule.CurrentModule->getGlobalList().push_back(GV);
541 GV->setInitializer(Initializer);
542 GV->setLinkage(Linkage);
543 GV->setConstant(isConstantGlobal);
544 InsertValue(GV, CurModule.Values);
548 // If this global has a name, check to see if there is already a definition
549 // of this global in the module. If so, merge as appropriate. Note that
550 // this is really just a hack around problems in the CFE. :(
552 // We are a simple redefinition of a value, check to see if it is defined
553 // the same as the old one.
554 if (GlobalVariable *EGV =
555 CurModule.CurrentModule->getGlobalVariable(Name, Ty)) {
556 // We are allowed to redefine a global variable in two circumstances:
557 // 1. If at least one of the globals is uninitialized or
558 // 2. If both initializers have the same value.
560 if (!EGV->hasInitializer() || !Initializer ||
561 EGV->getInitializer() == Initializer) {
563 // Make sure the existing global version gets the initializer! Make
564 // sure that it also gets marked const if the new version is.
565 if (Initializer && !EGV->hasInitializer())
566 EGV->setInitializer(Initializer);
567 if (isConstantGlobal)
568 EGV->setConstant(true);
569 EGV->setLinkage(Linkage);
573 ThrowException("Redefinition of global variable named '" + Name +
574 "' in the '" + Ty->getDescription() + "' type plane!");
578 // Otherwise there is no existing GV to use, create one now.
580 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
581 CurModule.CurrentModule);
582 InsertValue(GV, CurModule.Values);
585 // setTypeName - Set the specified type to the name given. The name may be
586 // null potentially, in which case this is a noop. The string passed in is
587 // assumed to be a malloc'd string buffer, and is freed by this function.
589 // This function returns true if the type has already been defined, but is
590 // allowed to be redefined in the specified context. If the name is a new name
591 // for the type plane, it is inserted and false is returned.
592 static bool setTypeName(const Type *T, char *NameStr) {
593 assert(!inFunctionScope() && "Can't give types function-local names!");
594 if (NameStr == 0) return false;
596 std::string Name(NameStr); // Copy string
597 free(NameStr); // Free old string
599 // We don't allow assigning names to void type
600 if (T == Type::VoidTy)
601 ThrowException("Can't assign name '" + Name + "' to the void type!");
603 // Set the type name, checking for conflicts as we do so.
604 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
606 if (AlreadyExists) { // Inserting a name that is already defined???
607 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
608 assert(Existing && "Conflict but no matching type?");
610 // There is only one case where this is allowed: when we are refining an
611 // opaque type. In this case, Existing will be an opaque type.
612 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
613 // We ARE replacing an opaque type!
614 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
618 // Otherwise, this is an attempt to redefine a type. That's okay if
619 // the redefinition is identical to the original. This will be so if
620 // Existing and T point to the same Type object. In this one case we
621 // allow the equivalent redefinition.
622 if (Existing == T) return true; // Yes, it's equal.
624 // Any other kind of (non-equivalent) redefinition is an error.
625 ThrowException("Redefinition of type named '" + Name + "' in the '" +
626 T->getDescription() + "' type plane!");
632 //===----------------------------------------------------------------------===//
633 // Code for handling upreferences in type names...
636 // TypeContains - Returns true if Ty directly contains E in it.
638 static bool TypeContains(const Type *Ty, const Type *E) {
639 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
640 E) != Ty->subtype_end();
645 // NestingLevel - The number of nesting levels that need to be popped before
646 // this type is resolved.
647 unsigned NestingLevel;
649 // LastContainedTy - This is the type at the current binding level for the
650 // type. Every time we reduce the nesting level, this gets updated.
651 const Type *LastContainedTy;
653 // UpRefTy - This is the actual opaque type that the upreference is
657 UpRefRecord(unsigned NL, OpaqueType *URTy)
658 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
662 // UpRefs - A list of the outstanding upreferences that need to be resolved.
663 static std::vector<UpRefRecord> UpRefs;
665 /// HandleUpRefs - Every time we finish a new layer of types, this function is
666 /// called. It loops through the UpRefs vector, which is a list of the
667 /// currently active types. For each type, if the up reference is contained in
668 /// the newly completed type, we decrement the level count. When the level
669 /// count reaches zero, the upreferenced type is the type that is passed in:
670 /// thus we can complete the cycle.
672 static PATypeHolder HandleUpRefs(const Type *ty) {
673 if (!ty->isAbstract()) return ty;
675 UR_OUT("Type '" << Ty->getDescription() <<
676 "' newly formed. Resolving upreferences.\n" <<
677 UpRefs.size() << " upreferences active!\n");
679 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
680 // to zero), we resolve them all together before we resolve them to Ty. At
681 // the end of the loop, if there is anything to resolve to Ty, it will be in
683 OpaqueType *TypeToResolve = 0;
685 for (unsigned i = 0; i != UpRefs.size(); ++i) {
686 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
687 << UpRefs[i].second->getDescription() << ") = "
688 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
689 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
690 // Decrement level of upreference
691 unsigned Level = --UpRefs[i].NestingLevel;
692 UpRefs[i].LastContainedTy = Ty;
693 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
694 if (Level == 0) { // Upreference should be resolved!
695 if (!TypeToResolve) {
696 TypeToResolve = UpRefs[i].UpRefTy;
698 UR_OUT(" * Resolving upreference for "
699 << UpRefs[i].second->getDescription() << "\n";
700 std::string OldName = UpRefs[i].UpRefTy->getDescription());
701 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
702 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
703 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
705 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
706 --i; // Do not skip the next element...
712 UR_OUT(" * Resolving upreference for "
713 << UpRefs[i].second->getDescription() << "\n";
714 std::string OldName = TypeToResolve->getDescription());
715 TypeToResolve->refineAbstractTypeTo(Ty);
722 //===----------------------------------------------------------------------===//
723 // RunVMAsmParser - Define an interface to this parser
724 //===----------------------------------------------------------------------===//
726 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
728 CurFilename = Filename;
729 llvmAsmlineno = 1; // Reset the current line number...
731 // Allocate a new module to read
732 CurModule.CurrentModule = new Module(Filename);
734 yyparse(); // Parse the file, potentially throwing exception
736 Module *Result = ParserResult;
738 llvmAsmin = stdin; // F is about to go away, don't use it anymore...
747 llvm::Module *ModuleVal;
748 llvm::Function *FunctionVal;
749 std::pair<llvm::PATypeHolder*, char*> *ArgVal;
750 llvm::BasicBlock *BasicBlockVal;
751 llvm::TerminatorInst *TermInstVal;
752 llvm::Instruction *InstVal;
753 llvm::Constant *ConstVal;
755 const llvm::Type *PrimType;
756 llvm::PATypeHolder *TypeVal;
757 llvm::Value *ValueVal;
759 std::vector<std::pair<llvm::PATypeHolder*,char*> > *ArgList;
760 std::vector<llvm::Value*> *ValueList;
761 std::list<llvm::PATypeHolder> *TypeList;
762 // Represent the RHS of PHI node
763 std::list<std::pair<llvm::Value*,
764 llvm::BasicBlock*> > *PHIList;
765 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
766 std::vector<llvm::Constant*> *ConstVector;
768 llvm::GlobalValue::LinkageTypes Linkage;
776 char *StrVal; // This memory is strdup'd!
777 llvm::ValID ValIDVal; // strdup'd memory maybe!
779 llvm::Instruction::BinaryOps BinaryOpVal;
780 llvm::Instruction::TermOps TermOpVal;
781 llvm::Instruction::MemoryOps MemOpVal;
782 llvm::Instruction::OtherOps OtherOpVal;
783 llvm::Module::Endianness Endianness;
786 %type <ModuleVal> Module FunctionList
787 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
788 %type <BasicBlockVal> BasicBlock InstructionList
789 %type <TermInstVal> BBTerminatorInst
790 %type <InstVal> Inst InstVal MemoryInst
791 %type <ConstVal> ConstVal ConstExpr
792 %type <ConstVector> ConstVector
793 %type <ArgList> ArgList ArgListH
794 %type <ArgVal> ArgVal
795 %type <PHIList> PHIList
796 %type <ValueList> ValueRefList ValueRefListE // For call param lists
797 %type <ValueList> IndexList // For GEP derived indices
798 %type <TypeList> TypeListI ArgTypeListI
799 %type <JumpTable> JumpTable
800 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
801 %type <BoolVal> OptVolatile // 'volatile' or not
802 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
803 %type <Linkage> OptLinkage
804 %type <Endianness> BigOrLittle
806 // ValueRef - Unresolved reference to a definition or BB
807 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
808 %type <ValueVal> ResolvedVal // <type> <valref> pair
809 // Tokens and types for handling constant integer values
811 // ESINT64VAL - A negative number within long long range
812 %token <SInt64Val> ESINT64VAL
814 // EUINT64VAL - A positive number within uns. long long range
815 %token <UInt64Val> EUINT64VAL
816 %type <SInt64Val> EINT64VAL
818 %token <SIntVal> SINTVAL // Signed 32 bit ints...
819 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
820 %type <SIntVal> INTVAL
821 %token <FPVal> FPVAL // Float or Double constant
824 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
825 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
826 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
827 %token <PrimType> FLOAT DOUBLE TYPE LABEL
829 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
830 %type <StrVal> Name OptName OptAssign
833 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
834 %token DECLARE GLOBAL CONSTANT VOLATILE
835 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
836 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG
837 %token DEPLIBS CALL TAIL
838 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK
839 %type <UIntVal> OptCallingConv
841 // Basic Block Terminating Operators
842 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
845 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
846 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
847 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comarators
849 // Memory Instructions
850 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
853 %type <OtherOpVal> ShiftOps
854 %token <OtherOpVal> PHI_TOK CAST SELECT SHL SHR VAARG VANEXT
860 // Handle constant integer size restriction and conversion...
864 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
865 ThrowException("Value too large for type!");
870 EINT64VAL : ESINT64VAL; // These have same type and can't cause problems...
871 EINT64VAL : EUINT64VAL {
872 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
873 ThrowException("Value too large for type!");
877 // Operations that are notably excluded from this list include:
878 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
880 ArithmeticOps: ADD | SUB | MUL | DIV | REM;
881 LogicalOps : AND | OR | XOR;
882 SetCondOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
884 ShiftOps : SHL | SHR;
886 // These are some types that allow classification if we only want a particular
887 // thing... for example, only a signed, unsigned, or integral type.
888 SIntType : LONG | INT | SHORT | SBYTE;
889 UIntType : ULONG | UINT | USHORT | UBYTE;
890 IntType : SIntType | UIntType;
891 FPType : FLOAT | DOUBLE;
893 // OptAssign - Value producing statements have an optional assignment component
894 OptAssign : Name '=' {
901 OptLinkage : INTERNAL { $$ = GlobalValue::InternalLinkage; } |
902 LINKONCE { $$ = GlobalValue::LinkOnceLinkage; } |
903 WEAK { $$ = GlobalValue::WeakLinkage; } |
904 APPENDING { $$ = GlobalValue::AppendingLinkage; } |
905 /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
907 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
908 CCC_TOK { $$ = CallingConv::C; } |
909 FASTCC_TOK { $$ = CallingConv::Fast; } |
910 COLDCC_TOK { $$ = CallingConv::Cold; } |
912 if ((unsigned)$2 != $2)
913 ThrowException("Calling conv too large!");
917 //===----------------------------------------------------------------------===//
918 // Types includes all predefined types... except void, because it can only be
919 // used in specific contexts (function returning void for example). To have
920 // access to it, a user must explicitly use TypesV.
923 // TypesV includes all of 'Types', but it also includes the void type.
924 TypesV : Types | VOID { $$ = new PATypeHolder($1); };
925 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
929 ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
934 // Derived types are added later...
936 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT ;
937 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL;
939 $$ = new PATypeHolder(OpaqueType::get());
942 $$ = new PATypeHolder($1);
944 UpRTypes : SymbolicValueRef { // Named types are also simple types...
945 $$ = new PATypeHolder(getTypeVal($1));
948 // Include derived types in the Types production.
950 UpRTypes : '\\' EUINT64VAL { // Type UpReference
951 if ($2 > (uint64_t)~0U) ThrowException("Value out of range!");
952 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
953 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
954 $$ = new PATypeHolder(OT);
955 UR_OUT("New Upreference!\n");
957 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
958 std::vector<const Type*> Params;
959 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
960 E = $3->end(); I != E; ++I)
961 Params.push_back(*I);
962 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
963 if (isVarArg) Params.pop_back();
965 $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
966 delete $3; // Delete the argument list
967 delete $1; // Delete the return type handle
969 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
970 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
973 | '<' EUINT64VAL 'x' UpRTypes '>' { // Packed array type?
974 const llvm::Type* ElemTy = $4->get();
975 if ((unsigned)$2 != $2) {
976 ThrowException("Unsigned result not equal to signed result");
978 if(!ElemTy->isPrimitiveType()) {
979 ThrowException("Elemental type of a PackedType must be primitive");
981 $$ = new PATypeHolder(HandleUpRefs(PackedType::get(*$4, (unsigned)$2)));
984 | '{' TypeListI '}' { // Structure type?
985 std::vector<const Type*> Elements;
986 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
987 E = $2->end(); I != E; ++I)
988 Elements.push_back(*I);
990 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
993 | '{' '}' { // Empty structure type?
994 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
996 | UpRTypes '*' { // Pointer type?
997 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1001 // TypeList - Used for struct declarations and as a basis for function type
1002 // declaration type lists
1004 TypeListI : UpRTypes {
1005 $$ = new std::list<PATypeHolder>();
1006 $$->push_back(*$1); delete $1;
1008 | TypeListI ',' UpRTypes {
1009 ($$=$1)->push_back(*$3); delete $3;
1012 // ArgTypeList - List of types for a function type declaration...
1013 ArgTypeListI : TypeListI
1014 | TypeListI ',' DOTDOTDOT {
1015 ($$=$1)->push_back(Type::VoidTy);
1018 ($$ = new std::list<PATypeHolder>())->push_back(Type::VoidTy);
1021 $$ = new std::list<PATypeHolder>();
1024 // ConstVal - The various declarations that go into the constant pool. This
1025 // production is used ONLY to represent constants that show up AFTER a 'const',
1026 // 'constant' or 'global' token at global scope. Constants that can be inlined
1027 // into other expressions (such as integers and constexprs) are handled by the
1028 // ResolvedVal, ValueRef and ConstValueRef productions.
1030 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1031 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1033 ThrowException("Cannot make array constant with type: '" +
1034 (*$1)->getDescription() + "'!");
1035 const Type *ETy = ATy->getElementType();
1036 int NumElements = ATy->getNumElements();
1038 // Verify that we have the correct size...
1039 if (NumElements != -1 && NumElements != (int)$3->size())
1040 ThrowException("Type mismatch: constant sized array initialized with " +
1041 utostr($3->size()) + " arguments, but has size of " +
1042 itostr(NumElements) + "!");
1044 // Verify all elements are correct type!
1045 for (unsigned i = 0; i < $3->size(); i++) {
1046 if (ETy != (*$3)[i]->getType())
1047 ThrowException("Element #" + utostr(i) + " is not of type '" +
1048 ETy->getDescription() +"' as required!\nIt is of type '"+
1049 (*$3)[i]->getType()->getDescription() + "'.");
1052 $$ = ConstantArray::get(ATy, *$3);
1053 delete $1; delete $3;
1056 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1058 ThrowException("Cannot make array constant with type: '" +
1059 (*$1)->getDescription() + "'!");
1061 int NumElements = ATy->getNumElements();
1062 if (NumElements != -1 && NumElements != 0)
1063 ThrowException("Type mismatch: constant sized array initialized with 0"
1064 " arguments, but has size of " + itostr(NumElements) +"!");
1065 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1068 | Types 'c' STRINGCONSTANT {
1069 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1071 ThrowException("Cannot make array constant with type: '" +
1072 (*$1)->getDescription() + "'!");
1074 int NumElements = ATy->getNumElements();
1075 const Type *ETy = ATy->getElementType();
1076 char *EndStr = UnEscapeLexed($3, true);
1077 if (NumElements != -1 && NumElements != (EndStr-$3))
1078 ThrowException("Can't build string constant of size " +
1079 itostr((int)(EndStr-$3)) +
1080 " when array has size " + itostr(NumElements) + "!");
1081 std::vector<Constant*> Vals;
1082 if (ETy == Type::SByteTy) {
1083 for (char *C = $3; C != EndStr; ++C)
1084 Vals.push_back(ConstantSInt::get(ETy, *C));
1085 } else if (ETy == Type::UByteTy) {
1086 for (char *C = $3; C != EndStr; ++C)
1087 Vals.push_back(ConstantUInt::get(ETy, (unsigned char)*C));
1090 ThrowException("Cannot build string arrays of non byte sized elements!");
1093 $$ = ConstantArray::get(ATy, Vals);
1096 | Types '<' ConstVector '>' { // Nonempty unsized arr
1097 const PackedType *PTy = dyn_cast<PackedType>($1->get());
1099 ThrowException("Cannot make packed constant with type: '" +
1100 (*$1)->getDescription() + "'!");
1101 const Type *ETy = PTy->getElementType();
1102 int NumElements = PTy->getNumElements();
1104 // Verify that we have the correct size...
1105 if (NumElements != -1 && NumElements != (int)$3->size())
1106 ThrowException("Type mismatch: constant sized packed initialized with " +
1107 utostr($3->size()) + " arguments, but has size of " +
1108 itostr(NumElements) + "!");
1110 // Verify all elements are correct type!
1111 for (unsigned i = 0; i < $3->size(); i++) {
1112 if (ETy != (*$3)[i]->getType())
1113 ThrowException("Element #" + utostr(i) + " is not of type '" +
1114 ETy->getDescription() +"' as required!\nIt is of type '"+
1115 (*$3)[i]->getType()->getDescription() + "'.");
1118 $$ = ConstantPacked::get(PTy, *$3);
1119 delete $1; delete $3;
1121 | Types '{' ConstVector '}' {
1122 const StructType *STy = dyn_cast<StructType>($1->get());
1124 ThrowException("Cannot make struct constant with type: '" +
1125 (*$1)->getDescription() + "'!");
1127 if ($3->size() != STy->getNumContainedTypes())
1128 ThrowException("Illegal number of initializers for structure type!");
1130 // Check to ensure that constants are compatible with the type initializer!
1131 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1132 if ((*$3)[i]->getType() != STy->getElementType(i))
1133 ThrowException("Expected type '" +
1134 STy->getElementType(i)->getDescription() +
1135 "' for element #" + utostr(i) +
1136 " of structure initializer!");
1138 $$ = ConstantStruct::get(STy, *$3);
1139 delete $1; delete $3;
1142 const StructType *STy = dyn_cast<StructType>($1->get());
1144 ThrowException("Cannot make struct constant with type: '" +
1145 (*$1)->getDescription() + "'!");
1147 if (STy->getNumContainedTypes() != 0)
1148 ThrowException("Illegal number of initializers for structure type!");
1150 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1154 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1156 ThrowException("Cannot make null pointer constant with type: '" +
1157 (*$1)->getDescription() + "'!");
1159 $$ = ConstantPointerNull::get(PTy);
1163 $$ = UndefValue::get($1->get());
1166 | Types SymbolicValueRef {
1167 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1169 ThrowException("Global const reference must be a pointer type!");
1171 // ConstExprs can exist in the body of a function, thus creating
1172 // GlobalValues whenever they refer to a variable. Because we are in
1173 // the context of a function, getValNonImprovising will search the functions
1174 // symbol table instead of the module symbol table for the global symbol,
1175 // which throws things all off. To get around this, we just tell
1176 // getValNonImprovising that we are at global scope here.
1178 Function *SavedCurFn = CurFun.CurrentFunction;
1179 CurFun.CurrentFunction = 0;
1181 Value *V = getValNonImprovising(Ty, $2);
1183 CurFun.CurrentFunction = SavedCurFn;
1185 // If this is an initializer for a constant pointer, which is referencing a
1186 // (currently) undefined variable, create a stub now that shall be replaced
1187 // in the future with the right type of variable.
1190 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1191 const PointerType *PT = cast<PointerType>(Ty);
1193 // First check to see if the forward references value is already created!
1194 PerModuleInfo::GlobalRefsType::iterator I =
1195 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1197 if (I != CurModule.GlobalRefs.end()) {
1198 V = I->second; // Placeholder already exists, use it...
1202 if ($2.Type == ValID::NameVal) Name = $2.Name;
1204 // Create the forward referenced global.
1206 if (const FunctionType *FTy =
1207 dyn_cast<FunctionType>(PT->getElementType())) {
1208 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1209 CurModule.CurrentModule);
1211 GV = new GlobalVariable(PT->getElementType(), false,
1212 GlobalValue::ExternalLinkage, 0,
1213 Name, CurModule.CurrentModule);
1216 // Keep track of the fact that we have a forward ref to recycle it
1217 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1222 $$ = cast<GlobalValue>(V);
1223 delete $1; // Free the type handle
1226 if ($1->get() != $2->getType())
1227 ThrowException("Mismatched types for constant expression!");
1231 | Types ZEROINITIALIZER {
1232 const Type *Ty = $1->get();
1233 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1234 ThrowException("Cannot create a null initialized value of this type!");
1235 $$ = Constant::getNullValue(Ty);
1239 ConstVal : SIntType EINT64VAL { // integral constants
1240 if (!ConstantSInt::isValueValidForType($1, $2))
1241 ThrowException("Constant value doesn't fit in type!");
1242 $$ = ConstantSInt::get($1, $2);
1244 | UIntType EUINT64VAL { // integral constants
1245 if (!ConstantUInt::isValueValidForType($1, $2))
1246 ThrowException("Constant value doesn't fit in type!");
1247 $$ = ConstantUInt::get($1, $2);
1249 | BOOL TRUETOK { // Boolean constants
1250 $$ = ConstantBool::True;
1252 | BOOL FALSETOK { // Boolean constants
1253 $$ = ConstantBool::False;
1255 | FPType FPVAL { // Float & Double constants
1256 if (!ConstantFP::isValueValidForType($1, $2))
1257 ThrowException("Floating point constant invalid for type!!");
1258 $$ = ConstantFP::get($1, $2);
1262 ConstExpr: CAST '(' ConstVal TO Types ')' {
1263 if (!$3->getType()->isFirstClassType())
1264 ThrowException("cast constant expression from a non-primitive type: '" +
1265 $3->getType()->getDescription() + "'!");
1266 if (!$5->get()->isFirstClassType())
1267 ThrowException("cast constant expression to a non-primitive type: '" +
1268 $5->get()->getDescription() + "'!");
1269 $$ = ConstantExpr::getCast($3, $5->get());
1272 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1273 if (!isa<PointerType>($3->getType()))
1274 ThrowException("GetElementPtr requires a pointer operand!");
1276 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
1277 // indices to uint struct indices for compatibility.
1278 generic_gep_type_iterator<std::vector<Value*>::iterator>
1279 GTI = gep_type_begin($3->getType(), $4->begin(), $4->end()),
1280 GTE = gep_type_end($3->getType(), $4->begin(), $4->end());
1281 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
1282 if (isa<StructType>(*GTI)) // Only change struct indices
1283 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
1284 if (CUI->getType() == Type::UByteTy)
1285 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
1288 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1290 ThrowException("Index list invalid for constant getelementptr!");
1292 std::vector<Constant*> IdxVec;
1293 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1294 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1295 IdxVec.push_back(C);
1297 ThrowException("Indices to constant getelementptr must be constants!");
1301 $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1303 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1304 if ($3->getType() != Type::BoolTy)
1305 ThrowException("Select condition must be of boolean type!");
1306 if ($5->getType() != $7->getType())
1307 ThrowException("Select operand types must match!");
1308 $$ = ConstantExpr::getSelect($3, $5, $7);
1310 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1311 if ($3->getType() != $5->getType())
1312 ThrowException("Binary operator types must match!");
1313 // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
1314 // To retain backward compatibility with these early compilers, we emit a
1315 // cast to the appropriate integer type automatically if we are in the
1316 // broken case. See PR424 for more information.
1317 if (!isa<PointerType>($3->getType())) {
1318 $$ = ConstantExpr::get($1, $3, $5);
1320 const Type *IntPtrTy = 0;
1321 switch (CurModule.CurrentModule->getPointerSize()) {
1322 case Module::Pointer32: IntPtrTy = Type::IntTy; break;
1323 case Module::Pointer64: IntPtrTy = Type::LongTy; break;
1324 default: ThrowException("invalid pointer binary constant expr!");
1326 $$ = ConstantExpr::get($1, ConstantExpr::getCast($3, IntPtrTy),
1327 ConstantExpr::getCast($5, IntPtrTy));
1328 $$ = ConstantExpr::getCast($$, $3->getType());
1331 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1332 if ($3->getType() != $5->getType())
1333 ThrowException("Logical operator types must match!");
1334 if (!$3->getType()->isIntegral())
1335 ThrowException("Logical operands must have integral types!");
1336 $$ = ConstantExpr::get($1, $3, $5);
1338 | SetCondOps '(' ConstVal ',' ConstVal ')' {
1339 if ($3->getType() != $5->getType())
1340 ThrowException("setcc operand types must match!");
1341 $$ = ConstantExpr::get($1, $3, $5);
1343 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1344 if ($5->getType() != Type::UByteTy)
1345 ThrowException("Shift count for shift constant must be unsigned byte!");
1346 if (!$3->getType()->isInteger())
1347 ThrowException("Shift constant expression requires integer operand!");
1348 $$ = ConstantExpr::get($1, $3, $5);
1352 // ConstVector - A list of comma separated constants.
1353 ConstVector : ConstVector ',' ConstVal {
1354 ($$ = $1)->push_back($3);
1357 $$ = new std::vector<Constant*>();
1362 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1363 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1366 //===----------------------------------------------------------------------===//
1367 // Rules to match Modules
1368 //===----------------------------------------------------------------------===//
1370 // Module rule: Capture the result of parsing the whole file into a result
1373 Module : FunctionList {
1374 $$ = ParserResult = $1;
1375 CurModule.ModuleDone();
1378 // FunctionList - A list of functions, preceeded by a constant pool.
1380 FunctionList : FunctionList Function {
1382 CurFun.FunctionDone();
1384 | FunctionList FunctionProto {
1387 | FunctionList IMPLEMENTATION {
1391 $$ = CurModule.CurrentModule;
1392 // Emit an error if there are any unresolved types left.
1393 if (!CurModule.LateResolveTypes.empty()) {
1394 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
1395 if (DID.Type == ValID::NameVal)
1396 ThrowException("Reference to an undefined type: '"+DID.getName() + "'");
1398 ThrowException("Reference to an undefined type: #" + itostr(DID.Num));
1402 // ConstPool - Constants with optional names assigned to them.
1403 ConstPool : ConstPool OptAssign TYPE TypesV {
1404 // Eagerly resolve types. This is not an optimization, this is a
1405 // requirement that is due to the fact that we could have this:
1407 // %list = type { %list * }
1408 // %list = type { %list * } ; repeated type decl
1410 // If types are not resolved eagerly, then the two types will not be
1411 // determined to be the same type!
1413 ResolveTypeTo($2, *$4);
1415 if (!setTypeName(*$4, $2) && !$2) {
1416 // If this is a named type that is not a redefinition, add it to the slot
1418 CurModule.Types.push_back(*$4);
1423 | ConstPool FunctionProto { // Function prototypes can be in const pool
1425 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
1426 if ($5 == 0) ThrowException("Global value initializer is not a constant!");
1427 ParseGlobalVariable($2, $3, $4, $5->getType(), $5);
1429 | ConstPool OptAssign EXTERNAL GlobalType Types {
1430 ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, *$5, 0);
1433 | ConstPool TARGET TargetDefinition {
1435 | ConstPool DEPLIBS '=' LibrariesDefinition {
1437 | /* empty: end of list */ {
1442 BigOrLittle : BIG { $$ = Module::BigEndian; };
1443 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1445 TargetDefinition : ENDIAN '=' BigOrLittle {
1446 CurModule.CurrentModule->setEndianness($3);
1448 | POINTERSIZE '=' EUINT64VAL {
1450 CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1452 CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1454 ThrowException("Invalid pointer size: '" + utostr($3) + "'!");
1456 | TRIPLE '=' STRINGCONSTANT {
1457 CurModule.CurrentModule->setTargetTriple($3);
1461 LibrariesDefinition : '[' LibList ']';
1463 LibList : LibList ',' STRINGCONSTANT {
1464 CurModule.CurrentModule->addLibrary($3);
1468 CurModule.CurrentModule->addLibrary($1);
1471 | /* empty: end of list */ {
1475 //===----------------------------------------------------------------------===//
1476 // Rules to match Function Headers
1477 //===----------------------------------------------------------------------===//
1479 Name : VAR_ID | STRINGCONSTANT;
1480 OptName : Name | /*empty*/ { $$ = 0; };
1482 ArgVal : Types OptName {
1483 if (*$1 == Type::VoidTy)
1484 ThrowException("void typed arguments are invalid!");
1485 $$ = new std::pair<PATypeHolder*, char*>($1, $2);
1488 ArgListH : ArgListH ',' ArgVal {
1494 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1499 ArgList : ArgListH {
1502 | ArgListH ',' DOTDOTDOT {
1504 $$->push_back(std::pair<PATypeHolder*,
1505 char*>(new PATypeHolder(Type::VoidTy), 0));
1508 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1509 $$->push_back(std::make_pair(new PATypeHolder(Type::VoidTy), (char*)0));
1515 FunctionHeaderH : OptCallingConv TypesV Name '(' ArgList ')' {
1517 std::string FunctionName($3);
1518 free($3); // Free strdup'd memory!
1520 if (!(*$2)->isFirstClassType() && *$2 != Type::VoidTy)
1521 ThrowException("LLVM functions cannot return aggregate types!");
1523 std::vector<const Type*> ParamTypeList;
1524 if ($5) { // If there are arguments...
1525 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
1526 I != $5->end(); ++I)
1527 ParamTypeList.push_back(I->first->get());
1530 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1531 if (isVarArg) ParamTypeList.pop_back();
1533 const FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
1534 const PointerType *PFT = PointerType::get(FT);
1538 if (!FunctionName.empty()) {
1539 ID = ValID::create((char*)FunctionName.c_str());
1541 ID = ValID::create((int)CurModule.Values[PFT].size());
1545 // See if this function was forward referenced. If so, recycle the object.
1546 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
1547 // Move the function to the end of the list, from whereever it was
1548 // previously inserted.
1549 Fn = cast<Function>(FWRef);
1550 CurModule.CurrentModule->getFunctionList().remove(Fn);
1551 CurModule.CurrentModule->getFunctionList().push_back(Fn);
1552 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
1553 (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
1554 // If this is the case, either we need to be a forward decl, or it needs
1556 if (!CurFun.isDeclare && !Fn->isExternal())
1557 ThrowException("Redefinition of function '" + FunctionName + "'!");
1559 // Make sure to strip off any argument names so we can't get conflicts.
1560 if (Fn->isExternal())
1561 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
1565 } else { // Not already defined?
1566 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
1567 CurModule.CurrentModule);
1568 InsertValue(Fn, CurModule.Values);
1571 CurFun.FunctionStart(Fn);
1572 Fn->setCallingConv($1);
1574 // Add all of the arguments we parsed to the function...
1575 if ($5) { // Is null if empty...
1576 if (isVarArg) { // Nuke the last entry
1577 assert($5->back().first->get() == Type::VoidTy && $5->back().second == 0&&
1578 "Not a varargs marker!");
1579 delete $5->back().first;
1580 $5->pop_back(); // Delete the last entry
1582 Function::arg_iterator ArgIt = Fn->arg_begin();
1583 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
1584 I != $5->end(); ++I, ++ArgIt) {
1585 delete I->first; // Delete the typeholder...
1587 setValueName(ArgIt, I->second); // Insert arg into symtab...
1591 delete $5; // We're now done with the argument list
1595 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
1597 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
1598 $$ = CurFun.CurrentFunction;
1600 // Make sure that we keep track of the linkage type even if there was a
1601 // previous "declare".
1605 END : ENDTOK | '}'; // Allow end of '}' to end a function
1607 Function : BasicBlockList END {
1611 FunctionProto : DECLARE { CurFun.isDeclare = true; } FunctionHeaderH {
1612 $$ = CurFun.CurrentFunction;
1613 CurFun.FunctionDone();
1616 //===----------------------------------------------------------------------===//
1617 // Rules to match Basic Blocks
1618 //===----------------------------------------------------------------------===//
1620 ConstValueRef : ESINT64VAL { // A reference to a direct constant
1621 $$ = ValID::create($1);
1624 $$ = ValID::create($1);
1626 | FPVAL { // Perhaps it's an FP constant?
1627 $$ = ValID::create($1);
1630 $$ = ValID::create(ConstantBool::True);
1633 $$ = ValID::create(ConstantBool::False);
1636 $$ = ValID::createNull();
1639 $$ = ValID::createUndef();
1641 | '<' ConstVector '>' { // Nonempty unsized packed vector
1642 const Type *ETy = (*$2)[0]->getType();
1643 int NumElements = $2->size();
1645 PackedType* pt = PackedType::get(ETy, NumElements);
1646 PATypeHolder* PTy = new PATypeHolder(
1654 // Verify all elements are correct type!
1655 for (unsigned i = 0; i < $2->size(); i++) {
1656 if (ETy != (*$2)[i]->getType())
1657 ThrowException("Element #" + utostr(i) + " is not of type '" +
1658 ETy->getDescription() +"' as required!\nIt is of type '" +
1659 (*$2)[i]->getType()->getDescription() + "'.");
1662 $$ = ValID::create(ConstantPacked::get(pt, *$2));
1663 delete PTy; delete $2;
1666 $$ = ValID::create($1);
1669 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1672 SymbolicValueRef : INTVAL { // Is it an integer reference...?
1673 $$ = ValID::create($1);
1675 | Name { // Is it a named reference...?
1676 $$ = ValID::create($1);
1679 // ValueRef - A reference to a definition... either constant or symbolic
1680 ValueRef : SymbolicValueRef | ConstValueRef;
1683 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
1684 // type immediately preceeds the value reference, and allows complex constant
1685 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1686 ResolvedVal : Types ValueRef {
1687 $$ = getVal(*$1, $2); delete $1;
1690 BasicBlockList : BasicBlockList BasicBlock {
1693 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
1698 // Basic blocks are terminated by branching instructions:
1699 // br, br/cc, switch, ret
1701 BasicBlock : InstructionList OptAssign BBTerminatorInst {
1702 setValueName($3, $2);
1705 $1->getInstList().push_back($3);
1710 InstructionList : InstructionList Inst {
1711 $1->getInstList().push_back($2);
1715 $$ = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
1717 // Make sure to move the basic block to the correct location in the
1718 // function, instead of leaving it inserted wherever it was first
1720 Function::BasicBlockListType &BBL =
1721 CurFun.CurrentFunction->getBasicBlockList();
1722 BBL.splice(BBL.end(), BBL, $$);
1725 $$ = getBBVal(ValID::create($1), true);
1727 // Make sure to move the basic block to the correct location in the
1728 // function, instead of leaving it inserted wherever it was first
1730 Function::BasicBlockListType &BBL =
1731 CurFun.CurrentFunction->getBasicBlockList();
1732 BBL.splice(BBL.end(), BBL, $$);
1735 BBTerminatorInst : RET ResolvedVal { // Return with a result...
1736 $$ = new ReturnInst($2);
1738 | RET VOID { // Return with no result...
1739 $$ = new ReturnInst();
1741 | BR LABEL ValueRef { // Unconditional Branch...
1742 $$ = new BranchInst(getBBVal($3));
1743 } // Conditional Branch...
1744 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
1745 $$ = new BranchInst(getBBVal($6), getBBVal($9), getVal(Type::BoolTy, $3));
1747 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1748 SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6), $8->size());
1751 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
1753 for (; I != E; ++I) {
1754 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
1755 S->addCase(CI, I->second);
1757 ThrowException("Switch case is constant, but not a simple integer!");
1761 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
1762 SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6), 0);
1765 | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
1766 TO LABEL ValueRef UNWIND LABEL ValueRef {
1767 const PointerType *PFTy;
1768 const FunctionType *Ty;
1770 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
1771 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1772 // Pull out the types of all of the arguments...
1773 std::vector<const Type*> ParamTypes;
1775 for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
1777 ParamTypes.push_back((*I)->getType());
1780 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1781 if (isVarArg) ParamTypes.pop_back();
1783 Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
1784 PFTy = PointerType::get(Ty);
1787 Value *V = getVal(PFTy, $4); // Get the function we're calling...
1789 BasicBlock *Normal = getBBVal($10);
1790 BasicBlock *Except = getBBVal($13);
1792 // Create the call node...
1793 if (!$6) { // Has no arguments?
1794 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
1795 } else { // Has arguments?
1796 // Loop through FunctionType's arguments and ensure they are specified
1799 FunctionType::param_iterator I = Ty->param_begin();
1800 FunctionType::param_iterator E = Ty->param_end();
1801 std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
1803 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1804 if ((*ArgI)->getType() != *I)
1805 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1806 (*I)->getDescription() + "'!");
1808 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1809 ThrowException("Invalid number of parameters detected!");
1811 $$ = new InvokeInst(V, Normal, Except, *$6);
1813 cast<InvokeInst>($$)->setCallingConv($2);
1819 $$ = new UnwindInst();
1822 $$ = new UnreachableInst();
1827 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1829 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
1831 ThrowException("May only switch on a constant pool value!");
1833 $$->push_back(std::make_pair(V, getBBVal($6)));
1835 | IntType ConstValueRef ',' LABEL ValueRef {
1836 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
1837 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
1840 ThrowException("May only switch on a constant pool value!");
1842 $$->push_back(std::make_pair(V, getBBVal($5)));
1845 Inst : OptAssign InstVal {
1846 // Is this definition named?? if so, assign the name...
1847 setValueName($2, $1);
1852 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
1853 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
1854 $$->push_back(std::make_pair(getVal(*$1, $3), getBBVal($5)));
1857 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1859 $1->push_back(std::make_pair(getVal($1->front().first->getType(), $4),
1864 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
1865 $$ = new std::vector<Value*>();
1868 | ValueRefList ',' ResolvedVal {
1873 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1874 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
1876 OptTailCall : TAIL CALL {
1885 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
1886 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
1887 !isa<PackedType>((*$2).get()))
1889 "Arithmetic operator requires integer, FP, or packed operands!");
1890 if (isa<PackedType>((*$2).get()) && $1 == Instruction::Rem)
1891 ThrowException("Rem not supported on packed types!");
1892 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1894 ThrowException("binary operator returned null!");
1897 | LogicalOps Types ValueRef ',' ValueRef {
1898 if (!(*$2)->isIntegral())
1899 ThrowException("Logical operator requires integral operands!");
1900 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1902 ThrowException("binary operator returned null!");
1905 | SetCondOps Types ValueRef ',' ValueRef {
1906 if(isa<PackedType>((*$2).get())) {
1908 "PackedTypes currently not supported in setcc instructions!");
1910 $$ = new SetCondInst($1, getVal(*$2, $3), getVal(*$2, $5));
1912 ThrowException("binary operator returned null!");
1916 std::cerr << "WARNING: Use of eliminated 'not' instruction:"
1917 << " Replacing with 'xor'.\n";
1919 Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
1921 ThrowException("Expected integral type for not instruction!");
1923 $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
1925 ThrowException("Could not create a xor instruction!");
1927 | ShiftOps ResolvedVal ',' ResolvedVal {
1928 if ($4->getType() != Type::UByteTy)
1929 ThrowException("Shift amount must be ubyte!");
1930 if (!$2->getType()->isInteger())
1931 ThrowException("Shift constant expression requires integer operand!");
1932 $$ = new ShiftInst($1, $2, $4);
1934 | CAST ResolvedVal TO Types {
1935 if (!$4->get()->isFirstClassType())
1936 ThrowException("cast instruction to a non-primitive type: '" +
1937 $4->get()->getDescription() + "'!");
1938 $$ = new CastInst($2, *$4);
1941 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
1942 if ($2->getType() != Type::BoolTy)
1943 ThrowException("select condition must be boolean!");
1944 if ($4->getType() != $6->getType())
1945 ThrowException("select value types should match!");
1946 $$ = new SelectInst($2, $4, $6);
1948 | VAARG ResolvedVal ',' Types {
1949 $$ = new VAArgInst($2, *$4);
1952 | VANEXT ResolvedVal ',' Types {
1953 $$ = new VANextInst($2, *$4);
1957 const Type *Ty = $2->front().first->getType();
1958 if (!Ty->isFirstClassType())
1959 ThrowException("PHI node operands must be of first class type!");
1960 $$ = new PHINode(Ty);
1961 ((PHINode*)$$)->reserveOperandSpace($2->size());
1962 while ($2->begin() != $2->end()) {
1963 if ($2->front().first->getType() != Ty)
1964 ThrowException("All elements of a PHI node must be of the same type!");
1965 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
1968 delete $2; // Free the list...
1970 | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')' {
1971 const PointerType *PFTy;
1972 const FunctionType *Ty;
1974 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
1975 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1976 // Pull out the types of all of the arguments...
1977 std::vector<const Type*> ParamTypes;
1979 for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
1981 ParamTypes.push_back((*I)->getType());
1984 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1985 if (isVarArg) ParamTypes.pop_back();
1987 if (!(*$3)->isFirstClassType() && *$3 != Type::VoidTy)
1988 ThrowException("LLVM functions cannot return aggregate types!");
1990 Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
1991 PFTy = PointerType::get(Ty);
1994 Value *V = getVal(PFTy, $4); // Get the function we're calling...
1996 // Create the call node...
1997 if (!$6) { // Has no arguments?
1998 // Make sure no arguments is a good thing!
1999 if (Ty->getNumParams() != 0)
2000 ThrowException("No arguments passed to a function that "
2001 "expects arguments!");
2003 $$ = new CallInst(V, std::vector<Value*>());
2004 } else { // Has arguments?
2005 // Loop through FunctionType's arguments and ensure they are specified
2008 FunctionType::param_iterator I = Ty->param_begin();
2009 FunctionType::param_iterator E = Ty->param_end();
2010 std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
2012 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2013 if ((*ArgI)->getType() != *I)
2014 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2015 (*I)->getDescription() + "'!");
2017 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2018 ThrowException("Invalid number of parameters detected!");
2020 $$ = new CallInst(V, *$6);
2022 cast<CallInst>($$)->setTailCall($1);
2023 cast<CallInst>($$)->setCallingConv($2);
2032 // IndexList - List of indices for GEP based instructions...
2033 IndexList : ',' ValueRefList {
2036 $$ = new std::vector<Value*>();
2039 OptVolatile : VOLATILE {
2048 MemoryInst : MALLOC Types {
2049 $$ = new MallocInst(*$2);
2052 | MALLOC Types ',' UINT ValueRef {
2053 $$ = new MallocInst(*$2, getVal($4, $5));
2057 $$ = new AllocaInst(*$2);
2060 | ALLOCA Types ',' UINT ValueRef {
2061 $$ = new AllocaInst(*$2, getVal($4, $5));
2064 | FREE ResolvedVal {
2065 if (!isa<PointerType>($2->getType()))
2066 ThrowException("Trying to free nonpointer type " +
2067 $2->getType()->getDescription() + "!");
2068 $$ = new FreeInst($2);
2071 | OptVolatile LOAD Types ValueRef {
2072 if (!isa<PointerType>($3->get()))
2073 ThrowException("Can't load from nonpointer type: " +
2074 (*$3)->getDescription());
2075 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
2076 ThrowException("Can't load from pointer of non-first-class type: " +
2077 (*$3)->getDescription());
2078 $$ = new LoadInst(getVal(*$3, $4), "", $1);
2081 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2082 const PointerType *PT = dyn_cast<PointerType>($5->get());
2084 ThrowException("Can't store to a nonpointer type: " +
2085 (*$5)->getDescription());
2086 const Type *ElTy = PT->getElementType();
2087 if (ElTy != $3->getType())
2088 ThrowException("Can't store '" + $3->getType()->getDescription() +
2089 "' into space of type '" + ElTy->getDescription() + "'!");
2091 $$ = new StoreInst($3, getVal(*$5, $6), $1);
2094 | GETELEMENTPTR Types ValueRef IndexList {
2095 if (!isa<PointerType>($2->get()))
2096 ThrowException("getelementptr insn requires pointer operand!");
2098 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
2099 // indices to uint struct indices for compatibility.
2100 generic_gep_type_iterator<std::vector<Value*>::iterator>
2101 GTI = gep_type_begin($2->get(), $4->begin(), $4->end()),
2102 GTE = gep_type_end($2->get(), $4->begin(), $4->end());
2103 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
2104 if (isa<StructType>(*GTI)) // Only change struct indices
2105 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
2106 if (CUI->getType() == Type::UByteTy)
2107 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
2109 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2110 ThrowException("Invalid getelementptr indices for type '" +
2111 (*$2)->getDescription()+ "'!");
2112 $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
2113 delete $2; delete $4;
2118 int yyerror(const char *ErrorMsg) {
2120 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2121 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2122 std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2123 if (yychar == YYEMPTY || yychar == 0)
2124 errMsg += "end-of-file.";
2126 errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2127 ThrowException(errMsg);