1 //===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/AutoUpgrade.h"
22 #include "llvm/Support/GetElementPtrTypeIterator.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Support/Streams.h"
33 // The following is a gross hack. In order to rid the libAsmParser library of
34 // exceptions, we have to have a way of getting the yyparse function to go into
35 // an error situation. So, whenever we want an error to occur, the GenerateError
36 // function (see bottom of file) sets TriggerError. Then, at the end of each
37 // production in the grammer we use CHECK_FOR_ERROR which will invoke YYERROR
38 // (a goto) to put YACC in error state. Furthermore, several calls to
39 // GenerateError are made from inside productions and they must simulate the
40 // previous exception behavior by exiting the production immediately. We have
41 // replaced these with the GEN_ERROR macro which calls GeneratError and then
42 // immediately invokes YYERROR. This would be so much cleaner if it was a
43 // recursive descent parser.
44 static bool TriggerError = false;
45 #define CHECK_FOR_ERROR { if (TriggerError) { TriggerError = false; YYABORT; } }
46 #define GEN_ERROR(msg) { GenerateError(msg); YYERROR; }
48 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
49 int yylex(); // declaration" of xxx warnings.
53 static Module *ParserResult;
55 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
56 // relating to upreferences in the input stream.
58 //#define DEBUG_UPREFS 1
60 #define UR_OUT(X) cerr << X
65 #define YYERROR_VERBOSE 1
67 static GlobalVariable *CurGV;
70 // This contains info used when building the body of a function. It is
71 // destroyed when the function is completed.
73 typedef std::vector<Value *> ValueList; // Numbered defs
76 ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers=0);
78 static struct PerModuleInfo {
79 Module *CurrentModule;
80 ValueList Values; // Module level numbered definitions
81 ValueList LateResolveValues;
82 std::vector<PATypeHolder> Types;
83 std::map<ValID, PATypeHolder> LateResolveTypes;
85 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
86 /// how they were referenced and on which line of the input they came from so
87 /// that we can resolve them later and print error messages as appropriate.
88 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
90 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
91 // references to global values. Global values may be referenced before they
92 // are defined, and if so, the temporary object that they represent is held
93 // here. This is used for forward references of GlobalValues.
95 typedef std::map<std::pair<const PointerType *,
96 ValID>, GlobalValue*> GlobalRefsType;
97 GlobalRefsType GlobalRefs;
100 // If we could not resolve some functions at function compilation time
101 // (calls to functions before they are defined), resolve them now... Types
102 // are resolved when the constant pool has been completely parsed.
104 ResolveDefinitions(LateResolveValues);
108 // Check to make sure that all global value forward references have been
111 if (!GlobalRefs.empty()) {
112 std::string UndefinedReferences = "Unresolved global references exist:\n";
114 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
116 UndefinedReferences += " " + I->first.first->getDescription() + " " +
117 I->first.second.getName() + "\n";
119 GenerateError(UndefinedReferences);
123 // Look for intrinsic functions and CallInst that need to be upgraded
124 for (Module::iterator FI = CurrentModule->begin(),
125 FE = CurrentModule->end(); FI != FE; )
126 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
128 Values.clear(); // Clear out function local definitions
133 // GetForwardRefForGlobal - Check to see if there is a forward reference
134 // for this global. If so, remove it from the GlobalRefs map and return it.
135 // If not, just return null.
136 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
137 // Check to see if there is a forward reference to this global variable...
138 // if there is, eliminate it and patch the reference to use the new def'n.
139 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
140 GlobalValue *Ret = 0;
141 if (I != GlobalRefs.end()) {
143 I->first.second.destroy();
149 bool TypeIsUnresolved(PATypeHolder* PATy) {
150 // If it isn't abstract, its resolved
151 const Type* Ty = PATy->get();
152 if (!Ty->isAbstract())
154 // Traverse the type looking for abstract types. If it isn't abstract then
155 // we don't need to traverse that leg of the type.
156 std::vector<const Type*> WorkList, SeenList;
157 WorkList.push_back(Ty);
158 while (!WorkList.empty()) {
159 const Type* Ty = WorkList.back();
160 SeenList.push_back(Ty);
162 if (const OpaqueType* OpTy = dyn_cast<OpaqueType>(Ty)) {
163 // Check to see if this is an unresolved type
164 std::map<ValID, PATypeHolder>::iterator I = LateResolveTypes.begin();
165 std::map<ValID, PATypeHolder>::iterator E = LateResolveTypes.end();
166 for ( ; I != E; ++I) {
167 if (I->second.get() == OpTy)
170 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(Ty)) {
171 const Type* TheTy = SeqTy->getElementType();
172 if (TheTy->isAbstract() && TheTy != Ty) {
173 std::vector<const Type*>::iterator I = SeenList.begin(),
179 WorkList.push_back(TheTy);
181 } else if (const StructType* StrTy = dyn_cast<StructType>(Ty)) {
182 for (unsigned i = 0; i < StrTy->getNumElements(); ++i) {
183 const Type* TheTy = StrTy->getElementType(i);
184 if (TheTy->isAbstract() && TheTy != Ty) {
185 std::vector<const Type*>::iterator I = SeenList.begin(),
191 WorkList.push_back(TheTy);
200 static struct PerFunctionInfo {
201 Function *CurrentFunction; // Pointer to current function being created
203 ValueList Values; // Keep track of #'d definitions
205 ValueList LateResolveValues;
206 bool isDeclare; // Is this function a forward declararation?
207 GlobalValue::LinkageTypes Linkage; // Linkage for forward declaration.
208 GlobalValue::VisibilityTypes Visibility;
210 /// BBForwardRefs - When we see forward references to basic blocks, keep
211 /// track of them here.
212 std::map<ValID, BasicBlock*> BBForwardRefs;
214 inline PerFunctionInfo() {
217 Linkage = GlobalValue::ExternalLinkage;
218 Visibility = GlobalValue::DefaultVisibility;
221 inline void FunctionStart(Function *M) {
226 void FunctionDone() {
227 // Any forward referenced blocks left?
228 if (!BBForwardRefs.empty()) {
229 GenerateError("Undefined reference to label " +
230 BBForwardRefs.begin()->second->getName());
234 // Resolve all forward references now.
235 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
237 Values.clear(); // Clear out function local definitions
238 BBForwardRefs.clear();
241 Linkage = GlobalValue::ExternalLinkage;
242 Visibility = GlobalValue::DefaultVisibility;
244 } CurFun; // Info for the current function...
246 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
249 //===----------------------------------------------------------------------===//
250 // Code to handle definitions of all the types
251 //===----------------------------------------------------------------------===//
253 /// InsertValue - Insert a value into the value table. If it is named, this
254 /// returns -1, otherwise it returns the slot number for the value.
255 static int InsertValue(Value *V, ValueList &ValueTab = CurFun.Values) {
256 // Things that have names or are void typed don't get slot numbers
257 if (V->hasName() || (V->getType() == Type::VoidTy))
260 // In the case of function values, we have to allow for the forward reference
261 // of basic blocks, which are included in the numbering. Consequently, we keep
262 // track of the next insertion location with NextValNum. When a BB gets
263 // inserted, it could change the size of the CurFun.Values vector.
264 if (&ValueTab == &CurFun.Values) {
265 if (ValueTab.size() <= CurFun.NextValNum)
266 ValueTab.resize(CurFun.NextValNum+1);
267 ValueTab[CurFun.NextValNum++] = V;
268 return CurFun.NextValNum-1;
270 // For all other lists, its okay to just tack it on the back of the vector.
271 ValueTab.push_back(V);
272 return ValueTab.size()-1;
275 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
277 case ValID::LocalID: // Is it a numbered definition?
278 // Module constants occupy the lowest numbered slots...
279 if (D.Num < CurModule.Types.size())
280 return CurModule.Types[D.Num];
282 case ValID::LocalName: // Is it a named definition?
283 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.getName())) {
284 D.destroy(); // Free old strdup'd memory...
289 GenerateError("Internal parser error: Invalid symbol type reference");
293 // If we reached here, we referenced either a symbol that we don't know about
294 // or an id number that hasn't been read yet. We may be referencing something
295 // forward, so just create an entry to be resolved later and get to it...
297 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
300 if (inFunctionScope()) {
301 if (D.Type == ValID::LocalName) {
302 GenerateError("Reference to an undefined type: '" + D.getName() + "'");
305 GenerateError("Reference to an undefined type: #" + utostr(D.Num));
310 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
311 if (I != CurModule.LateResolveTypes.end()) {
316 Type *Typ = OpaqueType::get();
317 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
321 // getExistingVal - Look up the value specified by the provided type and
322 // the provided ValID. If the value exists and has already been defined, return
323 // it. Otherwise return null.
325 static Value *getExistingVal(const Type *Ty, const ValID &D) {
326 if (isa<FunctionType>(Ty)) {
327 GenerateError("Functions are not values and "
328 "must be referenced as pointers");
333 case ValID::LocalID: { // Is it a numbered definition?
334 // Check that the number is within bounds.
335 if (D.Num >= CurFun.Values.size())
337 Value *Result = CurFun.Values[D.Num];
338 if (Ty != Result->getType()) {
339 GenerateError("Numbered value (%" + utostr(D.Num) + ") of type '" +
340 Result->getType()->getDescription() + "' does not match "
341 "expected type, '" + Ty->getDescription() + "'");
346 case ValID::GlobalID: { // Is it a numbered definition?
347 if (D.Num >= CurModule.Values.size())
349 Value *Result = CurModule.Values[D.Num];
350 if (Ty != Result->getType()) {
351 GenerateError("Numbered value (@" + utostr(D.Num) + ") of type '" +
352 Result->getType()->getDescription() + "' does not match "
353 "expected type, '" + Ty->getDescription() + "'");
359 case ValID::LocalName: { // Is it a named definition?
360 if (!inFunctionScope())
362 ValueSymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
363 Value *N = SymTab.lookup(D.getName());
366 if (N->getType() != Ty)
369 D.destroy(); // Free old strdup'd memory...
372 case ValID::GlobalName: { // Is it a named definition?
373 ValueSymbolTable &SymTab = CurModule.CurrentModule->getValueSymbolTable();
374 Value *N = SymTab.lookup(D.getName());
377 if (N->getType() != Ty)
380 D.destroy(); // Free old strdup'd memory...
384 // Check to make sure that "Ty" is an integral type, and that our
385 // value will fit into the specified type...
386 case ValID::ConstSIntVal: // Is it a constant pool reference??
387 if (!isa<IntegerType>(Ty) ||
388 !ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
389 GenerateError("Signed integral constant '" +
390 itostr(D.ConstPool64) + "' is invalid for type '" +
391 Ty->getDescription() + "'");
394 return ConstantInt::get(Ty, D.ConstPool64, true);
396 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
397 if (isa<IntegerType>(Ty) &&
398 ConstantInt::isValueValidForType(Ty, D.UConstPool64))
399 return ConstantInt::get(Ty, D.UConstPool64);
401 if (!isa<IntegerType>(Ty) ||
402 !ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
403 GenerateError("Integral constant '" + utostr(D.UConstPool64) +
404 "' is invalid or out of range for type '" +
405 Ty->getDescription() + "'");
408 // This is really a signed reference. Transmogrify.
409 return ConstantInt::get(Ty, D.ConstPool64, true);
411 case ValID::ConstAPInt: // Is it an unsigned const pool reference?
412 if (!isa<IntegerType>(Ty)) {
413 GenerateError("Integral constant '" + D.getName() +
414 "' is invalid or out of range for type '" +
415 Ty->getDescription() + "'");
420 APSInt Tmp = *D.ConstPoolInt;
422 Tmp.extOrTrunc(Ty->getPrimitiveSizeInBits());
423 return ConstantInt::get(Tmp);
426 case ValID::ConstFPVal: // Is it a floating point const pool reference?
427 if (!Ty->isFloatingPoint() ||
428 !ConstantFP::isValueValidForType(Ty, *D.ConstPoolFP)) {
429 GenerateError("FP constant invalid for type");
432 // Lexer has no type info, so builds all float and double FP constants
433 // as double. Fix this here. Long double does not need this.
434 if (&D.ConstPoolFP->getSemantics() == &APFloat::IEEEdouble &&
437 D.ConstPoolFP->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
441 ConstantFP *tmp = ConstantFP::get(*D.ConstPoolFP);
446 case ValID::ConstNullVal: // Is it a null value?
447 if (!isa<PointerType>(Ty)) {
448 GenerateError("Cannot create a a non pointer null");
451 return ConstantPointerNull::get(cast<PointerType>(Ty));
453 case ValID::ConstUndefVal: // Is it an undef value?
454 return UndefValue::get(Ty);
456 case ValID::ConstZeroVal: // Is it a zero value?
457 return Constant::getNullValue(Ty);
459 case ValID::ConstantVal: // Fully resolved constant?
460 if (D.ConstantValue->getType() != Ty) {
461 GenerateError("Constant expression type different from required type");
464 return D.ConstantValue;
466 case ValID::InlineAsmVal: { // Inline asm expression
467 const PointerType *PTy = dyn_cast<PointerType>(Ty);
468 const FunctionType *FTy =
469 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
470 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
471 GenerateError("Invalid type for asm constraint string");
474 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
475 D.IAD->HasSideEffects);
476 D.destroy(); // Free InlineAsmDescriptor.
480 assert(0 && "Unhandled case!");
484 assert(0 && "Unhandled case!");
488 // getVal - This function is identical to getExistingVal, except that if a
489 // value is not already defined, it "improvises" by creating a placeholder var
490 // that looks and acts just like the requested variable. When the value is
491 // defined later, all uses of the placeholder variable are replaced with the
494 static Value *getVal(const Type *Ty, const ValID &ID) {
495 if (Ty == Type::LabelTy) {
496 GenerateError("Cannot use a basic block here");
500 // See if the value has already been defined.
501 Value *V = getExistingVal(Ty, ID);
503 if (TriggerError) return 0;
505 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
506 GenerateError("Invalid use of a non-first-class type");
510 // If we reached here, we referenced either a symbol that we don't know about
511 // or an id number that hasn't been read yet. We may be referencing something
512 // forward, so just create an entry to be resolved later and get to it...
515 case ValID::GlobalName:
516 case ValID::GlobalID: {
517 const PointerType *PTy = dyn_cast<PointerType>(Ty);
519 GenerateError("Invalid type for reference to global" );
522 const Type* ElTy = PTy->getElementType();
523 if (const FunctionType *FTy = dyn_cast<FunctionType>(ElTy))
524 V = Function::Create(FTy, GlobalValue::ExternalLinkage);
526 V = new GlobalVariable(ElTy, false, GlobalValue::ExternalLinkage, 0, "",
527 (Module*)0, false, PTy->getAddressSpace());
531 V = new Argument(Ty);
534 // Remember where this forward reference came from. FIXME, shouldn't we try
535 // to recycle these things??
536 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
539 if (inFunctionScope())
540 InsertValue(V, CurFun.LateResolveValues);
542 InsertValue(V, CurModule.LateResolveValues);
546 /// defineBBVal - This is a definition of a new basic block with the specified
547 /// identifier which must be the same as CurFun.NextValNum, if its numeric.
548 static BasicBlock *defineBBVal(const ValID &ID) {
549 assert(inFunctionScope() && "Can't get basic block at global scope!");
553 // First, see if this was forward referenced
555 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
556 if (BBI != CurFun.BBForwardRefs.end()) {
558 // The forward declaration could have been inserted anywhere in the
559 // function: insert it into the correct place now.
560 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
561 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
563 // We're about to erase the entry, save the key so we can clean it up.
564 ValID Tmp = BBI->first;
566 // Erase the forward ref from the map as its no longer "forward"
567 CurFun.BBForwardRefs.erase(ID);
569 // The key has been removed from the map but so we don't want to leave
570 // strdup'd memory around so destroy it too.
573 // If its a numbered definition, bump the number and set the BB value.
574 if (ID.Type == ValID::LocalID) {
575 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
579 // We haven't seen this BB before and its first mention is a definition.
580 // Just create it and return it.
581 std::string Name (ID.Type == ValID::LocalName ? ID.getName() : "");
582 BB = BasicBlock::Create(Name, CurFun.CurrentFunction);
583 if (ID.Type == ValID::LocalID) {
584 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
593 /// getBBVal - get an existing BB value or create a forward reference for it.
595 static BasicBlock *getBBVal(const ValID &ID) {
596 assert(inFunctionScope() && "Can't get basic block at global scope!");
600 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
601 if (BBI != CurFun.BBForwardRefs.end()) {
603 } if (ID.Type == ValID::LocalName) {
604 std::string Name = ID.getName();
605 Value *N = CurFun.CurrentFunction->getValueSymbolTable().lookup(Name);
607 if (N->getType()->getTypeID() == Type::LabelTyID)
608 BB = cast<BasicBlock>(N);
610 GenerateError("Reference to label '" + Name + "' is actually of type '"+
611 N->getType()->getDescription() + "'");
613 } else if (ID.Type == ValID::LocalID) {
614 if (ID.Num < CurFun.NextValNum && ID.Num < CurFun.Values.size()) {
615 if (CurFun.Values[ID.Num]->getType()->getTypeID() == Type::LabelTyID)
616 BB = cast<BasicBlock>(CurFun.Values[ID.Num]);
618 GenerateError("Reference to label '%" + utostr(ID.Num) +
619 "' is actually of type '"+
620 CurFun.Values[ID.Num]->getType()->getDescription() + "'");
623 GenerateError("Illegal label reference " + ID.getName());
627 // If its already been defined, return it now.
629 ID.destroy(); // Free strdup'd memory.
633 // Otherwise, this block has not been seen before, create it.
635 if (ID.Type == ValID::LocalName)
637 BB = BasicBlock::Create(Name, CurFun.CurrentFunction);
639 // Insert it in the forward refs map.
640 CurFun.BBForwardRefs[ID] = BB;
646 //===----------------------------------------------------------------------===//
647 // Code to handle forward references in instructions
648 //===----------------------------------------------------------------------===//
650 // This code handles the late binding needed with statements that reference
651 // values not defined yet... for example, a forward branch, or the PHI node for
654 // This keeps a table (CurFun.LateResolveValues) of all such forward references
655 // and back patchs after we are done.
658 // ResolveDefinitions - If we could not resolve some defs at parsing
659 // time (forward branches, phi functions for loops, etc...) resolve the
663 ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers) {
664 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
665 while (!LateResolvers.empty()) {
666 Value *V = LateResolvers.back();
667 LateResolvers.pop_back();
669 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
670 CurModule.PlaceHolderInfo.find(V);
671 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
673 ValID &DID = PHI->second.first;
675 Value *TheRealValue = getExistingVal(V->getType(), DID);
679 V->replaceAllUsesWith(TheRealValue);
681 CurModule.PlaceHolderInfo.erase(PHI);
682 } else if (FutureLateResolvers) {
683 // Functions have their unresolved items forwarded to the module late
685 InsertValue(V, *FutureLateResolvers);
687 if (DID.Type == ValID::LocalName || DID.Type == ValID::GlobalName) {
688 GenerateError("Reference to an invalid definition: '" +DID.getName()+
689 "' of type '" + V->getType()->getDescription() + "'",
693 GenerateError("Reference to an invalid definition: #" +
694 itostr(DID.Num) + " of type '" +
695 V->getType()->getDescription() + "'",
701 LateResolvers.clear();
704 // ResolveTypeTo - A brand new type was just declared. This means that (if
705 // name is not null) things referencing Name can be resolved. Otherwise, things
706 // refering to the number can be resolved. Do this now.
708 static void ResolveTypeTo(std::string *Name, const Type *ToTy) {
711 D = ValID::createLocalName(*Name);
713 D = ValID::createLocalID(CurModule.Types.size());
715 std::map<ValID, PATypeHolder>::iterator I =
716 CurModule.LateResolveTypes.find(D);
717 if (I != CurModule.LateResolveTypes.end()) {
718 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
720 CurModule.LateResolveTypes.erase(I);
725 // setValueName - Set the specified value to the name given. The name may be
726 // null potentially, in which case this is a noop. The string passed in is
727 // assumed to be a malloc'd string buffer, and is free'd by this function.
729 static void setValueName(Value *V, std::string *NameStr) {
730 if (!NameStr) return;
731 std::string Name(*NameStr); // Copy string
732 delete NameStr; // Free old string
734 if (V->getType() == Type::VoidTy) {
735 GenerateError("Can't assign name '" + Name+"' to value with void type");
739 assert(inFunctionScope() && "Must be in function scope!");
740 ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
741 if (ST.lookup(Name)) {
742 GenerateError("Redefinition of value '" + Name + "' of type '" +
743 V->getType()->getDescription() + "'");
751 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
752 /// this is a declaration, otherwise it is a definition.
753 static GlobalVariable *
754 ParseGlobalVariable(std::string *NameStr,
755 GlobalValue::LinkageTypes Linkage,
756 GlobalValue::VisibilityTypes Visibility,
757 bool isConstantGlobal, const Type *Ty,
758 Constant *Initializer, bool IsThreadLocal,
759 unsigned AddressSpace = 0) {
760 if (isa<FunctionType>(Ty)) {
761 GenerateError("Cannot declare global vars of function type");
764 if (Ty == Type::LabelTy) {
765 GenerateError("Cannot declare global vars of label type");
769 const PointerType *PTy = PointerType::get(Ty, AddressSpace);
773 Name = *NameStr; // Copy string
774 delete NameStr; // Free old string
777 // See if this global value was forward referenced. If so, recycle the
781 ID = ValID::createGlobalName(Name);
783 ID = ValID::createGlobalID(CurModule.Values.size());
786 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
787 // Move the global to the end of the list, from whereever it was
788 // previously inserted.
789 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
790 CurModule.CurrentModule->getGlobalList().remove(GV);
791 CurModule.CurrentModule->getGlobalList().push_back(GV);
792 GV->setInitializer(Initializer);
793 GV->setLinkage(Linkage);
794 GV->setVisibility(Visibility);
795 GV->setConstant(isConstantGlobal);
796 GV->setThreadLocal(IsThreadLocal);
797 InsertValue(GV, CurModule.Values);
804 // If this global has a name
806 // if the global we're parsing has an initializer (is a definition) and
807 // has external linkage.
808 if (Initializer && Linkage != GlobalValue::InternalLinkage)
809 // If there is already a global with external linkage with this name
810 if (CurModule.CurrentModule->getGlobalVariable(Name, false)) {
811 // If we allow this GVar to get created, it will be renamed in the
812 // symbol table because it conflicts with an existing GVar. We can't
813 // allow redefinition of GVars whose linking indicates that their name
814 // must stay the same. Issue the error.
815 GenerateError("Redefinition of global variable named '" + Name +
816 "' of type '" + Ty->getDescription() + "'");
821 // Otherwise there is no existing GV to use, create one now.
823 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
824 CurModule.CurrentModule, IsThreadLocal, AddressSpace);
825 GV->setVisibility(Visibility);
826 InsertValue(GV, CurModule.Values);
830 // setTypeName - Set the specified type to the name given. The name may be
831 // null potentially, in which case this is a noop. The string passed in is
832 // assumed to be a malloc'd string buffer, and is freed by this function.
834 // This function returns true if the type has already been defined, but is
835 // allowed to be redefined in the specified context. If the name is a new name
836 // for the type plane, it is inserted and false is returned.
837 static bool setTypeName(const Type *T, std::string *NameStr) {
838 assert(!inFunctionScope() && "Can't give types function-local names!");
839 if (NameStr == 0) return false;
841 std::string Name(*NameStr); // Copy string
842 delete NameStr; // Free old string
844 // We don't allow assigning names to void type
845 if (T == Type::VoidTy) {
846 GenerateError("Can't assign name '" + Name + "' to the void type");
850 // Set the type name, checking for conflicts as we do so.
851 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
853 if (AlreadyExists) { // Inserting a name that is already defined???
854 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
855 assert(Existing && "Conflict but no matching type?!");
857 // There is only one case where this is allowed: when we are refining an
858 // opaque type. In this case, Existing will be an opaque type.
859 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
860 // We ARE replacing an opaque type!
861 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
865 // Otherwise, this is an attempt to redefine a type. That's okay if
866 // the redefinition is identical to the original. This will be so if
867 // Existing and T point to the same Type object. In this one case we
868 // allow the equivalent redefinition.
869 if (Existing == T) return true; // Yes, it's equal.
871 // Any other kind of (non-equivalent) redefinition is an error.
872 GenerateError("Redefinition of type named '" + Name + "' of type '" +
873 T->getDescription() + "'");
879 //===----------------------------------------------------------------------===//
880 // Code for handling upreferences in type names...
883 // TypeContains - Returns true if Ty directly contains E in it.
885 static bool TypeContains(const Type *Ty, const Type *E) {
886 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
887 E) != Ty->subtype_end();
892 // NestingLevel - The number of nesting levels that need to be popped before
893 // this type is resolved.
894 unsigned NestingLevel;
896 // LastContainedTy - This is the type at the current binding level for the
897 // type. Every time we reduce the nesting level, this gets updated.
898 const Type *LastContainedTy;
900 // UpRefTy - This is the actual opaque type that the upreference is
904 UpRefRecord(unsigned NL, OpaqueType *URTy)
905 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
909 // UpRefs - A list of the outstanding upreferences that need to be resolved.
910 static std::vector<UpRefRecord> UpRefs;
912 /// HandleUpRefs - Every time we finish a new layer of types, this function is
913 /// called. It loops through the UpRefs vector, which is a list of the
914 /// currently active types. For each type, if the up reference is contained in
915 /// the newly completed type, we decrement the level count. When the level
916 /// count reaches zero, the upreferenced type is the type that is passed in:
917 /// thus we can complete the cycle.
919 static PATypeHolder HandleUpRefs(const Type *ty) {
920 // If Ty isn't abstract, or if there are no up-references in it, then there is
921 // nothing to resolve here.
922 if (!ty->isAbstract() || UpRefs.empty()) return ty;
925 UR_OUT("Type '" << Ty->getDescription() <<
926 "' newly formed. Resolving upreferences.\n" <<
927 UpRefs.size() << " upreferences active!\n");
929 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
930 // to zero), we resolve them all together before we resolve them to Ty. At
931 // the end of the loop, if there is anything to resolve to Ty, it will be in
933 OpaqueType *TypeToResolve = 0;
935 for (unsigned i = 0; i != UpRefs.size(); ++i) {
936 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
937 << UpRefs[i].second->getDescription() << ") = "
938 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
939 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
940 // Decrement level of upreference
941 unsigned Level = --UpRefs[i].NestingLevel;
942 UpRefs[i].LastContainedTy = Ty;
943 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
944 if (Level == 0) { // Upreference should be resolved!
945 if (!TypeToResolve) {
946 TypeToResolve = UpRefs[i].UpRefTy;
948 UR_OUT(" * Resolving upreference for "
949 << UpRefs[i].second->getDescription() << "\n";
950 std::string OldName = UpRefs[i].UpRefTy->getDescription());
951 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
952 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
953 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
955 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
956 --i; // Do not skip the next element...
962 UR_OUT(" * Resolving upreference for "
963 << UpRefs[i].second->getDescription() << "\n";
964 std::string OldName = TypeToResolve->getDescription());
965 TypeToResolve->refineAbstractTypeTo(Ty);
971 //===----------------------------------------------------------------------===//
972 // RunVMAsmParser - Define an interface to this parser
973 //===----------------------------------------------------------------------===//
975 static Module* RunParser(Module * M);
977 Module *llvm::RunVMAsmParser(llvm::MemoryBuffer *MB) {
979 Module *M = RunParser(new Module(LLLgetFilename()));
987 llvm::Module *ModuleVal;
988 llvm::Function *FunctionVal;
989 llvm::BasicBlock *BasicBlockVal;
990 llvm::TerminatorInst *TermInstVal;
991 llvm::Instruction *InstVal;
992 llvm::Constant *ConstVal;
994 const llvm::Type *PrimType;
995 std::list<llvm::PATypeHolder> *TypeList;
996 llvm::PATypeHolder *TypeVal;
997 llvm::Value *ValueVal;
998 std::vector<llvm::Value*> *ValueList;
999 std::vector<unsigned> *ConstantList;
1000 llvm::ArgListType *ArgList;
1001 llvm::TypeWithAttrs TypeWithAttrs;
1002 llvm::TypeWithAttrsList *TypeWithAttrsList;
1003 llvm::ParamList *ParamList;
1005 // Represent the RHS of PHI node
1006 std::list<std::pair<llvm::Value*,
1007 llvm::BasicBlock*> > *PHIList;
1008 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
1009 std::vector<llvm::Constant*> *ConstVector;
1011 llvm::GlobalValue::LinkageTypes Linkage;
1012 llvm::GlobalValue::VisibilityTypes Visibility;
1013 llvm::Attributes Attributes;
1014 llvm::APInt *APIntVal;
1019 llvm::APFloat *FPVal;
1022 std::string *StrVal; // This memory must be deleted
1023 llvm::ValID ValIDVal;
1025 llvm::Instruction::BinaryOps BinaryOpVal;
1026 llvm::Instruction::TermOps TermOpVal;
1027 llvm::Instruction::MemoryOps MemOpVal;
1028 llvm::Instruction::CastOps CastOpVal;
1029 llvm::Instruction::OtherOps OtherOpVal;
1030 llvm::ICmpInst::Predicate IPredicate;
1031 llvm::FCmpInst::Predicate FPredicate;
1034 %type <ModuleVal> Module
1035 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1036 %type <BasicBlockVal> BasicBlock InstructionList
1037 %type <TermInstVal> BBTerminatorInst
1038 %type <InstVal> Inst InstVal MemoryInst
1039 %type <ConstVal> ConstVal ConstExpr AliaseeRef
1040 %type <ConstVector> ConstVector
1041 %type <ArgList> ArgList ArgListH
1042 %type <PHIList> PHIList
1043 %type <ParamList> ParamList // For call param lists & GEP indices
1044 %type <ValueList> IndexList // For GEP indices
1045 %type <ConstantList> ConstantIndexList // For insertvalue/extractvalue indices
1046 %type <TypeList> TypeListI
1047 %type <TypeWithAttrsList> ArgTypeList ArgTypeListI
1048 %type <TypeWithAttrs> ArgType
1049 %type <JumpTable> JumpTable
1050 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1051 %type <BoolVal> ThreadLocal // 'thread_local' or not
1052 %type <BoolVal> OptVolatile // 'volatile' or not
1053 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1054 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
1055 %type <Linkage> GVInternalLinkage GVExternalLinkage
1056 %type <Linkage> FunctionDefineLinkage FunctionDeclareLinkage
1057 %type <Linkage> AliasLinkage
1058 %type <Visibility> GVVisibilityStyle
1060 // ValueRef - Unresolved reference to a definition or BB
1061 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1062 %type <ValueVal> ResolvedVal // <type> <valref> pair
1063 %type <ValueList> ReturnedVal
1064 // Tokens and types for handling constant integer values
1066 // ESINT64VAL - A negative number within long long range
1067 %token <SInt64Val> ESINT64VAL
1069 // EUINT64VAL - A positive number within uns. long long range
1070 %token <UInt64Val> EUINT64VAL
1072 // ESAPINTVAL - A negative number with arbitrary precision
1073 %token <APIntVal> ESAPINTVAL
1075 // EUAPINTVAL - A positive number with arbitrary precision
1076 %token <APIntVal> EUAPINTVAL
1078 %token <UIntVal> LOCALVAL_ID GLOBALVAL_ID // %123 @123
1079 %token <FPVal> FPVAL // Float or Double constant
1081 // Built in types...
1082 %type <TypeVal> Types ResultTypes
1083 %type <PrimType> PrimType // Classifications
1084 %token <PrimType> VOID INTTYPE
1085 %token <PrimType> FLOAT DOUBLE X86_FP80 FP128 PPC_FP128 LABEL
1089 %token<StrVal> LOCALVAR GLOBALVAR LABELSTR
1090 %token<StrVal> STRINGCONSTANT ATSTRINGCONSTANT PCTSTRINGCONSTANT
1091 %type <StrVal> LocalName OptLocalName OptLocalAssign
1092 %type <StrVal> GlobalName OptGlobalAssign GlobalAssign
1093 %type <StrVal> OptSection SectionString OptGC
1095 %type <UIntVal> OptAlign OptCAlign OptAddrSpace
1097 %token ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1098 %token DECLARE DEFINE GLOBAL CONSTANT SECTION ALIAS VOLATILE THREAD_LOCAL
1099 %token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
1100 %token DLLIMPORT DLLEXPORT EXTERN_WEAK COMMON
1101 %token OPAQUE EXTERNAL TARGET TRIPLE ALIGN ADDRSPACE
1102 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1103 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1105 %type <UIntVal> OptCallingConv LocalNumber
1106 %type <Attributes> OptAttributes Attribute
1107 %type <Attributes> OptFuncAttrs FuncAttr
1108 %type <Attributes> OptRetAttrs RetAttr
1110 // Basic Block Terminating Operators
1111 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1114 %type <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
1115 %token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1116 %token <BinaryOpVal> SHL LSHR ASHR
1118 %token <OtherOpVal> ICMP FCMP VICMP VFCMP
1119 %type <IPredicate> IPredicates
1120 %type <FPredicate> FPredicates
1121 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1122 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1124 // Memory Instructions
1125 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1128 %type <CastOpVal> CastOps
1129 %token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1130 %token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1133 %token <OtherOpVal> PHI_TOK SELECT VAARG
1134 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1135 %token <OtherOpVal> GETRESULT
1136 %token <OtherOpVal> EXTRACTVALUE INSERTVALUE
1138 // Function Attributes
1139 %token SIGNEXT ZEROEXT NORETURN INREG SRET NOUNWIND NOALIAS BYVAL NEST
1140 %token READNONE READONLY GC OPTSIZE NOINLINE ALWAYSINLINE SSP SSPREQ
1142 // Visibility Styles
1143 %token DEFAULT HIDDEN PROTECTED
1149 // Operations that are notably excluded from this list include:
1150 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1152 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1153 LogicalOps : SHL | LSHR | ASHR | AND | OR | XOR;
1154 CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1155 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1158 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1159 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1160 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1161 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1162 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1166 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1167 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1168 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1169 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1170 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1171 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1172 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1173 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1174 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1177 LocalName : LOCALVAR | STRINGCONSTANT | PCTSTRINGCONSTANT ;
1178 OptLocalName : LocalName | /*empty*/ { $$ = 0; };
1180 OptAddrSpace : ADDRSPACE '(' EUINT64VAL ')' { $$=$3; }
1181 | /*empty*/ { $$=0; };
1183 /// OptLocalAssign - Value producing statements have an optional assignment
1185 OptLocalAssign : LocalName '=' {
1194 LocalNumber : LOCALVAL_ID '=' {
1200 GlobalName : GLOBALVAR | ATSTRINGCONSTANT ;
1202 OptGlobalAssign : GlobalAssign
1208 GlobalAssign : GlobalName '=' {
1214 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1215 | WEAK { $$ = GlobalValue::WeakLinkage; }
1216 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1217 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1218 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1219 | COMMON { $$ = GlobalValue::CommonLinkage; }
1223 : DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1224 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1225 | EXTERNAL { $$ = GlobalValue::ExternalLinkage; }
1229 : /*empty*/ { $$ = GlobalValue::DefaultVisibility; }
1230 | DEFAULT { $$ = GlobalValue::DefaultVisibility; }
1231 | HIDDEN { $$ = GlobalValue::HiddenVisibility; }
1232 | PROTECTED { $$ = GlobalValue::ProtectedVisibility; }
1235 FunctionDeclareLinkage
1236 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1237 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1238 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1241 FunctionDefineLinkage
1242 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1243 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1244 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1245 | WEAK { $$ = GlobalValue::WeakLinkage; }
1246 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1250 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1251 | WEAK { $$ = GlobalValue::WeakLinkage; }
1252 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1255 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1256 CCC_TOK { $$ = CallingConv::C; } |
1257 FASTCC_TOK { $$ = CallingConv::Fast; } |
1258 COLDCC_TOK { $$ = CallingConv::Cold; } |
1259 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1260 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1262 if ((unsigned)$2 != $2)
1263 GEN_ERROR("Calling conv too large");
1268 Attribute : ZEROEXT { $$ = Attribute::ZExt; }
1269 | ZEXT { $$ = Attribute::ZExt; }
1270 | SIGNEXT { $$ = Attribute::SExt; }
1271 | SEXT { $$ = Attribute::SExt; }
1272 | INREG { $$ = Attribute::InReg; }
1273 | SRET { $$ = Attribute::StructRet; }
1274 | NOALIAS { $$ = Attribute::NoAlias; }
1275 | BYVAL { $$ = Attribute::ByVal; }
1276 | NEST { $$ = Attribute::Nest; }
1277 | ALIGN EUINT64VAL { $$ =
1278 Attribute::constructAlignmentFromInt($2); }
1281 OptAttributes : /* empty */ { $$ = Attribute::None; }
1282 | OptAttributes Attribute {
1287 RetAttr : INREG { $$ = Attribute::InReg; }
1288 | ZEROEXT { $$ = Attribute::ZExt; }
1289 | SIGNEXT { $$ = Attribute::SExt; }
1292 OptRetAttrs : /* empty */ { $$ = Attribute::None; }
1293 | OptRetAttrs RetAttr {
1299 FuncAttr : NORETURN { $$ = Attribute::NoReturn; }
1300 | NOUNWIND { $$ = Attribute::NoUnwind; }
1301 | INREG { $$ = Attribute::InReg; }
1302 | ZEROEXT { $$ = Attribute::ZExt; }
1303 | SIGNEXT { $$ = Attribute::SExt; }
1304 | READNONE { $$ = Attribute::ReadNone; }
1305 | READONLY { $$ = Attribute::ReadOnly; }
1306 | NOINLINE { $$ = Attribute::NoInline; }
1307 | ALWAYSINLINE { $$ = Attribute::AlwaysInline; }
1308 | OPTSIZE { $$ = Attribute::OptimizeForSize; }
1309 | SSP { $$ = Attribute::StackProtect; }
1310 | SSPREQ { $$ = Attribute::StackProtectReq; }
1313 OptFuncAttrs : /* empty */ { $$ = Attribute::None; }
1314 | OptFuncAttrs FuncAttr {
1320 OptGC : /* empty */ { $$ = 0; }
1321 | GC STRINGCONSTANT {
1326 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1327 // a comma before it.
1328 OptAlign : /*empty*/ { $$ = 0; } |
1331 if ($$ != 0 && !isPowerOf2_32($$))
1332 GEN_ERROR("Alignment must be a power of two");
1335 OptCAlign : /*empty*/ { $$ = 0; } |
1336 ',' ALIGN EUINT64VAL {
1338 if ($$ != 0 && !isPowerOf2_32($$))
1339 GEN_ERROR("Alignment must be a power of two");
1345 SectionString : SECTION STRINGCONSTANT {
1346 for (unsigned i = 0, e = $2->length(); i != e; ++i)
1347 if ((*$2)[i] == '"' || (*$2)[i] == '\\')
1348 GEN_ERROR("Invalid character in section name");
1353 OptSection : /*empty*/ { $$ = 0; } |
1354 SectionString { $$ = $1; };
1356 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1357 // is set to be the global we are processing.
1359 GlobalVarAttributes : /* empty */ {} |
1360 ',' GlobalVarAttribute GlobalVarAttributes {};
1361 GlobalVarAttribute : SectionString {
1362 CurGV->setSection(*$1);
1366 | ALIGN EUINT64VAL {
1367 if ($2 != 0 && !isPowerOf2_32($2))
1368 GEN_ERROR("Alignment must be a power of two");
1369 CurGV->setAlignment($2);
1373 //===----------------------------------------------------------------------===//
1374 // Types includes all predefined types... except void, because it can only be
1375 // used in specific contexts (function returning void for example).
1377 // Derived types are added later...
1379 PrimType : INTTYPE | FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80 | LABEL ;
1383 $$ = new PATypeHolder(OpaqueType::get());
1387 $$ = new PATypeHolder($1);
1390 | Types OptAddrSpace '*' { // Pointer type?
1391 if (*$1 == Type::LabelTy)
1392 GEN_ERROR("Cannot form a pointer to a basic block");
1393 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1, $2)));
1397 | SymbolicValueRef { // Named types are also simple types...
1398 const Type* tmp = getTypeVal($1);
1400 $$ = new PATypeHolder(tmp);
1402 | '\\' EUINT64VAL { // Type UpReference
1403 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range");
1404 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1405 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1406 $$ = new PATypeHolder(OT);
1407 UR_OUT("New Upreference!\n");
1410 | Types '(' ArgTypeListI ')' OptFuncAttrs {
1411 // Allow but ignore attributes on function types; this permits auto-upgrade.
1412 // FIXME: remove in LLVM 3.0.
1413 const Type *RetTy = *$1;
1414 if (!FunctionType::isValidReturnType(RetTy))
1415 GEN_ERROR("Invalid result type for LLVM function");
1417 std::vector<const Type*> Params;
1418 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1419 for (; I != E; ++I ) {
1420 const Type *Ty = I->Ty->get();
1421 Params.push_back(Ty);
1424 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1425 if (isVarArg) Params.pop_back();
1427 for (unsigned i = 0; i != Params.size(); ++i)
1428 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1429 GEN_ERROR("Function arguments must be value types!");
1433 FunctionType *FT = FunctionType::get(RetTy, Params, isVarArg);
1434 delete $1; // Delete the return type handle
1435 $$ = new PATypeHolder(HandleUpRefs(FT));
1437 // Delete the argument list
1438 for (I = $3->begin() ; I != E; ++I ) {
1445 | VOID '(' ArgTypeListI ')' OptFuncAttrs {
1446 // Allow but ignore attributes on function types; this permits auto-upgrade.
1447 // FIXME: remove in LLVM 3.0.
1448 std::vector<const Type*> Params;
1449 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1450 for ( ; I != E; ++I ) {
1451 const Type* Ty = I->Ty->get();
1452 Params.push_back(Ty);
1455 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1456 if (isVarArg) Params.pop_back();
1458 for (unsigned i = 0; i != Params.size(); ++i)
1459 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1460 GEN_ERROR("Function arguments must be value types!");
1464 FunctionType *FT = FunctionType::get($1, Params, isVarArg);
1465 $$ = new PATypeHolder(HandleUpRefs(FT));
1467 // Delete the argument list
1468 for (I = $3->begin() ; I != E; ++I ) {
1476 | '[' EUINT64VAL 'x' Types ']' { // Sized array type?
1477 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, $2)));
1481 | '<' EUINT64VAL 'x' Types '>' { // Vector type?
1482 const llvm::Type* ElemTy = $4->get();
1483 if ((unsigned)$2 != $2)
1484 GEN_ERROR("Unsigned result not equal to signed result");
1485 if (!ElemTy->isFloatingPoint() && !ElemTy->isInteger())
1486 GEN_ERROR("Element type of a VectorType must be primitive");
1487 $$ = new PATypeHolder(HandleUpRefs(VectorType::get(*$4, (unsigned)$2)));
1491 | '{' TypeListI '}' { // Structure type?
1492 std::vector<const Type*> Elements;
1493 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1494 E = $2->end(); I != E; ++I)
1495 Elements.push_back(*I);
1497 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1501 | '{' '}' { // Empty structure type?
1502 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1505 | '<' '{' TypeListI '}' '>' {
1506 std::vector<const Type*> Elements;
1507 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1508 E = $3->end(); I != E; ++I)
1509 Elements.push_back(*I);
1511 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1515 | '<' '{' '}' '>' { // Empty structure type?
1516 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1522 : Types OptAttributes {
1523 // Allow but ignore attributes on function types; this permits auto-upgrade.
1524 // FIXME: remove in LLVM 3.0.
1526 $$.Attrs = Attribute::None;
1532 if (!UpRefs.empty())
1533 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1534 if (!(*$1)->isFirstClassType() && !isa<StructType>($1->get()))
1535 GEN_ERROR("LLVM functions cannot return aggregate types");
1539 $$ = new PATypeHolder(Type::VoidTy);
1543 ArgTypeList : ArgType {
1544 $$ = new TypeWithAttrsList();
1548 | ArgTypeList ',' ArgType {
1549 ($$=$1)->push_back($3);
1556 | ArgTypeList ',' DOTDOTDOT {
1558 TypeWithAttrs TWA; TWA.Attrs = Attribute::None;
1559 TWA.Ty = new PATypeHolder(Type::VoidTy);
1564 $$ = new TypeWithAttrsList;
1565 TypeWithAttrs TWA; TWA.Attrs = Attribute::None;
1566 TWA.Ty = new PATypeHolder(Type::VoidTy);
1571 $$ = new TypeWithAttrsList();
1575 // TypeList - Used for struct declarations and as a basis for function type
1576 // declaration type lists
1579 $$ = new std::list<PATypeHolder>();
1584 | TypeListI ',' Types {
1585 ($$=$1)->push_back(*$3);
1590 // ConstVal - The various declarations that go into the constant pool. This
1591 // production is used ONLY to represent constants that show up AFTER a 'const',
1592 // 'constant' or 'global' token at global scope. Constants that can be inlined
1593 // into other expressions (such as integers and constexprs) are handled by the
1594 // ResolvedVal, ValueRef and ConstValueRef productions.
1596 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1597 if (!UpRefs.empty())
1598 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1599 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1601 GEN_ERROR("Cannot make array constant with type: '" +
1602 (*$1)->getDescription() + "'");
1603 const Type *ETy = ATy->getElementType();
1604 uint64_t NumElements = ATy->getNumElements();
1606 // Verify that we have the correct size...
1607 if (NumElements != uint64_t(-1) && NumElements != $3->size())
1608 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1609 utostr($3->size()) + " arguments, but has size of " +
1610 utostr(NumElements) + "");
1612 // Verify all elements are correct type!
1613 for (unsigned i = 0; i < $3->size(); i++) {
1614 if (ETy != (*$3)[i]->getType())
1615 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1616 ETy->getDescription() +"' as required!\nIt is of type '"+
1617 (*$3)[i]->getType()->getDescription() + "'.");
1620 $$ = ConstantArray::get(ATy, *$3);
1621 delete $1; delete $3;
1625 if (!UpRefs.empty())
1626 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1627 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1629 GEN_ERROR("Cannot make array constant with type: '" +
1630 (*$1)->getDescription() + "'");
1632 uint64_t NumElements = ATy->getNumElements();
1633 if (NumElements != uint64_t(-1) && NumElements != 0)
1634 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1635 " arguments, but has size of " + utostr(NumElements) +"");
1636 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1640 | Types 'c' STRINGCONSTANT {
1641 if (!UpRefs.empty())
1642 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1643 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1645 GEN_ERROR("Cannot make array constant with type: '" +
1646 (*$1)->getDescription() + "'");
1648 uint64_t NumElements = ATy->getNumElements();
1649 const Type *ETy = ATy->getElementType();
1650 if (NumElements != uint64_t(-1) && NumElements != $3->length())
1651 GEN_ERROR("Can't build string constant of size " +
1652 utostr($3->length()) +
1653 " when array has size " + utostr(NumElements) + "");
1654 std::vector<Constant*> Vals;
1655 if (ETy == Type::Int8Ty) {
1656 for (uint64_t i = 0; i < $3->length(); ++i)
1657 Vals.push_back(ConstantInt::get(ETy, (*$3)[i]));
1660 GEN_ERROR("Cannot build string arrays of non byte sized elements");
1663 $$ = ConstantArray::get(ATy, Vals);
1667 | Types '<' ConstVector '>' { // Nonempty unsized arr
1668 if (!UpRefs.empty())
1669 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1670 const VectorType *PTy = dyn_cast<VectorType>($1->get());
1672 GEN_ERROR("Cannot make packed constant with type: '" +
1673 (*$1)->getDescription() + "'");
1674 const Type *ETy = PTy->getElementType();
1675 unsigned NumElements = PTy->getNumElements();
1677 // Verify that we have the correct size...
1678 if (NumElements != unsigned(-1) && NumElements != (unsigned)$3->size())
1679 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1680 utostr($3->size()) + " arguments, but has size of " +
1681 utostr(NumElements) + "");
1683 // Verify all elements are correct type!
1684 for (unsigned i = 0; i < $3->size(); i++) {
1685 if (ETy != (*$3)[i]->getType())
1686 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1687 ETy->getDescription() +"' as required!\nIt is of type '"+
1688 (*$3)[i]->getType()->getDescription() + "'.");
1691 $$ = ConstantVector::get(PTy, *$3);
1692 delete $1; delete $3;
1695 | Types '{' ConstVector '}' {
1696 const StructType *STy = dyn_cast<StructType>($1->get());
1698 GEN_ERROR("Cannot make struct constant with type: '" +
1699 (*$1)->getDescription() + "'");
1701 if ($3->size() != STy->getNumContainedTypes())
1702 GEN_ERROR("Illegal number of initializers for structure type");
1704 // Check to ensure that constants are compatible with the type initializer!
1705 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1706 if ((*$3)[i]->getType() != STy->getElementType(i))
1707 GEN_ERROR("Expected type '" +
1708 STy->getElementType(i)->getDescription() +
1709 "' for element #" + utostr(i) +
1710 " of structure initializer");
1712 // Check to ensure that Type is not packed
1713 if (STy->isPacked())
1714 GEN_ERROR("Unpacked Initializer to vector type '" +
1715 STy->getDescription() + "'");
1717 $$ = ConstantStruct::get(STy, *$3);
1718 delete $1; delete $3;
1722 if (!UpRefs.empty())
1723 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1724 const StructType *STy = dyn_cast<StructType>($1->get());
1726 GEN_ERROR("Cannot make struct constant with type: '" +
1727 (*$1)->getDescription() + "'");
1729 if (STy->getNumContainedTypes() != 0)
1730 GEN_ERROR("Illegal number of initializers for structure type");
1732 // Check to ensure that Type is not packed
1733 if (STy->isPacked())
1734 GEN_ERROR("Unpacked Initializer to vector type '" +
1735 STy->getDescription() + "'");
1737 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1741 | Types '<' '{' ConstVector '}' '>' {
1742 const StructType *STy = dyn_cast<StructType>($1->get());
1744 GEN_ERROR("Cannot make struct constant with type: '" +
1745 (*$1)->getDescription() + "'");
1747 if ($4->size() != STy->getNumContainedTypes())
1748 GEN_ERROR("Illegal number of initializers for structure type");
1750 // Check to ensure that constants are compatible with the type initializer!
1751 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1752 if ((*$4)[i]->getType() != STy->getElementType(i))
1753 GEN_ERROR("Expected type '" +
1754 STy->getElementType(i)->getDescription() +
1755 "' for element #" + utostr(i) +
1756 " of structure initializer");
1758 // Check to ensure that Type is packed
1759 if (!STy->isPacked())
1760 GEN_ERROR("Vector initializer to non-vector type '" +
1761 STy->getDescription() + "'");
1763 $$ = ConstantStruct::get(STy, *$4);
1764 delete $1; delete $4;
1767 | Types '<' '{' '}' '>' {
1768 if (!UpRefs.empty())
1769 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1770 const StructType *STy = dyn_cast<StructType>($1->get());
1772 GEN_ERROR("Cannot make struct constant with type: '" +
1773 (*$1)->getDescription() + "'");
1775 if (STy->getNumContainedTypes() != 0)
1776 GEN_ERROR("Illegal number of initializers for structure type");
1778 // Check to ensure that Type is packed
1779 if (!STy->isPacked())
1780 GEN_ERROR("Vector initializer to non-vector type '" +
1781 STy->getDescription() + "'");
1783 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1788 if (!UpRefs.empty())
1789 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1790 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1792 GEN_ERROR("Cannot make null pointer constant with type: '" +
1793 (*$1)->getDescription() + "'");
1795 $$ = ConstantPointerNull::get(PTy);
1800 if (!UpRefs.empty())
1801 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1802 $$ = UndefValue::get($1->get());
1806 | Types SymbolicValueRef {
1807 if (!UpRefs.empty())
1808 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1809 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1811 GEN_ERROR("Global const reference must be a pointer type " + (*$1)->getDescription());
1813 // ConstExprs can exist in the body of a function, thus creating
1814 // GlobalValues whenever they refer to a variable. Because we are in
1815 // the context of a function, getExistingVal will search the functions
1816 // symbol table instead of the module symbol table for the global symbol,
1817 // which throws things all off. To get around this, we just tell
1818 // getExistingVal that we are at global scope here.
1820 Function *SavedCurFn = CurFun.CurrentFunction;
1821 CurFun.CurrentFunction = 0;
1823 Value *V = getExistingVal(Ty, $2);
1826 CurFun.CurrentFunction = SavedCurFn;
1828 // If this is an initializer for a constant pointer, which is referencing a
1829 // (currently) undefined variable, create a stub now that shall be replaced
1830 // in the future with the right type of variable.
1833 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1834 const PointerType *PT = cast<PointerType>(Ty);
1836 // First check to see if the forward references value is already created!
1837 PerModuleInfo::GlobalRefsType::iterator I =
1838 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1840 if (I != CurModule.GlobalRefs.end()) {
1841 V = I->second; // Placeholder already exists, use it...
1845 if ($2.Type == ValID::GlobalName)
1846 Name = $2.getName();
1847 else if ($2.Type != ValID::GlobalID)
1848 GEN_ERROR("Invalid reference to global");
1850 // Create the forward referenced global.
1852 if (const FunctionType *FTy =
1853 dyn_cast<FunctionType>(PT->getElementType())) {
1854 GV = Function::Create(FTy, GlobalValue::ExternalWeakLinkage, Name,
1855 CurModule.CurrentModule);
1857 GV = new GlobalVariable(PT->getElementType(), false,
1858 GlobalValue::ExternalWeakLinkage, 0,
1859 Name, CurModule.CurrentModule);
1862 // Keep track of the fact that we have a forward ref to recycle it
1863 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1868 $$ = cast<GlobalValue>(V);
1869 delete $1; // Free the type handle
1873 if (!UpRefs.empty())
1874 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1875 if ($1->get() != $2->getType())
1876 GEN_ERROR("Mismatched types for constant expression: " +
1877 (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1882 | Types ZEROINITIALIZER {
1883 if (!UpRefs.empty())
1884 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1885 const Type *Ty = $1->get();
1886 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1887 GEN_ERROR("Cannot create a null initialized value of this type");
1888 $$ = Constant::getNullValue(Ty);
1892 | Types ESINT64VAL { // integral constants
1893 if (IntegerType *IT = dyn_cast<IntegerType>($1->get())) {
1894 if (!ConstantInt::isValueValidForType(IT, $2))
1895 GEN_ERROR("Constant value doesn't fit in type");
1896 $$ = ConstantInt::get(IT, $2, true);
1898 GEN_ERROR("integer constant must have integer type");
1903 | Types ESAPINTVAL { // arbitrary precision integer constants
1904 if (IntegerType *IT = dyn_cast<IntegerType>($1->get())) {
1905 if ($2->getBitWidth() > IT->getBitWidth())
1906 GEN_ERROR("Constant value does not fit in type");
1907 $2->sextOrTrunc(IT->getBitWidth());
1908 $$ = ConstantInt::get(*$2);
1910 GEN_ERROR("integer constant must have integer type");
1916 | Types EUINT64VAL { // integral constants
1917 if (IntegerType *IT = dyn_cast<IntegerType>($1->get())) {
1918 if (!ConstantInt::isValueValidForType(IT, $2))
1919 GEN_ERROR("Constant value doesn't fit in type");
1920 $$ = ConstantInt::get(IT, $2, false);
1922 GEN_ERROR("integer constant must have integer type");
1927 | Types EUAPINTVAL { // arbitrary precision integer constants
1928 if (IntegerType *IT = dyn_cast<IntegerType>($1->get())) {
1929 if ($2->getBitWidth() > IT->getBitWidth())
1930 GEN_ERROR("Constant value does not fit in type");
1931 $2->zextOrTrunc(IT->getBitWidth());
1932 $$ = ConstantInt::get(*$2);
1934 GEN_ERROR("integer constant must have integer type");
1941 | Types TRUETOK { // Boolean constants
1942 if ($1->get() != Type::Int1Ty)
1943 GEN_ERROR("Constant true must have type i1");
1944 $$ = ConstantInt::getTrue();
1948 | Types FALSETOK { // Boolean constants
1949 if ($1->get() != Type::Int1Ty)
1950 GEN_ERROR("Constant false must have type i1");
1951 $$ = ConstantInt::getFalse();
1955 | Types FPVAL { // Floating point constants
1956 if (!ConstantFP::isValueValidForType($1->get(), *$2))
1957 GEN_ERROR("Floating point constant invalid for type");
1959 // Lexer has no type info, so builds all float and double FP constants
1960 // as double. Fix this here. Long double is done right.
1961 if (&$2->getSemantics()==&APFloat::IEEEdouble && $1->get()==Type::FloatTy) {
1963 $2->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
1966 $$ = ConstantFP::get(*$2);
1973 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1974 if (!UpRefs.empty())
1975 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1977 const Type *DestTy = $5->get();
1978 if (!CastInst::castIsValid($1, $3, DestTy))
1979 GEN_ERROR("invalid cast opcode for cast from '" +
1980 Val->getType()->getDescription() + "' to '" +
1981 DestTy->getDescription() + "'");
1982 $$ = ConstantExpr::getCast($1, $3, DestTy);
1985 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1986 if (!isa<PointerType>($3->getType()))
1987 GEN_ERROR("GetElementPtr requires a pointer operand");
1990 GetElementPtrInst::getIndexedType($3->getType(), $4->begin(), $4->end());
1992 GEN_ERROR("Index list invalid for constant getelementptr");
1994 SmallVector<Constant*, 8> IdxVec;
1995 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1996 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1997 IdxVec.push_back(C);
1999 GEN_ERROR("Indices to constant getelementptr must be constants");
2003 $$ = ConstantExpr::getGetElementPtr($3, &IdxVec[0], IdxVec.size());
2006 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2007 if ($3->getType() != Type::Int1Ty)
2008 GEN_ERROR("Select condition must be of boolean type");
2009 if ($5->getType() != $7->getType())
2010 GEN_ERROR("Select operand types must match");
2011 $$ = ConstantExpr::getSelect($3, $5, $7);
2014 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
2015 if ($3->getType() != $5->getType())
2016 GEN_ERROR("Binary operator types must match");
2018 $$ = ConstantExpr::get($1, $3, $5);
2020 | LogicalOps '(' ConstVal ',' ConstVal ')' {
2021 if ($3->getType() != $5->getType())
2022 GEN_ERROR("Logical operator types must match");
2023 if (!$3->getType()->isInteger()) {
2024 if (!isa<VectorType>($3->getType()) ||
2025 !cast<VectorType>($3->getType())->getElementType()->isInteger())
2026 GEN_ERROR("Logical operator requires integral operands");
2028 $$ = ConstantExpr::get($1, $3, $5);
2031 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
2032 if ($4->getType() != $6->getType())
2033 GEN_ERROR("icmp operand types must match");
2034 $$ = ConstantExpr::getICmp($2, $4, $6);
2036 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
2037 if ($4->getType() != $6->getType())
2038 GEN_ERROR("fcmp operand types must match");
2039 $$ = ConstantExpr::getFCmp($2, $4, $6);
2041 | VICMP IPredicates '(' ConstVal ',' ConstVal ')' {
2042 if ($4->getType() != $6->getType())
2043 GEN_ERROR("vicmp operand types must match");
2044 $$ = ConstantExpr::getVICmp($2, $4, $6);
2046 | VFCMP FPredicates '(' ConstVal ',' ConstVal ')' {
2047 if ($4->getType() != $6->getType())
2048 GEN_ERROR("vfcmp operand types must match");
2049 $$ = ConstantExpr::getVFCmp($2, $4, $6);
2051 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
2052 if (!ExtractElementInst::isValidOperands($3, $5))
2053 GEN_ERROR("Invalid extractelement operands");
2054 $$ = ConstantExpr::getExtractElement($3, $5);
2057 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2058 if (!InsertElementInst::isValidOperands($3, $5, $7))
2059 GEN_ERROR("Invalid insertelement operands");
2060 $$ = ConstantExpr::getInsertElement($3, $5, $7);
2063 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2064 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
2065 GEN_ERROR("Invalid shufflevector operands");
2066 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
2069 | EXTRACTVALUE '(' ConstVal ConstantIndexList ')' {
2070 if (!isa<StructType>($3->getType()) && !isa<ArrayType>($3->getType()))
2071 GEN_ERROR("ExtractValue requires an aggregate operand");
2073 $$ = ConstantExpr::getExtractValue($3, &(*$4)[0], $4->size());
2077 | INSERTVALUE '(' ConstVal ',' ConstVal ConstantIndexList ')' {
2078 if (!isa<StructType>($3->getType()) && !isa<ArrayType>($3->getType()))
2079 GEN_ERROR("InsertValue requires an aggregate operand");
2081 $$ = ConstantExpr::getInsertValue($3, $5, &(*$6)[0], $6->size());
2087 // ConstVector - A list of comma separated constants.
2088 ConstVector : ConstVector ',' ConstVal {
2089 ($$ = $1)->push_back($3);
2093 $$ = new std::vector<Constant*>();
2099 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
2100 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
2103 ThreadLocal : THREAD_LOCAL { $$ = true; } | { $$ = false; };
2105 // AliaseeRef - Match either GlobalValue or bitcast to GlobalValue.
2106 AliaseeRef : ResultTypes SymbolicValueRef {
2107 const Type* VTy = $1->get();
2108 Value *V = getVal(VTy, $2);
2110 GlobalValue* Aliasee = dyn_cast<GlobalValue>(V);
2112 GEN_ERROR("Aliases can be created only to global values");
2118 | BITCAST '(' AliaseeRef TO Types ')' {
2120 const Type *DestTy = $5->get();
2121 if (!CastInst::castIsValid($1, $3, DestTy))
2122 GEN_ERROR("invalid cast opcode for cast from '" +
2123 Val->getType()->getDescription() + "' to '" +
2124 DestTy->getDescription() + "'");
2126 $$ = ConstantExpr::getCast($1, $3, DestTy);
2131 //===----------------------------------------------------------------------===//
2132 // Rules to match Modules
2133 //===----------------------------------------------------------------------===//
2135 // Module rule: Capture the result of parsing the whole file into a result
2140 $$ = ParserResult = CurModule.CurrentModule;
2141 CurModule.ModuleDone();
2145 $$ = ParserResult = CurModule.CurrentModule;
2146 CurModule.ModuleDone();
2153 | DefinitionList Definition
2157 : DEFINE { CurFun.isDeclare = false; } Function {
2158 CurFun.FunctionDone();
2161 | DECLARE { CurFun.isDeclare = true; } FunctionProto {
2164 | MODULE ASM_TOK AsmBlock {
2167 | OptLocalAssign TYPE Types {
2168 if (!UpRefs.empty())
2169 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2170 // Eagerly resolve types. This is not an optimization, this is a
2171 // requirement that is due to the fact that we could have this:
2173 // %list = type { %list * }
2174 // %list = type { %list * } ; repeated type decl
2176 // If types are not resolved eagerly, then the two types will not be
2177 // determined to be the same type!
2179 ResolveTypeTo($1, *$3);
2181 if (!setTypeName(*$3, $1) && !$1) {
2183 // If this is a named type that is not a redefinition, add it to the slot
2185 CurModule.Types.push_back(*$3);
2191 | OptLocalAssign TYPE VOID {
2192 ResolveTypeTo($1, $3);
2194 if (!setTypeName($3, $1) && !$1) {
2196 // If this is a named type that is not a redefinition, add it to the slot
2198 CurModule.Types.push_back($3);
2202 | OptGlobalAssign GVVisibilityStyle ThreadLocal GlobalType ConstVal
2204 /* "Externally Visible" Linkage */
2206 GEN_ERROR("Global value initializer is not a constant");
2207 CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
2208 $2, $4, $5->getType(), $5, $3, $6);
2210 } GlobalVarAttributes {
2213 | OptGlobalAssign GVInternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2214 ConstVal OptAddrSpace {
2216 GEN_ERROR("Global value initializer is not a constant");
2217 CurGV = ParseGlobalVariable($1, $2, $3, $5, $6->getType(), $6, $4, $7);
2219 } GlobalVarAttributes {
2222 | OptGlobalAssign GVExternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2223 Types OptAddrSpace {
2224 if (!UpRefs.empty())
2225 GEN_ERROR("Invalid upreference in type: " + (*$6)->getDescription());
2226 CurGV = ParseGlobalVariable($1, $2, $3, $5, *$6, 0, $4, $7);
2229 } GlobalVarAttributes {
2233 | OptGlobalAssign GVVisibilityStyle ALIAS AliasLinkage AliaseeRef {
2240 GEN_ERROR("Alias name cannot be empty");
2242 Constant* Aliasee = $5;
2244 GEN_ERROR(std::string("Invalid aliasee for alias: ") + Name);
2246 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(), $4, Name, Aliasee,
2247 CurModule.CurrentModule);
2248 GA->setVisibility($2);
2249 InsertValue(GA, CurModule.Values);
2252 // If there was a forward reference of this alias, resolve it now.
2256 ID = ValID::createGlobalName(Name);
2258 ID = ValID::createGlobalID(CurModule.Values.size()-1);
2260 if (GlobalValue *FWGV =
2261 CurModule.GetForwardRefForGlobal(GA->getType(), ID)) {
2262 // Replace uses of the fwdref with the actual alias.
2263 FWGV->replaceAllUsesWith(GA);
2264 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(FWGV))
2265 GV->eraseFromParent();
2267 cast<Function>(FWGV)->eraseFromParent();
2273 | TARGET TargetDefinition {
2276 | DEPLIBS '=' LibrariesDefinition {
2282 AsmBlock : STRINGCONSTANT {
2283 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2284 if (AsmSoFar.empty())
2285 CurModule.CurrentModule->setModuleInlineAsm(*$1);
2287 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+*$1);
2292 TargetDefinition : TRIPLE '=' STRINGCONSTANT {
2293 CurModule.CurrentModule->setTargetTriple(*$3);
2296 | DATALAYOUT '=' STRINGCONSTANT {
2297 CurModule.CurrentModule->setDataLayout(*$3);
2301 LibrariesDefinition : '[' LibList ']';
2303 LibList : LibList ',' STRINGCONSTANT {
2304 CurModule.CurrentModule->addLibrary(*$3);
2309 CurModule.CurrentModule->addLibrary(*$1);
2313 | /* empty: end of list */ {
2318 //===----------------------------------------------------------------------===//
2319 // Rules to match Function Headers
2320 //===----------------------------------------------------------------------===//
2322 ArgListH : ArgListH ',' Types OptAttributes OptLocalName {
2323 if (!UpRefs.empty())
2324 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2325 if (!(*$3)->isFirstClassType())
2326 GEN_ERROR("Argument types must be first-class");
2327 ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
2332 | Types OptAttributes OptLocalName {
2333 if (!UpRefs.empty())
2334 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2335 if (!(*$1)->isFirstClassType())
2336 GEN_ERROR("Argument types must be first-class");
2337 ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2338 $$ = new ArgListType;
2343 ArgList : ArgListH {
2347 | ArgListH ',' DOTDOTDOT {
2349 struct ArgListEntry E;
2350 E.Ty = new PATypeHolder(Type::VoidTy);
2352 E.Attrs = Attribute::None;
2357 $$ = new ArgListType;
2358 struct ArgListEntry E;
2359 E.Ty = new PATypeHolder(Type::VoidTy);
2361 E.Attrs = Attribute::None;
2370 FunctionHeaderH : OptCallingConv OptRetAttrs ResultTypes GlobalName '(' ArgList ')'
2371 OptFuncAttrs OptSection OptAlign OptGC {
2372 std::string FunctionName(*$4);
2373 delete $4; // Free strdup'd memory!
2375 // Check the function result for abstractness if this is a define. We should
2376 // have no abstract types at this point
2377 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($3))
2378 GEN_ERROR("Reference to abstract result: "+ $3->get()->getDescription());
2380 if (!FunctionType::isValidReturnType(*$3))
2381 GEN_ERROR("Invalid result type for LLVM function");
2383 std::vector<const Type*> ParamTypeList;
2384 SmallVector<AttributeWithIndex, 8> Attrs;
2385 //FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2387 Attributes RetAttrs = $2;
2388 if ($8 != Attribute::None) {
2389 if ($8 & Attribute::ZExt) {
2390 RetAttrs = RetAttrs | Attribute::ZExt;
2391 $8 = $8 ^ Attribute::ZExt;
2393 if ($8 & Attribute::SExt) {
2394 RetAttrs = RetAttrs | Attribute::SExt;
2395 $8 = $8 ^ Attribute::SExt;
2397 if ($8 & Attribute::InReg) {
2398 RetAttrs = RetAttrs | Attribute::InReg;
2399 $8 = $8 ^ Attribute::InReg;
2402 if (RetAttrs != Attribute::None)
2403 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2404 if ($6) { // If there are arguments...
2406 for (ArgListType::iterator I = $6->begin(); I != $6->end(); ++I, ++index) {
2407 const Type* Ty = I->Ty->get();
2408 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2409 GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2410 ParamTypeList.push_back(Ty);
2411 if (Ty != Type::VoidTy && I->Attrs != Attribute::None)
2412 Attrs.push_back(AttributeWithIndex::get(index, I->Attrs));
2415 if ($8 != Attribute::None)
2416 Attrs.push_back(AttributeWithIndex::get(~0, $8));
2418 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2419 if (isVarArg) ParamTypeList.pop_back();
2423 PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2425 FunctionType *FT = FunctionType::get(*$3, ParamTypeList, isVarArg);
2426 const PointerType *PFT = PointerType::getUnqual(FT);
2430 if (!FunctionName.empty()) {
2431 ID = ValID::createGlobalName((char*)FunctionName.c_str());
2433 ID = ValID::createGlobalID(CurModule.Values.size());
2437 // See if this function was forward referenced. If so, recycle the object.
2438 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2439 // Move the function to the end of the list, from whereever it was
2440 // previously inserted.
2441 Fn = cast<Function>(FWRef);
2442 assert(Fn->getAttributes().isEmpty() &&
2443 "Forward reference has parameter attributes!");
2444 CurModule.CurrentModule->getFunctionList().remove(Fn);
2445 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2446 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2447 (Fn = CurModule.CurrentModule->getFunction(FunctionName))) {
2448 if (Fn->getFunctionType() != FT ) {
2449 // The existing function doesn't have the same type. This is an overload
2451 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2452 } else if (Fn->getAttributes() != PAL) {
2453 // The existing function doesn't have the same parameter attributes.
2454 // This is an overload error.
2455 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2456 } else if (!CurFun.isDeclare && !Fn->isDeclaration()) {
2457 // Neither the existing or the current function is a declaration and they
2458 // have the same name and same type. Clearly this is a redefinition.
2459 GEN_ERROR("Redefinition of function '" + FunctionName + "'");
2460 } else if (Fn->isDeclaration()) {
2461 // Make sure to strip off any argument names so we can't get conflicts.
2462 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2466 } else { // Not already defined?
2467 Fn = Function::Create(FT, GlobalValue::ExternalWeakLinkage, FunctionName,
2468 CurModule.CurrentModule);
2469 InsertValue(Fn, CurModule.Values);
2473 CurFun.FunctionStart(Fn);
2475 if (CurFun.isDeclare) {
2476 // If we have declaration, always overwrite linkage. This will allow us to
2477 // correctly handle cases, when pointer to function is passed as argument to
2478 // another function.
2479 Fn->setLinkage(CurFun.Linkage);
2480 Fn->setVisibility(CurFun.Visibility);
2482 Fn->setCallingConv($1);
2483 Fn->setAttributes(PAL);
2484 Fn->setAlignment($10);
2486 Fn->setSection(*$9);
2490 Fn->setGC($11->c_str());
2494 // Add all of the arguments we parsed to the function...
2495 if ($6) { // Is null if empty...
2496 if (isVarArg) { // Nuke the last entry
2497 assert($6->back().Ty->get() == Type::VoidTy && $6->back().Name == 0 &&
2498 "Not a varargs marker!");
2499 delete $6->back().Ty;
2500 $6->pop_back(); // Delete the last entry
2502 Function::arg_iterator ArgIt = Fn->arg_begin();
2503 Function::arg_iterator ArgEnd = Fn->arg_end();
2505 for (ArgListType::iterator I = $6->begin();
2506 I != $6->end() && ArgIt != ArgEnd; ++I, ++ArgIt) {
2507 delete I->Ty; // Delete the typeholder...
2508 setValueName(ArgIt, I->Name); // Insert arg into symtab...
2514 delete $6; // We're now done with the argument list
2519 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2521 FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2522 $$ = CurFun.CurrentFunction;
2524 // Make sure that we keep track of the linkage type even if there was a
2525 // previous "declare".
2527 $$->setVisibility($2);
2530 END : ENDTOK | '}'; // Allow end of '}' to end a function
2532 Function : BasicBlockList END {
2537 FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2538 CurFun.CurrentFunction->setLinkage($1);
2539 CurFun.CurrentFunction->setVisibility($2);
2540 $$ = CurFun.CurrentFunction;
2541 CurFun.FunctionDone();
2545 //===----------------------------------------------------------------------===//
2546 // Rules to match Basic Blocks
2547 //===----------------------------------------------------------------------===//
2549 OptSideEffect : /* empty */ {
2558 ConstValueRef : ESINT64VAL { // A reference to a direct constant
2559 $$ = ValID::create($1);
2563 $$ = ValID::create($1);
2566 | ESAPINTVAL { // arbitrary precision integer constants
2567 $$ = ValID::create(*$1, true);
2571 | EUAPINTVAL { // arbitrary precision integer constants
2572 $$ = ValID::create(*$1, false);
2576 | FPVAL { // Perhaps it's an FP constant?
2577 $$ = ValID::create($1);
2581 $$ = ValID::create(ConstantInt::getTrue());
2585 $$ = ValID::create(ConstantInt::getFalse());
2589 $$ = ValID::createNull();
2593 $$ = ValID::createUndef();
2596 | ZEROINITIALIZER { // A vector zero constant.
2597 $$ = ValID::createZeroInit();
2600 | '<' ConstVector '>' { // Nonempty unsized packed vector
2601 const Type *ETy = (*$2)[0]->getType();
2602 unsigned NumElements = $2->size();
2604 if (!ETy->isInteger() && !ETy->isFloatingPoint())
2605 GEN_ERROR("Invalid vector element type: " + ETy->getDescription());
2607 VectorType* pt = VectorType::get(ETy, NumElements);
2608 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(pt));
2610 // Verify all elements are correct type!
2611 for (unsigned i = 0; i < $2->size(); i++) {
2612 if (ETy != (*$2)[i]->getType())
2613 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2614 ETy->getDescription() +"' as required!\nIt is of type '" +
2615 (*$2)[i]->getType()->getDescription() + "'.");
2618 $$ = ValID::create(ConstantVector::get(pt, *$2));
2619 delete PTy; delete $2;
2622 | '[' ConstVector ']' { // Nonempty unsized arr
2623 const Type *ETy = (*$2)[0]->getType();
2624 uint64_t NumElements = $2->size();
2626 if (!ETy->isFirstClassType())
2627 GEN_ERROR("Invalid array element type: " + ETy->getDescription());
2629 ArrayType *ATy = ArrayType::get(ETy, NumElements);
2630 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(ATy));
2632 // Verify all elements are correct type!
2633 for (unsigned i = 0; i < $2->size(); i++) {
2634 if (ETy != (*$2)[i]->getType())
2635 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2636 ETy->getDescription() +"' as required!\nIt is of type '"+
2637 (*$2)[i]->getType()->getDescription() + "'.");
2640 $$ = ValID::create(ConstantArray::get(ATy, *$2));
2641 delete PTy; delete $2;
2645 // Use undef instead of an array because it's inconvenient to determine
2646 // the element type at this point, there being no elements to examine.
2647 $$ = ValID::createUndef();
2650 | 'c' STRINGCONSTANT {
2651 uint64_t NumElements = $2->length();
2652 const Type *ETy = Type::Int8Ty;
2654 ArrayType *ATy = ArrayType::get(ETy, NumElements);
2656 std::vector<Constant*> Vals;
2657 for (unsigned i = 0; i < $2->length(); ++i)
2658 Vals.push_back(ConstantInt::get(ETy, (*$2)[i]));
2660 $$ = ValID::create(ConstantArray::get(ATy, Vals));
2663 | '{' ConstVector '}' {
2664 std::vector<const Type*> Elements($2->size());
2665 for (unsigned i = 0, e = $2->size(); i != e; ++i)
2666 Elements[i] = (*$2)[i]->getType();
2668 const StructType *STy = StructType::get(Elements);
2669 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(STy));
2671 $$ = ValID::create(ConstantStruct::get(STy, *$2));
2672 delete PTy; delete $2;
2676 const StructType *STy = StructType::get(std::vector<const Type*>());
2677 $$ = ValID::create(ConstantStruct::get(STy, std::vector<Constant*>()));
2680 | '<' '{' ConstVector '}' '>' {
2681 std::vector<const Type*> Elements($3->size());
2682 for (unsigned i = 0, e = $3->size(); i != e; ++i)
2683 Elements[i] = (*$3)[i]->getType();
2685 const StructType *STy = StructType::get(Elements, /*isPacked=*/true);
2686 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(STy));
2688 $$ = ValID::create(ConstantStruct::get(STy, *$3));
2689 delete PTy; delete $3;
2693 const StructType *STy = StructType::get(std::vector<const Type*>(),
2695 $$ = ValID::create(ConstantStruct::get(STy, std::vector<Constant*>()));
2699 $$ = ValID::create($1);
2702 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2703 $$ = ValID::createInlineAsm(*$3, *$5, $2);
2709 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2712 SymbolicValueRef : LOCALVAL_ID { // Is it an integer reference...?
2713 $$ = ValID::createLocalID($1);
2717 $$ = ValID::createGlobalID($1);
2720 | LocalName { // Is it a named reference...?
2721 $$ = ValID::createLocalName(*$1);
2725 | GlobalName { // Is it a named reference...?
2726 $$ = ValID::createGlobalName(*$1);
2731 // ValueRef - A reference to a definition... either constant or symbolic
2732 ValueRef : SymbolicValueRef | ConstValueRef;
2735 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2736 // type immediately preceeds the value reference, and allows complex constant
2737 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2738 ResolvedVal : Types ValueRef {
2739 if (!UpRefs.empty())
2740 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2741 $$ = getVal(*$1, $2);
2747 ReturnedVal : ResolvedVal {
2748 $$ = new std::vector<Value *>();
2752 | ReturnedVal ',' ResolvedVal {
2753 ($$=$1)->push_back($3);
2757 BasicBlockList : BasicBlockList BasicBlock {
2761 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2767 // Basic blocks are terminated by branching instructions:
2768 // br, br/cc, switch, ret
2770 BasicBlock : InstructionList OptLocalAssign BBTerminatorInst {
2771 setValueName($3, $2);
2774 $1->getInstList().push_back($3);
2779 BasicBlock : InstructionList LocalNumber BBTerminatorInst {
2781 int ValNum = InsertValue($3);
2782 if (ValNum != (int)$2)
2783 GEN_ERROR("Result value number %" + utostr($2) +
2784 " is incorrect, expected %" + utostr((unsigned)ValNum));
2786 $1->getInstList().push_back($3);
2792 InstructionList : InstructionList Inst {
2793 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2794 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2795 if (CI2->getParent() == 0)
2796 $1->getInstList().push_back(CI2);
2797 $1->getInstList().push_back($2);
2801 | /* empty */ { // Empty space between instruction lists
2802 $$ = defineBBVal(ValID::createLocalID(CurFun.NextValNum));
2805 | LABELSTR { // Labelled (named) basic block
2806 $$ = defineBBVal(ValID::createLocalName(*$1));
2813 RET ReturnedVal { // Return with a result...
2814 ValueList &VL = *$2;
2815 assert(!VL.empty() && "Invalid ret operands!");
2816 const Type *ReturnType = CurFun.CurrentFunction->getReturnType();
2817 if (VL.size() > 1 ||
2818 (isa<StructType>(ReturnType) &&
2819 (VL.empty() || VL[0]->getType() != ReturnType))) {
2820 Value *RV = UndefValue::get(ReturnType);
2821 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
2822 Instruction *I = InsertValueInst::Create(RV, VL[i], i, "mrv");
2823 ($<BasicBlockVal>-1)->getInstList().push_back(I);
2826 $$ = ReturnInst::Create(RV);
2828 $$ = ReturnInst::Create(VL[0]);
2833 | RET VOID { // Return with no result...
2834 $$ = ReturnInst::Create();
2837 | BR LABEL ValueRef { // Unconditional Branch...
2838 BasicBlock* tmpBB = getBBVal($3);
2840 $$ = BranchInst::Create(tmpBB);
2841 } // Conditional Branch...
2842 | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2843 if (cast<IntegerType>($2)->getBitWidth() != 1)
2844 GEN_ERROR("Branch condition must have type i1");
2845 BasicBlock* tmpBBA = getBBVal($6);
2847 BasicBlock* tmpBBB = getBBVal($9);
2849 Value* tmpVal = getVal(Type::Int1Ty, $3);
2851 $$ = BranchInst::Create(tmpBBA, tmpBBB, tmpVal);
2853 | SWITCH INTTYPE ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2854 Value* tmpVal = getVal($2, $3);
2856 BasicBlock* tmpBB = getBBVal($6);
2858 SwitchInst *S = SwitchInst::Create(tmpVal, tmpBB, $8->size());
2861 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2863 for (; I != E; ++I) {
2864 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2865 S->addCase(CI, I->second);
2867 GEN_ERROR("Switch case is constant, but not a simple integer");
2872 | SWITCH INTTYPE ValueRef ',' LABEL ValueRef '[' ']' {
2873 Value* tmpVal = getVal($2, $3);
2875 BasicBlock* tmpBB = getBBVal($6);
2877 SwitchInst *S = SwitchInst::Create(tmpVal, tmpBB, 0);
2881 | INVOKE OptCallingConv OptRetAttrs ResultTypes ValueRef '(' ParamList ')'
2882 OptFuncAttrs TO LABEL ValueRef UNWIND LABEL ValueRef {
2884 // Handle the short syntax
2885 const PointerType *PFTy = 0;
2886 const FunctionType *Ty = 0;
2887 if (!(PFTy = dyn_cast<PointerType>($4->get())) ||
2888 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2889 // Pull out the types of all of the arguments...
2890 std::vector<const Type*> ParamTypes;
2891 ParamList::iterator I = $7->begin(), E = $7->end();
2892 for (; I != E; ++I) {
2893 const Type *Ty = I->Val->getType();
2894 if (Ty == Type::VoidTy)
2895 GEN_ERROR("Short call syntax cannot be used with varargs");
2896 ParamTypes.push_back(Ty);
2899 if (!FunctionType::isValidReturnType(*$4))
2900 GEN_ERROR("Invalid result type for LLVM function");
2902 Ty = FunctionType::get($4->get(), ParamTypes, false);
2903 PFTy = PointerType::getUnqual(Ty);
2908 Value *V = getVal(PFTy, $5); // Get the function we're calling...
2910 BasicBlock *Normal = getBBVal($12);
2912 BasicBlock *Except = getBBVal($15);
2915 SmallVector<AttributeWithIndex, 8> Attrs;
2916 //FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2918 Attributes RetAttrs = $3;
2919 if ($9 != Attribute::None) {
2920 if ($9 & Attribute::ZExt) {
2921 RetAttrs = RetAttrs | Attribute::ZExt;
2922 $9 = $9 ^ Attribute::ZExt;
2924 if ($9 & Attribute::SExt) {
2925 RetAttrs = RetAttrs | Attribute::SExt;
2926 $9 = $9 ^ Attribute::SExt;
2928 if ($9 & Attribute::InReg) {
2929 RetAttrs = RetAttrs | Attribute::InReg;
2930 $9 = $9 ^ Attribute::InReg;
2933 if (RetAttrs != Attribute::None)
2934 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2936 // Check the arguments
2938 if ($7->empty()) { // Has no arguments?
2939 // Make sure no arguments is a good thing!
2940 if (Ty->getNumParams() != 0)
2941 GEN_ERROR("No arguments passed to a function that "
2942 "expects arguments");
2943 } else { // Has arguments?
2944 // Loop through FunctionType's arguments and ensure they are specified
2946 FunctionType::param_iterator I = Ty->param_begin();
2947 FunctionType::param_iterator E = Ty->param_end();
2948 ParamList::iterator ArgI = $7->begin(), ArgE = $7->end();
2951 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
2952 if (ArgI->Val->getType() != *I)
2953 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2954 (*I)->getDescription() + "'");
2955 Args.push_back(ArgI->Val);
2956 if (ArgI->Attrs != Attribute::None)
2957 Attrs.push_back(AttributeWithIndex::get(index, ArgI->Attrs));
2960 if (Ty->isVarArg()) {
2962 for (; ArgI != ArgE; ++ArgI, ++index) {
2963 Args.push_back(ArgI->Val); // push the remaining varargs
2964 if (ArgI->Attrs != Attribute::None)
2965 Attrs.push_back(AttributeWithIndex::get(index, ArgI->Attrs));
2967 } else if (I != E || ArgI != ArgE)
2968 GEN_ERROR("Invalid number of parameters detected");
2970 if ($9 != Attribute::None)
2971 Attrs.push_back(AttributeWithIndex::get(~0, $9));
2974 PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2976 // Create the InvokeInst
2977 InvokeInst *II = InvokeInst::Create(V, Normal, Except,
2978 Args.begin(), Args.end());
2979 II->setCallingConv($2);
2980 II->setAttributes(PAL);
2986 $$ = new UnwindInst();
2990 $$ = new UnreachableInst();
2996 JumpTable : JumpTable INTTYPE ConstValueRef ',' LABEL ValueRef {
2998 Constant *V = cast<Constant>(getExistingVal($2, $3));
3001 GEN_ERROR("May only switch on a constant pool value");
3003 BasicBlock* tmpBB = getBBVal($6);
3005 $$->push_back(std::make_pair(V, tmpBB));
3007 | INTTYPE ConstValueRef ',' LABEL ValueRef {
3008 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
3009 Constant *V = cast<Constant>(getExistingVal($1, $2));
3013 GEN_ERROR("May only switch on a constant pool value");
3015 BasicBlock* tmpBB = getBBVal($5);
3017 $$->push_back(std::make_pair(V, tmpBB));
3020 Inst : OptLocalAssign InstVal {
3021 // Is this definition named?? if so, assign the name...
3022 setValueName($2, $1);
3029 Inst : LocalNumber InstVal {
3031 int ValNum = InsertValue($2);
3033 if (ValNum != (int)$1)
3034 GEN_ERROR("Result value number %" + utostr($1) +
3035 " is incorrect, expected %" + utostr((unsigned)ValNum));
3042 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
3043 if (!UpRefs.empty())
3044 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
3045 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
3046 Value* tmpVal = getVal(*$1, $3);
3048 BasicBlock* tmpBB = getBBVal($5);
3050 $$->push_back(std::make_pair(tmpVal, tmpBB));
3053 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
3055 Value* tmpVal = getVal($1->front().first->getType(), $4);
3057 BasicBlock* tmpBB = getBBVal($6);
3059 $1->push_back(std::make_pair(tmpVal, tmpBB));
3063 ParamList : Types OptAttributes ValueRef OptAttributes {
3064 // FIXME: Remove trailing OptAttributes in LLVM 3.0, it was a mistake in 2.0
3065 if (!UpRefs.empty())
3066 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
3067 // Used for call and invoke instructions
3068 $$ = new ParamList();
3069 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getVal($1->get(), $3);
3074 | LABEL OptAttributes ValueRef OptAttributes {
3075 // FIXME: Remove trailing OptAttributes in LLVM 3.0, it was a mistake in 2.0
3076 // Labels are only valid in ASMs
3077 $$ = new ParamList();
3078 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getBBVal($3);
3082 | ParamList ',' Types OptAttributes ValueRef OptAttributes {
3083 // FIXME: Remove trailing OptAttributes in LLVM 3.0, it was a mistake in 2.0
3084 if (!UpRefs.empty())
3085 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3087 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getVal($3->get(), $5);
3092 | ParamList ',' LABEL OptAttributes ValueRef OptAttributes {
3093 // FIXME: Remove trailing OptAttributes in LLVM 3.0, it was a mistake in 2.0
3095 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getBBVal($5);
3099 | /*empty*/ { $$ = new ParamList(); };
3101 IndexList // Used for gep instructions and constant expressions
3102 : /*empty*/ { $$ = new std::vector<Value*>(); }
3103 | IndexList ',' ResolvedVal {
3110 ConstantIndexList // Used for insertvalue and extractvalue instructions
3112 $$ = new std::vector<unsigned>();
3113 if ((unsigned)$2 != $2)
3114 GEN_ERROR("Index " + utostr($2) + " is not valid for insertvalue or extractvalue.");
3117 | ConstantIndexList ',' EUINT64VAL {
3119 if ((unsigned)$3 != $3)
3120 GEN_ERROR("Index " + utostr($3) + " is not valid for insertvalue or extractvalue.");
3126 OptTailCall : TAIL CALL {
3135 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
3136 if (!UpRefs.empty())
3137 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3138 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
3139 !isa<VectorType>((*$2).get()))
3141 "Arithmetic operator requires integer, FP, or packed operands");
3142 Value* val1 = getVal(*$2, $3);
3144 Value* val2 = getVal(*$2, $5);
3146 $$ = BinaryOperator::Create($1, val1, val2);
3148 GEN_ERROR("binary operator returned null");
3151 | LogicalOps Types ValueRef ',' ValueRef {
3152 if (!UpRefs.empty())
3153 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3154 if (!(*$2)->isInteger()) {
3155 if (!isa<VectorType>($2->get()) ||
3156 !cast<VectorType>($2->get())->getElementType()->isInteger())
3157 GEN_ERROR("Logical operator requires integral operands");
3159 Value* tmpVal1 = getVal(*$2, $3);
3161 Value* tmpVal2 = getVal(*$2, $5);
3163 $$ = BinaryOperator::Create($1, tmpVal1, tmpVal2);
3165 GEN_ERROR("binary operator returned null");
3168 | ICMP IPredicates Types ValueRef ',' ValueRef {
3169 if (!UpRefs.empty())
3170 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3171 Value* tmpVal1 = getVal(*$3, $4);
3173 Value* tmpVal2 = getVal(*$3, $6);
3175 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3177 GEN_ERROR("icmp operator returned null");
3180 | FCMP FPredicates Types ValueRef ',' ValueRef {
3181 if (!UpRefs.empty())
3182 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3183 Value* tmpVal1 = getVal(*$3, $4);
3185 Value* tmpVal2 = getVal(*$3, $6);
3187 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3189 GEN_ERROR("fcmp operator returned null");
3192 | VICMP IPredicates Types ValueRef ',' ValueRef {
3193 if (!UpRefs.empty())
3194 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3195 if (!isa<VectorType>((*$3).get()))
3196 GEN_ERROR("Scalar types not supported by vicmp instruction");
3197 Value* tmpVal1 = getVal(*$3, $4);
3199 Value* tmpVal2 = getVal(*$3, $6);
3201 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3203 GEN_ERROR("vicmp operator returned null");
3206 | VFCMP FPredicates Types ValueRef ',' ValueRef {
3207 if (!UpRefs.empty())
3208 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3209 if (!isa<VectorType>((*$3).get()))
3210 GEN_ERROR("Scalar types not supported by vfcmp instruction");
3211 Value* tmpVal1 = getVal(*$3, $4);
3213 Value* tmpVal2 = getVal(*$3, $6);
3215 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3217 GEN_ERROR("vfcmp operator returned null");
3220 | CastOps ResolvedVal TO Types {
3221 if (!UpRefs.empty())
3222 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
3224 const Type* DestTy = $4->get();
3225 if (!CastInst::castIsValid($1, Val, DestTy))
3226 GEN_ERROR("invalid cast opcode for cast from '" +
3227 Val->getType()->getDescription() + "' to '" +
3228 DestTy->getDescription() + "'");
3229 $$ = CastInst::Create($1, Val, DestTy);
3232 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3233 if (isa<VectorType>($2->getType())) {
3235 if (!isa<VectorType>($4->getType())
3236 || !isa<VectorType>($6->getType()) )
3237 GEN_ERROR("vector select value types must be vector types");
3238 const VectorType* cond_type = cast<VectorType>($2->getType());
3239 const VectorType* select_type = cast<VectorType>($4->getType());
3240 if (cond_type->getElementType() != Type::Int1Ty)
3241 GEN_ERROR("vector select condition element type must be boolean");
3242 if (cond_type->getNumElements() != select_type->getNumElements())
3243 GEN_ERROR("vector select number of elements must be the same");
3245 if ($2->getType() != Type::Int1Ty)
3246 GEN_ERROR("select condition must be boolean");
3248 if ($4->getType() != $6->getType())
3249 GEN_ERROR("select value types must match");
3250 $$ = SelectInst::Create($2, $4, $6);
3253 | VAARG ResolvedVal ',' Types {
3254 if (!UpRefs.empty())
3255 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
3256 $$ = new VAArgInst($2, *$4);
3260 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
3261 if (!ExtractElementInst::isValidOperands($2, $4))
3262 GEN_ERROR("Invalid extractelement operands");
3263 $$ = new ExtractElementInst($2, $4);
3266 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3267 if (!InsertElementInst::isValidOperands($2, $4, $6))
3268 GEN_ERROR("Invalid insertelement operands");
3269 $$ = InsertElementInst::Create($2, $4, $6);
3272 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3273 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
3274 GEN_ERROR("Invalid shufflevector operands");
3275 $$ = new ShuffleVectorInst($2, $4, $6);
3279 const Type *Ty = $2->front().first->getType();
3280 if (!Ty->isFirstClassType())
3281 GEN_ERROR("PHI node operands must be of first class type");
3282 $$ = PHINode::Create(Ty);
3283 ((PHINode*)$$)->reserveOperandSpace($2->size());
3284 while ($2->begin() != $2->end()) {
3285 if ($2->front().first->getType() != Ty)
3286 GEN_ERROR("All elements of a PHI node must be of the same type");
3287 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
3290 delete $2; // Free the list...
3293 | OptTailCall OptCallingConv OptRetAttrs ResultTypes ValueRef '(' ParamList ')'
3296 // Handle the short syntax
3297 const PointerType *PFTy = 0;
3298 const FunctionType *Ty = 0;
3299 if (!(PFTy = dyn_cast<PointerType>($4->get())) ||
3300 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3301 // Pull out the types of all of the arguments...
3302 std::vector<const Type*> ParamTypes;
3303 ParamList::iterator I = $7->begin(), E = $7->end();
3304 for (; I != E; ++I) {
3305 const Type *Ty = I->Val->getType();
3306 if (Ty == Type::VoidTy)
3307 GEN_ERROR("Short call syntax cannot be used with varargs");
3308 ParamTypes.push_back(Ty);
3311 if (!FunctionType::isValidReturnType(*$4))
3312 GEN_ERROR("Invalid result type for LLVM function");
3314 Ty = FunctionType::get($4->get(), ParamTypes, false);
3315 PFTy = PointerType::getUnqual(Ty);
3318 Value *V = getVal(PFTy, $5); // Get the function we're calling...
3321 // Check for call to invalid intrinsic to avoid crashing later.
3322 if (Function *theF = dyn_cast<Function>(V)) {
3323 if (theF->hasName() && (theF->getValueName()->getKeyLength() >= 5) &&
3324 (0 == strncmp(theF->getValueName()->getKeyData(), "llvm.", 5)) &&
3325 !theF->getIntrinsicID(true))
3326 GEN_ERROR("Call to invalid LLVM intrinsic function '" +
3327 theF->getName() + "'");
3330 // Set up the Attributes for the function
3331 SmallVector<AttributeWithIndex, 8> Attrs;
3332 //FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
3334 Attributes RetAttrs = $3;
3335 if ($9 != Attribute::None) {
3336 if ($9 & Attribute::ZExt) {
3337 RetAttrs = RetAttrs | Attribute::ZExt;
3338 $9 = $9 ^ Attribute::ZExt;
3340 if ($9 & Attribute::SExt) {
3341 RetAttrs = RetAttrs | Attribute::SExt;
3342 $9 = $9 ^ Attribute::SExt;
3344 if ($9 & Attribute::InReg) {
3345 RetAttrs = RetAttrs | Attribute::InReg;
3346 $9 = $9 ^ Attribute::InReg;
3349 if (RetAttrs != Attribute::None)
3350 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3352 // Check the arguments
3354 if ($7->empty()) { // Has no arguments?
3355 // Make sure no arguments is a good thing!
3356 if (Ty->getNumParams() != 0)
3357 GEN_ERROR("No arguments passed to a function that "
3358 "expects arguments");
3359 } else { // Has arguments?
3360 // Loop through FunctionType's arguments and ensure they are specified
3361 // correctly. Also, gather any parameter attributes.
3362 FunctionType::param_iterator I = Ty->param_begin();
3363 FunctionType::param_iterator E = Ty->param_end();
3364 ParamList::iterator ArgI = $7->begin(), ArgE = $7->end();
3367 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
3368 if (ArgI->Val->getType() != *I)
3369 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
3370 (*I)->getDescription() + "'");
3371 Args.push_back(ArgI->Val);
3372 if (ArgI->Attrs != Attribute::None)
3373 Attrs.push_back(AttributeWithIndex::get(index, ArgI->Attrs));
3375 if (Ty->isVarArg()) {
3377 for (; ArgI != ArgE; ++ArgI, ++index) {
3378 Args.push_back(ArgI->Val); // push the remaining varargs
3379 if (ArgI->Attrs != Attribute::None)
3380 Attrs.push_back(AttributeWithIndex::get(index, ArgI->Attrs));
3382 } else if (I != E || ArgI != ArgE)
3383 GEN_ERROR("Invalid number of parameters detected");
3385 if ($9 != Attribute::None)
3386 Attrs.push_back(AttributeWithIndex::get(~0, $9));
3388 // Finish off the Attributes and check them
3391 PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3393 // Create the call node
3394 CallInst *CI = CallInst::Create(V, Args.begin(), Args.end());
3395 CI->setTailCall($1);
3396 CI->setCallingConv($2);
3397 CI->setAttributes(PAL);
3408 OptVolatile : VOLATILE {
3419 MemoryInst : MALLOC Types OptCAlign {
3420 if (!UpRefs.empty())
3421 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3422 $$ = new MallocInst(*$2, 0, $3);
3426 | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
3427 if (!UpRefs.empty())
3428 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3429 if ($4 != Type::Int32Ty)
3430 GEN_ERROR("Malloc array size is not a 32-bit integer!");
3431 Value* tmpVal = getVal($4, $5);
3433 $$ = new MallocInst(*$2, tmpVal, $6);
3436 | ALLOCA Types OptCAlign {
3437 if (!UpRefs.empty())
3438 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3439 $$ = new AllocaInst(*$2, 0, $3);
3443 | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
3444 if (!UpRefs.empty())
3445 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3446 if ($4 != Type::Int32Ty)
3447 GEN_ERROR("Alloca array size is not a 32-bit integer!");
3448 Value* tmpVal = getVal($4, $5);
3450 $$ = new AllocaInst(*$2, tmpVal, $6);
3453 | FREE ResolvedVal {
3454 if (!isa<PointerType>($2->getType()))
3455 GEN_ERROR("Trying to free nonpointer type " +
3456 $2->getType()->getDescription() + "");
3457 $$ = new FreeInst($2);
3461 | OptVolatile LOAD Types ValueRef OptCAlign {
3462 if (!UpRefs.empty())
3463 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3464 if (!isa<PointerType>($3->get()))
3465 GEN_ERROR("Can't load from nonpointer type: " +
3466 (*$3)->getDescription());
3467 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
3468 GEN_ERROR("Can't load from pointer of non-first-class type: " +
3469 (*$3)->getDescription());
3470 Value* tmpVal = getVal(*$3, $4);
3472 $$ = new LoadInst(tmpVal, "", $1, $5);
3475 | OptVolatile STORE ResolvedVal ',' Types ValueRef OptCAlign {
3476 if (!UpRefs.empty())
3477 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
3478 const PointerType *PT = dyn_cast<PointerType>($5->get());
3480 GEN_ERROR("Can't store to a nonpointer type: " +
3481 (*$5)->getDescription());
3482 const Type *ElTy = PT->getElementType();
3483 if (ElTy != $3->getType())
3484 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
3485 "' into space of type '" + ElTy->getDescription() + "'");
3487 Value* tmpVal = getVal(*$5, $6);
3489 $$ = new StoreInst($3, tmpVal, $1, $7);
3492 | GETRESULT Types ValueRef ',' EUINT64VAL {
3493 if (!UpRefs.empty())
3494 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3495 if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3496 GEN_ERROR("getresult insn requires an aggregate operand");
3497 if (!ExtractValueInst::getIndexedType(*$2, $5))
3498 GEN_ERROR("Invalid getresult index for type '" +
3499 (*$2)->getDescription()+ "'");
3501 Value *tmpVal = getVal(*$2, $3);
3503 $$ = ExtractValueInst::Create(tmpVal, $5);
3506 | GETELEMENTPTR Types ValueRef IndexList {
3507 if (!UpRefs.empty())
3508 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3509 if (!isa<PointerType>($2->get()))
3510 GEN_ERROR("getelementptr insn requires pointer operand");
3512 if (!GetElementPtrInst::getIndexedType(*$2, $4->begin(), $4->end()))
3513 GEN_ERROR("Invalid getelementptr indices for type '" +
3514 (*$2)->getDescription()+ "'");
3515 Value* tmpVal = getVal(*$2, $3);
3517 $$ = GetElementPtrInst::Create(tmpVal, $4->begin(), $4->end());
3521 | EXTRACTVALUE Types ValueRef ConstantIndexList {
3522 if (!UpRefs.empty())
3523 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3524 if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3525 GEN_ERROR("extractvalue insn requires an aggregate operand");
3527 if (!ExtractValueInst::getIndexedType(*$2, $4->begin(), $4->end()))
3528 GEN_ERROR("Invalid extractvalue indices for type '" +
3529 (*$2)->getDescription()+ "'");
3530 Value* tmpVal = getVal(*$2, $3);
3532 $$ = ExtractValueInst::Create(tmpVal, $4->begin(), $4->end());
3536 | INSERTVALUE Types ValueRef ',' Types ValueRef ConstantIndexList {
3537 if (!UpRefs.empty())
3538 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3539 if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3540 GEN_ERROR("extractvalue insn requires an aggregate operand");
3542 if (ExtractValueInst::getIndexedType(*$2, $7->begin(), $7->end()) != $5->get())
3543 GEN_ERROR("Invalid insertvalue indices for type '" +
3544 (*$2)->getDescription()+ "'");
3545 Value* aggVal = getVal(*$2, $3);
3546 Value* tmpVal = getVal(*$5, $6);
3548 $$ = InsertValueInst::Create(aggVal, tmpVal, $7->begin(), $7->end());
3557 // common code from the two 'RunVMAsmParser' functions
3558 static Module* RunParser(Module * M) {
3559 CurModule.CurrentModule = M;
3560 // Check to make sure the parser succeeded
3563 delete ParserResult;
3567 // Emit an error if there are any unresolved types left.
3568 if (!CurModule.LateResolveTypes.empty()) {
3569 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
3570 if (DID.Type == ValID::LocalName) {
3571 GenerateError("Undefined type remains at eof: '"+DID.getName() + "'");
3573 GenerateError("Undefined type remains at eof: #" + itostr(DID.Num));
3576 delete ParserResult;
3580 // Emit an error if there are any unresolved values left.
3581 if (!CurModule.LateResolveValues.empty()) {
3582 Value *V = CurModule.LateResolveValues.back();
3583 std::map<Value*, std::pair<ValID, int> >::iterator I =
3584 CurModule.PlaceHolderInfo.find(V);
3586 if (I != CurModule.PlaceHolderInfo.end()) {
3587 ValID &DID = I->second.first;
3588 if (DID.Type == ValID::LocalName) {
3589 GenerateError("Undefined value remains at eof: "+DID.getName() + "'");
3591 GenerateError("Undefined value remains at eof: #" + itostr(DID.Num));
3594 delete ParserResult;
3599 // Check to make sure that parsing produced a result
3603 // Reset ParserResult variable while saving its value for the result.
3604 Module *Result = ParserResult;
3610 void llvm::GenerateError(const std::string &message, int LineNo) {
3611 if (LineNo == -1) LineNo = LLLgetLineNo();
3612 // TODO: column number in exception
3614 TheParseError->setError(LLLgetFilename(), message, LineNo);
3618 int yyerror(const char *ErrorMsg) {
3619 std::string where = LLLgetFilename() + ":" + utostr(LLLgetLineNo()) + ": ";
3620 std::string errMsg = where + "error: " + std::string(ErrorMsg);
3621 if (yychar != YYEMPTY && yychar != 0) {
3622 errMsg += " while reading token: '";
3623 errMsg += std::string(LLLgetTokenStart(),
3624 LLLgetTokenStart()+LLLgetTokenLength()) + "'";
3626 GenerateError(errMsg);