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/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()) return 0;
345 if (D.Num >= VI->second.size()) return 0;
346 return VI->second[Num];
349 case ValID::LocalName: { // Is it a named definition?
350 if (!inFunctionScope()) return 0;
351 SymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
352 Value *N = SymTab.lookup(Ty, D.Name);
353 if (N == 0) return 0;
355 D.destroy(); // Free old strdup'd memory...
358 case ValID::GlobalName: { // Is it a named definition?
359 SymbolTable &SymTab = CurModule.CurrentModule->getValueSymbolTable();
360 Value *N = SymTab.lookup(Ty, D.Name);
361 if (N == 0) return 0;
363 D.destroy(); // Free old strdup'd memory...
367 // Check to make sure that "Ty" is an integral type, and that our
368 // value will fit into the specified type...
369 case ValID::ConstSIntVal: // Is it a constant pool reference??
370 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
371 GenerateError("Signed integral constant '" +
372 itostr(D.ConstPool64) + "' is invalid for type '" +
373 Ty->getDescription() + "'!");
376 return ConstantInt::get(Ty, D.ConstPool64);
378 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
379 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
380 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
381 GenerateError("Integral constant '" + utostr(D.UConstPool64) +
382 "' is invalid or out of range!");
384 } else { // This is really a signed reference. Transmogrify.
385 return ConstantInt::get(Ty, D.ConstPool64);
388 return ConstantInt::get(Ty, D.UConstPool64);
391 case ValID::ConstFPVal: // Is it a floating point const pool reference?
392 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP)) {
393 GenerateError("FP constant invalid for type!!");
396 return ConstantFP::get(Ty, D.ConstPoolFP);
398 case ValID::ConstNullVal: // Is it a null value?
399 if (!isa<PointerType>(Ty)) {
400 GenerateError("Cannot create a a non pointer null!");
403 return ConstantPointerNull::get(cast<PointerType>(Ty));
405 case ValID::ConstUndefVal: // Is it an undef value?
406 return UndefValue::get(Ty);
408 case ValID::ConstZeroVal: // Is it a zero value?
409 return Constant::getNullValue(Ty);
411 case ValID::ConstantVal: // Fully resolved constant?
412 if (D.ConstantValue->getType() != Ty) {
413 GenerateError("Constant expression type different from required type!");
416 return D.ConstantValue;
418 case ValID::InlineAsmVal: { // Inline asm expression
419 const PointerType *PTy = dyn_cast<PointerType>(Ty);
420 const FunctionType *FTy =
421 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
422 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
423 GenerateError("Invalid type for asm constraint string!");
426 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
427 D.IAD->HasSideEffects);
428 D.destroy(); // Free InlineAsmDescriptor.
432 assert(0 && "Unhandled case!");
436 assert(0 && "Unhandled case!");
440 // getVal - This function is identical to getValNonImprovising, except that if a
441 // value is not already defined, it "improvises" by creating a placeholder var
442 // that looks and acts just like the requested variable. When the value is
443 // defined later, all uses of the placeholder variable are replaced with the
446 static Value *getVal(const Type *Ty, const ValID &ID) {
447 if (Ty == Type::LabelTy) {
448 GenerateError("Cannot use a basic block here");
452 // See if the value has already been defined.
453 Value *V = getValNonImprovising(Ty, ID);
455 if (TriggerError) return 0;
457 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
458 GenerateError("Invalid use of a composite type!");
462 // If we reached here, we referenced either a symbol that we don't know about
463 // or an id number that hasn't been read yet. We may be referencing something
464 // forward, so just create an entry to be resolved later and get to it...
466 V = new Argument(Ty);
468 // Remember where this forward reference came from. FIXME, shouldn't we try
469 // to recycle these things??
470 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
473 if (inFunctionScope())
474 InsertValue(V, CurFun.LateResolveValues);
476 InsertValue(V, CurModule.LateResolveValues);
480 /// getBBVal - This is used for two purposes:
481 /// * If isDefinition is true, a new basic block with the specified ID is being
483 /// * If isDefinition is true, this is a reference to a basic block, which may
484 /// or may not be a forward reference.
486 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
487 assert(inFunctionScope() && "Can't get basic block at global scope!");
493 GenerateError("Illegal label reference " + ID.getName());
495 case ValID::LocalID: // Is it a numbered definition?
496 if (ID.Num >= CurFun.NumberedBlocks.size())
497 CurFun.NumberedBlocks.resize(ID.Num+1);
498 BB = CurFun.NumberedBlocks[ID.Num];
500 case ValID::LocalName: // Is it a named definition?
502 if (Value *N = CurFun.CurrentFunction->
503 getValueSymbolTable().lookup(Type::LabelTy, Name))
504 BB = cast<BasicBlock>(N);
508 // See if the block has already been defined.
510 // If this is the definition of the block, make sure the existing value was
511 // just a forward reference. If it was a forward reference, there will be
512 // an entry for it in the PlaceHolderInfo map.
513 if (isDefinition && !CurFun.BBForwardRefs.erase(BB)) {
514 // The existing value was a definition, not a forward reference.
515 GenerateError("Redefinition of label " + ID.getName());
519 ID.destroy(); // Free strdup'd memory.
523 // Otherwise this block has not been seen before.
524 BB = new BasicBlock("", CurFun.CurrentFunction);
525 if (ID.Type == ValID::LocalName) {
526 BB->setName(ID.Name);
528 CurFun.NumberedBlocks[ID.Num] = BB;
531 // If this is not a definition, keep track of it so we can use it as a forward
534 // Remember where this forward reference came from.
535 CurFun.BBForwardRefs[BB] = std::make_pair(ID, llvmAsmlineno);
537 // The forward declaration could have been inserted anywhere in the
538 // function: insert it into the correct place now.
539 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
540 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
547 //===----------------------------------------------------------------------===//
548 // Code to handle forward references in instructions
549 //===----------------------------------------------------------------------===//
551 // This code handles the late binding needed with statements that reference
552 // values not defined yet... for example, a forward branch, or the PHI node for
555 // This keeps a table (CurFun.LateResolveValues) of all such forward references
556 // and back patchs after we are done.
559 // ResolveDefinitions - If we could not resolve some defs at parsing
560 // time (forward branches, phi functions for loops, etc...) resolve the
564 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
565 std::map<const Type*,ValueList> *FutureLateResolvers) {
566 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
567 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
568 E = LateResolvers.end(); LRI != E; ++LRI) {
569 ValueList &List = LRI->second;
570 while (!List.empty()) {
571 Value *V = List.back();
574 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
575 CurModule.PlaceHolderInfo.find(V);
576 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
578 ValID &DID = PHI->second.first;
580 Value *TheRealValue = getValNonImprovising(LRI->first, DID);
584 V->replaceAllUsesWith(TheRealValue);
586 CurModule.PlaceHolderInfo.erase(PHI);
587 } else if (FutureLateResolvers) {
588 // Functions have their unresolved items forwarded to the module late
590 InsertValue(V, *FutureLateResolvers);
592 if (DID.Type == ValID::LocalName || DID.Type == ValID::GlobalName) {
593 GenerateError("Reference to an invalid definition: '" +DID.getName()+
594 "' of type '" + V->getType()->getDescription() + "'",
598 GenerateError("Reference to an invalid definition: #" +
599 itostr(DID.Num) + " of type '" +
600 V->getType()->getDescription() + "'",
608 LateResolvers.clear();
611 // ResolveTypeTo - A brand new type was just declared. This means that (if
612 // name is not null) things referencing Name can be resolved. Otherwise, things
613 // refering to the number can be resolved. Do this now.
615 static void ResolveTypeTo(char *Name, const Type *ToTy) {
617 if (Name) D = ValID::createLocalName(Name);
618 else D = ValID::createLocalID(CurModule.Types.size());
620 std::map<ValID, PATypeHolder>::iterator I =
621 CurModule.LateResolveTypes.find(D);
622 if (I != CurModule.LateResolveTypes.end()) {
623 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
624 CurModule.LateResolveTypes.erase(I);
628 // setValueName - Set the specified value to the name given. The name may be
629 // null potentially, in which case this is a noop. The string passed in is
630 // assumed to be a malloc'd string buffer, and is free'd by this function.
632 static void setValueName(Value *V, char *NameStr) {
633 if (!NameStr) return;
634 std::string Name(NameStr); // Copy string
635 free(NameStr); // Free old string
637 if (V->getType() == Type::VoidTy) {
638 GenerateError("Can't assign name '" + Name+"' to value with void type!");
642 assert(inFunctionScope() && "Must be in function scope!");
643 SymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
644 if (ST.lookup(V->getType(), Name)) {
645 GenerateError("Redefinition of value '" + Name + "' of type '" +
646 V->getType()->getDescription() + "'!");
654 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
655 /// this is a declaration, otherwise it is a definition.
656 static GlobalVariable *
657 ParseGlobalVariable(char *NameStr,
658 GlobalValue::LinkageTypes Linkage,
659 GlobalValue::VisibilityTypes Visibility,
660 bool isConstantGlobal, const Type *Ty,
661 Constant *Initializer) {
662 if (isa<FunctionType>(Ty)) {
663 GenerateError("Cannot declare global vars of function type!");
667 const PointerType *PTy = PointerType::get(Ty);
671 Name = NameStr; // Copy string
672 free(NameStr); // Free old string
675 // See if this global value was forward referenced. If so, recycle the
679 ID = ValID::createGlobalName((char*)Name.c_str());
681 ID = ValID::createGlobalID(CurModule.Values[PTy].size());
684 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
685 // Move the global to the end of the list, from whereever it was
686 // previously inserted.
687 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
688 CurModule.CurrentModule->getGlobalList().remove(GV);
689 CurModule.CurrentModule->getGlobalList().push_back(GV);
690 GV->setInitializer(Initializer);
691 GV->setLinkage(Linkage);
692 GV->setVisibility(Visibility);
693 GV->setConstant(isConstantGlobal);
694 InsertValue(GV, CurModule.Values);
698 // If this global has a name, check to see if there is already a definition
699 // of this global in the module. If so, it is an error.
701 // We are a simple redefinition of a value, check to see if it is defined
702 // the same as the old one.
703 if (CurModule.CurrentModule->getGlobalVariable(Name, Ty)) {
704 GenerateError("Redefinition of global variable named '" + Name +
705 "' of type '" + Ty->getDescription() + "'!");
710 // Otherwise there is no existing GV to use, create one now.
712 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
713 CurModule.CurrentModule);
714 GV->setVisibility(Visibility);
715 InsertValue(GV, CurModule.Values);
719 // setTypeName - Set the specified type to the name given. The name may be
720 // null potentially, in which case this is a noop. The string passed in is
721 // assumed to be a malloc'd string buffer, and is freed by this function.
723 // This function returns true if the type has already been defined, but is
724 // allowed to be redefined in the specified context. If the name is a new name
725 // for the type plane, it is inserted and false is returned.
726 static bool setTypeName(const Type *T, char *NameStr) {
727 assert(!inFunctionScope() && "Can't give types function-local names!");
728 if (NameStr == 0) return false;
730 std::string Name(NameStr); // Copy string
731 free(NameStr); // Free old string
733 // We don't allow assigning names to void type
734 if (T == Type::VoidTy) {
735 GenerateError("Can't assign name '" + Name + "' to the void type!");
739 // Set the type name, checking for conflicts as we do so.
740 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
742 if (AlreadyExists) { // Inserting a name that is already defined???
743 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
744 assert(Existing && "Conflict but no matching type?");
746 // There is only one case where this is allowed: when we are refining an
747 // opaque type. In this case, Existing will be an opaque type.
748 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
749 // We ARE replacing an opaque type!
750 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
754 // Otherwise, this is an attempt to redefine a type. That's okay if
755 // the redefinition is identical to the original. This will be so if
756 // Existing and T point to the same Type object. In this one case we
757 // allow the equivalent redefinition.
758 if (Existing == T) return true; // Yes, it's equal.
760 // Any other kind of (non-equivalent) redefinition is an error.
761 GenerateError("Redefinition of type named '" + Name + "' of type '" +
762 T->getDescription() + "'!");
768 //===----------------------------------------------------------------------===//
769 // Code for handling upreferences in type names...
772 // TypeContains - Returns true if Ty directly contains E in it.
774 static bool TypeContains(const Type *Ty, const Type *E) {
775 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
776 E) != Ty->subtype_end();
781 // NestingLevel - The number of nesting levels that need to be popped before
782 // this type is resolved.
783 unsigned NestingLevel;
785 // LastContainedTy - This is the type at the current binding level for the
786 // type. Every time we reduce the nesting level, this gets updated.
787 const Type *LastContainedTy;
789 // UpRefTy - This is the actual opaque type that the upreference is
793 UpRefRecord(unsigned NL, OpaqueType *URTy)
794 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
798 // UpRefs - A list of the outstanding upreferences that need to be resolved.
799 static std::vector<UpRefRecord> UpRefs;
801 /// HandleUpRefs - Every time we finish a new layer of types, this function is
802 /// called. It loops through the UpRefs vector, which is a list of the
803 /// currently active types. For each type, if the up reference is contained in
804 /// the newly completed type, we decrement the level count. When the level
805 /// count reaches zero, the upreferenced type is the type that is passed in:
806 /// thus we can complete the cycle.
808 static PATypeHolder HandleUpRefs(const Type *ty) {
809 // If Ty isn't abstract, or if there are no up-references in it, then there is
810 // nothing to resolve here.
811 if (!ty->isAbstract() || UpRefs.empty()) return ty;
814 UR_OUT("Type '" << Ty->getDescription() <<
815 "' newly formed. Resolving upreferences.\n" <<
816 UpRefs.size() << " upreferences active!\n");
818 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
819 // to zero), we resolve them all together before we resolve them to Ty. At
820 // the end of the loop, if there is anything to resolve to Ty, it will be in
822 OpaqueType *TypeToResolve = 0;
824 for (unsigned i = 0; i != UpRefs.size(); ++i) {
825 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
826 << UpRefs[i].second->getDescription() << ") = "
827 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
828 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
829 // Decrement level of upreference
830 unsigned Level = --UpRefs[i].NestingLevel;
831 UpRefs[i].LastContainedTy = Ty;
832 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
833 if (Level == 0) { // Upreference should be resolved!
834 if (!TypeToResolve) {
835 TypeToResolve = UpRefs[i].UpRefTy;
837 UR_OUT(" * Resolving upreference for "
838 << UpRefs[i].second->getDescription() << "\n";
839 std::string OldName = UpRefs[i].UpRefTy->getDescription());
840 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
841 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
842 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
844 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
845 --i; // Do not skip the next element...
851 UR_OUT(" * Resolving upreference for "
852 << UpRefs[i].second->getDescription() << "\n";
853 std::string OldName = TypeToResolve->getDescription());
854 TypeToResolve->refineAbstractTypeTo(Ty);
860 //===----------------------------------------------------------------------===//
861 // RunVMAsmParser - Define an interface to this parser
862 //===----------------------------------------------------------------------===//
864 static Module* RunParser(Module * M);
866 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
869 CurFilename = Filename;
870 return RunParser(new Module(CurFilename));
873 Module *llvm::RunVMAsmParser(const char * AsmString, Module * M) {
874 set_scan_string(AsmString);
876 CurFilename = "from_memory";
878 return RunParser(new Module (CurFilename));
887 llvm::Module *ModuleVal;
888 llvm::Function *FunctionVal;
889 llvm::BasicBlock *BasicBlockVal;
890 llvm::TerminatorInst *TermInstVal;
891 llvm::Instruction *InstVal;
892 llvm::Constant *ConstVal;
894 const llvm::Type *PrimType;
895 std::list<llvm::PATypeHolder> *TypeList;
896 llvm::PATypeHolder *TypeVal;
897 llvm::Value *ValueVal;
898 std::vector<llvm::Value*> *ValueList;
899 llvm::ArgListType *ArgList;
900 llvm::TypeWithAttrs TypeWithAttrs;
901 llvm::TypeWithAttrsList *TypeWithAttrsList;
902 llvm::ValueRefList *ValueRefList;
904 // Represent the RHS of PHI node
905 std::list<std::pair<llvm::Value*,
906 llvm::BasicBlock*> > *PHIList;
907 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
908 std::vector<llvm::Constant*> *ConstVector;
910 llvm::GlobalValue::LinkageTypes Linkage;
911 llvm::GlobalValue::VisibilityTypes Visibility;
912 llvm::FunctionType::ParameterAttributes ParamAttrs;
920 char *StrVal; // This memory is strdup'd!
921 llvm::ValID ValIDVal; // strdup'd memory maybe!
923 llvm::Instruction::BinaryOps BinaryOpVal;
924 llvm::Instruction::TermOps TermOpVal;
925 llvm::Instruction::MemoryOps MemOpVal;
926 llvm::Instruction::CastOps CastOpVal;
927 llvm::Instruction::OtherOps OtherOpVal;
928 llvm::ICmpInst::Predicate IPredicate;
929 llvm::FCmpInst::Predicate FPredicate;
932 %type <ModuleVal> Module
933 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
934 %type <BasicBlockVal> BasicBlock InstructionList
935 %type <TermInstVal> BBTerminatorInst
936 %type <InstVal> Inst InstVal MemoryInst
937 %type <ConstVal> ConstVal ConstExpr
938 %type <ConstVector> ConstVector
939 %type <ArgList> ArgList ArgListH
940 %type <PHIList> PHIList
941 %type <ValueRefList> ValueRefList // For call param lists & GEP indices
942 %type <ValueList> IndexList // For GEP indices
943 %type <TypeList> TypeListI
944 %type <TypeWithAttrsList> ArgTypeList ArgTypeListI
945 %type <TypeWithAttrs> ArgType
946 %type <JumpTable> JumpTable
947 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
948 %type <BoolVal> OptVolatile // 'volatile' or not
949 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
950 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
951 %type <Linkage> GVInternalLinkage GVExternalLinkage
952 %type <Linkage> FunctionDefineLinkage FunctionDeclareLinkage
953 %type <Visibility> GVVisibilityStyle
955 // ValueRef - Unresolved reference to a definition or BB
956 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
957 %type <ValueVal> ResolvedVal // <type> <valref> pair
958 // Tokens and types for handling constant integer values
960 // ESINT64VAL - A negative number within long long range
961 %token <SInt64Val> ESINT64VAL
963 // EUINT64VAL - A positive number within uns. long long range
964 %token <UInt64Val> EUINT64VAL
966 %token <UIntVal> LOCALVAL_ID GLOBALVAL_ID // %123 @123
967 %token <FPVal> FPVAL // Float or Double constant
970 %type <TypeVal> Types ResultTypes
971 %type <PrimType> IntType FPType PrimType // Classifications
972 %token <PrimType> VOID INTTYPE
973 %token <PrimType> FLOAT DOUBLE LABEL
976 %token<StrVal> LOCALVAR GLOBALVAR LABELSTR STRINGCONSTANT ATSTRINGCONSTANT
977 %type <StrVal> LocalName OptLocalName OptLocalAssign
978 %type <StrVal> GlobalName OptGlobalAssign
979 %type <UIntVal> OptAlign OptCAlign
980 %type <StrVal> OptSection SectionString
982 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
983 %token DECLARE DEFINE GLOBAL CONSTANT SECTION VOLATILE
984 %token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
985 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
986 %token OPAQUE EXTERNAL TARGET TRIPLE ALIGN
987 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
988 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
990 %type <UIntVal> OptCallingConv
991 %type <ParamAttrs> OptParamAttrs ParamAttr
992 %type <ParamAttrs> OptFuncAttrs FuncAttr
994 // Basic Block Terminating Operators
995 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
998 %type <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
999 %token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1000 %token <BinaryOpVal> SHL LSHR ASHR
1002 %token <OtherOpVal> ICMP FCMP
1003 %type <IPredicate> IPredicates
1004 %type <FPredicate> FPredicates
1005 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1006 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1008 // Memory Instructions
1009 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1012 %type <CastOpVal> CastOps
1013 %token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1014 %token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1017 %token <OtherOpVal> PHI_TOK SELECT VAARG
1018 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1020 // Function Attributes
1021 %token NORETURN INREG SRET
1023 // Visibility Styles
1024 %token DEFAULT HIDDEN
1030 // Operations that are notably excluded from this list include:
1031 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1033 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1034 LogicalOps : SHL | LSHR | ASHR | AND | OR | XOR;
1035 CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1036 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1039 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1040 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1041 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1042 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1043 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1047 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1048 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1049 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1050 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1051 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1052 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1053 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1054 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1055 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1058 // These are some types that allow classification if we only want a particular
1059 // thing... for example, only a signed, unsigned, or integral type.
1061 FPType : FLOAT | DOUBLE;
1063 LocalName : LOCALVAR | STRINGCONSTANT;
1064 OptLocalName : LocalName | /*empty*/ { $$ = 0; };
1066 /// OptLocalAssign - Value producing statements have an optional assignment
1068 OptLocalAssign : LocalName '=' {
1077 GlobalName : GLOBALVAR | ATSTRINGCONSTANT;
1079 OptGlobalAssign : GlobalName '=' {
1089 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1090 | WEAK { $$ = GlobalValue::WeakLinkage; }
1091 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1092 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1093 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1097 : DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1098 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1099 | EXTERNAL { $$ = GlobalValue::ExternalLinkage; }
1103 : /*empty*/ { $$ = GlobalValue::DefaultVisibility; }
1104 | HIDDEN { $$ = GlobalValue::HiddenVisibility; }
1107 FunctionDeclareLinkage
1108 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1109 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1110 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1113 FunctionDefineLinkage
1114 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1115 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1116 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1117 | WEAK { $$ = GlobalValue::WeakLinkage; }
1118 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1121 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1122 CCC_TOK { $$ = CallingConv::C; } |
1123 FASTCC_TOK { $$ = CallingConv::Fast; } |
1124 COLDCC_TOK { $$ = CallingConv::Cold; } |
1125 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1126 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1128 if ((unsigned)$2 != $2)
1129 GEN_ERROR("Calling conv too large!");
1134 ParamAttr : ZEXT { $$ = FunctionType::ZExtAttribute; }
1135 | SEXT { $$ = FunctionType::SExtAttribute; }
1136 | INREG { $$ = FunctionType::InRegAttribute; }
1137 | SRET { $$ = FunctionType::StructRetAttribute; }
1140 OptParamAttrs : /* empty */ { $$ = FunctionType::NoAttributeSet; }
1141 | OptParamAttrs ParamAttr {
1142 $$ = FunctionType::ParameterAttributes($1 | $2);
1146 FuncAttr : NORETURN { $$ = FunctionType::NoReturnAttribute; }
1150 OptFuncAttrs : /* empty */ { $$ = FunctionType::NoAttributeSet; }
1151 | OptFuncAttrs FuncAttr {
1152 $$ = FunctionType::ParameterAttributes($1 | $2);
1156 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1157 // a comma before it.
1158 OptAlign : /*empty*/ { $$ = 0; } |
1161 if ($$ != 0 && !isPowerOf2_32($$))
1162 GEN_ERROR("Alignment must be a power of two!");
1165 OptCAlign : /*empty*/ { $$ = 0; } |
1166 ',' ALIGN EUINT64VAL {
1168 if ($$ != 0 && !isPowerOf2_32($$))
1169 GEN_ERROR("Alignment must be a power of two!");
1174 SectionString : SECTION STRINGCONSTANT {
1175 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1176 if ($2[i] == '"' || $2[i] == '\\')
1177 GEN_ERROR("Invalid character in section name!");
1182 OptSection : /*empty*/ { $$ = 0; } |
1183 SectionString { $$ = $1; };
1185 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1186 // is set to be the global we are processing.
1188 GlobalVarAttributes : /* empty */ {} |
1189 ',' GlobalVarAttribute GlobalVarAttributes {};
1190 GlobalVarAttribute : SectionString {
1191 CurGV->setSection($1);
1195 | ALIGN EUINT64VAL {
1196 if ($2 != 0 && !isPowerOf2_32($2))
1197 GEN_ERROR("Alignment must be a power of two!");
1198 CurGV->setAlignment($2);
1202 //===----------------------------------------------------------------------===//
1203 // Types includes all predefined types... except void, because it can only be
1204 // used in specific contexts (function returning void for example).
1206 // Derived types are added later...
1208 PrimType : INTTYPE | FLOAT | DOUBLE | LABEL ;
1212 $$ = new PATypeHolder(OpaqueType::get());
1216 $$ = new PATypeHolder($1);
1219 | Types '*' { // Pointer type?
1220 if (*$1 == Type::LabelTy)
1221 GEN_ERROR("Cannot form a pointer to a basic block");
1222 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1226 | SymbolicValueRef { // Named types are also simple types...
1227 const Type* tmp = getTypeVal($1);
1229 $$ = new PATypeHolder(tmp);
1231 | '\\' EUINT64VAL { // Type UpReference
1232 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range!");
1233 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1234 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1235 $$ = new PATypeHolder(OT);
1236 UR_OUT("New Upreference!\n");
1239 | Types '(' ArgTypeListI ')' OptFuncAttrs {
1240 std::vector<const Type*> Params;
1241 std::vector<FunctionType::ParameterAttributes> Attrs;
1242 Attrs.push_back($5);
1243 for (TypeWithAttrsList::iterator I=$3->begin(), E=$3->end(); I != E; ++I) {
1244 Params.push_back(I->Ty->get());
1245 if (I->Ty->get() != Type::VoidTy)
1246 Attrs.push_back(I->Attrs);
1248 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1249 if (isVarArg) Params.pop_back();
1251 FunctionType *FT = FunctionType::get(*$1, Params, isVarArg, Attrs);
1252 delete $3; // Delete the argument list
1253 delete $1; // Delete the return type handle
1254 $$ = new PATypeHolder(HandleUpRefs(FT));
1257 | VOID '(' ArgTypeListI ')' OptFuncAttrs {
1258 std::vector<const Type*> Params;
1259 std::vector<FunctionType::ParameterAttributes> Attrs;
1260 Attrs.push_back($5);
1261 for (TypeWithAttrsList::iterator I=$3->begin(), E=$3->end(); I != E; ++I) {
1262 Params.push_back(I->Ty->get());
1263 if (I->Ty->get() != Type::VoidTy)
1264 Attrs.push_back(I->Attrs);
1266 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1267 if (isVarArg) Params.pop_back();
1269 FunctionType *FT = FunctionType::get($1, Params, isVarArg, Attrs);
1270 delete $3; // Delete the argument list
1271 $$ = new PATypeHolder(HandleUpRefs(FT));
1275 | '[' EUINT64VAL 'x' Types ']' { // Sized array type?
1276 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1280 | '<' EUINT64VAL 'x' Types '>' { // Packed array type?
1281 const llvm::Type* ElemTy = $4->get();
1282 if ((unsigned)$2 != $2)
1283 GEN_ERROR("Unsigned result not equal to signed result");
1284 if (!ElemTy->isFloatingPoint() && !ElemTy->isInteger())
1285 GEN_ERROR("Element type of a PackedType must be primitive");
1286 if (!isPowerOf2_32($2))
1287 GEN_ERROR("Vector length should be a power of 2!");
1288 $$ = new PATypeHolder(HandleUpRefs(PackedType::get(*$4, (unsigned)$2)));
1292 | '{' TypeListI '}' { // Structure type?
1293 std::vector<const Type*> Elements;
1294 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1295 E = $2->end(); I != E; ++I)
1296 Elements.push_back(*I);
1298 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1302 | '{' '}' { // Empty structure type?
1303 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1306 | '<' '{' TypeListI '}' '>' {
1307 std::vector<const Type*> Elements;
1308 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1309 E = $3->end(); I != E; ++I)
1310 Elements.push_back(*I);
1312 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1316 | '<' '{' '}' '>' { // Empty structure type?
1317 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1323 : Types OptParamAttrs {
1331 if (!UpRefs.empty())
1332 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1333 if (!(*$1)->isFirstClassType())
1334 GEN_ERROR("LLVM functions cannot return aggregate types!");
1338 $$ = new PATypeHolder(Type::VoidTy);
1342 ArgTypeList : ArgType {
1343 $$ = new TypeWithAttrsList();
1347 | ArgTypeList ',' ArgType {
1348 ($$=$1)->push_back($3);
1355 | ArgTypeList ',' DOTDOTDOT {
1357 TypeWithAttrs TWA; TWA.Attrs = FunctionType::NoAttributeSet;
1358 TWA.Ty = new PATypeHolder(Type::VoidTy);
1363 $$ = new TypeWithAttrsList;
1364 TypeWithAttrs TWA; TWA.Attrs = FunctionType::NoAttributeSet;
1365 TWA.Ty = new PATypeHolder(Type::VoidTy);
1370 $$ = new TypeWithAttrsList();
1374 // TypeList - Used for struct declarations and as a basis for function type
1375 // declaration type lists
1378 $$ = new std::list<PATypeHolder>();
1379 $$->push_back(*$1); delete $1;
1382 | TypeListI ',' Types {
1383 ($$=$1)->push_back(*$3); delete $3;
1387 // ConstVal - The various declarations that go into the constant pool. This
1388 // production is used ONLY to represent constants that show up AFTER a 'const',
1389 // 'constant' or 'global' token at global scope. Constants that can be inlined
1390 // into other expressions (such as integers and constexprs) are handled by the
1391 // ResolvedVal, ValueRef and ConstValueRef productions.
1393 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1394 if (!UpRefs.empty())
1395 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1396 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1398 GEN_ERROR("Cannot make array constant with type: '" +
1399 (*$1)->getDescription() + "'!");
1400 const Type *ETy = ATy->getElementType();
1401 int NumElements = ATy->getNumElements();
1403 // Verify that we have the correct size...
1404 if (NumElements != -1 && NumElements != (int)$3->size())
1405 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1406 utostr($3->size()) + " arguments, but has size of " +
1407 itostr(NumElements) + "!");
1409 // Verify all elements are correct type!
1410 for (unsigned i = 0; i < $3->size(); i++) {
1411 if (ETy != (*$3)[i]->getType())
1412 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1413 ETy->getDescription() +"' as required!\nIt is of type '"+
1414 (*$3)[i]->getType()->getDescription() + "'.");
1417 $$ = ConstantArray::get(ATy, *$3);
1418 delete $1; delete $3;
1422 if (!UpRefs.empty())
1423 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1424 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1426 GEN_ERROR("Cannot make array constant with type: '" +
1427 (*$1)->getDescription() + "'!");
1429 int NumElements = ATy->getNumElements();
1430 if (NumElements != -1 && NumElements != 0)
1431 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1432 " arguments, but has size of " + itostr(NumElements) +"!");
1433 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1437 | Types 'c' STRINGCONSTANT {
1438 if (!UpRefs.empty())
1439 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1440 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1442 GEN_ERROR("Cannot make array constant with type: '" +
1443 (*$1)->getDescription() + "'!");
1445 int NumElements = ATy->getNumElements();
1446 const Type *ETy = ATy->getElementType();
1447 char *EndStr = UnEscapeLexed($3, true);
1448 if (NumElements != -1 && NumElements != (EndStr-$3))
1449 GEN_ERROR("Can't build string constant of size " +
1450 itostr((int)(EndStr-$3)) +
1451 " when array has size " + itostr(NumElements) + "!");
1452 std::vector<Constant*> Vals;
1453 if (ETy == Type::Int8Ty) {
1454 for (unsigned char *C = (unsigned char *)$3;
1455 C != (unsigned char*)EndStr; ++C)
1456 Vals.push_back(ConstantInt::get(ETy, *C));
1459 GEN_ERROR("Cannot build string arrays of non byte sized elements!");
1462 $$ = ConstantArray::get(ATy, Vals);
1466 | Types '<' ConstVector '>' { // Nonempty unsized arr
1467 if (!UpRefs.empty())
1468 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1469 const PackedType *PTy = dyn_cast<PackedType>($1->get());
1471 GEN_ERROR("Cannot make packed constant with type: '" +
1472 (*$1)->getDescription() + "'!");
1473 const Type *ETy = PTy->getElementType();
1474 int NumElements = PTy->getNumElements();
1476 // Verify that we have the correct size...
1477 if (NumElements != -1 && NumElements != (int)$3->size())
1478 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1479 utostr($3->size()) + " arguments, but has size of " +
1480 itostr(NumElements) + "!");
1482 // Verify all elements are correct type!
1483 for (unsigned i = 0; i < $3->size(); i++) {
1484 if (ETy != (*$3)[i]->getType())
1485 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1486 ETy->getDescription() +"' as required!\nIt is of type '"+
1487 (*$3)[i]->getType()->getDescription() + "'.");
1490 $$ = ConstantPacked::get(PTy, *$3);
1491 delete $1; delete $3;
1494 | Types '{' ConstVector '}' {
1495 const StructType *STy = dyn_cast<StructType>($1->get());
1497 GEN_ERROR("Cannot make struct constant with type: '" +
1498 (*$1)->getDescription() + "'!");
1500 if ($3->size() != STy->getNumContainedTypes())
1501 GEN_ERROR("Illegal number of initializers for structure type!");
1503 // Check to ensure that constants are compatible with the type initializer!
1504 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1505 if ((*$3)[i]->getType() != STy->getElementType(i))
1506 GEN_ERROR("Expected type '" +
1507 STy->getElementType(i)->getDescription() +
1508 "' for element #" + utostr(i) +
1509 " of structure initializer!");
1511 // Check to ensure that Type is not packed
1512 if (STy->isPacked())
1513 GEN_ERROR("Unpacked Initializer to packed type '" + STy->getDescription() + "'");
1515 $$ = ConstantStruct::get(STy, *$3);
1516 delete $1; delete $3;
1520 if (!UpRefs.empty())
1521 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1522 const StructType *STy = dyn_cast<StructType>($1->get());
1524 GEN_ERROR("Cannot make struct constant with type: '" +
1525 (*$1)->getDescription() + "'!");
1527 if (STy->getNumContainedTypes() != 0)
1528 GEN_ERROR("Illegal number of initializers for structure type!");
1530 // Check to ensure that Type is not packed
1531 if (STy->isPacked())
1532 GEN_ERROR("Unpacked Initializer to packed type '" + STy->getDescription() + "'");
1534 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1538 | Types '<' '{' ConstVector '}' '>' {
1539 const StructType *STy = dyn_cast<StructType>($1->get());
1541 GEN_ERROR("Cannot make struct constant with type: '" +
1542 (*$1)->getDescription() + "'!");
1544 if ($4->size() != STy->getNumContainedTypes())
1545 GEN_ERROR("Illegal number of initializers for structure type!");
1547 // Check to ensure that constants are compatible with the type initializer!
1548 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1549 if ((*$4)[i]->getType() != STy->getElementType(i))
1550 GEN_ERROR("Expected type '" +
1551 STy->getElementType(i)->getDescription() +
1552 "' for element #" + utostr(i) +
1553 " of structure initializer!");
1555 // Check to ensure that Type is packed
1556 if (!STy->isPacked())
1557 GEN_ERROR("Packed Initializer to unpacked type '" + STy->getDescription() + "'");
1559 $$ = ConstantStruct::get(STy, *$4);
1560 delete $1; delete $4;
1563 | Types '<' '{' '}' '>' {
1564 if (!UpRefs.empty())
1565 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1566 const StructType *STy = dyn_cast<StructType>($1->get());
1568 GEN_ERROR("Cannot make struct constant with type: '" +
1569 (*$1)->getDescription() + "'!");
1571 if (STy->getNumContainedTypes() != 0)
1572 GEN_ERROR("Illegal number of initializers for structure type!");
1574 // Check to ensure that Type is packed
1575 if (!STy->isPacked())
1576 GEN_ERROR("Packed Initializer to unpacked type '" + STy->getDescription() + "'");
1578 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1583 if (!UpRefs.empty())
1584 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1585 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1587 GEN_ERROR("Cannot make null pointer constant with type: '" +
1588 (*$1)->getDescription() + "'!");
1590 $$ = ConstantPointerNull::get(PTy);
1595 if (!UpRefs.empty())
1596 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1597 $$ = UndefValue::get($1->get());
1601 | Types SymbolicValueRef {
1602 if (!UpRefs.empty())
1603 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1604 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1606 GEN_ERROR("Global const reference must be a pointer type!");
1608 // ConstExprs can exist in the body of a function, thus creating
1609 // GlobalValues whenever they refer to a variable. Because we are in
1610 // the context of a function, getValNonImprovising will search the functions
1611 // symbol table instead of the module symbol table for the global symbol,
1612 // which throws things all off. To get around this, we just tell
1613 // getValNonImprovising that we are at global scope here.
1615 Function *SavedCurFn = CurFun.CurrentFunction;
1616 CurFun.CurrentFunction = 0;
1618 Value *V = getValNonImprovising(Ty, $2);
1621 CurFun.CurrentFunction = SavedCurFn;
1623 // If this is an initializer for a constant pointer, which is referencing a
1624 // (currently) undefined variable, create a stub now that shall be replaced
1625 // in the future with the right type of variable.
1628 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1629 const PointerType *PT = cast<PointerType>(Ty);
1631 // First check to see if the forward references value is already created!
1632 PerModuleInfo::GlobalRefsType::iterator I =
1633 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1635 if (I != CurModule.GlobalRefs.end()) {
1636 V = I->second; // Placeholder already exists, use it...
1640 if ($2.Type == ValID::GlobalName)
1642 else if ($2.Type != ValID::GlobalID)
1643 GEN_ERROR("Invalid reference to global");
1645 // Create the forward referenced global.
1647 if (const FunctionType *FTy =
1648 dyn_cast<FunctionType>(PT->getElementType())) {
1649 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1650 CurModule.CurrentModule);
1652 GV = new GlobalVariable(PT->getElementType(), false,
1653 GlobalValue::ExternalLinkage, 0,
1654 Name, CurModule.CurrentModule);
1657 // Keep track of the fact that we have a forward ref to recycle it
1658 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1663 $$ = cast<GlobalValue>(V);
1664 delete $1; // Free the type handle
1668 if (!UpRefs.empty())
1669 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1670 if ($1->get() != $2->getType())
1671 GEN_ERROR("Mismatched types for constant expression: " +
1672 (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1677 | Types ZEROINITIALIZER {
1678 if (!UpRefs.empty())
1679 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1680 const Type *Ty = $1->get();
1681 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1682 GEN_ERROR("Cannot create a null initialized value of this type!");
1683 $$ = Constant::getNullValue(Ty);
1687 | IntType ESINT64VAL { // integral constants
1688 if (!ConstantInt::isValueValidForType($1, $2))
1689 GEN_ERROR("Constant value doesn't fit in type!");
1690 $$ = ConstantInt::get($1, $2);
1693 | IntType EUINT64VAL { // integral constants
1694 if (!ConstantInt::isValueValidForType($1, $2))
1695 GEN_ERROR("Constant value doesn't fit in type!");
1696 $$ = ConstantInt::get($1, $2);
1699 | INTTYPE TRUETOK { // Boolean constants
1700 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1701 $$ = ConstantInt::getTrue();
1704 | INTTYPE FALSETOK { // Boolean constants
1705 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1706 $$ = ConstantInt::getFalse();
1709 | FPType FPVAL { // Float & Double constants
1710 if (!ConstantFP::isValueValidForType($1, $2))
1711 GEN_ERROR("Floating point constant invalid for type!!");
1712 $$ = ConstantFP::get($1, $2);
1717 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1718 if (!UpRefs.empty())
1719 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1721 const Type *DestTy = $5->get();
1722 if (!CastInst::castIsValid($1, $3, DestTy))
1723 GEN_ERROR("invalid cast opcode for cast from '" +
1724 Val->getType()->getDescription() + "' to '" +
1725 DestTy->getDescription() + "'!");
1726 $$ = ConstantExpr::getCast($1, $3, DestTy);
1729 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1730 if (!isa<PointerType>($3->getType()))
1731 GEN_ERROR("GetElementPtr requires a pointer operand!");
1734 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1736 GEN_ERROR("Index list invalid for constant getelementptr!");
1738 SmallVector<Constant*, 8> IdxVec;
1739 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1740 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1741 IdxVec.push_back(C);
1743 GEN_ERROR("Indices to constant getelementptr must be constants!");
1747 $$ = ConstantExpr::getGetElementPtr($3, &IdxVec[0], IdxVec.size());
1750 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1751 if ($3->getType() != Type::Int1Ty)
1752 GEN_ERROR("Select condition must be of boolean type!");
1753 if ($5->getType() != $7->getType())
1754 GEN_ERROR("Select operand types must match!");
1755 $$ = ConstantExpr::getSelect($3, $5, $7);
1758 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1759 if ($3->getType() != $5->getType())
1760 GEN_ERROR("Binary operator types must match!");
1762 $$ = ConstantExpr::get($1, $3, $5);
1764 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1765 if ($3->getType() != $5->getType())
1766 GEN_ERROR("Logical operator types must match!");
1767 if (!$3->getType()->isInteger()) {
1768 if (Instruction::isShift($1) || !isa<PackedType>($3->getType()) ||
1769 !cast<PackedType>($3->getType())->getElementType()->isInteger())
1770 GEN_ERROR("Logical operator requires integral operands!");
1772 $$ = ConstantExpr::get($1, $3, $5);
1775 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1776 if ($4->getType() != $6->getType())
1777 GEN_ERROR("icmp operand types must match!");
1778 $$ = ConstantExpr::getICmp($2, $4, $6);
1780 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1781 if ($4->getType() != $6->getType())
1782 GEN_ERROR("fcmp operand types must match!");
1783 $$ = ConstantExpr::getFCmp($2, $4, $6);
1785 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1786 if (!ExtractElementInst::isValidOperands($3, $5))
1787 GEN_ERROR("Invalid extractelement operands!");
1788 $$ = ConstantExpr::getExtractElement($3, $5);
1791 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1792 if (!InsertElementInst::isValidOperands($3, $5, $7))
1793 GEN_ERROR("Invalid insertelement operands!");
1794 $$ = ConstantExpr::getInsertElement($3, $5, $7);
1797 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1798 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1799 GEN_ERROR("Invalid shufflevector operands!");
1800 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1805 // ConstVector - A list of comma separated constants.
1806 ConstVector : ConstVector ',' ConstVal {
1807 ($$ = $1)->push_back($3);
1811 $$ = new std::vector<Constant*>();
1817 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1818 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1821 //===----------------------------------------------------------------------===//
1822 // Rules to match Modules
1823 //===----------------------------------------------------------------------===//
1825 // Module rule: Capture the result of parsing the whole file into a result
1830 $$ = ParserResult = CurModule.CurrentModule;
1831 CurModule.ModuleDone();
1835 $$ = ParserResult = CurModule.CurrentModule;
1836 CurModule.ModuleDone();
1843 | DefinitionList Definition
1847 : DEFINE { CurFun.isDeclare = false; } Function {
1848 CurFun.FunctionDone();
1851 | DECLARE { CurFun.isDeclare = true; } FunctionProto {
1854 | MODULE ASM_TOK AsmBlock {
1858 // Emit an error if there are any unresolved types left.
1859 if (!CurModule.LateResolveTypes.empty()) {
1860 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
1861 if (DID.Type == ValID::LocalName) {
1862 GEN_ERROR("Reference to an undefined type: '"+DID.getName() + "'");
1864 GEN_ERROR("Reference to an undefined type: #" + itostr(DID.Num));
1869 | OptLocalAssign TYPE Types {
1870 if (!UpRefs.empty())
1871 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
1872 // Eagerly resolve types. This is not an optimization, this is a
1873 // requirement that is due to the fact that we could have this:
1875 // %list = type { %list * }
1876 // %list = type { %list * } ; repeated type decl
1878 // If types are not resolved eagerly, then the two types will not be
1879 // determined to be the same type!
1881 ResolveTypeTo($1, *$3);
1883 if (!setTypeName(*$3, $1) && !$1) {
1885 // If this is a named type that is not a redefinition, add it to the slot
1887 CurModule.Types.push_back(*$3);
1893 | OptLocalAssign TYPE VOID {
1894 ResolveTypeTo($1, $3);
1896 if (!setTypeName($3, $1) && !$1) {
1898 // If this is a named type that is not a redefinition, add it to the slot
1900 CurModule.Types.push_back($3);
1904 | OptGlobalAssign GVVisibilityStyle GlobalType ConstVal {
1905 /* "Externally Visible" Linkage */
1907 GEN_ERROR("Global value initializer is not a constant!");
1908 CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
1909 $2, $3, $4->getType(), $4);
1911 } GlobalVarAttributes {
1914 | OptGlobalAssign GVInternalLinkage GVVisibilityStyle GlobalType ConstVal {
1916 GEN_ERROR("Global value initializer is not a constant!");
1917 CurGV = ParseGlobalVariable($1, $2, $3, $4, $5->getType(), $5);
1919 } GlobalVarAttributes {
1922 | OptGlobalAssign GVExternalLinkage GVVisibilityStyle GlobalType Types {
1923 if (!UpRefs.empty())
1924 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1925 CurGV = ParseGlobalVariable($1, $2, $3, $4, *$5, 0);
1928 } GlobalVarAttributes {
1932 | TARGET TargetDefinition {
1935 | DEPLIBS '=' LibrariesDefinition {
1941 AsmBlock : STRINGCONSTANT {
1942 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
1943 char *EndStr = UnEscapeLexed($1, true);
1944 std::string NewAsm($1, EndStr);
1947 if (AsmSoFar.empty())
1948 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
1950 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
1954 TargetDefinition : TRIPLE '=' STRINGCONSTANT {
1955 CurModule.CurrentModule->setTargetTriple($3);
1958 | DATALAYOUT '=' STRINGCONSTANT {
1959 CurModule.CurrentModule->setDataLayout($3);
1963 LibrariesDefinition : '[' LibList ']';
1965 LibList : LibList ',' STRINGCONSTANT {
1966 CurModule.CurrentModule->addLibrary($3);
1971 CurModule.CurrentModule->addLibrary($1);
1975 | /* empty: end of list */ {
1980 //===----------------------------------------------------------------------===//
1981 // Rules to match Function Headers
1982 //===----------------------------------------------------------------------===//
1984 ArgListH : ArgListH ',' Types OptParamAttrs OptLocalName {
1985 if (!UpRefs.empty())
1986 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
1987 if (*$3 == Type::VoidTy)
1988 GEN_ERROR("void typed arguments are invalid!");
1989 ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
1994 | Types OptParamAttrs OptLocalName {
1995 if (!UpRefs.empty())
1996 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1997 if (*$1 == Type::VoidTy)
1998 GEN_ERROR("void typed arguments are invalid!");
1999 ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2000 $$ = new ArgListType;
2005 ArgList : ArgListH {
2009 | ArgListH ',' DOTDOTDOT {
2011 struct ArgListEntry E;
2012 E.Ty = new PATypeHolder(Type::VoidTy);
2014 E.Attrs = FunctionType::NoAttributeSet;
2019 $$ = new ArgListType;
2020 struct ArgListEntry E;
2021 E.Ty = new PATypeHolder(Type::VoidTy);
2023 E.Attrs = FunctionType::NoAttributeSet;
2032 FunctionHeaderH : OptCallingConv ResultTypes GlobalName '(' ArgList ')'
2033 OptFuncAttrs OptSection OptAlign {
2035 std::string FunctionName($3);
2036 free($3); // Free strdup'd memory!
2038 // Check the function result for abstractness if this is a define. We should
2039 // have no abstract types at this point
2040 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($2))
2041 GEN_ERROR("Reference to abstract result: "+ $2->get()->getDescription());
2043 std::vector<const Type*> ParamTypeList;
2044 std::vector<FunctionType::ParameterAttributes> ParamAttrs;
2045 ParamAttrs.push_back($7);
2046 if ($5) { // If there are arguments...
2047 for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I) {
2048 const Type* Ty = I->Ty->get();
2049 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2050 GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2051 ParamTypeList.push_back(Ty);
2052 if (Ty != Type::VoidTy)
2053 ParamAttrs.push_back(I->Attrs);
2057 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2058 if (isVarArg) ParamTypeList.pop_back();
2060 FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg,
2062 const PointerType *PFT = PointerType::get(FT);
2066 if (!FunctionName.empty()) {
2067 ID = ValID::createGlobalName((char*)FunctionName.c_str());
2069 ID = ValID::createGlobalID(CurModule.Values[PFT].size());
2073 // See if this function was forward referenced. If so, recycle the object.
2074 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2075 // Move the function to the end of the list, from whereever it was
2076 // previously inserted.
2077 Fn = cast<Function>(FWRef);
2078 CurModule.CurrentModule->getFunctionList().remove(Fn);
2079 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2080 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2081 (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
2082 // If this is the case, either we need to be a forward decl, or it needs
2084 if (!CurFun.isDeclare && !Fn->isDeclaration())
2085 GEN_ERROR("Redefinition of function '" + FunctionName + "'!");
2087 // Make sure to strip off any argument names so we can't get conflicts.
2088 if (Fn->isDeclaration())
2089 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2092 } else { // Not already defined?
2093 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
2094 CurModule.CurrentModule);
2096 InsertValue(Fn, CurModule.Values);
2099 CurFun.FunctionStart(Fn);
2101 if (CurFun.isDeclare) {
2102 // If we have declaration, always overwrite linkage. This will allow us to
2103 // correctly handle cases, when pointer to function is passed as argument to
2104 // another function.
2105 Fn->setLinkage(CurFun.Linkage);
2106 Fn->setVisibility(CurFun.Visibility);
2108 Fn->setCallingConv($1);
2109 Fn->setAlignment($9);
2115 // Add all of the arguments we parsed to the function...
2116 if ($5) { // Is null if empty...
2117 if (isVarArg) { // Nuke the last entry
2118 assert($5->back().Ty->get() == Type::VoidTy && $5->back().Name == 0&&
2119 "Not a varargs marker!");
2120 delete $5->back().Ty;
2121 $5->pop_back(); // Delete the last entry
2123 Function::arg_iterator ArgIt = Fn->arg_begin();
2125 for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I, ++ArgIt) {
2126 delete I->Ty; // Delete the typeholder...
2127 setValueName(ArgIt, I->Name); // Insert arg into symtab...
2133 delete $5; // We're now done with the argument list
2138 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2140 FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2141 $$ = CurFun.CurrentFunction;
2143 // Make sure that we keep track of the linkage type even if there was a
2144 // previous "declare".
2146 $$->setVisibility($2);
2149 END : ENDTOK | '}'; // Allow end of '}' to end a function
2151 Function : BasicBlockList END {
2156 FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2157 CurFun.CurrentFunction->setLinkage($1);
2158 CurFun.CurrentFunction->setVisibility($2);
2159 $$ = CurFun.CurrentFunction;
2160 CurFun.FunctionDone();
2164 //===----------------------------------------------------------------------===//
2165 // Rules to match Basic Blocks
2166 //===----------------------------------------------------------------------===//
2168 OptSideEffect : /* empty */ {
2177 ConstValueRef : ESINT64VAL { // A reference to a direct constant
2178 $$ = ValID::create($1);
2182 $$ = ValID::create($1);
2185 | FPVAL { // Perhaps it's an FP constant?
2186 $$ = ValID::create($1);
2190 $$ = ValID::create(ConstantInt::getTrue());
2194 $$ = ValID::create(ConstantInt::getFalse());
2198 $$ = ValID::createNull();
2202 $$ = ValID::createUndef();
2205 | ZEROINITIALIZER { // A vector zero constant.
2206 $$ = ValID::createZeroInit();
2209 | '<' ConstVector '>' { // Nonempty unsized packed vector
2210 const Type *ETy = (*$2)[0]->getType();
2211 int NumElements = $2->size();
2213 PackedType* pt = PackedType::get(ETy, NumElements);
2214 PATypeHolder* PTy = new PATypeHolder(
2222 // Verify all elements are correct type!
2223 for (unsigned i = 0; i < $2->size(); i++) {
2224 if (ETy != (*$2)[i]->getType())
2225 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2226 ETy->getDescription() +"' as required!\nIt is of type '" +
2227 (*$2)[i]->getType()->getDescription() + "'.");
2230 $$ = ValID::create(ConstantPacked::get(pt, *$2));
2231 delete PTy; delete $2;
2235 $$ = ValID::create($1);
2238 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2239 char *End = UnEscapeLexed($3, true);
2240 std::string AsmStr = std::string($3, End);
2241 End = UnEscapeLexed($5, true);
2242 std::string Constraints = std::string($5, End);
2243 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2249 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2252 SymbolicValueRef : LOCALVAL_ID { // Is it an integer reference...?
2253 $$ = ValID::createLocalID($1);
2257 $$ = ValID::createGlobalID($1);
2260 | LocalName { // Is it a named reference...?
2261 $$ = ValID::createLocalName($1);
2264 | GlobalName { // Is it a named reference...?
2265 $$ = ValID::createGlobalName($1);
2269 // ValueRef - A reference to a definition... either constant or symbolic
2270 ValueRef : SymbolicValueRef | ConstValueRef;
2273 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2274 // type immediately preceeds the value reference, and allows complex constant
2275 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2276 ResolvedVal : Types ValueRef {
2277 if (!UpRefs.empty())
2278 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2279 $$ = getVal(*$1, $2);
2285 BasicBlockList : BasicBlockList BasicBlock {
2289 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2295 // Basic blocks are terminated by branching instructions:
2296 // br, br/cc, switch, ret
2298 BasicBlock : InstructionList OptLocalAssign BBTerminatorInst {
2299 setValueName($3, $2);
2303 $1->getInstList().push_back($3);
2309 InstructionList : InstructionList Inst {
2310 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2311 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2312 if (CI2->getParent() == 0)
2313 $1->getInstList().push_back(CI2);
2314 $1->getInstList().push_back($2);
2319 $$ = getBBVal(ValID::createLocalID(CurFun.NextBBNum++), true);
2322 // Make sure to move the basic block to the correct location in the
2323 // function, instead of leaving it inserted wherever it was first
2325 Function::BasicBlockListType &BBL =
2326 CurFun.CurrentFunction->getBasicBlockList();
2327 BBL.splice(BBL.end(), BBL, $$);
2331 $$ = getBBVal(ValID::createLocalName($1), true);
2334 // Make sure to move the basic block to the correct location in the
2335 // function, instead of leaving it inserted wherever it was first
2337 Function::BasicBlockListType &BBL =
2338 CurFun.CurrentFunction->getBasicBlockList();
2339 BBL.splice(BBL.end(), BBL, $$);
2343 BBTerminatorInst : RET ResolvedVal { // Return with a result...
2344 $$ = new ReturnInst($2);
2347 | RET VOID { // Return with no result...
2348 $$ = new ReturnInst();
2351 | BR LABEL ValueRef { // Unconditional Branch...
2352 BasicBlock* tmpBB = getBBVal($3);
2354 $$ = new BranchInst(tmpBB);
2355 } // Conditional Branch...
2356 | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2357 assert(cast<IntegerType>($2)->getBitWidth() == 1 && "Not Bool?");
2358 BasicBlock* tmpBBA = getBBVal($6);
2360 BasicBlock* tmpBBB = getBBVal($9);
2362 Value* tmpVal = getVal(Type::Int1Ty, $3);
2364 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2366 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2367 Value* tmpVal = getVal($2, $3);
2369 BasicBlock* tmpBB = getBBVal($6);
2371 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2374 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2376 for (; I != E; ++I) {
2377 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2378 S->addCase(CI, I->second);
2380 GEN_ERROR("Switch case is constant, but not a simple integer!");
2385 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2386 Value* tmpVal = getVal($2, $3);
2388 BasicBlock* tmpBB = getBBVal($6);
2390 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2394 | INVOKE OptCallingConv ResultTypes ValueRef '(' ValueRefList ')' OptFuncAttrs
2395 TO LABEL ValueRef UNWIND LABEL ValueRef {
2397 // Handle the short syntax
2398 const PointerType *PFTy = 0;
2399 const FunctionType *Ty = 0;
2400 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2401 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2402 // Pull out the types of all of the arguments...
2403 std::vector<const Type*> ParamTypes;
2404 FunctionType::ParamAttrsList ParamAttrs;
2405 ParamAttrs.push_back($8);
2406 for (ValueRefList::iterator I = $6->begin(), E = $6->end(); I != E; ++I) {
2407 const Type *Ty = I->Val->getType();
2408 if (Ty == Type::VoidTy)
2409 GEN_ERROR("Short call syntax cannot be used with varargs");
2410 ParamTypes.push_back(Ty);
2411 ParamAttrs.push_back(I->Attrs);
2414 Ty = FunctionType::get($3->get(), ParamTypes, false, ParamAttrs);
2415 PFTy = PointerType::get(Ty);
2418 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2420 BasicBlock *Normal = getBBVal($11);
2422 BasicBlock *Except = getBBVal($14);
2425 // Check the arguments
2427 if ($6->empty()) { // Has no arguments?
2428 // Make sure no arguments is a good thing!
2429 if (Ty->getNumParams() != 0)
2430 GEN_ERROR("No arguments passed to a function that "
2431 "expects arguments!");
2432 } else { // Has arguments?
2433 // Loop through FunctionType's arguments and ensure they are specified
2435 FunctionType::param_iterator I = Ty->param_begin();
2436 FunctionType::param_iterator E = Ty->param_end();
2437 ValueRefList::iterator ArgI = $6->begin(), ArgE = $6->end();
2439 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2440 if (ArgI->Val->getType() != *I)
2441 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2442 (*I)->getDescription() + "'!");
2443 Args.push_back(ArgI->Val);
2446 if (Ty->isVarArg()) {
2448 for (; ArgI != ArgE; ++ArgI)
2449 Args.push_back(ArgI->Val); // push the remaining varargs
2450 } else if (I != E || ArgI != ArgE)
2451 GEN_ERROR("Invalid number of parameters detected!");
2454 // Create the InvokeInst
2455 InvokeInst *II = new InvokeInst(V, Normal, Except, Args);
2456 II->setCallingConv($2);
2462 $$ = new UnwindInst();
2466 $$ = new UnreachableInst();
2472 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2474 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
2477 GEN_ERROR("May only switch on a constant pool value!");
2479 BasicBlock* tmpBB = getBBVal($6);
2481 $$->push_back(std::make_pair(V, tmpBB));
2483 | IntType ConstValueRef ',' LABEL ValueRef {
2484 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2485 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
2489 GEN_ERROR("May only switch on a constant pool value!");
2491 BasicBlock* tmpBB = getBBVal($5);
2493 $$->push_back(std::make_pair(V, tmpBB));
2496 Inst : OptLocalAssign InstVal {
2497 // Is this definition named?? if so, assign the name...
2498 setValueName($2, $1);
2505 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2506 if (!UpRefs.empty())
2507 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2508 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2509 Value* tmpVal = getVal(*$1, $3);
2511 BasicBlock* tmpBB = getBBVal($5);
2513 $$->push_back(std::make_pair(tmpVal, tmpBB));
2516 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2518 Value* tmpVal = getVal($1->front().first->getType(), $4);
2520 BasicBlock* tmpBB = getBBVal($6);
2522 $1->push_back(std::make_pair(tmpVal, tmpBB));
2526 ValueRefList : Types ValueRef OptParamAttrs {
2527 if (!UpRefs.empty())
2528 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2529 // Used for call and invoke instructions
2530 $$ = new ValueRefList();
2531 ValueRefListEntry E; E.Attrs = $3; E.Val = getVal($1->get(), $2);
2534 | ValueRefList ',' Types ValueRef OptParamAttrs {
2535 if (!UpRefs.empty())
2536 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2538 ValueRefListEntry E; E.Attrs = $5; E.Val = getVal($3->get(), $4);
2542 | /*empty*/ { $$ = new ValueRefList(); };
2544 IndexList // Used for gep instructions and constant expressions
2545 : /*empty*/ { $$ = new std::vector<Value*>(); }
2546 | IndexList ',' ResolvedVal {
2553 OptTailCall : TAIL CALL {
2562 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2563 if (!UpRefs.empty())
2564 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2565 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
2566 !isa<PackedType>((*$2).get()))
2568 "Arithmetic operator requires integer, FP, or packed operands!");
2569 if (isa<PackedType>((*$2).get()) &&
2570 ($1 == Instruction::URem ||
2571 $1 == Instruction::SRem ||
2572 $1 == Instruction::FRem))
2573 GEN_ERROR("U/S/FRem not supported on packed types!");
2574 Value* val1 = getVal(*$2, $3);
2576 Value* val2 = getVal(*$2, $5);
2578 $$ = BinaryOperator::create($1, val1, val2);
2580 GEN_ERROR("binary operator returned null!");
2583 | LogicalOps Types ValueRef ',' ValueRef {
2584 if (!UpRefs.empty())
2585 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2586 if (!(*$2)->isInteger()) {
2587 if (Instruction::isShift($1) || !isa<PackedType>($2->get()) ||
2588 !cast<PackedType>($2->get())->getElementType()->isInteger())
2589 GEN_ERROR("Logical operator requires integral operands!");
2591 Value* tmpVal1 = getVal(*$2, $3);
2593 Value* tmpVal2 = getVal(*$2, $5);
2595 $$ = BinaryOperator::create($1, tmpVal1, tmpVal2);
2597 GEN_ERROR("binary operator returned null!");
2600 | ICMP IPredicates Types ValueRef ',' ValueRef {
2601 if (!UpRefs.empty())
2602 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2603 if (isa<PackedType>((*$3).get()))
2604 GEN_ERROR("Packed types not supported by icmp instruction");
2605 Value* tmpVal1 = getVal(*$3, $4);
2607 Value* tmpVal2 = getVal(*$3, $6);
2609 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2611 GEN_ERROR("icmp operator returned null!");
2613 | FCMP FPredicates Types ValueRef ',' ValueRef {
2614 if (!UpRefs.empty())
2615 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2616 if (isa<PackedType>((*$3).get()))
2617 GEN_ERROR("Packed types not supported by fcmp instruction");
2618 Value* tmpVal1 = getVal(*$3, $4);
2620 Value* tmpVal2 = getVal(*$3, $6);
2622 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2624 GEN_ERROR("fcmp operator returned null!");
2626 | CastOps ResolvedVal TO Types {
2627 if (!UpRefs.empty())
2628 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2630 const Type* DestTy = $4->get();
2631 if (!CastInst::castIsValid($1, Val, DestTy))
2632 GEN_ERROR("invalid cast opcode for cast from '" +
2633 Val->getType()->getDescription() + "' to '" +
2634 DestTy->getDescription() + "'!");
2635 $$ = CastInst::create($1, Val, DestTy);
2638 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2639 if ($2->getType() != Type::Int1Ty)
2640 GEN_ERROR("select condition must be boolean!");
2641 if ($4->getType() != $6->getType())
2642 GEN_ERROR("select value types should match!");
2643 $$ = new SelectInst($2, $4, $6);
2646 | VAARG ResolvedVal ',' Types {
2647 if (!UpRefs.empty())
2648 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2649 $$ = new VAArgInst($2, *$4);
2653 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2654 if (!ExtractElementInst::isValidOperands($2, $4))
2655 GEN_ERROR("Invalid extractelement operands!");
2656 $$ = new ExtractElementInst($2, $4);
2659 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2660 if (!InsertElementInst::isValidOperands($2, $4, $6))
2661 GEN_ERROR("Invalid insertelement operands!");
2662 $$ = new InsertElementInst($2, $4, $6);
2665 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2666 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
2667 GEN_ERROR("Invalid shufflevector operands!");
2668 $$ = new ShuffleVectorInst($2, $4, $6);
2672 const Type *Ty = $2->front().first->getType();
2673 if (!Ty->isFirstClassType())
2674 GEN_ERROR("PHI node operands must be of first class type!");
2675 $$ = new PHINode(Ty);
2676 ((PHINode*)$$)->reserveOperandSpace($2->size());
2677 while ($2->begin() != $2->end()) {
2678 if ($2->front().first->getType() != Ty)
2679 GEN_ERROR("All elements of a PHI node must be of the same type!");
2680 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2683 delete $2; // Free the list...
2686 | OptTailCall OptCallingConv ResultTypes ValueRef '(' ValueRefList ')'
2689 // Handle the short syntax
2690 const PointerType *PFTy = 0;
2691 const FunctionType *Ty = 0;
2692 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2693 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2694 // Pull out the types of all of the arguments...
2695 std::vector<const Type*> ParamTypes;
2696 FunctionType::ParamAttrsList ParamAttrs;
2697 ParamAttrs.push_back($8);
2698 for (ValueRefList::iterator I = $6->begin(), E = $6->end(); I != E; ++I) {
2699 const Type *Ty = I->Val->getType();
2700 if (Ty == Type::VoidTy)
2701 GEN_ERROR("Short call syntax cannot be used with varargs");
2702 ParamTypes.push_back(Ty);
2703 ParamAttrs.push_back(I->Attrs);
2706 Ty = FunctionType::get($3->get(), ParamTypes, false, ParamAttrs);
2707 PFTy = PointerType::get(Ty);
2710 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2713 // Check the arguments
2715 if ($6->empty()) { // Has no arguments?
2716 // Make sure no arguments is a good thing!
2717 if (Ty->getNumParams() != 0)
2718 GEN_ERROR("No arguments passed to a function that "
2719 "expects arguments!");
2720 } else { // Has arguments?
2721 // Loop through FunctionType's arguments and ensure they are specified
2724 FunctionType::param_iterator I = Ty->param_begin();
2725 FunctionType::param_iterator E = Ty->param_end();
2726 ValueRefList::iterator ArgI = $6->begin(), ArgE = $6->end();
2728 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2729 if (ArgI->Val->getType() != *I)
2730 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2731 (*I)->getDescription() + "'!");
2732 Args.push_back(ArgI->Val);
2734 if (Ty->isVarArg()) {
2736 for (; ArgI != ArgE; ++ArgI)
2737 Args.push_back(ArgI->Val); // push the remaining varargs
2738 } else if (I != E || ArgI != ArgE)
2739 GEN_ERROR("Invalid number of parameters detected!");
2741 // Create the call node
2742 CallInst *CI = new CallInst(V, Args);
2743 CI->setTailCall($1);
2744 CI->setCallingConv($2);
2755 OptVolatile : VOLATILE {
2766 MemoryInst : MALLOC Types OptCAlign {
2767 if (!UpRefs.empty())
2768 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2769 $$ = new MallocInst(*$2, 0, $3);
2773 | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
2774 if (!UpRefs.empty())
2775 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2776 Value* tmpVal = getVal($4, $5);
2778 $$ = new MallocInst(*$2, tmpVal, $6);
2781 | ALLOCA Types OptCAlign {
2782 if (!UpRefs.empty())
2783 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2784 $$ = new AllocaInst(*$2, 0, $3);
2788 | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
2789 if (!UpRefs.empty())
2790 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2791 Value* tmpVal = getVal($4, $5);
2793 $$ = new AllocaInst(*$2, tmpVal, $6);
2796 | FREE ResolvedVal {
2797 if (!isa<PointerType>($2->getType()))
2798 GEN_ERROR("Trying to free nonpointer type " +
2799 $2->getType()->getDescription() + "!");
2800 $$ = new FreeInst($2);
2804 | OptVolatile LOAD Types ValueRef {
2805 if (!UpRefs.empty())
2806 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2807 if (!isa<PointerType>($3->get()))
2808 GEN_ERROR("Can't load from nonpointer type: " +
2809 (*$3)->getDescription());
2810 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
2811 GEN_ERROR("Can't load from pointer of non-first-class type: " +
2812 (*$3)->getDescription());
2813 Value* tmpVal = getVal(*$3, $4);
2815 $$ = new LoadInst(tmpVal, "", $1);
2818 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2819 if (!UpRefs.empty())
2820 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
2821 const PointerType *PT = dyn_cast<PointerType>($5->get());
2823 GEN_ERROR("Can't store to a nonpointer type: " +
2824 (*$5)->getDescription());
2825 const Type *ElTy = PT->getElementType();
2826 if (ElTy != $3->getType())
2827 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
2828 "' into space of type '" + ElTy->getDescription() + "'!");
2830 Value* tmpVal = getVal(*$5, $6);
2832 $$ = new StoreInst($3, tmpVal, $1);
2835 | GETELEMENTPTR Types ValueRef IndexList {
2836 if (!UpRefs.empty())
2837 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2838 if (!isa<PointerType>($2->get()))
2839 GEN_ERROR("getelementptr insn requires pointer operand!");
2841 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2842 GEN_ERROR("Invalid getelementptr indices for type '" +
2843 (*$2)->getDescription()+ "'!");
2844 Value* tmpVal = getVal(*$2, $3);
2846 $$ = new GetElementPtrInst(tmpVal, *$4);
2854 // common code from the two 'RunVMAsmParser' functions
2855 static Module* RunParser(Module * M) {
2857 llvmAsmlineno = 1; // Reset the current line number...
2858 CurModule.CurrentModule = M;
2863 // Check to make sure the parser succeeded
2866 delete ParserResult;
2870 // Check to make sure that parsing produced a result
2874 // Reset ParserResult variable while saving its value for the result.
2875 Module *Result = ParserResult;
2881 void llvm::GenerateError(const std::string &message, int LineNo) {
2882 if (LineNo == -1) LineNo = llvmAsmlineno;
2883 // TODO: column number in exception
2885 TheParseError->setError(CurFilename, message, LineNo);
2889 int yyerror(const char *ErrorMsg) {
2891 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2892 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2893 std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2894 if (yychar == YYEMPTY || yychar == 0)
2895 errMsg += "end-of-file.";
2897 errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2898 GenerateError(errMsg);