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->getValueSymbolTable() :
315 CurModule.CurrentModule->getValueSymbolTable();
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 getValueSymbolTable().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->getValueSymbolTable();
637 if (ST.lookup(V->getType(), Name)) {
638 GenerateError("Redefinition of value '" + Name + "' of type '" +
639 V->getType()->getDescription() + "'!");
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, it is an error.
692 // We are a simple redefinition of a value, check to see if it is defined
693 // the same as the old one.
694 if (CurModule.CurrentModule->getGlobalVariable(Name, Ty)) {
695 GenerateError("Redefinition of global variable named '" + Name +
696 "' of type '" + Ty->getDescription() + "'!");
701 // Otherwise there is no existing GV to use, create one now.
703 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
704 CurModule.CurrentModule);
705 InsertValue(GV, CurModule.Values);
709 // setTypeName - Set the specified type to the name given. The name may be
710 // null potentially, in which case this is a noop. The string passed in is
711 // assumed to be a malloc'd string buffer, and is freed by this function.
713 // This function returns true if the type has already been defined, but is
714 // allowed to be redefined in the specified context. If the name is a new name
715 // for the type plane, it is inserted and false is returned.
716 static bool setTypeName(const Type *T, char *NameStr) {
717 assert(!inFunctionScope() && "Can't give types function-local names!");
718 if (NameStr == 0) return false;
720 std::string Name(NameStr); // Copy string
721 free(NameStr); // Free old string
723 // We don't allow assigning names to void type
724 if (T == Type::VoidTy) {
725 GenerateError("Can't assign name '" + Name + "' to the void type!");
729 // Set the type name, checking for conflicts as we do so.
730 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
732 if (AlreadyExists) { // Inserting a name that is already defined???
733 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
734 assert(Existing && "Conflict but no matching type?");
736 // There is only one case where this is allowed: when we are refining an
737 // opaque type. In this case, Existing will be an opaque type.
738 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
739 // We ARE replacing an opaque type!
740 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
744 // Otherwise, this is an attempt to redefine a type. That's okay if
745 // the redefinition is identical to the original. This will be so if
746 // Existing and T point to the same Type object. In this one case we
747 // allow the equivalent redefinition.
748 if (Existing == T) return true; // Yes, it's equal.
750 // Any other kind of (non-equivalent) redefinition is an error.
751 GenerateError("Redefinition of type named '" + Name + "' of type '" +
752 T->getDescription() + "'!");
758 //===----------------------------------------------------------------------===//
759 // Code for handling upreferences in type names...
762 // TypeContains - Returns true if Ty directly contains E in it.
764 static bool TypeContains(const Type *Ty, const Type *E) {
765 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
766 E) != Ty->subtype_end();
771 // NestingLevel - The number of nesting levels that need to be popped before
772 // this type is resolved.
773 unsigned NestingLevel;
775 // LastContainedTy - This is the type at the current binding level for the
776 // type. Every time we reduce the nesting level, this gets updated.
777 const Type *LastContainedTy;
779 // UpRefTy - This is the actual opaque type that the upreference is
783 UpRefRecord(unsigned NL, OpaqueType *URTy)
784 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
788 // UpRefs - A list of the outstanding upreferences that need to be resolved.
789 static std::vector<UpRefRecord> UpRefs;
791 /// HandleUpRefs - Every time we finish a new layer of types, this function is
792 /// called. It loops through the UpRefs vector, which is a list of the
793 /// currently active types. For each type, if the up reference is contained in
794 /// the newly completed type, we decrement the level count. When the level
795 /// count reaches zero, the upreferenced type is the type that is passed in:
796 /// thus we can complete the cycle.
798 static PATypeHolder HandleUpRefs(const Type *ty) {
799 // If Ty isn't abstract, or if there are no up-references in it, then there is
800 // nothing to resolve here.
801 if (!ty->isAbstract() || UpRefs.empty()) return ty;
804 UR_OUT("Type '" << Ty->getDescription() <<
805 "' newly formed. Resolving upreferences.\n" <<
806 UpRefs.size() << " upreferences active!\n");
808 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
809 // to zero), we resolve them all together before we resolve them to Ty. At
810 // the end of the loop, if there is anything to resolve to Ty, it will be in
812 OpaqueType *TypeToResolve = 0;
814 for (unsigned i = 0; i != UpRefs.size(); ++i) {
815 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
816 << UpRefs[i].second->getDescription() << ") = "
817 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
818 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
819 // Decrement level of upreference
820 unsigned Level = --UpRefs[i].NestingLevel;
821 UpRefs[i].LastContainedTy = Ty;
822 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
823 if (Level == 0) { // Upreference should be resolved!
824 if (!TypeToResolve) {
825 TypeToResolve = UpRefs[i].UpRefTy;
827 UR_OUT(" * Resolving upreference for "
828 << UpRefs[i].second->getDescription() << "\n";
829 std::string OldName = UpRefs[i].UpRefTy->getDescription());
830 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
831 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
832 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
834 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
835 --i; // Do not skip the next element...
841 UR_OUT(" * Resolving upreference for "
842 << UpRefs[i].second->getDescription() << "\n";
843 std::string OldName = TypeToResolve->getDescription());
844 TypeToResolve->refineAbstractTypeTo(Ty);
850 //===----------------------------------------------------------------------===//
851 // RunVMAsmParser - Define an interface to this parser
852 //===----------------------------------------------------------------------===//
854 static Module* RunParser(Module * M);
856 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
859 CurFilename = Filename;
860 return RunParser(new Module(CurFilename));
863 Module *llvm::RunVMAsmParser(const char * AsmString, Module * M) {
864 set_scan_string(AsmString);
866 CurFilename = "from_memory";
868 return RunParser(new Module (CurFilename));
877 llvm::Module *ModuleVal;
878 llvm::Function *FunctionVal;
879 llvm::BasicBlock *BasicBlockVal;
880 llvm::TerminatorInst *TermInstVal;
881 llvm::Instruction *InstVal;
882 llvm::Constant *ConstVal;
884 const llvm::Type *PrimType;
885 std::list<llvm::PATypeHolder> *TypeList;
886 llvm::PATypeHolder *TypeVal;
887 llvm::Value *ValueVal;
888 std::vector<llvm::Value*> *ValueList;
889 llvm::ArgListType *ArgList;
890 llvm::TypeWithAttrs TypeWithAttrs;
891 llvm::TypeWithAttrsList *TypeWithAttrsList;
892 llvm::ValueRefList *ValueRefList;
894 // Represent the RHS of PHI node
895 std::list<std::pair<llvm::Value*,
896 llvm::BasicBlock*> > *PHIList;
897 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
898 std::vector<llvm::Constant*> *ConstVector;
900 llvm::GlobalValue::LinkageTypes Linkage;
901 llvm::FunctionType::ParameterAttributes ParamAttrs;
909 char *StrVal; // This memory is strdup'd!
910 llvm::ValID ValIDVal; // strdup'd memory maybe!
912 llvm::Instruction::BinaryOps BinaryOpVal;
913 llvm::Instruction::TermOps TermOpVal;
914 llvm::Instruction::MemoryOps MemOpVal;
915 llvm::Instruction::CastOps CastOpVal;
916 llvm::Instruction::OtherOps OtherOpVal;
917 llvm::Module::Endianness Endianness;
918 llvm::ICmpInst::Predicate IPredicate;
919 llvm::FCmpInst::Predicate FPredicate;
922 %type <ModuleVal> Module
923 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
924 %type <BasicBlockVal> BasicBlock InstructionList
925 %type <TermInstVal> BBTerminatorInst
926 %type <InstVal> Inst InstVal MemoryInst
927 %type <ConstVal> ConstVal ConstExpr
928 %type <ConstVector> ConstVector
929 %type <ArgList> ArgList ArgListH
930 %type <PHIList> PHIList
931 %type <ValueRefList> ValueRefList // For call param lists & GEP indices
932 %type <ValueList> IndexList // For GEP indices
933 %type <TypeList> TypeListI
934 %type <TypeWithAttrsList> ArgTypeList ArgTypeListI
935 %type <TypeWithAttrs> ArgType
936 %type <JumpTable> JumpTable
937 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
938 %type <BoolVal> OptVolatile // 'volatile' or not
939 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
940 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
941 %type <Linkage> GVInternalLinkage GVExternalLinkage
942 %type <Linkage> FunctionDefineLinkage FunctionDeclareLinkage
943 %type <Endianness> BigOrLittle
945 // ValueRef - Unresolved reference to a definition or BB
946 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
947 %type <ValueVal> ResolvedVal // <type> <valref> pair
948 // Tokens and types for handling constant integer values
950 // ESINT64VAL - A negative number within long long range
951 %token <SInt64Val> ESINT64VAL
953 // EUINT64VAL - A positive number within uns. long long range
954 %token <UInt64Val> EUINT64VAL
956 %token <SIntVal> SINTVAL // Signed 32 bit ints...
957 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
958 %type <SIntVal> INTVAL
959 %token <FPVal> FPVAL // Float or Double constant
962 %type <TypeVal> Types ResultTypes
963 %type <PrimType> IntType FPType PrimType // Classifications
964 %token <PrimType> VOID BOOL INT8 INT16 INT32 INT64
965 %token <PrimType> FLOAT DOUBLE LABEL
968 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
969 %type <StrVal> Name OptName OptAssign
970 %type <UIntVal> OptAlign OptCAlign
971 %type <StrVal> OptSection SectionString
973 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
974 %token DECLARE DEFINE GLOBAL CONSTANT SECTION VOLATILE
975 %token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
976 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
977 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
978 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
979 %token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
980 %token X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
982 %type <UIntVal> OptCallingConv
983 %type <ParamAttrs> OptParamAttrs ParamAttr
984 %type <ParamAttrs> OptFuncAttrs FuncAttr
986 // Basic Block Terminating Operators
987 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
990 %type <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
991 %token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
992 %token <OtherOpVal> ICMP FCMP
993 %type <IPredicate> IPredicates
994 %type <FPredicate> FPredicates
995 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
996 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
998 // Memory Instructions
999 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1002 %type <CastOpVal> CastOps
1003 %token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1004 %token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1007 %type <OtherOpVal> ShiftOps
1008 %token <OtherOpVal> PHI_TOK SELECT SHL LSHR ASHR VAARG
1009 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1011 // Function Attributes
1017 // Handle constant integer size restriction and conversion...
1021 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
1022 GEN_ERROR("Value too large for type!");
1027 // Operations that are notably excluded from this list include:
1028 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1030 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1031 LogicalOps : AND | OR | XOR;
1032 CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1033 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1034 ShiftOps : SHL | LSHR | ASHR;
1036 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1037 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1038 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1039 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1040 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1044 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1045 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1046 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1047 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1048 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1049 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1050 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1051 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1052 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1055 // These are some types that allow classification if we only want a particular
1056 // thing... for example, only a signed, unsigned, or integral type.
1057 IntType : INT64 | INT32 | INT16 | INT8;
1058 FPType : FLOAT | DOUBLE;
1060 // OptAssign - Value producing statements have an optional assignment component
1061 OptAssign : Name '=' {
1071 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1072 | WEAK { $$ = GlobalValue::WeakLinkage; }
1073 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1074 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1075 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1079 : DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1080 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1081 | EXTERNAL { $$ = GlobalValue::ExternalLinkage; }
1084 FunctionDeclareLinkage
1085 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1086 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1087 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1090 FunctionDefineLinkage
1091 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1092 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1093 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1094 | WEAK { $$ = GlobalValue::WeakLinkage; }
1095 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1098 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1099 CCC_TOK { $$ = CallingConv::C; } |
1100 CSRETCC_TOK { $$ = CallingConv::CSRet; } |
1101 FASTCC_TOK { $$ = CallingConv::Fast; } |
1102 COLDCC_TOK { $$ = CallingConv::Cold; } |
1103 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1104 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1106 if ((unsigned)$2 != $2)
1107 GEN_ERROR("Calling conv too large!");
1112 ParamAttr : ZEXT { $$ = FunctionType::ZExtAttribute; }
1113 | SEXT { $$ = FunctionType::SExtAttribute; }
1116 OptParamAttrs : /* empty */ { $$ = FunctionType::NoAttributeSet; }
1117 | OptParamAttrs ParamAttr {
1118 $$ = FunctionType::ParameterAttributes($1 | $2);
1122 FuncAttr : NORETURN { $$ = FunctionType::NoReturnAttribute; }
1126 OptFuncAttrs : /* empty */ { $$ = FunctionType::NoAttributeSet; }
1127 | OptFuncAttrs FuncAttr {
1128 $$ = FunctionType::ParameterAttributes($1 | $2);
1132 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1133 // a comma before it.
1134 OptAlign : /*empty*/ { $$ = 0; } |
1137 if ($$ != 0 && !isPowerOf2_32($$))
1138 GEN_ERROR("Alignment must be a power of two!");
1141 OptCAlign : /*empty*/ { $$ = 0; } |
1142 ',' ALIGN EUINT64VAL {
1144 if ($$ != 0 && !isPowerOf2_32($$))
1145 GEN_ERROR("Alignment must be a power of two!");
1150 SectionString : SECTION STRINGCONSTANT {
1151 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1152 if ($2[i] == '"' || $2[i] == '\\')
1153 GEN_ERROR("Invalid character in section name!");
1158 OptSection : /*empty*/ { $$ = 0; } |
1159 SectionString { $$ = $1; };
1161 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1162 // is set to be the global we are processing.
1164 GlobalVarAttributes : /* empty */ {} |
1165 ',' GlobalVarAttribute GlobalVarAttributes {};
1166 GlobalVarAttribute : SectionString {
1167 CurGV->setSection($1);
1171 | ALIGN EUINT64VAL {
1172 if ($2 != 0 && !isPowerOf2_32($2))
1173 GEN_ERROR("Alignment must be a power of two!");
1174 CurGV->setAlignment($2);
1178 //===----------------------------------------------------------------------===//
1179 // Types includes all predefined types... except void, because it can only be
1180 // used in specific contexts (function returning void for example).
1182 // Derived types are added later...
1184 PrimType : BOOL | INT8 | INT16 | INT32 | INT64 | FLOAT | DOUBLE | LABEL ;
1188 $$ = new PATypeHolder(OpaqueType::get());
1192 $$ = new PATypeHolder($1);
1195 | Types '*' { // Pointer type?
1196 if (*$1 == Type::LabelTy)
1197 GEN_ERROR("Cannot form a pointer to a basic block");
1198 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1202 | SymbolicValueRef { // Named types are also simple types...
1203 const Type* tmp = getTypeVal($1);
1205 $$ = new PATypeHolder(tmp);
1207 | '\\' EUINT64VAL { // Type UpReference
1208 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range!");
1209 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1210 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1211 $$ = new PATypeHolder(OT);
1212 UR_OUT("New Upreference!\n");
1215 | Types '(' ArgTypeListI ')' OptFuncAttrs {
1216 std::vector<const Type*> Params;
1217 std::vector<FunctionType::ParameterAttributes> Attrs;
1218 Attrs.push_back($5);
1219 for (TypeWithAttrsList::iterator I=$3->begin(), E=$3->end(); I != E; ++I) {
1220 Params.push_back(I->Ty->get());
1221 if (I->Ty->get() != Type::VoidTy)
1222 Attrs.push_back(I->Attrs);
1224 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1225 if (isVarArg) Params.pop_back();
1227 FunctionType *FT = FunctionType::get(*$1, Params, isVarArg, Attrs);
1228 delete $3; // Delete the argument list
1229 delete $1; // Delete the return type handle
1230 $$ = new PATypeHolder(HandleUpRefs(FT));
1233 | VOID '(' ArgTypeListI ')' OptFuncAttrs {
1234 std::vector<const Type*> Params;
1235 std::vector<FunctionType::ParameterAttributes> Attrs;
1236 Attrs.push_back($5);
1237 for (TypeWithAttrsList::iterator I=$3->begin(), E=$3->end(); I != E; ++I) {
1238 Params.push_back(I->Ty->get());
1239 if (I->Ty->get() != Type::VoidTy)
1240 Attrs.push_back(I->Attrs);
1242 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1243 if (isVarArg) Params.pop_back();
1245 FunctionType *FT = FunctionType::get($1, Params, isVarArg, Attrs);
1246 delete $3; // Delete the argument list
1247 $$ = new PATypeHolder(HandleUpRefs(FT));
1251 | '[' EUINT64VAL 'x' Types ']' { // Sized array type?
1252 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1256 | '<' EUINT64VAL 'x' Types '>' { // Packed array type?
1257 const llvm::Type* ElemTy = $4->get();
1258 if ((unsigned)$2 != $2)
1259 GEN_ERROR("Unsigned result not equal to signed result");
1260 if (!ElemTy->isPrimitiveType())
1261 GEN_ERROR("Elemental type of a PackedType must be primitive");
1262 if (!isPowerOf2_32($2))
1263 GEN_ERROR("Vector length should be a power of 2!");
1264 $$ = new PATypeHolder(HandleUpRefs(PackedType::get(*$4, (unsigned)$2)));
1268 | '{' TypeListI '}' { // Structure type?
1269 std::vector<const Type*> Elements;
1270 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1271 E = $2->end(); I != E; ++I)
1272 Elements.push_back(*I);
1274 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1278 | '{' '}' { // Empty structure type?
1279 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1282 | '<' '{' TypeListI '}' '>' {
1283 std::vector<const Type*> Elements;
1284 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1285 E = $3->end(); I != E; ++I)
1286 Elements.push_back(*I);
1288 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1292 | '<' '{' '}' '>' { // Empty structure type?
1293 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1299 : Types OptParamAttrs {
1307 if (!UpRefs.empty())
1308 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1309 if (!(*$1)->isFirstClassType())
1310 GEN_ERROR("LLVM functions cannot return aggregate types!");
1314 $$ = new PATypeHolder(Type::VoidTy);
1318 ArgTypeList : ArgType {
1319 $$ = new TypeWithAttrsList();
1323 | ArgTypeList ',' ArgType {
1324 ($$=$1)->push_back($3);
1331 | ArgTypeList ',' DOTDOTDOT {
1333 TypeWithAttrs TWA; TWA.Attrs = FunctionType::NoAttributeSet;
1334 TWA.Ty = new PATypeHolder(Type::VoidTy);
1339 $$ = new TypeWithAttrsList;
1340 TypeWithAttrs TWA; TWA.Attrs = FunctionType::NoAttributeSet;
1341 TWA.Ty = new PATypeHolder(Type::VoidTy);
1346 $$ = new TypeWithAttrsList();
1350 // TypeList - Used for struct declarations and as a basis for function type
1351 // declaration type lists
1354 $$ = new std::list<PATypeHolder>();
1355 $$->push_back(*$1); delete $1;
1358 | TypeListI ',' Types {
1359 ($$=$1)->push_back(*$3); delete $3;
1363 // ConstVal - The various declarations that go into the constant pool. This
1364 // production is used ONLY to represent constants that show up AFTER a 'const',
1365 // 'constant' or 'global' token at global scope. Constants that can be inlined
1366 // into other expressions (such as integers and constexprs) are handled by the
1367 // ResolvedVal, ValueRef and ConstValueRef productions.
1369 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1370 if (!UpRefs.empty())
1371 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1372 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1374 GEN_ERROR("Cannot make array constant with type: '" +
1375 (*$1)->getDescription() + "'!");
1376 const Type *ETy = ATy->getElementType();
1377 int NumElements = ATy->getNumElements();
1379 // Verify that we have the correct size...
1380 if (NumElements != -1 && NumElements != (int)$3->size())
1381 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1382 utostr($3->size()) + " arguments, but has size of " +
1383 itostr(NumElements) + "!");
1385 // Verify all elements are correct type!
1386 for (unsigned i = 0; i < $3->size(); i++) {
1387 if (ETy != (*$3)[i]->getType())
1388 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1389 ETy->getDescription() +"' as required!\nIt is of type '"+
1390 (*$3)[i]->getType()->getDescription() + "'.");
1393 $$ = ConstantArray::get(ATy, *$3);
1394 delete $1; delete $3;
1398 if (!UpRefs.empty())
1399 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1400 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1402 GEN_ERROR("Cannot make array constant with type: '" +
1403 (*$1)->getDescription() + "'!");
1405 int NumElements = ATy->getNumElements();
1406 if (NumElements != -1 && NumElements != 0)
1407 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1408 " arguments, but has size of " + itostr(NumElements) +"!");
1409 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1413 | Types 'c' STRINGCONSTANT {
1414 if (!UpRefs.empty())
1415 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1416 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1418 GEN_ERROR("Cannot make array constant with type: '" +
1419 (*$1)->getDescription() + "'!");
1421 int NumElements = ATy->getNumElements();
1422 const Type *ETy = ATy->getElementType();
1423 char *EndStr = UnEscapeLexed($3, true);
1424 if (NumElements != -1 && NumElements != (EndStr-$3))
1425 GEN_ERROR("Can't build string constant of size " +
1426 itostr((int)(EndStr-$3)) +
1427 " when array has size " + itostr(NumElements) + "!");
1428 std::vector<Constant*> Vals;
1429 if (ETy == Type::Int8Ty) {
1430 for (unsigned char *C = (unsigned char *)$3;
1431 C != (unsigned char*)EndStr; ++C)
1432 Vals.push_back(ConstantInt::get(ETy, *C));
1435 GEN_ERROR("Cannot build string arrays of non byte sized elements!");
1438 $$ = ConstantArray::get(ATy, Vals);
1442 | Types '<' ConstVector '>' { // Nonempty unsized arr
1443 if (!UpRefs.empty())
1444 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1445 const PackedType *PTy = dyn_cast<PackedType>($1->get());
1447 GEN_ERROR("Cannot make packed constant with type: '" +
1448 (*$1)->getDescription() + "'!");
1449 const Type *ETy = PTy->getElementType();
1450 int NumElements = PTy->getNumElements();
1452 // Verify that we have the correct size...
1453 if (NumElements != -1 && NumElements != (int)$3->size())
1454 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1455 utostr($3->size()) + " arguments, but has size of " +
1456 itostr(NumElements) + "!");
1458 // Verify all elements are correct type!
1459 for (unsigned i = 0; i < $3->size(); i++) {
1460 if (ETy != (*$3)[i]->getType())
1461 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1462 ETy->getDescription() +"' as required!\nIt is of type '"+
1463 (*$3)[i]->getType()->getDescription() + "'.");
1466 $$ = ConstantPacked::get(PTy, *$3);
1467 delete $1; delete $3;
1470 | Types '{' ConstVector '}' {
1471 const StructType *STy = dyn_cast<StructType>($1->get());
1473 GEN_ERROR("Cannot make struct constant with type: '" +
1474 (*$1)->getDescription() + "'!");
1476 if ($3->size() != STy->getNumContainedTypes())
1477 GEN_ERROR("Illegal number of initializers for structure type!");
1479 // Check to ensure that constants are compatible with the type initializer!
1480 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1481 if ((*$3)[i]->getType() != STy->getElementType(i))
1482 GEN_ERROR("Expected type '" +
1483 STy->getElementType(i)->getDescription() +
1484 "' for element #" + utostr(i) +
1485 " of structure initializer!");
1487 // Check to ensure that Type is not packed
1488 if (STy->isPacked())
1489 GEN_ERROR("Unpacked Initializer to packed type '" + STy->getDescription() + "'");
1491 $$ = ConstantStruct::get(STy, *$3);
1492 delete $1; delete $3;
1496 if (!UpRefs.empty())
1497 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1498 const StructType *STy = dyn_cast<StructType>($1->get());
1500 GEN_ERROR("Cannot make struct constant with type: '" +
1501 (*$1)->getDescription() + "'!");
1503 if (STy->getNumContainedTypes() != 0)
1504 GEN_ERROR("Illegal number of initializers for structure type!");
1506 // Check to ensure that Type is not packed
1507 if (STy->isPacked())
1508 GEN_ERROR("Unpacked Initializer to packed type '" + STy->getDescription() + "'");
1510 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1514 | Types '<' '{' ConstVector '}' '>' {
1515 const StructType *STy = dyn_cast<StructType>($1->get());
1517 GEN_ERROR("Cannot make struct constant with type: '" +
1518 (*$1)->getDescription() + "'!");
1520 if ($4->size() != STy->getNumContainedTypes())
1521 GEN_ERROR("Illegal number of initializers for structure type!");
1523 // Check to ensure that constants are compatible with the type initializer!
1524 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1525 if ((*$4)[i]->getType() != STy->getElementType(i))
1526 GEN_ERROR("Expected type '" +
1527 STy->getElementType(i)->getDescription() +
1528 "' for element #" + utostr(i) +
1529 " of structure initializer!");
1531 // Check to ensure that Type is packed
1532 if (!STy->isPacked())
1533 GEN_ERROR("Packed Initializer to unpacked type '" + STy->getDescription() + "'");
1535 $$ = ConstantStruct::get(STy, *$4);
1536 delete $1; delete $4;
1539 | Types '<' '{' '}' '>' {
1540 if (!UpRefs.empty())
1541 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1542 const StructType *STy = dyn_cast<StructType>($1->get());
1544 GEN_ERROR("Cannot make struct constant with type: '" +
1545 (*$1)->getDescription() + "'!");
1547 if (STy->getNumContainedTypes() != 0)
1548 GEN_ERROR("Illegal number of initializers for structure type!");
1550 // Check to ensure that Type is packed
1551 if (!STy->isPacked())
1552 GEN_ERROR("Packed Initializer to unpacked type '" + STy->getDescription() + "'");
1554 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1559 if (!UpRefs.empty())
1560 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1561 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1563 GEN_ERROR("Cannot make null pointer constant with type: '" +
1564 (*$1)->getDescription() + "'!");
1566 $$ = ConstantPointerNull::get(PTy);
1571 if (!UpRefs.empty())
1572 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1573 $$ = UndefValue::get($1->get());
1577 | Types SymbolicValueRef {
1578 if (!UpRefs.empty())
1579 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1580 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1582 GEN_ERROR("Global const reference must be a pointer type!");
1584 // ConstExprs can exist in the body of a function, thus creating
1585 // GlobalValues whenever they refer to a variable. Because we are in
1586 // the context of a function, getValNonImprovising will search the functions
1587 // symbol table instead of the module symbol table for the global symbol,
1588 // which throws things all off. To get around this, we just tell
1589 // getValNonImprovising that we are at global scope here.
1591 Function *SavedCurFn = CurFun.CurrentFunction;
1592 CurFun.CurrentFunction = 0;
1594 Value *V = getValNonImprovising(Ty, $2);
1597 CurFun.CurrentFunction = SavedCurFn;
1599 // If this is an initializer for a constant pointer, which is referencing a
1600 // (currently) undefined variable, create a stub now that shall be replaced
1601 // in the future with the right type of variable.
1604 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1605 const PointerType *PT = cast<PointerType>(Ty);
1607 // First check to see if the forward references value is already created!
1608 PerModuleInfo::GlobalRefsType::iterator I =
1609 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1611 if (I != CurModule.GlobalRefs.end()) {
1612 V = I->second; // Placeholder already exists, use it...
1616 if ($2.Type == ValID::NameVal) Name = $2.Name;
1618 // Create the forward referenced global.
1620 if (const FunctionType *FTy =
1621 dyn_cast<FunctionType>(PT->getElementType())) {
1622 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1623 CurModule.CurrentModule);
1625 GV = new GlobalVariable(PT->getElementType(), false,
1626 GlobalValue::ExternalLinkage, 0,
1627 Name, CurModule.CurrentModule);
1630 // Keep track of the fact that we have a forward ref to recycle it
1631 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1636 $$ = cast<GlobalValue>(V);
1637 delete $1; // Free the type handle
1641 if (!UpRefs.empty())
1642 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1643 if ($1->get() != $2->getType())
1644 GEN_ERROR("Mismatched types for constant expression: " +
1645 (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1650 | Types ZEROINITIALIZER {
1651 if (!UpRefs.empty())
1652 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1653 const Type *Ty = $1->get();
1654 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1655 GEN_ERROR("Cannot create a null initialized value of this type!");
1656 $$ = Constant::getNullValue(Ty);
1660 | IntType ESINT64VAL { // integral constants
1661 if (!ConstantInt::isValueValidForType($1, $2))
1662 GEN_ERROR("Constant value doesn't fit in type!");
1663 $$ = ConstantInt::get($1, $2);
1666 | IntType EUINT64VAL { // integral constants
1667 if (!ConstantInt::isValueValidForType($1, $2))
1668 GEN_ERROR("Constant value doesn't fit in type!");
1669 $$ = ConstantInt::get($1, $2);
1672 | BOOL TRUETOK { // Boolean constants
1673 $$ = ConstantInt::getTrue();
1676 | BOOL FALSETOK { // Boolean constants
1677 $$ = ConstantInt::getFalse();
1680 | FPType FPVAL { // Float & Double constants
1681 if (!ConstantFP::isValueValidForType($1, $2))
1682 GEN_ERROR("Floating point constant invalid for type!!");
1683 $$ = ConstantFP::get($1, $2);
1688 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1689 if (!UpRefs.empty())
1690 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1692 const Type *Ty = $5->get();
1693 if (!Val->getType()->isFirstClassType())
1694 GEN_ERROR("cast constant expression from a non-primitive type: '" +
1695 Val->getType()->getDescription() + "'!");
1696 if (!Ty->isFirstClassType())
1697 GEN_ERROR("cast constant expression to a non-primitive type: '" +
1698 Ty->getDescription() + "'!");
1699 $$ = ConstantExpr::getCast($1, $3, $5->get());
1702 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1703 if (!isa<PointerType>($3->getType()))
1704 GEN_ERROR("GetElementPtr requires a pointer operand!");
1707 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1709 GEN_ERROR("Index list invalid for constant getelementptr!");
1711 std::vector<Constant*> IdxVec;
1712 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1713 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1714 IdxVec.push_back(C);
1716 GEN_ERROR("Indices to constant getelementptr must be constants!");
1720 $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1723 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1724 if ($3->getType() != Type::BoolTy)
1725 GEN_ERROR("Select condition must be of boolean type!");
1726 if ($5->getType() != $7->getType())
1727 GEN_ERROR("Select operand types must match!");
1728 $$ = ConstantExpr::getSelect($3, $5, $7);
1731 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1732 if ($3->getType() != $5->getType())
1733 GEN_ERROR("Binary operator types must match!");
1735 $$ = ConstantExpr::get($1, $3, $5);
1737 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1738 if ($3->getType() != $5->getType())
1739 GEN_ERROR("Logical operator types must match!");
1740 if (!$3->getType()->isIntegral()) {
1741 if (!isa<PackedType>($3->getType()) ||
1742 !cast<PackedType>($3->getType())->getElementType()->isIntegral())
1743 GEN_ERROR("Logical operator requires integral operands!");
1745 $$ = ConstantExpr::get($1, $3, $5);
1748 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1749 if ($4->getType() != $6->getType())
1750 GEN_ERROR("icmp operand types must match!");
1751 $$ = ConstantExpr::getICmp($2, $4, $6);
1753 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1754 if ($4->getType() != $6->getType())
1755 GEN_ERROR("fcmp operand types must match!");
1756 $$ = ConstantExpr::getFCmp($2, $4, $6);
1758 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1759 if ($5->getType() != Type::Int8Ty)
1760 GEN_ERROR("Shift count for shift constant must be i8 type!");
1761 if (!$3->getType()->isInteger())
1762 GEN_ERROR("Shift constant expression requires integer operand!");
1764 $$ = ConstantExpr::get($1, $3, $5);
1767 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1768 if (!ExtractElementInst::isValidOperands($3, $5))
1769 GEN_ERROR("Invalid extractelement operands!");
1770 $$ = ConstantExpr::getExtractElement($3, $5);
1773 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1774 if (!InsertElementInst::isValidOperands($3, $5, $7))
1775 GEN_ERROR("Invalid insertelement operands!");
1776 $$ = ConstantExpr::getInsertElement($3, $5, $7);
1779 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1780 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1781 GEN_ERROR("Invalid shufflevector operands!");
1782 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1787 // ConstVector - A list of comma separated constants.
1788 ConstVector : ConstVector ',' ConstVal {
1789 ($$ = $1)->push_back($3);
1793 $$ = new std::vector<Constant*>();
1799 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1800 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1803 //===----------------------------------------------------------------------===//
1804 // Rules to match Modules
1805 //===----------------------------------------------------------------------===//
1807 // Module rule: Capture the result of parsing the whole file into a result
1812 $$ = ParserResult = CurModule.CurrentModule;
1813 CurModule.ModuleDone();
1817 $$ = ParserResult = CurModule.CurrentModule;
1818 CurModule.ModuleDone();
1825 | DefinitionList Definition
1829 : DEFINE { CurFun.isDeclare = false } Function {
1830 CurFun.FunctionDone();
1833 | DECLARE { CurFun.isDeclare = true; } FunctionProto {
1836 | MODULE ASM_TOK AsmBlock {
1840 // Emit an error if there are any unresolved types left.
1841 if (!CurModule.LateResolveTypes.empty()) {
1842 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
1843 if (DID.Type == ValID::NameVal) {
1844 GEN_ERROR("Reference to an undefined type: '"+DID.getName() + "'");
1846 GEN_ERROR("Reference to an undefined type: #" + itostr(DID.Num));
1851 | OptAssign TYPE Types {
1852 if (!UpRefs.empty())
1853 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
1854 // Eagerly resolve types. This is not an optimization, this is a
1855 // requirement that is due to the fact that we could have this:
1857 // %list = type { %list * }
1858 // %list = type { %list * } ; repeated type decl
1860 // If types are not resolved eagerly, then the two types will not be
1861 // determined to be the same type!
1863 ResolveTypeTo($1, *$3);
1865 if (!setTypeName(*$3, $1) && !$1) {
1867 // If this is a named type that is not a redefinition, add it to the slot
1869 CurModule.Types.push_back(*$3);
1875 | OptAssign TYPE VOID {
1876 ResolveTypeTo($1, $3);
1878 if (!setTypeName($3, $1) && !$1) {
1880 // If this is a named type that is not a redefinition, add it to the slot
1882 CurModule.Types.push_back($3);
1886 | OptAssign GlobalType ConstVal { /* "Externally Visible" Linkage */
1888 GEN_ERROR("Global value initializer is not a constant!");
1889 CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage, $2,
1892 } GlobalVarAttributes {
1895 | OptAssign GVInternalLinkage GlobalType ConstVal {
1897 GEN_ERROR("Global value initializer is not a constant!");
1898 CurGV = ParseGlobalVariable($1, $2, $3, $4->getType(), $4);
1900 } GlobalVarAttributes {
1903 | OptAssign GVExternalLinkage GlobalType Types {
1904 if (!UpRefs.empty())
1905 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
1906 CurGV = ParseGlobalVariable($1, $2, $3, *$4, 0);
1909 } GlobalVarAttributes {
1913 | TARGET TargetDefinition {
1916 | DEPLIBS '=' LibrariesDefinition {
1922 AsmBlock : STRINGCONSTANT {
1923 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
1924 char *EndStr = UnEscapeLexed($1, true);
1925 std::string NewAsm($1, EndStr);
1928 if (AsmSoFar.empty())
1929 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
1931 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
1935 BigOrLittle : BIG { $$ = Module::BigEndian; };
1936 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1938 TargetDefinition : ENDIAN '=' BigOrLittle {
1939 CurModule.CurrentModule->setEndianness($3);
1942 | POINTERSIZE '=' EUINT64VAL {
1944 CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1946 CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1948 GEN_ERROR("Invalid pointer size: '" + utostr($3) + "'!");
1951 | TRIPLE '=' STRINGCONSTANT {
1952 CurModule.CurrentModule->setTargetTriple($3);
1955 | DATALAYOUT '=' STRINGCONSTANT {
1956 CurModule.CurrentModule->setDataLayout($3);
1960 LibrariesDefinition : '[' LibList ']';
1962 LibList : LibList ',' STRINGCONSTANT {
1963 CurModule.CurrentModule->addLibrary($3);
1968 CurModule.CurrentModule->addLibrary($1);
1972 | /* empty: end of list */ {
1977 //===----------------------------------------------------------------------===//
1978 // Rules to match Function Headers
1979 //===----------------------------------------------------------------------===//
1981 Name : VAR_ID | STRINGCONSTANT;
1982 OptName : Name | /*empty*/ { $$ = 0; };
1984 ArgListH : ArgListH ',' Types OptParamAttrs OptName {
1985 if (!UpRefs.empty())
1986 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
1987 if (*$3 == Type::VoidTy)
1988 GEN_ERROR("void typed arguments are invalid!");
1989 ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
1994 | Types OptParamAttrs OptName {
1995 if (!UpRefs.empty())
1996 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1997 if (*$1 == Type::VoidTy)
1998 GEN_ERROR("void typed arguments are invalid!");
1999 ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2000 $$ = new ArgListType;
2005 ArgList : ArgListH {
2009 | ArgListH ',' DOTDOTDOT {
2011 struct ArgListEntry E;
2012 E.Ty = new PATypeHolder(Type::VoidTy);
2014 E.Attrs = FunctionType::NoAttributeSet;
2019 $$ = new ArgListType;
2020 struct ArgListEntry E;
2021 E.Ty = new PATypeHolder(Type::VoidTy);
2023 E.Attrs = FunctionType::NoAttributeSet;
2032 FunctionHeaderH : OptCallingConv ResultTypes Name '(' ArgList ')'
2033 OptFuncAttrs OptSection OptAlign {
2035 std::string FunctionName($3);
2036 free($3); // Free strdup'd memory!
2038 // Check the function result for abstractness if this is a define. We should
2039 // have no abstract types at this point
2040 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($2))
2041 GEN_ERROR("Reference to abstract result: "+ $2->get()->getDescription());
2043 std::vector<const Type*> ParamTypeList;
2044 std::vector<FunctionType::ParameterAttributes> ParamAttrs;
2045 ParamAttrs.push_back($7);
2046 if ($5) { // If there are arguments...
2047 for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I) {
2048 const Type* Ty = I->Ty->get();
2049 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2050 GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2051 ParamTypeList.push_back(Ty);
2052 if (Ty != Type::VoidTy)
2053 ParamAttrs.push_back(I->Attrs);
2057 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2058 if (isVarArg) ParamTypeList.pop_back();
2060 FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg,
2062 const PointerType *PFT = PointerType::get(FT);
2066 if (!FunctionName.empty()) {
2067 ID = ValID::create((char*)FunctionName.c_str());
2069 ID = ValID::create((int)CurModule.Values[PFT].size());
2073 // See if this function was forward referenced. If so, recycle the object.
2074 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2075 // Move the function to the end of the list, from whereever it was
2076 // previously inserted.
2077 Fn = cast<Function>(FWRef);
2078 CurModule.CurrentModule->getFunctionList().remove(Fn);
2079 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2080 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2081 (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
2082 // If this is the case, either we need to be a forward decl, or it needs
2084 if (!CurFun.isDeclare && !Fn->isExternal())
2085 GEN_ERROR("Redefinition of function '" + FunctionName + "'!");
2087 // Make sure to strip off any argument names so we can't get conflicts.
2088 if (Fn->isExternal())
2089 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2092 } else { // Not already defined?
2093 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
2094 CurModule.CurrentModule);
2096 InsertValue(Fn, CurModule.Values);
2099 CurFun.FunctionStart(Fn);
2101 if (CurFun.isDeclare) {
2102 // If we have declaration, always overwrite linkage. This will allow us to
2103 // correctly handle cases, when pointer to function is passed as argument to
2104 // another function.
2105 Fn->setLinkage(CurFun.Linkage);
2107 Fn->setCallingConv($1);
2108 Fn->setAlignment($9);
2114 // Add all of the arguments we parsed to the function...
2115 if ($5) { // Is null if empty...
2116 if (isVarArg) { // Nuke the last entry
2117 assert($5->back().Ty->get() == Type::VoidTy && $5->back().Name == 0&&
2118 "Not a varargs marker!");
2119 delete $5->back().Ty;
2120 $5->pop_back(); // Delete the last entry
2122 Function::arg_iterator ArgIt = Fn->arg_begin();
2124 for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I, ++ArgIt) {
2125 delete I->Ty; // Delete the typeholder...
2126 setValueName(ArgIt, I->Name); // Insert arg into symtab...
2132 delete $5; // We're now done with the argument list
2137 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2139 FunctionHeader : FunctionDefineLinkage FunctionHeaderH BEGIN {
2140 $$ = CurFun.CurrentFunction;
2142 // Make sure that we keep track of the linkage type even if there was a
2143 // previous "declare".
2147 END : ENDTOK | '}'; // Allow end of '}' to end a function
2149 Function : BasicBlockList END {
2154 FunctionProto : FunctionDeclareLinkage FunctionHeaderH {
2155 CurFun.CurrentFunction->setLinkage($1);
2156 $$ = CurFun.CurrentFunction;
2157 CurFun.FunctionDone();
2161 //===----------------------------------------------------------------------===//
2162 // Rules to match Basic Blocks
2163 //===----------------------------------------------------------------------===//
2165 OptSideEffect : /* empty */ {
2174 ConstValueRef : ESINT64VAL { // A reference to a direct constant
2175 $$ = ValID::create($1);
2179 $$ = ValID::create($1);
2182 | FPVAL { // Perhaps it's an FP constant?
2183 $$ = ValID::create($1);
2187 $$ = ValID::create(ConstantInt::getTrue());
2191 $$ = ValID::create(ConstantInt::getFalse());
2195 $$ = ValID::createNull();
2199 $$ = ValID::createUndef();
2202 | ZEROINITIALIZER { // A vector zero constant.
2203 $$ = ValID::createZeroInit();
2206 | '<' ConstVector '>' { // Nonempty unsized packed vector
2207 const Type *ETy = (*$2)[0]->getType();
2208 int NumElements = $2->size();
2210 PackedType* pt = PackedType::get(ETy, NumElements);
2211 PATypeHolder* PTy = new PATypeHolder(
2219 // Verify all elements are correct type!
2220 for (unsigned i = 0; i < $2->size(); i++) {
2221 if (ETy != (*$2)[i]->getType())
2222 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2223 ETy->getDescription() +"' as required!\nIt is of type '" +
2224 (*$2)[i]->getType()->getDescription() + "'.");
2227 $$ = ValID::create(ConstantPacked::get(pt, *$2));
2228 delete PTy; delete $2;
2232 $$ = ValID::create($1);
2235 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2236 char *End = UnEscapeLexed($3, true);
2237 std::string AsmStr = std::string($3, End);
2238 End = UnEscapeLexed($5, true);
2239 std::string Constraints = std::string($5, End);
2240 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2246 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2249 SymbolicValueRef : INTVAL { // Is it an integer reference...?
2250 $$ = ValID::create($1);
2253 | Name { // Is it a named reference...?
2254 $$ = ValID::create($1);
2258 // ValueRef - A reference to a definition... either constant or symbolic
2259 ValueRef : SymbolicValueRef | ConstValueRef;
2262 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2263 // type immediately preceeds the value reference, and allows complex constant
2264 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2265 ResolvedVal : Types ValueRef {
2266 if (!UpRefs.empty())
2267 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2268 $$ = getVal(*$1, $2);
2274 BasicBlockList : BasicBlockList BasicBlock {
2278 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2284 // Basic blocks are terminated by branching instructions:
2285 // br, br/cc, switch, ret
2287 BasicBlock : InstructionList OptAssign BBTerminatorInst {
2288 setValueName($3, $2);
2292 $1->getInstList().push_back($3);
2298 InstructionList : InstructionList Inst {
2299 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2300 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2301 if (CI2->getParent() == 0)
2302 $1->getInstList().push_back(CI2);
2303 $1->getInstList().push_back($2);
2308 $$ = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
2311 // Make sure to move the basic block to the correct location in the
2312 // function, instead of leaving it inserted wherever it was first
2314 Function::BasicBlockListType &BBL =
2315 CurFun.CurrentFunction->getBasicBlockList();
2316 BBL.splice(BBL.end(), BBL, $$);
2320 $$ = getBBVal(ValID::create($1), true);
2323 // Make sure to move the basic block to the correct location in the
2324 // function, instead of leaving it inserted wherever it was first
2326 Function::BasicBlockListType &BBL =
2327 CurFun.CurrentFunction->getBasicBlockList();
2328 BBL.splice(BBL.end(), BBL, $$);
2332 BBTerminatorInst : RET ResolvedVal { // Return with a result...
2333 $$ = new ReturnInst($2);
2336 | RET VOID { // Return with no result...
2337 $$ = new ReturnInst();
2340 | BR LABEL ValueRef { // Unconditional Branch...
2341 BasicBlock* tmpBB = getBBVal($3);
2343 $$ = new BranchInst(tmpBB);
2344 } // Conditional Branch...
2345 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2346 BasicBlock* tmpBBA = getBBVal($6);
2348 BasicBlock* tmpBBB = getBBVal($9);
2350 Value* tmpVal = getVal(Type::BoolTy, $3);
2352 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2354 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2355 Value* tmpVal = getVal($2, $3);
2357 BasicBlock* tmpBB = getBBVal($6);
2359 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2362 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2364 for (; I != E; ++I) {
2365 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2366 S->addCase(CI, I->second);
2368 GEN_ERROR("Switch case is constant, but not a simple integer!");
2373 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2374 Value* tmpVal = getVal($2, $3);
2376 BasicBlock* tmpBB = getBBVal($6);
2378 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2382 | INVOKE OptCallingConv ResultTypes ValueRef '(' ValueRefList ')' OptFuncAttrs
2383 TO LABEL ValueRef UNWIND LABEL ValueRef {
2385 // Handle the short syntax
2386 const PointerType *PFTy = 0;
2387 const FunctionType *Ty = 0;
2388 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2389 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2390 // Pull out the types of all of the arguments...
2391 std::vector<const Type*> ParamTypes;
2392 FunctionType::ParamAttrsList ParamAttrs;
2393 ParamAttrs.push_back($8);
2394 for (ValueRefList::iterator I = $6->begin(), E = $6->end(); I != E; ++I) {
2395 const Type *Ty = I->Val->getType();
2396 if (Ty == Type::VoidTy)
2397 GEN_ERROR("Short call syntax cannot be used with varargs");
2398 ParamTypes.push_back(Ty);
2399 ParamAttrs.push_back(I->Attrs);
2402 Ty = FunctionType::get($3->get(), ParamTypes, false, ParamAttrs);
2403 PFTy = PointerType::get(Ty);
2406 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2408 BasicBlock *Normal = getBBVal($11);
2410 BasicBlock *Except = getBBVal($14);
2413 // Check the arguments
2415 if ($6->empty()) { // Has no arguments?
2416 // Make sure no arguments is a good thing!
2417 if (Ty->getNumParams() != 0)
2418 GEN_ERROR("No arguments passed to a function that "
2419 "expects arguments!");
2420 } else { // Has arguments?
2421 // Loop through FunctionType's arguments and ensure they are specified
2423 FunctionType::param_iterator I = Ty->param_begin();
2424 FunctionType::param_iterator E = Ty->param_end();
2425 ValueRefList::iterator ArgI = $6->begin(), ArgE = $6->end();
2427 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2428 if (ArgI->Val->getType() != *I)
2429 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2430 (*I)->getDescription() + "'!");
2431 Args.push_back(ArgI->Val);
2434 if (Ty->isVarArg()) {
2436 for (; ArgI != ArgE; ++ArgI)
2437 Args.push_back(ArgI->Val); // push the remaining varargs
2438 } else if (I != E || ArgI != ArgE)
2439 GEN_ERROR("Invalid number of parameters detected!");
2442 // Create the InvokeInst
2443 InvokeInst *II = new InvokeInst(V, Normal, Except, Args);
2444 II->setCallingConv($2);
2450 $$ = new UnwindInst();
2454 $$ = new UnreachableInst();
2460 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2462 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
2465 GEN_ERROR("May only switch on a constant pool value!");
2467 BasicBlock* tmpBB = getBBVal($6);
2469 $$->push_back(std::make_pair(V, tmpBB));
2471 | IntType ConstValueRef ',' LABEL ValueRef {
2472 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2473 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
2477 GEN_ERROR("May only switch on a constant pool value!");
2479 BasicBlock* tmpBB = getBBVal($5);
2481 $$->push_back(std::make_pair(V, tmpBB));
2484 Inst : OptAssign InstVal {
2485 // Is this definition named?? if so, assign the name...
2486 setValueName($2, $1);
2493 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2494 if (!UpRefs.empty())
2495 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2496 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2497 Value* tmpVal = getVal(*$1, $3);
2499 BasicBlock* tmpBB = getBBVal($5);
2501 $$->push_back(std::make_pair(tmpVal, tmpBB));
2504 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2506 Value* tmpVal = getVal($1->front().first->getType(), $4);
2508 BasicBlock* tmpBB = getBBVal($6);
2510 $1->push_back(std::make_pair(tmpVal, tmpBB));
2514 ValueRefList : Types ValueRef OptParamAttrs {
2515 if (!UpRefs.empty())
2516 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2517 // Used for call and invoke instructions
2518 $$ = new ValueRefList();
2519 ValueRefListEntry E; E.Attrs = $3; E.Val = getVal($1->get(), $2);
2522 | ValueRefList ',' Types ValueRef OptParamAttrs {
2523 if (!UpRefs.empty())
2524 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2526 ValueRefListEntry E; E.Attrs = $5; E.Val = getVal($3->get(), $4);
2530 | /*empty*/ { $$ = new ValueRefList(); };
2532 IndexList // Used for gep instructions and constant expressions
2533 : /*empty*/ { $$ = new std::vector<Value*>(); }
2534 | IndexList ',' ResolvedVal {
2541 OptTailCall : TAIL CALL {
2550 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2551 if (!UpRefs.empty())
2552 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2553 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
2554 !isa<PackedType>((*$2).get()))
2556 "Arithmetic operator requires integer, FP, or packed operands!");
2557 if (isa<PackedType>((*$2).get()) &&
2558 ($1 == Instruction::URem ||
2559 $1 == Instruction::SRem ||
2560 $1 == Instruction::FRem))
2561 GEN_ERROR("U/S/FRem not supported on packed types!");
2562 Value* val1 = getVal(*$2, $3);
2564 Value* val2 = getVal(*$2, $5);
2566 $$ = BinaryOperator::create($1, val1, val2);
2568 GEN_ERROR("binary operator returned null!");
2571 | LogicalOps Types ValueRef ',' ValueRef {
2572 if (!UpRefs.empty())
2573 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2574 if (!(*$2)->isIntegral()) {
2575 if (!isa<PackedType>($2->get()) ||
2576 !cast<PackedType>($2->get())->getElementType()->isIntegral())
2577 GEN_ERROR("Logical operator requires integral operands!");
2579 Value* tmpVal1 = getVal(*$2, $3);
2581 Value* tmpVal2 = getVal(*$2, $5);
2583 $$ = BinaryOperator::create($1, tmpVal1, tmpVal2);
2585 GEN_ERROR("binary operator returned null!");
2588 | ICMP IPredicates Types ValueRef ',' ValueRef {
2589 if (!UpRefs.empty())
2590 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2591 if (isa<PackedType>((*$3).get()))
2592 GEN_ERROR("Packed types not supported by icmp instruction");
2593 Value* tmpVal1 = getVal(*$3, $4);
2595 Value* tmpVal2 = getVal(*$3, $6);
2597 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2599 GEN_ERROR("icmp operator returned null!");
2601 | FCMP FPredicates Types ValueRef ',' ValueRef {
2602 if (!UpRefs.empty())
2603 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2604 if (isa<PackedType>((*$3).get()))
2605 GEN_ERROR("Packed types not supported by fcmp instruction");
2606 Value* tmpVal1 = getVal(*$3, $4);
2608 Value* tmpVal2 = getVal(*$3, $6);
2610 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2612 GEN_ERROR("fcmp operator returned null!");
2615 cerr << "WARNING: Use of eliminated 'not' instruction:"
2616 << " Replacing with 'xor'.\n";
2618 Value *Ones = ConstantInt::getAllOnesValue($2->getType());
2620 GEN_ERROR("Expected integral type for not instruction!");
2622 $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
2624 GEN_ERROR("Could not create a xor instruction!");
2627 | ShiftOps ResolvedVal ',' ResolvedVal {
2628 if ($4->getType() != Type::Int8Ty)
2629 GEN_ERROR("Shift amount must be i8 type!");
2630 if (!$2->getType()->isInteger())
2631 GEN_ERROR("Shift constant expression requires integer operand!");
2633 $$ = new ShiftInst($1, $2, $4);
2636 | CastOps ResolvedVal TO Types {
2637 if (!UpRefs.empty())
2638 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2640 const Type* Ty = $4->get();
2641 if (!Val->getType()->isFirstClassType())
2642 GEN_ERROR("cast from a non-primitive type: '" +
2643 Val->getType()->getDescription() + "'!");
2644 if (!Ty->isFirstClassType())
2645 GEN_ERROR("cast to a non-primitive type: '" + Ty->getDescription() +"'!");
2646 $$ = CastInst::create($1, Val, $4->get());
2649 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2650 if ($2->getType() != Type::BoolTy)
2651 GEN_ERROR("select condition must be boolean!");
2652 if ($4->getType() != $6->getType())
2653 GEN_ERROR("select value types should match!");
2654 $$ = new SelectInst($2, $4, $6);
2657 | VAARG ResolvedVal ',' Types {
2658 if (!UpRefs.empty())
2659 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2660 $$ = new VAArgInst($2, *$4);
2664 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2665 if (!ExtractElementInst::isValidOperands($2, $4))
2666 GEN_ERROR("Invalid extractelement operands!");
2667 $$ = new ExtractElementInst($2, $4);
2670 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2671 if (!InsertElementInst::isValidOperands($2, $4, $6))
2672 GEN_ERROR("Invalid insertelement operands!");
2673 $$ = new InsertElementInst($2, $4, $6);
2676 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2677 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
2678 GEN_ERROR("Invalid shufflevector operands!");
2679 $$ = new ShuffleVectorInst($2, $4, $6);
2683 const Type *Ty = $2->front().first->getType();
2684 if (!Ty->isFirstClassType())
2685 GEN_ERROR("PHI node operands must be of first class type!");
2686 $$ = new PHINode(Ty);
2687 ((PHINode*)$$)->reserveOperandSpace($2->size());
2688 while ($2->begin() != $2->end()) {
2689 if ($2->front().first->getType() != Ty)
2690 GEN_ERROR("All elements of a PHI node must be of the same type!");
2691 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2694 delete $2; // Free the list...
2697 | OptTailCall OptCallingConv ResultTypes ValueRef '(' ValueRefList ')'
2700 // Handle the short syntax
2701 const PointerType *PFTy = 0;
2702 const FunctionType *Ty = 0;
2703 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2704 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2705 // Pull out the types of all of the arguments...
2706 std::vector<const Type*> ParamTypes;
2707 FunctionType::ParamAttrsList ParamAttrs;
2708 ParamAttrs.push_back($8);
2709 for (ValueRefList::iterator I = $6->begin(), E = $6->end(); I != E; ++I) {
2710 const Type *Ty = I->Val->getType();
2711 if (Ty == Type::VoidTy)
2712 GEN_ERROR("Short call syntax cannot be used with varargs");
2713 ParamTypes.push_back(Ty);
2714 ParamAttrs.push_back(I->Attrs);
2717 Ty = FunctionType::get($3->get(), ParamTypes, false, ParamAttrs);
2718 PFTy = PointerType::get(Ty);
2721 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2724 // Check the arguments
2726 if ($6->empty()) { // Has no arguments?
2727 // Make sure no arguments is a good thing!
2728 if (Ty->getNumParams() != 0)
2729 GEN_ERROR("No arguments passed to a function that "
2730 "expects arguments!");
2731 } else { // Has arguments?
2732 // Loop through FunctionType's arguments and ensure they are specified
2735 FunctionType::param_iterator I = Ty->param_begin();
2736 FunctionType::param_iterator E = Ty->param_end();
2737 ValueRefList::iterator ArgI = $6->begin(), ArgE = $6->end();
2739 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2740 if (ArgI->Val->getType() != *I)
2741 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2742 (*I)->getDescription() + "'!");
2743 Args.push_back(ArgI->Val);
2745 if (Ty->isVarArg()) {
2747 for (; ArgI != ArgE; ++ArgI)
2748 Args.push_back(ArgI->Val); // push the remaining varargs
2749 } else if (I != E || ArgI != ArgE)
2750 GEN_ERROR("Invalid number of parameters detected!");
2752 // Create the call node
2753 CallInst *CI = new CallInst(V, Args);
2754 CI->setTailCall($1);
2755 CI->setCallingConv($2);
2765 OptVolatile : VOLATILE {
2776 MemoryInst : MALLOC Types OptCAlign {
2777 if (!UpRefs.empty())
2778 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2779 $$ = new MallocInst(*$2, 0, $3);
2783 | MALLOC Types ',' INT32 ValueRef OptCAlign {
2784 if (!UpRefs.empty())
2785 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2786 Value* tmpVal = getVal($4, $5);
2788 $$ = new MallocInst(*$2, tmpVal, $6);
2791 | ALLOCA Types OptCAlign {
2792 if (!UpRefs.empty())
2793 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2794 $$ = new AllocaInst(*$2, 0, $3);
2798 | ALLOCA Types ',' INT32 ValueRef OptCAlign {
2799 if (!UpRefs.empty())
2800 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2801 Value* tmpVal = getVal($4, $5);
2803 $$ = new AllocaInst(*$2, tmpVal, $6);
2806 | FREE ResolvedVal {
2807 if (!isa<PointerType>($2->getType()))
2808 GEN_ERROR("Trying to free nonpointer type " +
2809 $2->getType()->getDescription() + "!");
2810 $$ = new FreeInst($2);
2814 | OptVolatile LOAD Types ValueRef {
2815 if (!UpRefs.empty())
2816 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2817 if (!isa<PointerType>($3->get()))
2818 GEN_ERROR("Can't load from nonpointer type: " +
2819 (*$3)->getDescription());
2820 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
2821 GEN_ERROR("Can't load from pointer of non-first-class type: " +
2822 (*$3)->getDescription());
2823 Value* tmpVal = getVal(*$3, $4);
2825 $$ = new LoadInst(tmpVal, "", $1);
2828 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2829 if (!UpRefs.empty())
2830 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
2831 const PointerType *PT = dyn_cast<PointerType>($5->get());
2833 GEN_ERROR("Can't store to a nonpointer type: " +
2834 (*$5)->getDescription());
2835 const Type *ElTy = PT->getElementType();
2836 if (ElTy != $3->getType())
2837 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
2838 "' into space of type '" + ElTy->getDescription() + "'!");
2840 Value* tmpVal = getVal(*$5, $6);
2842 $$ = new StoreInst($3, tmpVal, $1);
2845 | GETELEMENTPTR Types ValueRef IndexList {
2846 if (!UpRefs.empty())
2847 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2848 if (!isa<PointerType>($2->get()))
2849 GEN_ERROR("getelementptr insn requires pointer operand!");
2851 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2852 GEN_ERROR("Invalid getelementptr indices for type '" +
2853 (*$2)->getDescription()+ "'!");
2854 Value* tmpVal = getVal(*$2, $3);
2856 $$ = new GetElementPtrInst(tmpVal, *$4);
2864 // common code from the two 'RunVMAsmParser' functions
2865 static Module* RunParser(Module * M) {
2867 llvmAsmlineno = 1; // Reset the current line number...
2868 CurModule.CurrentModule = M;
2873 // Check to make sure the parser succeeded
2876 delete ParserResult;
2880 // Check to make sure that parsing produced a result
2884 // Reset ParserResult variable while saving its value for the result.
2885 Module *Result = ParserResult;
2891 void llvm::GenerateError(const std::string &message, int LineNo) {
2892 if (LineNo == -1) LineNo = llvmAsmlineno;
2893 // TODO: column number in exception
2895 TheParseError->setError(CurFilename, message, LineNo);
2899 int yyerror(const char *ErrorMsg) {
2901 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2902 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2903 std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2904 if (yychar == YYEMPTY || yychar == 0)
2905 errMsg += "end-of-file.";
2907 errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2908 GenerateError(errMsg);