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/ValueSymbolTable.h"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/Streams.h"
34 // The following is a gross hack. In order to rid the libAsmParser library of
35 // exceptions, we have to have a way of getting the yyparse function to go into
36 // an error situation. So, whenever we want an error to occur, the GenerateError
37 // function (see bottom of file) sets TriggerError. Then, at the end of each
38 // production in the grammer we use CHECK_FOR_ERROR which will invoke YYERROR
39 // (a goto) to put YACC in error state. Furthermore, several calls to
40 // GenerateError are made from inside productions and they must simulate the
41 // previous exception behavior by exiting the production immediately. We have
42 // replaced these with the GEN_ERROR macro which calls GeneratError and then
43 // immediately invokes YYERROR. This would be so much cleaner if it was a
44 // recursive descent parser.
45 static bool TriggerError = false;
46 #define CHECK_FOR_ERROR { if (TriggerError) { TriggerError = false; YYABORT; } }
47 #define GEN_ERROR(msg) { GenerateError(msg); YYERROR; }
49 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
50 int yylex(); // declaration" of xxx warnings.
54 std::string CurFilename;
57 Debug("debug-yacc", cl::desc("Print yacc debug state changes"),
58 cl::Hidden, cl::init(false));
63 static Module *ParserResult;
65 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
66 // relating to upreferences in the input stream.
68 //#define DEBUG_UPREFS 1
70 #define UR_OUT(X) cerr << X
75 #define YYERROR_VERBOSE 1
77 static GlobalVariable *CurGV;
80 // This contains info used when building the body of a function. It is
81 // destroyed when the function is completed.
83 typedef std::vector<Value *> ValueList; // Numbered defs
86 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
87 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
89 static struct PerModuleInfo {
90 Module *CurrentModule;
91 std::map<const Type *, ValueList> Values; // Module level numbered definitions
92 std::map<const Type *,ValueList> LateResolveValues;
93 std::vector<PATypeHolder> Types;
94 std::map<ValID, PATypeHolder> LateResolveTypes;
96 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
97 /// how they were referenced and on which line of the input they came from so
98 /// that we can resolve them later and print error messages as appropriate.
99 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
101 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
102 // references to global values. Global values may be referenced before they
103 // are defined, and if so, the temporary object that they represent is held
104 // here. This is used for forward references of GlobalValues.
106 typedef std::map<std::pair<const PointerType *,
107 ValID>, GlobalValue*> GlobalRefsType;
108 GlobalRefsType GlobalRefs;
111 // If we could not resolve some functions at function compilation time
112 // (calls to functions before they are defined), resolve them now... Types
113 // are resolved when the constant pool has been completely parsed.
115 ResolveDefinitions(LateResolveValues);
119 // Check to make sure that all global value forward references have been
122 if (!GlobalRefs.empty()) {
123 std::string UndefinedReferences = "Unresolved global references exist:\n";
125 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
127 UndefinedReferences += " " + I->first.first->getDescription() + " " +
128 I->first.second.getName() + "\n";
130 GenerateError(UndefinedReferences);
134 Values.clear(); // Clear out function local definitions
139 // GetForwardRefForGlobal - Check to see if there is a forward reference
140 // for this global. If so, remove it from the GlobalRefs map and return it.
141 // If not, just return null.
142 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
143 // Check to see if there is a forward reference to this global variable...
144 // if there is, eliminate it and patch the reference to use the new def'n.
145 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
146 GlobalValue *Ret = 0;
147 if (I != GlobalRefs.end()) {
154 bool TypeIsUnresolved(PATypeHolder* PATy) {
155 // If it isn't abstract, its resolved
156 const Type* Ty = PATy->get();
157 if (!Ty->isAbstract())
159 // Traverse the type looking for abstract types. If it isn't abstract then
160 // we don't need to traverse that leg of the type.
161 std::vector<const Type*> WorkList, SeenList;
162 WorkList.push_back(Ty);
163 while (!WorkList.empty()) {
164 const Type* Ty = WorkList.back();
165 SeenList.push_back(Ty);
167 if (const OpaqueType* OpTy = dyn_cast<OpaqueType>(Ty)) {
168 // Check to see if this is an unresolved type
169 std::map<ValID, PATypeHolder>::iterator I = LateResolveTypes.begin();
170 std::map<ValID, PATypeHolder>::iterator E = LateResolveTypes.end();
171 for ( ; I != E; ++I) {
172 if (I->second.get() == OpTy)
175 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(Ty)) {
176 const Type* TheTy = SeqTy->getElementType();
177 if (TheTy->isAbstract() && TheTy != Ty) {
178 std::vector<const Type*>::iterator I = SeenList.begin(),
184 WorkList.push_back(TheTy);
186 } else if (const StructType* StrTy = dyn_cast<StructType>(Ty)) {
187 for (unsigned i = 0; i < StrTy->getNumElements(); ++i) {
188 const Type* TheTy = StrTy->getElementType(i);
189 if (TheTy->isAbstract() && TheTy != Ty) {
190 std::vector<const Type*>::iterator I = SeenList.begin(),
196 WorkList.push_back(TheTy);
207 static struct PerFunctionInfo {
208 Function *CurrentFunction; // Pointer to current function being created
210 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
211 std::map<const Type*, ValueList> LateResolveValues;
212 bool isDeclare; // Is this function a forward declararation?
213 GlobalValue::LinkageTypes Linkage; // Linkage for forward declaration.
214 GlobalValue::VisibilityTypes Visibility;
216 /// BBForwardRefs - When we see forward references to basic blocks, keep
217 /// track of them here.
218 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
219 std::vector<BasicBlock*> NumberedBlocks;
222 inline PerFunctionInfo() {
225 Linkage = GlobalValue::ExternalLinkage;
226 Visibility = GlobalValue::DefaultVisibility;
229 inline void FunctionStart(Function *M) {
234 void FunctionDone() {
235 NumberedBlocks.clear();
237 // Any forward referenced blocks left?
238 if (!BBForwardRefs.empty()) {
239 GenerateError("Undefined reference to label " +
240 BBForwardRefs.begin()->first->getName());
244 // Resolve all forward references now.
245 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
247 Values.clear(); // Clear out function local definitions
250 Linkage = GlobalValue::ExternalLinkage;
251 Visibility = GlobalValue::DefaultVisibility;
253 } CurFun; // Info for the current function...
255 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
258 //===----------------------------------------------------------------------===//
259 // Code to handle definitions of all the types
260 //===----------------------------------------------------------------------===//
262 static int InsertValue(Value *V,
263 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
264 if (V->hasName()) return -1; // Is this a numbered definition?
266 // Yes, insert the value into the value table...
267 ValueList &List = ValueTab[V->getType()];
269 return List.size()-1;
272 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
274 case ValID::LocalID: // Is it a numbered definition?
275 // Module constants occupy the lowest numbered slots...
276 if (D.Num < CurModule.Types.size())
277 return CurModule.Types[D.Num];
279 case ValID::LocalName: // Is it a named definition?
280 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
281 D.destroy(); // Free old strdup'd memory...
286 GenerateError("Internal parser error: Invalid symbol type reference");
290 // If we reached here, we referenced either a symbol that we don't know about
291 // or an id number that hasn't been read yet. We may be referencing something
292 // forward, so just create an entry to be resolved later and get to it...
294 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
297 if (inFunctionScope()) {
298 if (D.Type == ValID::LocalName) {
299 GenerateError("Reference to an undefined type: '" + D.getName() + "'");
302 GenerateError("Reference to an undefined type: #" + utostr(D.Num));
307 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
308 if (I != CurModule.LateResolveTypes.end())
311 Type *Typ = OpaqueType::get();
312 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
316 // getValNonImprovising - Look up the value specified by the provided type and
317 // the provided ValID. If the value exists and has already been defined, return
318 // it. Otherwise return null.
320 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
321 if (isa<FunctionType>(Ty)) {
322 GenerateError("Functions are not values and "
323 "must be referenced as pointers");
328 case ValID::LocalID: { // Is it a numbered definition?
329 // Module constants occupy the lowest numbered slots.
330 std::map<const Type*,ValueList>::iterator VI = CurFun.Values.find(Ty);
331 // Make sure that our type is within bounds.
332 if (VI == CurFun.Values.end()) return 0;
334 // Check that the number is within bounds.
335 if (D.Num >= VI->second.size()) return 0;
337 return VI->second[D.Num];
339 case ValID::GlobalID: { // Is it a numbered definition?
340 unsigned Num = D.Num;
342 // Module constants occupy the lowest numbered slots...
343 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
344 if (VI == CurModule.Values.end())
346 if (D.Num >= VI->second.size())
348 return VI->second[Num];
351 case ValID::LocalName: { // Is it a named definition?
352 if (!inFunctionScope())
354 ValueSymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
355 Value *N = SymTab.lookup(D.Name);
358 if (N->getType() != Ty)
361 D.destroy(); // Free old strdup'd memory...
364 case ValID::GlobalName: { // Is it a named definition?
365 ValueSymbolTable &SymTab = CurModule.CurrentModule->getValueSymbolTable();
366 Value *N = SymTab.lookup(D.Name);
369 if (N->getType() != Ty)
372 D.destroy(); // Free old strdup'd memory...
376 // Check to make sure that "Ty" is an integral type, and that our
377 // value will fit into the specified type...
378 case ValID::ConstSIntVal: // Is it a constant pool reference??
379 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
380 GenerateError("Signed integral constant '" +
381 itostr(D.ConstPool64) + "' is invalid for type '" +
382 Ty->getDescription() + "'");
385 return ConstantInt::get(Ty, D.ConstPool64);
387 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
388 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
389 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
390 GenerateError("Integral constant '" + utostr(D.UConstPool64) +
391 "' is invalid or out of range");
393 } else { // This is really a signed reference. Transmogrify.
394 return ConstantInt::get(Ty, D.ConstPool64);
397 return ConstantInt::get(Ty, D.UConstPool64);
400 case ValID::ConstFPVal: // Is it a floating point const pool reference?
401 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP)) {
402 GenerateError("FP constant invalid for type");
405 return ConstantFP::get(Ty, D.ConstPoolFP);
407 case ValID::ConstNullVal: // Is it a null value?
408 if (!isa<PointerType>(Ty)) {
409 GenerateError("Cannot create a a non pointer null");
412 return ConstantPointerNull::get(cast<PointerType>(Ty));
414 case ValID::ConstUndefVal: // Is it an undef value?
415 return UndefValue::get(Ty);
417 case ValID::ConstZeroVal: // Is it a zero value?
418 return Constant::getNullValue(Ty);
420 case ValID::ConstantVal: // Fully resolved constant?
421 if (D.ConstantValue->getType() != Ty) {
422 GenerateError("Constant expression type different from required type");
425 return D.ConstantValue;
427 case ValID::InlineAsmVal: { // Inline asm expression
428 const PointerType *PTy = dyn_cast<PointerType>(Ty);
429 const FunctionType *FTy =
430 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
431 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
432 GenerateError("Invalid type for asm constraint string");
435 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
436 D.IAD->HasSideEffects);
437 D.destroy(); // Free InlineAsmDescriptor.
441 assert(0 && "Unhandled case!");
445 assert(0 && "Unhandled case!");
449 // getVal - This function is identical to getValNonImprovising, except that if a
450 // value is not already defined, it "improvises" by creating a placeholder var
451 // that looks and acts just like the requested variable. When the value is
452 // defined later, all uses of the placeholder variable are replaced with the
455 static Value *getVal(const Type *Ty, const ValID &ID) {
456 if (Ty == Type::LabelTy) {
457 GenerateError("Cannot use a basic block here");
461 // See if the value has already been defined.
462 Value *V = getValNonImprovising(Ty, ID);
464 if (TriggerError) return 0;
466 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
467 GenerateError("Invalid use of a composite type");
471 // If we reached here, we referenced either a symbol that we don't know about
472 // or an id number that hasn't been read yet. We may be referencing something
473 // forward, so just create an entry to be resolved later and get to it...
475 V = new Argument(Ty);
477 // Remember where this forward reference came from. FIXME, shouldn't we try
478 // to recycle these things??
479 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
482 if (inFunctionScope())
483 InsertValue(V, CurFun.LateResolveValues);
485 InsertValue(V, CurModule.LateResolveValues);
489 /// getBBVal - This is used for two purposes:
490 /// * If isDefinition is true, a new basic block with the specified ID is being
492 /// * If isDefinition is true, this is a reference to a basic block, which may
493 /// or may not be a forward reference.
495 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
496 assert(inFunctionScope() && "Can't get basic block at global scope!");
502 GenerateError("Illegal label reference " + ID.getName());
504 case ValID::LocalID: // Is it a numbered definition?
505 if (ID.Num >= CurFun.NumberedBlocks.size())
506 CurFun.NumberedBlocks.resize(ID.Num+1);
507 BB = CurFun.NumberedBlocks[ID.Num];
509 case ValID::LocalName: // Is it a named definition?
511 Value *N = CurFun.CurrentFunction->getValueSymbolTable().lookup(Name);
512 if (N && N->getType()->getTypeID() == Type::LabelTyID)
513 BB = cast<BasicBlock>(N);
517 // See if the block has already been defined.
519 // If this is the definition of the block, make sure the existing value was
520 // just a forward reference. If it was a forward reference, there will be
521 // an entry for it in the PlaceHolderInfo map.
522 if (isDefinition && !CurFun.BBForwardRefs.erase(BB)) {
523 // The existing value was a definition, not a forward reference.
524 GenerateError("Redefinition of label " + ID.getName());
528 ID.destroy(); // Free strdup'd memory.
532 // Otherwise this block has not been seen before.
533 BB = new BasicBlock("", CurFun.CurrentFunction);
534 if (ID.Type == ValID::LocalName) {
535 BB->setName(ID.Name);
537 CurFun.NumberedBlocks[ID.Num] = BB;
540 // If this is not a definition, keep track of it so we can use it as a forward
543 // Remember where this forward reference came from.
544 CurFun.BBForwardRefs[BB] = std::make_pair(ID, llvmAsmlineno);
546 // The forward declaration could have been inserted anywhere in the
547 // function: insert it into the correct place now.
548 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
549 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
556 //===----------------------------------------------------------------------===//
557 // Code to handle forward references in instructions
558 //===----------------------------------------------------------------------===//
560 // This code handles the late binding needed with statements that reference
561 // values not defined yet... for example, a forward branch, or the PHI node for
564 // This keeps a table (CurFun.LateResolveValues) of all such forward references
565 // and back patchs after we are done.
568 // ResolveDefinitions - If we could not resolve some defs at parsing
569 // time (forward branches, phi functions for loops, etc...) resolve the
573 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
574 std::map<const Type*,ValueList> *FutureLateResolvers) {
575 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
576 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
577 E = LateResolvers.end(); LRI != E; ++LRI) {
578 ValueList &List = LRI->second;
579 while (!List.empty()) {
580 Value *V = List.back();
583 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
584 CurModule.PlaceHolderInfo.find(V);
585 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
587 ValID &DID = PHI->second.first;
589 Value *TheRealValue = getValNonImprovising(LRI->first, DID);
593 V->replaceAllUsesWith(TheRealValue);
595 CurModule.PlaceHolderInfo.erase(PHI);
596 } else if (FutureLateResolvers) {
597 // Functions have their unresolved items forwarded to the module late
599 InsertValue(V, *FutureLateResolvers);
601 if (DID.Type == ValID::LocalName || DID.Type == ValID::GlobalName) {
602 GenerateError("Reference to an invalid definition: '" +DID.getName()+
603 "' of type '" + V->getType()->getDescription() + "'",
607 GenerateError("Reference to an invalid definition: #" +
608 itostr(DID.Num) + " of type '" +
609 V->getType()->getDescription() + "'",
617 LateResolvers.clear();
620 // ResolveTypeTo - A brand new type was just declared. This means that (if
621 // name is not null) things referencing Name can be resolved. Otherwise, things
622 // refering to the number can be resolved. Do this now.
624 static void ResolveTypeTo(char *Name, const Type *ToTy) {
626 if (Name) D = ValID::createLocalName(Name);
627 else D = ValID::createLocalID(CurModule.Types.size());
629 std::map<ValID, PATypeHolder>::iterator I =
630 CurModule.LateResolveTypes.find(D);
631 if (I != CurModule.LateResolveTypes.end()) {
632 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
633 CurModule.LateResolveTypes.erase(I);
637 // setValueName - Set the specified value to the name given. The name may be
638 // null potentially, in which case this is a noop. The string passed in is
639 // assumed to be a malloc'd string buffer, and is free'd by this function.
641 static void setValueName(Value *V, char *NameStr) {
642 if (!NameStr) return;
643 std::string Name(NameStr); // Copy string
644 free(NameStr); // Free old string
646 if (V->getType() == Type::VoidTy) {
647 GenerateError("Can't assign name '" + Name+"' to value with void type");
651 assert(inFunctionScope() && "Must be in function scope!");
652 ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
653 if (ST.lookup(Name)) {
654 GenerateError("Redefinition of value '" + Name + "' of type '" +
655 V->getType()->getDescription() + "'");
663 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
664 /// this is a declaration, otherwise it is a definition.
665 static GlobalVariable *
666 ParseGlobalVariable(char *NameStr,
667 GlobalValue::LinkageTypes Linkage,
668 GlobalValue::VisibilityTypes Visibility,
669 bool isConstantGlobal, const Type *Ty,
670 Constant *Initializer) {
671 if (isa<FunctionType>(Ty)) {
672 GenerateError("Cannot declare global vars of function type");
676 const PointerType *PTy = PointerType::get(Ty);
680 Name = NameStr; // Copy string
681 free(NameStr); // Free old string
684 // See if this global value was forward referenced. If so, recycle the
688 ID = ValID::createGlobalName((char*)Name.c_str());
690 ID = ValID::createGlobalID(CurModule.Values[PTy].size());
693 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
694 // Move the global to the end of the list, from whereever it was
695 // previously inserted.
696 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
697 CurModule.CurrentModule->getGlobalList().remove(GV);
698 CurModule.CurrentModule->getGlobalList().push_back(GV);
699 GV->setInitializer(Initializer);
700 GV->setLinkage(Linkage);
701 GV->setVisibility(Visibility);
702 GV->setConstant(isConstantGlobal);
703 InsertValue(GV, CurModule.Values);
707 // If this global has a name
709 // if the global we're parsing has an initializer (is a definition) and
710 // has external linkage.
711 if (Initializer && Linkage != GlobalValue::InternalLinkage)
712 // If there is already a global with external linkage with this name
713 if (CurModule.CurrentModule->getGlobalVariable(Name, false)) {
714 // If we allow this GVar to get created, it will be renamed in the
715 // symbol table because it conflicts with an existing GVar. We can't
716 // allow redefinition of GVars whose linking indicates that their name
717 // must stay the same. Issue the error.
718 GenerateError("Redefinition of global variable named '" + Name +
719 "' of type '" + Ty->getDescription() + "'");
724 // Otherwise there is no existing GV to use, create one now.
726 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
727 CurModule.CurrentModule);
728 GV->setVisibility(Visibility);
729 InsertValue(GV, CurModule.Values);
733 // setTypeName - Set the specified type to the name given. The name may be
734 // null potentially, in which case this is a noop. The string passed in is
735 // assumed to be a malloc'd string buffer, and is freed by this function.
737 // This function returns true if the type has already been defined, but is
738 // allowed to be redefined in the specified context. If the name is a new name
739 // for the type plane, it is inserted and false is returned.
740 static bool setTypeName(const Type *T, char *NameStr) {
741 assert(!inFunctionScope() && "Can't give types function-local names!");
742 if (NameStr == 0) return false;
744 std::string Name(NameStr); // Copy string
745 free(NameStr); // Free old string
747 // We don't allow assigning names to void type
748 if (T == Type::VoidTy) {
749 GenerateError("Can't assign name '" + Name + "' to the void type");
753 // Set the type name, checking for conflicts as we do so.
754 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
756 if (AlreadyExists) { // Inserting a name that is already defined???
757 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
758 assert(Existing && "Conflict but no matching type?!");
760 // There is only one case where this is allowed: when we are refining an
761 // opaque type. In this case, Existing will be an opaque type.
762 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
763 // We ARE replacing an opaque type!
764 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
768 // Otherwise, this is an attempt to redefine a type. That's okay if
769 // the redefinition is identical to the original. This will be so if
770 // Existing and T point to the same Type object. In this one case we
771 // allow the equivalent redefinition.
772 if (Existing == T) return true; // Yes, it's equal.
774 // Any other kind of (non-equivalent) redefinition is an error.
775 GenerateError("Redefinition of type named '" + Name + "' of type '" +
776 T->getDescription() + "'");
782 //===----------------------------------------------------------------------===//
783 // Code for handling upreferences in type names...
786 // TypeContains - Returns true if Ty directly contains E in it.
788 static bool TypeContains(const Type *Ty, const Type *E) {
789 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
790 E) != Ty->subtype_end();
795 // NestingLevel - The number of nesting levels that need to be popped before
796 // this type is resolved.
797 unsigned NestingLevel;
799 // LastContainedTy - This is the type at the current binding level for the
800 // type. Every time we reduce the nesting level, this gets updated.
801 const Type *LastContainedTy;
803 // UpRefTy - This is the actual opaque type that the upreference is
807 UpRefRecord(unsigned NL, OpaqueType *URTy)
808 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
812 // UpRefs - A list of the outstanding upreferences that need to be resolved.
813 static std::vector<UpRefRecord> UpRefs;
815 /// HandleUpRefs - Every time we finish a new layer of types, this function is
816 /// called. It loops through the UpRefs vector, which is a list of the
817 /// currently active types. For each type, if the up reference is contained in
818 /// the newly completed type, we decrement the level count. When the level
819 /// count reaches zero, the upreferenced type is the type that is passed in:
820 /// thus we can complete the cycle.
822 static PATypeHolder HandleUpRefs(const Type *ty) {
823 // If Ty isn't abstract, or if there are no up-references in it, then there is
824 // nothing to resolve here.
825 if (!ty->isAbstract() || UpRefs.empty()) return ty;
828 UR_OUT("Type '" << Ty->getDescription() <<
829 "' newly formed. Resolving upreferences.\n" <<
830 UpRefs.size() << " upreferences active!\n");
832 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
833 // to zero), we resolve them all together before we resolve them to Ty. At
834 // the end of the loop, if there is anything to resolve to Ty, it will be in
836 OpaqueType *TypeToResolve = 0;
838 for (unsigned i = 0; i != UpRefs.size(); ++i) {
839 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
840 << UpRefs[i].second->getDescription() << ") = "
841 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
842 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
843 // Decrement level of upreference
844 unsigned Level = --UpRefs[i].NestingLevel;
845 UpRefs[i].LastContainedTy = Ty;
846 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
847 if (Level == 0) { // Upreference should be resolved!
848 if (!TypeToResolve) {
849 TypeToResolve = UpRefs[i].UpRefTy;
851 UR_OUT(" * Resolving upreference for "
852 << UpRefs[i].second->getDescription() << "\n";
853 std::string OldName = UpRefs[i].UpRefTy->getDescription());
854 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
855 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
856 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
858 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
859 --i; // Do not skip the next element...
865 UR_OUT(" * Resolving upreference for "
866 << UpRefs[i].second->getDescription() << "\n";
867 std::string OldName = TypeToResolve->getDescription());
868 TypeToResolve->refineAbstractTypeTo(Ty);
874 //===----------------------------------------------------------------------===//
875 // RunVMAsmParser - Define an interface to this parser
876 //===----------------------------------------------------------------------===//
878 static Module* RunParser(Module * M);
880 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
883 CurFilename = Filename;
884 return RunParser(new Module(CurFilename));
887 Module *llvm::RunVMAsmParser(const char * AsmString, Module * M) {
888 set_scan_string(AsmString);
890 CurFilename = "from_memory";
892 return RunParser(new Module (CurFilename));
901 llvm::Module *ModuleVal;
902 llvm::Function *FunctionVal;
903 llvm::BasicBlock *BasicBlockVal;
904 llvm::TerminatorInst *TermInstVal;
905 llvm::Instruction *InstVal;
906 llvm::Constant *ConstVal;
908 const llvm::Type *PrimType;
909 std::list<llvm::PATypeHolder> *TypeList;
910 llvm::PATypeHolder *TypeVal;
911 llvm::Value *ValueVal;
912 std::vector<llvm::Value*> *ValueList;
913 llvm::ArgListType *ArgList;
914 llvm::TypeWithAttrs TypeWithAttrs;
915 llvm::TypeWithAttrsList *TypeWithAttrsList;
916 llvm::ValueRefList *ValueRefList;
918 // Represent the RHS of PHI node
919 std::list<std::pair<llvm::Value*,
920 llvm::BasicBlock*> > *PHIList;
921 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
922 std::vector<llvm::Constant*> *ConstVector;
924 llvm::GlobalValue::LinkageTypes Linkage;
925 llvm::GlobalValue::VisibilityTypes Visibility;
926 llvm::FunctionType::ParameterAttributes ParamAttrs;
934 char *StrVal; // This memory is strdup'd!
935 llvm::ValID ValIDVal; // strdup'd memory maybe!
937 llvm::Instruction::BinaryOps BinaryOpVal;
938 llvm::Instruction::TermOps TermOpVal;
939 llvm::Instruction::MemoryOps MemOpVal;
940 llvm::Instruction::CastOps CastOpVal;
941 llvm::Instruction::OtherOps OtherOpVal;
942 llvm::ICmpInst::Predicate IPredicate;
943 llvm::FCmpInst::Predicate FPredicate;
946 %type <ModuleVal> Module
947 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
948 %type <BasicBlockVal> BasicBlock InstructionList
949 %type <TermInstVal> BBTerminatorInst
950 %type <InstVal> Inst InstVal MemoryInst
951 %type <ConstVal> ConstVal ConstExpr
952 %type <ConstVector> ConstVector
953 %type <ArgList> ArgList ArgListH
954 %type <PHIList> PHIList
955 %type <ValueRefList> ValueRefList // For call param lists & GEP indices
956 %type <ValueList> IndexList // For GEP indices
957 %type <TypeList> TypeListI
958 %type <TypeWithAttrsList> ArgTypeList ArgTypeListI
959 %type <TypeWithAttrs> ArgType
960 %type <JumpTable> JumpTable
961 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
962 %type <BoolVal> OptVolatile // 'volatile' or not
963 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
964 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
965 %type <Linkage> GVInternalLinkage GVExternalLinkage
966 %type <Linkage> FunctionDefineLinkage FunctionDeclareLinkage
967 %type <Visibility> GVVisibilityStyle
969 // ValueRef - Unresolved reference to a definition or BB
970 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
971 %type <ValueVal> ResolvedVal // <type> <valref> pair
972 // Tokens and types for handling constant integer values
974 // ESINT64VAL - A negative number within long long range
975 %token <SInt64Val> ESINT64VAL
977 // EUINT64VAL - A positive number within uns. long long range
978 %token <UInt64Val> EUINT64VAL
980 %token <UIntVal> LOCALVAL_ID GLOBALVAL_ID // %123 @123
981 %token <FPVal> FPVAL // Float or Double constant
984 %type <TypeVal> Types ResultTypes
985 %type <PrimType> IntType FPType PrimType // Classifications
986 %token <PrimType> VOID INTTYPE
987 %token <PrimType> FLOAT DOUBLE LABEL
990 %token<StrVal> LOCALVAR GLOBALVAR LABELSTR STRINGCONSTANT ATSTRINGCONSTANT
991 %type <StrVal> LocalName OptLocalName OptLocalAssign
992 %type <StrVal> GlobalName OptGlobalAssign
993 %type <UIntVal> OptAlign OptCAlign
994 %type <StrVal> OptSection SectionString
996 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
997 %token DECLARE DEFINE GLOBAL CONSTANT SECTION VOLATILE
998 %token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
999 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
1000 %token OPAQUE EXTERNAL TARGET TRIPLE ALIGN
1001 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1002 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1004 %type <UIntVal> OptCallingConv
1005 %type <ParamAttrs> OptParamAttrs ParamAttr
1006 %type <ParamAttrs> OptFuncAttrs FuncAttr
1008 // Basic Block Terminating Operators
1009 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1012 %type <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
1013 %token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1014 %token <BinaryOpVal> SHL LSHR ASHR
1016 %token <OtherOpVal> ICMP FCMP
1017 %type <IPredicate> IPredicates
1018 %type <FPredicate> FPredicates
1019 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1020 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1022 // Memory Instructions
1023 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1026 %type <CastOpVal> CastOps
1027 %token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1028 %token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1031 %token <OtherOpVal> PHI_TOK SELECT VAARG
1032 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1034 // Function Attributes
1035 %token NORETURN INREG SRET
1037 // Visibility Styles
1038 %token DEFAULT HIDDEN
1044 // Operations that are notably excluded from this list include:
1045 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1047 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1048 LogicalOps : SHL | LSHR | ASHR | AND | OR | XOR;
1049 CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1050 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1053 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1054 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1055 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1056 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1057 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1061 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1062 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1063 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1064 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1065 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1066 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1067 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1068 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1069 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1072 // These are some types that allow classification if we only want a particular
1073 // thing... for example, only a signed, unsigned, or integral type.
1075 FPType : FLOAT | DOUBLE;
1077 LocalName : LOCALVAR | STRINGCONSTANT;
1078 OptLocalName : LocalName | /*empty*/ { $$ = 0; };
1080 /// OptLocalAssign - Value producing statements have an optional assignment
1082 OptLocalAssign : LocalName '=' {
1091 GlobalName : GLOBALVAR | ATSTRINGCONSTANT;
1093 OptGlobalAssign : GlobalName '=' {
1103 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1104 | WEAK { $$ = GlobalValue::WeakLinkage; }
1105 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1106 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1107 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1111 : DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1112 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1113 | EXTERNAL { $$ = GlobalValue::ExternalLinkage; }
1117 : /*empty*/ { $$ = GlobalValue::DefaultVisibility; }
1118 | HIDDEN { $$ = GlobalValue::HiddenVisibility; }
1121 FunctionDeclareLinkage
1122 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1123 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1124 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1127 FunctionDefineLinkage
1128 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1129 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1130 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1131 | WEAK { $$ = GlobalValue::WeakLinkage; }
1132 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1135 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1136 CCC_TOK { $$ = CallingConv::C; } |
1137 FASTCC_TOK { $$ = CallingConv::Fast; } |
1138 COLDCC_TOK { $$ = CallingConv::Cold; } |
1139 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1140 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1142 if ((unsigned)$2 != $2)
1143 GEN_ERROR("Calling conv too large");
1148 ParamAttr : ZEXT { $$ = FunctionType::ZExtAttribute; }
1149 | SEXT { $$ = FunctionType::SExtAttribute; }
1150 | INREG { $$ = FunctionType::InRegAttribute; }
1151 | SRET { $$ = FunctionType::StructRetAttribute; }
1154 OptParamAttrs : /* empty */ { $$ = FunctionType::NoAttributeSet; }
1155 | OptParamAttrs ParamAttr {
1156 $$ = FunctionType::ParameterAttributes($1 | $2);
1160 FuncAttr : NORETURN { $$ = FunctionType::NoReturnAttribute; }
1164 OptFuncAttrs : /* empty */ { $$ = FunctionType::NoAttributeSet; }
1165 | OptFuncAttrs FuncAttr {
1166 $$ = FunctionType::ParameterAttributes($1 | $2);
1170 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1171 // a comma before it.
1172 OptAlign : /*empty*/ { $$ = 0; } |
1175 if ($$ != 0 && !isPowerOf2_32($$))
1176 GEN_ERROR("Alignment must be a power of two");
1179 OptCAlign : /*empty*/ { $$ = 0; } |
1180 ',' ALIGN EUINT64VAL {
1182 if ($$ != 0 && !isPowerOf2_32($$))
1183 GEN_ERROR("Alignment must be a power of two");
1188 SectionString : SECTION STRINGCONSTANT {
1189 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1190 if ($2[i] == '"' || $2[i] == '\\')
1191 GEN_ERROR("Invalid character in section name");
1196 OptSection : /*empty*/ { $$ = 0; } |
1197 SectionString { $$ = $1; };
1199 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1200 // is set to be the global we are processing.
1202 GlobalVarAttributes : /* empty */ {} |
1203 ',' GlobalVarAttribute GlobalVarAttributes {};
1204 GlobalVarAttribute : SectionString {
1205 CurGV->setSection($1);
1209 | ALIGN EUINT64VAL {
1210 if ($2 != 0 && !isPowerOf2_32($2))
1211 GEN_ERROR("Alignment must be a power of two");
1212 CurGV->setAlignment($2);
1216 //===----------------------------------------------------------------------===//
1217 // Types includes all predefined types... except void, because it can only be
1218 // used in specific contexts (function returning void for example).
1220 // Derived types are added later...
1222 PrimType : INTTYPE | FLOAT | DOUBLE | LABEL ;
1226 $$ = new PATypeHolder(OpaqueType::get());
1230 $$ = new PATypeHolder($1);
1233 | Types '*' { // Pointer type?
1234 if (*$1 == Type::LabelTy)
1235 GEN_ERROR("Cannot form a pointer to a basic block");
1236 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1240 | SymbolicValueRef { // Named types are also simple types...
1241 const Type* tmp = getTypeVal($1);
1243 $$ = new PATypeHolder(tmp);
1245 | '\\' EUINT64VAL { // Type UpReference
1246 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range");
1247 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1248 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1249 $$ = new PATypeHolder(OT);
1250 UR_OUT("New Upreference!\n");
1253 | Types '(' ArgTypeListI ')' OptFuncAttrs {
1254 std::vector<const Type*> Params;
1255 std::vector<FunctionType::ParameterAttributes> Attrs;
1256 Attrs.push_back($5);
1257 for (TypeWithAttrsList::iterator I=$3->begin(), E=$3->end(); I != E; ++I) {
1258 Params.push_back(I->Ty->get());
1259 if (I->Ty->get() != Type::VoidTy)
1260 Attrs.push_back(I->Attrs);
1262 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1263 if (isVarArg) Params.pop_back();
1265 FunctionType *FT = FunctionType::get(*$1, Params, isVarArg, Attrs);
1266 delete $3; // Delete the argument list
1267 delete $1; // Delete the return type handle
1268 $$ = new PATypeHolder(HandleUpRefs(FT));
1271 | VOID '(' ArgTypeListI ')' OptFuncAttrs {
1272 std::vector<const Type*> Params;
1273 std::vector<FunctionType::ParameterAttributes> Attrs;
1274 Attrs.push_back($5);
1275 for (TypeWithAttrsList::iterator I=$3->begin(), E=$3->end(); I != E; ++I) {
1276 Params.push_back(I->Ty->get());
1277 if (I->Ty->get() != Type::VoidTy)
1278 Attrs.push_back(I->Attrs);
1280 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1281 if (isVarArg) Params.pop_back();
1283 FunctionType *FT = FunctionType::get($1, Params, isVarArg, Attrs);
1284 delete $3; // Delete the argument list
1285 $$ = new PATypeHolder(HandleUpRefs(FT));
1289 | '[' EUINT64VAL 'x' Types ']' { // Sized array type?
1290 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1294 | '<' EUINT64VAL 'x' Types '>' { // Packed array type?
1295 const llvm::Type* ElemTy = $4->get();
1296 if ((unsigned)$2 != $2)
1297 GEN_ERROR("Unsigned result not equal to signed result");
1298 if (!ElemTy->isFloatingPoint() && !ElemTy->isInteger())
1299 GEN_ERROR("Element type of a PackedType must be primitive");
1300 if (!isPowerOf2_32($2))
1301 GEN_ERROR("Vector length should be a power of 2");
1302 $$ = new PATypeHolder(HandleUpRefs(PackedType::get(*$4, (unsigned)$2)));
1306 | '{' TypeListI '}' { // Structure type?
1307 std::vector<const Type*> Elements;
1308 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1309 E = $2->end(); I != E; ++I)
1310 Elements.push_back(*I);
1312 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1316 | '{' '}' { // Empty structure type?
1317 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1320 | '<' '{' TypeListI '}' '>' {
1321 std::vector<const Type*> Elements;
1322 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1323 E = $3->end(); I != E; ++I)
1324 Elements.push_back(*I);
1326 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1330 | '<' '{' '}' '>' { // Empty structure type?
1331 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1337 : Types OptParamAttrs {
1345 if (!UpRefs.empty())
1346 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1347 if (!(*$1)->isFirstClassType())
1348 GEN_ERROR("LLVM functions cannot return aggregate types");
1352 $$ = new PATypeHolder(Type::VoidTy);
1356 ArgTypeList : ArgType {
1357 $$ = new TypeWithAttrsList();
1361 | ArgTypeList ',' ArgType {
1362 ($$=$1)->push_back($3);
1369 | ArgTypeList ',' DOTDOTDOT {
1371 TypeWithAttrs TWA; TWA.Attrs = FunctionType::NoAttributeSet;
1372 TWA.Ty = new PATypeHolder(Type::VoidTy);
1377 $$ = new TypeWithAttrsList;
1378 TypeWithAttrs TWA; TWA.Attrs = FunctionType::NoAttributeSet;
1379 TWA.Ty = new PATypeHolder(Type::VoidTy);
1384 $$ = new TypeWithAttrsList();
1388 // TypeList - Used for struct declarations and as a basis for function type
1389 // declaration type lists
1392 $$ = new std::list<PATypeHolder>();
1393 $$->push_back(*$1); delete $1;
1396 | TypeListI ',' Types {
1397 ($$=$1)->push_back(*$3); delete $3;
1401 // ConstVal - The various declarations that go into the constant pool. This
1402 // production is used ONLY to represent constants that show up AFTER a 'const',
1403 // 'constant' or 'global' token at global scope. Constants that can be inlined
1404 // into other expressions (such as integers and constexprs) are handled by the
1405 // ResolvedVal, ValueRef and ConstValueRef productions.
1407 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1408 if (!UpRefs.empty())
1409 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1410 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1412 GEN_ERROR("Cannot make array constant with type: '" +
1413 (*$1)->getDescription() + "'");
1414 const Type *ETy = ATy->getElementType();
1415 int NumElements = ATy->getNumElements();
1417 // Verify that we have the correct size...
1418 if (NumElements != -1 && NumElements != (int)$3->size())
1419 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1420 utostr($3->size()) + " arguments, but has size of " +
1421 itostr(NumElements) + "");
1423 // Verify all elements are correct type!
1424 for (unsigned i = 0; i < $3->size(); i++) {
1425 if (ETy != (*$3)[i]->getType())
1426 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1427 ETy->getDescription() +"' as required!\nIt is of type '"+
1428 (*$3)[i]->getType()->getDescription() + "'.");
1431 $$ = ConstantArray::get(ATy, *$3);
1432 delete $1; delete $3;
1436 if (!UpRefs.empty())
1437 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1438 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1440 GEN_ERROR("Cannot make array constant with type: '" +
1441 (*$1)->getDescription() + "'");
1443 int NumElements = ATy->getNumElements();
1444 if (NumElements != -1 && NumElements != 0)
1445 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1446 " arguments, but has size of " + itostr(NumElements) +"");
1447 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1451 | Types 'c' STRINGCONSTANT {
1452 if (!UpRefs.empty())
1453 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1454 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1456 GEN_ERROR("Cannot make array constant with type: '" +
1457 (*$1)->getDescription() + "'");
1459 int NumElements = ATy->getNumElements();
1460 const Type *ETy = ATy->getElementType();
1461 char *EndStr = UnEscapeLexed($3, true);
1462 if (NumElements != -1 && NumElements != (EndStr-$3))
1463 GEN_ERROR("Can't build string constant of size " +
1464 itostr((int)(EndStr-$3)) +
1465 " when array has size " + itostr(NumElements) + "");
1466 std::vector<Constant*> Vals;
1467 if (ETy == Type::Int8Ty) {
1468 for (unsigned char *C = (unsigned char *)$3;
1469 C != (unsigned char*)EndStr; ++C)
1470 Vals.push_back(ConstantInt::get(ETy, *C));
1473 GEN_ERROR("Cannot build string arrays of non byte sized elements");
1476 $$ = ConstantArray::get(ATy, Vals);
1480 | Types '<' ConstVector '>' { // Nonempty unsized arr
1481 if (!UpRefs.empty())
1482 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1483 const PackedType *PTy = dyn_cast<PackedType>($1->get());
1485 GEN_ERROR("Cannot make packed constant with type: '" +
1486 (*$1)->getDescription() + "'");
1487 const Type *ETy = PTy->getElementType();
1488 int NumElements = PTy->getNumElements();
1490 // Verify that we have the correct size...
1491 if (NumElements != -1 && NumElements != (int)$3->size())
1492 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1493 utostr($3->size()) + " arguments, but has size of " +
1494 itostr(NumElements) + "");
1496 // Verify all elements are correct type!
1497 for (unsigned i = 0; i < $3->size(); i++) {
1498 if (ETy != (*$3)[i]->getType())
1499 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1500 ETy->getDescription() +"' as required!\nIt is of type '"+
1501 (*$3)[i]->getType()->getDescription() + "'.");
1504 $$ = ConstantPacked::get(PTy, *$3);
1505 delete $1; delete $3;
1508 | Types '{' ConstVector '}' {
1509 const StructType *STy = dyn_cast<StructType>($1->get());
1511 GEN_ERROR("Cannot make struct constant with type: '" +
1512 (*$1)->getDescription() + "'");
1514 if ($3->size() != STy->getNumContainedTypes())
1515 GEN_ERROR("Illegal number of initializers for structure type");
1517 // Check to ensure that constants are compatible with the type initializer!
1518 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1519 if ((*$3)[i]->getType() != STy->getElementType(i))
1520 GEN_ERROR("Expected type '" +
1521 STy->getElementType(i)->getDescription() +
1522 "' for element #" + utostr(i) +
1523 " of structure initializer");
1525 // Check to ensure that Type is not packed
1526 if (STy->isPacked())
1527 GEN_ERROR("Unpacked Initializer to packed type '" + STy->getDescription() + "'");
1529 $$ = ConstantStruct::get(STy, *$3);
1530 delete $1; delete $3;
1534 if (!UpRefs.empty())
1535 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1536 const StructType *STy = dyn_cast<StructType>($1->get());
1538 GEN_ERROR("Cannot make struct constant with type: '" +
1539 (*$1)->getDescription() + "'");
1541 if (STy->getNumContainedTypes() != 0)
1542 GEN_ERROR("Illegal number of initializers for structure type");
1544 // Check to ensure that Type is not packed
1545 if (STy->isPacked())
1546 GEN_ERROR("Unpacked Initializer to packed type '" + STy->getDescription() + "'");
1548 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1552 | Types '<' '{' ConstVector '}' '>' {
1553 const StructType *STy = dyn_cast<StructType>($1->get());
1555 GEN_ERROR("Cannot make struct constant with type: '" +
1556 (*$1)->getDescription() + "'");
1558 if ($4->size() != STy->getNumContainedTypes())
1559 GEN_ERROR("Illegal number of initializers for structure type");
1561 // Check to ensure that constants are compatible with the type initializer!
1562 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1563 if ((*$4)[i]->getType() != STy->getElementType(i))
1564 GEN_ERROR("Expected type '" +
1565 STy->getElementType(i)->getDescription() +
1566 "' for element #" + utostr(i) +
1567 " of structure initializer");
1569 // Check to ensure that Type is packed
1570 if (!STy->isPacked())
1571 GEN_ERROR("Packed Initializer to unpacked type '" + STy->getDescription() + "'");
1573 $$ = ConstantStruct::get(STy, *$4);
1574 delete $1; delete $4;
1577 | Types '<' '{' '}' '>' {
1578 if (!UpRefs.empty())
1579 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1580 const StructType *STy = dyn_cast<StructType>($1->get());
1582 GEN_ERROR("Cannot make struct constant with type: '" +
1583 (*$1)->getDescription() + "'");
1585 if (STy->getNumContainedTypes() != 0)
1586 GEN_ERROR("Illegal number of initializers for structure type");
1588 // Check to ensure that Type is packed
1589 if (!STy->isPacked())
1590 GEN_ERROR("Packed Initializer to unpacked type '" + STy->getDescription() + "'");
1592 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1597 if (!UpRefs.empty())
1598 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1599 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1601 GEN_ERROR("Cannot make null pointer constant with type: '" +
1602 (*$1)->getDescription() + "'");
1604 $$ = ConstantPointerNull::get(PTy);
1609 if (!UpRefs.empty())
1610 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1611 $$ = UndefValue::get($1->get());
1615 | Types SymbolicValueRef {
1616 if (!UpRefs.empty())
1617 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1618 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1620 GEN_ERROR("Global const reference must be a pointer type");
1622 // ConstExprs can exist in the body of a function, thus creating
1623 // GlobalValues whenever they refer to a variable. Because we are in
1624 // the context of a function, getValNonImprovising will search the functions
1625 // symbol table instead of the module symbol table for the global symbol,
1626 // which throws things all off. To get around this, we just tell
1627 // getValNonImprovising that we are at global scope here.
1629 Function *SavedCurFn = CurFun.CurrentFunction;
1630 CurFun.CurrentFunction = 0;
1632 Value *V = getValNonImprovising(Ty, $2);
1635 CurFun.CurrentFunction = SavedCurFn;
1637 // If this is an initializer for a constant pointer, which is referencing a
1638 // (currently) undefined variable, create a stub now that shall be replaced
1639 // in the future with the right type of variable.
1642 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1643 const PointerType *PT = cast<PointerType>(Ty);
1645 // First check to see if the forward references value is already created!
1646 PerModuleInfo::GlobalRefsType::iterator I =
1647 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1649 if (I != CurModule.GlobalRefs.end()) {
1650 V = I->second; // Placeholder already exists, use it...
1654 if ($2.Type == ValID::GlobalName)
1656 else if ($2.Type != ValID::GlobalID)
1657 GEN_ERROR("Invalid reference to global");
1659 // Create the forward referenced global.
1661 if (const FunctionType *FTy =
1662 dyn_cast<FunctionType>(PT->getElementType())) {
1663 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1664 CurModule.CurrentModule);
1666 GV = new GlobalVariable(PT->getElementType(), false,
1667 GlobalValue::ExternalLinkage, 0,
1668 Name, CurModule.CurrentModule);
1671 // Keep track of the fact that we have a forward ref to recycle it
1672 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1677 $$ = cast<GlobalValue>(V);
1678 delete $1; // Free the type handle
1682 if (!UpRefs.empty())
1683 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1684 if ($1->get() != $2->getType())
1685 GEN_ERROR("Mismatched types for constant expression: " +
1686 (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1691 | Types ZEROINITIALIZER {
1692 if (!UpRefs.empty())
1693 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1694 const Type *Ty = $1->get();
1695 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1696 GEN_ERROR("Cannot create a null initialized value of this type");
1697 $$ = Constant::getNullValue(Ty);
1701 | IntType ESINT64VAL { // integral constants
1702 if (!ConstantInt::isValueValidForType($1, $2))
1703 GEN_ERROR("Constant value doesn't fit in type");
1704 $$ = ConstantInt::get($1, $2);
1707 | IntType EUINT64VAL { // integral constants
1708 if (!ConstantInt::isValueValidForType($1, $2))
1709 GEN_ERROR("Constant value doesn't fit in type");
1710 $$ = ConstantInt::get($1, $2);
1713 | INTTYPE TRUETOK { // Boolean constants
1714 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1715 $$ = ConstantInt::getTrue();
1718 | INTTYPE FALSETOK { // Boolean constants
1719 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1720 $$ = ConstantInt::getFalse();
1723 | FPType FPVAL { // Float & Double constants
1724 if (!ConstantFP::isValueValidForType($1, $2))
1725 GEN_ERROR("Floating point constant invalid for type");
1726 $$ = ConstantFP::get($1, $2);
1731 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1732 if (!UpRefs.empty())
1733 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1735 const Type *DestTy = $5->get();
1736 if (!CastInst::castIsValid($1, $3, DestTy))
1737 GEN_ERROR("invalid cast opcode for cast from '" +
1738 Val->getType()->getDescription() + "' to '" +
1739 DestTy->getDescription() + "'");
1740 $$ = ConstantExpr::getCast($1, $3, DestTy);
1743 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1744 if (!isa<PointerType>($3->getType()))
1745 GEN_ERROR("GetElementPtr requires a pointer operand");
1748 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1750 GEN_ERROR("Index list invalid for constant getelementptr");
1752 SmallVector<Constant*, 8> IdxVec;
1753 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1754 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1755 IdxVec.push_back(C);
1757 GEN_ERROR("Indices to constant getelementptr must be constants");
1761 $$ = ConstantExpr::getGetElementPtr($3, &IdxVec[0], IdxVec.size());
1764 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1765 if ($3->getType() != Type::Int1Ty)
1766 GEN_ERROR("Select condition must be of boolean type");
1767 if ($5->getType() != $7->getType())
1768 GEN_ERROR("Select operand types must match");
1769 $$ = ConstantExpr::getSelect($3, $5, $7);
1772 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1773 if ($3->getType() != $5->getType())
1774 GEN_ERROR("Binary operator types must match");
1776 $$ = ConstantExpr::get($1, $3, $5);
1778 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1779 if ($3->getType() != $5->getType())
1780 GEN_ERROR("Logical operator types must match");
1781 if (!$3->getType()->isInteger()) {
1782 if (Instruction::isShift($1) || !isa<PackedType>($3->getType()) ||
1783 !cast<PackedType>($3->getType())->getElementType()->isInteger())
1784 GEN_ERROR("Logical operator requires integral operands");
1786 $$ = ConstantExpr::get($1, $3, $5);
1789 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1790 if ($4->getType() != $6->getType())
1791 GEN_ERROR("icmp operand types must match");
1792 $$ = ConstantExpr::getICmp($2, $4, $6);
1794 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1795 if ($4->getType() != $6->getType())
1796 GEN_ERROR("fcmp operand types must match");
1797 $$ = ConstantExpr::getFCmp($2, $4, $6);
1799 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1800 if (!ExtractElementInst::isValidOperands($3, $5))
1801 GEN_ERROR("Invalid extractelement operands");
1802 $$ = ConstantExpr::getExtractElement($3, $5);
1805 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1806 if (!InsertElementInst::isValidOperands($3, $5, $7))
1807 GEN_ERROR("Invalid insertelement operands");
1808 $$ = ConstantExpr::getInsertElement($3, $5, $7);
1811 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1812 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1813 GEN_ERROR("Invalid shufflevector operands");
1814 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1819 // ConstVector - A list of comma separated constants.
1820 ConstVector : ConstVector ',' ConstVal {
1821 ($$ = $1)->push_back($3);
1825 $$ = new std::vector<Constant*>();
1831 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1832 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1835 //===----------------------------------------------------------------------===//
1836 // Rules to match Modules
1837 //===----------------------------------------------------------------------===//
1839 // Module rule: Capture the result of parsing the whole file into a result
1844 $$ = ParserResult = CurModule.CurrentModule;
1845 CurModule.ModuleDone();
1849 $$ = ParserResult = CurModule.CurrentModule;
1850 CurModule.ModuleDone();
1857 | DefinitionList Definition
1861 : DEFINE { CurFun.isDeclare = false; } Function {
1862 CurFun.FunctionDone();
1865 | DECLARE { CurFun.isDeclare = true; } FunctionProto {
1868 | MODULE ASM_TOK AsmBlock {
1872 // Emit an error if there are any unresolved types left.
1873 if (!CurModule.LateResolveTypes.empty()) {
1874 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
1875 if (DID.Type == ValID::LocalName) {
1876 GEN_ERROR("Reference to an undefined type: '"+DID.getName() + "'");
1878 GEN_ERROR("Reference to an undefined type: #" + itostr(DID.Num));
1883 | OptLocalAssign TYPE Types {
1884 if (!UpRefs.empty())
1885 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
1886 // Eagerly resolve types. This is not an optimization, this is a
1887 // requirement that is due to the fact that we could have this:
1889 // %list = type { %list * }
1890 // %list = type { %list * } ; repeated type decl
1892 // If types are not resolved eagerly, then the two types will not be
1893 // determined to be the same type!
1895 ResolveTypeTo($1, *$3);
1897 if (!setTypeName(*$3, $1) && !$1) {
1899 // If this is a named type that is not a redefinition, add it to the slot
1901 CurModule.Types.push_back(*$3);
1907 | OptLocalAssign TYPE VOID {
1908 ResolveTypeTo($1, $3);
1910 if (!setTypeName($3, $1) && !$1) {
1912 // If this is a named type that is not a redefinition, add it to the slot
1914 CurModule.Types.push_back($3);
1918 | OptGlobalAssign GVVisibilityStyle GlobalType ConstVal {
1919 /* "Externally Visible" Linkage */
1921 GEN_ERROR("Global value initializer is not a constant");
1922 CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
1923 $2, $3, $4->getType(), $4);
1925 } GlobalVarAttributes {
1928 | OptGlobalAssign GVInternalLinkage GVVisibilityStyle GlobalType ConstVal {
1930 GEN_ERROR("Global value initializer is not a constant");
1931 CurGV = ParseGlobalVariable($1, $2, $3, $4, $5->getType(), $5);
1933 } GlobalVarAttributes {
1936 | OptGlobalAssign GVExternalLinkage GVVisibilityStyle GlobalType Types {
1937 if (!UpRefs.empty())
1938 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1939 CurGV = ParseGlobalVariable($1, $2, $3, $4, *$5, 0);
1942 } GlobalVarAttributes {
1946 | TARGET TargetDefinition {
1949 | DEPLIBS '=' LibrariesDefinition {
1955 AsmBlock : STRINGCONSTANT {
1956 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
1957 char *EndStr = UnEscapeLexed($1, true);
1958 std::string NewAsm($1, EndStr);
1961 if (AsmSoFar.empty())
1962 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
1964 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
1968 TargetDefinition : TRIPLE '=' STRINGCONSTANT {
1969 CurModule.CurrentModule->setTargetTriple($3);
1972 | DATALAYOUT '=' STRINGCONSTANT {
1973 CurModule.CurrentModule->setDataLayout($3);
1977 LibrariesDefinition : '[' LibList ']';
1979 LibList : LibList ',' STRINGCONSTANT {
1980 CurModule.CurrentModule->addLibrary($3);
1985 CurModule.CurrentModule->addLibrary($1);
1989 | /* empty: end of list */ {
1994 //===----------------------------------------------------------------------===//
1995 // Rules to match Function Headers
1996 //===----------------------------------------------------------------------===//
1998 ArgListH : ArgListH ',' Types OptParamAttrs OptLocalName {
1999 if (!UpRefs.empty())
2000 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2001 if (*$3 == Type::VoidTy)
2002 GEN_ERROR("void typed arguments are invalid");
2003 ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
2008 | Types OptParamAttrs OptLocalName {
2009 if (!UpRefs.empty())
2010 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2011 if (*$1 == Type::VoidTy)
2012 GEN_ERROR("void typed arguments are invalid");
2013 ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2014 $$ = new ArgListType;
2019 ArgList : ArgListH {
2023 | ArgListH ',' DOTDOTDOT {
2025 struct ArgListEntry E;
2026 E.Ty = new PATypeHolder(Type::VoidTy);
2028 E.Attrs = FunctionType::NoAttributeSet;
2033 $$ = new ArgListType;
2034 struct ArgListEntry E;
2035 E.Ty = new PATypeHolder(Type::VoidTy);
2037 E.Attrs = FunctionType::NoAttributeSet;
2046 FunctionHeaderH : OptCallingConv ResultTypes GlobalName '(' ArgList ')'
2047 OptFuncAttrs OptSection OptAlign {
2049 std::string FunctionName($3);
2050 free($3); // Free strdup'd memory!
2052 // Check the function result for abstractness if this is a define. We should
2053 // have no abstract types at this point
2054 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($2))
2055 GEN_ERROR("Reference to abstract result: "+ $2->get()->getDescription());
2057 std::vector<const Type*> ParamTypeList;
2058 std::vector<FunctionType::ParameterAttributes> ParamAttrs;
2059 ParamAttrs.push_back($7);
2060 if ($5) { // If there are arguments...
2061 for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I) {
2062 const Type* Ty = I->Ty->get();
2063 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2064 GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2065 ParamTypeList.push_back(Ty);
2066 if (Ty != Type::VoidTy)
2067 ParamAttrs.push_back(I->Attrs);
2071 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2072 if (isVarArg) ParamTypeList.pop_back();
2074 FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg,
2076 const PointerType *PFT = PointerType::get(FT);
2080 if (!FunctionName.empty()) {
2081 ID = ValID::createGlobalName((char*)FunctionName.c_str());
2083 ID = ValID::createGlobalID(CurModule.Values[PFT].size());
2087 // See if this function was forward referenced. If so, recycle the object.
2088 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2089 // Move the function to the end of the list, from whereever it was
2090 // previously inserted.
2091 Fn = cast<Function>(FWRef);
2092 CurModule.CurrentModule->getFunctionList().remove(Fn);
2093 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2094 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2095 (Fn = CurModule.CurrentModule->getFunction(FunctionName))) {
2096 if (Fn->getFunctionType() != FT ) {
2097 // The existing function doesn't have the same type. This is an overload
2099 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2100 } else if (!CurFun.isDeclare && !Fn->isDeclaration()) {
2101 // Neither the existing or the current function is a declaration and they
2102 // have the same name and same type. Clearly this is a redefinition.
2103 GEN_ERROR("Redefinition of function '" + FunctionName + "'");
2104 } if (Fn->isDeclaration()) {
2105 // Make sure to strip off any argument names so we can't get conflicts.
2106 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2110 } else { // Not already defined?
2111 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
2112 CurModule.CurrentModule);
2114 InsertValue(Fn, CurModule.Values);
2117 CurFun.FunctionStart(Fn);
2119 if (CurFun.isDeclare) {
2120 // If we have declaration, always overwrite linkage. This will allow us to
2121 // correctly handle cases, when pointer to function is passed as argument to
2122 // another function.
2123 Fn->setLinkage(CurFun.Linkage);
2124 Fn->setVisibility(CurFun.Visibility);
2126 Fn->setCallingConv($1);
2127 Fn->setAlignment($9);
2133 // Add all of the arguments we parsed to the function...
2134 if ($5) { // Is null if empty...
2135 if (isVarArg) { // Nuke the last entry
2136 assert($5->back().Ty->get() == Type::VoidTy && $5->back().Name == 0 &&
2137 "Not a varargs marker!");
2138 delete $5->back().Ty;
2139 $5->pop_back(); // Delete the last entry
2141 Function::arg_iterator ArgIt = Fn->arg_begin();
2142 Function::arg_iterator ArgEnd = Fn->arg_end();
2144 for (ArgListType::iterator I = $5->begin();
2145 I != $5->end() && ArgIt != ArgEnd; ++I, ++ArgIt) {
2146 delete I->Ty; // Delete the typeholder...
2147 setValueName(ArgIt, I->Name); // Insert arg into symtab...
2153 delete $5; // We're now done with the argument list
2158 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2160 FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2161 $$ = CurFun.CurrentFunction;
2163 // Make sure that we keep track of the linkage type even if there was a
2164 // previous "declare".
2166 $$->setVisibility($2);
2169 END : ENDTOK | '}'; // Allow end of '}' to end a function
2171 Function : BasicBlockList END {
2176 FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2177 CurFun.CurrentFunction->setLinkage($1);
2178 CurFun.CurrentFunction->setVisibility($2);
2179 $$ = CurFun.CurrentFunction;
2180 CurFun.FunctionDone();
2184 //===----------------------------------------------------------------------===//
2185 // Rules to match Basic Blocks
2186 //===----------------------------------------------------------------------===//
2188 OptSideEffect : /* empty */ {
2197 ConstValueRef : ESINT64VAL { // A reference to a direct constant
2198 $$ = ValID::create($1);
2202 $$ = ValID::create($1);
2205 | FPVAL { // Perhaps it's an FP constant?
2206 $$ = ValID::create($1);
2210 $$ = ValID::create(ConstantInt::getTrue());
2214 $$ = ValID::create(ConstantInt::getFalse());
2218 $$ = ValID::createNull();
2222 $$ = ValID::createUndef();
2225 | ZEROINITIALIZER { // A vector zero constant.
2226 $$ = ValID::createZeroInit();
2229 | '<' ConstVector '>' { // Nonempty unsized packed vector
2230 const Type *ETy = (*$2)[0]->getType();
2231 int NumElements = $2->size();
2233 PackedType* pt = PackedType::get(ETy, NumElements);
2234 PATypeHolder* PTy = new PATypeHolder(
2242 // Verify all elements are correct type!
2243 for (unsigned i = 0; i < $2->size(); i++) {
2244 if (ETy != (*$2)[i]->getType())
2245 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2246 ETy->getDescription() +"' as required!\nIt is of type '" +
2247 (*$2)[i]->getType()->getDescription() + "'.");
2250 $$ = ValID::create(ConstantPacked::get(pt, *$2));
2251 delete PTy; delete $2;
2255 $$ = ValID::create($1);
2258 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2259 char *End = UnEscapeLexed($3, true);
2260 std::string AsmStr = std::string($3, End);
2261 End = UnEscapeLexed($5, true);
2262 std::string Constraints = std::string($5, End);
2263 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2269 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2272 SymbolicValueRef : LOCALVAL_ID { // Is it an integer reference...?
2273 $$ = ValID::createLocalID($1);
2277 $$ = ValID::createGlobalID($1);
2280 | LocalName { // Is it a named reference...?
2281 $$ = ValID::createLocalName($1);
2284 | GlobalName { // Is it a named reference...?
2285 $$ = ValID::createGlobalName($1);
2289 // ValueRef - A reference to a definition... either constant or symbolic
2290 ValueRef : SymbolicValueRef | ConstValueRef;
2293 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2294 // type immediately preceeds the value reference, and allows complex constant
2295 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2296 ResolvedVal : Types ValueRef {
2297 if (!UpRefs.empty())
2298 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2299 $$ = getVal(*$1, $2);
2305 BasicBlockList : BasicBlockList BasicBlock {
2309 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2315 // Basic blocks are terminated by branching instructions:
2316 // br, br/cc, switch, ret
2318 BasicBlock : InstructionList OptLocalAssign BBTerminatorInst {
2319 setValueName($3, $2);
2322 $1->getInstList().push_back($3);
2328 InstructionList : InstructionList Inst {
2329 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2330 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2331 if (CI2->getParent() == 0)
2332 $1->getInstList().push_back(CI2);
2333 $1->getInstList().push_back($2);
2338 $$ = getBBVal(ValID::createLocalID(CurFun.NextBBNum++), true);
2341 // Make sure to move the basic block to the correct location in the
2342 // function, instead of leaving it inserted wherever it was first
2344 Function::BasicBlockListType &BBL =
2345 CurFun.CurrentFunction->getBasicBlockList();
2346 BBL.splice(BBL.end(), BBL, $$);
2350 $$ = getBBVal(ValID::createLocalName($1), true);
2353 // Make sure to move the basic block to the correct location in the
2354 // function, instead of leaving it inserted wherever it was first
2356 Function::BasicBlockListType &BBL =
2357 CurFun.CurrentFunction->getBasicBlockList();
2358 BBL.splice(BBL.end(), BBL, $$);
2362 BBTerminatorInst : RET ResolvedVal { // Return with a result...
2363 $$ = new ReturnInst($2);
2366 | RET VOID { // Return with no result...
2367 $$ = new ReturnInst();
2370 | BR LABEL ValueRef { // Unconditional Branch...
2371 BasicBlock* tmpBB = getBBVal($3);
2373 $$ = new BranchInst(tmpBB);
2374 } // Conditional Branch...
2375 | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2376 assert(cast<IntegerType>($2)->getBitWidth() == 1 && "Not Bool?");
2377 BasicBlock* tmpBBA = getBBVal($6);
2379 BasicBlock* tmpBBB = getBBVal($9);
2381 Value* tmpVal = getVal(Type::Int1Ty, $3);
2383 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2385 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2386 Value* tmpVal = getVal($2, $3);
2388 BasicBlock* tmpBB = getBBVal($6);
2390 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2393 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2395 for (; I != E; ++I) {
2396 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2397 S->addCase(CI, I->second);
2399 GEN_ERROR("Switch case is constant, but not a simple integer");
2404 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2405 Value* tmpVal = getVal($2, $3);
2407 BasicBlock* tmpBB = getBBVal($6);
2409 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2413 | INVOKE OptCallingConv ResultTypes ValueRef '(' ValueRefList ')' OptFuncAttrs
2414 TO LABEL ValueRef UNWIND LABEL ValueRef {
2416 // Handle the short syntax
2417 const PointerType *PFTy = 0;
2418 const FunctionType *Ty = 0;
2419 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2420 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2421 // Pull out the types of all of the arguments...
2422 std::vector<const Type*> ParamTypes;
2423 FunctionType::ParamAttrsList ParamAttrs;
2424 ParamAttrs.push_back($8);
2425 for (ValueRefList::iterator I = $6->begin(), E = $6->end(); I != E; ++I) {
2426 const Type *Ty = I->Val->getType();
2427 if (Ty == Type::VoidTy)
2428 GEN_ERROR("Short call syntax cannot be used with varargs");
2429 ParamTypes.push_back(Ty);
2430 ParamAttrs.push_back(I->Attrs);
2433 Ty = FunctionType::get($3->get(), ParamTypes, false, ParamAttrs);
2434 PFTy = PointerType::get(Ty);
2437 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2439 BasicBlock *Normal = getBBVal($11);
2441 BasicBlock *Except = getBBVal($14);
2444 // Check the arguments
2446 if ($6->empty()) { // Has no arguments?
2447 // Make sure no arguments is a good thing!
2448 if (Ty->getNumParams() != 0)
2449 GEN_ERROR("No arguments passed to a function that "
2450 "expects arguments");
2451 } else { // Has arguments?
2452 // Loop through FunctionType's arguments and ensure they are specified
2454 FunctionType::param_iterator I = Ty->param_begin();
2455 FunctionType::param_iterator E = Ty->param_end();
2456 ValueRefList::iterator ArgI = $6->begin(), ArgE = $6->end();
2458 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2459 if (ArgI->Val->getType() != *I)
2460 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2461 (*I)->getDescription() + "'");
2462 Args.push_back(ArgI->Val);
2465 if (Ty->isVarArg()) {
2467 for (; ArgI != ArgE; ++ArgI)
2468 Args.push_back(ArgI->Val); // push the remaining varargs
2469 } else if (I != E || ArgI != ArgE)
2470 GEN_ERROR("Invalid number of parameters detected");
2473 // Create the InvokeInst
2474 InvokeInst *II = new InvokeInst(V, Normal, Except, Args);
2475 II->setCallingConv($2);
2481 $$ = new UnwindInst();
2485 $$ = new UnreachableInst();
2491 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2493 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
2496 GEN_ERROR("May only switch on a constant pool value");
2498 BasicBlock* tmpBB = getBBVal($6);
2500 $$->push_back(std::make_pair(V, tmpBB));
2502 | IntType ConstValueRef ',' LABEL ValueRef {
2503 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2504 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
2508 GEN_ERROR("May only switch on a constant pool value");
2510 BasicBlock* tmpBB = getBBVal($5);
2512 $$->push_back(std::make_pair(V, tmpBB));
2515 Inst : OptLocalAssign InstVal {
2516 // Is this definition named?? if so, assign the name...
2517 setValueName($2, $1);
2525 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2526 if (!UpRefs.empty())
2527 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2528 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2529 Value* tmpVal = getVal(*$1, $3);
2531 BasicBlock* tmpBB = getBBVal($5);
2533 $$->push_back(std::make_pair(tmpVal, tmpBB));
2536 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2538 Value* tmpVal = getVal($1->front().first->getType(), $4);
2540 BasicBlock* tmpBB = getBBVal($6);
2542 $1->push_back(std::make_pair(tmpVal, tmpBB));
2546 ValueRefList : Types ValueRef OptParamAttrs {
2547 if (!UpRefs.empty())
2548 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2549 // Used for call and invoke instructions
2550 $$ = new ValueRefList();
2551 ValueRefListEntry E; E.Attrs = $3; E.Val = getVal($1->get(), $2);
2554 | ValueRefList ',' Types ValueRef OptParamAttrs {
2555 if (!UpRefs.empty())
2556 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2558 ValueRefListEntry E; E.Attrs = $5; E.Val = getVal($3->get(), $4);
2562 | /*empty*/ { $$ = new ValueRefList(); };
2564 IndexList // Used for gep instructions and constant expressions
2565 : /*empty*/ { $$ = new std::vector<Value*>(); }
2566 | IndexList ',' ResolvedVal {
2573 OptTailCall : TAIL CALL {
2582 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2583 if (!UpRefs.empty())
2584 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2585 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
2586 !isa<PackedType>((*$2).get()))
2588 "Arithmetic operator requires integer, FP, or packed operands");
2589 if (isa<PackedType>((*$2).get()) &&
2590 ($1 == Instruction::URem ||
2591 $1 == Instruction::SRem ||
2592 $1 == Instruction::FRem))
2593 GEN_ERROR("Remainder not supported on packed types");
2594 Value* val1 = getVal(*$2, $3);
2596 Value* val2 = getVal(*$2, $5);
2598 $$ = BinaryOperator::create($1, val1, val2);
2600 GEN_ERROR("binary operator returned null");
2603 | LogicalOps Types ValueRef ',' ValueRef {
2604 if (!UpRefs.empty())
2605 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2606 if (!(*$2)->isInteger()) {
2607 if (Instruction::isShift($1) || !isa<PackedType>($2->get()) ||
2608 !cast<PackedType>($2->get())->getElementType()->isInteger())
2609 GEN_ERROR("Logical operator requires integral operands");
2611 Value* tmpVal1 = getVal(*$2, $3);
2613 Value* tmpVal2 = getVal(*$2, $5);
2615 $$ = BinaryOperator::create($1, tmpVal1, tmpVal2);
2617 GEN_ERROR("binary operator returned null");
2620 | ICMP IPredicates Types ValueRef ',' ValueRef {
2621 if (!UpRefs.empty())
2622 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2623 if (isa<PackedType>((*$3).get()))
2624 GEN_ERROR("Packed types not supported by icmp instruction");
2625 Value* tmpVal1 = getVal(*$3, $4);
2627 Value* tmpVal2 = getVal(*$3, $6);
2629 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2631 GEN_ERROR("icmp operator returned null");
2633 | FCMP FPredicates Types ValueRef ',' ValueRef {
2634 if (!UpRefs.empty())
2635 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2636 if (isa<PackedType>((*$3).get()))
2637 GEN_ERROR("Packed types not supported by fcmp instruction");
2638 Value* tmpVal1 = getVal(*$3, $4);
2640 Value* tmpVal2 = getVal(*$3, $6);
2642 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2644 GEN_ERROR("fcmp operator returned null");
2646 | CastOps ResolvedVal TO Types {
2647 if (!UpRefs.empty())
2648 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2650 const Type* DestTy = $4->get();
2651 if (!CastInst::castIsValid($1, Val, DestTy))
2652 GEN_ERROR("invalid cast opcode for cast from '" +
2653 Val->getType()->getDescription() + "' to '" +
2654 DestTy->getDescription() + "'");
2655 $$ = CastInst::create($1, Val, DestTy);
2658 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2659 if ($2->getType() != Type::Int1Ty)
2660 GEN_ERROR("select condition must be boolean");
2661 if ($4->getType() != $6->getType())
2662 GEN_ERROR("select value types should match");
2663 $$ = new SelectInst($2, $4, $6);
2666 | VAARG ResolvedVal ',' Types {
2667 if (!UpRefs.empty())
2668 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2669 $$ = new VAArgInst($2, *$4);
2673 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2674 if (!ExtractElementInst::isValidOperands($2, $4))
2675 GEN_ERROR("Invalid extractelement operands");
2676 $$ = new ExtractElementInst($2, $4);
2679 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2680 if (!InsertElementInst::isValidOperands($2, $4, $6))
2681 GEN_ERROR("Invalid insertelement operands");
2682 $$ = new InsertElementInst($2, $4, $6);
2685 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2686 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
2687 GEN_ERROR("Invalid shufflevector operands");
2688 $$ = new ShuffleVectorInst($2, $4, $6);
2692 const Type *Ty = $2->front().first->getType();
2693 if (!Ty->isFirstClassType())
2694 GEN_ERROR("PHI node operands must be of first class type");
2695 $$ = new PHINode(Ty);
2696 ((PHINode*)$$)->reserveOperandSpace($2->size());
2697 while ($2->begin() != $2->end()) {
2698 if ($2->front().first->getType() != Ty)
2699 GEN_ERROR("All elements of a PHI node must be of the same type");
2700 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2703 delete $2; // Free the list...
2706 | OptTailCall OptCallingConv ResultTypes ValueRef '(' ValueRefList ')'
2709 // Handle the short syntax
2710 const PointerType *PFTy = 0;
2711 const FunctionType *Ty = 0;
2712 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2713 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2714 // Pull out the types of all of the arguments...
2715 std::vector<const Type*> ParamTypes;
2716 FunctionType::ParamAttrsList ParamAttrs;
2717 ParamAttrs.push_back($8);
2718 for (ValueRefList::iterator I = $6->begin(), E = $6->end(); I != E; ++I) {
2719 const Type *Ty = I->Val->getType();
2720 if (Ty == Type::VoidTy)
2721 GEN_ERROR("Short call syntax cannot be used with varargs");
2722 ParamTypes.push_back(Ty);
2723 ParamAttrs.push_back(I->Attrs);
2726 Ty = FunctionType::get($3->get(), ParamTypes, false, ParamAttrs);
2727 PFTy = PointerType::get(Ty);
2730 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2733 // Check the arguments
2735 if ($6->empty()) { // Has no arguments?
2736 // Make sure no arguments is a good thing!
2737 if (Ty->getNumParams() != 0)
2738 GEN_ERROR("No arguments passed to a function that "
2739 "expects arguments");
2740 } else { // Has arguments?
2741 // Loop through FunctionType's arguments and ensure they are specified
2744 FunctionType::param_iterator I = Ty->param_begin();
2745 FunctionType::param_iterator E = Ty->param_end();
2746 ValueRefList::iterator ArgI = $6->begin(), ArgE = $6->end();
2748 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2749 if (ArgI->Val->getType() != *I)
2750 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2751 (*I)->getDescription() + "'");
2752 Args.push_back(ArgI->Val);
2754 if (Ty->isVarArg()) {
2756 for (; ArgI != ArgE; ++ArgI)
2757 Args.push_back(ArgI->Val); // push the remaining varargs
2758 } else if (I != E || ArgI != ArgE)
2759 GEN_ERROR("Invalid number of parameters detected");
2761 // Create the call node
2762 CallInst *CI = new CallInst(V, Args);
2763 CI->setTailCall($1);
2764 CI->setCallingConv($2);
2775 OptVolatile : VOLATILE {
2786 MemoryInst : MALLOC Types OptCAlign {
2787 if (!UpRefs.empty())
2788 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2789 $$ = new MallocInst(*$2, 0, $3);
2793 | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
2794 if (!UpRefs.empty())
2795 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2796 Value* tmpVal = getVal($4, $5);
2798 $$ = new MallocInst(*$2, tmpVal, $6);
2801 | ALLOCA Types OptCAlign {
2802 if (!UpRefs.empty())
2803 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2804 $$ = new AllocaInst(*$2, 0, $3);
2808 | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
2809 if (!UpRefs.empty())
2810 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2811 Value* tmpVal = getVal($4, $5);
2813 $$ = new AllocaInst(*$2, tmpVal, $6);
2816 | FREE ResolvedVal {
2817 if (!isa<PointerType>($2->getType()))
2818 GEN_ERROR("Trying to free nonpointer type " +
2819 $2->getType()->getDescription() + "");
2820 $$ = new FreeInst($2);
2824 | OptVolatile LOAD Types ValueRef {
2825 if (!UpRefs.empty())
2826 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2827 if (!isa<PointerType>($3->get()))
2828 GEN_ERROR("Can't load from nonpointer type: " +
2829 (*$3)->getDescription());
2830 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
2831 GEN_ERROR("Can't load from pointer of non-first-class type: " +
2832 (*$3)->getDescription());
2833 Value* tmpVal = getVal(*$3, $4);
2835 $$ = new LoadInst(tmpVal, "", $1);
2838 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2839 if (!UpRefs.empty())
2840 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
2841 const PointerType *PT = dyn_cast<PointerType>($5->get());
2843 GEN_ERROR("Can't store to a nonpointer type: " +
2844 (*$5)->getDescription());
2845 const Type *ElTy = PT->getElementType();
2846 if (ElTy != $3->getType())
2847 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
2848 "' into space of type '" + ElTy->getDescription() + "'");
2850 Value* tmpVal = getVal(*$5, $6);
2852 $$ = new StoreInst($3, tmpVal, $1);
2855 | GETELEMENTPTR Types ValueRef IndexList {
2856 if (!UpRefs.empty())
2857 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2858 if (!isa<PointerType>($2->get()))
2859 GEN_ERROR("getelementptr insn requires pointer operand");
2861 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2862 GEN_ERROR("Invalid getelementptr indices for type '" +
2863 (*$2)->getDescription()+ "'");
2864 Value* tmpVal = getVal(*$2, $3);
2866 $$ = new GetElementPtrInst(tmpVal, *$4);
2874 // common code from the two 'RunVMAsmParser' functions
2875 static Module* RunParser(Module * M) {
2877 llvmAsmlineno = 1; // Reset the current line number...
2878 CurModule.CurrentModule = M;
2883 // Check to make sure the parser succeeded
2886 delete ParserResult;
2890 // Check to make sure that parsing produced a result
2894 // Reset ParserResult variable while saving its value for the result.
2895 Module *Result = ParserResult;
2901 void llvm::GenerateError(const std::string &message, int LineNo) {
2902 if (LineNo == -1) LineNo = llvmAsmlineno;
2903 // TODO: column number in exception
2905 TheParseError->setError(CurFilename, message, LineNo);
2909 int yyerror(const char *ErrorMsg) {
2911 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2912 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2913 std::string errMsg = where + "error: " + std::string(ErrorMsg);
2914 if (yychar != YYEMPTY && yychar != 0)
2915 errMsg += " while reading token: '" + std::string(llvmAsmtext, llvmAsmleng)+
2917 GenerateError(errMsg);