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.
213 GlobalValue::VisibilityTypes Visibility;
215 /// BBForwardRefs - When we see forward references to basic blocks, keep
216 /// track of them here.
217 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
218 std::vector<BasicBlock*> NumberedBlocks;
221 inline PerFunctionInfo() {
224 Linkage = GlobalValue::ExternalLinkage;
225 Visibility = GlobalValue::DefaultVisibility;
228 inline void FunctionStart(Function *M) {
233 void FunctionDone() {
234 NumberedBlocks.clear();
236 // Any forward referenced blocks left?
237 if (!BBForwardRefs.empty()) {
238 GenerateError("Undefined reference to label " +
239 BBForwardRefs.begin()->first->getName());
243 // Resolve all forward references now.
244 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
246 Values.clear(); // Clear out function local definitions
249 Linkage = GlobalValue::ExternalLinkage;
250 Visibility = GlobalValue::DefaultVisibility;
252 } CurFun; // Info for the current function...
254 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
257 //===----------------------------------------------------------------------===//
258 // Code to handle definitions of all the types
259 //===----------------------------------------------------------------------===//
261 static int InsertValue(Value *V,
262 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
263 if (V->hasName()) return -1; // Is this a numbered definition?
265 // Yes, insert the value into the value table...
266 ValueList &List = ValueTab[V->getType()];
268 return List.size()-1;
271 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
273 case ValID::LocalID: // Is it a numbered definition?
274 // Module constants occupy the lowest numbered slots...
275 if (D.Num < CurModule.Types.size())
276 return CurModule.Types[D.Num];
278 case ValID::LocalName: // Is it a named definition?
279 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
280 D.destroy(); // Free old strdup'd memory...
285 GenerateError("Internal parser error: Invalid symbol type reference!");
289 // If we reached here, we referenced either a symbol that we don't know about
290 // or an id number that hasn't been read yet. We may be referencing something
291 // forward, so just create an entry to be resolved later and get to it...
293 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
296 if (inFunctionScope()) {
297 if (D.Type == ValID::LocalName) {
298 GenerateError("Reference to an undefined type: '" + D.getName() + "'");
301 GenerateError("Reference to an undefined type: #" + utostr(D.Num));
306 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
307 if (I != CurModule.LateResolveTypes.end())
310 Type *Typ = OpaqueType::get();
311 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
315 // getValNonImprovising - Look up the value specified by the provided type and
316 // the provided ValID. If the value exists and has already been defined, return
317 // it. Otherwise return null.
319 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
320 if (isa<FunctionType>(Ty)) {
321 GenerateError("Functions are not values and "
322 "must be referenced as pointers");
327 case ValID::LocalID: { // Is it a numbered definition?
328 // Module constants occupy the lowest numbered slots.
329 std::map<const Type*,ValueList>::iterator VI = CurFun.Values.find(Ty);
330 // Make sure that our type is within bounds.
331 if (VI == CurFun.Values.end()) return 0;
333 // Check that the number is within bounds.
334 if (D.Num >= VI->second.size()) return 0;
336 return VI->second[D.Num];
338 case ValID::GlobalID: { // Is it a numbered definition?
339 unsigned Num = D.Num;
341 // Module constants occupy the lowest numbered slots...
342 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
343 if (VI == CurModule.Values.end()) return 0;
344 if (D.Num >= VI->second.size()) return 0;
345 return VI->second[Num];
348 case ValID::LocalName: { // Is it a named definition?
349 if (!inFunctionScope()) return 0;
350 SymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
351 Value *N = SymTab.lookup(Ty, D.Name);
352 if (N == 0) return 0;
354 D.destroy(); // Free old strdup'd memory...
357 case ValID::GlobalName: { // Is it a named definition?
358 SymbolTable &SymTab = CurModule.CurrentModule->getValueSymbolTable();
359 Value *N = SymTab.lookup(Ty, D.Name);
360 if (N == 0) return 0;
362 D.destroy(); // Free old strdup'd memory...
366 // Check to make sure that "Ty" is an integral type, and that our
367 // value will fit into the specified type...
368 case ValID::ConstSIntVal: // Is it a constant pool reference??
369 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
370 GenerateError("Signed integral constant '" +
371 itostr(D.ConstPool64) + "' is invalid for type '" +
372 Ty->getDescription() + "'!");
375 return ConstantInt::get(Ty, D.ConstPool64);
377 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
378 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
379 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
380 GenerateError("Integral constant '" + utostr(D.UConstPool64) +
381 "' is invalid or out of range!");
383 } else { // This is really a signed reference. Transmogrify.
384 return ConstantInt::get(Ty, D.ConstPool64);
387 return ConstantInt::get(Ty, D.UConstPool64);
390 case ValID::ConstFPVal: // Is it a floating point const pool reference?
391 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP)) {
392 GenerateError("FP constant invalid for type!!");
395 return ConstantFP::get(Ty, D.ConstPoolFP);
397 case ValID::ConstNullVal: // Is it a null value?
398 if (!isa<PointerType>(Ty)) {
399 GenerateError("Cannot create a a non pointer null!");
402 return ConstantPointerNull::get(cast<PointerType>(Ty));
404 case ValID::ConstUndefVal: // Is it an undef value?
405 return UndefValue::get(Ty);
407 case ValID::ConstZeroVal: // Is it a zero value?
408 return Constant::getNullValue(Ty);
410 case ValID::ConstantVal: // Fully resolved constant?
411 if (D.ConstantValue->getType() != Ty) {
412 GenerateError("Constant expression type different from required type!");
415 return D.ConstantValue;
417 case ValID::InlineAsmVal: { // Inline asm expression
418 const PointerType *PTy = dyn_cast<PointerType>(Ty);
419 const FunctionType *FTy =
420 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
421 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
422 GenerateError("Invalid type for asm constraint string!");
425 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
426 D.IAD->HasSideEffects);
427 D.destroy(); // Free InlineAsmDescriptor.
431 assert(0 && "Unhandled case!");
435 assert(0 && "Unhandled case!");
439 // getVal - This function is identical to getValNonImprovising, except that if a
440 // value is not already defined, it "improvises" by creating a placeholder var
441 // that looks and acts just like the requested variable. When the value is
442 // defined later, all uses of the placeholder variable are replaced with the
445 static Value *getVal(const Type *Ty, const ValID &ID) {
446 if (Ty == Type::LabelTy) {
447 GenerateError("Cannot use a basic block here");
451 // See if the value has already been defined.
452 Value *V = getValNonImprovising(Ty, ID);
454 if (TriggerError) return 0;
456 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
457 GenerateError("Invalid use of a composite type!");
461 // If we reached here, we referenced either a symbol that we don't know about
462 // or an id number that hasn't been read yet. We may be referencing something
463 // forward, so just create an entry to be resolved later and get to it...
465 V = new Argument(Ty);
467 // Remember where this forward reference came from. FIXME, shouldn't we try
468 // to recycle these things??
469 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
472 if (inFunctionScope())
473 InsertValue(V, CurFun.LateResolveValues);
475 InsertValue(V, CurModule.LateResolveValues);
479 /// getBBVal - This is used for two purposes:
480 /// * If isDefinition is true, a new basic block with the specified ID is being
482 /// * If isDefinition is true, this is a reference to a basic block, which may
483 /// or may not be a forward reference.
485 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
486 assert(inFunctionScope() && "Can't get basic block at global scope!");
492 GenerateError("Illegal label reference " + ID.getName());
494 case ValID::LocalID: // Is it a numbered definition?
495 if (ID.Num >= CurFun.NumberedBlocks.size())
496 CurFun.NumberedBlocks.resize(ID.Num+1);
497 BB = CurFun.NumberedBlocks[ID.Num];
499 case ValID::LocalName: // Is it a named definition?
501 if (Value *N = CurFun.CurrentFunction->
502 getValueSymbolTable().lookup(Type::LabelTy, Name))
503 BB = cast<BasicBlock>(N);
507 // See if the block has already been defined.
509 // If this is the definition of the block, make sure the existing value was
510 // just a forward reference. If it was a forward reference, there will be
511 // an entry for it in the PlaceHolderInfo map.
512 if (isDefinition && !CurFun.BBForwardRefs.erase(BB)) {
513 // The existing value was a definition, not a forward reference.
514 GenerateError("Redefinition of label " + ID.getName());
518 ID.destroy(); // Free strdup'd memory.
522 // Otherwise this block has not been seen before.
523 BB = new BasicBlock("", CurFun.CurrentFunction);
524 if (ID.Type == ValID::LocalName) {
525 BB->setName(ID.Name);
527 CurFun.NumberedBlocks[ID.Num] = BB;
530 // If this is not a definition, keep track of it so we can use it as a forward
533 // Remember where this forward reference came from.
534 CurFun.BBForwardRefs[BB] = std::make_pair(ID, llvmAsmlineno);
536 // The forward declaration could have been inserted anywhere in the
537 // function: insert it into the correct place now.
538 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
539 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
546 //===----------------------------------------------------------------------===//
547 // Code to handle forward references in instructions
548 //===----------------------------------------------------------------------===//
550 // This code handles the late binding needed with statements that reference
551 // values not defined yet... for example, a forward branch, or the PHI node for
554 // This keeps a table (CurFun.LateResolveValues) of all such forward references
555 // and back patchs after we are done.
558 // ResolveDefinitions - If we could not resolve some defs at parsing
559 // time (forward branches, phi functions for loops, etc...) resolve the
563 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
564 std::map<const Type*,ValueList> *FutureLateResolvers) {
565 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
566 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
567 E = LateResolvers.end(); LRI != E; ++LRI) {
568 ValueList &List = LRI->second;
569 while (!List.empty()) {
570 Value *V = List.back();
573 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
574 CurModule.PlaceHolderInfo.find(V);
575 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
577 ValID &DID = PHI->second.first;
579 Value *TheRealValue = getValNonImprovising(LRI->first, DID);
583 V->replaceAllUsesWith(TheRealValue);
585 CurModule.PlaceHolderInfo.erase(PHI);
586 } else if (FutureLateResolvers) {
587 // Functions have their unresolved items forwarded to the module late
589 InsertValue(V, *FutureLateResolvers);
591 if (DID.Type == ValID::LocalName || DID.Type == ValID::GlobalName) {
592 GenerateError("Reference to an invalid definition: '" +DID.getName()+
593 "' of type '" + V->getType()->getDescription() + "'",
597 GenerateError("Reference to an invalid definition: #" +
598 itostr(DID.Num) + " of type '" +
599 V->getType()->getDescription() + "'",
607 LateResolvers.clear();
610 // ResolveTypeTo - A brand new type was just declared. This means that (if
611 // name is not null) things referencing Name can be resolved. Otherwise, things
612 // refering to the number can be resolved. Do this now.
614 static void ResolveTypeTo(char *Name, const Type *ToTy) {
616 if (Name) D = ValID::createLocalName(Name);
617 else D = ValID::createLocalID(CurModule.Types.size());
619 std::map<ValID, PATypeHolder>::iterator I =
620 CurModule.LateResolveTypes.find(D);
621 if (I != CurModule.LateResolveTypes.end()) {
622 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
623 CurModule.LateResolveTypes.erase(I);
627 // setValueName - Set the specified value to the name given. The name may be
628 // null potentially, in which case this is a noop. The string passed in is
629 // assumed to be a malloc'd string buffer, and is free'd by this function.
631 static void setValueName(Value *V, char *NameStr) {
632 if (!NameStr) return;
633 std::string Name(NameStr); // Copy string
634 free(NameStr); // Free old string
636 if (V->getType() == Type::VoidTy) {
637 GenerateError("Can't assign name '" + Name+"' to value with void type!");
641 assert(inFunctionScope() && "Must be in function scope!");
642 SymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
643 if (ST.lookup(V->getType(), Name)) {
644 GenerateError("Redefinition of value '" + Name + "' of type '" +
645 V->getType()->getDescription() + "'!");
653 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
654 /// this is a declaration, otherwise it is a definition.
655 static GlobalVariable *
656 ParseGlobalVariable(char *NameStr,
657 GlobalValue::LinkageTypes Linkage,
658 GlobalValue::VisibilityTypes Visibility,
659 bool isConstantGlobal, const Type *Ty,
660 Constant *Initializer) {
661 if (isa<FunctionType>(Ty)) {
662 GenerateError("Cannot declare global vars of function type!");
666 const PointerType *PTy = PointerType::get(Ty);
670 Name = NameStr; // Copy string
671 free(NameStr); // Free old string
674 // See if this global value was forward referenced. If so, recycle the
678 ID = ValID::createGlobalName((char*)Name.c_str());
680 ID = ValID::createGlobalID(CurModule.Values[PTy].size());
683 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
684 // Move the global to the end of the list, from whereever it was
685 // previously inserted.
686 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
687 CurModule.CurrentModule->getGlobalList().remove(GV);
688 CurModule.CurrentModule->getGlobalList().push_back(GV);
689 GV->setInitializer(Initializer);
690 GV->setLinkage(Linkage);
691 GV->setVisibility(Visibility);
692 GV->setConstant(isConstantGlobal);
693 InsertValue(GV, CurModule.Values);
697 // If this global has a name, check to see if there is already a definition
698 // of this global in the module. If so, it is an error.
700 // We are a simple redefinition of a value, check to see if it is defined
701 // the same as the old one.
702 if (CurModule.CurrentModule->getGlobalVariable(Name, Ty)) {
703 GenerateError("Redefinition of global variable named '" + Name +
704 "' of type '" + Ty->getDescription() + "'!");
709 // Otherwise there is no existing GV to use, create one now.
711 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
712 CurModule.CurrentModule);
713 GV->setVisibility(Visibility);
714 InsertValue(GV, CurModule.Values);
718 // setTypeName - Set the specified type to the name given. The name may be
719 // null potentially, in which case this is a noop. The string passed in is
720 // assumed to be a malloc'd string buffer, and is freed by this function.
722 // This function returns true if the type has already been defined, but is
723 // allowed to be redefined in the specified context. If the name is a new name
724 // for the type plane, it is inserted and false is returned.
725 static bool setTypeName(const Type *T, char *NameStr) {
726 assert(!inFunctionScope() && "Can't give types function-local names!");
727 if (NameStr == 0) return false;
729 std::string Name(NameStr); // Copy string
730 free(NameStr); // Free old string
732 // We don't allow assigning names to void type
733 if (T == Type::VoidTy) {
734 GenerateError("Can't assign name '" + Name + "' to the void type!");
738 // Set the type name, checking for conflicts as we do so.
739 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
741 if (AlreadyExists) { // Inserting a name that is already defined???
742 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
743 assert(Existing && "Conflict but no matching type?");
745 // There is only one case where this is allowed: when we are refining an
746 // opaque type. In this case, Existing will be an opaque type.
747 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
748 // We ARE replacing an opaque type!
749 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
753 // Otherwise, this is an attempt to redefine a type. That's okay if
754 // the redefinition is identical to the original. This will be so if
755 // Existing and T point to the same Type object. In this one case we
756 // allow the equivalent redefinition.
757 if (Existing == T) return true; // Yes, it's equal.
759 // Any other kind of (non-equivalent) redefinition is an error.
760 GenerateError("Redefinition of type named '" + Name + "' of type '" +
761 T->getDescription() + "'!");
767 //===----------------------------------------------------------------------===//
768 // Code for handling upreferences in type names...
771 // TypeContains - Returns true if Ty directly contains E in it.
773 static bool TypeContains(const Type *Ty, const Type *E) {
774 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
775 E) != Ty->subtype_end();
780 // NestingLevel - The number of nesting levels that need to be popped before
781 // this type is resolved.
782 unsigned NestingLevel;
784 // LastContainedTy - This is the type at the current binding level for the
785 // type. Every time we reduce the nesting level, this gets updated.
786 const Type *LastContainedTy;
788 // UpRefTy - This is the actual opaque type that the upreference is
792 UpRefRecord(unsigned NL, OpaqueType *URTy)
793 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
797 // UpRefs - A list of the outstanding upreferences that need to be resolved.
798 static std::vector<UpRefRecord> UpRefs;
800 /// HandleUpRefs - Every time we finish a new layer of types, this function is
801 /// called. It loops through the UpRefs vector, which is a list of the
802 /// currently active types. For each type, if the up reference is contained in
803 /// the newly completed type, we decrement the level count. When the level
804 /// count reaches zero, the upreferenced type is the type that is passed in:
805 /// thus we can complete the cycle.
807 static PATypeHolder HandleUpRefs(const Type *ty) {
808 // If Ty isn't abstract, or if there are no up-references in it, then there is
809 // nothing to resolve here.
810 if (!ty->isAbstract() || UpRefs.empty()) return ty;
813 UR_OUT("Type '" << Ty->getDescription() <<
814 "' newly formed. Resolving upreferences.\n" <<
815 UpRefs.size() << " upreferences active!\n");
817 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
818 // to zero), we resolve them all together before we resolve them to Ty. At
819 // the end of the loop, if there is anything to resolve to Ty, it will be in
821 OpaqueType *TypeToResolve = 0;
823 for (unsigned i = 0; i != UpRefs.size(); ++i) {
824 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
825 << UpRefs[i].second->getDescription() << ") = "
826 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
827 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
828 // Decrement level of upreference
829 unsigned Level = --UpRefs[i].NestingLevel;
830 UpRefs[i].LastContainedTy = Ty;
831 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
832 if (Level == 0) { // Upreference should be resolved!
833 if (!TypeToResolve) {
834 TypeToResolve = UpRefs[i].UpRefTy;
836 UR_OUT(" * Resolving upreference for "
837 << UpRefs[i].second->getDescription() << "\n";
838 std::string OldName = UpRefs[i].UpRefTy->getDescription());
839 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
840 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
841 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
843 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
844 --i; // Do not skip the next element...
850 UR_OUT(" * Resolving upreference for "
851 << UpRefs[i].second->getDescription() << "\n";
852 std::string OldName = TypeToResolve->getDescription());
853 TypeToResolve->refineAbstractTypeTo(Ty);
859 //===----------------------------------------------------------------------===//
860 // RunVMAsmParser - Define an interface to this parser
861 //===----------------------------------------------------------------------===//
863 static Module* RunParser(Module * M);
865 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
868 CurFilename = Filename;
869 return RunParser(new Module(CurFilename));
872 Module *llvm::RunVMAsmParser(const char * AsmString, Module * M) {
873 set_scan_string(AsmString);
875 CurFilename = "from_memory";
877 return RunParser(new Module (CurFilename));
886 llvm::Module *ModuleVal;
887 llvm::Function *FunctionVal;
888 llvm::BasicBlock *BasicBlockVal;
889 llvm::TerminatorInst *TermInstVal;
890 llvm::Instruction *InstVal;
891 llvm::Constant *ConstVal;
893 const llvm::Type *PrimType;
894 std::list<llvm::PATypeHolder> *TypeList;
895 llvm::PATypeHolder *TypeVal;
896 llvm::Value *ValueVal;
897 std::vector<llvm::Value*> *ValueList;
898 llvm::ArgListType *ArgList;
899 llvm::TypeWithAttrs TypeWithAttrs;
900 llvm::TypeWithAttrsList *TypeWithAttrsList;
901 llvm::ValueRefList *ValueRefList;
903 // Represent the RHS of PHI node
904 std::list<std::pair<llvm::Value*,
905 llvm::BasicBlock*> > *PHIList;
906 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
907 std::vector<llvm::Constant*> *ConstVector;
909 llvm::GlobalValue::LinkageTypes Linkage;
910 llvm::GlobalValue::VisibilityTypes Visibility;
911 llvm::FunctionType::ParameterAttributes ParamAttrs;
919 char *StrVal; // This memory is strdup'd!
920 llvm::ValID ValIDVal; // strdup'd memory maybe!
922 llvm::Instruction::BinaryOps BinaryOpVal;
923 llvm::Instruction::TermOps TermOpVal;
924 llvm::Instruction::MemoryOps MemOpVal;
925 llvm::Instruction::CastOps CastOpVal;
926 llvm::Instruction::OtherOps OtherOpVal;
927 llvm::ICmpInst::Predicate IPredicate;
928 llvm::FCmpInst::Predicate FPredicate;
931 %type <ModuleVal> Module
932 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
933 %type <BasicBlockVal> BasicBlock InstructionList
934 %type <TermInstVal> BBTerminatorInst
935 %type <InstVal> Inst InstVal MemoryInst
936 %type <ConstVal> ConstVal ConstExpr
937 %type <ConstVector> ConstVector
938 %type <ArgList> ArgList ArgListH
939 %type <PHIList> PHIList
940 %type <ValueRefList> ValueRefList // For call param lists & GEP indices
941 %type <ValueList> IndexList // For GEP indices
942 %type <TypeList> TypeListI
943 %type <TypeWithAttrsList> ArgTypeList ArgTypeListI
944 %type <TypeWithAttrs> ArgType
945 %type <JumpTable> JumpTable
946 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
947 %type <BoolVal> OptVolatile // 'volatile' or not
948 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
949 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
950 %type <Linkage> GVInternalLinkage GVExternalLinkage
951 %type <Linkage> FunctionDefineLinkage FunctionDeclareLinkage
952 %type <Visibility> GVVisibilityStyle
954 // ValueRef - Unresolved reference to a definition or BB
955 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
956 %type <ValueVal> ResolvedVal // <type> <valref> pair
957 // Tokens and types for handling constant integer values
959 // ESINT64VAL - A negative number within long long range
960 %token <SInt64Val> ESINT64VAL
962 // EUINT64VAL - A positive number within uns. long long range
963 %token <UInt64Val> EUINT64VAL
965 %token <UIntVal> LOCALVAL_ID GLOBALVAL_ID // %123 @123
966 %token <FPVal> FPVAL // Float or Double constant
969 %type <TypeVal> Types ResultTypes
970 %type <PrimType> IntType FPType PrimType // Classifications
971 %token <PrimType> VOID INTTYPE
972 %token <PrimType> FLOAT DOUBLE LABEL
975 %token<StrVal> LOCALVAR GLOBALVAR LABELSTR STRINGCONSTANT ATSTRINGCONSTANT
976 %type <StrVal> LocalName OptLocalName OptLocalAssign
977 %type <StrVal> GlobalName OptGlobalAssign
978 %type <UIntVal> OptAlign OptCAlign
979 %type <StrVal> OptSection SectionString
981 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
982 %token DECLARE DEFINE GLOBAL CONSTANT SECTION VOLATILE
983 %token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
984 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
985 %token OPAQUE EXTERNAL TARGET TRIPLE ALIGN
986 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
987 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
989 %type <UIntVal> OptCallingConv
990 %type <ParamAttrs> OptParamAttrs ParamAttr
991 %type <ParamAttrs> OptFuncAttrs FuncAttr
993 // Basic Block Terminating Operators
994 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
997 %type <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
998 %token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
999 %token <OtherOpVal> ICMP FCMP
1000 %type <IPredicate> IPredicates
1001 %type <FPredicate> FPredicates
1002 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1003 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1005 // Memory Instructions
1006 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1009 %type <CastOpVal> CastOps
1010 %token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1011 %token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1014 %type <OtherOpVal> ShiftOps
1015 %token <OtherOpVal> PHI_TOK SELECT SHL LSHR ASHR VAARG
1016 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1018 // Function Attributes
1019 %token NORETURN INREG SRET
1021 // Visibility Styles
1022 %token DEFAULT HIDDEN
1028 // Operations that are notably excluded from this list include:
1029 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1031 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1032 LogicalOps : AND | OR | XOR;
1033 CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1034 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1035 ShiftOps : SHL | LSHR | ASHR;
1037 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1038 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1039 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1040 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1041 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1045 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1046 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1047 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1048 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1049 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1050 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1051 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1052 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1053 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1056 // These are some types that allow classification if we only want a particular
1057 // thing... for example, only a signed, unsigned, or integral type.
1059 FPType : FLOAT | DOUBLE;
1061 LocalName : LOCALVAR | STRINGCONSTANT;
1062 OptLocalName : LocalName | /*empty*/ { $$ = 0; };
1064 /// OptLocalAssign - Value producing statements have an optional assignment
1066 OptLocalAssign : LocalName '=' {
1075 GlobalName : GLOBALVAR | ATSTRINGCONSTANT;
1077 OptGlobalAssign : GlobalName '=' {
1087 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1088 | WEAK { $$ = GlobalValue::WeakLinkage; }
1089 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1090 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1091 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1095 : DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1096 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1097 | EXTERNAL { $$ = GlobalValue::ExternalLinkage; }
1101 : /*empty*/ { $$ = GlobalValue::DefaultVisibility; }
1102 | HIDDEN { $$ = GlobalValue::HiddenVisibility; }
1105 FunctionDeclareLinkage
1106 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1107 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1108 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1111 FunctionDefineLinkage
1112 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1113 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1114 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1115 | WEAK { $$ = GlobalValue::WeakLinkage; }
1116 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1119 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1120 CCC_TOK { $$ = CallingConv::C; } |
1121 FASTCC_TOK { $$ = CallingConv::Fast; } |
1122 COLDCC_TOK { $$ = CallingConv::Cold; } |
1123 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1124 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1126 if ((unsigned)$2 != $2)
1127 GEN_ERROR("Calling conv too large!");
1132 ParamAttr : ZEXT { $$ = FunctionType::ZExtAttribute; }
1133 | SEXT { $$ = FunctionType::SExtAttribute; }
1134 | INREG { $$ = FunctionType::InRegAttribute; }
1135 | SRET { $$ = FunctionType::StructRetAttribute; }
1138 OptParamAttrs : /* empty */ { $$ = FunctionType::NoAttributeSet; }
1139 | OptParamAttrs ParamAttr {
1140 $$ = FunctionType::ParameterAttributes($1 | $2);
1144 FuncAttr : NORETURN { $$ = FunctionType::NoReturnAttribute; }
1148 OptFuncAttrs : /* empty */ { $$ = FunctionType::NoAttributeSet; }
1149 | OptFuncAttrs FuncAttr {
1150 $$ = FunctionType::ParameterAttributes($1 | $2);
1154 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1155 // a comma before it.
1156 OptAlign : /*empty*/ { $$ = 0; } |
1159 if ($$ != 0 && !isPowerOf2_32($$))
1160 GEN_ERROR("Alignment must be a power of two!");
1163 OptCAlign : /*empty*/ { $$ = 0; } |
1164 ',' ALIGN EUINT64VAL {
1166 if ($$ != 0 && !isPowerOf2_32($$))
1167 GEN_ERROR("Alignment must be a power of two!");
1172 SectionString : SECTION STRINGCONSTANT {
1173 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1174 if ($2[i] == '"' || $2[i] == '\\')
1175 GEN_ERROR("Invalid character in section name!");
1180 OptSection : /*empty*/ { $$ = 0; } |
1181 SectionString { $$ = $1; };
1183 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1184 // is set to be the global we are processing.
1186 GlobalVarAttributes : /* empty */ {} |
1187 ',' GlobalVarAttribute GlobalVarAttributes {};
1188 GlobalVarAttribute : SectionString {
1189 CurGV->setSection($1);
1193 | ALIGN EUINT64VAL {
1194 if ($2 != 0 && !isPowerOf2_32($2))
1195 GEN_ERROR("Alignment must be a power of two!");
1196 CurGV->setAlignment($2);
1200 //===----------------------------------------------------------------------===//
1201 // Types includes all predefined types... except void, because it can only be
1202 // used in specific contexts (function returning void for example).
1204 // Derived types are added later...
1206 PrimType : INTTYPE | FLOAT | DOUBLE | LABEL ;
1210 $$ = new PATypeHolder(OpaqueType::get());
1214 $$ = new PATypeHolder($1);
1217 | Types '*' { // Pointer type?
1218 if (*$1 == Type::LabelTy)
1219 GEN_ERROR("Cannot form a pointer to a basic block");
1220 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1224 | SymbolicValueRef { // Named types are also simple types...
1225 const Type* tmp = getTypeVal($1);
1227 $$ = new PATypeHolder(tmp);
1229 | '\\' EUINT64VAL { // Type UpReference
1230 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range!");
1231 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1232 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1233 $$ = new PATypeHolder(OT);
1234 UR_OUT("New Upreference!\n");
1237 | Types '(' ArgTypeListI ')' OptFuncAttrs {
1238 std::vector<const Type*> Params;
1239 std::vector<FunctionType::ParameterAttributes> Attrs;
1240 Attrs.push_back($5);
1241 for (TypeWithAttrsList::iterator I=$3->begin(), E=$3->end(); I != E; ++I) {
1242 Params.push_back(I->Ty->get());
1243 if (I->Ty->get() != Type::VoidTy)
1244 Attrs.push_back(I->Attrs);
1246 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1247 if (isVarArg) Params.pop_back();
1249 FunctionType *FT = FunctionType::get(*$1, Params, isVarArg, Attrs);
1250 delete $3; // Delete the argument list
1251 delete $1; // Delete the return type handle
1252 $$ = new PATypeHolder(HandleUpRefs(FT));
1255 | VOID '(' ArgTypeListI ')' OptFuncAttrs {
1256 std::vector<const Type*> Params;
1257 std::vector<FunctionType::ParameterAttributes> Attrs;
1258 Attrs.push_back($5);
1259 for (TypeWithAttrsList::iterator I=$3->begin(), E=$3->end(); I != E; ++I) {
1260 Params.push_back(I->Ty->get());
1261 if (I->Ty->get() != Type::VoidTy)
1262 Attrs.push_back(I->Attrs);
1264 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1265 if (isVarArg) Params.pop_back();
1267 FunctionType *FT = FunctionType::get($1, Params, isVarArg, Attrs);
1268 delete $3; // Delete the argument list
1269 $$ = new PATypeHolder(HandleUpRefs(FT));
1273 | '[' EUINT64VAL 'x' Types ']' { // Sized array type?
1274 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1278 | '<' EUINT64VAL 'x' Types '>' { // Packed array type?
1279 const llvm::Type* ElemTy = $4->get();
1280 if ((unsigned)$2 != $2)
1281 GEN_ERROR("Unsigned result not equal to signed result");
1282 if (!ElemTy->isFloatingPoint() && !ElemTy->isInteger())
1283 GEN_ERROR("Element type of a PackedType must be primitive");
1284 if (!isPowerOf2_32($2))
1285 GEN_ERROR("Vector length should be a power of 2!");
1286 $$ = new PATypeHolder(HandleUpRefs(PackedType::get(*$4, (unsigned)$2)));
1290 | '{' TypeListI '}' { // Structure type?
1291 std::vector<const Type*> Elements;
1292 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1293 E = $2->end(); I != E; ++I)
1294 Elements.push_back(*I);
1296 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1300 | '{' '}' { // Empty structure type?
1301 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1304 | '<' '{' TypeListI '}' '>' {
1305 std::vector<const Type*> Elements;
1306 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1307 E = $3->end(); I != E; ++I)
1308 Elements.push_back(*I);
1310 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1314 | '<' '{' '}' '>' { // Empty structure type?
1315 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1321 : Types OptParamAttrs {
1329 if (!UpRefs.empty())
1330 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1331 if (!(*$1)->isFirstClassType())
1332 GEN_ERROR("LLVM functions cannot return aggregate types!");
1336 $$ = new PATypeHolder(Type::VoidTy);
1340 ArgTypeList : ArgType {
1341 $$ = new TypeWithAttrsList();
1345 | ArgTypeList ',' ArgType {
1346 ($$=$1)->push_back($3);
1353 | ArgTypeList ',' DOTDOTDOT {
1355 TypeWithAttrs TWA; TWA.Attrs = FunctionType::NoAttributeSet;
1356 TWA.Ty = new PATypeHolder(Type::VoidTy);
1361 $$ = new TypeWithAttrsList;
1362 TypeWithAttrs TWA; TWA.Attrs = FunctionType::NoAttributeSet;
1363 TWA.Ty = new PATypeHolder(Type::VoidTy);
1368 $$ = new TypeWithAttrsList();
1372 // TypeList - Used for struct declarations and as a basis for function type
1373 // declaration type lists
1376 $$ = new std::list<PATypeHolder>();
1377 $$->push_back(*$1); delete $1;
1380 | TypeListI ',' Types {
1381 ($$=$1)->push_back(*$3); delete $3;
1385 // ConstVal - The various declarations that go into the constant pool. This
1386 // production is used ONLY to represent constants that show up AFTER a 'const',
1387 // 'constant' or 'global' token at global scope. Constants that can be inlined
1388 // into other expressions (such as integers and constexprs) are handled by the
1389 // ResolvedVal, ValueRef and ConstValueRef productions.
1391 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1392 if (!UpRefs.empty())
1393 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1394 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1396 GEN_ERROR("Cannot make array constant with type: '" +
1397 (*$1)->getDescription() + "'!");
1398 const Type *ETy = ATy->getElementType();
1399 int NumElements = ATy->getNumElements();
1401 // Verify that we have the correct size...
1402 if (NumElements != -1 && NumElements != (int)$3->size())
1403 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1404 utostr($3->size()) + " arguments, but has size of " +
1405 itostr(NumElements) + "!");
1407 // Verify all elements are correct type!
1408 for (unsigned i = 0; i < $3->size(); i++) {
1409 if (ETy != (*$3)[i]->getType())
1410 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1411 ETy->getDescription() +"' as required!\nIt is of type '"+
1412 (*$3)[i]->getType()->getDescription() + "'.");
1415 $$ = ConstantArray::get(ATy, *$3);
1416 delete $1; delete $3;
1420 if (!UpRefs.empty())
1421 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1422 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1424 GEN_ERROR("Cannot make array constant with type: '" +
1425 (*$1)->getDescription() + "'!");
1427 int NumElements = ATy->getNumElements();
1428 if (NumElements != -1 && NumElements != 0)
1429 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1430 " arguments, but has size of " + itostr(NumElements) +"!");
1431 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1435 | Types 'c' STRINGCONSTANT {
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 const Type *ETy = ATy->getElementType();
1445 char *EndStr = UnEscapeLexed($3, true);
1446 if (NumElements != -1 && NumElements != (EndStr-$3))
1447 GEN_ERROR("Can't build string constant of size " +
1448 itostr((int)(EndStr-$3)) +
1449 " when array has size " + itostr(NumElements) + "!");
1450 std::vector<Constant*> Vals;
1451 if (ETy == Type::Int8Ty) {
1452 for (unsigned char *C = (unsigned char *)$3;
1453 C != (unsigned char*)EndStr; ++C)
1454 Vals.push_back(ConstantInt::get(ETy, *C));
1457 GEN_ERROR("Cannot build string arrays of non byte sized elements!");
1460 $$ = ConstantArray::get(ATy, Vals);
1464 | Types '<' ConstVector '>' { // Nonempty unsized arr
1465 if (!UpRefs.empty())
1466 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1467 const PackedType *PTy = dyn_cast<PackedType>($1->get());
1469 GEN_ERROR("Cannot make packed constant with type: '" +
1470 (*$1)->getDescription() + "'!");
1471 const Type *ETy = PTy->getElementType();
1472 int NumElements = PTy->getNumElements();
1474 // Verify that we have the correct size...
1475 if (NumElements != -1 && NumElements != (int)$3->size())
1476 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1477 utostr($3->size()) + " arguments, but has size of " +
1478 itostr(NumElements) + "!");
1480 // Verify all elements are correct type!
1481 for (unsigned i = 0; i < $3->size(); i++) {
1482 if (ETy != (*$3)[i]->getType())
1483 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1484 ETy->getDescription() +"' as required!\nIt is of type '"+
1485 (*$3)[i]->getType()->getDescription() + "'.");
1488 $$ = ConstantPacked::get(PTy, *$3);
1489 delete $1; delete $3;
1492 | Types '{' ConstVector '}' {
1493 const StructType *STy = dyn_cast<StructType>($1->get());
1495 GEN_ERROR("Cannot make struct constant with type: '" +
1496 (*$1)->getDescription() + "'!");
1498 if ($3->size() != STy->getNumContainedTypes())
1499 GEN_ERROR("Illegal number of initializers for structure type!");
1501 // Check to ensure that constants are compatible with the type initializer!
1502 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1503 if ((*$3)[i]->getType() != STy->getElementType(i))
1504 GEN_ERROR("Expected type '" +
1505 STy->getElementType(i)->getDescription() +
1506 "' for element #" + utostr(i) +
1507 " of structure initializer!");
1509 // Check to ensure that Type is not packed
1510 if (STy->isPacked())
1511 GEN_ERROR("Unpacked Initializer to packed type '" + STy->getDescription() + "'");
1513 $$ = ConstantStruct::get(STy, *$3);
1514 delete $1; delete $3;
1518 if (!UpRefs.empty())
1519 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1520 const StructType *STy = dyn_cast<StructType>($1->get());
1522 GEN_ERROR("Cannot make struct constant with type: '" +
1523 (*$1)->getDescription() + "'!");
1525 if (STy->getNumContainedTypes() != 0)
1526 GEN_ERROR("Illegal number of initializers for structure type!");
1528 // Check to ensure that Type is not packed
1529 if (STy->isPacked())
1530 GEN_ERROR("Unpacked Initializer to packed type '" + STy->getDescription() + "'");
1532 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1536 | Types '<' '{' ConstVector '}' '>' {
1537 const StructType *STy = dyn_cast<StructType>($1->get());
1539 GEN_ERROR("Cannot make struct constant with type: '" +
1540 (*$1)->getDescription() + "'!");
1542 if ($4->size() != STy->getNumContainedTypes())
1543 GEN_ERROR("Illegal number of initializers for structure type!");
1545 // Check to ensure that constants are compatible with the type initializer!
1546 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1547 if ((*$4)[i]->getType() != STy->getElementType(i))
1548 GEN_ERROR("Expected type '" +
1549 STy->getElementType(i)->getDescription() +
1550 "' for element #" + utostr(i) +
1551 " of structure initializer!");
1553 // Check to ensure that Type is packed
1554 if (!STy->isPacked())
1555 GEN_ERROR("Packed Initializer to unpacked type '" + STy->getDescription() + "'");
1557 $$ = ConstantStruct::get(STy, *$4);
1558 delete $1; delete $4;
1561 | Types '<' '{' '}' '>' {
1562 if (!UpRefs.empty())
1563 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1564 const StructType *STy = dyn_cast<StructType>($1->get());
1566 GEN_ERROR("Cannot make struct constant with type: '" +
1567 (*$1)->getDescription() + "'!");
1569 if (STy->getNumContainedTypes() != 0)
1570 GEN_ERROR("Illegal number of initializers for structure type!");
1572 // Check to ensure that Type is packed
1573 if (!STy->isPacked())
1574 GEN_ERROR("Packed Initializer to unpacked type '" + STy->getDescription() + "'");
1576 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1581 if (!UpRefs.empty())
1582 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1583 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1585 GEN_ERROR("Cannot make null pointer constant with type: '" +
1586 (*$1)->getDescription() + "'!");
1588 $$ = ConstantPointerNull::get(PTy);
1593 if (!UpRefs.empty())
1594 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1595 $$ = UndefValue::get($1->get());
1599 | Types SymbolicValueRef {
1600 if (!UpRefs.empty())
1601 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1602 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1604 GEN_ERROR("Global const reference must be a pointer type!");
1606 // ConstExprs can exist in the body of a function, thus creating
1607 // GlobalValues whenever they refer to a variable. Because we are in
1608 // the context of a function, getValNonImprovising will search the functions
1609 // symbol table instead of the module symbol table for the global symbol,
1610 // which throws things all off. To get around this, we just tell
1611 // getValNonImprovising that we are at global scope here.
1613 Function *SavedCurFn = CurFun.CurrentFunction;
1614 CurFun.CurrentFunction = 0;
1616 Value *V = getValNonImprovising(Ty, $2);
1619 CurFun.CurrentFunction = SavedCurFn;
1621 // If this is an initializer for a constant pointer, which is referencing a
1622 // (currently) undefined variable, create a stub now that shall be replaced
1623 // in the future with the right type of variable.
1626 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1627 const PointerType *PT = cast<PointerType>(Ty);
1629 // First check to see if the forward references value is already created!
1630 PerModuleInfo::GlobalRefsType::iterator I =
1631 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1633 if (I != CurModule.GlobalRefs.end()) {
1634 V = I->second; // Placeholder already exists, use it...
1638 if ($2.Type == ValID::GlobalName)
1640 else if ($2.Type != ValID::GlobalID)
1641 GEN_ERROR("Invalid reference to global");
1643 // Create the forward referenced global.
1645 if (const FunctionType *FTy =
1646 dyn_cast<FunctionType>(PT->getElementType())) {
1647 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1648 CurModule.CurrentModule);
1650 GV = new GlobalVariable(PT->getElementType(), false,
1651 GlobalValue::ExternalLinkage, 0,
1652 Name, CurModule.CurrentModule);
1655 // Keep track of the fact that we have a forward ref to recycle it
1656 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1661 $$ = cast<GlobalValue>(V);
1662 delete $1; // Free the type handle
1666 if (!UpRefs.empty())
1667 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1668 if ($1->get() != $2->getType())
1669 GEN_ERROR("Mismatched types for constant expression: " +
1670 (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1675 | Types ZEROINITIALIZER {
1676 if (!UpRefs.empty())
1677 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1678 const Type *Ty = $1->get();
1679 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1680 GEN_ERROR("Cannot create a null initialized value of this type!");
1681 $$ = Constant::getNullValue(Ty);
1685 | IntType ESINT64VAL { // integral constants
1686 if (!ConstantInt::isValueValidForType($1, $2))
1687 GEN_ERROR("Constant value doesn't fit in type!");
1688 $$ = ConstantInt::get($1, $2);
1691 | IntType EUINT64VAL { // integral constants
1692 if (!ConstantInt::isValueValidForType($1, $2))
1693 GEN_ERROR("Constant value doesn't fit in type!");
1694 $$ = ConstantInt::get($1, $2);
1697 | INTTYPE TRUETOK { // Boolean constants
1698 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1699 $$ = ConstantInt::getTrue();
1702 | INTTYPE FALSETOK { // Boolean constants
1703 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1704 $$ = ConstantInt::getFalse();
1707 | FPType FPVAL { // Float & Double constants
1708 if (!ConstantFP::isValueValidForType($1, $2))
1709 GEN_ERROR("Floating point constant invalid for type!!");
1710 $$ = ConstantFP::get($1, $2);
1715 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1716 if (!UpRefs.empty())
1717 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1719 const Type *DestTy = $5->get();
1720 if (!CastInst::castIsValid($1, $3, DestTy))
1721 GEN_ERROR("invalid cast opcode for cast from '" +
1722 Val->getType()->getDescription() + "' to '" +
1723 DestTy->getDescription() + "'!");
1724 $$ = ConstantExpr::getCast($1, $3, DestTy);
1727 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1728 if (!isa<PointerType>($3->getType()))
1729 GEN_ERROR("GetElementPtr requires a pointer operand!");
1732 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1734 GEN_ERROR("Index list invalid for constant getelementptr!");
1736 std::vector<Constant*> IdxVec;
1737 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1738 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1739 IdxVec.push_back(C);
1741 GEN_ERROR("Indices to constant getelementptr must be constants!");
1745 $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1748 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1749 if ($3->getType() != Type::Int1Ty)
1750 GEN_ERROR("Select condition must be of boolean type!");
1751 if ($5->getType() != $7->getType())
1752 GEN_ERROR("Select operand types must match!");
1753 $$ = ConstantExpr::getSelect($3, $5, $7);
1756 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1757 if ($3->getType() != $5->getType())
1758 GEN_ERROR("Binary operator types must match!");
1760 $$ = ConstantExpr::get($1, $3, $5);
1762 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1763 if ($3->getType() != $5->getType())
1764 GEN_ERROR("Logical operator types must match!");
1765 if (!$3->getType()->isInteger()) {
1766 if (!isa<PackedType>($3->getType()) ||
1767 !cast<PackedType>($3->getType())->getElementType()->isInteger())
1768 GEN_ERROR("Logical operator requires integral operands!");
1770 $$ = ConstantExpr::get($1, $3, $5);
1773 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1774 if ($4->getType() != $6->getType())
1775 GEN_ERROR("icmp operand types must match!");
1776 $$ = ConstantExpr::getICmp($2, $4, $6);
1778 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1779 if ($4->getType() != $6->getType())
1780 GEN_ERROR("fcmp operand types must match!");
1781 $$ = ConstantExpr::getFCmp($2, $4, $6);
1783 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1784 if ($5->getType() != Type::Int8Ty)
1785 GEN_ERROR("Shift count for shift constant must be i8 type!");
1786 if (!$3->getType()->isInteger())
1787 GEN_ERROR("Shift constant expression requires integer operand!");
1789 $$ = ConstantExpr::get($1, $3, $5);
1792 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1793 if (!ExtractElementInst::isValidOperands($3, $5))
1794 GEN_ERROR("Invalid extractelement operands!");
1795 $$ = ConstantExpr::getExtractElement($3, $5);
1798 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1799 if (!InsertElementInst::isValidOperands($3, $5, $7))
1800 GEN_ERROR("Invalid insertelement operands!");
1801 $$ = ConstantExpr::getInsertElement($3, $5, $7);
1804 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1805 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1806 GEN_ERROR("Invalid shufflevector operands!");
1807 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1812 // ConstVector - A list of comma separated constants.
1813 ConstVector : ConstVector ',' ConstVal {
1814 ($$ = $1)->push_back($3);
1818 $$ = new std::vector<Constant*>();
1824 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1825 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1828 //===----------------------------------------------------------------------===//
1829 // Rules to match Modules
1830 //===----------------------------------------------------------------------===//
1832 // Module rule: Capture the result of parsing the whole file into a result
1837 $$ = ParserResult = CurModule.CurrentModule;
1838 CurModule.ModuleDone();
1842 $$ = ParserResult = CurModule.CurrentModule;
1843 CurModule.ModuleDone();
1850 | DefinitionList Definition
1854 : DEFINE { CurFun.isDeclare = false; } Function {
1855 CurFun.FunctionDone();
1858 | DECLARE { CurFun.isDeclare = true; } FunctionProto {
1861 | MODULE ASM_TOK AsmBlock {
1865 // Emit an error if there are any unresolved types left.
1866 if (!CurModule.LateResolveTypes.empty()) {
1867 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
1868 if (DID.Type == ValID::LocalName) {
1869 GEN_ERROR("Reference to an undefined type: '"+DID.getName() + "'");
1871 GEN_ERROR("Reference to an undefined type: #" + itostr(DID.Num));
1876 | OptLocalAssign TYPE Types {
1877 if (!UpRefs.empty())
1878 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
1879 // Eagerly resolve types. This is not an optimization, this is a
1880 // requirement that is due to the fact that we could have this:
1882 // %list = type { %list * }
1883 // %list = type { %list * } ; repeated type decl
1885 // If types are not resolved eagerly, then the two types will not be
1886 // determined to be the same type!
1888 ResolveTypeTo($1, *$3);
1890 if (!setTypeName(*$3, $1) && !$1) {
1892 // If this is a named type that is not a redefinition, add it to the slot
1894 CurModule.Types.push_back(*$3);
1900 | OptLocalAssign TYPE VOID {
1901 ResolveTypeTo($1, $3);
1903 if (!setTypeName($3, $1) && !$1) {
1905 // If this is a named type that is not a redefinition, add it to the slot
1907 CurModule.Types.push_back($3);
1911 | OptGlobalAssign GVVisibilityStyle GlobalType ConstVal {
1912 /* "Externally Visible" Linkage */
1914 GEN_ERROR("Global value initializer is not a constant!");
1915 CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
1916 $2, $3, $4->getType(), $4);
1918 } GlobalVarAttributes {
1921 | OptGlobalAssign GVInternalLinkage GVVisibilityStyle GlobalType ConstVal {
1923 GEN_ERROR("Global value initializer is not a constant!");
1924 CurGV = ParseGlobalVariable($1, $2, $3, $4, $5->getType(), $5);
1926 } GlobalVarAttributes {
1929 | OptGlobalAssign GVExternalLinkage GVVisibilityStyle GlobalType Types {
1930 if (!UpRefs.empty())
1931 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1932 CurGV = ParseGlobalVariable($1, $2, $3, $4, *$5, 0);
1935 } GlobalVarAttributes {
1939 | TARGET TargetDefinition {
1942 | DEPLIBS '=' LibrariesDefinition {
1948 AsmBlock : STRINGCONSTANT {
1949 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
1950 char *EndStr = UnEscapeLexed($1, true);
1951 std::string NewAsm($1, EndStr);
1954 if (AsmSoFar.empty())
1955 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
1957 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
1961 TargetDefinition : TRIPLE '=' STRINGCONSTANT {
1962 CurModule.CurrentModule->setTargetTriple($3);
1965 | DATALAYOUT '=' STRINGCONSTANT {
1966 CurModule.CurrentModule->setDataLayout($3);
1970 LibrariesDefinition : '[' LibList ']';
1972 LibList : LibList ',' STRINGCONSTANT {
1973 CurModule.CurrentModule->addLibrary($3);
1978 CurModule.CurrentModule->addLibrary($1);
1982 | /* empty: end of list */ {
1987 //===----------------------------------------------------------------------===//
1988 // Rules to match Function Headers
1989 //===----------------------------------------------------------------------===//
1991 ArgListH : ArgListH ',' Types OptParamAttrs OptLocalName {
1992 if (!UpRefs.empty())
1993 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
1994 if (*$3 == Type::VoidTy)
1995 GEN_ERROR("void typed arguments are invalid!");
1996 ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
2001 | Types OptParamAttrs OptLocalName {
2002 if (!UpRefs.empty())
2003 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2004 if (*$1 == Type::VoidTy)
2005 GEN_ERROR("void typed arguments are invalid!");
2006 ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2007 $$ = new ArgListType;
2012 ArgList : ArgListH {
2016 | ArgListH ',' DOTDOTDOT {
2018 struct ArgListEntry E;
2019 E.Ty = new PATypeHolder(Type::VoidTy);
2021 E.Attrs = FunctionType::NoAttributeSet;
2026 $$ = new ArgListType;
2027 struct ArgListEntry E;
2028 E.Ty = new PATypeHolder(Type::VoidTy);
2030 E.Attrs = FunctionType::NoAttributeSet;
2039 FunctionHeaderH : OptCallingConv ResultTypes GlobalName '(' ArgList ')'
2040 OptFuncAttrs OptSection OptAlign {
2042 std::string FunctionName($3);
2043 free($3); // Free strdup'd memory!
2045 // Check the function result for abstractness if this is a define. We should
2046 // have no abstract types at this point
2047 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($2))
2048 GEN_ERROR("Reference to abstract result: "+ $2->get()->getDescription());
2050 std::vector<const Type*> ParamTypeList;
2051 std::vector<FunctionType::ParameterAttributes> ParamAttrs;
2052 ParamAttrs.push_back($7);
2053 if ($5) { // If there are arguments...
2054 for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I) {
2055 const Type* Ty = I->Ty->get();
2056 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2057 GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2058 ParamTypeList.push_back(Ty);
2059 if (Ty != Type::VoidTy)
2060 ParamAttrs.push_back(I->Attrs);
2064 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2065 if (isVarArg) ParamTypeList.pop_back();
2067 FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg,
2069 const PointerType *PFT = PointerType::get(FT);
2073 if (!FunctionName.empty()) {
2074 ID = ValID::createGlobalName((char*)FunctionName.c_str());
2076 ID = ValID::createGlobalID(CurModule.Values[PFT].size());
2080 // See if this function was forward referenced. If so, recycle the object.
2081 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2082 // Move the function to the end of the list, from whereever it was
2083 // previously inserted.
2084 Fn = cast<Function>(FWRef);
2085 CurModule.CurrentModule->getFunctionList().remove(Fn);
2086 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2087 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2088 (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
2089 // If this is the case, either we need to be a forward decl, or it needs
2091 if (!CurFun.isDeclare && !Fn->isDeclaration())
2092 GEN_ERROR("Redefinition of function '" + FunctionName + "'!");
2094 // Make sure to strip off any argument names so we can't get conflicts.
2095 if (Fn->isDeclaration())
2096 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2099 } else { // Not already defined?
2100 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
2101 CurModule.CurrentModule);
2103 InsertValue(Fn, CurModule.Values);
2106 CurFun.FunctionStart(Fn);
2108 if (CurFun.isDeclare) {
2109 // If we have declaration, always overwrite linkage. This will allow us to
2110 // correctly handle cases, when pointer to function is passed as argument to
2111 // another function.
2112 Fn->setLinkage(CurFun.Linkage);
2113 Fn->setVisibility(CurFun.Visibility);
2115 Fn->setCallingConv($1);
2116 Fn->setAlignment($9);
2122 // Add all of the arguments we parsed to the function...
2123 if ($5) { // Is null if empty...
2124 if (isVarArg) { // Nuke the last entry
2125 assert($5->back().Ty->get() == Type::VoidTy && $5->back().Name == 0&&
2126 "Not a varargs marker!");
2127 delete $5->back().Ty;
2128 $5->pop_back(); // Delete the last entry
2130 Function::arg_iterator ArgIt = Fn->arg_begin();
2132 for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I, ++ArgIt) {
2133 delete I->Ty; // Delete the typeholder...
2134 setValueName(ArgIt, I->Name); // Insert arg into symtab...
2140 delete $5; // We're now done with the argument list
2145 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2147 FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2148 $$ = CurFun.CurrentFunction;
2150 // Make sure that we keep track of the linkage type even if there was a
2151 // previous "declare".
2153 $$->setVisibility($2);
2156 END : ENDTOK | '}'; // Allow end of '}' to end a function
2158 Function : BasicBlockList END {
2163 FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2164 CurFun.CurrentFunction->setLinkage($1);
2165 CurFun.CurrentFunction->setVisibility($2);
2166 $$ = CurFun.CurrentFunction;
2167 CurFun.FunctionDone();
2171 //===----------------------------------------------------------------------===//
2172 // Rules to match Basic Blocks
2173 //===----------------------------------------------------------------------===//
2175 OptSideEffect : /* empty */ {
2184 ConstValueRef : ESINT64VAL { // A reference to a direct constant
2185 $$ = ValID::create($1);
2189 $$ = ValID::create($1);
2192 | FPVAL { // Perhaps it's an FP constant?
2193 $$ = ValID::create($1);
2197 $$ = ValID::create(ConstantInt::getTrue());
2201 $$ = ValID::create(ConstantInt::getFalse());
2205 $$ = ValID::createNull();
2209 $$ = ValID::createUndef();
2212 | ZEROINITIALIZER { // A vector zero constant.
2213 $$ = ValID::createZeroInit();
2216 | '<' ConstVector '>' { // Nonempty unsized packed vector
2217 const Type *ETy = (*$2)[0]->getType();
2218 int NumElements = $2->size();
2220 PackedType* pt = PackedType::get(ETy, NumElements);
2221 PATypeHolder* PTy = new PATypeHolder(
2229 // Verify all elements are correct type!
2230 for (unsigned i = 0; i < $2->size(); i++) {
2231 if (ETy != (*$2)[i]->getType())
2232 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2233 ETy->getDescription() +"' as required!\nIt is of type '" +
2234 (*$2)[i]->getType()->getDescription() + "'.");
2237 $$ = ValID::create(ConstantPacked::get(pt, *$2));
2238 delete PTy; delete $2;
2242 $$ = ValID::create($1);
2245 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2246 char *End = UnEscapeLexed($3, true);
2247 std::string AsmStr = std::string($3, End);
2248 End = UnEscapeLexed($5, true);
2249 std::string Constraints = std::string($5, End);
2250 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2256 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2259 SymbolicValueRef : LOCALVAL_ID { // Is it an integer reference...?
2260 $$ = ValID::createLocalID($1);
2264 $$ = ValID::createGlobalID($1);
2267 | LocalName { // Is it a named reference...?
2268 $$ = ValID::createLocalName($1);
2271 | GlobalName { // Is it a named reference...?
2272 $$ = ValID::createGlobalName($1);
2276 // ValueRef - A reference to a definition... either constant or symbolic
2277 ValueRef : SymbolicValueRef | ConstValueRef;
2280 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2281 // type immediately preceeds the value reference, and allows complex constant
2282 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2283 ResolvedVal : Types ValueRef {
2284 if (!UpRefs.empty())
2285 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2286 $$ = getVal(*$1, $2);
2292 BasicBlockList : BasicBlockList BasicBlock {
2296 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2302 // Basic blocks are terminated by branching instructions:
2303 // br, br/cc, switch, ret
2305 BasicBlock : InstructionList OptLocalAssign BBTerminatorInst {
2306 setValueName($3, $2);
2310 $1->getInstList().push_back($3);
2316 InstructionList : InstructionList Inst {
2317 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2318 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2319 if (CI2->getParent() == 0)
2320 $1->getInstList().push_back(CI2);
2321 $1->getInstList().push_back($2);
2326 $$ = getBBVal(ValID::createLocalID(CurFun.NextBBNum++), true);
2329 // Make sure to move the basic block to the correct location in the
2330 // function, instead of leaving it inserted wherever it was first
2332 Function::BasicBlockListType &BBL =
2333 CurFun.CurrentFunction->getBasicBlockList();
2334 BBL.splice(BBL.end(), BBL, $$);
2338 $$ = getBBVal(ValID::createLocalName($1), 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 BBTerminatorInst : RET ResolvedVal { // Return with a result...
2351 $$ = new ReturnInst($2);
2354 | RET VOID { // Return with no result...
2355 $$ = new ReturnInst();
2358 | BR LABEL ValueRef { // Unconditional Branch...
2359 BasicBlock* tmpBB = getBBVal($3);
2361 $$ = new BranchInst(tmpBB);
2362 } // Conditional Branch...
2363 | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2364 assert(cast<IntegerType>($2)->getBitWidth() == 1 && "Not Bool?");
2365 BasicBlock* tmpBBA = getBBVal($6);
2367 BasicBlock* tmpBBB = getBBVal($9);
2369 Value* tmpVal = getVal(Type::Int1Ty, $3);
2371 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2373 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2374 Value* tmpVal = getVal($2, $3);
2376 BasicBlock* tmpBB = getBBVal($6);
2378 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2381 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2383 for (; I != E; ++I) {
2384 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2385 S->addCase(CI, I->second);
2387 GEN_ERROR("Switch case is constant, but not a simple integer!");
2392 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2393 Value* tmpVal = getVal($2, $3);
2395 BasicBlock* tmpBB = getBBVal($6);
2397 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2401 | INVOKE OptCallingConv ResultTypes ValueRef '(' ValueRefList ')' OptFuncAttrs
2402 TO LABEL ValueRef UNWIND LABEL ValueRef {
2404 // Handle the short syntax
2405 const PointerType *PFTy = 0;
2406 const FunctionType *Ty = 0;
2407 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2408 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2409 // Pull out the types of all of the arguments...
2410 std::vector<const Type*> ParamTypes;
2411 FunctionType::ParamAttrsList ParamAttrs;
2412 ParamAttrs.push_back($8);
2413 for (ValueRefList::iterator I = $6->begin(), E = $6->end(); I != E; ++I) {
2414 const Type *Ty = I->Val->getType();
2415 if (Ty == Type::VoidTy)
2416 GEN_ERROR("Short call syntax cannot be used with varargs");
2417 ParamTypes.push_back(Ty);
2418 ParamAttrs.push_back(I->Attrs);
2421 Ty = FunctionType::get($3->get(), ParamTypes, false, ParamAttrs);
2422 PFTy = PointerType::get(Ty);
2425 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2427 BasicBlock *Normal = getBBVal($11);
2429 BasicBlock *Except = getBBVal($14);
2432 // Check the arguments
2434 if ($6->empty()) { // Has no arguments?
2435 // Make sure no arguments is a good thing!
2436 if (Ty->getNumParams() != 0)
2437 GEN_ERROR("No arguments passed to a function that "
2438 "expects arguments!");
2439 } else { // Has arguments?
2440 // Loop through FunctionType's arguments and ensure they are specified
2442 FunctionType::param_iterator I = Ty->param_begin();
2443 FunctionType::param_iterator E = Ty->param_end();
2444 ValueRefList::iterator ArgI = $6->begin(), ArgE = $6->end();
2446 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2447 if (ArgI->Val->getType() != *I)
2448 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2449 (*I)->getDescription() + "'!");
2450 Args.push_back(ArgI->Val);
2453 if (Ty->isVarArg()) {
2455 for (; ArgI != ArgE; ++ArgI)
2456 Args.push_back(ArgI->Val); // push the remaining varargs
2457 } else if (I != E || ArgI != ArgE)
2458 GEN_ERROR("Invalid number of parameters detected!");
2461 // Create the InvokeInst
2462 InvokeInst *II = new InvokeInst(V, Normal, Except, Args);
2463 II->setCallingConv($2);
2469 $$ = new UnwindInst();
2473 $$ = new UnreachableInst();
2479 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2481 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
2484 GEN_ERROR("May only switch on a constant pool value!");
2486 BasicBlock* tmpBB = getBBVal($6);
2488 $$->push_back(std::make_pair(V, tmpBB));
2490 | IntType ConstValueRef ',' LABEL ValueRef {
2491 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2492 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
2496 GEN_ERROR("May only switch on a constant pool value!");
2498 BasicBlock* tmpBB = getBBVal($5);
2500 $$->push_back(std::make_pair(V, tmpBB));
2503 Inst : OptLocalAssign InstVal {
2504 // Is this definition named?? if so, assign the name...
2505 setValueName($2, $1);
2512 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2513 if (!UpRefs.empty())
2514 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2515 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2516 Value* tmpVal = getVal(*$1, $3);
2518 BasicBlock* tmpBB = getBBVal($5);
2520 $$->push_back(std::make_pair(tmpVal, tmpBB));
2523 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2525 Value* tmpVal = getVal($1->front().first->getType(), $4);
2527 BasicBlock* tmpBB = getBBVal($6);
2529 $1->push_back(std::make_pair(tmpVal, tmpBB));
2533 ValueRefList : Types ValueRef OptParamAttrs {
2534 if (!UpRefs.empty())
2535 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2536 // Used for call and invoke instructions
2537 $$ = new ValueRefList();
2538 ValueRefListEntry E; E.Attrs = $3; E.Val = getVal($1->get(), $2);
2541 | ValueRefList ',' Types ValueRef OptParamAttrs {
2542 if (!UpRefs.empty())
2543 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2545 ValueRefListEntry E; E.Attrs = $5; E.Val = getVal($3->get(), $4);
2549 | /*empty*/ { $$ = new ValueRefList(); };
2551 IndexList // Used for gep instructions and constant expressions
2552 : /*empty*/ { $$ = new std::vector<Value*>(); }
2553 | IndexList ',' ResolvedVal {
2560 OptTailCall : TAIL CALL {
2569 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2570 if (!UpRefs.empty())
2571 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2572 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
2573 !isa<PackedType>((*$2).get()))
2575 "Arithmetic operator requires integer, FP, or packed operands!");
2576 if (isa<PackedType>((*$2).get()) &&
2577 ($1 == Instruction::URem ||
2578 $1 == Instruction::SRem ||
2579 $1 == Instruction::FRem))
2580 GEN_ERROR("U/S/FRem not supported on packed types!");
2581 Value* val1 = getVal(*$2, $3);
2583 Value* val2 = getVal(*$2, $5);
2585 $$ = BinaryOperator::create($1, val1, val2);
2587 GEN_ERROR("binary operator returned null!");
2590 | LogicalOps Types ValueRef ',' ValueRef {
2591 if (!UpRefs.empty())
2592 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2593 if (!(*$2)->isInteger()) {
2594 if (!isa<PackedType>($2->get()) ||
2595 !cast<PackedType>($2->get())->getElementType()->isInteger())
2596 GEN_ERROR("Logical operator requires integral operands!");
2598 Value* tmpVal1 = getVal(*$2, $3);
2600 Value* tmpVal2 = getVal(*$2, $5);
2602 $$ = BinaryOperator::create($1, tmpVal1, tmpVal2);
2604 GEN_ERROR("binary operator returned null!");
2607 | ICMP IPredicates Types ValueRef ',' ValueRef {
2608 if (!UpRefs.empty())
2609 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2610 if (isa<PackedType>((*$3).get()))
2611 GEN_ERROR("Packed types not supported by icmp instruction");
2612 Value* tmpVal1 = getVal(*$3, $4);
2614 Value* tmpVal2 = getVal(*$3, $6);
2616 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2618 GEN_ERROR("icmp operator returned null!");
2620 | FCMP FPredicates 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 fcmp instruction");
2625 Value* tmpVal1 = getVal(*$3, $4);
2627 Value* tmpVal2 = getVal(*$3, $6);
2629 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2631 GEN_ERROR("fcmp operator returned null!");
2633 | ShiftOps ResolvedVal ',' ResolvedVal {
2634 if ($4->getType() != Type::Int8Ty)
2635 GEN_ERROR("Shift amount must be i8 type!");
2636 if (!$2->getType()->isInteger())
2637 GEN_ERROR("Shift constant expression requires integer operand!");
2639 $$ = new ShiftInst($1, $2, $4);
2642 | CastOps ResolvedVal TO Types {
2643 if (!UpRefs.empty())
2644 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2646 const Type* DestTy = $4->get();
2647 if (!CastInst::castIsValid($1, Val, DestTy))
2648 GEN_ERROR("invalid cast opcode for cast from '" +
2649 Val->getType()->getDescription() + "' to '" +
2650 DestTy->getDescription() + "'!");
2651 $$ = CastInst::create($1, Val, DestTy);
2654 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2655 if ($2->getType() != Type::Int1Ty)
2656 GEN_ERROR("select condition must be boolean!");
2657 if ($4->getType() != $6->getType())
2658 GEN_ERROR("select value types should match!");
2659 $$ = new SelectInst($2, $4, $6);
2662 | VAARG ResolvedVal ',' Types {
2663 if (!UpRefs.empty())
2664 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2665 $$ = new VAArgInst($2, *$4);
2669 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2670 if (!ExtractElementInst::isValidOperands($2, $4))
2671 GEN_ERROR("Invalid extractelement operands!");
2672 $$ = new ExtractElementInst($2, $4);
2675 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2676 if (!InsertElementInst::isValidOperands($2, $4, $6))
2677 GEN_ERROR("Invalid insertelement operands!");
2678 $$ = new InsertElementInst($2, $4, $6);
2681 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2682 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
2683 GEN_ERROR("Invalid shufflevector operands!");
2684 $$ = new ShuffleVectorInst($2, $4, $6);
2688 const Type *Ty = $2->front().first->getType();
2689 if (!Ty->isFirstClassType())
2690 GEN_ERROR("PHI node operands must be of first class type!");
2691 $$ = new PHINode(Ty);
2692 ((PHINode*)$$)->reserveOperandSpace($2->size());
2693 while ($2->begin() != $2->end()) {
2694 if ($2->front().first->getType() != Ty)
2695 GEN_ERROR("All elements of a PHI node must be of the same type!");
2696 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2699 delete $2; // Free the list...
2702 | OptTailCall OptCallingConv ResultTypes ValueRef '(' ValueRefList ')'
2705 // Handle the short syntax
2706 const PointerType *PFTy = 0;
2707 const FunctionType *Ty = 0;
2708 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2709 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2710 // Pull out the types of all of the arguments...
2711 std::vector<const Type*> ParamTypes;
2712 FunctionType::ParamAttrsList ParamAttrs;
2713 ParamAttrs.push_back($8);
2714 for (ValueRefList::iterator I = $6->begin(), E = $6->end(); I != E; ++I) {
2715 const Type *Ty = I->Val->getType();
2716 if (Ty == Type::VoidTy)
2717 GEN_ERROR("Short call syntax cannot be used with varargs");
2718 ParamTypes.push_back(Ty);
2719 ParamAttrs.push_back(I->Attrs);
2722 Ty = FunctionType::get($3->get(), ParamTypes, false, ParamAttrs);
2723 PFTy = PointerType::get(Ty);
2726 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2729 // Check the arguments
2731 if ($6->empty()) { // Has no arguments?
2732 // Make sure no arguments is a good thing!
2733 if (Ty->getNumParams() != 0)
2734 GEN_ERROR("No arguments passed to a function that "
2735 "expects arguments!");
2736 } else { // Has arguments?
2737 // Loop through FunctionType's arguments and ensure they are specified
2740 FunctionType::param_iterator I = Ty->param_begin();
2741 FunctionType::param_iterator E = Ty->param_end();
2742 ValueRefList::iterator ArgI = $6->begin(), ArgE = $6->end();
2744 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2745 if (ArgI->Val->getType() != *I)
2746 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2747 (*I)->getDescription() + "'!");
2748 Args.push_back(ArgI->Val);
2750 if (Ty->isVarArg()) {
2752 for (; ArgI != ArgE; ++ArgI)
2753 Args.push_back(ArgI->Val); // push the remaining varargs
2754 } else if (I != E || ArgI != ArgE)
2755 GEN_ERROR("Invalid number of parameters detected!");
2757 // Create the call node
2758 CallInst *CI = new CallInst(V, Args);
2759 CI->setTailCall($1);
2760 CI->setCallingConv($2);
2771 OptVolatile : VOLATILE {
2782 MemoryInst : MALLOC Types OptCAlign {
2783 if (!UpRefs.empty())
2784 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2785 $$ = new MallocInst(*$2, 0, $3);
2789 | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
2790 if (!UpRefs.empty())
2791 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2792 Value* tmpVal = getVal($4, $5);
2794 $$ = new MallocInst(*$2, tmpVal, $6);
2797 | ALLOCA Types OptCAlign {
2798 if (!UpRefs.empty())
2799 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2800 $$ = new AllocaInst(*$2, 0, $3);
2804 | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
2805 if (!UpRefs.empty())
2806 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2807 Value* tmpVal = getVal($4, $5);
2809 $$ = new AllocaInst(*$2, tmpVal, $6);
2812 | FREE ResolvedVal {
2813 if (!isa<PointerType>($2->getType()))
2814 GEN_ERROR("Trying to free nonpointer type " +
2815 $2->getType()->getDescription() + "!");
2816 $$ = new FreeInst($2);
2820 | OptVolatile LOAD Types ValueRef {
2821 if (!UpRefs.empty())
2822 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2823 if (!isa<PointerType>($3->get()))
2824 GEN_ERROR("Can't load from nonpointer type: " +
2825 (*$3)->getDescription());
2826 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
2827 GEN_ERROR("Can't load from pointer of non-first-class type: " +
2828 (*$3)->getDescription());
2829 Value* tmpVal = getVal(*$3, $4);
2831 $$ = new LoadInst(tmpVal, "", $1);
2834 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2835 if (!UpRefs.empty())
2836 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
2837 const PointerType *PT = dyn_cast<PointerType>($5->get());
2839 GEN_ERROR("Can't store to a nonpointer type: " +
2840 (*$5)->getDescription());
2841 const Type *ElTy = PT->getElementType();
2842 if (ElTy != $3->getType())
2843 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
2844 "' into space of type '" + ElTy->getDescription() + "'!");
2846 Value* tmpVal = getVal(*$5, $6);
2848 $$ = new StoreInst($3, tmpVal, $1);
2851 | GETELEMENTPTR Types ValueRef IndexList {
2852 if (!UpRefs.empty())
2853 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2854 if (!isa<PointerType>($2->get()))
2855 GEN_ERROR("getelementptr insn requires pointer operand!");
2857 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2858 GEN_ERROR("Invalid getelementptr indices for type '" +
2859 (*$2)->getDescription()+ "'!");
2860 Value* tmpVal = getVal(*$2, $3);
2862 $$ = new GetElementPtrInst(tmpVal, *$4);
2870 // common code from the two 'RunVMAsmParser' functions
2871 static Module* RunParser(Module * M) {
2873 llvmAsmlineno = 1; // Reset the current line number...
2874 CurModule.CurrentModule = M;
2879 // Check to make sure the parser succeeded
2882 delete ParserResult;
2886 // Check to make sure that parsing produced a result
2890 // Reset ParserResult variable while saving its value for the result.
2891 Module *Result = ParserResult;
2897 void llvm::GenerateError(const std::string &message, int LineNo) {
2898 if (LineNo == -1) LineNo = llvmAsmlineno;
2899 // TODO: column number in exception
2901 TheParseError->setError(CurFilename, message, LineNo);
2905 int yyerror(const char *ErrorMsg) {
2907 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2908 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2909 std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2910 if (yychar == YYEMPTY || yychar == 0)
2911 errMsg += "end-of-file.";
2913 errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2914 GenerateError(errMsg);