1 //===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the bison parser for LLVM assembly languages files.
12 //===----------------------------------------------------------------------===//
15 #include "ParserInternals.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/InlineAsm.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/ValueSymbolTable.h"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/Streams.h"
35 // The following is a gross hack. In order to rid the libAsmParser library of
36 // exceptions, we have to have a way of getting the yyparse function to go into
37 // an error situation. So, whenever we want an error to occur, the GenerateError
38 // function (see bottom of file) sets TriggerError. Then, at the end of each
39 // production in the grammer we use CHECK_FOR_ERROR which will invoke YYERROR
40 // (a goto) to put YACC in error state. Furthermore, several calls to
41 // GenerateError are made from inside productions and they must simulate the
42 // previous exception behavior by exiting the production immediately. We have
43 // replaced these with the GEN_ERROR macro which calls GeneratError and then
44 // immediately invokes YYERROR. This would be so much cleaner if it was a
45 // recursive descent parser.
46 static bool TriggerError = false;
47 #define CHECK_FOR_ERROR { if (TriggerError) { TriggerError = false; YYABORT; } }
48 #define GEN_ERROR(msg) { GenerateError(msg); YYERROR; }
50 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
51 int yylex(); // declaration" of xxx warnings.
55 std::string CurFilename;
58 Debug("debug-yacc", cl::desc("Print yacc debug state changes"),
59 cl::Hidden, cl::init(false));
64 static Module *ParserResult;
66 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
67 // relating to upreferences in the input stream.
69 //#define DEBUG_UPREFS 1
71 #define UR_OUT(X) cerr << X
76 #define YYERROR_VERBOSE 1
78 static GlobalVariable *CurGV;
81 // This contains info used when building the body of a function. It is
82 // destroyed when the function is completed.
84 typedef std::vector<Value *> ValueList; // Numbered defs
87 ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers=0);
89 static struct PerModuleInfo {
90 Module *CurrentModule;
91 ValueList Values; // Module level numbered definitions
92 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 ValueList Values; // Keep track of #'d definitions
212 ValueList LateResolveValues;
213 bool isDeclare; // Is this function a forward declararation?
214 GlobalValue::LinkageTypes Linkage; // Linkage for forward declaration.
215 GlobalValue::VisibilityTypes Visibility;
217 /// BBForwardRefs - When we see forward references to basic blocks, keep
218 /// track of them here.
219 std::map<ValID, BasicBlock*> BBForwardRefs;
221 inline PerFunctionInfo() {
224 Linkage = GlobalValue::ExternalLinkage;
225 Visibility = GlobalValue::DefaultVisibility;
228 inline void FunctionStart(Function *M) {
233 void FunctionDone() {
234 // Any forward referenced blocks left?
235 if (!BBForwardRefs.empty()) {
236 GenerateError("Undefined reference to label " +
237 BBForwardRefs.begin()->second->getName());
241 // Resolve all forward references now.
242 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
244 Values.clear(); // Clear out function local definitions
245 BBForwardRefs.clear();
248 Linkage = GlobalValue::ExternalLinkage;
249 Visibility = GlobalValue::DefaultVisibility;
251 } CurFun; // Info for the current function...
253 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
256 //===----------------------------------------------------------------------===//
257 // Code to handle definitions of all the types
258 //===----------------------------------------------------------------------===//
260 static void InsertValue(Value *V, ValueList &ValueTab = CurFun.Values) {
261 // Things that have names or are void typed don't get slot numbers
262 if (V->hasName() || (V->getType() == Type::VoidTy))
265 // In the case of function values, we have to allow for the forward reference
266 // of basic blocks, which are included in the numbering. Consequently, we keep
267 // track of the next insertion location with NextValNum. When a BB gets
268 // inserted, it could change the size of the CurFun.Values vector.
269 if (&ValueTab == &CurFun.Values) {
270 if (ValueTab.size() <= CurFun.NextValNum)
271 ValueTab.resize(CurFun.NextValNum+1);
272 ValueTab[CurFun.NextValNum++] = V;
275 // For all other lists, its okay to just tack it on the back of the vector.
276 ValueTab.push_back(V);
279 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
281 case ValID::LocalID: // Is it a numbered definition?
282 // Module constants occupy the lowest numbered slots...
283 if (D.Num < CurModule.Types.size())
284 return CurModule.Types[D.Num];
286 case ValID::LocalName: // Is it a named definition?
287 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
288 D.destroy(); // Free old strdup'd memory...
293 GenerateError("Internal parser error: Invalid symbol type reference");
297 // If we reached here, we referenced either a symbol that we don't know about
298 // or an id number that hasn't been read yet. We may be referencing something
299 // forward, so just create an entry to be resolved later and get to it...
301 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
304 if (inFunctionScope()) {
305 if (D.Type == ValID::LocalName) {
306 GenerateError("Reference to an undefined type: '" + D.getName() + "'");
309 GenerateError("Reference to an undefined type: #" + utostr(D.Num));
314 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
315 if (I != CurModule.LateResolveTypes.end())
318 Type *Typ = OpaqueType::get();
319 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
323 // getExistingVal - Look up the value specified by the provided type and
324 // the provided ValID. If the value exists and has already been defined, return
325 // it. Otherwise return null.
327 static Value *getExistingVal(const Type *Ty, const ValID &D) {
328 if (isa<FunctionType>(Ty)) {
329 GenerateError("Functions are not values and "
330 "must be referenced as pointers");
335 case ValID::LocalID: { // Is it a numbered definition?
336 // Check that the number is within bounds.
337 if (D.Num >= CurFun.Values.size())
339 Value *Result = CurFun.Values[D.Num];
340 if (Ty != Result->getType()) {
341 GenerateError("Numbered value (%" + utostr(D.Num) + ") of type '" +
342 Result->getType()->getDescription() + "' does not match "
343 "expected type, '" + Ty->getDescription() + "'");
348 case ValID::GlobalID: { // Is it a numbered definition?
349 if (D.Num >= CurModule.Values.size())
351 Value *Result = CurModule.Values[D.Num];
352 if (Ty != Result->getType()) {
353 GenerateError("Numbered value (@" + utostr(D.Num) + ") of type '" +
354 Result->getType()->getDescription() + "' does not match "
355 "expected type, '" + Ty->getDescription() + "'");
361 case ValID::LocalName: { // Is it a named definition?
362 if (!inFunctionScope())
364 ValueSymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
365 Value *N = SymTab.lookup(D.Name);
368 if (N->getType() != Ty)
371 D.destroy(); // Free old strdup'd memory...
374 case ValID::GlobalName: { // Is it a named definition?
375 ValueSymbolTable &SymTab = CurModule.CurrentModule->getValueSymbolTable();
376 Value *N = SymTab.lookup(D.Name);
379 if (N->getType() != Ty)
382 D.destroy(); // Free old strdup'd memory...
386 // Check to make sure that "Ty" is an integral type, and that our
387 // value will fit into the specified type...
388 case ValID::ConstSIntVal: // Is it a constant pool reference??
389 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
390 GenerateError("Signed integral constant '" +
391 itostr(D.ConstPool64) + "' is invalid for type '" +
392 Ty->getDescription() + "'");
395 return ConstantInt::get(Ty, D.ConstPool64, true);
397 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
398 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
399 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
400 GenerateError("Integral constant '" + utostr(D.UConstPool64) +
401 "' is invalid or out of range");
403 } else { // This is really a signed reference. Transmogrify.
404 return ConstantInt::get(Ty, D.ConstPool64, true);
407 return ConstantInt::get(Ty, D.UConstPool64);
410 case ValID::ConstFPVal: // Is it a floating point const pool reference?
411 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP)) {
412 GenerateError("FP constant invalid for type");
415 return ConstantFP::get(Ty, D.ConstPoolFP);
417 case ValID::ConstNullVal: // Is it a null value?
418 if (!isa<PointerType>(Ty)) {
419 GenerateError("Cannot create a a non pointer null");
422 return ConstantPointerNull::get(cast<PointerType>(Ty));
424 case ValID::ConstUndefVal: // Is it an undef value?
425 return UndefValue::get(Ty);
427 case ValID::ConstZeroVal: // Is it a zero value?
428 return Constant::getNullValue(Ty);
430 case ValID::ConstantVal: // Fully resolved constant?
431 if (D.ConstantValue->getType() != Ty) {
432 GenerateError("Constant expression type different from required type");
435 return D.ConstantValue;
437 case ValID::InlineAsmVal: { // Inline asm expression
438 const PointerType *PTy = dyn_cast<PointerType>(Ty);
439 const FunctionType *FTy =
440 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
441 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
442 GenerateError("Invalid type for asm constraint string");
445 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
446 D.IAD->HasSideEffects);
447 D.destroy(); // Free InlineAsmDescriptor.
451 assert(0 && "Unhandled case!");
455 assert(0 && "Unhandled case!");
459 // getVal - This function is identical to getExistingVal, except that if a
460 // value is not already defined, it "improvises" by creating a placeholder var
461 // that looks and acts just like the requested variable. When the value is
462 // defined later, all uses of the placeholder variable are replaced with the
465 static Value *getVal(const Type *Ty, const ValID &ID) {
466 if (Ty == Type::LabelTy) {
467 GenerateError("Cannot use a basic block here");
471 // See if the value has already been defined.
472 Value *V = getExistingVal(Ty, ID);
474 if (TriggerError) return 0;
476 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
477 GenerateError("Invalid use of a composite type");
481 // If we reached here, we referenced either a symbol that we don't know about
482 // or an id number that hasn't been read yet. We may be referencing something
483 // forward, so just create an entry to be resolved later and get to it...
485 V = new Argument(Ty);
487 // Remember where this forward reference came from. FIXME, shouldn't we try
488 // to recycle these things??
489 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
492 if (inFunctionScope())
493 InsertValue(V, CurFun.LateResolveValues);
495 InsertValue(V, CurModule.LateResolveValues);
499 /// defineBBVal - This is a definition of a new basic block with the specified
500 /// identifier which must be the same as CurFun.NextValNum, if its numeric.
501 static BasicBlock *defineBBVal(const ValID &ID) {
502 assert(inFunctionScope() && "Can't get basic block at global scope!");
506 // First, see if this was forward referenced
508 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
509 if (BBI != CurFun.BBForwardRefs.end()) {
511 // The forward declaration could have been inserted anywhere in the
512 // function: insert it into the correct place now.
513 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
514 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
516 // We're about to erase the entry, save the key so we can clean it up.
517 ValID Tmp = BBI->first;
519 // Erase the forward ref from the map as its no longer "forward"
520 CurFun.BBForwardRefs.erase(ID);
522 // The key has been removed from the map but so we don't want to leave
523 // strdup'd memory around so destroy it too.
526 // If its a numbered definition, bump the number and set the BB value.
527 if (ID.Type == ValID::LocalID) {
528 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
536 // We haven't seen this BB before and its first mention is a definition.
537 // Just create it and return it.
538 std::string Name (ID.Type == ValID::LocalName ? ID.Name : "");
539 BB = new BasicBlock(Name, CurFun.CurrentFunction);
540 if (ID.Type == ValID::LocalID) {
541 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
545 ID.destroy(); // Free strdup'd memory
549 /// getBBVal - get an existing BB value or create a forward reference for it.
551 static BasicBlock *getBBVal(const ValID &ID) {
552 assert(inFunctionScope() && "Can't get basic block at global scope!");
556 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
557 if (BBI != CurFun.BBForwardRefs.end()) {
559 } if (ID.Type == ValID::LocalName) {
560 std::string Name = ID.Name;
561 Value *N = CurFun.CurrentFunction->getValueSymbolTable().lookup(Name);
563 if (N->getType()->getTypeID() == Type::LabelTyID)
564 BB = cast<BasicBlock>(N);
566 GenerateError("Reference to label '" + Name + "' is actually of type '"+
567 N->getType()->getDescription() + "'");
568 } else if (ID.Type == ValID::LocalID) {
569 if (ID.Num < CurFun.NextValNum && ID.Num < CurFun.Values.size()) {
570 if (CurFun.Values[ID.Num]->getType()->getTypeID() == Type::LabelTyID)
571 BB = cast<BasicBlock>(CurFun.Values[ID.Num]);
573 GenerateError("Reference to label '%" + utostr(ID.Num) +
574 "' is actually of type '"+
575 CurFun.Values[ID.Num]->getType()->getDescription() + "'");
578 GenerateError("Illegal label reference " + ID.getName());
582 // If its already been defined, return it now.
584 ID.destroy(); // Free strdup'd memory.
588 // Otherwise, this block has not been seen before, create it.
590 if (ID.Type == ValID::LocalName)
592 BB = new BasicBlock(Name, CurFun.CurrentFunction);
594 // Insert it in the forward refs map.
595 CurFun.BBForwardRefs[ID] = BB;
601 //===----------------------------------------------------------------------===//
602 // Code to handle forward references in instructions
603 //===----------------------------------------------------------------------===//
605 // This code handles the late binding needed with statements that reference
606 // values not defined yet... for example, a forward branch, or the PHI node for
609 // This keeps a table (CurFun.LateResolveValues) of all such forward references
610 // and back patchs after we are done.
613 // ResolveDefinitions - If we could not resolve some defs at parsing
614 // time (forward branches, phi functions for loops, etc...) resolve the
618 ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers) {
619 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
620 while (!LateResolvers.empty()) {
621 Value *V = LateResolvers.back();
622 LateResolvers.pop_back();
624 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
625 CurModule.PlaceHolderInfo.find(V);
626 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
628 ValID &DID = PHI->second.first;
630 Value *TheRealValue = getExistingVal(V->getType(), DID);
634 V->replaceAllUsesWith(TheRealValue);
636 CurModule.PlaceHolderInfo.erase(PHI);
637 } else if (FutureLateResolvers) {
638 // Functions have their unresolved items forwarded to the module late
640 InsertValue(V, *FutureLateResolvers);
642 if (DID.Type == ValID::LocalName || DID.Type == ValID::GlobalName) {
643 GenerateError("Reference to an invalid definition: '" +DID.getName()+
644 "' of type '" + V->getType()->getDescription() + "'",
648 GenerateError("Reference to an invalid definition: #" +
649 itostr(DID.Num) + " of type '" +
650 V->getType()->getDescription() + "'",
656 LateResolvers.clear();
659 // ResolveTypeTo - A brand new type was just declared. This means that (if
660 // name is not null) things referencing Name can be resolved. Otherwise, things
661 // refering to the number can be resolved. Do this now.
663 static void ResolveTypeTo(char *Name, const Type *ToTy) {
665 if (Name) D = ValID::createLocalName(Name);
666 else D = ValID::createLocalID(CurModule.Types.size());
668 std::map<ValID, PATypeHolder>::iterator I =
669 CurModule.LateResolveTypes.find(D);
670 if (I != CurModule.LateResolveTypes.end()) {
671 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
672 CurModule.LateResolveTypes.erase(I);
676 // setValueName - Set the specified value to the name given. The name may be
677 // null potentially, in which case this is a noop. The string passed in is
678 // assumed to be a malloc'd string buffer, and is free'd by this function.
680 static void setValueName(Value *V, char *NameStr) {
681 if (!NameStr) return;
682 std::string Name(NameStr); // Copy string
683 free(NameStr); // Free old string
685 if (V->getType() == Type::VoidTy) {
686 GenerateError("Can't assign name '" + Name+"' to value with void type");
690 assert(inFunctionScope() && "Must be in function scope!");
691 ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
692 if (ST.lookup(Name)) {
693 GenerateError("Redefinition of value '" + Name + "' of type '" +
694 V->getType()->getDescription() + "'");
702 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
703 /// this is a declaration, otherwise it is a definition.
704 static GlobalVariable *
705 ParseGlobalVariable(char *NameStr,
706 GlobalValue::LinkageTypes Linkage,
707 GlobalValue::VisibilityTypes Visibility,
708 bool isConstantGlobal, const Type *Ty,
709 Constant *Initializer) {
710 if (isa<FunctionType>(Ty)) {
711 GenerateError("Cannot declare global vars of function type");
715 const PointerType *PTy = PointerType::get(Ty);
719 Name = NameStr; // Copy string
720 free(NameStr); // Free old string
723 // See if this global value was forward referenced. If so, recycle the
727 ID = ValID::createGlobalName((char*)Name.c_str());
729 ID = ValID::createGlobalID(CurModule.Values.size());
732 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
733 // Move the global to the end of the list, from whereever it was
734 // previously inserted.
735 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
736 CurModule.CurrentModule->getGlobalList().remove(GV);
737 CurModule.CurrentModule->getGlobalList().push_back(GV);
738 GV->setInitializer(Initializer);
739 GV->setLinkage(Linkage);
740 GV->setVisibility(Visibility);
741 GV->setConstant(isConstantGlobal);
742 InsertValue(GV, CurModule.Values);
746 // If this global has a name
748 // if the global we're parsing has an initializer (is a definition) and
749 // has external linkage.
750 if (Initializer && Linkage != GlobalValue::InternalLinkage)
751 // If there is already a global with external linkage with this name
752 if (CurModule.CurrentModule->getGlobalVariable(Name, false)) {
753 // If we allow this GVar to get created, it will be renamed in the
754 // symbol table because it conflicts with an existing GVar. We can't
755 // allow redefinition of GVars whose linking indicates that their name
756 // must stay the same. Issue the error.
757 GenerateError("Redefinition of global variable named '" + Name +
758 "' of type '" + Ty->getDescription() + "'");
763 // Otherwise there is no existing GV to use, create one now.
765 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
766 CurModule.CurrentModule);
767 GV->setVisibility(Visibility);
768 InsertValue(GV, CurModule.Values);
772 // setTypeName - Set the specified type to the name given. The name may be
773 // null potentially, in which case this is a noop. The string passed in is
774 // assumed to be a malloc'd string buffer, and is freed by this function.
776 // This function returns true if the type has already been defined, but is
777 // allowed to be redefined in the specified context. If the name is a new name
778 // for the type plane, it is inserted and false is returned.
779 static bool setTypeName(const Type *T, char *NameStr) {
780 assert(!inFunctionScope() && "Can't give types function-local names!");
781 if (NameStr == 0) return false;
783 std::string Name(NameStr); // Copy string
784 free(NameStr); // Free old string
786 // We don't allow assigning names to void type
787 if (T == Type::VoidTy) {
788 GenerateError("Can't assign name '" + Name + "' to the void type");
792 // Set the type name, checking for conflicts as we do so.
793 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
795 if (AlreadyExists) { // Inserting a name that is already defined???
796 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
797 assert(Existing && "Conflict but no matching type?!");
799 // There is only one case where this is allowed: when we are refining an
800 // opaque type. In this case, Existing will be an opaque type.
801 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
802 // We ARE replacing an opaque type!
803 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
807 // Otherwise, this is an attempt to redefine a type. That's okay if
808 // the redefinition is identical to the original. This will be so if
809 // Existing and T point to the same Type object. In this one case we
810 // allow the equivalent redefinition.
811 if (Existing == T) return true; // Yes, it's equal.
813 // Any other kind of (non-equivalent) redefinition is an error.
814 GenerateError("Redefinition of type named '" + Name + "' of type '" +
815 T->getDescription() + "'");
821 //===----------------------------------------------------------------------===//
822 // Code for handling upreferences in type names...
825 // TypeContains - Returns true if Ty directly contains E in it.
827 static bool TypeContains(const Type *Ty, const Type *E) {
828 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
829 E) != Ty->subtype_end();
834 // NestingLevel - The number of nesting levels that need to be popped before
835 // this type is resolved.
836 unsigned NestingLevel;
838 // LastContainedTy - This is the type at the current binding level for the
839 // type. Every time we reduce the nesting level, this gets updated.
840 const Type *LastContainedTy;
842 // UpRefTy - This is the actual opaque type that the upreference is
846 UpRefRecord(unsigned NL, OpaqueType *URTy)
847 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
851 // UpRefs - A list of the outstanding upreferences that need to be resolved.
852 static std::vector<UpRefRecord> UpRefs;
854 /// HandleUpRefs - Every time we finish a new layer of types, this function is
855 /// called. It loops through the UpRefs vector, which is a list of the
856 /// currently active types. For each type, if the up reference is contained in
857 /// the newly completed type, we decrement the level count. When the level
858 /// count reaches zero, the upreferenced type is the type that is passed in:
859 /// thus we can complete the cycle.
861 static PATypeHolder HandleUpRefs(const Type *ty) {
862 // If Ty isn't abstract, or if there are no up-references in it, then there is
863 // nothing to resolve here.
864 if (!ty->isAbstract() || UpRefs.empty()) return ty;
867 UR_OUT("Type '" << Ty->getDescription() <<
868 "' newly formed. Resolving upreferences.\n" <<
869 UpRefs.size() << " upreferences active!\n");
871 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
872 // to zero), we resolve them all together before we resolve them to Ty. At
873 // the end of the loop, if there is anything to resolve to Ty, it will be in
875 OpaqueType *TypeToResolve = 0;
877 for (unsigned i = 0; i != UpRefs.size(); ++i) {
878 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
879 << UpRefs[i].second->getDescription() << ") = "
880 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
881 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
882 // Decrement level of upreference
883 unsigned Level = --UpRefs[i].NestingLevel;
884 UpRefs[i].LastContainedTy = Ty;
885 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
886 if (Level == 0) { // Upreference should be resolved!
887 if (!TypeToResolve) {
888 TypeToResolve = UpRefs[i].UpRefTy;
890 UR_OUT(" * Resolving upreference for "
891 << UpRefs[i].second->getDescription() << "\n";
892 std::string OldName = UpRefs[i].UpRefTy->getDescription());
893 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
894 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
895 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
897 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
898 --i; // Do not skip the next element...
904 UR_OUT(" * Resolving upreference for "
905 << UpRefs[i].second->getDescription() << "\n";
906 std::string OldName = TypeToResolve->getDescription());
907 TypeToResolve->refineAbstractTypeTo(Ty);
913 //===----------------------------------------------------------------------===//
914 // RunVMAsmParser - Define an interface to this parser
915 //===----------------------------------------------------------------------===//
917 static Module* RunParser(Module * M);
919 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
922 CurFilename = Filename;
923 return RunParser(new Module(CurFilename));
926 Module *llvm::RunVMAsmParser(const char * AsmString, Module * M) {
927 set_scan_string(AsmString);
929 CurFilename = "from_memory";
931 return RunParser(new Module (CurFilename));
940 llvm::Module *ModuleVal;
941 llvm::Function *FunctionVal;
942 llvm::BasicBlock *BasicBlockVal;
943 llvm::TerminatorInst *TermInstVal;
944 llvm::Instruction *InstVal;
945 llvm::Constant *ConstVal;
947 const llvm::Type *PrimType;
948 std::list<llvm::PATypeHolder> *TypeList;
949 llvm::PATypeHolder *TypeVal;
950 llvm::Value *ValueVal;
951 std::vector<llvm::Value*> *ValueList;
952 llvm::ArgListType *ArgList;
953 llvm::TypeWithAttrs TypeWithAttrs;
954 llvm::TypeWithAttrsList *TypeWithAttrsList;
955 llvm::ValueRefList *ValueRefList;
957 // Represent the RHS of PHI node
958 std::list<std::pair<llvm::Value*,
959 llvm::BasicBlock*> > *PHIList;
960 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
961 std::vector<llvm::Constant*> *ConstVector;
963 llvm::GlobalValue::LinkageTypes Linkage;
964 llvm::GlobalValue::VisibilityTypes Visibility;
965 llvm::FunctionType::ParameterAttributes ParamAttrs;
966 llvm::APInt *APIntVal;
974 char *StrVal; // This memory is strdup'd!
975 llvm::ValID ValIDVal; // strdup'd memory maybe!
977 llvm::Instruction::BinaryOps BinaryOpVal;
978 llvm::Instruction::TermOps TermOpVal;
979 llvm::Instruction::MemoryOps MemOpVal;
980 llvm::Instruction::CastOps CastOpVal;
981 llvm::Instruction::OtherOps OtherOpVal;
982 llvm::ICmpInst::Predicate IPredicate;
983 llvm::FCmpInst::Predicate FPredicate;
986 %type <ModuleVal> Module
987 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
988 %type <BasicBlockVal> BasicBlock InstructionList
989 %type <TermInstVal> BBTerminatorInst
990 %type <InstVal> Inst InstVal MemoryInst
991 %type <ConstVal> ConstVal ConstExpr
992 %type <ConstVector> ConstVector
993 %type <ArgList> ArgList ArgListH
994 %type <PHIList> PHIList
995 %type <ValueRefList> ValueRefList // For call param lists & GEP indices
996 %type <ValueList> IndexList // For GEP indices
997 %type <TypeList> TypeListI
998 %type <TypeWithAttrsList> ArgTypeList ArgTypeListI
999 %type <TypeWithAttrs> ArgType
1000 %type <JumpTable> JumpTable
1001 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1002 %type <BoolVal> OptVolatile // 'volatile' or not
1003 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1004 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
1005 %type <Linkage> GVInternalLinkage GVExternalLinkage
1006 %type <Linkage> FunctionDefineLinkage FunctionDeclareLinkage
1007 %type <Visibility> GVVisibilityStyle
1009 // ValueRef - Unresolved reference to a definition or BB
1010 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1011 %type <ValueVal> ResolvedVal // <type> <valref> pair
1012 // Tokens and types for handling constant integer values
1014 // ESINT64VAL - A negative number within long long range
1015 %token <SInt64Val> ESINT64VAL
1017 // EUINT64VAL - A positive number within uns. long long range
1018 %token <UInt64Val> EUINT64VAL
1020 // ESAPINTVAL - A negative number with arbitrary precision
1021 %token <APIntVal> ESAPINTVAL
1023 // EUAPINTVAL - A positive number with arbitrary precision
1024 %token <APIntVal> EUAPINTVAL
1026 %token <UIntVal> LOCALVAL_ID GLOBALVAL_ID // %123 @123
1027 %token <FPVal> FPVAL // Float or Double constant
1029 // Built in types...
1030 %type <TypeVal> Types ResultTypes
1031 %type <PrimType> IntType FPType PrimType // Classifications
1032 %token <PrimType> VOID INTTYPE
1033 %token <PrimType> FLOAT DOUBLE LABEL
1036 %token<StrVal> LOCALVAR GLOBALVAR LABELSTR STRINGCONSTANT ATSTRINGCONSTANT
1037 %type <StrVal> LocalName OptLocalName OptLocalAssign
1038 %type <StrVal> GlobalName OptGlobalAssign
1039 %type <UIntVal> OptAlign OptCAlign
1040 %type <StrVal> OptSection SectionString
1042 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1043 %token DECLARE DEFINE GLOBAL CONSTANT SECTION VOLATILE
1044 %token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
1045 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
1046 %token OPAQUE EXTERNAL TARGET TRIPLE ALIGN
1047 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1048 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1050 %type <UIntVal> OptCallingConv
1051 %type <ParamAttrs> OptParamAttrs ParamAttr
1052 %type <ParamAttrs> OptFuncAttrs FuncAttr
1054 // Basic Block Terminating Operators
1055 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1058 %type <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
1059 %token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1060 %token <BinaryOpVal> SHL LSHR ASHR
1062 %token <OtherOpVal> ICMP FCMP
1063 %type <IPredicate> IPredicates
1064 %type <FPredicate> FPredicates
1065 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1066 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1068 // Memory Instructions
1069 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1072 %type <CastOpVal> CastOps
1073 %token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1074 %token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1077 %token <OtherOpVal> PHI_TOK SELECT VAARG
1078 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1080 // Function Attributes
1081 %token NORETURN INREG SRET NOUNWIND
1083 // Visibility Styles
1084 %token DEFAULT HIDDEN
1090 // Operations that are notably excluded from this list include:
1091 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1093 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1094 LogicalOps : SHL | LSHR | ASHR | AND | OR | XOR;
1095 CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1096 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1099 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1100 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1101 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1102 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1103 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1107 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1108 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1109 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1110 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1111 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1112 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1113 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1114 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1115 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1118 // These are some types that allow classification if we only want a particular
1119 // thing... for example, only a signed, unsigned, or integral type.
1121 FPType : FLOAT | DOUBLE;
1123 LocalName : LOCALVAR | STRINGCONSTANT;
1124 OptLocalName : LocalName | /*empty*/ { $$ = 0; };
1126 /// OptLocalAssign - Value producing statements have an optional assignment
1128 OptLocalAssign : LocalName '=' {
1137 GlobalName : GLOBALVAR | ATSTRINGCONSTANT;
1139 OptGlobalAssign : GlobalName '=' {
1149 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1150 | WEAK { $$ = GlobalValue::WeakLinkage; }
1151 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1152 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1153 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1157 : DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1158 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1159 | EXTERNAL { $$ = GlobalValue::ExternalLinkage; }
1163 : /*empty*/ { $$ = GlobalValue::DefaultVisibility; }
1164 | HIDDEN { $$ = GlobalValue::HiddenVisibility; }
1167 FunctionDeclareLinkage
1168 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1169 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1170 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1173 FunctionDefineLinkage
1174 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1175 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1176 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1177 | WEAK { $$ = GlobalValue::WeakLinkage; }
1178 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1181 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1182 CCC_TOK { $$ = CallingConv::C; } |
1183 FASTCC_TOK { $$ = CallingConv::Fast; } |
1184 COLDCC_TOK { $$ = CallingConv::Cold; } |
1185 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1186 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1188 if ((unsigned)$2 != $2)
1189 GEN_ERROR("Calling conv too large");
1194 ParamAttr : ZEXT { $$ = FunctionType::ZExtAttribute; }
1195 | SEXT { $$ = FunctionType::SExtAttribute; }
1196 | INREG { $$ = FunctionType::InRegAttribute; }
1197 | SRET { $$ = FunctionType::StructRetAttribute; }
1200 OptParamAttrs : /* empty */ { $$ = FunctionType::NoAttributeSet; }
1201 | OptParamAttrs ParamAttr {
1202 $$ = FunctionType::ParameterAttributes($1 | $2);
1206 FuncAttr : NORETURN { $$ = FunctionType::NoReturnAttribute; }
1207 | NOUNWIND { $$ = FunctionType::NoUnwindAttribute; }
1211 OptFuncAttrs : /* empty */ { $$ = FunctionType::NoAttributeSet; }
1212 | OptFuncAttrs FuncAttr {
1213 $$ = FunctionType::ParameterAttributes($1 | $2);
1217 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1218 // a comma before it.
1219 OptAlign : /*empty*/ { $$ = 0; } |
1222 if ($$ != 0 && !isPowerOf2_32($$))
1223 GEN_ERROR("Alignment must be a power of two");
1226 OptCAlign : /*empty*/ { $$ = 0; } |
1227 ',' ALIGN EUINT64VAL {
1229 if ($$ != 0 && !isPowerOf2_32($$))
1230 GEN_ERROR("Alignment must be a power of two");
1235 SectionString : SECTION STRINGCONSTANT {
1236 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1237 if ($2[i] == '"' || $2[i] == '\\')
1238 GEN_ERROR("Invalid character in section name");
1243 OptSection : /*empty*/ { $$ = 0; } |
1244 SectionString { $$ = $1; };
1246 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1247 // is set to be the global we are processing.
1249 GlobalVarAttributes : /* empty */ {} |
1250 ',' GlobalVarAttribute GlobalVarAttributes {};
1251 GlobalVarAttribute : SectionString {
1252 CurGV->setSection($1);
1256 | ALIGN EUINT64VAL {
1257 if ($2 != 0 && !isPowerOf2_32($2))
1258 GEN_ERROR("Alignment must be a power of two");
1259 CurGV->setAlignment($2);
1263 //===----------------------------------------------------------------------===//
1264 // Types includes all predefined types... except void, because it can only be
1265 // used in specific contexts (function returning void for example).
1267 // Derived types are added later...
1269 PrimType : INTTYPE | FLOAT | DOUBLE | LABEL ;
1273 $$ = new PATypeHolder(OpaqueType::get());
1277 $$ = new PATypeHolder($1);
1280 | Types '*' { // Pointer type?
1281 if (*$1 == Type::LabelTy)
1282 GEN_ERROR("Cannot form a pointer to a basic block");
1283 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1287 | SymbolicValueRef { // Named types are also simple types...
1288 const Type* tmp = getTypeVal($1);
1290 $$ = new PATypeHolder(tmp);
1292 | '\\' EUINT64VAL { // Type UpReference
1293 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range");
1294 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1295 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1296 $$ = new PATypeHolder(OT);
1297 UR_OUT("New Upreference!\n");
1300 | Types '(' ArgTypeListI ')' OptFuncAttrs {
1301 std::vector<const Type*> Params;
1302 std::vector<FunctionType::ParameterAttributes> Attrs;
1303 Attrs.push_back($5);
1304 for (TypeWithAttrsList::iterator I=$3->begin(), E=$3->end(); I != E; ++I) {
1305 const Type *Ty = I->Ty->get();
1306 Params.push_back(Ty);
1307 if (Ty != Type::VoidTy)
1308 Attrs.push_back(I->Attrs);
1310 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1311 if (isVarArg) Params.pop_back();
1313 FunctionType *FT = FunctionType::get(*$1, Params, isVarArg, Attrs);
1314 delete $3; // Delete the argument list
1315 delete $1; // Delete the return type handle
1316 $$ = new PATypeHolder(HandleUpRefs(FT));
1319 | VOID '(' ArgTypeListI ')' OptFuncAttrs {
1320 std::vector<const Type*> Params;
1321 std::vector<FunctionType::ParameterAttributes> Attrs;
1322 Attrs.push_back($5);
1323 for (TypeWithAttrsList::iterator I=$3->begin(), E=$3->end(); I != E; ++I) {
1324 const Type* Ty = I->Ty->get();
1325 Params.push_back(Ty);
1326 if (Ty != Type::VoidTy)
1327 Attrs.push_back(I->Attrs);
1329 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1330 if (isVarArg) Params.pop_back();
1332 FunctionType *FT = FunctionType::get($1, Params, isVarArg, Attrs);
1333 delete $3; // Delete the argument list
1334 $$ = new PATypeHolder(HandleUpRefs(FT));
1338 | '[' EUINT64VAL 'x' Types ']' { // Sized array type?
1339 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1343 | '<' EUINT64VAL 'x' Types '>' { // Vector type?
1344 const llvm::Type* ElemTy = $4->get();
1345 if ((unsigned)$2 != $2)
1346 GEN_ERROR("Unsigned result not equal to signed result");
1347 if (!ElemTy->isFloatingPoint() && !ElemTy->isInteger())
1348 GEN_ERROR("Element type of a VectorType must be primitive");
1349 if (!isPowerOf2_32($2))
1350 GEN_ERROR("Vector length should be a power of 2");
1351 $$ = new PATypeHolder(HandleUpRefs(VectorType::get(*$4, (unsigned)$2)));
1355 | '{' TypeListI '}' { // Structure type?
1356 std::vector<const Type*> Elements;
1357 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1358 E = $2->end(); I != E; ++I)
1359 Elements.push_back(*I);
1361 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1365 | '{' '}' { // Empty structure type?
1366 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1369 | '<' '{' TypeListI '}' '>' {
1370 std::vector<const Type*> Elements;
1371 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1372 E = $3->end(); I != E; ++I)
1373 Elements.push_back(*I);
1375 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1379 | '<' '{' '}' '>' { // Empty structure type?
1380 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1386 : Types OptParamAttrs {
1394 if (!UpRefs.empty())
1395 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1396 if (!(*$1)->isFirstClassType())
1397 GEN_ERROR("LLVM functions cannot return aggregate types");
1401 $$ = new PATypeHolder(Type::VoidTy);
1405 ArgTypeList : ArgType {
1406 $$ = new TypeWithAttrsList();
1410 | ArgTypeList ',' ArgType {
1411 ($$=$1)->push_back($3);
1418 | ArgTypeList ',' DOTDOTDOT {
1420 TypeWithAttrs TWA; TWA.Attrs = FunctionType::NoAttributeSet;
1421 TWA.Ty = new PATypeHolder(Type::VoidTy);
1426 $$ = new TypeWithAttrsList;
1427 TypeWithAttrs TWA; TWA.Attrs = FunctionType::NoAttributeSet;
1428 TWA.Ty = new PATypeHolder(Type::VoidTy);
1433 $$ = new TypeWithAttrsList();
1437 // TypeList - Used for struct declarations and as a basis for function type
1438 // declaration type lists
1441 $$ = new std::list<PATypeHolder>();
1446 | TypeListI ',' Types {
1447 ($$=$1)->push_back(*$3);
1452 // ConstVal - The various declarations that go into the constant pool. This
1453 // production is used ONLY to represent constants that show up AFTER a 'const',
1454 // 'constant' or 'global' token at global scope. Constants that can be inlined
1455 // into other expressions (such as integers and constexprs) are handled by the
1456 // ResolvedVal, ValueRef and ConstValueRef productions.
1458 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1459 if (!UpRefs.empty())
1460 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1461 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1463 GEN_ERROR("Cannot make array constant with type: '" +
1464 (*$1)->getDescription() + "'");
1465 const Type *ETy = ATy->getElementType();
1466 int NumElements = ATy->getNumElements();
1468 // Verify that we have the correct size...
1469 if (NumElements != -1 && NumElements != (int)$3->size())
1470 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1471 utostr($3->size()) + " arguments, but has size of " +
1472 itostr(NumElements) + "");
1474 // Verify all elements are correct type!
1475 for (unsigned i = 0; i < $3->size(); i++) {
1476 if (ETy != (*$3)[i]->getType())
1477 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1478 ETy->getDescription() +"' as required!\nIt is of type '"+
1479 (*$3)[i]->getType()->getDescription() + "'.");
1482 $$ = ConstantArray::get(ATy, *$3);
1483 delete $1; delete $3;
1487 if (!UpRefs.empty())
1488 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1489 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1491 GEN_ERROR("Cannot make array constant with type: '" +
1492 (*$1)->getDescription() + "'");
1494 int NumElements = ATy->getNumElements();
1495 if (NumElements != -1 && NumElements != 0)
1496 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1497 " arguments, but has size of " + itostr(NumElements) +"");
1498 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1502 | Types 'c' STRINGCONSTANT {
1503 if (!UpRefs.empty())
1504 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1505 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1507 GEN_ERROR("Cannot make array constant with type: '" +
1508 (*$1)->getDescription() + "'");
1510 int NumElements = ATy->getNumElements();
1511 const Type *ETy = ATy->getElementType();
1512 char *EndStr = UnEscapeLexed($3, true);
1513 if (NumElements != -1 && NumElements != (EndStr-$3))
1514 GEN_ERROR("Can't build string constant of size " +
1515 itostr((int)(EndStr-$3)) +
1516 " when array has size " + itostr(NumElements) + "");
1517 std::vector<Constant*> Vals;
1518 if (ETy == Type::Int8Ty) {
1519 for (unsigned char *C = (unsigned char *)$3;
1520 C != (unsigned char*)EndStr; ++C)
1521 Vals.push_back(ConstantInt::get(ETy, *C));
1524 GEN_ERROR("Cannot build string arrays of non byte sized elements");
1527 $$ = ConstantArray::get(ATy, Vals);
1531 | Types '<' ConstVector '>' { // Nonempty unsized arr
1532 if (!UpRefs.empty())
1533 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1534 const VectorType *PTy = dyn_cast<VectorType>($1->get());
1536 GEN_ERROR("Cannot make packed constant with type: '" +
1537 (*$1)->getDescription() + "'");
1538 const Type *ETy = PTy->getElementType();
1539 int NumElements = PTy->getNumElements();
1541 // Verify that we have the correct size...
1542 if (NumElements != -1 && NumElements != (int)$3->size())
1543 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1544 utostr($3->size()) + " arguments, but has size of " +
1545 itostr(NumElements) + "");
1547 // Verify all elements are correct type!
1548 for (unsigned i = 0; i < $3->size(); i++) {
1549 if (ETy != (*$3)[i]->getType())
1550 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1551 ETy->getDescription() +"' as required!\nIt is of type '"+
1552 (*$3)[i]->getType()->getDescription() + "'.");
1555 $$ = ConstantVector::get(PTy, *$3);
1556 delete $1; delete $3;
1559 | Types '{' ConstVector '}' {
1560 const StructType *STy = dyn_cast<StructType>($1->get());
1562 GEN_ERROR("Cannot make struct constant with type: '" +
1563 (*$1)->getDescription() + "'");
1565 if ($3->size() != STy->getNumContainedTypes())
1566 GEN_ERROR("Illegal number of initializers for structure type");
1568 // Check to ensure that constants are compatible with the type initializer!
1569 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1570 if ((*$3)[i]->getType() != STy->getElementType(i))
1571 GEN_ERROR("Expected type '" +
1572 STy->getElementType(i)->getDescription() +
1573 "' for element #" + utostr(i) +
1574 " of structure initializer");
1576 // Check to ensure that Type is not packed
1577 if (STy->isPacked())
1578 GEN_ERROR("Unpacked Initializer to vector type '" + STy->getDescription() + "'");
1580 $$ = ConstantStruct::get(STy, *$3);
1581 delete $1; delete $3;
1585 if (!UpRefs.empty())
1586 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1587 const StructType *STy = dyn_cast<StructType>($1->get());
1589 GEN_ERROR("Cannot make struct constant with type: '" +
1590 (*$1)->getDescription() + "'");
1592 if (STy->getNumContainedTypes() != 0)
1593 GEN_ERROR("Illegal number of initializers for structure type");
1595 // Check to ensure that Type is not packed
1596 if (STy->isPacked())
1597 GEN_ERROR("Unpacked Initializer to vector type '" + STy->getDescription() + "'");
1599 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1603 | Types '<' '{' ConstVector '}' '>' {
1604 const StructType *STy = dyn_cast<StructType>($1->get());
1606 GEN_ERROR("Cannot make struct constant with type: '" +
1607 (*$1)->getDescription() + "'");
1609 if ($4->size() != STy->getNumContainedTypes())
1610 GEN_ERROR("Illegal number of initializers for structure type");
1612 // Check to ensure that constants are compatible with the type initializer!
1613 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1614 if ((*$4)[i]->getType() != STy->getElementType(i))
1615 GEN_ERROR("Expected type '" +
1616 STy->getElementType(i)->getDescription() +
1617 "' for element #" + utostr(i) +
1618 " of structure initializer");
1620 // Check to ensure that Type is packed
1621 if (!STy->isPacked())
1622 GEN_ERROR("Vector initializer to non-vector type '" +
1623 STy->getDescription() + "'");
1625 $$ = ConstantStruct::get(STy, *$4);
1626 delete $1; delete $4;
1629 | Types '<' '{' '}' '>' {
1630 if (!UpRefs.empty())
1631 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1632 const StructType *STy = dyn_cast<StructType>($1->get());
1634 GEN_ERROR("Cannot make struct constant with type: '" +
1635 (*$1)->getDescription() + "'");
1637 if (STy->getNumContainedTypes() != 0)
1638 GEN_ERROR("Illegal number of initializers for structure type");
1640 // Check to ensure that Type is packed
1641 if (!STy->isPacked())
1642 GEN_ERROR("Vector initializer to non-vector type '" +
1643 STy->getDescription() + "'");
1645 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1650 if (!UpRefs.empty())
1651 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1652 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1654 GEN_ERROR("Cannot make null pointer constant with type: '" +
1655 (*$1)->getDescription() + "'");
1657 $$ = ConstantPointerNull::get(PTy);
1662 if (!UpRefs.empty())
1663 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1664 $$ = UndefValue::get($1->get());
1668 | Types SymbolicValueRef {
1669 if (!UpRefs.empty())
1670 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1671 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1673 GEN_ERROR("Global const reference must be a pointer type");
1675 // ConstExprs can exist in the body of a function, thus creating
1676 // GlobalValues whenever they refer to a variable. Because we are in
1677 // the context of a function, getExistingVal will search the functions
1678 // symbol table instead of the module symbol table for the global symbol,
1679 // which throws things all off. To get around this, we just tell
1680 // getExistingVal that we are at global scope here.
1682 Function *SavedCurFn = CurFun.CurrentFunction;
1683 CurFun.CurrentFunction = 0;
1685 Value *V = getExistingVal(Ty, $2);
1688 CurFun.CurrentFunction = SavedCurFn;
1690 // If this is an initializer for a constant pointer, which is referencing a
1691 // (currently) undefined variable, create a stub now that shall be replaced
1692 // in the future with the right type of variable.
1695 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1696 const PointerType *PT = cast<PointerType>(Ty);
1698 // First check to see if the forward references value is already created!
1699 PerModuleInfo::GlobalRefsType::iterator I =
1700 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1702 if (I != CurModule.GlobalRefs.end()) {
1703 V = I->second; // Placeholder already exists, use it...
1707 if ($2.Type == ValID::GlobalName)
1709 else if ($2.Type != ValID::GlobalID)
1710 GEN_ERROR("Invalid reference to global");
1712 // Create the forward referenced global.
1714 if (const FunctionType *FTy =
1715 dyn_cast<FunctionType>(PT->getElementType())) {
1716 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1717 CurModule.CurrentModule);
1719 GV = new GlobalVariable(PT->getElementType(), false,
1720 GlobalValue::ExternalLinkage, 0,
1721 Name, CurModule.CurrentModule);
1724 // Keep track of the fact that we have a forward ref to recycle it
1725 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1730 $$ = cast<GlobalValue>(V);
1731 delete $1; // Free the type handle
1735 if (!UpRefs.empty())
1736 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1737 if ($1->get() != $2->getType())
1738 GEN_ERROR("Mismatched types for constant expression: " +
1739 (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1744 | Types ZEROINITIALIZER {
1745 if (!UpRefs.empty())
1746 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1747 const Type *Ty = $1->get();
1748 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1749 GEN_ERROR("Cannot create a null initialized value of this type");
1750 $$ = Constant::getNullValue(Ty);
1754 | IntType ESINT64VAL { // integral constants
1755 if (!ConstantInt::isValueValidForType($1, $2))
1756 GEN_ERROR("Constant value doesn't fit in type");
1757 $$ = ConstantInt::get($1, $2, true);
1760 | IntType ESAPINTVAL { // arbitrary precision integer constants
1761 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1762 if ($2->getBitWidth() > BitWidth) {
1763 GEN_ERROR("Constant value does not fit in type");
1765 $2->sextOrTrunc(BitWidth);
1766 $$ = ConstantInt::get(*$2);
1770 | IntType EUINT64VAL { // integral constants
1771 if (!ConstantInt::isValueValidForType($1, $2))
1772 GEN_ERROR("Constant value doesn't fit in type");
1773 $$ = ConstantInt::get($1, $2, false);
1776 | IntType EUAPINTVAL { // arbitrary precision integer constants
1777 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1778 if ($2->getBitWidth() > BitWidth) {
1779 GEN_ERROR("Constant value does not fit in type");
1781 $2->zextOrTrunc(BitWidth);
1782 $$ = ConstantInt::get(*$2);
1786 | INTTYPE TRUETOK { // Boolean constants
1787 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1788 $$ = ConstantInt::getTrue();
1791 | INTTYPE FALSETOK { // Boolean constants
1792 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1793 $$ = ConstantInt::getFalse();
1796 | FPType FPVAL { // Float & Double constants
1797 if (!ConstantFP::isValueValidForType($1, $2))
1798 GEN_ERROR("Floating point constant invalid for type");
1799 $$ = ConstantFP::get($1, $2);
1804 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1805 if (!UpRefs.empty())
1806 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1808 const Type *DestTy = $5->get();
1809 if (!CastInst::castIsValid($1, $3, DestTy))
1810 GEN_ERROR("invalid cast opcode for cast from '" +
1811 Val->getType()->getDescription() + "' to '" +
1812 DestTy->getDescription() + "'");
1813 $$ = ConstantExpr::getCast($1, $3, DestTy);
1816 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1817 if (!isa<PointerType>($3->getType()))
1818 GEN_ERROR("GetElementPtr requires a pointer operand");
1821 GetElementPtrInst::getIndexedType($3->getType(), &(*$4)[0], $4->size(),
1824 GEN_ERROR("Index list invalid for constant getelementptr");
1826 SmallVector<Constant*, 8> IdxVec;
1827 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1828 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1829 IdxVec.push_back(C);
1831 GEN_ERROR("Indices to constant getelementptr must be constants");
1835 $$ = ConstantExpr::getGetElementPtr($3, &IdxVec[0], IdxVec.size());
1838 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1839 if ($3->getType() != Type::Int1Ty)
1840 GEN_ERROR("Select condition must be of boolean type");
1841 if ($5->getType() != $7->getType())
1842 GEN_ERROR("Select operand types must match");
1843 $$ = ConstantExpr::getSelect($3, $5, $7);
1846 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1847 if ($3->getType() != $5->getType())
1848 GEN_ERROR("Binary operator types must match");
1850 $$ = ConstantExpr::get($1, $3, $5);
1852 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1853 if ($3->getType() != $5->getType())
1854 GEN_ERROR("Logical operator types must match");
1855 if (!$3->getType()->isInteger()) {
1856 if (Instruction::isShift($1) || !isa<VectorType>($3->getType()) ||
1857 !cast<VectorType>($3->getType())->getElementType()->isInteger())
1858 GEN_ERROR("Logical operator requires integral operands");
1860 $$ = ConstantExpr::get($1, $3, $5);
1863 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1864 if ($4->getType() != $6->getType())
1865 GEN_ERROR("icmp operand types must match");
1866 $$ = ConstantExpr::getICmp($2, $4, $6);
1868 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1869 if ($4->getType() != $6->getType())
1870 GEN_ERROR("fcmp operand types must match");
1871 $$ = ConstantExpr::getFCmp($2, $4, $6);
1873 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1874 if (!ExtractElementInst::isValidOperands($3, $5))
1875 GEN_ERROR("Invalid extractelement operands");
1876 $$ = ConstantExpr::getExtractElement($3, $5);
1879 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1880 if (!InsertElementInst::isValidOperands($3, $5, $7))
1881 GEN_ERROR("Invalid insertelement operands");
1882 $$ = ConstantExpr::getInsertElement($3, $5, $7);
1885 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1886 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1887 GEN_ERROR("Invalid shufflevector operands");
1888 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1893 // ConstVector - A list of comma separated constants.
1894 ConstVector : ConstVector ',' ConstVal {
1895 ($$ = $1)->push_back($3);
1899 $$ = new std::vector<Constant*>();
1905 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1906 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1909 //===----------------------------------------------------------------------===//
1910 // Rules to match Modules
1911 //===----------------------------------------------------------------------===//
1913 // Module rule: Capture the result of parsing the whole file into a result
1918 $$ = ParserResult = CurModule.CurrentModule;
1919 CurModule.ModuleDone();
1923 $$ = ParserResult = CurModule.CurrentModule;
1924 CurModule.ModuleDone();
1931 | DefinitionList Definition
1935 : DEFINE { CurFun.isDeclare = false; } Function {
1936 CurFun.FunctionDone();
1939 | DECLARE { CurFun.isDeclare = true; } FunctionProto {
1942 | MODULE ASM_TOK AsmBlock {
1946 // Emit an error if there are any unresolved types left.
1947 if (!CurModule.LateResolveTypes.empty()) {
1948 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
1949 if (DID.Type == ValID::LocalName) {
1950 GEN_ERROR("Reference to an undefined type: '"+DID.getName() + "'");
1952 GEN_ERROR("Reference to an undefined type: #" + itostr(DID.Num));
1957 | OptLocalAssign TYPE Types {
1958 if (!UpRefs.empty())
1959 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
1960 // Eagerly resolve types. This is not an optimization, this is a
1961 // requirement that is due to the fact that we could have this:
1963 // %list = type { %list * }
1964 // %list = type { %list * } ; repeated type decl
1966 // If types are not resolved eagerly, then the two types will not be
1967 // determined to be the same type!
1969 ResolveTypeTo($1, *$3);
1971 if (!setTypeName(*$3, $1) && !$1) {
1973 // If this is a named type that is not a redefinition, add it to the slot
1975 CurModule.Types.push_back(*$3);
1981 | OptLocalAssign TYPE VOID {
1982 ResolveTypeTo($1, $3);
1984 if (!setTypeName($3, $1) && !$1) {
1986 // If this is a named type that is not a redefinition, add it to the slot
1988 CurModule.Types.push_back($3);
1992 | OptGlobalAssign GVVisibilityStyle GlobalType ConstVal {
1993 /* "Externally Visible" Linkage */
1995 GEN_ERROR("Global value initializer is not a constant");
1996 CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
1997 $2, $3, $4->getType(), $4);
1999 } GlobalVarAttributes {
2002 | OptGlobalAssign GVInternalLinkage GVVisibilityStyle GlobalType ConstVal {
2004 GEN_ERROR("Global value initializer is not a constant");
2005 CurGV = ParseGlobalVariable($1, $2, $3, $4, $5->getType(), $5);
2007 } GlobalVarAttributes {
2010 | OptGlobalAssign GVExternalLinkage GVVisibilityStyle GlobalType Types {
2011 if (!UpRefs.empty())
2012 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
2013 CurGV = ParseGlobalVariable($1, $2, $3, $4, *$5, 0);
2016 } GlobalVarAttributes {
2020 | TARGET TargetDefinition {
2023 | DEPLIBS '=' LibrariesDefinition {
2029 AsmBlock : STRINGCONSTANT {
2030 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2031 char *EndStr = UnEscapeLexed($1, true);
2032 std::string NewAsm($1, EndStr);
2035 if (AsmSoFar.empty())
2036 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
2038 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
2042 TargetDefinition : TRIPLE '=' STRINGCONSTANT {
2043 CurModule.CurrentModule->setTargetTriple($3);
2046 | DATALAYOUT '=' STRINGCONSTANT {
2047 CurModule.CurrentModule->setDataLayout($3);
2051 LibrariesDefinition : '[' LibList ']';
2053 LibList : LibList ',' STRINGCONSTANT {
2054 CurModule.CurrentModule->addLibrary($3);
2059 CurModule.CurrentModule->addLibrary($1);
2063 | /* empty: end of list */ {
2068 //===----------------------------------------------------------------------===//
2069 // Rules to match Function Headers
2070 //===----------------------------------------------------------------------===//
2072 ArgListH : ArgListH ',' Types OptParamAttrs OptLocalName {
2073 if (!UpRefs.empty())
2074 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2075 if (*$3 == Type::VoidTy)
2076 GEN_ERROR("void typed arguments are invalid");
2077 ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
2082 | Types OptParamAttrs OptLocalName {
2083 if (!UpRefs.empty())
2084 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2085 if (*$1 == Type::VoidTy)
2086 GEN_ERROR("void typed arguments are invalid");
2087 ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2088 $$ = new ArgListType;
2093 ArgList : ArgListH {
2097 | ArgListH ',' DOTDOTDOT {
2099 struct ArgListEntry E;
2100 E.Ty = new PATypeHolder(Type::VoidTy);
2102 E.Attrs = FunctionType::NoAttributeSet;
2107 $$ = new ArgListType;
2108 struct ArgListEntry E;
2109 E.Ty = new PATypeHolder(Type::VoidTy);
2111 E.Attrs = FunctionType::NoAttributeSet;
2120 FunctionHeaderH : OptCallingConv ResultTypes GlobalName '(' ArgList ')'
2121 OptFuncAttrs OptSection OptAlign {
2123 std::string FunctionName($3);
2124 free($3); // Free strdup'd memory!
2126 // Check the function result for abstractness if this is a define. We should
2127 // have no abstract types at this point
2128 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($2))
2129 GEN_ERROR("Reference to abstract result: "+ $2->get()->getDescription());
2131 std::vector<const Type*> ParamTypeList;
2132 std::vector<FunctionType::ParameterAttributes> ParamAttrs;
2133 ParamAttrs.push_back($7);
2134 if ($5) { // If there are arguments...
2135 for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I) {
2136 const Type* Ty = I->Ty->get();
2137 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2138 GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2139 ParamTypeList.push_back(Ty);
2140 if (Ty != Type::VoidTy)
2141 ParamAttrs.push_back(I->Attrs);
2145 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2146 if (isVarArg) ParamTypeList.pop_back();
2148 FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg,
2150 const PointerType *PFT = PointerType::get(FT);
2154 if (!FunctionName.empty()) {
2155 ID = ValID::createGlobalName((char*)FunctionName.c_str());
2157 ID = ValID::createGlobalID(CurModule.Values.size());
2161 // See if this function was forward referenced. If so, recycle the object.
2162 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2163 // Move the function to the end of the list, from whereever it was
2164 // previously inserted.
2165 Fn = cast<Function>(FWRef);
2166 CurModule.CurrentModule->getFunctionList().remove(Fn);
2167 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2168 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2169 (Fn = CurModule.CurrentModule->getFunction(FunctionName))) {
2170 if (Fn->getFunctionType() != FT ) {
2171 // The existing function doesn't have the same type. This is an overload
2173 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2174 } else if (!CurFun.isDeclare && !Fn->isDeclaration()) {
2175 // Neither the existing or the current function is a declaration and they
2176 // have the same name and same type. Clearly this is a redefinition.
2177 GEN_ERROR("Redefinition of function '" + FunctionName + "'");
2178 } if (Fn->isDeclaration()) {
2179 // Make sure to strip off any argument names so we can't get conflicts.
2180 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2184 } else { // Not already defined?
2185 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
2186 CurModule.CurrentModule);
2188 InsertValue(Fn, CurModule.Values);
2191 CurFun.FunctionStart(Fn);
2193 if (CurFun.isDeclare) {
2194 // If we have declaration, always overwrite linkage. This will allow us to
2195 // correctly handle cases, when pointer to function is passed as argument to
2196 // another function.
2197 Fn->setLinkage(CurFun.Linkage);
2198 Fn->setVisibility(CurFun.Visibility);
2200 Fn->setCallingConv($1);
2201 Fn->setAlignment($9);
2207 // Add all of the arguments we parsed to the function...
2208 if ($5) { // Is null if empty...
2209 if (isVarArg) { // Nuke the last entry
2210 assert($5->back().Ty->get() == Type::VoidTy && $5->back().Name == 0 &&
2211 "Not a varargs marker!");
2212 delete $5->back().Ty;
2213 $5->pop_back(); // Delete the last entry
2215 Function::arg_iterator ArgIt = Fn->arg_begin();
2216 Function::arg_iterator ArgEnd = Fn->arg_end();
2218 for (ArgListType::iterator I = $5->begin();
2219 I != $5->end() && ArgIt != ArgEnd; ++I, ++ArgIt) {
2220 delete I->Ty; // Delete the typeholder...
2221 setValueName(ArgIt, I->Name); // Insert arg into symtab...
2227 delete $5; // We're now done with the argument list
2232 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2234 FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2235 $$ = CurFun.CurrentFunction;
2237 // Make sure that we keep track of the linkage type even if there was a
2238 // previous "declare".
2240 $$->setVisibility($2);
2243 END : ENDTOK | '}'; // Allow end of '}' to end a function
2245 Function : BasicBlockList END {
2250 FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2251 CurFun.CurrentFunction->setLinkage($1);
2252 CurFun.CurrentFunction->setVisibility($2);
2253 $$ = CurFun.CurrentFunction;
2254 CurFun.FunctionDone();
2258 //===----------------------------------------------------------------------===//
2259 // Rules to match Basic Blocks
2260 //===----------------------------------------------------------------------===//
2262 OptSideEffect : /* empty */ {
2271 ConstValueRef : ESINT64VAL { // A reference to a direct constant
2272 $$ = ValID::create($1);
2276 $$ = ValID::create($1);
2279 | FPVAL { // Perhaps it's an FP constant?
2280 $$ = ValID::create($1);
2284 $$ = ValID::create(ConstantInt::getTrue());
2288 $$ = ValID::create(ConstantInt::getFalse());
2292 $$ = ValID::createNull();
2296 $$ = ValID::createUndef();
2299 | ZEROINITIALIZER { // A vector zero constant.
2300 $$ = ValID::createZeroInit();
2303 | '<' ConstVector '>' { // Nonempty unsized packed vector
2304 const Type *ETy = (*$2)[0]->getType();
2305 int NumElements = $2->size();
2307 VectorType* pt = VectorType::get(ETy, NumElements);
2308 PATypeHolder* PTy = new PATypeHolder(
2316 // Verify all elements are correct type!
2317 for (unsigned i = 0; i < $2->size(); i++) {
2318 if (ETy != (*$2)[i]->getType())
2319 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2320 ETy->getDescription() +"' as required!\nIt is of type '" +
2321 (*$2)[i]->getType()->getDescription() + "'.");
2324 $$ = ValID::create(ConstantVector::get(pt, *$2));
2325 delete PTy; delete $2;
2329 $$ = ValID::create($1);
2332 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2333 char *End = UnEscapeLexed($3, true);
2334 std::string AsmStr = std::string($3, End);
2335 End = UnEscapeLexed($5, true);
2336 std::string Constraints = std::string($5, End);
2337 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2343 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2346 SymbolicValueRef : LOCALVAL_ID { // Is it an integer reference...?
2347 $$ = ValID::createLocalID($1);
2351 $$ = ValID::createGlobalID($1);
2354 | LocalName { // Is it a named reference...?
2355 $$ = ValID::createLocalName($1);
2358 | GlobalName { // Is it a named reference...?
2359 $$ = ValID::createGlobalName($1);
2363 // ValueRef - A reference to a definition... either constant or symbolic
2364 ValueRef : SymbolicValueRef | ConstValueRef;
2367 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2368 // type immediately preceeds the value reference, and allows complex constant
2369 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2370 ResolvedVal : Types ValueRef {
2371 if (!UpRefs.empty())
2372 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2373 $$ = getVal(*$1, $2);
2379 BasicBlockList : BasicBlockList BasicBlock {
2383 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2389 // Basic blocks are terminated by branching instructions:
2390 // br, br/cc, switch, ret
2392 BasicBlock : InstructionList OptLocalAssign BBTerminatorInst {
2393 setValueName($3, $2);
2396 $1->getInstList().push_back($3);
2401 InstructionList : InstructionList Inst {
2402 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2403 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2404 if (CI2->getParent() == 0)
2405 $1->getInstList().push_back(CI2);
2406 $1->getInstList().push_back($2);
2410 | /* empty */ { // Empty space between instruction lists
2411 $$ = defineBBVal(ValID::createLocalID(CurFun.NextValNum));
2414 | LABELSTR { // Labelled (named) basic block
2415 $$ = defineBBVal(ValID::createLocalName($1));
2419 BBTerminatorInst : RET ResolvedVal { // Return with a result...
2420 $$ = new ReturnInst($2);
2423 | RET VOID { // Return with no result...
2424 $$ = new ReturnInst();
2427 | BR LABEL ValueRef { // Unconditional Branch...
2428 BasicBlock* tmpBB = getBBVal($3);
2430 $$ = new BranchInst(tmpBB);
2431 } // Conditional Branch...
2432 | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2433 assert(cast<IntegerType>($2)->getBitWidth() == 1 && "Not Bool?");
2434 BasicBlock* tmpBBA = getBBVal($6);
2436 BasicBlock* tmpBBB = getBBVal($9);
2438 Value* tmpVal = getVal(Type::Int1Ty, $3);
2440 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2442 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2443 Value* tmpVal = getVal($2, $3);
2445 BasicBlock* tmpBB = getBBVal($6);
2447 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2450 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2452 for (; I != E; ++I) {
2453 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2454 S->addCase(CI, I->second);
2456 GEN_ERROR("Switch case is constant, but not a simple integer");
2461 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2462 Value* tmpVal = getVal($2, $3);
2464 BasicBlock* tmpBB = getBBVal($6);
2466 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2470 | INVOKE OptCallingConv ResultTypes ValueRef '(' ValueRefList ')' OptFuncAttrs
2471 TO LABEL ValueRef UNWIND LABEL ValueRef {
2473 // Handle the short syntax
2474 const PointerType *PFTy = 0;
2475 const FunctionType *Ty = 0;
2476 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2477 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2478 // Pull out the types of all of the arguments...
2479 std::vector<const Type*> ParamTypes;
2480 FunctionType::ParamAttrsList ParamAttrs;
2481 ParamAttrs.push_back($8);
2482 for (ValueRefList::iterator I = $6->begin(), E = $6->end(); I != E; ++I) {
2483 const Type *Ty = I->Val->getType();
2484 if (Ty == Type::VoidTy)
2485 GEN_ERROR("Short call syntax cannot be used with varargs");
2486 ParamTypes.push_back(Ty);
2487 ParamAttrs.push_back(I->Attrs);
2490 Ty = FunctionType::get($3->get(), ParamTypes, false, ParamAttrs);
2491 PFTy = PointerType::get(Ty);
2496 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2498 BasicBlock *Normal = getBBVal($11);
2500 BasicBlock *Except = getBBVal($14);
2503 // Check the arguments
2505 if ($6->empty()) { // Has no arguments?
2506 // Make sure no arguments is a good thing!
2507 if (Ty->getNumParams() != 0)
2508 GEN_ERROR("No arguments passed to a function that "
2509 "expects arguments");
2510 } else { // Has arguments?
2511 // Loop through FunctionType's arguments and ensure they are specified
2513 FunctionType::param_iterator I = Ty->param_begin();
2514 FunctionType::param_iterator E = Ty->param_end();
2515 ValueRefList::iterator ArgI = $6->begin(), ArgE = $6->end();
2517 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2518 if (ArgI->Val->getType() != *I)
2519 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2520 (*I)->getDescription() + "'");
2521 Args.push_back(ArgI->Val);
2524 if (Ty->isVarArg()) {
2526 for (; ArgI != ArgE; ++ArgI)
2527 Args.push_back(ArgI->Val); // push the remaining varargs
2528 } else if (I != E || ArgI != ArgE)
2529 GEN_ERROR("Invalid number of parameters detected");
2532 // Create the InvokeInst
2533 InvokeInst *II = new InvokeInst(V, Normal, Except, &Args[0], Args.size());
2534 II->setCallingConv($2);
2540 $$ = new UnwindInst();
2544 $$ = new UnreachableInst();
2550 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2552 Constant *V = cast<Constant>(getExistingVal($2, $3));
2555 GEN_ERROR("May only switch on a constant pool value");
2557 BasicBlock* tmpBB = getBBVal($6);
2559 $$->push_back(std::make_pair(V, tmpBB));
2561 | IntType ConstValueRef ',' LABEL ValueRef {
2562 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2563 Constant *V = cast<Constant>(getExistingVal($1, $2));
2567 GEN_ERROR("May only switch on a constant pool value");
2569 BasicBlock* tmpBB = getBBVal($5);
2571 $$->push_back(std::make_pair(V, tmpBB));
2574 Inst : OptLocalAssign InstVal {
2575 // Is this definition named?? if so, assign the name...
2576 setValueName($2, $1);
2584 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2585 if (!UpRefs.empty())
2586 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2587 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2588 Value* tmpVal = getVal(*$1, $3);
2590 BasicBlock* tmpBB = getBBVal($5);
2592 $$->push_back(std::make_pair(tmpVal, tmpBB));
2595 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2597 Value* tmpVal = getVal($1->front().first->getType(), $4);
2599 BasicBlock* tmpBB = getBBVal($6);
2601 $1->push_back(std::make_pair(tmpVal, tmpBB));
2605 ValueRefList : Types ValueRef OptParamAttrs {
2606 if (!UpRefs.empty())
2607 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2608 // Used for call and invoke instructions
2609 $$ = new ValueRefList();
2610 ValueRefListEntry E; E.Attrs = $3; E.Val = getVal($1->get(), $2);
2614 | ValueRefList ',' Types ValueRef OptParamAttrs {
2615 if (!UpRefs.empty())
2616 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2618 ValueRefListEntry E; E.Attrs = $5; E.Val = getVal($3->get(), $4);
2623 | /*empty*/ { $$ = new ValueRefList(); };
2625 IndexList // Used for gep instructions and constant expressions
2626 : /*empty*/ { $$ = new std::vector<Value*>(); }
2627 | IndexList ',' ResolvedVal {
2634 OptTailCall : TAIL CALL {
2643 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2644 if (!UpRefs.empty())
2645 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2646 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
2647 !isa<VectorType>((*$2).get()))
2649 "Arithmetic operator requires integer, FP, or packed operands");
2650 if (isa<VectorType>((*$2).get()) &&
2651 ($1 == Instruction::URem ||
2652 $1 == Instruction::SRem ||
2653 $1 == Instruction::FRem))
2654 GEN_ERROR("Remainder not supported on vector types");
2655 Value* val1 = getVal(*$2, $3);
2657 Value* val2 = getVal(*$2, $5);
2659 $$ = BinaryOperator::create($1, val1, val2);
2661 GEN_ERROR("binary operator returned null");
2664 | LogicalOps Types ValueRef ',' ValueRef {
2665 if (!UpRefs.empty())
2666 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2667 if (!(*$2)->isInteger()) {
2668 if (Instruction::isShift($1) || !isa<VectorType>($2->get()) ||
2669 !cast<VectorType>($2->get())->getElementType()->isInteger())
2670 GEN_ERROR("Logical operator requires integral operands");
2672 Value* tmpVal1 = getVal(*$2, $3);
2674 Value* tmpVal2 = getVal(*$2, $5);
2676 $$ = BinaryOperator::create($1, tmpVal1, tmpVal2);
2678 GEN_ERROR("binary operator returned null");
2681 | ICMP IPredicates Types ValueRef ',' ValueRef {
2682 if (!UpRefs.empty())
2683 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2684 if (isa<VectorType>((*$3).get()))
2685 GEN_ERROR("Vector types not supported by icmp instruction");
2686 Value* tmpVal1 = getVal(*$3, $4);
2688 Value* tmpVal2 = getVal(*$3, $6);
2690 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2692 GEN_ERROR("icmp operator returned null");
2695 | FCMP FPredicates Types ValueRef ',' ValueRef {
2696 if (!UpRefs.empty())
2697 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2698 if (isa<VectorType>((*$3).get()))
2699 GEN_ERROR("Vector types not supported by fcmp instruction");
2700 Value* tmpVal1 = getVal(*$3, $4);
2702 Value* tmpVal2 = getVal(*$3, $6);
2704 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2706 GEN_ERROR("fcmp operator returned null");
2709 | CastOps ResolvedVal TO Types {
2710 if (!UpRefs.empty())
2711 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2713 const Type* DestTy = $4->get();
2714 if (!CastInst::castIsValid($1, Val, DestTy))
2715 GEN_ERROR("invalid cast opcode for cast from '" +
2716 Val->getType()->getDescription() + "' to '" +
2717 DestTy->getDescription() + "'");
2718 $$ = CastInst::create($1, Val, DestTy);
2721 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2722 if ($2->getType() != Type::Int1Ty)
2723 GEN_ERROR("select condition must be boolean");
2724 if ($4->getType() != $6->getType())
2725 GEN_ERROR("select value types should match");
2726 $$ = new SelectInst($2, $4, $6);
2729 | VAARG ResolvedVal ',' Types {
2730 if (!UpRefs.empty())
2731 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2732 $$ = new VAArgInst($2, *$4);
2736 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2737 if (!ExtractElementInst::isValidOperands($2, $4))
2738 GEN_ERROR("Invalid extractelement operands");
2739 $$ = new ExtractElementInst($2, $4);
2742 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2743 if (!InsertElementInst::isValidOperands($2, $4, $6))
2744 GEN_ERROR("Invalid insertelement operands");
2745 $$ = new InsertElementInst($2, $4, $6);
2748 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2749 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
2750 GEN_ERROR("Invalid shufflevector operands");
2751 $$ = new ShuffleVectorInst($2, $4, $6);
2755 const Type *Ty = $2->front().first->getType();
2756 if (!Ty->isFirstClassType())
2757 GEN_ERROR("PHI node operands must be of first class type");
2758 $$ = new PHINode(Ty);
2759 ((PHINode*)$$)->reserveOperandSpace($2->size());
2760 while ($2->begin() != $2->end()) {
2761 if ($2->front().first->getType() != Ty)
2762 GEN_ERROR("All elements of a PHI node must be of the same type");
2763 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2766 delete $2; // Free the list...
2769 | OptTailCall OptCallingConv ResultTypes ValueRef '(' ValueRefList ')'
2772 // Handle the short syntax
2773 const PointerType *PFTy = 0;
2774 const FunctionType *Ty = 0;
2775 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2776 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2777 // Pull out the types of all of the arguments...
2778 std::vector<const Type*> ParamTypes;
2779 FunctionType::ParamAttrsList ParamAttrs;
2780 ParamAttrs.push_back($8);
2781 for (ValueRefList::iterator I = $6->begin(), E = $6->end(); I != E; ++I) {
2782 const Type *Ty = I->Val->getType();
2783 if (Ty == Type::VoidTy)
2784 GEN_ERROR("Short call syntax cannot be used with varargs");
2785 ParamTypes.push_back(Ty);
2786 ParamAttrs.push_back(I->Attrs);
2789 Ty = FunctionType::get($3->get(), ParamTypes, false, ParamAttrs);
2790 PFTy = PointerType::get(Ty);
2793 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2796 // Check the arguments
2798 if ($6->empty()) { // Has no arguments?
2799 // Make sure no arguments is a good thing!
2800 if (Ty->getNumParams() != 0)
2801 GEN_ERROR("No arguments passed to a function that "
2802 "expects arguments");
2803 } else { // Has arguments?
2804 // Loop through FunctionType's arguments and ensure they are specified
2807 FunctionType::param_iterator I = Ty->param_begin();
2808 FunctionType::param_iterator E = Ty->param_end();
2809 ValueRefList::iterator ArgI = $6->begin(), ArgE = $6->end();
2811 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2812 if (ArgI->Val->getType() != *I)
2813 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2814 (*I)->getDescription() + "'");
2815 Args.push_back(ArgI->Val);
2817 if (Ty->isVarArg()) {
2819 for (; ArgI != ArgE; ++ArgI)
2820 Args.push_back(ArgI->Val); // push the remaining varargs
2821 } else if (I != E || ArgI != ArgE)
2822 GEN_ERROR("Invalid number of parameters detected");
2824 // Create the call node
2825 CallInst *CI = new CallInst(V, &Args[0], Args.size());
2826 CI->setTailCall($1);
2827 CI->setCallingConv($2);
2838 OptVolatile : VOLATILE {
2849 MemoryInst : MALLOC Types OptCAlign {
2850 if (!UpRefs.empty())
2851 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2852 $$ = new MallocInst(*$2, 0, $3);
2856 | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
2857 if (!UpRefs.empty())
2858 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2859 Value* tmpVal = getVal($4, $5);
2861 $$ = new MallocInst(*$2, tmpVal, $6);
2864 | ALLOCA Types OptCAlign {
2865 if (!UpRefs.empty())
2866 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2867 $$ = new AllocaInst(*$2, 0, $3);
2871 | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
2872 if (!UpRefs.empty())
2873 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2874 Value* tmpVal = getVal($4, $5);
2876 $$ = new AllocaInst(*$2, tmpVal, $6);
2879 | FREE ResolvedVal {
2880 if (!isa<PointerType>($2->getType()))
2881 GEN_ERROR("Trying to free nonpointer type " +
2882 $2->getType()->getDescription() + "");
2883 $$ = new FreeInst($2);
2887 | OptVolatile LOAD Types ValueRef {
2888 if (!UpRefs.empty())
2889 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2890 if (!isa<PointerType>($3->get()))
2891 GEN_ERROR("Can't load from nonpointer type: " +
2892 (*$3)->getDescription());
2893 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
2894 GEN_ERROR("Can't load from pointer of non-first-class type: " +
2895 (*$3)->getDescription());
2896 Value* tmpVal = getVal(*$3, $4);
2898 $$ = new LoadInst(tmpVal, "", $1);
2901 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2902 if (!UpRefs.empty())
2903 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
2904 const PointerType *PT = dyn_cast<PointerType>($5->get());
2906 GEN_ERROR("Can't store to a nonpointer type: " +
2907 (*$5)->getDescription());
2908 const Type *ElTy = PT->getElementType();
2909 if (ElTy != $3->getType())
2910 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
2911 "' into space of type '" + ElTy->getDescription() + "'");
2913 Value* tmpVal = getVal(*$5, $6);
2915 $$ = new StoreInst($3, tmpVal, $1);
2918 | GETELEMENTPTR Types ValueRef IndexList {
2919 if (!UpRefs.empty())
2920 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2921 if (!isa<PointerType>($2->get()))
2922 GEN_ERROR("getelementptr insn requires pointer operand");
2924 if (!GetElementPtrInst::getIndexedType(*$2, &(*$4)[0], $4->size(), true))
2925 GEN_ERROR("Invalid getelementptr indices for type '" +
2926 (*$2)->getDescription()+ "'");
2927 Value* tmpVal = getVal(*$2, $3);
2929 $$ = new GetElementPtrInst(tmpVal, &(*$4)[0], $4->size());
2937 // common code from the two 'RunVMAsmParser' functions
2938 static Module* RunParser(Module * M) {
2940 llvmAsmlineno = 1; // Reset the current line number...
2941 CurModule.CurrentModule = M;
2946 // Check to make sure the parser succeeded
2949 delete ParserResult;
2953 // Check to make sure that parsing produced a result
2957 // Reset ParserResult variable while saving its value for the result.
2958 Module *Result = ParserResult;
2964 void llvm::GenerateError(const std::string &message, int LineNo) {
2965 if (LineNo == -1) LineNo = llvmAsmlineno;
2966 // TODO: column number in exception
2968 TheParseError->setError(CurFilename, message, LineNo);
2972 int yyerror(const char *ErrorMsg) {
2974 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2975 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2976 std::string errMsg = where + "error: " + std::string(ErrorMsg);
2977 if (yychar != YYEMPTY && yychar != 0)
2978 errMsg += " while reading token: '" + std::string(llvmAsmtext, llvmAsmleng)+
2980 GenerateError(errMsg);