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/Assembly/AutoUpgrade.h"
22 #include "llvm/Support/GetElementPtrTypeIterator.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/Support/MathExtras.h"
30 // The following is a gross hack. In order to rid the libAsmParser library of
31 // exceptions, we have to have a way of getting the yyparse function to go into
32 // an error situation. So, whenever we want an error to occur, the GenerateError
33 // function (see bottom of file) sets TriggerError. Then, at the end of each
34 // production in the grammer we use CHECK_FOR_ERROR which will invoke YYERROR
35 // (a goto) to put YACC in error state. Furthermore, several calls to
36 // GenerateError are made from inside productions and they must simulate the
37 // previous exception behavior by exiting the production immediately. We have
38 // replaced these with the GEN_ERROR macro which calls GeneratError and then
39 // immediately invokes YYERROR. This would be so much cleaner if it was a
40 // recursive descent parser.
41 static bool TriggerError = false;
42 #define CHECK_FOR_ERROR { if (TriggerError) { TriggerError = false; YYABORT; } }
43 #define GEN_ERROR(msg) { GenerateError(msg); YYERROR; }
45 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
46 int yylex(); // declaration" of xxx warnings.
50 std::string CurFilename;
54 static Module *ParserResult;
56 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
57 // relating to upreferences in the input stream.
59 //#define DEBUG_UPREFS 1
61 #define UR_OUT(X) std::cerr << X
66 #define YYERROR_VERBOSE 1
68 static bool ObsoleteVarArgs;
69 static bool NewVarArgs;
70 static BasicBlock *CurBB;
71 static GlobalVariable *CurGV;
74 // This contains info used when building the body of a function. It is
75 // destroyed when the function is completed.
77 typedef std::vector<Value *> ValueList; // Numbered defs
79 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
80 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
82 static struct PerModuleInfo {
83 Module *CurrentModule;
84 std::map<const Type *, ValueList> Values; // Module level numbered definitions
85 std::map<const Type *,ValueList> LateResolveValues;
86 std::vector<TypeInfo> Types;
87 std::map<ValID, TypeInfo> LateResolveTypes;
89 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
90 /// how they were referenced and on which line of the input they came from so
91 /// that we can resolve them later and print error messages as appropriate.
92 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
94 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
95 // references to global values. Global values may be referenced before they
96 // are defined, and if so, the temporary object that they represent is held
97 // here. This is used for forward references of GlobalValues.
99 typedef std::map<std::pair<const PointerType *,
100 ValID>, GlobalValue*> GlobalRefsType;
101 GlobalRefsType GlobalRefs;
104 // If we could not resolve some functions at function compilation time
105 // (calls to functions before they are defined), resolve them now... Types
106 // are resolved when the constant pool has been completely parsed.
108 ResolveDefinitions(LateResolveValues);
112 // Check to make sure that all global value forward references have been
115 if (!GlobalRefs.empty()) {
116 std::string UndefinedReferences = "Unresolved global references exist:\n";
118 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
120 UndefinedReferences += " " + I->first.first->getDescription() + " " +
121 I->first.second.getName() + "\n";
123 GenerateError(UndefinedReferences);
127 // Look for intrinsic functions and CallInst that need to be upgraded
128 for (Module::iterator FI = CurrentModule->begin(),
129 FE = CurrentModule->end(); FI != FE; )
130 UpgradeCallsToIntrinsic(FI++);
132 Values.clear(); // Clear out function local definitions
137 // GetForwardRefForGlobal - Check to see if there is a forward reference
138 // for this global. If so, remove it from the GlobalRefs map and return it.
139 // If not, just return null.
140 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
141 // Check to see if there is a forward reference to this global variable...
142 // if there is, eliminate it and patch the reference to use the new def'n.
143 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
144 GlobalValue *Ret = 0;
145 if (I != GlobalRefs.end()) {
153 static struct PerFunctionInfo {
154 Function *CurrentFunction; // Pointer to current function being created
156 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
157 std::map<const Type*, ValueList> LateResolveValues;
158 bool isDeclare; // Is this function a forward declararation?
159 GlobalValue::LinkageTypes Linkage; // Linkage for forward declaration.
161 /// BBForwardRefs - When we see forward references to basic blocks, keep
162 /// track of them here.
163 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
164 std::vector<BasicBlock*> NumberedBlocks;
167 inline PerFunctionInfo() {
170 Linkage = GlobalValue::ExternalLinkage;
173 inline void FunctionStart(Function *M) {
178 void FunctionDone() {
179 NumberedBlocks.clear();
181 // Any forward referenced blocks left?
182 if (!BBForwardRefs.empty()) {
183 GenerateError("Undefined reference to label " +
184 BBForwardRefs.begin()->first->getName());
188 // Resolve all forward references now.
189 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
191 Values.clear(); // Clear out function local definitions
194 Linkage = GlobalValue::ExternalLinkage;
196 } CurFun; // Info for the current function...
198 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
201 //===----------------------------------------------------------------------===//
202 // Code to handle definitions of all the types
203 //===----------------------------------------------------------------------===//
205 static int InsertValue(Value *V,
206 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
207 if (V->hasName()) return -1; // Is this a numbered definition?
209 // Yes, insert the value into the value table...
210 ValueList &List = ValueTab[V->getType()];
212 return List.size()-1;
215 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
217 case ValID::NumberVal: // Is it a numbered definition?
218 // Module constants occupy the lowest numbered slots...
219 if ((unsigned)D.Num < CurModule.Types.size())
220 return CurModule.Types[(unsigned)D.Num].type->get();
222 case ValID::NameVal: // Is it a named definition?
223 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
224 D.destroy(); // Free old strdup'd memory...
229 GenerateError("Internal parser error: Invalid symbol type reference!");
233 // If we reached here, we referenced either a symbol that we don't know about
234 // or an id number that hasn't been read yet. We may be referencing something
235 // forward, so just create an entry to be resolved later and get to it...
237 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
240 if (inFunctionScope()) {
241 if (D.Type == ValID::NameVal) {
242 GenerateError("Reference to an undefined type: '" + D.getName() + "'");
245 GenerateError("Reference to an undefined type: #" + itostr(D.Num));
250 std::map<ValID, TypeInfo>::iterator I =CurModule.LateResolveTypes.find(D);
251 if (I != CurModule.LateResolveTypes.end())
252 return I->second.type->get();
255 TI.type = new PATypeHolder(OpaqueType::get());
256 TI.signedness = isSignless;
257 CurModule.LateResolveTypes.insert(std::make_pair(D, TI));
258 return TI.type->get();
261 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
262 SymbolTable &SymTab =
263 inFunctionScope() ? CurFun.CurrentFunction->getSymbolTable() :
264 CurModule.CurrentModule->getSymbolTable();
265 return SymTab.lookup(Ty, Name);
268 // getValNonImprovising - Look up the value specified by the provided type and
269 // the provided ValID. If the value exists and has already been defined, return
270 // it. Otherwise return null.
272 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
273 if (isa<FunctionType>(Ty)) {
274 GenerateError("Functions are not values and "
275 "must be referenced as pointers");
280 case ValID::NumberVal: { // Is it a numbered definition?
281 unsigned Num = (unsigned)D.Num;
283 // Module constants occupy the lowest numbered slots...
284 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
285 if (VI != CurModule.Values.end()) {
286 if (Num < VI->second.size())
287 return VI->second[Num];
288 Num -= VI->second.size();
291 // Make sure that our type is within bounds
292 VI = CurFun.Values.find(Ty);
293 if (VI == CurFun.Values.end()) return 0;
295 // Check that the number is within bounds...
296 if (VI->second.size() <= Num) return 0;
298 return VI->second[Num];
301 case ValID::NameVal: { // Is it a named definition?
302 Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
303 if (N == 0) return 0;
305 D.destroy(); // Free old strdup'd memory...
309 // Check to make sure that "Ty" is an integral type, and that our
310 // value will fit into the specified type...
311 case ValID::ConstSIntVal: // Is it a constant pool reference??
312 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
313 GenerateError("Signed integral constant '" +
314 itostr(D.ConstPool64) + "' is invalid for type '" +
315 Ty->getDescription() + "'!");
318 return ConstantInt::get(Ty, D.ConstPool64);
320 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
321 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
322 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
323 GenerateError("Integral constant '" + utostr(D.UConstPool64) +
324 "' is invalid or out of range!");
326 } else { // This is really a signed reference. Transmogrify.
327 return ConstantInt::get(Ty, D.ConstPool64);
330 return ConstantInt::get(Ty, D.UConstPool64);
333 case ValID::ConstFPVal: // Is it a floating point const pool reference?
334 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP)) {
335 GenerateError("FP constant invalid for type!!");
338 return ConstantFP::get(Ty, D.ConstPoolFP);
340 case ValID::ConstNullVal: // Is it a null value?
341 if (!isa<PointerType>(Ty)) {
342 GenerateError("Cannot create a a non pointer null!");
345 return ConstantPointerNull::get(cast<PointerType>(Ty));
347 case ValID::ConstUndefVal: // Is it an undef value?
348 return UndefValue::get(Ty);
350 case ValID::ConstZeroVal: // Is it a zero value?
351 return Constant::getNullValue(Ty);
353 case ValID::ConstantVal: // Fully resolved constant?
354 if (D.ConstantValue->getType() != Ty) {
355 GenerateError("Constant expression type different from required type!");
358 return D.ConstantValue;
360 case ValID::InlineAsmVal: { // Inline asm expression
361 const PointerType *PTy = dyn_cast<PointerType>(Ty);
362 const FunctionType *FTy =
363 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
364 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
365 GenerateError("Invalid type for asm constraint string!");
368 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
369 D.IAD->HasSideEffects);
370 D.destroy(); // Free InlineAsmDescriptor.
374 assert(0 && "Unhandled case!");
378 assert(0 && "Unhandled case!");
382 // getVal - This function is identical to getValNonImprovising, except that if a
383 // value is not already defined, it "improvises" by creating a placeholder var
384 // that looks and acts just like the requested variable. When the value is
385 // defined later, all uses of the placeholder variable are replaced with the
388 static Value *getVal(const Type *Ty, const ValID &ID) {
389 if (Ty == Type::LabelTy) {
390 GenerateError("Cannot use a basic block here");
394 // See if the value has already been defined.
395 Value *V = getValNonImprovising(Ty, ID);
397 if (TriggerError) return 0;
399 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
400 GenerateError("Invalid use of a composite type!");
404 // If we reached here, we referenced either a symbol that we don't know about
405 // or an id number that hasn't been read yet. We may be referencing something
406 // forward, so just create an entry to be resolved later and get to it...
408 V = new Argument(Ty);
410 // Remember where this forward reference came from. FIXME, shouldn't we try
411 // to recycle these things??
412 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
415 if (inFunctionScope())
416 InsertValue(V, CurFun.LateResolveValues);
418 InsertValue(V, CurModule.LateResolveValues);
422 /// getBBVal - This is used for two purposes:
423 /// * If isDefinition is true, a new basic block with the specified ID is being
425 /// * If isDefinition is true, this is a reference to a basic block, which may
426 /// or may not be a forward reference.
428 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
429 assert(inFunctionScope() && "Can't get basic block at global scope!");
435 GenerateError("Illegal label reference " + ID.getName());
437 case ValID::NumberVal: // Is it a numbered definition?
438 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
439 CurFun.NumberedBlocks.resize(ID.Num+1);
440 BB = CurFun.NumberedBlocks[ID.Num];
442 case ValID::NameVal: // Is it a named definition?
444 if (Value *N = CurFun.CurrentFunction->
445 getSymbolTable().lookup(Type::LabelTy, Name))
446 BB = cast<BasicBlock>(N);
450 // See if the block has already been defined.
452 // If this is the definition of the block, make sure the existing value was
453 // just a forward reference. If it was a forward reference, there will be
454 // an entry for it in the PlaceHolderInfo map.
455 if (isDefinition && !CurFun.BBForwardRefs.erase(BB)) {
456 // The existing value was a definition, not a forward reference.
457 GenerateError("Redefinition of label " + ID.getName());
461 ID.destroy(); // Free strdup'd memory.
465 // Otherwise this block has not been seen before.
466 BB = new BasicBlock("", CurFun.CurrentFunction);
467 if (ID.Type == ValID::NameVal) {
468 BB->setName(ID.Name);
470 CurFun.NumberedBlocks[ID.Num] = BB;
473 // If this is not a definition, keep track of it so we can use it as a forward
476 // Remember where this forward reference came from.
477 CurFun.BBForwardRefs[BB] = std::make_pair(ID, llvmAsmlineno);
479 // The forward declaration could have been inserted anywhere in the
480 // function: insert it into the correct place now.
481 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
482 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
489 //===----------------------------------------------------------------------===//
490 // Code to handle forward references in instructions
491 //===----------------------------------------------------------------------===//
493 // This code handles the late binding needed with statements that reference
494 // values not defined yet... for example, a forward branch, or the PHI node for
497 // This keeps a table (CurFun.LateResolveValues) of all such forward references
498 // and back patchs after we are done.
501 // ResolveDefinitions - If we could not resolve some defs at parsing
502 // time (forward branches, phi functions for loops, etc...) resolve the
506 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
507 std::map<const Type*,ValueList> *FutureLateResolvers) {
508 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
509 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
510 E = LateResolvers.end(); LRI != E; ++LRI) {
511 ValueList &List = LRI->second;
512 while (!List.empty()) {
513 Value *V = List.back();
516 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
517 CurModule.PlaceHolderInfo.find(V);
518 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
520 ValID &DID = PHI->second.first;
522 Value *TheRealValue = getValNonImprovising(LRI->first, DID);
526 V->replaceAllUsesWith(TheRealValue);
528 CurModule.PlaceHolderInfo.erase(PHI);
529 } else if (FutureLateResolvers) {
530 // Functions have their unresolved items forwarded to the module late
532 InsertValue(V, *FutureLateResolvers);
534 if (DID.Type == ValID::NameVal) {
535 GenerateError("Reference to an invalid definition: '" +DID.getName()+
536 "' of type '" + V->getType()->getDescription() + "'",
540 GenerateError("Reference to an invalid definition: #" +
541 itostr(DID.Num) + " of type '" +
542 V->getType()->getDescription() + "'",
550 LateResolvers.clear();
553 // ResolveTypeTo - A brand new type was just declared. This means that (if
554 // name is not null) things referencing Name can be resolved. Otherwise, things
555 // refering to the number can be resolved. Do this now.
557 static void ResolveTypeTo(char *Name, const Type *ToTy) {
559 if (Name) D = ValID::create(Name);
560 else D = ValID::create((int)CurModule.Types.size());
562 std::map<ValID, TypeInfo>::iterator I =
563 CurModule.LateResolveTypes.find(D);
564 if (I != CurModule.LateResolveTypes.end()) {
565 ((DerivedType*)I->second.type->get())->refineAbstractTypeTo(ToTy);
566 CurModule.LateResolveTypes.erase(I);
570 // setValueName - Set the specified value to the name given. The name may be
571 // null potentially, in which case this is a noop. The string passed in is
572 // assumed to be a malloc'd string buffer, and is free'd by this function.
574 static void setValueName(Value *V, char *NameStr) {
576 std::string Name(NameStr); // Copy string
577 free(NameStr); // Free old string
579 if (V->getType() == Type::VoidTy) {
580 GenerateError("Can't assign name '" + Name+"' to value with void type!");
584 assert(inFunctionScope() && "Must be in function scope!");
585 SymbolTable &ST = CurFun.CurrentFunction->getSymbolTable();
586 if (ST.lookup(V->getType(), Name)) {
587 GenerateError("Redefinition of value named '" + Name + "' in the '" +
588 V->getType()->getDescription() + "' type plane!");
597 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
598 /// this is a declaration, otherwise it is a definition.
599 static GlobalVariable *
600 ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
601 bool isConstantGlobal, const Type *Ty,
602 Constant *Initializer) {
603 if (isa<FunctionType>(Ty)) {
604 GenerateError("Cannot declare global vars of function type!");
608 const PointerType *PTy = PointerType::get(Ty);
612 Name = NameStr; // Copy string
613 free(NameStr); // Free old string
616 // See if this global value was forward referenced. If so, recycle the
620 ID = ValID::create((char*)Name.c_str());
622 ID = ValID::create((int)CurModule.Values[PTy].size());
625 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
626 // Move the global to the end of the list, from whereever it was
627 // previously inserted.
628 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
629 CurModule.CurrentModule->getGlobalList().remove(GV);
630 CurModule.CurrentModule->getGlobalList().push_back(GV);
631 GV->setInitializer(Initializer);
632 GV->setLinkage(Linkage);
633 GV->setConstant(isConstantGlobal);
634 InsertValue(GV, CurModule.Values);
638 // If this global has a name, check to see if there is already a definition
639 // of this global in the module. If so, merge as appropriate. Note that
640 // this is really just a hack around problems in the CFE. :(
642 // We are a simple redefinition of a value, check to see if it is defined
643 // the same as the old one.
644 if (GlobalVariable *EGV =
645 CurModule.CurrentModule->getGlobalVariable(Name, Ty)) {
646 // We are allowed to redefine a global variable in two circumstances:
647 // 1. If at least one of the globals is uninitialized or
648 // 2. If both initializers have the same value.
650 if (!EGV->hasInitializer() || !Initializer ||
651 EGV->getInitializer() == Initializer) {
653 // Make sure the existing global version gets the initializer! Make
654 // sure that it also gets marked const if the new version is.
655 if (Initializer && !EGV->hasInitializer())
656 EGV->setInitializer(Initializer);
657 if (isConstantGlobal)
658 EGV->setConstant(true);
659 EGV->setLinkage(Linkage);
663 GenerateError("Redefinition of global variable named '" + Name +
664 "' in the '" + Ty->getDescription() + "' type plane!");
669 // Otherwise there is no existing GV to use, create one now.
671 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
672 CurModule.CurrentModule);
673 InsertValue(GV, CurModule.Values);
677 // setTypeName - Set the specified type to the name given. The name may be
678 // null potentially, in which case this is a noop. The string passed in is
679 // assumed to be a malloc'd string buffer, and is freed by this function.
681 // This function returns true if the type has already been defined, but is
682 // allowed to be redefined in the specified context. If the name is a new name
683 // for the type plane, it is inserted and false is returned.
684 static bool setTypeName(const Type *T, char *NameStr) {
685 assert(!inFunctionScope() && "Can't give types function-local names!");
686 if (NameStr == 0) return false;
688 std::string Name(NameStr); // Copy string
689 free(NameStr); // Free old string
691 // We don't allow assigning names to void type
692 if (T == Type::VoidTy) {
693 GenerateError("Can't assign name '" + Name + "' to the void type!");
697 // Set the type name, checking for conflicts as we do so.
698 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
700 if (AlreadyExists) { // Inserting a name that is already defined???
701 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
702 assert(Existing && "Conflict but no matching type?");
704 // There is only one case where this is allowed: when we are refining an
705 // opaque type. In this case, Existing will be an opaque type.
706 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
707 // We ARE replacing an opaque type!
708 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
712 // Otherwise, this is an attempt to redefine a type. That's okay if
713 // the redefinition is identical to the original. This will be so if
714 // Existing and T point to the same Type object. In this one case we
715 // allow the equivalent redefinition.
716 if (Existing == T) return true; // Yes, it's equal.
718 // Any other kind of (non-equivalent) redefinition is an error.
719 GenerateError("Redefinition of type named '" + Name + "' in the '" +
720 T->getDescription() + "' type plane!");
726 //===----------------------------------------------------------------------===//
727 // Code for handling upreferences in type names...
730 // TypeContains - Returns true if Ty directly contains E in it.
732 static bool TypeContains(const Type *Ty, const Type *E) {
733 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
734 E) != Ty->subtype_end();
739 // NestingLevel - The number of nesting levels that need to be popped before
740 // this type is resolved.
741 unsigned NestingLevel;
743 // LastContainedTy - This is the type at the current binding level for the
744 // type. Every time we reduce the nesting level, this gets updated.
745 const Type *LastContainedTy;
747 // UpRefTy - This is the actual opaque type that the upreference is
751 UpRefRecord(unsigned NL, OpaqueType *URTy)
752 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
756 // UpRefs - A list of the outstanding upreferences that need to be resolved.
757 static std::vector<UpRefRecord> UpRefs;
759 /// HandleUpRefs - Every time we finish a new layer of types, this function is
760 /// called. It loops through the UpRefs vector, which is a list of the
761 /// currently active types. For each type, if the up reference is contained in
762 /// the newly completed type, we decrement the level count. When the level
763 /// count reaches zero, the upreferenced type is the type that is passed in:
764 /// thus we can complete the cycle.
766 static PATypeHolder HandleUpRefs(const Type *ty) {
767 // If Ty isn't abstract, or if there are no up-references in it, then there is
768 // nothing to resolve here.
769 if (!ty->isAbstract() || UpRefs.empty()) return ty;
772 UR_OUT("Type '" << Ty->getDescription() <<
773 "' newly formed. Resolving upreferences.\n" <<
774 UpRefs.size() << " upreferences active!\n");
776 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
777 // to zero), we resolve them all together before we resolve them to Ty. At
778 // the end of the loop, if there is anything to resolve to Ty, it will be in
780 OpaqueType *TypeToResolve = 0;
782 for (unsigned i = 0; i != UpRefs.size(); ++i) {
783 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
784 << UpRefs[i].second->getDescription() << ") = "
785 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
786 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
787 // Decrement level of upreference
788 unsigned Level = --UpRefs[i].NestingLevel;
789 UpRefs[i].LastContainedTy = Ty;
790 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
791 if (Level == 0) { // Upreference should be resolved!
792 if (!TypeToResolve) {
793 TypeToResolve = UpRefs[i].UpRefTy;
795 UR_OUT(" * Resolving upreference for "
796 << UpRefs[i].second->getDescription() << "\n";
797 std::string OldName = UpRefs[i].UpRefTy->getDescription());
798 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
799 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
800 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
802 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
803 --i; // Do not skip the next element...
809 UR_OUT(" * Resolving upreference for "
810 << UpRefs[i].second->getDescription() << "\n";
811 std::string OldName = TypeToResolve->getDescription());
812 TypeToResolve->refineAbstractTypeTo(Ty);
818 /// This function is used to obtain the correct opcode for an instruction when
819 /// an obsolete opcode is encountered. The OI parameter (OpcodeInfo) has both
820 /// an opcode and an "obsolete" flag. These are generated by the lexer and
821 /// the "obsolete" member will be true when the lexer encounters the token for
822 /// an obsolete opcode. For example, "div" was replaced by [usf]div but we need
823 /// to maintain backwards compatibility for asm files that still have the "div"
824 /// instruction. This function handles converting div -> [usf]div appropriately.
825 /// @brief Convert obsolete BinaryOps opcodes to new values
827 sanitizeOpcode(OpcodeInfo<Instruction::BinaryOps> &OI, const Type *Ty)
829 // If its not obsolete, don't do anything
833 // If its a packed type we want to use the element type
834 if (const PackedType *PTy = dyn_cast<PackedType>(Ty))
835 Ty = PTy->getElementType();
837 // Depending on the opcode ..
840 GenerateError("Invalid obsolete opCode (check Lexer.l)");
842 case Instruction::UDiv:
843 // Handle cases where the opcode needs to change
844 if (Ty->isFloatingPoint())
845 OI.opcode = Instruction::FDiv;
846 else if (Ty->isSigned())
847 OI.opcode = Instruction::SDiv;
849 case Instruction::URem:
850 if (Ty->isFloatingPoint())
851 OI.opcode = Instruction::FRem;
852 else if (Ty->isSigned())
853 OI.opcode = Instruction::SRem;
856 // Its not obsolete any more, we fixed it.
860 /// This function is similar to the previous overload of sanitizeOpcode but
861 /// operates on Instruction::OtherOps instead of Instruction::BinaryOps.
862 /// @brief Convert obsolete OtherOps opcodes to new values
864 sanitizeOpcode(OpcodeInfo<Instruction::OtherOps> &OI, const Type *Ty)
866 // If its not obsolete, don't do anything
872 GenerateError("Invalid obsolete opcode (check Lexer.l)");
874 case Instruction::LShr:
876 OI.opcode = Instruction::AShr;
879 // Its not obsolete any more, we fixed it.
883 // common code from the two 'RunVMAsmParser' functions
884 static Module* RunParser(Module * M) {
886 llvmAsmlineno = 1; // Reset the current line number...
887 ObsoleteVarArgs = false;
889 CurModule.CurrentModule = M;
891 // Check to make sure the parser succeeded
898 // Check to make sure that parsing produced a result
902 // Reset ParserResult variable while saving its value for the result.
903 Module *Result = ParserResult;
906 //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
909 if ((F = Result->getNamedFunction("llvm.va_start"))
910 && F->getFunctionType()->getNumParams() == 0)
911 ObsoleteVarArgs = true;
912 if((F = Result->getNamedFunction("llvm.va_copy"))
913 && F->getFunctionType()->getNumParams() == 1)
914 ObsoleteVarArgs = true;
917 if (ObsoleteVarArgs && NewVarArgs) {
919 "This file is corrupt: it uses both new and old style varargs");
923 if(ObsoleteVarArgs) {
924 if(Function* F = Result->getNamedFunction("llvm.va_start")) {
925 if (F->arg_size() != 0) {
926 GenerateError("Obsolete va_start takes 0 argument!");
932 //bar = alloca typeof(foo)
936 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
937 const Type* ArgTy = F->getFunctionType()->getReturnType();
938 const Type* ArgTyPtr = PointerType::get(ArgTy);
939 Function* NF = Result->getOrInsertFunction("llvm.va_start",
940 RetTy, ArgTyPtr, (Type *)0);
942 while (!F->use_empty()) {
943 CallInst* CI = cast<CallInst>(F->use_back());
944 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
945 new CallInst(NF, bar, "", CI);
946 Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
947 CI->replaceAllUsesWith(foo);
948 CI->getParent()->getInstList().erase(CI);
950 Result->getFunctionList().erase(F);
953 if(Function* F = Result->getNamedFunction("llvm.va_end")) {
954 if(F->arg_size() != 1) {
955 GenerateError("Obsolete va_end takes 1 argument!");
961 //bar = alloca 1 of typeof(foo)
963 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
964 const Type* ArgTy = F->getFunctionType()->getParamType(0);
965 const Type* ArgTyPtr = PointerType::get(ArgTy);
966 Function* NF = Result->getOrInsertFunction("llvm.va_end",
967 RetTy, ArgTyPtr, (Type *)0);
969 while (!F->use_empty()) {
970 CallInst* CI = cast<CallInst>(F->use_back());
971 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
972 new StoreInst(CI->getOperand(1), bar, CI);
973 new CallInst(NF, bar, "", CI);
974 CI->getParent()->getInstList().erase(CI);
976 Result->getFunctionList().erase(F);
979 if(Function* F = Result->getNamedFunction("llvm.va_copy")) {
980 if(F->arg_size() != 1) {
981 GenerateError("Obsolete va_copy takes 1 argument!");
986 //a = alloca 1 of typeof(foo)
987 //b = alloca 1 of typeof(foo)
992 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
993 const Type* ArgTy = F->getFunctionType()->getReturnType();
994 const Type* ArgTyPtr = PointerType::get(ArgTy);
995 Function* NF = Result->getOrInsertFunction("llvm.va_copy",
996 RetTy, ArgTyPtr, ArgTyPtr,
999 while (!F->use_empty()) {
1000 CallInst* CI = cast<CallInst>(F->use_back());
1001 AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
1002 AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
1003 new StoreInst(CI->getOperand(1), b, CI);
1004 new CallInst(NF, a, b, "", CI);
1005 Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
1006 CI->replaceAllUsesWith(foo);
1007 CI->getParent()->getInstList().erase(CI);
1009 Result->getFunctionList().erase(F);
1016 //===----------------------------------------------------------------------===//
1017 // RunVMAsmParser - Define an interface to this parser
1018 //===----------------------------------------------------------------------===//
1020 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
1023 CurFilename = Filename;
1024 return RunParser(new Module(CurFilename));
1027 Module *llvm::RunVMAsmParser(const char * AsmString, Module * M) {
1028 set_scan_string(AsmString);
1030 CurFilename = "from_memory";
1032 return RunParser(new Module (CurFilename));
1034 return RunParser(M);
1041 llvm::Module *ModuleVal;
1042 llvm::Function *FunctionVal;
1043 std::pair<TypeInfo, char*> *ArgVal;
1044 llvm::BasicBlock *BasicBlockVal;
1045 llvm::TerminatorInst *TermInstVal;
1046 llvm::Instruction *InstVal;
1047 llvm::Constant *ConstVal;
1050 llvm::Value *ValueVal;
1052 std::vector<std::pair<TypeInfo,char*> >*ArgList;
1053 std::vector<llvm::Value*> *ValueList;
1054 std::list<TypeInfo> *TypeList;
1055 // Represent the RHS of PHI node
1056 std::list<std::pair<llvm::Value*,
1057 llvm::BasicBlock*> > *PHIList;
1058 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
1059 std::vector<llvm::Constant*> *ConstVector;
1061 llvm::GlobalValue::LinkageTypes Linkage;
1069 char *StrVal; // This memory is strdup'd!
1070 llvm::ValID ValIDVal; // strdup'd memory maybe!
1072 BinaryOpInfo BinaryOpVal;
1073 TermOpInfo TermOpVal;
1075 CastOpInfo CastOpVal;
1076 OtherOpInfo OtherOpVal;
1077 llvm::Module::Endianness Endianness;
1080 %type <ModuleVal> Module FunctionList
1081 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1082 %type <BasicBlockVal> BasicBlock InstructionList
1083 %type <TermInstVal> BBTerminatorInst
1084 %type <InstVal> Inst InstVal MemoryInst
1085 %type <ConstVal> ConstVal ConstExpr
1086 %type <ConstVector> ConstVector
1087 %type <ArgList> ArgList ArgListH
1088 %type <ArgVal> ArgVal
1089 %type <PHIList> PHIList
1090 %type <ValueList> ValueRefList ValueRefListE // For call param lists
1091 %type <ValueList> IndexList // For GEP derived indices
1092 %type <TypeList> TypeListI ArgTypeListI
1093 %type <JumpTable> JumpTable
1094 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1095 %type <BoolVal> OptVolatile // 'volatile' or not
1096 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1097 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
1098 %type <Linkage> OptLinkage
1099 %type <Endianness> BigOrLittle
1101 // ValueRef - Unresolved reference to a definition or BB
1102 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1103 %type <ValueVal> ResolvedVal // <type> <valref> pair
1104 // Tokens and types for handling constant integer values
1106 // ESINT64VAL - A negative number within long long range
1107 %token <SInt64Val> ESINT64VAL
1109 // EUINT64VAL - A positive number within uns. long long range
1110 %token <UInt64Val> EUINT64VAL
1111 %type <SInt64Val> EINT64VAL
1113 %token <SIntVal> SINTVAL // Signed 32 bit ints...
1114 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
1115 %type <SIntVal> INTVAL
1116 %token <FPVal> FPVAL // Float or Double constant
1118 // Built in types...
1119 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
1120 %type <TypeVal> SIntType UIntType IntType FPType PrimType // Classifications
1121 %token <TypeVal> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
1122 %token <TypeVal> FLOAT DOUBLE TYPE LABEL
1124 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
1125 %type <StrVal> Name OptName OptAssign
1126 %type <UIntVal> OptAlign OptCAlign
1127 %type <StrVal> OptSection SectionString
1129 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1130 %token DECLARE GLOBAL CONSTANT SECTION VOLATILE
1131 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
1132 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
1133 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
1134 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1135 %token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
1136 %token X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1138 %type <UIntVal> OptCallingConv
1140 // Basic Block Terminating Operators
1141 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1144 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
1145 %token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1146 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comparators
1148 // Memory Instructions
1149 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1152 %type <CastOpVal> CastOps
1153 %token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1154 %token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1157 %type <OtherOpVal> ShiftOps
1158 %token <OtherOpVal> PHI_TOK SELECT SHL LSHR ASHR VAARG
1159 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1160 %token VAARG_old VANEXT_old //OBSOLETE
1166 // Handle constant integer size restriction and conversion...
1170 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
1171 GEN_ERROR("Value too large for type!");
1177 EINT64VAL : ESINT64VAL; // These have same type and can't cause problems...
1178 EINT64VAL : EUINT64VAL {
1179 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
1180 GEN_ERROR("Value too large for type!");
1185 // Operations that are notably excluded from this list include:
1186 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1188 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1189 LogicalOps : AND | OR | XOR;
1190 SetCondOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
1191 CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1192 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1193 ShiftOps : SHL | LSHR | ASHR;
1195 // These are some types that allow classification if we only want a particular
1196 // thing... for example, only a signed, unsigned, or integral type.
1197 SIntType : LONG | INT | SHORT | SBYTE;
1198 UIntType : ULONG | UINT | USHORT | UBYTE;
1199 IntType : SIntType | UIntType;
1200 FPType : FLOAT | DOUBLE;
1202 // OptAssign - Value producing statements have an optional assignment component
1203 OptAssign : Name '=' {
1212 OptLinkage : INTERNAL { $$ = GlobalValue::InternalLinkage; } |
1213 LINKONCE { $$ = GlobalValue::LinkOnceLinkage; } |
1214 WEAK { $$ = GlobalValue::WeakLinkage; } |
1215 APPENDING { $$ = GlobalValue::AppendingLinkage; } |
1216 DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; } |
1217 DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; } |
1218 EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; } |
1219 /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
1221 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1222 CCC_TOK { $$ = CallingConv::C; } |
1223 CSRETCC_TOK { $$ = CallingConv::CSRet; } |
1224 FASTCC_TOK { $$ = CallingConv::Fast; } |
1225 COLDCC_TOK { $$ = CallingConv::Cold; } |
1226 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1227 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1229 if ((unsigned)$2 != $2)
1230 GEN_ERROR("Calling conv too large!");
1235 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1236 // a comma before it.
1237 OptAlign : /*empty*/ { $$ = 0; } |
1240 if ($$ != 0 && !isPowerOf2_32($$))
1241 GEN_ERROR("Alignment must be a power of two!");
1244 OptCAlign : /*empty*/ { $$ = 0; } |
1245 ',' ALIGN EUINT64VAL {
1247 if ($$ != 0 && !isPowerOf2_32($$))
1248 GEN_ERROR("Alignment must be a power of two!");
1253 SectionString : SECTION STRINGCONSTANT {
1254 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1255 if ($2[i] == '"' || $2[i] == '\\')
1256 GEN_ERROR("Invalid character in section name!");
1261 OptSection : /*empty*/ { $$ = 0; } |
1262 SectionString { $$ = $1; };
1264 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1265 // is set to be the global we are processing.
1267 GlobalVarAttributes : /* empty */ {} |
1268 ',' GlobalVarAttribute GlobalVarAttributes {};
1269 GlobalVarAttribute : SectionString {
1270 CurGV->setSection($1);
1274 | ALIGN EUINT64VAL {
1275 if ($2 != 0 && !isPowerOf2_32($2))
1276 GEN_ERROR("Alignment must be a power of two!");
1277 CurGV->setAlignment($2);
1281 //===----------------------------------------------------------------------===//
1282 // Types includes all predefined types... except void, because it can only be
1283 // used in specific contexts (function returning void for example). To have
1284 // access to it, a user must explicitly use TypesV.
1287 // TypesV includes all of 'Types', but it also includes the void type.
1288 TypesV : Types | VOID {
1289 $$.type = new PATypeHolder($1.type->get());
1290 $$.signedness = $1.signedness;
1292 UpRTypesV : UpRTypes | VOID {
1293 $$.type = new PATypeHolder($1.type->get());
1294 $$.signedness = $1.signedness;
1298 if (!UpRefs.empty())
1299 GEN_ERROR("Invalid upreference in type: " +
1300 ($1.type->get())->getDescription());
1306 // Derived types are added later...
1308 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT ;
1309 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL;
1311 $$.type = new PATypeHolder(OpaqueType::get());
1312 $$.signedness = isSignless;
1319 UpRTypes : SymbolicValueRef { // Named types are also simple types...
1320 const Type* tmp = getTypeVal($1);
1322 $$.type = new PATypeHolder(tmp);
1323 $$.signedness = isSignless;
1326 // Include derived types in the Types production.
1328 UpRTypes : '\\' EUINT64VAL { // Type UpReference
1329 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range!");
1330 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1331 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1332 $$.type = new PATypeHolder(OT);
1333 $$.signedness = isSignless;
1334 UR_OUT("New Upreference!\n");
1337 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
1338 std::vector<const Type*> Params;
1339 for (std::list<TypeInfo>::iterator I = $3->begin(),
1340 E = $3->end(); I != E; ++I)
1341 Params.push_back(I->type->get());
1342 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1343 if (isVarArg) Params.pop_back();
1345 $$.type = new PATypeHolder(HandleUpRefs(
1346 FunctionType::get($1.type->get(),Params,isVarArg)));
1347 $$.signedness = isSignless;
1348 delete $3; // Delete the argument list
1352 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
1353 $$.type = new PATypeHolder(HandleUpRefs(
1354 ArrayType::get($4.type->get(), (unsigned)$2)));
1355 $$.signedness = isSignless;
1359 | '<' EUINT64VAL 'x' UpRTypes '>' { // Packed array type?
1360 const llvm::Type* ElemTy = $4.type->get();
1361 if ((unsigned)$2 != $2)
1362 GEN_ERROR("Unsigned result not equal to signed result");
1363 if (!ElemTy->isPrimitiveType())
1364 GEN_ERROR("Elemental type of a PackedType must be primitive");
1365 if (!isPowerOf2_32($2))
1366 GEN_ERROR("Vector length should be a power of 2!");
1367 $$.type = new PATypeHolder(HandleUpRefs(
1368 PackedType::get($4.type->get(), (unsigned)$2)));
1369 $$.signedness = isSignless;
1373 | '{' TypeListI '}' { // Structure type?
1374 std::vector<const Type*> Elements;
1375 for (std::list<TypeInfo>::iterator I = $2->begin(),
1376 E = $2->end(); I != E; ++I)
1377 Elements.push_back(I->type->get());
1379 $$.type = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1380 $$.signedness = isSignless;
1384 | '{' '}' { // Empty structure type?
1385 $$.type = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1386 $$.signedness = isSignless;
1389 | UpRTypes '*' { // Pointer type?
1390 if ($1.type->get() == Type::LabelTy)
1391 GEN_ERROR("Cannot form a pointer to a basic block");
1392 $$.type = new PATypeHolder(HandleUpRefs(PointerType::get($1.type->get())));
1393 $$.signedness = $1.signedness;
1398 // TypeList - Used for struct declarations and as a basis for function type
1399 // declaration type lists
1401 TypeListI : UpRTypes {
1402 $$ = new std::list<TypeInfo>();
1406 | TypeListI ',' UpRTypes {
1407 ($$=$1)->push_back($3);
1411 // ArgTypeList - List of types for a function type declaration...
1412 ArgTypeListI : TypeListI
1413 | TypeListI ',' DOTDOTDOT {
1415 TI.type = new PATypeHolder(Type::VoidTy); TI.signedness = isSignless;
1416 ($$=$1)->push_back(TI);
1421 TI.type = new PATypeHolder(Type::VoidTy); TI.signedness = isSignless;
1422 ($$ = new std::list<TypeInfo>())->push_back(TI);
1426 $$ = new std::list<TypeInfo>();
1430 // ConstVal - The various declarations that go into the constant pool. This
1431 // production is used ONLY to represent constants that show up AFTER a 'const',
1432 // 'constant' or 'global' token at global scope. Constants that can be inlined
1433 // into other expressions (such as integers and constexprs) are handled by the
1434 // ResolvedVal, ValueRef and ConstValueRef productions.
1436 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1437 const ArrayType *ATy = dyn_cast<ArrayType>($1.type->get());
1439 GEN_ERROR("Cannot make array constant with type: '" +
1440 ($1.type->get())->getDescription() + "'!");
1441 const Type *ETy = ATy->getElementType();
1442 int NumElements = ATy->getNumElements();
1444 // Verify that we have the correct size...
1445 if (NumElements != -1 && NumElements != (int)$3->size())
1446 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1447 utostr($3->size()) + " arguments, but has size of " +
1448 itostr(NumElements) + "!");
1450 // Verify all elements are correct type!
1451 for (unsigned i = 0; i < $3->size(); i++) {
1452 if (ETy != (*$3)[i]->getType())
1453 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1454 ETy->getDescription() +"' as required!\nIt is of type '"+
1455 (*$3)[i]->getType()->getDescription() + "'.");
1458 $$ = ConstantArray::get(ATy, *$3);
1459 delete $1.type; delete $3;
1463 const ArrayType *ATy = dyn_cast<ArrayType>($1.type->get());
1465 GEN_ERROR("Cannot make array constant with type: '" +
1466 ($1.type->get())->getDescription() + "'!");
1468 int NumElements = ATy->getNumElements();
1469 if (NumElements != -1 && NumElements != 0)
1470 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1471 " arguments, but has size of " + itostr(NumElements) +"!");
1472 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1476 | Types 'c' STRINGCONSTANT {
1477 const ArrayType *ATy = dyn_cast<ArrayType>($1.type->get());
1479 GEN_ERROR("Cannot make array constant with type: '" +
1480 ($1.type->get())->getDescription() + "'!");
1482 int NumElements = ATy->getNumElements();
1483 const Type *ETy = ATy->getElementType();
1484 char *EndStr = UnEscapeLexed($3, true);
1485 if (NumElements != -1 && NumElements != (EndStr-$3))
1486 GEN_ERROR("Can't build string constant of size " +
1487 itostr((int)(EndStr-$3)) +
1488 " when array has size " + itostr(NumElements) + "!");
1489 std::vector<Constant*> Vals;
1490 if (ETy == Type::SByteTy) {
1491 for (signed char *C = (signed char *)$3; C != (signed char *)EndStr; ++C)
1492 Vals.push_back(ConstantInt::get(ETy, *C));
1493 } else if (ETy == Type::UByteTy) {
1494 for (unsigned char *C = (unsigned char *)$3;
1495 C != (unsigned char*)EndStr; ++C)
1496 Vals.push_back(ConstantInt::get(ETy, *C));
1499 GEN_ERROR("Cannot build string arrays of non byte sized elements!");
1502 $$ = ConstantArray::get(ATy, Vals);
1506 | Types '<' ConstVector '>' { // Nonempty unsized arr
1507 const PackedType *PTy = dyn_cast<PackedType>($1.type->get());
1509 GEN_ERROR("Cannot make packed constant with type: '" +
1510 $1.type->get()->getDescription() + "'!");
1511 const Type *ETy = PTy->getElementType();
1512 int NumElements = PTy->getNumElements();
1514 // Verify that we have the correct size...
1515 if (NumElements != -1 && NumElements != (int)$3->size())
1516 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1517 utostr($3->size()) + " arguments, but has size of " +
1518 itostr(NumElements) + "!");
1520 // Verify all elements are correct type!
1521 for (unsigned i = 0; i < $3->size(); i++) {
1522 if (ETy != (*$3)[i]->getType())
1523 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1524 ETy->getDescription() +"' as required!\nIt is of type '"+
1525 (*$3)[i]->getType()->getDescription() + "'.");
1528 $$ = ConstantPacked::get(PTy, *$3);
1529 delete $1.type; delete $3;
1532 | Types '{' ConstVector '}' {
1533 const StructType *STy = dyn_cast<StructType>($1.type->get());
1535 GEN_ERROR("Cannot make struct constant with type: '" +
1536 $1.type->get()->getDescription() + "'!");
1538 if ($3->size() != STy->getNumContainedTypes())
1539 GEN_ERROR("Illegal number of initializers for structure type!");
1541 // Check to ensure that constants are compatible with the type initializer!
1542 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1543 if ((*$3)[i]->getType() != STy->getElementType(i))
1544 GEN_ERROR("Expected type '" +
1545 STy->getElementType(i)->getDescription() +
1546 "' for element #" + utostr(i) +
1547 " of structure initializer!");
1549 $$ = ConstantStruct::get(STy, *$3);
1550 delete $1.type; delete $3;
1554 const StructType *STy = dyn_cast<StructType>($1.type->get());
1556 GEN_ERROR("Cannot make struct constant with type: '" +
1557 $1.type->get()->getDescription() + "'!");
1559 if (STy->getNumContainedTypes() != 0)
1560 GEN_ERROR("Illegal number of initializers for structure type!");
1562 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1567 const PointerType *PTy = dyn_cast<PointerType>($1.type->get());
1569 GEN_ERROR("Cannot make null pointer constant with type: '" +
1570 $1.type->get()->getDescription() + "'!");
1572 $$ = ConstantPointerNull::get(PTy);
1577 $$ = UndefValue::get($1.type->get());
1581 | Types SymbolicValueRef {
1582 const PointerType *Ty = dyn_cast<PointerType>($1.type->get());
1584 GEN_ERROR("Global const reference must be a pointer type!");
1586 // ConstExprs can exist in the body of a function, thus creating
1587 // GlobalValues whenever they refer to a variable. Because we are in
1588 // the context of a function, getValNonImprovising will search the functions
1589 // symbol table instead of the module symbol table for the global symbol,
1590 // which throws things all off. To get around this, we just tell
1591 // getValNonImprovising that we are at global scope here.
1593 Function *SavedCurFn = CurFun.CurrentFunction;
1594 CurFun.CurrentFunction = 0;
1596 Value *V = getValNonImprovising(Ty, $2);
1599 CurFun.CurrentFunction = SavedCurFn;
1601 // If this is an initializer for a constant pointer, which is referencing a
1602 // (currently) undefined variable, create a stub now that shall be replaced
1603 // in the future with the right type of variable.
1606 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1607 const PointerType *PT = cast<PointerType>(Ty);
1609 // First check to see if the forward references value is already created!
1610 PerModuleInfo::GlobalRefsType::iterator I =
1611 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1613 if (I != CurModule.GlobalRefs.end()) {
1614 V = I->second; // Placeholder already exists, use it...
1618 if ($2.Type == ValID::NameVal) Name = $2.Name;
1620 // Create the forward referenced global.
1622 if (const FunctionType *FTy =
1623 dyn_cast<FunctionType>(PT->getElementType())) {
1624 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1625 CurModule.CurrentModule);
1627 GV = new GlobalVariable(PT->getElementType(), false,
1628 GlobalValue::ExternalLinkage, 0,
1629 Name, CurModule.CurrentModule);
1632 // Keep track of the fact that we have a forward ref to recycle it
1633 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1638 $$ = cast<GlobalValue>(V);
1639 delete $1.type; // Free the type handle
1643 if ($1.type->get() != $2->getType())
1644 GEN_ERROR("Mismatched types for constant expression!");
1649 | Types ZEROINITIALIZER {
1650 const Type *Ty = $1.type->get();
1651 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1652 GEN_ERROR("Cannot create a null initialized value of this type!");
1653 $$ = Constant::getNullValue(Ty);
1658 ConstVal : SIntType EINT64VAL { // integral constants
1659 if (!ConstantInt::isValueValidForType($1.type->get(), $2))
1660 GEN_ERROR("Constant value doesn't fit in type!");
1661 $$ = ConstantInt::get($1.type->get(), $2);
1664 | UIntType EUINT64VAL { // integral constants
1665 if (!ConstantInt::isValueValidForType($1.type->get(), $2))
1666 GEN_ERROR("Constant value doesn't fit in type!");
1667 $$ = ConstantInt::get($1.type->get(), $2);
1670 | BOOL TRUETOK { // Boolean constants
1671 $$ = ConstantBool::getTrue();
1674 | BOOL FALSETOK { // Boolean constants
1675 $$ = ConstantBool::getFalse();
1678 | FPType FPVAL { // Float & Double constants
1679 if (!ConstantFP::isValueValidForType($1.type->get(), $2))
1680 GEN_ERROR("Floating point constant invalid for type!!");
1681 $$ = ConstantFP::get($1.type->get(), $2);
1686 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1688 const Type *Ty = $5.type->get();
1689 if (!Val->getType()->isFirstClassType())
1690 GEN_ERROR("cast constant expression from a non-primitive type: '" +
1691 Val->getType()->getDescription() + "'!");
1692 if (!Ty->isFirstClassType())
1693 GEN_ERROR("cast constant expression to a non-primitive type: '" +
1694 Ty->getDescription() + "'!");
1696 if (Ty == Type::BoolTy) {
1697 // The previous definition of cast to bool was a compare against zero.
1698 // We have to retain that semantic so we do it here.
1699 $$ = ConstantExpr::get(Instruction::SetNE, Val,
1700 Constant::getNullValue(Val->getType()));
1701 } else if (Val->getType()->isFloatingPoint() && isa<PointerType>(Ty)) {
1702 Constant *CE = ConstantExpr::getFPToUI(Val, Type::ULongTy);
1703 $$ = ConstantExpr::getIntToPtr(CE, Ty);
1705 $$ = ConstantExpr::getCast(Val, Ty);
1708 $$ = ConstantExpr::getCast($1.opcode, $3, $5.type->get());
1712 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1713 if (!isa<PointerType>($3->getType()))
1714 GEN_ERROR("GetElementPtr requires a pointer operand!");
1716 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
1717 // indices to uint struct indices for compatibility.
1718 generic_gep_type_iterator<std::vector<Value*>::iterator>
1719 GTI = gep_type_begin($3->getType(), $4->begin(), $4->end()),
1720 GTE = gep_type_end($3->getType(), $4->begin(), $4->end());
1721 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
1722 if (isa<StructType>(*GTI)) // Only change struct indices
1723 if (ConstantInt *CUI = dyn_cast<ConstantInt>((*$4)[i]))
1724 if (CUI->getType() == Type::UByteTy)
1725 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
1728 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1730 GEN_ERROR("Index list invalid for constant getelementptr!");
1732 std::vector<Constant*> IdxVec;
1733 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1734 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1735 IdxVec.push_back(C);
1737 GEN_ERROR("Indices to constant getelementptr must be constants!");
1741 $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1744 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1745 if ($3->getType() != Type::BoolTy)
1746 GEN_ERROR("Select condition must be of boolean type!");
1747 if ($5->getType() != $7->getType())
1748 GEN_ERROR("Select operand types must match!");
1749 $$ = ConstantExpr::getSelect($3, $5, $7);
1752 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1753 if ($3->getType() != $5->getType())
1754 GEN_ERROR("Binary operator types must match!");
1755 // First, make sure we're dealing with the right opcode by upgrading from
1756 // obsolete versions.
1757 sanitizeOpcode($1, $3->getType());
1760 // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
1761 // To retain backward compatibility with these early compilers, we emit a
1762 // cast to the appropriate integer type automatically if we are in the
1763 // broken case. See PR424 for more information.
1764 if (!isa<PointerType>($3->getType())) {
1765 $$ = ConstantExpr::get($1.opcode, $3, $5);
1767 const Type *IntPtrTy = 0;
1768 switch (CurModule.CurrentModule->getPointerSize()) {
1769 case Module::Pointer32: IntPtrTy = Type::IntTy; break;
1770 case Module::Pointer64: IntPtrTy = Type::LongTy; break;
1771 default: GEN_ERROR("invalid pointer binary constant expr!");
1773 $$ = ConstantExpr::get($1.opcode, ConstantExpr::getCast($3, IntPtrTy),
1774 ConstantExpr::getCast($5, IntPtrTy));
1775 $$ = ConstantExpr::getCast($$, $3->getType());
1779 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1780 if ($3->getType() != $5->getType())
1781 GEN_ERROR("Logical operator types must match!");
1782 if (!$3->getType()->isIntegral()) {
1783 if (!isa<PackedType>($3->getType()) ||
1784 !cast<PackedType>($3->getType())->getElementType()->isIntegral())
1785 GEN_ERROR("Logical operator requires integral operands!");
1787 $$ = ConstantExpr::get($1.opcode, $3, $5);
1790 | SetCondOps '(' ConstVal ',' ConstVal ')' {
1791 if ($3->getType() != $5->getType())
1792 GEN_ERROR("setcc operand types must match!");
1793 $$ = ConstantExpr::get($1.opcode, $3, $5);
1796 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1797 if ($5->getType() != Type::UByteTy)
1798 GEN_ERROR("Shift count for shift constant must be unsigned byte!");
1799 if (!$3->getType()->isInteger())
1800 GEN_ERROR("Shift constant expression requires integer operand!");
1801 // Handle opcode upgrade situations
1802 sanitizeOpcode($1, $3->getType());
1804 $$ = ConstantExpr::get($1.opcode, $3, $5);
1807 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1808 if (!ExtractElementInst::isValidOperands($3, $5))
1809 GEN_ERROR("Invalid extractelement operands!");
1810 $$ = ConstantExpr::getExtractElement($3, $5);
1813 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1814 if (!InsertElementInst::isValidOperands($3, $5, $7))
1815 GEN_ERROR("Invalid insertelement operands!");
1816 $$ = ConstantExpr::getInsertElement($3, $5, $7);
1819 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1820 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1821 GEN_ERROR("Invalid shufflevector operands!");
1822 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1827 // ConstVector - A list of comma separated constants.
1828 ConstVector : ConstVector ',' ConstVal {
1829 ($$ = $1)->push_back($3);
1833 $$ = new std::vector<Constant*>();
1839 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1840 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1843 //===----------------------------------------------------------------------===//
1844 // Rules to match Modules
1845 //===----------------------------------------------------------------------===//
1847 // Module rule: Capture the result of parsing the whole file into a result
1850 Module : FunctionList {
1851 $$ = ParserResult = $1;
1852 CurModule.ModuleDone();
1856 // FunctionList - A list of functions, preceeded by a constant pool.
1858 FunctionList : FunctionList Function {
1860 CurFun.FunctionDone();
1863 | FunctionList FunctionProto {
1867 | FunctionList MODULE ASM_TOK AsmBlock {
1871 | FunctionList IMPLEMENTATION {
1876 $$ = CurModule.CurrentModule;
1877 // Emit an error if there are any unresolved types left.
1878 if (!CurModule.LateResolveTypes.empty()) {
1879 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
1880 if (DID.Type == ValID::NameVal) {
1881 GEN_ERROR("Reference to an undefined type: '"+DID.getName() + "'");
1883 GEN_ERROR("Reference to an undefined type: #" + itostr(DID.Num));
1889 // ConstPool - Constants with optional names assigned to them.
1890 ConstPool : ConstPool OptAssign TYPE TypesV {
1891 // Eagerly resolve types. This is not an optimization, this is a
1892 // requirement that is due to the fact that we could have this:
1894 // %list = type { %list * }
1895 // %list = type { %list * } ; repeated type decl
1897 // If types are not resolved eagerly, then the two types will not be
1898 // determined to be the same type!
1900 ResolveTypeTo($2, $4.type->get());
1902 if (!setTypeName($4.type->get(), $2) && !$2) {
1904 // If this is a named type that is not a redefinition, add it to the slot
1906 CurModule.Types.push_back($4);
1912 | ConstPool FunctionProto { // Function prototypes can be in const pool
1915 | ConstPool MODULE ASM_TOK AsmBlock { // Asm blocks can be in the const pool
1918 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
1920 GEN_ERROR("Global value initializer is not a constant!");
1921 CurGV = ParseGlobalVariable($2, $3, $4, $5->getType(), $5);
1923 } GlobalVarAttributes {
1926 | ConstPool OptAssign EXTERNAL GlobalType Types {
1927 CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4,
1931 } GlobalVarAttributes {
1935 | ConstPool OptAssign DLLIMPORT GlobalType Types {
1936 CurGV = ParseGlobalVariable($2, GlobalValue::DLLImportLinkage, $4,
1940 } GlobalVarAttributes {
1944 | ConstPool OptAssign EXTERN_WEAK GlobalType Types {
1946 ParseGlobalVariable($2, GlobalValue::ExternalWeakLinkage, $4,
1950 } GlobalVarAttributes {
1954 | ConstPool TARGET TargetDefinition {
1957 | ConstPool DEPLIBS '=' LibrariesDefinition {
1960 | /* empty: end of list */ {
1964 AsmBlock : STRINGCONSTANT {
1965 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
1966 char *EndStr = UnEscapeLexed($1, true);
1967 std::string NewAsm($1, EndStr);
1970 if (AsmSoFar.empty())
1971 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
1973 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
1977 BigOrLittle : BIG { $$ = Module::BigEndian; };
1978 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1980 TargetDefinition : ENDIAN '=' BigOrLittle {
1981 CurModule.CurrentModule->setEndianness($3);
1984 | POINTERSIZE '=' EUINT64VAL {
1986 CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1988 CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1990 GEN_ERROR("Invalid pointer size: '" + utostr($3) + "'!");
1993 | TRIPLE '=' STRINGCONSTANT {
1994 CurModule.CurrentModule->setTargetTriple($3);
1997 | DATALAYOUT '=' STRINGCONSTANT {
1998 CurModule.CurrentModule->setDataLayout($3);
2002 LibrariesDefinition : '[' LibList ']';
2004 LibList : LibList ',' STRINGCONSTANT {
2005 CurModule.CurrentModule->addLibrary($3);
2010 CurModule.CurrentModule->addLibrary($1);
2014 | /* empty: end of list */ {
2019 //===----------------------------------------------------------------------===//
2020 // Rules to match Function Headers
2021 //===----------------------------------------------------------------------===//
2023 Name : VAR_ID | STRINGCONSTANT;
2024 OptName : Name | /*empty*/ { $$ = 0; };
2026 ArgVal : Types OptName {
2027 if ($1.type->get() == Type::VoidTy)
2028 GEN_ERROR("void typed arguments are invalid!");
2029 $$ = new std::pair<TypeInfo, char*>($1, $2);
2033 ArgListH : ArgListH ',' ArgVal {
2040 $$ = new std::vector<std::pair<TypeInfo,char*> >();
2046 ArgList : ArgListH {
2050 | ArgListH ',' DOTDOTDOT {
2053 TI.type = new PATypeHolder(Type::VoidTy);
2054 TI.signedness = isSignless;
2055 $$->push_back(std::pair<TypeInfo,char*>(TI,(char*)0));
2059 $$ = new std::vector<std::pair<TypeInfo,char*> >();
2061 TI.type = new PATypeHolder(Type::VoidTy);
2062 TI.signedness = isSignless;
2063 $$->push_back(std::make_pair(TI, (char*)0));
2071 FunctionHeaderH : OptCallingConv TypesV Name '(' ArgList ')'
2072 OptSection OptAlign {
2074 std::string FunctionName($3);
2075 free($3); // Free strdup'd memory!
2077 if (!($2.type->get())->isFirstClassType() && $2.type->get() != Type::VoidTy)
2078 GEN_ERROR("LLVM functions cannot return aggregate types!");
2080 std::vector<const Type*> ParamTypeList;
2081 if ($5) { // If there are arguments...
2082 for (std::vector<std::pair<TypeInfo,char*> >::iterator I = $5->begin();
2083 I != $5->end(); ++I)
2084 ParamTypeList.push_back(I->first.type->get());
2087 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2088 if (isVarArg) ParamTypeList.pop_back();
2090 const FunctionType *FT = FunctionType::get($2.type->get(), ParamTypeList,
2092 const PointerType *PFT = PointerType::get(FT);
2096 if (!FunctionName.empty()) {
2097 ID = ValID::create((char*)FunctionName.c_str());
2099 ID = ValID::create((int)CurModule.Values[PFT].size());
2103 // See if this function was forward referenced. If so, recycle the object.
2104 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2105 // Move the function to the end of the list, from whereever it was
2106 // previously inserted.
2107 Fn = cast<Function>(FWRef);
2108 CurModule.CurrentModule->getFunctionList().remove(Fn);
2109 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2110 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2111 (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
2112 // If this is the case, either we need to be a forward decl, or it needs
2114 if (!CurFun.isDeclare && !Fn->isExternal())
2115 GEN_ERROR("Redefinition of function '" + FunctionName + "'!");
2117 // Make sure to strip off any argument names so we can't get conflicts.
2118 if (Fn->isExternal())
2119 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2122 } else { // Not already defined?
2123 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
2124 CurModule.CurrentModule);
2126 InsertValue(Fn, CurModule.Values);
2129 CurFun.FunctionStart(Fn);
2131 if (CurFun.isDeclare) {
2132 // If we have declaration, always overwrite linkage. This will allow us to
2133 // correctly handle cases, when pointer to function is passed as argument to
2134 // another function.
2135 Fn->setLinkage(CurFun.Linkage);
2137 Fn->setCallingConv($1);
2138 Fn->setAlignment($8);
2144 // Add all of the arguments we parsed to the function...
2145 if ($5) { // Is null if empty...
2146 if (isVarArg) { // Nuke the last entry
2147 assert($5->back().first.type->get() == Type::VoidTy &&
2148 $5->back().second == 0 && "Not a varargs marker!");
2149 delete $5->back().first.type;
2150 $5->pop_back(); // Delete the last entry
2152 Function::arg_iterator ArgIt = Fn->arg_begin();
2153 for (std::vector<std::pair<TypeInfo,char*> >::iterator I = $5->begin();
2154 I != $5->end(); ++I, ++ArgIt) {
2155 delete I->first.type; // Delete the typeholder...
2156 setValueName(ArgIt, I->second); // Insert arg into symtab...
2160 delete $5; // We're now done with the argument list
2165 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2167 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
2168 $$ = CurFun.CurrentFunction;
2170 // Make sure that we keep track of the linkage type even if there was a
2171 // previous "declare".
2175 END : ENDTOK | '}'; // Allow end of '}' to end a function
2177 Function : BasicBlockList END {
2182 FnDeclareLinkage: /*default*/ |
2183 DLLIMPORT { CurFun.Linkage = GlobalValue::DLLImportLinkage; } |
2184 EXTERN_WEAK { CurFun.Linkage = GlobalValue::DLLImportLinkage; };
2186 FunctionProto : DECLARE { CurFun.isDeclare = true; } FnDeclareLinkage FunctionHeaderH {
2187 $$ = CurFun.CurrentFunction;
2188 CurFun.FunctionDone();
2192 //===----------------------------------------------------------------------===//
2193 // Rules to match Basic Blocks
2194 //===----------------------------------------------------------------------===//
2196 OptSideEffect : /* empty */ {
2205 ConstValueRef : ESINT64VAL { // A reference to a direct constant
2206 $$ = ValID::create($1);
2210 $$ = ValID::create($1);
2213 | FPVAL { // Perhaps it's an FP constant?
2214 $$ = ValID::create($1);
2218 $$ = ValID::create(ConstantBool::getTrue());
2222 $$ = ValID::create(ConstantBool::getFalse());
2226 $$ = ValID::createNull();
2230 $$ = ValID::createUndef();
2233 | ZEROINITIALIZER { // A vector zero constant.
2234 $$ = ValID::createZeroInit();
2237 | '<' ConstVector '>' { // Nonempty unsized packed vector
2238 const Type *ETy = (*$2)[0]->getType();
2239 int NumElements = $2->size();
2241 PackedType* pt = PackedType::get(ETy, NumElements);
2242 PATypeHolder* PTy = new PATypeHolder(
2243 HandleUpRefs(PackedType::get( ETy, NumElements)));
2245 // Verify all elements are correct type!
2246 for (unsigned i = 0; i < $2->size(); i++) {
2247 if (ETy != (*$2)[i]->getType())
2248 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2249 ETy->getDescription() +"' as required!\nIt is of type '" +
2250 (*$2)[i]->getType()->getDescription() + "'.");
2253 $$ = ValID::create(ConstantPacked::get(pt, *$2));
2254 delete PTy; delete $2;
2258 $$ = ValID::create($1);
2261 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2262 char *End = UnEscapeLexed($3, true);
2263 std::string AsmStr = std::string($3, End);
2264 End = UnEscapeLexed($5, true);
2265 std::string Constraints = std::string($5, End);
2266 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2272 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2275 SymbolicValueRef : INTVAL { // Is it an integer reference...?
2276 $$ = ValID::create($1);
2279 | Name { // Is it a named reference...?
2280 $$ = ValID::create($1);
2284 // ValueRef - A reference to a definition... either constant or symbolic
2285 ValueRef : SymbolicValueRef | ConstValueRef;
2288 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2289 // type immediately preceeds the value reference, and allows complex constant
2290 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2291 ResolvedVal : Types ValueRef {
2292 $$ = getVal($1.type->get(), $2); delete $1.type;
2296 BasicBlockList : BasicBlockList BasicBlock {
2300 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2306 // Basic blocks are terminated by branching instructions:
2307 // br, br/cc, switch, ret
2309 BasicBlock : InstructionList OptAssign BBTerminatorInst {
2310 setValueName($3, $2);
2314 $1->getInstList().push_back($3);
2320 InstructionList : InstructionList Inst {
2321 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2322 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2323 if (CI2->getParent() == 0)
2324 $1->getInstList().push_back(CI2);
2325 $1->getInstList().push_back($2);
2330 $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
2333 // Make sure to move the basic block to the correct location in the
2334 // function, instead of leaving it inserted wherever it was first
2336 Function::BasicBlockListType &BBL =
2337 CurFun.CurrentFunction->getBasicBlockList();
2338 BBL.splice(BBL.end(), BBL, $$);
2342 $$ = CurBB = getBBVal(ValID::create($1), true);
2345 // Make sure to move the basic block to the correct location in the
2346 // function, instead of leaving it inserted wherever it was first
2348 Function::BasicBlockListType &BBL =
2349 CurFun.CurrentFunction->getBasicBlockList();
2350 BBL.splice(BBL.end(), BBL, $$);
2354 BBTerminatorInst : RET ResolvedVal { // Return with a result...
2355 $$ = new ReturnInst($2);
2358 | RET VOID { // Return with no result...
2359 $$ = new ReturnInst();
2362 | BR LABEL ValueRef { // Unconditional Branch...
2363 BasicBlock* tmpBB = getBBVal($3);
2365 $$ = new BranchInst(tmpBB);
2366 } // Conditional Branch...
2367 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2368 BasicBlock* tmpBBA = getBBVal($6);
2370 BasicBlock* tmpBBB = getBBVal($9);
2372 Value* tmpVal = getVal(Type::BoolTy, $3);
2374 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2376 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2377 Value* tmpVal = getVal($2.type->get(), $3);
2379 BasicBlock* tmpBB = getBBVal($6);
2381 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2384 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2386 for (; I != E; ++I) {
2387 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2388 S->addCase(CI, I->second);
2390 GEN_ERROR("Switch case is constant, but not a simple integer!");
2395 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2396 Value* tmpVal = getVal($2.type->get(), $3);
2398 BasicBlock* tmpBB = getBBVal($6);
2400 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2404 | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
2405 TO LABEL ValueRef UNWIND LABEL ValueRef {
2406 const PointerType *PFTy;
2407 const FunctionType *Ty;
2409 if (!(PFTy = dyn_cast<PointerType>($3.type->get())) ||
2410 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2411 // Pull out the types of all of the arguments...
2412 std::vector<const Type*> ParamTypes;
2414 for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
2416 ParamTypes.push_back((*I)->getType());
2419 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2420 if (isVarArg) ParamTypes.pop_back();
2422 Ty = FunctionType::get($3.type->get(), ParamTypes, isVarArg);
2423 PFTy = PointerType::get(Ty);
2426 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2428 BasicBlock *Normal = getBBVal($10);
2430 BasicBlock *Except = getBBVal($13);
2433 // Create the call node...
2434 if (!$6) { // Has no arguments?
2435 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
2436 } else { // Has arguments?
2437 // Loop through FunctionType's arguments and ensure they are specified
2440 FunctionType::param_iterator I = Ty->param_begin();
2441 FunctionType::param_iterator E = Ty->param_end();
2442 std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
2444 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2445 if ((*ArgI)->getType() != *I)
2446 GEN_ERROR("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2447 (*I)->getDescription() + "'!");
2449 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2450 GEN_ERROR("Invalid number of parameters detected!");
2452 $$ = new InvokeInst(V, Normal, Except, *$6);
2454 cast<InvokeInst>($$)->setCallingConv($2);
2461 $$ = new UnwindInst();
2465 $$ = new UnreachableInst();
2471 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2473 Constant *V = cast<Constant>(getValNonImprovising($2.type->get(), $3));
2476 GEN_ERROR("May only switch on a constant pool value!");
2478 BasicBlock* tmpBB = getBBVal($6);
2480 $$->push_back(std::make_pair(V, tmpBB));
2482 | IntType ConstValueRef ',' LABEL ValueRef {
2483 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2484 Constant *V = cast<Constant>(getValNonImprovising($1.type->get(), $2));
2488 GEN_ERROR("May only switch on a constant pool value!");
2490 BasicBlock* tmpBB = getBBVal($5);
2492 $$->push_back(std::make_pair(V, tmpBB));
2495 Inst : OptAssign InstVal {
2496 // Is this definition named?? if so, assign the name...
2497 setValueName($2, $1);
2504 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2505 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2506 Value* tmpVal = getVal($1.type->get(), $3);
2508 BasicBlock* tmpBB = getBBVal($5);
2510 $$->push_back(std::make_pair(tmpVal, tmpBB));
2513 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2515 Value* tmpVal = getVal($1->front().first->getType(), $4);
2517 BasicBlock* tmpBB = getBBVal($6);
2519 $1->push_back(std::make_pair(tmpVal, tmpBB));
2523 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
2524 $$ = new std::vector<Value*>();
2527 | ValueRefList ',' ResolvedVal {
2533 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
2534 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
2536 OptTailCall : TAIL CALL {
2545 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2546 if (!$2.type->get()->isInteger() && !$2.type->get()->isFloatingPoint() &&
2547 !isa<PackedType>($2.type->get()))
2549 "Arithmetic operator requires integer, FP, or packed operands!");
2550 if (isa<PackedType>($2.type->get()) &&
2551 ($1.opcode == Instruction::URem ||
2552 $1.opcode == Instruction::SRem ||
2553 $1.opcode == Instruction::FRem))
2554 GEN_ERROR("U/S/FRem not supported on packed types!");
2555 // Upgrade the opcode from obsolete versions before we do anything with it.
2556 sanitizeOpcode($1,$2.type->get());
2558 Value* val1 = getVal($2.type->get(), $3);
2560 Value* val2 = getVal($2.type->get(), $5);
2562 $$ = BinaryOperator::create($1.opcode, val1, val2);
2564 GEN_ERROR("binary operator returned null!");
2567 | LogicalOps Types ValueRef ',' ValueRef {
2568 if (!$2.type->get()->isIntegral()) {
2569 if (!isa<PackedType>($2.type->get()) ||
2570 !cast<PackedType>($2.type->get())->getElementType()->isIntegral())
2571 GEN_ERROR("Logical operator requires integral operands!");
2573 Value* tmpVal1 = getVal($2.type->get(), $3);
2575 Value* tmpVal2 = getVal($2.type->get(), $5);
2577 $$ = BinaryOperator::create($1.opcode, tmpVal1, tmpVal2);
2579 GEN_ERROR("binary operator returned null!");
2582 | SetCondOps Types ValueRef ',' ValueRef {
2583 if(isa<PackedType>($2.type->get())) {
2585 "PackedTypes currently not supported in setcc instructions!");
2587 Value* tmpVal1 = getVal($2.type->get(), $3);
2589 Value* tmpVal2 = getVal($2.type->get(), $5);
2591 $$ = new SetCondInst($1.opcode, tmpVal1, tmpVal2);
2593 GEN_ERROR("binary operator returned null!");
2597 std::cerr << "WARNING: Use of eliminated 'not' instruction:"
2598 << " Replacing with 'xor'.\n";
2600 Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
2602 GEN_ERROR("Expected integral type for not instruction!");
2604 $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
2606 GEN_ERROR("Could not create a xor instruction!");
2609 | ShiftOps ResolvedVal ',' ResolvedVal {
2610 if ($4->getType() != Type::UByteTy)
2611 GEN_ERROR("Shift amount must be ubyte!");
2612 if (!$2->getType()->isInteger())
2613 GEN_ERROR("Shift constant expression requires integer operand!");
2614 // Handle opcode upgrade situations
2615 sanitizeOpcode($1, $2->getType());
2617 $$ = new ShiftInst($1.opcode, $2, $4);
2620 | CastOps ResolvedVal TO Types {
2622 const Type* Ty = $4.type->get();
2623 if (!Val->getType()->isFirstClassType())
2624 GEN_ERROR("cast from a non-primitive type: '" +
2625 Val->getType()->getDescription() + "'!");
2626 if (!Ty->isFirstClassType())
2627 GEN_ERROR("cast to a non-primitive type: '" + Ty->getDescription() +"'!");
2630 if (Ty == Type::BoolTy) {
2631 // The previous definition of cast to bool was a compare against zero.
2632 // We have to retain that semantic so we do it here.
2633 $$ = new SetCondInst(Instruction::SetNE, $2,
2634 Constant::getNullValue($2->getType()));
2635 } else if (Val->getType()->isFloatingPoint() && isa<PointerType>(Ty)) {
2636 CastInst *CI = new FPToUIInst(Val, Type::ULongTy);
2637 $$ = new IntToPtrInst(CI, Ty);
2639 $$ = CastInst::createInferredCast(Val, Ty);
2642 $$ = CastInst::create($1.opcode, $2, $4.type->get());
2646 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2647 if ($2->getType() != Type::BoolTy)
2648 GEN_ERROR("select condition must be boolean!");
2649 if ($4->getType() != $6->getType())
2650 GEN_ERROR("select value types should match!");
2651 $$ = new SelectInst($2, $4, $6);
2654 | VAARG ResolvedVal ',' Types {
2656 $$ = new VAArgInst($2, $4.type->get());
2660 | VAARG_old ResolvedVal ',' Types {
2661 ObsoleteVarArgs = true;
2662 const Type* ArgTy = $2->getType();
2663 Function* NF = CurModule.CurrentModule->
2664 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0);
2667 //foo = alloca 1 of t
2671 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
2672 CurBB->getInstList().push_back(foo);
2673 CallInst* bar = new CallInst(NF, $2);
2674 CurBB->getInstList().push_back(bar);
2675 CurBB->getInstList().push_back(new StoreInst(bar, foo));
2676 $$ = new VAArgInst(foo, $4.type->get());
2680 | VANEXT_old ResolvedVal ',' Types {
2681 ObsoleteVarArgs = true;
2682 const Type* ArgTy = $2->getType();
2683 Function* NF = CurModule.CurrentModule->
2684 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0);
2686 //b = vanext a, t ->
2687 //foo = alloca 1 of t
2690 //tmp = vaarg foo, t
2692 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
2693 CurBB->getInstList().push_back(foo);
2694 CallInst* bar = new CallInst(NF, $2);
2695 CurBB->getInstList().push_back(bar);
2696 CurBB->getInstList().push_back(new StoreInst(bar, foo));
2697 Instruction* tmp = new VAArgInst(foo, $4.type->get());
2698 CurBB->getInstList().push_back(tmp);
2699 $$ = new LoadInst(foo);
2703 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2704 if (!ExtractElementInst::isValidOperands($2, $4))
2705 GEN_ERROR("Invalid extractelement operands!");
2706 $$ = new ExtractElementInst($2, $4);
2709 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2710 if (!InsertElementInst::isValidOperands($2, $4, $6))
2711 GEN_ERROR("Invalid insertelement operands!");
2712 $$ = new InsertElementInst($2, $4, $6);
2715 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2716 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
2717 GEN_ERROR("Invalid shufflevector operands!");
2718 $$ = new ShuffleVectorInst($2, $4, $6);
2722 const Type *Ty = $2->front().first->getType();
2723 if (!Ty->isFirstClassType())
2724 GEN_ERROR("PHI node operands must be of first class type!");
2725 $$ = new PHINode(Ty);
2726 ((PHINode*)$$)->reserveOperandSpace($2->size());
2727 while ($2->begin() != $2->end()) {
2728 if ($2->front().first->getType() != Ty)
2729 GEN_ERROR("All elements of a PHI node must be of the same type!");
2730 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2733 delete $2; // Free the list...
2736 | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')' {
2737 const PointerType *PFTy = 0;
2738 const FunctionType *Ty = 0;
2740 if (!(PFTy = dyn_cast<PointerType>($3.type->get())) ||
2741 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2742 // Pull out the types of all of the arguments...
2743 std::vector<const Type*> ParamTypes;
2745 for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
2747 ParamTypes.push_back((*I)->getType());
2750 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2751 if (isVarArg) ParamTypes.pop_back();
2753 if (!$3.type->get()->isFirstClassType() &&
2754 $3.type->get() != Type::VoidTy)
2755 GEN_ERROR("LLVM functions cannot return aggregate types!");
2757 Ty = FunctionType::get($3.type->get(), ParamTypes, isVarArg);
2758 PFTy = PointerType::get(Ty);
2761 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2764 // Create the call node...
2765 if (!$6) { // Has no arguments?
2766 // Make sure no arguments is a good thing!
2767 if (Ty->getNumParams() != 0)
2768 GEN_ERROR("No arguments passed to a function that "
2769 "expects arguments!");
2771 $$ = new CallInst(V, std::vector<Value*>());
2772 } else { // Has arguments?
2773 // Loop through FunctionType's arguments and ensure they are specified
2776 FunctionType::param_iterator I = Ty->param_begin();
2777 FunctionType::param_iterator E = Ty->param_end();
2778 std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
2780 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2781 if ((*ArgI)->getType() != *I)
2782 GEN_ERROR("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2783 (*I)->getDescription() + "'!");
2785 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2786 GEN_ERROR("Invalid number of parameters detected!");
2788 $$ = new CallInst(V, *$6);
2790 cast<CallInst>($$)->setTailCall($1);
2791 cast<CallInst>($$)->setCallingConv($2);
2802 // IndexList - List of indices for GEP based instructions...
2803 IndexList : ',' ValueRefList {
2807 $$ = new std::vector<Value*>();
2811 OptVolatile : VOLATILE {
2822 MemoryInst : MALLOC Types OptCAlign {
2823 $$ = new MallocInst($2.type->get(), 0, $3);
2827 | MALLOC Types ',' UINT ValueRef OptCAlign {
2828 Value* tmpVal = getVal($4.type->get(), $5);
2830 $$ = new MallocInst($2.type->get(), tmpVal, $6);
2833 | ALLOCA Types OptCAlign {
2834 $$ = new AllocaInst($2.type->get(), 0, $3);
2838 | ALLOCA Types ',' UINT ValueRef OptCAlign {
2839 Value* tmpVal = getVal($4.type->get(), $5);
2841 $$ = new AllocaInst($2.type->get(), tmpVal, $6);
2844 | FREE ResolvedVal {
2845 if (!isa<PointerType>($2->getType()))
2846 GEN_ERROR("Trying to free nonpointer type " +
2847 $2->getType()->getDescription() + "!");
2848 $$ = new FreeInst($2);
2852 | OptVolatile LOAD Types ValueRef {
2853 if (!isa<PointerType>($3.type->get()))
2854 GEN_ERROR("Can't load from nonpointer type: " +
2855 $3.type->get()->getDescription());
2856 if (!cast<PointerType>($3.type->get())->getElementType()->isFirstClassType())
2857 GEN_ERROR("Can't load from pointer of non-first-class type: " +
2858 $3.type->get()->getDescription());
2859 Value* tmpVal = getVal($3.type->get(), $4);
2861 $$ = new LoadInst(tmpVal, "", $1);
2864 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2865 const PointerType *PT = dyn_cast<PointerType>($5.type->get());
2867 GEN_ERROR("Can't store to a nonpointer type: " +
2868 ($5.type->get())->getDescription());
2869 const Type *ElTy = PT->getElementType();
2870 if (ElTy != $3->getType())
2871 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
2872 "' into space of type '" + ElTy->getDescription() + "'!");
2874 Value* tmpVal = getVal($5.type->get(), $6);
2876 $$ = new StoreInst($3, tmpVal, $1);
2879 | GETELEMENTPTR Types ValueRef IndexList {
2880 if (!isa<PointerType>($2.type->get()))
2881 GEN_ERROR("getelementptr insn requires pointer operand!");
2883 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
2884 // indices to uint struct indices for compatibility.
2885 generic_gep_type_iterator<std::vector<Value*>::iterator>
2886 GTI = gep_type_begin($2.type->get(), $4->begin(), $4->end()),
2887 GTE = gep_type_end($2.type->get(), $4->begin(), $4->end());
2888 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
2889 if (isa<StructType>(*GTI)) // Only change struct indices
2890 if (ConstantInt *CUI = dyn_cast<ConstantInt>((*$4)[i]))
2891 if (CUI->getType() == Type::UByteTy)
2892 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
2894 if (!GetElementPtrInst::getIndexedType($2.type->get(), *$4, true))
2895 GEN_ERROR("Invalid getelementptr indices for type '" +
2896 $2.type->get()->getDescription()+ "'!");
2897 Value* tmpVal = getVal($2.type->get(), $3);
2899 $$ = new GetElementPtrInst(tmpVal, *$4);
2907 void llvm::GenerateError(const std::string &message, int LineNo) {
2908 if (LineNo == -1) LineNo = llvmAsmlineno;
2909 // TODO: column number in exception
2911 TheParseError->setError(CurFilename, message, LineNo);
2915 int yyerror(const char *ErrorMsg) {
2917 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2918 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2919 std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2920 if (yychar == YYEMPTY || yychar == 0)
2921 errMsg += "end-of-file.";
2923 errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2924 GenerateError(errMsg);