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/InlineAsm.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/SymbolTable.h"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/Support/Streams.h"
33 // The following is a gross hack. In order to rid the libAsmParser library of
34 // exceptions, we have to have a way of getting the yyparse function to go into
35 // an error situation. So, whenever we want an error to occur, the GenerateError
36 // function (see bottom of file) sets TriggerError. Then, at the end of each
37 // production in the grammer we use CHECK_FOR_ERROR which will invoke YYERROR
38 // (a goto) to put YACC in error state. Furthermore, several calls to
39 // GenerateError are made from inside productions and they must simulate the
40 // previous exception behavior by exiting the production immediately. We have
41 // replaced these with the GEN_ERROR macro which calls GeneratError and then
42 // immediately invokes YYERROR. This would be so much cleaner if it was a
43 // recursive descent parser.
44 static bool TriggerError = false;
45 #define CHECK_FOR_ERROR { if (TriggerError) { TriggerError = false; YYABORT; } }
46 #define GEN_ERROR(msg) { GenerateError(msg); YYERROR; }
48 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
49 int yylex(); // declaration" of xxx warnings.
53 std::string CurFilename;
56 Debug("debug-yacc", cl::desc("Print yacc debug state changes"),
57 cl::Hidden, cl::init(false));
62 static Module *ParserResult;
64 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
65 // relating to upreferences in the input stream.
67 //#define DEBUG_UPREFS 1
69 #define UR_OUT(X) cerr << X
74 #define YYERROR_VERBOSE 1
76 static GlobalVariable *CurGV;
79 // This contains info used when building the body of a function. It is
80 // destroyed when the function is completed.
82 typedef std::vector<Value *> ValueList; // Numbered defs
85 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
86 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
88 static struct PerModuleInfo {
89 Module *CurrentModule;
90 std::map<const Type *, ValueList> Values; // Module level numbered definitions
91 std::map<const Type *,ValueList> LateResolveValues;
92 std::vector<PATypeHolder> Types;
93 std::map<ValID, PATypeHolder> LateResolveTypes;
95 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
96 /// how they were referenced and on which line of the input they came from so
97 /// that we can resolve them later and print error messages as appropriate.
98 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
100 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
101 // references to global values. Global values may be referenced before they
102 // are defined, and if so, the temporary object that they represent is held
103 // here. This is used for forward references of GlobalValues.
105 typedef std::map<std::pair<const PointerType *,
106 ValID>, GlobalValue*> GlobalRefsType;
107 GlobalRefsType GlobalRefs;
110 // If we could not resolve some functions at function compilation time
111 // (calls to functions before they are defined), resolve them now... Types
112 // are resolved when the constant pool has been completely parsed.
114 ResolveDefinitions(LateResolveValues);
118 // Check to make sure that all global value forward references have been
121 if (!GlobalRefs.empty()) {
122 std::string UndefinedReferences = "Unresolved global references exist:\n";
124 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
126 UndefinedReferences += " " + I->first.first->getDescription() + " " +
127 I->first.second.getName() + "\n";
129 GenerateError(UndefinedReferences);
133 Values.clear(); // Clear out function local definitions
138 // GetForwardRefForGlobal - Check to see if there is a forward reference
139 // for this global. If so, remove it from the GlobalRefs map and return it.
140 // If not, just return null.
141 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
142 // Check to see if there is a forward reference to this global variable...
143 // if there is, eliminate it and patch the reference to use the new def'n.
144 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
145 GlobalValue *Ret = 0;
146 if (I != GlobalRefs.end()) {
153 bool TypeIsUnresolved(PATypeHolder* PATy) {
154 // If it isn't abstract, its resolved
155 const Type* Ty = PATy->get();
156 if (!Ty->isAbstract())
158 // Traverse the type looking for abstract types. If it isn't abstract then
159 // we don't need to traverse that leg of the type.
160 std::vector<const Type*> WorkList, SeenList;
161 WorkList.push_back(Ty);
162 while (!WorkList.empty()) {
163 const Type* Ty = WorkList.back();
164 SeenList.push_back(Ty);
166 if (const OpaqueType* OpTy = dyn_cast<OpaqueType>(Ty)) {
167 // Check to see if this is an unresolved type
168 std::map<ValID, PATypeHolder>::iterator I = LateResolveTypes.begin();
169 std::map<ValID, PATypeHolder>::iterator E = LateResolveTypes.end();
170 for ( ; I != E; ++I) {
171 if (I->second.get() == OpTy)
174 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(Ty)) {
175 const Type* TheTy = SeqTy->getElementType();
176 if (TheTy->isAbstract() && TheTy != Ty) {
177 std::vector<const Type*>::iterator I = SeenList.begin(),
183 WorkList.push_back(TheTy);
185 } else if (const StructType* StrTy = dyn_cast<StructType>(Ty)) {
186 for (unsigned i = 0; i < StrTy->getNumElements(); ++i) {
187 const Type* TheTy = StrTy->getElementType(i);
188 if (TheTy->isAbstract() && TheTy != Ty) {
189 std::vector<const Type*>::iterator I = SeenList.begin(),
195 WorkList.push_back(TheTy);
206 static struct PerFunctionInfo {
207 Function *CurrentFunction; // Pointer to current function being created
209 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
210 std::map<const Type*, ValueList> LateResolveValues;
211 bool isDeclare; // Is this function a forward declararation?
212 GlobalValue::LinkageTypes Linkage; // Linkage for forward declaration.
214 /// BBForwardRefs - When we see forward references to basic blocks, keep
215 /// track of them here.
216 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
217 std::vector<BasicBlock*> NumberedBlocks;
220 inline PerFunctionInfo() {
223 Linkage = GlobalValue::ExternalLinkage;
226 inline void FunctionStart(Function *M) {
231 void FunctionDone() {
232 NumberedBlocks.clear();
234 // Any forward referenced blocks left?
235 if (!BBForwardRefs.empty()) {
236 GenerateError("Undefined reference to label " +
237 BBForwardRefs.begin()->first->getName());
241 // Resolve all forward references now.
242 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
244 Values.clear(); // Clear out function local definitions
247 Linkage = GlobalValue::ExternalLinkage;
249 } CurFun; // Info for the current function...
251 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
254 //===----------------------------------------------------------------------===//
255 // Code to handle definitions of all the types
256 //===----------------------------------------------------------------------===//
258 static int InsertValue(Value *V,
259 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
260 if (V->hasName()) return -1; // Is this a numbered definition?
262 // Yes, insert the value into the value table...
263 ValueList &List = ValueTab[V->getType()];
265 return List.size()-1;
268 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
270 case ValID::NumberVal: // Is it a numbered definition?
271 // Module constants occupy the lowest numbered slots...
272 if ((unsigned)D.Num < CurModule.Types.size())
273 return CurModule.Types[(unsigned)D.Num];
275 case ValID::NameVal: // Is it a named definition?
276 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
277 D.destroy(); // Free old strdup'd memory...
282 GenerateError("Internal parser error: Invalid symbol type reference!");
286 // If we reached here, we referenced either a symbol that we don't know about
287 // or an id number that hasn't been read yet. We may be referencing something
288 // forward, so just create an entry to be resolved later and get to it...
290 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
293 if (inFunctionScope()) {
294 if (D.Type == ValID::NameVal) {
295 GenerateError("Reference to an undefined type: '" + D.getName() + "'");
298 GenerateError("Reference to an undefined type: #" + itostr(D.Num));
303 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
304 if (I != CurModule.LateResolveTypes.end())
307 Type *Typ = OpaqueType::get();
308 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
312 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
313 SymbolTable &SymTab =
314 inFunctionScope() ? CurFun.CurrentFunction->getSymbolTable() :
315 CurModule.CurrentModule->getSymbolTable();
316 return SymTab.lookup(Ty, Name);
319 // getValNonImprovising - Look up the value specified by the provided type and
320 // the provided ValID. If the value exists and has already been defined, return
321 // it. Otherwise return null.
323 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
324 if (isa<FunctionType>(Ty)) {
325 GenerateError("Functions are not values and "
326 "must be referenced as pointers");
331 case ValID::NumberVal: { // Is it a numbered definition?
332 unsigned Num = (unsigned)D.Num;
334 // Module constants occupy the lowest numbered slots...
335 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
336 if (VI != CurModule.Values.end()) {
337 if (Num < VI->second.size())
338 return VI->second[Num];
339 Num -= VI->second.size();
342 // Make sure that our type is within bounds
343 VI = CurFun.Values.find(Ty);
344 if (VI == CurFun.Values.end()) return 0;
346 // Check that the number is within bounds...
347 if (VI->second.size() <= Num) return 0;
349 return VI->second[Num];
352 case ValID::NameVal: { // Is it a named definition?
353 Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
354 if (N == 0) return 0;
356 D.destroy(); // Free old strdup'd memory...
360 // Check to make sure that "Ty" is an integral type, and that our
361 // value will fit into the specified type...
362 case ValID::ConstSIntVal: // Is it a constant pool reference??
363 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
364 GenerateError("Signed integral constant '" +
365 itostr(D.ConstPool64) + "' is invalid for type '" +
366 Ty->getDescription() + "'!");
369 return ConstantInt::get(Ty, D.ConstPool64);
371 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
372 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
373 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
374 GenerateError("Integral constant '" + utostr(D.UConstPool64) +
375 "' is invalid or out of range!");
377 } else { // This is really a signed reference. Transmogrify.
378 return ConstantInt::get(Ty, D.ConstPool64);
381 return ConstantInt::get(Ty, D.UConstPool64);
384 case ValID::ConstFPVal: // Is it a floating point const pool reference?
385 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP)) {
386 GenerateError("FP constant invalid for type!!");
389 return ConstantFP::get(Ty, D.ConstPoolFP);
391 case ValID::ConstNullVal: // Is it a null value?
392 if (!isa<PointerType>(Ty)) {
393 GenerateError("Cannot create a a non pointer null!");
396 return ConstantPointerNull::get(cast<PointerType>(Ty));
398 case ValID::ConstUndefVal: // Is it an undef value?
399 return UndefValue::get(Ty);
401 case ValID::ConstZeroVal: // Is it a zero value?
402 return Constant::getNullValue(Ty);
404 case ValID::ConstantVal: // Fully resolved constant?
405 if (D.ConstantValue->getType() != Ty) {
406 GenerateError("Constant expression type different from required type!");
409 return D.ConstantValue;
411 case ValID::InlineAsmVal: { // Inline asm expression
412 const PointerType *PTy = dyn_cast<PointerType>(Ty);
413 const FunctionType *FTy =
414 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
415 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
416 GenerateError("Invalid type for asm constraint string!");
419 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
420 D.IAD->HasSideEffects);
421 D.destroy(); // Free InlineAsmDescriptor.
425 assert(0 && "Unhandled case!");
429 assert(0 && "Unhandled case!");
433 // getVal - This function is identical to getValNonImprovising, except that if a
434 // value is not already defined, it "improvises" by creating a placeholder var
435 // that looks and acts just like the requested variable. When the value is
436 // defined later, all uses of the placeholder variable are replaced with the
439 static Value *getVal(const Type *Ty, const ValID &ID) {
440 if (Ty == Type::LabelTy) {
441 GenerateError("Cannot use a basic block here");
445 // See if the value has already been defined.
446 Value *V = getValNonImprovising(Ty, ID);
448 if (TriggerError) return 0;
450 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
451 GenerateError("Invalid use of a composite type!");
455 // If we reached here, we referenced either a symbol that we don't know about
456 // or an id number that hasn't been read yet. We may be referencing something
457 // forward, so just create an entry to be resolved later and get to it...
459 V = new Argument(Ty);
461 // Remember where this forward reference came from. FIXME, shouldn't we try
462 // to recycle these things??
463 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
466 if (inFunctionScope())
467 InsertValue(V, CurFun.LateResolveValues);
469 InsertValue(V, CurModule.LateResolveValues);
473 /// getBBVal - This is used for two purposes:
474 /// * If isDefinition is true, a new basic block with the specified ID is being
476 /// * If isDefinition is true, this is a reference to a basic block, which may
477 /// or may not be a forward reference.
479 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
480 assert(inFunctionScope() && "Can't get basic block at global scope!");
486 GenerateError("Illegal label reference " + ID.getName());
488 case ValID::NumberVal: // Is it a numbered definition?
489 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
490 CurFun.NumberedBlocks.resize(ID.Num+1);
491 BB = CurFun.NumberedBlocks[ID.Num];
493 case ValID::NameVal: // Is it a named definition?
495 if (Value *N = CurFun.CurrentFunction->
496 getSymbolTable().lookup(Type::LabelTy, Name))
497 BB = cast<BasicBlock>(N);
501 // See if the block has already been defined.
503 // If this is the definition of the block, make sure the existing value was
504 // just a forward reference. If it was a forward reference, there will be
505 // an entry for it in the PlaceHolderInfo map.
506 if (isDefinition && !CurFun.BBForwardRefs.erase(BB)) {
507 // The existing value was a definition, not a forward reference.
508 GenerateError("Redefinition of label " + ID.getName());
512 ID.destroy(); // Free strdup'd memory.
516 // Otherwise this block has not been seen before.
517 BB = new BasicBlock("", CurFun.CurrentFunction);
518 if (ID.Type == ValID::NameVal) {
519 BB->setName(ID.Name);
521 CurFun.NumberedBlocks[ID.Num] = BB;
524 // If this is not a definition, keep track of it so we can use it as a forward
527 // Remember where this forward reference came from.
528 CurFun.BBForwardRefs[BB] = std::make_pair(ID, llvmAsmlineno);
530 // The forward declaration could have been inserted anywhere in the
531 // function: insert it into the correct place now.
532 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
533 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
540 //===----------------------------------------------------------------------===//
541 // Code to handle forward references in instructions
542 //===----------------------------------------------------------------------===//
544 // This code handles the late binding needed with statements that reference
545 // values not defined yet... for example, a forward branch, or the PHI node for
548 // This keeps a table (CurFun.LateResolveValues) of all such forward references
549 // and back patchs after we are done.
552 // ResolveDefinitions - If we could not resolve some defs at parsing
553 // time (forward branches, phi functions for loops, etc...) resolve the
557 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
558 std::map<const Type*,ValueList> *FutureLateResolvers) {
559 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
560 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
561 E = LateResolvers.end(); LRI != E; ++LRI) {
562 ValueList &List = LRI->second;
563 while (!List.empty()) {
564 Value *V = List.back();
567 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
568 CurModule.PlaceHolderInfo.find(V);
569 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
571 ValID &DID = PHI->second.first;
573 Value *TheRealValue = getValNonImprovising(LRI->first, DID);
577 V->replaceAllUsesWith(TheRealValue);
579 CurModule.PlaceHolderInfo.erase(PHI);
580 } else if (FutureLateResolvers) {
581 // Functions have their unresolved items forwarded to the module late
583 InsertValue(V, *FutureLateResolvers);
585 if (DID.Type == ValID::NameVal) {
586 GenerateError("Reference to an invalid definition: '" +DID.getName()+
587 "' of type '" + V->getType()->getDescription() + "'",
591 GenerateError("Reference to an invalid definition: #" +
592 itostr(DID.Num) + " of type '" +
593 V->getType()->getDescription() + "'",
601 LateResolvers.clear();
604 // ResolveTypeTo - A brand new type was just declared. This means that (if
605 // name is not null) things referencing Name can be resolved. Otherwise, things
606 // refering to the number can be resolved. Do this now.
608 static void ResolveTypeTo(char *Name, const Type *ToTy) {
610 if (Name) D = ValID::create(Name);
611 else D = ValID::create((int)CurModule.Types.size());
613 std::map<ValID, PATypeHolder>::iterator I =
614 CurModule.LateResolveTypes.find(D);
615 if (I != CurModule.LateResolveTypes.end()) {
616 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
617 CurModule.LateResolveTypes.erase(I);
621 // setValueName - Set the specified value to the name given. The name may be
622 // null potentially, in which case this is a noop. The string passed in is
623 // assumed to be a malloc'd string buffer, and is free'd by this function.
625 static void setValueName(Value *V, char *NameStr) {
627 std::string Name(NameStr); // Copy string
628 free(NameStr); // Free old string
630 if (V->getType() == Type::VoidTy) {
631 GenerateError("Can't assign name '" + Name+"' to value with void type!");
635 assert(inFunctionScope() && "Must be in function scope!");
636 SymbolTable &ST = CurFun.CurrentFunction->getSymbolTable();
637 if (ST.lookup(V->getType(), Name)) {
638 GenerateError("Redefinition of value named '" + Name + "' in the '" +
639 V->getType()->getDescription() + "' type plane!");
648 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
649 /// this is a declaration, otherwise it is a definition.
650 static GlobalVariable *
651 ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
652 bool isConstantGlobal, const Type *Ty,
653 Constant *Initializer) {
654 if (isa<FunctionType>(Ty)) {
655 GenerateError("Cannot declare global vars of function type!");
659 const PointerType *PTy = PointerType::get(Ty);
663 Name = NameStr; // Copy string
664 free(NameStr); // Free old string
667 // See if this global value was forward referenced. If so, recycle the
671 ID = ValID::create((char*)Name.c_str());
673 ID = ValID::create((int)CurModule.Values[PTy].size());
676 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
677 // Move the global to the end of the list, from whereever it was
678 // previously inserted.
679 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
680 CurModule.CurrentModule->getGlobalList().remove(GV);
681 CurModule.CurrentModule->getGlobalList().push_back(GV);
682 GV->setInitializer(Initializer);
683 GV->setLinkage(Linkage);
684 GV->setConstant(isConstantGlobal);
685 InsertValue(GV, CurModule.Values);
689 // If this global has a name, check to see if there is already a definition
690 // of this global in the module. If so, merge as appropriate. Note that
691 // this is really just a hack around problems in the CFE. :(
693 // We are a simple redefinition of a value, check to see if it is defined
694 // the same as the old one.
695 if (GlobalVariable *EGV =
696 CurModule.CurrentModule->getGlobalVariable(Name, Ty)) {
697 // We are allowed to redefine a global variable in two circumstances:
698 // 1. If at least one of the globals is uninitialized or
699 // 2. If both initializers have the same value.
701 if (!EGV->hasInitializer() || !Initializer ||
702 EGV->getInitializer() == Initializer) {
704 // Make sure the existing global version gets the initializer! Make
705 // sure that it also gets marked const if the new version is.
706 if (Initializer && !EGV->hasInitializer())
707 EGV->setInitializer(Initializer);
708 if (isConstantGlobal)
709 EGV->setConstant(true);
710 EGV->setLinkage(Linkage);
714 GenerateError("Redefinition of global variable named '" + Name +
715 "' in the '" + Ty->getDescription() + "' type plane!");
720 // Otherwise there is no existing GV to use, create one now.
722 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
723 CurModule.CurrentModule);
724 InsertValue(GV, CurModule.Values);
728 // setTypeName - Set the specified type to the name given. The name may be
729 // null potentially, in which case this is a noop. The string passed in is
730 // assumed to be a malloc'd string buffer, and is freed by this function.
732 // This function returns true if the type has already been defined, but is
733 // allowed to be redefined in the specified context. If the name is a new name
734 // for the type plane, it is inserted and false is returned.
735 static bool setTypeName(const Type *T, char *NameStr) {
736 assert(!inFunctionScope() && "Can't give types function-local names!");
737 if (NameStr == 0) return false;
739 std::string Name(NameStr); // Copy string
740 free(NameStr); // Free old string
742 // We don't allow assigning names to void type
743 if (T == Type::VoidTy) {
744 GenerateError("Can't assign name '" + Name + "' to the void type!");
748 // Set the type name, checking for conflicts as we do so.
749 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
751 if (AlreadyExists) { // Inserting a name that is already defined???
752 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
753 assert(Existing && "Conflict but no matching type?");
755 // There is only one case where this is allowed: when we are refining an
756 // opaque type. In this case, Existing will be an opaque type.
757 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
758 // We ARE replacing an opaque type!
759 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
763 // Otherwise, this is an attempt to redefine a type. That's okay if
764 // the redefinition is identical to the original. This will be so if
765 // Existing and T point to the same Type object. In this one case we
766 // allow the equivalent redefinition.
767 if (Existing == T) return true; // Yes, it's equal.
769 // Any other kind of (non-equivalent) redefinition is an error.
770 GenerateError("Redefinition of type named '" + Name + "' in the '" +
771 T->getDescription() + "' type plane!");
777 //===----------------------------------------------------------------------===//
778 // Code for handling upreferences in type names...
781 // TypeContains - Returns true if Ty directly contains E in it.
783 static bool TypeContains(const Type *Ty, const Type *E) {
784 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
785 E) != Ty->subtype_end();
790 // NestingLevel - The number of nesting levels that need to be popped before
791 // this type is resolved.
792 unsigned NestingLevel;
794 // LastContainedTy - This is the type at the current binding level for the
795 // type. Every time we reduce the nesting level, this gets updated.
796 const Type *LastContainedTy;
798 // UpRefTy - This is the actual opaque type that the upreference is
802 UpRefRecord(unsigned NL, OpaqueType *URTy)
803 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
807 // UpRefs - A list of the outstanding upreferences that need to be resolved.
808 static std::vector<UpRefRecord> UpRefs;
810 /// HandleUpRefs - Every time we finish a new layer of types, this function is
811 /// called. It loops through the UpRefs vector, which is a list of the
812 /// currently active types. For each type, if the up reference is contained in
813 /// the newly completed type, we decrement the level count. When the level
814 /// count reaches zero, the upreferenced type is the type that is passed in:
815 /// thus we can complete the cycle.
817 static PATypeHolder HandleUpRefs(const Type *ty) {
818 // If Ty isn't abstract, or if there are no up-references in it, then there is
819 // nothing to resolve here.
820 if (!ty->isAbstract() || UpRefs.empty()) return ty;
823 UR_OUT("Type '" << Ty->getDescription() <<
824 "' newly formed. Resolving upreferences.\n" <<
825 UpRefs.size() << " upreferences active!\n");
827 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
828 // to zero), we resolve them all together before we resolve them to Ty. At
829 // the end of the loop, if there is anything to resolve to Ty, it will be in
831 OpaqueType *TypeToResolve = 0;
833 for (unsigned i = 0; i != UpRefs.size(); ++i) {
834 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
835 << UpRefs[i].second->getDescription() << ") = "
836 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
837 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
838 // Decrement level of upreference
839 unsigned Level = --UpRefs[i].NestingLevel;
840 UpRefs[i].LastContainedTy = Ty;
841 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
842 if (Level == 0) { // Upreference should be resolved!
843 if (!TypeToResolve) {
844 TypeToResolve = UpRefs[i].UpRefTy;
846 UR_OUT(" * Resolving upreference for "
847 << UpRefs[i].second->getDescription() << "\n";
848 std::string OldName = UpRefs[i].UpRefTy->getDescription());
849 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
850 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
851 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
853 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
854 --i; // Do not skip the next element...
860 UR_OUT(" * Resolving upreference for "
861 << UpRefs[i].second->getDescription() << "\n";
862 std::string OldName = TypeToResolve->getDescription());
863 TypeToResolve->refineAbstractTypeTo(Ty);
869 //===----------------------------------------------------------------------===//
870 // RunVMAsmParser - Define an interface to this parser
871 //===----------------------------------------------------------------------===//
873 static Module* RunParser(Module * M);
875 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
878 CurFilename = Filename;
879 return RunParser(new Module(CurFilename));
882 Module *llvm::RunVMAsmParser(const char * AsmString, Module * M) {
883 set_scan_string(AsmString);
885 CurFilename = "from_memory";
887 return RunParser(new Module (CurFilename));
896 llvm::Module *ModuleVal;
897 llvm::Function *FunctionVal;
898 llvm::BasicBlock *BasicBlockVal;
899 llvm::TerminatorInst *TermInstVal;
900 llvm::Instruction *InstVal;
901 llvm::Constant *ConstVal;
903 const llvm::Type *PrimType;
904 std::list<llvm::PATypeHolder> *TypeList;
905 llvm::PATypeHolder *TypeVal;
906 llvm::Value *ValueVal;
907 std::vector<llvm::Value*> *ValueList;
908 llvm::ArgListType *ArgList;
909 llvm::TypeWithAttrs TypeWithAttrs;
910 llvm::TypeWithAttrsList *TypeWithAttrsList;
911 llvm::ValueRefList *ValueRefList;
913 // Represent the RHS of PHI node
914 std::list<std::pair<llvm::Value*,
915 llvm::BasicBlock*> > *PHIList;
916 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
917 std::vector<llvm::Constant*> *ConstVector;
919 llvm::GlobalValue::LinkageTypes Linkage;
920 llvm::FunctionType::ParameterAttributes ParamAttrs;
928 char *StrVal; // This memory is strdup'd!
929 llvm::ValID ValIDVal; // strdup'd memory maybe!
931 llvm::Instruction::BinaryOps BinaryOpVal;
932 llvm::Instruction::TermOps TermOpVal;
933 llvm::Instruction::MemoryOps MemOpVal;
934 llvm::Instruction::CastOps CastOpVal;
935 llvm::Instruction::OtherOps OtherOpVal;
936 llvm::Module::Endianness Endianness;
937 llvm::ICmpInst::Predicate IPredicate;
938 llvm::FCmpInst::Predicate FPredicate;
941 %type <ModuleVal> Module
942 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
943 %type <BasicBlockVal> BasicBlock InstructionList
944 %type <TermInstVal> BBTerminatorInst
945 %type <InstVal> Inst InstVal MemoryInst
946 %type <ConstVal> ConstVal ConstExpr
947 %type <ConstVector> ConstVector
948 %type <ArgList> ArgList ArgListH
949 %type <PHIList> PHIList
950 %type <ValueRefList> ValueRefList // For call param lists & GEP indices
951 %type <ValueList> IndexList // For GEP indices
952 %type <TypeList> TypeListI
953 %type <TypeWithAttrsList> ArgTypeList ArgTypeListI
954 %type <TypeWithAttrs> ArgType
955 %type <JumpTable> JumpTable
956 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
957 %type <BoolVal> OptVolatile // 'volatile' or not
958 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
959 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
960 %type <Linkage> GVInternalLinkage GVExternalLinkage
961 %type <Linkage> FunctionDefineLinkage FunctionDeclareLinkage
962 %type <Endianness> BigOrLittle
964 // ValueRef - Unresolved reference to a definition or BB
965 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
966 %type <ValueVal> ResolvedVal // <type> <valref> pair
967 // Tokens and types for handling constant integer values
969 // ESINT64VAL - A negative number within long long range
970 %token <SInt64Val> ESINT64VAL
972 // EUINT64VAL - A positive number within uns. long long range
973 %token <UInt64Val> EUINT64VAL
975 %token <SIntVal> SINTVAL // Signed 32 bit ints...
976 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
977 %type <SIntVal> INTVAL
978 %token <FPVal> FPVAL // Float or Double constant
981 %type <TypeVal> Types ResultTypes
982 %type <PrimType> IntType FPType PrimType // Classifications
983 %token <PrimType> VOID BOOL INT8 INT16 INT32 INT64
984 %token <PrimType> FLOAT DOUBLE LABEL
987 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
988 %type <StrVal> Name OptName OptAssign
989 %type <UIntVal> OptAlign OptCAlign
990 %type <StrVal> OptSection SectionString
992 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
993 %token DECLARE DEFINE GLOBAL CONSTANT SECTION VOLATILE
994 %token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
995 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
996 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
997 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
998 %token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
999 %token X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1001 %type <UIntVal> OptCallingConv
1002 %type <ParamAttrs> OptParamAttrs ParamAttr
1003 %type <ParamAttrs> OptFuncAttrs FuncAttr
1005 // Basic Block Terminating Operators
1006 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1009 %type <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
1010 %token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1011 %token <OtherOpVal> ICMP FCMP
1012 %type <IPredicate> IPredicates
1013 %type <FPredicate> FPredicates
1014 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1015 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1017 // Memory Instructions
1018 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1021 %type <CastOpVal> CastOps
1022 %token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1023 %token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1026 %type <OtherOpVal> ShiftOps
1027 %token <OtherOpVal> PHI_TOK SELECT SHL LSHR ASHR VAARG
1028 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1030 // Function Attributes
1036 // Handle constant integer size restriction and conversion...
1040 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
1041 GEN_ERROR("Value too large for type!");
1046 // Operations that are notably excluded from this list include:
1047 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1049 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1050 LogicalOps : AND | OR | XOR;
1051 CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1052 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1053 ShiftOps : SHL | LSHR | ASHR;
1055 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1056 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1057 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1058 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1059 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1063 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1064 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1065 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1066 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1067 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1068 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1069 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1070 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1071 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1074 // These are some types that allow classification if we only want a particular
1075 // thing... for example, only a signed, unsigned, or integral type.
1076 IntType : INT64 | INT32 | INT16 | INT8;
1077 FPType : FLOAT | DOUBLE;
1079 // OptAssign - Value producing statements have an optional assignment component
1080 OptAssign : Name '=' {
1090 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1091 | WEAK { $$ = GlobalValue::WeakLinkage; }
1092 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1093 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1094 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1098 : DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1099 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1100 | EXTERNAL { $$ = GlobalValue::ExternalLinkage; }
1103 FunctionDeclareLinkage
1104 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1105 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1106 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1109 FunctionDefineLinkage
1110 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1111 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1112 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1113 | WEAK { $$ = GlobalValue::WeakLinkage; }
1114 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1117 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1118 CCC_TOK { $$ = CallingConv::C; } |
1119 CSRETCC_TOK { $$ = CallingConv::CSRet; } |
1120 FASTCC_TOK { $$ = CallingConv::Fast; } |
1121 COLDCC_TOK { $$ = CallingConv::Cold; } |
1122 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1123 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1125 if ((unsigned)$2 != $2)
1126 GEN_ERROR("Calling conv too large!");
1131 ParamAttr : ZEXT { $$ = FunctionType::ZExtAttribute; }
1132 | SEXT { $$ = FunctionType::SExtAttribute; }
1135 OptParamAttrs : /* empty */ { $$ = FunctionType::NoAttributeSet; }
1136 | OptParamAttrs ParamAttr {
1137 $$ = FunctionType::ParameterAttributes($1 | $2);
1141 FuncAttr : NORETURN { $$ = FunctionType::NoReturnAttribute; }
1145 OptFuncAttrs : /* empty */ { $$ = FunctionType::NoAttributeSet; }
1146 | OptFuncAttrs FuncAttr {
1147 $$ = FunctionType::ParameterAttributes($1 | $2);
1151 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1152 // a comma before it.
1153 OptAlign : /*empty*/ { $$ = 0; } |
1156 if ($$ != 0 && !isPowerOf2_32($$))
1157 GEN_ERROR("Alignment must be a power of two!");
1160 OptCAlign : /*empty*/ { $$ = 0; } |
1161 ',' ALIGN EUINT64VAL {
1163 if ($$ != 0 && !isPowerOf2_32($$))
1164 GEN_ERROR("Alignment must be a power of two!");
1169 SectionString : SECTION STRINGCONSTANT {
1170 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1171 if ($2[i] == '"' || $2[i] == '\\')
1172 GEN_ERROR("Invalid character in section name!");
1177 OptSection : /*empty*/ { $$ = 0; } |
1178 SectionString { $$ = $1; };
1180 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1181 // is set to be the global we are processing.
1183 GlobalVarAttributes : /* empty */ {} |
1184 ',' GlobalVarAttribute GlobalVarAttributes {};
1185 GlobalVarAttribute : SectionString {
1186 CurGV->setSection($1);
1190 | ALIGN EUINT64VAL {
1191 if ($2 != 0 && !isPowerOf2_32($2))
1192 GEN_ERROR("Alignment must be a power of two!");
1193 CurGV->setAlignment($2);
1197 //===----------------------------------------------------------------------===//
1198 // Types includes all predefined types... except void, because it can only be
1199 // used in specific contexts (function returning void for example).
1201 // Derived types are added later...
1203 PrimType : BOOL | INT8 | INT16 | INT32 | INT64 | FLOAT | DOUBLE | LABEL ;
1207 $$ = new PATypeHolder(OpaqueType::get());
1211 $$ = new PATypeHolder($1);
1214 | Types '*' { // Pointer type?
1215 if (*$1 == Type::LabelTy)
1216 GEN_ERROR("Cannot form a pointer to a basic block");
1217 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1221 | SymbolicValueRef { // Named types are also simple types...
1222 const Type* tmp = getTypeVal($1);
1224 $$ = new PATypeHolder(tmp);
1226 | '\\' EUINT64VAL { // Type UpReference
1227 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range!");
1228 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1229 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1230 $$ = new PATypeHolder(OT);
1231 UR_OUT("New Upreference!\n");
1234 | Types '(' ArgTypeListI ')' OptFuncAttrs {
1235 std::vector<const Type*> Params;
1236 std::vector<FunctionType::ParameterAttributes> Attrs;
1237 Attrs.push_back($5);
1238 for (TypeWithAttrsList::iterator I=$3->begin(), E=$3->end(); I != E; ++I) {
1239 Params.push_back(I->Ty->get());
1240 if (I->Ty->get() != Type::VoidTy)
1241 Attrs.push_back(I->Attrs);
1243 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1244 if (isVarArg) Params.pop_back();
1246 FunctionType *FT = FunctionType::get(*$1, Params, isVarArg, Attrs);
1247 delete $3; // Delete the argument list
1248 delete $1; // Delete the return type handle
1249 $$ = new PATypeHolder(HandleUpRefs(FT));
1252 | VOID '(' ArgTypeListI ')' OptFuncAttrs {
1253 std::vector<const Type*> Params;
1254 std::vector<FunctionType::ParameterAttributes> Attrs;
1255 Attrs.push_back($5);
1256 for (TypeWithAttrsList::iterator I=$3->begin(), E=$3->end(); I != E; ++I) {
1257 Params.push_back(I->Ty->get());
1258 if (I->Ty->get() != Type::VoidTy)
1259 Attrs.push_back(I->Attrs);
1261 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1262 if (isVarArg) Params.pop_back();
1264 FunctionType *FT = FunctionType::get($1, Params, isVarArg, Attrs);
1265 delete $3; // Delete the argument list
1266 $$ = new PATypeHolder(HandleUpRefs(FT));
1270 | '[' EUINT64VAL 'x' Types ']' { // Sized array type?
1271 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1275 | '<' EUINT64VAL 'x' Types '>' { // Packed array type?
1276 const llvm::Type* ElemTy = $4->get();
1277 if ((unsigned)$2 != $2)
1278 GEN_ERROR("Unsigned result not equal to signed result");
1279 if (!ElemTy->isPrimitiveType())
1280 GEN_ERROR("Elemental type of a PackedType must be primitive");
1281 if (!isPowerOf2_32($2))
1282 GEN_ERROR("Vector length should be a power of 2!");
1283 $$ = new PATypeHolder(HandleUpRefs(PackedType::get(*$4, (unsigned)$2)));
1287 | '{' TypeListI '}' { // Structure type?
1288 std::vector<const Type*> Elements;
1289 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1290 E = $2->end(); I != E; ++I)
1291 Elements.push_back(*I);
1293 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1297 | '{' '}' { // Empty structure type?
1298 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1301 | '<' '{' TypeListI '}' '>' {
1302 std::vector<const Type*> Elements;
1303 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1304 E = $3->end(); I != E; ++I)
1305 Elements.push_back(*I);
1307 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1311 | '<' '{' '}' '>' { // Empty structure type?
1312 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1318 : Types OptParamAttrs {
1326 if (!UpRefs.empty())
1327 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1328 if (!(*$1)->isFirstClassType())
1329 GEN_ERROR("LLVM functions cannot return aggregate types!");
1333 $$ = new PATypeHolder(Type::VoidTy);
1337 ArgTypeList : ArgType {
1338 $$ = new TypeWithAttrsList();
1342 | ArgTypeList ',' ArgType {
1343 ($$=$1)->push_back($3);
1350 | ArgTypeList ',' DOTDOTDOT {
1352 TypeWithAttrs TWA; TWA.Attrs = FunctionType::NoAttributeSet;
1353 TWA.Ty = new PATypeHolder(Type::VoidTy);
1358 $$ = new TypeWithAttrsList;
1359 TypeWithAttrs TWA; TWA.Attrs = FunctionType::NoAttributeSet;
1360 TWA.Ty = new PATypeHolder(Type::VoidTy);
1365 $$ = new TypeWithAttrsList();
1369 // TypeList - Used for struct declarations and as a basis for function type
1370 // declaration type lists
1373 $$ = new std::list<PATypeHolder>();
1374 $$->push_back(*$1); delete $1;
1377 | TypeListI ',' Types {
1378 ($$=$1)->push_back(*$3); delete $3;
1382 // ConstVal - The various declarations that go into the constant pool. This
1383 // production is used ONLY to represent constants that show up AFTER a 'const',
1384 // 'constant' or 'global' token at global scope. Constants that can be inlined
1385 // into other expressions (such as integers and constexprs) are handled by the
1386 // ResolvedVal, ValueRef and ConstValueRef productions.
1388 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1389 if (!UpRefs.empty())
1390 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1391 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1393 GEN_ERROR("Cannot make array constant with type: '" +
1394 (*$1)->getDescription() + "'!");
1395 const Type *ETy = ATy->getElementType();
1396 int NumElements = ATy->getNumElements();
1398 // Verify that we have the correct size...
1399 if (NumElements != -1 && NumElements != (int)$3->size())
1400 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1401 utostr($3->size()) + " arguments, but has size of " +
1402 itostr(NumElements) + "!");
1404 // Verify all elements are correct type!
1405 for (unsigned i = 0; i < $3->size(); i++) {
1406 if (ETy != (*$3)[i]->getType())
1407 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1408 ETy->getDescription() +"' as required!\nIt is of type '"+
1409 (*$3)[i]->getType()->getDescription() + "'.");
1412 $$ = ConstantArray::get(ATy, *$3);
1413 delete $1; delete $3;
1417 if (!UpRefs.empty())
1418 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1419 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1421 GEN_ERROR("Cannot make array constant with type: '" +
1422 (*$1)->getDescription() + "'!");
1424 int NumElements = ATy->getNumElements();
1425 if (NumElements != -1 && NumElements != 0)
1426 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1427 " arguments, but has size of " + itostr(NumElements) +"!");
1428 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1432 | Types 'c' STRINGCONSTANT {
1433 if (!UpRefs.empty())
1434 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1435 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1437 GEN_ERROR("Cannot make array constant with type: '" +
1438 (*$1)->getDescription() + "'!");
1440 int NumElements = ATy->getNumElements();
1441 const Type *ETy = ATy->getElementType();
1442 char *EndStr = UnEscapeLexed($3, true);
1443 if (NumElements != -1 && NumElements != (EndStr-$3))
1444 GEN_ERROR("Can't build string constant of size " +
1445 itostr((int)(EndStr-$3)) +
1446 " when array has size " + itostr(NumElements) + "!");
1447 std::vector<Constant*> Vals;
1448 if (ETy == Type::Int8Ty) {
1449 for (unsigned char *C = (unsigned char *)$3;
1450 C != (unsigned char*)EndStr; ++C)
1451 Vals.push_back(ConstantInt::get(ETy, *C));
1454 GEN_ERROR("Cannot build string arrays of non byte sized elements!");
1457 $$ = ConstantArray::get(ATy, Vals);
1461 | Types '<' ConstVector '>' { // Nonempty unsized arr
1462 if (!UpRefs.empty())
1463 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1464 const PackedType *PTy = dyn_cast<PackedType>($1->get());
1466 GEN_ERROR("Cannot make packed constant with type: '" +
1467 (*$1)->getDescription() + "'!");
1468 const Type *ETy = PTy->getElementType();
1469 int NumElements = PTy->getNumElements();
1471 // Verify that we have the correct size...
1472 if (NumElements != -1 && NumElements != (int)$3->size())
1473 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1474 utostr($3->size()) + " arguments, but has size of " +
1475 itostr(NumElements) + "!");
1477 // Verify all elements are correct type!
1478 for (unsigned i = 0; i < $3->size(); i++) {
1479 if (ETy != (*$3)[i]->getType())
1480 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1481 ETy->getDescription() +"' as required!\nIt is of type '"+
1482 (*$3)[i]->getType()->getDescription() + "'.");
1485 $$ = ConstantPacked::get(PTy, *$3);
1486 delete $1; delete $3;
1489 | Types '{' ConstVector '}' {
1490 const StructType *STy = dyn_cast<StructType>($1->get());
1492 GEN_ERROR("Cannot make struct constant with type: '" +
1493 (*$1)->getDescription() + "'!");
1495 if ($3->size() != STy->getNumContainedTypes())
1496 GEN_ERROR("Illegal number of initializers for structure type!");
1498 // Check to ensure that constants are compatible with the type initializer!
1499 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1500 if ((*$3)[i]->getType() != STy->getElementType(i))
1501 GEN_ERROR("Expected type '" +
1502 STy->getElementType(i)->getDescription() +
1503 "' for element #" + utostr(i) +
1504 " of structure initializer!");
1506 $$ = ConstantStruct::get(STy, *$3);
1507 delete $1; delete $3;
1511 if (!UpRefs.empty())
1512 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1513 const StructType *STy = dyn_cast<StructType>($1->get());
1515 GEN_ERROR("Cannot make struct constant with type: '" +
1516 (*$1)->getDescription() + "'!");
1518 if (STy->getNumContainedTypes() != 0)
1519 GEN_ERROR("Illegal number of initializers for structure type!");
1521 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1526 if (!UpRefs.empty())
1527 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1528 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1530 GEN_ERROR("Cannot make null pointer constant with type: '" +
1531 (*$1)->getDescription() + "'!");
1533 $$ = ConstantPointerNull::get(PTy);
1538 if (!UpRefs.empty())
1539 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1540 $$ = UndefValue::get($1->get());
1544 | Types SymbolicValueRef {
1545 if (!UpRefs.empty())
1546 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1547 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1549 GEN_ERROR("Global const reference must be a pointer type!");
1551 // ConstExprs can exist in the body of a function, thus creating
1552 // GlobalValues whenever they refer to a variable. Because we are in
1553 // the context of a function, getValNonImprovising will search the functions
1554 // symbol table instead of the module symbol table for the global symbol,
1555 // which throws things all off. To get around this, we just tell
1556 // getValNonImprovising that we are at global scope here.
1558 Function *SavedCurFn = CurFun.CurrentFunction;
1559 CurFun.CurrentFunction = 0;
1561 Value *V = getValNonImprovising(Ty, $2);
1564 CurFun.CurrentFunction = SavedCurFn;
1566 // If this is an initializer for a constant pointer, which is referencing a
1567 // (currently) undefined variable, create a stub now that shall be replaced
1568 // in the future with the right type of variable.
1571 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1572 const PointerType *PT = cast<PointerType>(Ty);
1574 // First check to see if the forward references value is already created!
1575 PerModuleInfo::GlobalRefsType::iterator I =
1576 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1578 if (I != CurModule.GlobalRefs.end()) {
1579 V = I->second; // Placeholder already exists, use it...
1583 if ($2.Type == ValID::NameVal) Name = $2.Name;
1585 // Create the forward referenced global.
1587 if (const FunctionType *FTy =
1588 dyn_cast<FunctionType>(PT->getElementType())) {
1589 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1590 CurModule.CurrentModule);
1592 GV = new GlobalVariable(PT->getElementType(), false,
1593 GlobalValue::ExternalLinkage, 0,
1594 Name, CurModule.CurrentModule);
1597 // Keep track of the fact that we have a forward ref to recycle it
1598 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1603 $$ = cast<GlobalValue>(V);
1604 delete $1; // Free the type handle
1608 if (!UpRefs.empty())
1609 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1610 if ($1->get() != $2->getType())
1611 GEN_ERROR("Mismatched types for constant expression: " +
1612 (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1617 | Types ZEROINITIALIZER {
1618 if (!UpRefs.empty())
1619 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1620 const Type *Ty = $1->get();
1621 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1622 GEN_ERROR("Cannot create a null initialized value of this type!");
1623 $$ = Constant::getNullValue(Ty);
1627 | IntType ESINT64VAL { // integral constants
1628 if (!ConstantInt::isValueValidForType($1, $2))
1629 GEN_ERROR("Constant value doesn't fit in type!");
1630 $$ = ConstantInt::get($1, $2);
1633 | IntType EUINT64VAL { // integral constants
1634 if (!ConstantInt::isValueValidForType($1, $2))
1635 GEN_ERROR("Constant value doesn't fit in type!");
1636 $$ = ConstantInt::get($1, $2);
1639 | BOOL TRUETOK { // Boolean constants
1640 $$ = ConstantBool::getTrue();
1643 | BOOL FALSETOK { // Boolean constants
1644 $$ = ConstantBool::getFalse();
1647 | FPType FPVAL { // Float & Double constants
1648 if (!ConstantFP::isValueValidForType($1, $2))
1649 GEN_ERROR("Floating point constant invalid for type!!");
1650 $$ = ConstantFP::get($1, $2);
1655 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1656 if (!UpRefs.empty())
1657 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1659 const Type *Ty = $5->get();
1660 if (!Val->getType()->isFirstClassType())
1661 GEN_ERROR("cast constant expression from a non-primitive type: '" +
1662 Val->getType()->getDescription() + "'!");
1663 if (!Ty->isFirstClassType())
1664 GEN_ERROR("cast constant expression to a non-primitive type: '" +
1665 Ty->getDescription() + "'!");
1666 $$ = ConstantExpr::getCast($1, $3, $5->get());
1669 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1670 if (!isa<PointerType>($3->getType()))
1671 GEN_ERROR("GetElementPtr requires a pointer operand!");
1674 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1676 GEN_ERROR("Index list invalid for constant getelementptr!");
1678 std::vector<Constant*> IdxVec;
1679 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1680 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1681 IdxVec.push_back(C);
1683 GEN_ERROR("Indices to constant getelementptr must be constants!");
1687 $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1690 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1691 if ($3->getType() != Type::BoolTy)
1692 GEN_ERROR("Select condition must be of boolean type!");
1693 if ($5->getType() != $7->getType())
1694 GEN_ERROR("Select operand types must match!");
1695 $$ = ConstantExpr::getSelect($3, $5, $7);
1698 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1699 if ($3->getType() != $5->getType())
1700 GEN_ERROR("Binary operator types must match!");
1702 $$ = ConstantExpr::get($1, $3, $5);
1704 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1705 if ($3->getType() != $5->getType())
1706 GEN_ERROR("Logical operator types must match!");
1707 if (!$3->getType()->isIntegral()) {
1708 if (!isa<PackedType>($3->getType()) ||
1709 !cast<PackedType>($3->getType())->getElementType()->isIntegral())
1710 GEN_ERROR("Logical operator requires integral operands!");
1712 $$ = ConstantExpr::get($1, $3, $5);
1715 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1716 if ($4->getType() != $6->getType())
1717 GEN_ERROR("icmp operand types must match!");
1718 $$ = ConstantExpr::getICmp($2, $4, $6);
1720 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1721 if ($4->getType() != $6->getType())
1722 GEN_ERROR("fcmp operand types must match!");
1723 $$ = ConstantExpr::getFCmp($2, $4, $6);
1725 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1726 if ($5->getType() != Type::Int8Ty)
1727 GEN_ERROR("Shift count for shift constant must be i8 type!");
1728 if (!$3->getType()->isInteger())
1729 GEN_ERROR("Shift constant expression requires integer operand!");
1731 $$ = ConstantExpr::get($1, $3, $5);
1734 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1735 if (!ExtractElementInst::isValidOperands($3, $5))
1736 GEN_ERROR("Invalid extractelement operands!");
1737 $$ = ConstantExpr::getExtractElement($3, $5);
1740 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1741 if (!InsertElementInst::isValidOperands($3, $5, $7))
1742 GEN_ERROR("Invalid insertelement operands!");
1743 $$ = ConstantExpr::getInsertElement($3, $5, $7);
1746 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1747 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1748 GEN_ERROR("Invalid shufflevector operands!");
1749 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1754 // ConstVector - A list of comma separated constants.
1755 ConstVector : ConstVector ',' ConstVal {
1756 ($$ = $1)->push_back($3);
1760 $$ = new std::vector<Constant*>();
1766 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1767 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1770 //===----------------------------------------------------------------------===//
1771 // Rules to match Modules
1772 //===----------------------------------------------------------------------===//
1774 // Module rule: Capture the result of parsing the whole file into a result
1779 $$ = ParserResult = CurModule.CurrentModule;
1780 CurModule.ModuleDone();
1784 $$ = ParserResult = CurModule.CurrentModule;
1785 CurModule.ModuleDone();
1792 | DefinitionList Definition
1796 : DEFINE { CurFun.isDeclare = false } Function {
1797 CurFun.FunctionDone();
1800 | DECLARE { CurFun.isDeclare = true; } FunctionProto {
1803 | MODULE ASM_TOK AsmBlock {
1807 // Emit an error if there are any unresolved types left.
1808 if (!CurModule.LateResolveTypes.empty()) {
1809 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
1810 if (DID.Type == ValID::NameVal) {
1811 GEN_ERROR("Reference to an undefined type: '"+DID.getName() + "'");
1813 GEN_ERROR("Reference to an undefined type: #" + itostr(DID.Num));
1818 | OptAssign TYPE Types {
1819 if (!UpRefs.empty())
1820 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
1821 // Eagerly resolve types. This is not an optimization, this is a
1822 // requirement that is due to the fact that we could have this:
1824 // %list = type { %list * }
1825 // %list = type { %list * } ; repeated type decl
1827 // If types are not resolved eagerly, then the two types will not be
1828 // determined to be the same type!
1830 ResolveTypeTo($1, *$3);
1832 if (!setTypeName(*$3, $1) && !$1) {
1834 // If this is a named type that is not a redefinition, add it to the slot
1836 CurModule.Types.push_back(*$3);
1842 | OptAssign TYPE VOID {
1843 ResolveTypeTo($1, $3);
1845 if (!setTypeName($3, $1) && !$1) {
1847 // If this is a named type that is not a redefinition, add it to the slot
1849 CurModule.Types.push_back($3);
1853 | OptAssign GlobalType ConstVal { /* "Externally Visible" Linkage */
1855 GEN_ERROR("Global value initializer is not a constant!");
1856 CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage, $2,
1859 } GlobalVarAttributes {
1862 | OptAssign GVInternalLinkage GlobalType ConstVal {
1864 GEN_ERROR("Global value initializer is not a constant!");
1865 CurGV = ParseGlobalVariable($1, $2, $3, $4->getType(), $4);
1867 } GlobalVarAttributes {
1870 | OptAssign GVExternalLinkage GlobalType Types {
1871 if (!UpRefs.empty())
1872 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
1873 CurGV = ParseGlobalVariable($1, $2, $3, *$4, 0);
1876 } GlobalVarAttributes {
1880 | TARGET TargetDefinition {
1883 | DEPLIBS '=' LibrariesDefinition {
1889 AsmBlock : STRINGCONSTANT {
1890 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
1891 char *EndStr = UnEscapeLexed($1, true);
1892 std::string NewAsm($1, EndStr);
1895 if (AsmSoFar.empty())
1896 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
1898 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
1902 BigOrLittle : BIG { $$ = Module::BigEndian; };
1903 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1905 TargetDefinition : ENDIAN '=' BigOrLittle {
1906 CurModule.CurrentModule->setEndianness($3);
1909 | POINTERSIZE '=' EUINT64VAL {
1911 CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1913 CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1915 GEN_ERROR("Invalid pointer size: '" + utostr($3) + "'!");
1918 | TRIPLE '=' STRINGCONSTANT {
1919 CurModule.CurrentModule->setTargetTriple($3);
1922 | DATALAYOUT '=' STRINGCONSTANT {
1923 CurModule.CurrentModule->setDataLayout($3);
1927 LibrariesDefinition : '[' LibList ']';
1929 LibList : LibList ',' STRINGCONSTANT {
1930 CurModule.CurrentModule->addLibrary($3);
1935 CurModule.CurrentModule->addLibrary($1);
1939 | /* empty: end of list */ {
1944 //===----------------------------------------------------------------------===//
1945 // Rules to match Function Headers
1946 //===----------------------------------------------------------------------===//
1948 Name : VAR_ID | STRINGCONSTANT;
1949 OptName : Name | /*empty*/ { $$ = 0; };
1951 ArgListH : ArgListH ',' Types OptParamAttrs OptName {
1952 if (!UpRefs.empty())
1953 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
1954 if (*$3 == Type::VoidTy)
1955 GEN_ERROR("void typed arguments are invalid!");
1956 ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
1961 | Types OptParamAttrs OptName {
1962 if (!UpRefs.empty())
1963 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1964 if (*$1 == Type::VoidTy)
1965 GEN_ERROR("void typed arguments are invalid!");
1966 ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
1967 $$ = new ArgListType;
1972 ArgList : ArgListH {
1976 | ArgListH ',' DOTDOTDOT {
1978 struct ArgListEntry E;
1979 E.Ty = new PATypeHolder(Type::VoidTy);
1981 E.Attrs = FunctionType::NoAttributeSet;
1986 $$ = new ArgListType;
1987 struct ArgListEntry E;
1988 E.Ty = new PATypeHolder(Type::VoidTy);
1990 E.Attrs = FunctionType::NoAttributeSet;
1999 FunctionHeaderH : OptCallingConv ResultTypes Name '(' ArgList ')'
2000 OptFuncAttrs OptSection OptAlign {
2002 std::string FunctionName($3);
2003 free($3); // Free strdup'd memory!
2005 // Check the function result for abstractness if this is a define. We should
2006 // have no abstract types at this point
2007 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($2))
2008 GEN_ERROR("Reference to abstract result: "+ $2->get()->getDescription());
2010 std::vector<const Type*> ParamTypeList;
2011 std::vector<FunctionType::ParameterAttributes> ParamAttrs;
2012 ParamAttrs.push_back($7);
2013 if ($5) { // If there are arguments...
2014 for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I) {
2015 const Type* Ty = I->Ty->get();
2016 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2017 GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2018 ParamTypeList.push_back(Ty);
2019 if (Ty != Type::VoidTy)
2020 ParamAttrs.push_back(I->Attrs);
2024 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2025 if (isVarArg) ParamTypeList.pop_back();
2027 FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg,
2029 const PointerType *PFT = PointerType::get(FT);
2033 if (!FunctionName.empty()) {
2034 ID = ValID::create((char*)FunctionName.c_str());
2036 ID = ValID::create((int)CurModule.Values[PFT].size());
2040 // See if this function was forward referenced. If so, recycle the object.
2041 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2042 // Move the function to the end of the list, from whereever it was
2043 // previously inserted.
2044 Fn = cast<Function>(FWRef);
2045 CurModule.CurrentModule->getFunctionList().remove(Fn);
2046 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2047 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2048 (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
2049 // If this is the case, either we need to be a forward decl, or it needs
2051 if (!CurFun.isDeclare && !Fn->isExternal())
2052 GEN_ERROR("Redefinition of function '" + FunctionName + "'!");
2054 // Make sure to strip off any argument names so we can't get conflicts.
2055 if (Fn->isExternal())
2056 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2059 } else { // Not already defined?
2060 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
2061 CurModule.CurrentModule);
2063 InsertValue(Fn, CurModule.Values);
2066 CurFun.FunctionStart(Fn);
2068 if (CurFun.isDeclare) {
2069 // If we have declaration, always overwrite linkage. This will allow us to
2070 // correctly handle cases, when pointer to function is passed as argument to
2071 // another function.
2072 Fn->setLinkage(CurFun.Linkage);
2074 Fn->setCallingConv($1);
2075 Fn->setAlignment($9);
2081 // Add all of the arguments we parsed to the function...
2082 if ($5) { // Is null if empty...
2083 if (isVarArg) { // Nuke the last entry
2084 assert($5->back().Ty->get() == Type::VoidTy && $5->back().Name == 0&&
2085 "Not a varargs marker!");
2086 delete $5->back().Ty;
2087 $5->pop_back(); // Delete the last entry
2089 Function::arg_iterator ArgIt = Fn->arg_begin();
2091 for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I, ++ArgIt) {
2092 delete I->Ty; // Delete the typeholder...
2093 setValueName(ArgIt, I->Name); // Insert arg into symtab...
2099 delete $5; // We're now done with the argument list
2104 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2106 FunctionHeader : FunctionDefineLinkage FunctionHeaderH BEGIN {
2107 $$ = CurFun.CurrentFunction;
2109 // Make sure that we keep track of the linkage type even if there was a
2110 // previous "declare".
2114 END : ENDTOK | '}'; // Allow end of '}' to end a function
2116 Function : BasicBlockList END {
2121 FunctionProto : FunctionDeclareLinkage FunctionHeaderH {
2122 CurFun.CurrentFunction->setLinkage($1);
2123 $$ = CurFun.CurrentFunction;
2124 CurFun.FunctionDone();
2128 //===----------------------------------------------------------------------===//
2129 // Rules to match Basic Blocks
2130 //===----------------------------------------------------------------------===//
2132 OptSideEffect : /* empty */ {
2141 ConstValueRef : ESINT64VAL { // A reference to a direct constant
2142 $$ = ValID::create($1);
2146 $$ = ValID::create($1);
2149 | FPVAL { // Perhaps it's an FP constant?
2150 $$ = ValID::create($1);
2154 $$ = ValID::create(ConstantBool::getTrue());
2158 $$ = ValID::create(ConstantBool::getFalse());
2162 $$ = ValID::createNull();
2166 $$ = ValID::createUndef();
2169 | ZEROINITIALIZER { // A vector zero constant.
2170 $$ = ValID::createZeroInit();
2173 | '<' ConstVector '>' { // Nonempty unsized packed vector
2174 const Type *ETy = (*$2)[0]->getType();
2175 int NumElements = $2->size();
2177 PackedType* pt = PackedType::get(ETy, NumElements);
2178 PATypeHolder* PTy = new PATypeHolder(
2186 // Verify all elements are correct type!
2187 for (unsigned i = 0; i < $2->size(); i++) {
2188 if (ETy != (*$2)[i]->getType())
2189 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2190 ETy->getDescription() +"' as required!\nIt is of type '" +
2191 (*$2)[i]->getType()->getDescription() + "'.");
2194 $$ = ValID::create(ConstantPacked::get(pt, *$2));
2195 delete PTy; delete $2;
2199 $$ = ValID::create($1);
2202 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2203 char *End = UnEscapeLexed($3, true);
2204 std::string AsmStr = std::string($3, End);
2205 End = UnEscapeLexed($5, true);
2206 std::string Constraints = std::string($5, End);
2207 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2213 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2216 SymbolicValueRef : INTVAL { // Is it an integer reference...?
2217 $$ = ValID::create($1);
2220 | Name { // Is it a named reference...?
2221 $$ = ValID::create($1);
2225 // ValueRef - A reference to a definition... either constant or symbolic
2226 ValueRef : SymbolicValueRef | ConstValueRef;
2229 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2230 // type immediately preceeds the value reference, and allows complex constant
2231 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2232 ResolvedVal : Types ValueRef {
2233 if (!UpRefs.empty())
2234 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2235 $$ = getVal(*$1, $2);
2241 BasicBlockList : BasicBlockList BasicBlock {
2245 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2251 // Basic blocks are terminated by branching instructions:
2252 // br, br/cc, switch, ret
2254 BasicBlock : InstructionList OptAssign BBTerminatorInst {
2255 setValueName($3, $2);
2259 $1->getInstList().push_back($3);
2265 InstructionList : InstructionList Inst {
2266 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2267 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2268 if (CI2->getParent() == 0)
2269 $1->getInstList().push_back(CI2);
2270 $1->getInstList().push_back($2);
2275 $$ = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
2278 // Make sure to move the basic block to the correct location in the
2279 // function, instead of leaving it inserted wherever it was first
2281 Function::BasicBlockListType &BBL =
2282 CurFun.CurrentFunction->getBasicBlockList();
2283 BBL.splice(BBL.end(), BBL, $$);
2287 $$ = getBBVal(ValID::create($1), true);
2290 // Make sure to move the basic block to the correct location in the
2291 // function, instead of leaving it inserted wherever it was first
2293 Function::BasicBlockListType &BBL =
2294 CurFun.CurrentFunction->getBasicBlockList();
2295 BBL.splice(BBL.end(), BBL, $$);
2299 BBTerminatorInst : RET ResolvedVal { // Return with a result...
2300 $$ = new ReturnInst($2);
2303 | RET VOID { // Return with no result...
2304 $$ = new ReturnInst();
2307 | BR LABEL ValueRef { // Unconditional Branch...
2308 BasicBlock* tmpBB = getBBVal($3);
2310 $$ = new BranchInst(tmpBB);
2311 } // Conditional Branch...
2312 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2313 BasicBlock* tmpBBA = getBBVal($6);
2315 BasicBlock* tmpBBB = getBBVal($9);
2317 Value* tmpVal = getVal(Type::BoolTy, $3);
2319 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2321 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2322 Value* tmpVal = getVal($2, $3);
2324 BasicBlock* tmpBB = getBBVal($6);
2326 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2329 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2331 for (; I != E; ++I) {
2332 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2333 S->addCase(CI, I->second);
2335 GEN_ERROR("Switch case is constant, but not a simple integer!");
2340 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2341 Value* tmpVal = getVal($2, $3);
2343 BasicBlock* tmpBB = getBBVal($6);
2345 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2349 | INVOKE OptCallingConv ResultTypes ValueRef '(' ValueRefList ')' OptFuncAttrs
2350 TO LABEL ValueRef UNWIND LABEL ValueRef {
2352 // Handle the short syntax
2353 const PointerType *PFTy = 0;
2354 const FunctionType *Ty = 0;
2355 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2356 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2357 // Pull out the types of all of the arguments...
2358 std::vector<const Type*> ParamTypes;
2359 FunctionType::ParamAttrsList ParamAttrs;
2360 ParamAttrs.push_back($8);
2361 for (ValueRefList::iterator I = $6->begin(), E = $6->end(); I != E; ++I) {
2362 const Type *Ty = I->Val->getType();
2363 if (Ty == Type::VoidTy)
2364 GEN_ERROR("Short call syntax cannot be used with varargs");
2365 ParamTypes.push_back(Ty);
2366 ParamAttrs.push_back(I->Attrs);
2369 Ty = FunctionType::get($3->get(), ParamTypes, false, ParamAttrs);
2370 PFTy = PointerType::get(Ty);
2373 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2375 BasicBlock *Normal = getBBVal($11);
2377 BasicBlock *Except = getBBVal($14);
2380 // Check the arguments
2382 if ($6->empty()) { // Has no arguments?
2383 // Make sure no arguments is a good thing!
2384 if (Ty->getNumParams() != 0)
2385 GEN_ERROR("No arguments passed to a function that "
2386 "expects arguments!");
2387 } else { // Has arguments?
2388 // Loop through FunctionType's arguments and ensure they are specified
2390 FunctionType::param_iterator I = Ty->param_begin();
2391 FunctionType::param_iterator E = Ty->param_end();
2392 ValueRefList::iterator ArgI = $6->begin(), ArgE = $6->end();
2394 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2395 if (ArgI->Val->getType() != *I)
2396 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2397 (*I)->getDescription() + "'!");
2398 Args.push_back(ArgI->Val);
2401 if (Ty->isVarArg()) {
2403 for (; ArgI != ArgE; ++ArgI)
2404 Args.push_back(ArgI->Val); // push the remaining varargs
2405 } else if (I != E || ArgI != ArgE)
2406 GEN_ERROR("Invalid number of parameters detected!");
2409 // Create the InvokeInst
2410 InvokeInst *II = new InvokeInst(V, Normal, Except, Args);
2411 II->setCallingConv($2);
2417 $$ = new UnwindInst();
2421 $$ = new UnreachableInst();
2427 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2429 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
2432 GEN_ERROR("May only switch on a constant pool value!");
2434 BasicBlock* tmpBB = getBBVal($6);
2436 $$->push_back(std::make_pair(V, tmpBB));
2438 | IntType ConstValueRef ',' LABEL ValueRef {
2439 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2440 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
2444 GEN_ERROR("May only switch on a constant pool value!");
2446 BasicBlock* tmpBB = getBBVal($5);
2448 $$->push_back(std::make_pair(V, tmpBB));
2451 Inst : OptAssign InstVal {
2452 // Is this definition named?? if so, assign the name...
2453 setValueName($2, $1);
2460 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2461 if (!UpRefs.empty())
2462 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2463 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2464 Value* tmpVal = getVal(*$1, $3);
2466 BasicBlock* tmpBB = getBBVal($5);
2468 $$->push_back(std::make_pair(tmpVal, tmpBB));
2471 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2473 Value* tmpVal = getVal($1->front().first->getType(), $4);
2475 BasicBlock* tmpBB = getBBVal($6);
2477 $1->push_back(std::make_pair(tmpVal, tmpBB));
2481 ValueRefList : Types ValueRef OptParamAttrs {
2482 if (!UpRefs.empty())
2483 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2484 // Used for call and invoke instructions
2485 $$ = new ValueRefList();
2486 ValueRefListEntry E; E.Attrs = $3; E.Val = getVal($1->get(), $2);
2489 | ValueRefList ',' Types ValueRef OptParamAttrs {
2490 if (!UpRefs.empty())
2491 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2493 ValueRefListEntry E; E.Attrs = $5; E.Val = getVal($3->get(), $4);
2497 | /*empty*/ { $$ = new ValueRefList(); };
2499 IndexList // Used for gep instructions and constant expressions
2500 : /*empty*/ { $$ = new std::vector<Value*>(); }
2501 | IndexList ',' ResolvedVal {
2508 OptTailCall : TAIL CALL {
2517 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2518 if (!UpRefs.empty())
2519 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2520 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
2521 !isa<PackedType>((*$2).get()))
2523 "Arithmetic operator requires integer, FP, or packed operands!");
2524 if (isa<PackedType>((*$2).get()) &&
2525 ($1 == Instruction::URem ||
2526 $1 == Instruction::SRem ||
2527 $1 == Instruction::FRem))
2528 GEN_ERROR("U/S/FRem not supported on packed types!");
2529 Value* val1 = getVal(*$2, $3);
2531 Value* val2 = getVal(*$2, $5);
2533 $$ = BinaryOperator::create($1, val1, val2);
2535 GEN_ERROR("binary operator returned null!");
2538 | LogicalOps Types ValueRef ',' ValueRef {
2539 if (!UpRefs.empty())
2540 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2541 if (!(*$2)->isIntegral()) {
2542 if (!isa<PackedType>($2->get()) ||
2543 !cast<PackedType>($2->get())->getElementType()->isIntegral())
2544 GEN_ERROR("Logical operator requires integral operands!");
2546 Value* tmpVal1 = getVal(*$2, $3);
2548 Value* tmpVal2 = getVal(*$2, $5);
2550 $$ = BinaryOperator::create($1, tmpVal1, tmpVal2);
2552 GEN_ERROR("binary operator returned null!");
2555 | ICMP IPredicates Types ValueRef ',' ValueRef {
2556 if (!UpRefs.empty())
2557 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2558 if (isa<PackedType>((*$3).get()))
2559 GEN_ERROR("Packed types not supported by icmp instruction");
2560 Value* tmpVal1 = getVal(*$3, $4);
2562 Value* tmpVal2 = getVal(*$3, $6);
2564 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2566 GEN_ERROR("icmp operator returned null!");
2568 | FCMP FPredicates Types ValueRef ',' ValueRef {
2569 if (!UpRefs.empty())
2570 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2571 if (isa<PackedType>((*$3).get()))
2572 GEN_ERROR("Packed types not supported by fcmp instruction");
2573 Value* tmpVal1 = getVal(*$3, $4);
2575 Value* tmpVal2 = getVal(*$3, $6);
2577 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2579 GEN_ERROR("fcmp operator returned null!");
2582 cerr << "WARNING: Use of eliminated 'not' instruction:"
2583 << " Replacing with 'xor'.\n";
2585 Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
2587 GEN_ERROR("Expected integral type for not instruction!");
2589 $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
2591 GEN_ERROR("Could not create a xor instruction!");
2594 | ShiftOps ResolvedVal ',' ResolvedVal {
2595 if ($4->getType() != Type::Int8Ty)
2596 GEN_ERROR("Shift amount must be i8 type!");
2597 if (!$2->getType()->isInteger())
2598 GEN_ERROR("Shift constant expression requires integer operand!");
2600 $$ = new ShiftInst($1, $2, $4);
2603 | CastOps ResolvedVal TO Types {
2604 if (!UpRefs.empty())
2605 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2607 const Type* Ty = $4->get();
2608 if (!Val->getType()->isFirstClassType())
2609 GEN_ERROR("cast from a non-primitive type: '" +
2610 Val->getType()->getDescription() + "'!");
2611 if (!Ty->isFirstClassType())
2612 GEN_ERROR("cast to a non-primitive type: '" + Ty->getDescription() +"'!");
2613 $$ = CastInst::create($1, Val, $4->get());
2616 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2617 if ($2->getType() != Type::BoolTy)
2618 GEN_ERROR("select condition must be boolean!");
2619 if ($4->getType() != $6->getType())
2620 GEN_ERROR("select value types should match!");
2621 $$ = new SelectInst($2, $4, $6);
2624 | VAARG ResolvedVal ',' Types {
2625 if (!UpRefs.empty())
2626 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2627 $$ = new VAArgInst($2, *$4);
2631 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2632 if (!ExtractElementInst::isValidOperands($2, $4))
2633 GEN_ERROR("Invalid extractelement operands!");
2634 $$ = new ExtractElementInst($2, $4);
2637 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2638 if (!InsertElementInst::isValidOperands($2, $4, $6))
2639 GEN_ERROR("Invalid insertelement operands!");
2640 $$ = new InsertElementInst($2, $4, $6);
2643 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2644 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
2645 GEN_ERROR("Invalid shufflevector operands!");
2646 $$ = new ShuffleVectorInst($2, $4, $6);
2650 const Type *Ty = $2->front().first->getType();
2651 if (!Ty->isFirstClassType())
2652 GEN_ERROR("PHI node operands must be of first class type!");
2653 $$ = new PHINode(Ty);
2654 ((PHINode*)$$)->reserveOperandSpace($2->size());
2655 while ($2->begin() != $2->end()) {
2656 if ($2->front().first->getType() != Ty)
2657 GEN_ERROR("All elements of a PHI node must be of the same type!");
2658 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2661 delete $2; // Free the list...
2664 | OptTailCall OptCallingConv ResultTypes ValueRef '(' ValueRefList ')'
2667 // Handle the short syntax
2668 const PointerType *PFTy = 0;
2669 const FunctionType *Ty = 0;
2670 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2671 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2672 // Pull out the types of all of the arguments...
2673 std::vector<const Type*> ParamTypes;
2674 FunctionType::ParamAttrsList ParamAttrs;
2675 ParamAttrs.push_back($8);
2676 for (ValueRefList::iterator I = $6->begin(), E = $6->end(); I != E; ++I) {
2677 const Type *Ty = I->Val->getType();
2678 if (Ty == Type::VoidTy)
2679 GEN_ERROR("Short call syntax cannot be used with varargs");
2680 ParamTypes.push_back(Ty);
2681 ParamAttrs.push_back(I->Attrs);
2684 Ty = FunctionType::get($3->get(), ParamTypes, false, ParamAttrs);
2685 PFTy = PointerType::get(Ty);
2688 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2691 // Check the arguments
2693 if ($6->empty()) { // Has no arguments?
2694 // Make sure no arguments is a good thing!
2695 if (Ty->getNumParams() != 0)
2696 GEN_ERROR("No arguments passed to a function that "
2697 "expects arguments!");
2698 } else { // Has arguments?
2699 // Loop through FunctionType's arguments and ensure they are specified
2702 FunctionType::param_iterator I = Ty->param_begin();
2703 FunctionType::param_iterator E = Ty->param_end();
2704 ValueRefList::iterator ArgI = $6->begin(), ArgE = $6->end();
2706 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2707 if (ArgI->Val->getType() != *I)
2708 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2709 (*I)->getDescription() + "'!");
2710 Args.push_back(ArgI->Val);
2712 if (Ty->isVarArg()) {
2714 for (; ArgI != ArgE; ++ArgI)
2715 Args.push_back(ArgI->Val); // push the remaining varargs
2716 } else if (I != E || ArgI != ArgE)
2717 GEN_ERROR("Invalid number of parameters detected!");
2719 // Create the call node
2720 CallInst *CI = new CallInst(V, Args);
2721 CI->setTailCall($1);
2722 CI->setCallingConv($2);
2732 OptVolatile : VOLATILE {
2743 MemoryInst : MALLOC Types OptCAlign {
2744 if (!UpRefs.empty())
2745 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2746 $$ = new MallocInst(*$2, 0, $3);
2750 | MALLOC Types ',' INT32 ValueRef OptCAlign {
2751 if (!UpRefs.empty())
2752 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2753 Value* tmpVal = getVal($4, $5);
2755 $$ = new MallocInst(*$2, tmpVal, $6);
2758 | ALLOCA Types OptCAlign {
2759 if (!UpRefs.empty())
2760 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2761 $$ = new AllocaInst(*$2, 0, $3);
2765 | ALLOCA Types ',' INT32 ValueRef OptCAlign {
2766 if (!UpRefs.empty())
2767 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2768 Value* tmpVal = getVal($4, $5);
2770 $$ = new AllocaInst(*$2, tmpVal, $6);
2773 | FREE ResolvedVal {
2774 if (!isa<PointerType>($2->getType()))
2775 GEN_ERROR("Trying to free nonpointer type " +
2776 $2->getType()->getDescription() + "!");
2777 $$ = new FreeInst($2);
2781 | OptVolatile LOAD Types ValueRef {
2782 if (!UpRefs.empty())
2783 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2784 if (!isa<PointerType>($3->get()))
2785 GEN_ERROR("Can't load from nonpointer type: " +
2786 (*$3)->getDescription());
2787 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
2788 GEN_ERROR("Can't load from pointer of non-first-class type: " +
2789 (*$3)->getDescription());
2790 Value* tmpVal = getVal(*$3, $4);
2792 $$ = new LoadInst(tmpVal, "", $1);
2795 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2796 if (!UpRefs.empty())
2797 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
2798 const PointerType *PT = dyn_cast<PointerType>($5->get());
2800 GEN_ERROR("Can't store to a nonpointer type: " +
2801 (*$5)->getDescription());
2802 const Type *ElTy = PT->getElementType();
2803 if (ElTy != $3->getType())
2804 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
2805 "' into space of type '" + ElTy->getDescription() + "'!");
2807 Value* tmpVal = getVal(*$5, $6);
2809 $$ = new StoreInst($3, tmpVal, $1);
2812 | GETELEMENTPTR Types ValueRef IndexList {
2813 if (!UpRefs.empty())
2814 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2815 if (!isa<PointerType>($2->get()))
2816 GEN_ERROR("getelementptr insn requires pointer operand!");
2818 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2819 GEN_ERROR("Invalid getelementptr indices for type '" +
2820 (*$2)->getDescription()+ "'!");
2821 Value* tmpVal = getVal(*$2, $3);
2823 $$ = new GetElementPtrInst(tmpVal, *$4);
2831 // common code from the two 'RunVMAsmParser' functions
2832 static Module* RunParser(Module * M) {
2834 llvmAsmlineno = 1; // Reset the current line number...
2835 CurModule.CurrentModule = M;
2840 // Check to make sure the parser succeeded
2843 delete ParserResult;
2847 // Check to make sure that parsing produced a result
2851 // Reset ParserResult variable while saving its value for the result.
2852 Module *Result = ParserResult;
2858 void llvm::GenerateError(const std::string &message, int LineNo) {
2859 if (LineNo == -1) LineNo = llvmAsmlineno;
2860 // TODO: column number in exception
2862 TheParseError->setError(CurFilename, message, LineNo);
2866 int yyerror(const char *ErrorMsg) {
2868 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2869 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2870 std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2871 if (yychar == YYEMPTY || yychar == 0)
2872 errMsg += "end-of-file.";
2874 errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2875 GenerateError(errMsg);