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,
440 return ConstantFP::get(*D.ConstPoolFP);
442 case ValID::ConstNullVal: // Is it a null value?
443 if (!isa<PointerType>(Ty)) {
444 GenerateError("Cannot create a a non pointer null");
447 return ConstantPointerNull::get(cast<PointerType>(Ty));
449 case ValID::ConstUndefVal: // Is it an undef value?
450 return UndefValue::get(Ty);
452 case ValID::ConstZeroVal: // Is it a zero value?
453 return Constant::getNullValue(Ty);
455 case ValID::ConstantVal: // Fully resolved constant?
456 if (D.ConstantValue->getType() != Ty) {
457 GenerateError("Constant expression type different from required type");
460 return D.ConstantValue;
462 case ValID::InlineAsmVal: { // Inline asm expression
463 const PointerType *PTy = dyn_cast<PointerType>(Ty);
464 const FunctionType *FTy =
465 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
466 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
467 GenerateError("Invalid type for asm constraint string");
470 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
471 D.IAD->HasSideEffects);
472 D.destroy(); // Free InlineAsmDescriptor.
476 assert(0 && "Unhandled case!");
480 assert(0 && "Unhandled case!");
484 // getVal - This function is identical to getExistingVal, except that if a
485 // value is not already defined, it "improvises" by creating a placeholder var
486 // that looks and acts just like the requested variable. When the value is
487 // defined later, all uses of the placeholder variable are replaced with the
490 static Value *getVal(const Type *Ty, const ValID &ID) {
491 if (Ty == Type::LabelTy) {
492 GenerateError("Cannot use a basic block here");
496 // See if the value has already been defined.
497 Value *V = getExistingVal(Ty, ID);
499 if (TriggerError) return 0;
501 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
502 GenerateError("Invalid use of a non-first-class type");
506 // If we reached here, we referenced either a symbol that we don't know about
507 // or an id number that hasn't been read yet. We may be referencing something
508 // forward, so just create an entry to be resolved later and get to it...
511 case ValID::GlobalName:
512 case ValID::GlobalID: {
513 const PointerType *PTy = dyn_cast<PointerType>(Ty);
515 GenerateError("Invalid type for reference to global" );
518 const Type* ElTy = PTy->getElementType();
519 if (const FunctionType *FTy = dyn_cast<FunctionType>(ElTy))
520 V = Function::Create(FTy, GlobalValue::ExternalLinkage);
522 V = new GlobalVariable(ElTy, false, GlobalValue::ExternalLinkage, 0, "",
523 (Module*)0, false, PTy->getAddressSpace());
527 V = new Argument(Ty);
530 // Remember where this forward reference came from. FIXME, shouldn't we try
531 // to recycle these things??
532 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
535 if (inFunctionScope())
536 InsertValue(V, CurFun.LateResolveValues);
538 InsertValue(V, CurModule.LateResolveValues);
542 /// defineBBVal - This is a definition of a new basic block with the specified
543 /// identifier which must be the same as CurFun.NextValNum, if its numeric.
544 static BasicBlock *defineBBVal(const ValID &ID) {
545 assert(inFunctionScope() && "Can't get basic block at global scope!");
549 // First, see if this was forward referenced
551 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
552 if (BBI != CurFun.BBForwardRefs.end()) {
554 // The forward declaration could have been inserted anywhere in the
555 // function: insert it into the correct place now.
556 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
557 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
559 // We're about to erase the entry, save the key so we can clean it up.
560 ValID Tmp = BBI->first;
562 // Erase the forward ref from the map as its no longer "forward"
563 CurFun.BBForwardRefs.erase(ID);
565 // The key has been removed from the map but so we don't want to leave
566 // strdup'd memory around so destroy it too.
569 // If its a numbered definition, bump the number and set the BB value.
570 if (ID.Type == ValID::LocalID) {
571 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
575 // We haven't seen this BB before and its first mention is a definition.
576 // Just create it and return it.
577 std::string Name (ID.Type == ValID::LocalName ? ID.getName() : "");
578 BB = BasicBlock::Create(Name, CurFun.CurrentFunction);
579 if (ID.Type == ValID::LocalID) {
580 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
589 /// getBBVal - get an existing BB value or create a forward reference for it.
591 static BasicBlock *getBBVal(const ValID &ID) {
592 assert(inFunctionScope() && "Can't get basic block at global scope!");
596 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
597 if (BBI != CurFun.BBForwardRefs.end()) {
599 } if (ID.Type == ValID::LocalName) {
600 std::string Name = ID.getName();
601 Value *N = CurFun.CurrentFunction->getValueSymbolTable().lookup(Name);
603 if (N->getType()->getTypeID() == Type::LabelTyID)
604 BB = cast<BasicBlock>(N);
606 GenerateError("Reference to label '" + Name + "' is actually of type '"+
607 N->getType()->getDescription() + "'");
609 } else if (ID.Type == ValID::LocalID) {
610 if (ID.Num < CurFun.NextValNum && ID.Num < CurFun.Values.size()) {
611 if (CurFun.Values[ID.Num]->getType()->getTypeID() == Type::LabelTyID)
612 BB = cast<BasicBlock>(CurFun.Values[ID.Num]);
614 GenerateError("Reference to label '%" + utostr(ID.Num) +
615 "' is actually of type '"+
616 CurFun.Values[ID.Num]->getType()->getDescription() + "'");
619 GenerateError("Illegal label reference " + ID.getName());
623 // If its already been defined, return it now.
625 ID.destroy(); // Free strdup'd memory.
629 // Otherwise, this block has not been seen before, create it.
631 if (ID.Type == ValID::LocalName)
633 BB = BasicBlock::Create(Name, CurFun.CurrentFunction);
635 // Insert it in the forward refs map.
636 CurFun.BBForwardRefs[ID] = BB;
642 //===----------------------------------------------------------------------===//
643 // Code to handle forward references in instructions
644 //===----------------------------------------------------------------------===//
646 // This code handles the late binding needed with statements that reference
647 // values not defined yet... for example, a forward branch, or the PHI node for
650 // This keeps a table (CurFun.LateResolveValues) of all such forward references
651 // and back patchs after we are done.
654 // ResolveDefinitions - If we could not resolve some defs at parsing
655 // time (forward branches, phi functions for loops, etc...) resolve the
659 ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers) {
660 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
661 while (!LateResolvers.empty()) {
662 Value *V = LateResolvers.back();
663 LateResolvers.pop_back();
665 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
666 CurModule.PlaceHolderInfo.find(V);
667 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
669 ValID &DID = PHI->second.first;
671 Value *TheRealValue = getExistingVal(V->getType(), DID);
675 V->replaceAllUsesWith(TheRealValue);
677 CurModule.PlaceHolderInfo.erase(PHI);
678 } else if (FutureLateResolvers) {
679 // Functions have their unresolved items forwarded to the module late
681 InsertValue(V, *FutureLateResolvers);
683 if (DID.Type == ValID::LocalName || DID.Type == ValID::GlobalName) {
684 GenerateError("Reference to an invalid definition: '" +DID.getName()+
685 "' of type '" + V->getType()->getDescription() + "'",
689 GenerateError("Reference to an invalid definition: #" +
690 itostr(DID.Num) + " of type '" +
691 V->getType()->getDescription() + "'",
697 LateResolvers.clear();
700 // ResolveTypeTo - A brand new type was just declared. This means that (if
701 // name is not null) things referencing Name can be resolved. Otherwise, things
702 // refering to the number can be resolved. Do this now.
704 static void ResolveTypeTo(std::string *Name, const Type *ToTy) {
707 D = ValID::createLocalName(*Name);
709 D = ValID::createLocalID(CurModule.Types.size());
711 std::map<ValID, PATypeHolder>::iterator I =
712 CurModule.LateResolveTypes.find(D);
713 if (I != CurModule.LateResolveTypes.end()) {
714 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
716 CurModule.LateResolveTypes.erase(I);
721 // setValueName - Set the specified value to the name given. The name may be
722 // null potentially, in which case this is a noop. The string passed in is
723 // assumed to be a malloc'd string buffer, and is free'd by this function.
725 static void setValueName(Value *V, std::string *NameStr) {
726 if (!NameStr) return;
727 std::string Name(*NameStr); // Copy string
728 delete NameStr; // Free old string
730 if (V->getType() == Type::VoidTy) {
731 GenerateError("Can't assign name '" + Name+"' to value with void type");
735 assert(inFunctionScope() && "Must be in function scope!");
736 ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
737 if (ST.lookup(Name)) {
738 GenerateError("Redefinition of value '" + Name + "' of type '" +
739 V->getType()->getDescription() + "'");
747 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
748 /// this is a declaration, otherwise it is a definition.
749 static GlobalVariable *
750 ParseGlobalVariable(std::string *NameStr,
751 GlobalValue::LinkageTypes Linkage,
752 GlobalValue::VisibilityTypes Visibility,
753 bool isConstantGlobal, const Type *Ty,
754 Constant *Initializer, bool IsThreadLocal,
755 unsigned AddressSpace = 0) {
756 if (isa<FunctionType>(Ty)) {
757 GenerateError("Cannot declare global vars of function type");
760 if (Ty == Type::LabelTy) {
761 GenerateError("Cannot declare global vars of label type");
765 const PointerType *PTy = PointerType::get(Ty, AddressSpace);
769 Name = *NameStr; // Copy string
770 delete NameStr; // Free old string
773 // See if this global value was forward referenced. If so, recycle the
777 ID = ValID::createGlobalName(Name);
779 ID = ValID::createGlobalID(CurModule.Values.size());
782 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
783 // Move the global to the end of the list, from whereever it was
784 // previously inserted.
785 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
786 CurModule.CurrentModule->getGlobalList().remove(GV);
787 CurModule.CurrentModule->getGlobalList().push_back(GV);
788 GV->setInitializer(Initializer);
789 GV->setLinkage(Linkage);
790 GV->setVisibility(Visibility);
791 GV->setConstant(isConstantGlobal);
792 GV->setThreadLocal(IsThreadLocal);
793 InsertValue(GV, CurModule.Values);
800 // If this global has a name
802 // if the global we're parsing has an initializer (is a definition) and
803 // has external linkage.
804 if (Initializer && Linkage != GlobalValue::InternalLinkage)
805 // If there is already a global with external linkage with this name
806 if (CurModule.CurrentModule->getGlobalVariable(Name, false)) {
807 // If we allow this GVar to get created, it will be renamed in the
808 // symbol table because it conflicts with an existing GVar. We can't
809 // allow redefinition of GVars whose linking indicates that their name
810 // must stay the same. Issue the error.
811 GenerateError("Redefinition of global variable named '" + Name +
812 "' of type '" + Ty->getDescription() + "'");
817 // Otherwise there is no existing GV to use, create one now.
819 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
820 CurModule.CurrentModule, IsThreadLocal, AddressSpace);
821 GV->setVisibility(Visibility);
822 InsertValue(GV, CurModule.Values);
826 // setTypeName - Set the specified type to the name given. The name may be
827 // null potentially, in which case this is a noop. The string passed in is
828 // assumed to be a malloc'd string buffer, and is freed by this function.
830 // This function returns true if the type has already been defined, but is
831 // allowed to be redefined in the specified context. If the name is a new name
832 // for the type plane, it is inserted and false is returned.
833 static bool setTypeName(const Type *T, std::string *NameStr) {
834 assert(!inFunctionScope() && "Can't give types function-local names!");
835 if (NameStr == 0) return false;
837 std::string Name(*NameStr); // Copy string
838 delete NameStr; // Free old string
840 // We don't allow assigning names to void type
841 if (T == Type::VoidTy) {
842 GenerateError("Can't assign name '" + Name + "' to the void type");
846 // Set the type name, checking for conflicts as we do so.
847 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
849 if (AlreadyExists) { // Inserting a name that is already defined???
850 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
851 assert(Existing && "Conflict but no matching type?!");
853 // There is only one case where this is allowed: when we are refining an
854 // opaque type. In this case, Existing will be an opaque type.
855 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
856 // We ARE replacing an opaque type!
857 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
861 // Otherwise, this is an attempt to redefine a type. That's okay if
862 // the redefinition is identical to the original. This will be so if
863 // Existing and T point to the same Type object. In this one case we
864 // allow the equivalent redefinition.
865 if (Existing == T) return true; // Yes, it's equal.
867 // Any other kind of (non-equivalent) redefinition is an error.
868 GenerateError("Redefinition of type named '" + Name + "' of type '" +
869 T->getDescription() + "'");
875 //===----------------------------------------------------------------------===//
876 // Code for handling upreferences in type names...
879 // TypeContains - Returns true if Ty directly contains E in it.
881 static bool TypeContains(const Type *Ty, const Type *E) {
882 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
883 E) != Ty->subtype_end();
888 // NestingLevel - The number of nesting levels that need to be popped before
889 // this type is resolved.
890 unsigned NestingLevel;
892 // LastContainedTy - This is the type at the current binding level for the
893 // type. Every time we reduce the nesting level, this gets updated.
894 const Type *LastContainedTy;
896 // UpRefTy - This is the actual opaque type that the upreference is
900 UpRefRecord(unsigned NL, OpaqueType *URTy)
901 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
905 // UpRefs - A list of the outstanding upreferences that need to be resolved.
906 static std::vector<UpRefRecord> UpRefs;
908 /// HandleUpRefs - Every time we finish a new layer of types, this function is
909 /// called. It loops through the UpRefs vector, which is a list of the
910 /// currently active types. For each type, if the up reference is contained in
911 /// the newly completed type, we decrement the level count. When the level
912 /// count reaches zero, the upreferenced type is the type that is passed in:
913 /// thus we can complete the cycle.
915 static PATypeHolder HandleUpRefs(const Type *ty) {
916 // If Ty isn't abstract, or if there are no up-references in it, then there is
917 // nothing to resolve here.
918 if (!ty->isAbstract() || UpRefs.empty()) return ty;
921 UR_OUT("Type '" << Ty->getDescription() <<
922 "' newly formed. Resolving upreferences.\n" <<
923 UpRefs.size() << " upreferences active!\n");
925 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
926 // to zero), we resolve them all together before we resolve them to Ty. At
927 // the end of the loop, if there is anything to resolve to Ty, it will be in
929 OpaqueType *TypeToResolve = 0;
931 for (unsigned i = 0; i != UpRefs.size(); ++i) {
932 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
933 << UpRefs[i].second->getDescription() << ") = "
934 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
935 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
936 // Decrement level of upreference
937 unsigned Level = --UpRefs[i].NestingLevel;
938 UpRefs[i].LastContainedTy = Ty;
939 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
940 if (Level == 0) { // Upreference should be resolved!
941 if (!TypeToResolve) {
942 TypeToResolve = UpRefs[i].UpRefTy;
944 UR_OUT(" * Resolving upreference for "
945 << UpRefs[i].second->getDescription() << "\n";
946 std::string OldName = UpRefs[i].UpRefTy->getDescription());
947 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
948 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
949 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
951 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
952 --i; // Do not skip the next element...
958 UR_OUT(" * Resolving upreference for "
959 << UpRefs[i].second->getDescription() << "\n";
960 std::string OldName = TypeToResolve->getDescription());
961 TypeToResolve->refineAbstractTypeTo(Ty);
967 //===----------------------------------------------------------------------===//
968 // RunVMAsmParser - Define an interface to this parser
969 //===----------------------------------------------------------------------===//
971 static Module* RunParser(Module * M);
973 Module *llvm::RunVMAsmParser(llvm::MemoryBuffer *MB) {
975 Module *M = RunParser(new Module(LLLgetFilename()));
983 llvm::Module *ModuleVal;
984 llvm::Function *FunctionVal;
985 llvm::BasicBlock *BasicBlockVal;
986 llvm::TerminatorInst *TermInstVal;
987 llvm::Instruction *InstVal;
988 llvm::Constant *ConstVal;
990 const llvm::Type *PrimType;
991 std::list<llvm::PATypeHolder> *TypeList;
992 llvm::PATypeHolder *TypeVal;
993 llvm::Value *ValueVal;
994 std::vector<llvm::Value*> *ValueList;
995 std::vector<unsigned> *ConstantList;
996 llvm::ArgListType *ArgList;
997 llvm::TypeWithAttrs TypeWithAttrs;
998 llvm::TypeWithAttrsList *TypeWithAttrsList;
999 llvm::ParamList *ParamList;
1001 // Represent the RHS of PHI node
1002 std::list<std::pair<llvm::Value*,
1003 llvm::BasicBlock*> > *PHIList;
1004 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
1005 std::vector<llvm::Constant*> *ConstVector;
1007 llvm::GlobalValue::LinkageTypes Linkage;
1008 llvm::GlobalValue::VisibilityTypes Visibility;
1009 llvm::Attributes Attributes;
1010 llvm::APInt *APIntVal;
1015 llvm::APFloat *FPVal;
1018 std::string *StrVal; // This memory must be deleted
1019 llvm::ValID ValIDVal;
1021 llvm::Instruction::BinaryOps BinaryOpVal;
1022 llvm::Instruction::TermOps TermOpVal;
1023 llvm::Instruction::MemoryOps MemOpVal;
1024 llvm::Instruction::CastOps CastOpVal;
1025 llvm::Instruction::OtherOps OtherOpVal;
1026 llvm::ICmpInst::Predicate IPredicate;
1027 llvm::FCmpInst::Predicate FPredicate;
1030 %type <ModuleVal> Module
1031 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1032 %type <BasicBlockVal> BasicBlock InstructionList
1033 %type <TermInstVal> BBTerminatorInst
1034 %type <InstVal> Inst InstVal MemoryInst
1035 %type <ConstVal> ConstVal ConstExpr AliaseeRef
1036 %type <ConstVector> ConstVector
1037 %type <ArgList> ArgList ArgListH
1038 %type <PHIList> PHIList
1039 %type <ParamList> ParamList // For call param lists & GEP indices
1040 %type <ValueList> IndexList // For GEP indices
1041 %type <ConstantList> ConstantIndexList // For insertvalue/extractvalue indices
1042 %type <TypeList> TypeListI
1043 %type <TypeWithAttrsList> ArgTypeList ArgTypeListI
1044 %type <TypeWithAttrs> ArgType
1045 %type <JumpTable> JumpTable
1046 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1047 %type <BoolVal> ThreadLocal // 'thread_local' or not
1048 %type <BoolVal> OptVolatile // 'volatile' or not
1049 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1050 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
1051 %type <Linkage> GVInternalLinkage GVExternalLinkage
1052 %type <Linkage> FunctionDefineLinkage FunctionDeclareLinkage
1053 %type <Linkage> AliasLinkage
1054 %type <Visibility> GVVisibilityStyle
1056 // ValueRef - Unresolved reference to a definition or BB
1057 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1058 %type <ValueVal> ResolvedVal // <type> <valref> pair
1059 %type <ValueList> ReturnedVal
1060 // Tokens and types for handling constant integer values
1062 // ESINT64VAL - A negative number within long long range
1063 %token <SInt64Val> ESINT64VAL
1065 // EUINT64VAL - A positive number within uns. long long range
1066 %token <UInt64Val> EUINT64VAL
1068 // ESAPINTVAL - A negative number with arbitrary precision
1069 %token <APIntVal> ESAPINTVAL
1071 // EUAPINTVAL - A positive number with arbitrary precision
1072 %token <APIntVal> EUAPINTVAL
1074 %token <UIntVal> LOCALVAL_ID GLOBALVAL_ID // %123 @123
1075 %token <FPVal> FPVAL // Float or Double constant
1077 // Built in types...
1078 %type <TypeVal> Types ResultTypes
1079 %type <PrimType> PrimType // Classifications
1080 %token <PrimType> VOID INTTYPE
1081 %token <PrimType> FLOAT DOUBLE X86_FP80 FP128 PPC_FP128 LABEL
1085 %token<StrVal> LOCALVAR GLOBALVAR LABELSTR
1086 %token<StrVal> STRINGCONSTANT ATSTRINGCONSTANT PCTSTRINGCONSTANT
1087 %type <StrVal> LocalName OptLocalName OptLocalAssign
1088 %type <StrVal> GlobalName OptGlobalAssign GlobalAssign
1089 %type <StrVal> OptSection SectionString OptGC
1091 %type <UIntVal> OptAlign OptCAlign OptAddrSpace
1093 %token ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1094 %token DECLARE DEFINE GLOBAL CONSTANT SECTION ALIAS VOLATILE THREAD_LOCAL
1095 %token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
1096 %token DLLIMPORT DLLEXPORT EXTERN_WEAK COMMON
1097 %token OPAQUE EXTERNAL TARGET TRIPLE ALIGN ADDRSPACE
1098 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1099 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1101 %type <UIntVal> OptCallingConv LocalNumber
1102 %type <Attributes> OptAttributes Attribute
1103 %type <Attributes> OptFuncAttrs FuncAttr
1104 %type <Attributes> OptRetAttrs RetAttr
1106 // Basic Block Terminating Operators
1107 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1110 %type <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
1111 %token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1112 %token <BinaryOpVal> SHL LSHR ASHR
1114 %token <OtherOpVal> ICMP FCMP VICMP VFCMP
1115 %type <IPredicate> IPredicates
1116 %type <FPredicate> FPredicates
1117 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1118 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1120 // Memory Instructions
1121 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1124 %type <CastOpVal> CastOps
1125 %token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1126 %token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1129 %token <OtherOpVal> PHI_TOK SELECT VAARG
1130 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1131 %token <OtherOpVal> GETRESULT
1132 %token <OtherOpVal> EXTRACTVALUE INSERTVALUE
1134 // Function Attributes
1135 %token SIGNEXT ZEROEXT NORETURN INREG SRET NOUNWIND NOALIAS BYVAL NEST
1136 %token READNONE READONLY GC OPTSIZE NOINLINE ALWAYSINLINE
1138 // Visibility Styles
1139 %token DEFAULT HIDDEN PROTECTED
1145 // Operations that are notably excluded from this list include:
1146 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1148 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1149 LogicalOps : SHL | LSHR | ASHR | AND | OR | XOR;
1150 CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1151 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1154 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1155 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1156 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1157 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1158 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1162 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1163 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1164 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1165 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1166 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1167 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1168 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1169 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1170 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1173 LocalName : LOCALVAR | STRINGCONSTANT | PCTSTRINGCONSTANT ;
1174 OptLocalName : LocalName | /*empty*/ { $$ = 0; };
1176 OptAddrSpace : ADDRSPACE '(' EUINT64VAL ')' { $$=$3; }
1177 | /*empty*/ { $$=0; };
1179 /// OptLocalAssign - Value producing statements have an optional assignment
1181 OptLocalAssign : LocalName '=' {
1190 LocalNumber : LOCALVAL_ID '=' {
1196 GlobalName : GLOBALVAR | ATSTRINGCONSTANT ;
1198 OptGlobalAssign : GlobalAssign
1204 GlobalAssign : GlobalName '=' {
1210 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1211 | WEAK { $$ = GlobalValue::WeakLinkage; }
1212 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1213 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1214 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1215 | COMMON { $$ = GlobalValue::CommonLinkage; }
1219 : DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1220 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1221 | EXTERNAL { $$ = GlobalValue::ExternalLinkage; }
1225 : /*empty*/ { $$ = GlobalValue::DefaultVisibility; }
1226 | DEFAULT { $$ = GlobalValue::DefaultVisibility; }
1227 | HIDDEN { $$ = GlobalValue::HiddenVisibility; }
1228 | PROTECTED { $$ = GlobalValue::ProtectedVisibility; }
1231 FunctionDeclareLinkage
1232 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1233 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1234 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1237 FunctionDefineLinkage
1238 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1239 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1240 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1241 | WEAK { $$ = GlobalValue::WeakLinkage; }
1242 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1246 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1247 | WEAK { $$ = GlobalValue::WeakLinkage; }
1248 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1251 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1252 CCC_TOK { $$ = CallingConv::C; } |
1253 FASTCC_TOK { $$ = CallingConv::Fast; } |
1254 COLDCC_TOK { $$ = CallingConv::Cold; } |
1255 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1256 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1258 if ((unsigned)$2 != $2)
1259 GEN_ERROR("Calling conv too large");
1264 Attribute : ZEROEXT { $$ = Attribute::ZExt; }
1265 | ZEXT { $$ = Attribute::ZExt; }
1266 | SIGNEXT { $$ = Attribute::SExt; }
1267 | SEXT { $$ = Attribute::SExt; }
1268 | INREG { $$ = Attribute::InReg; }
1269 | SRET { $$ = Attribute::StructRet; }
1270 | NOALIAS { $$ = Attribute::NoAlias; }
1271 | BYVAL { $$ = Attribute::ByVal; }
1272 | NEST { $$ = Attribute::Nest; }
1273 | ALIGN EUINT64VAL { $$ =
1274 Attribute::constructAlignmentFromInt($2); }
1277 OptAttributes : /* empty */ { $$ = Attribute::None; }
1278 | OptAttributes Attribute {
1283 RetAttr : INREG { $$ = Attribute::InReg; }
1284 | ZEROEXT { $$ = Attribute::ZExt; }
1285 | SIGNEXT { $$ = Attribute::SExt; }
1288 OptRetAttrs : /* empty */ { $$ = Attribute::None; }
1289 | OptRetAttrs RetAttr {
1295 FuncAttr : NORETURN { $$ = Attribute::NoReturn; }
1296 | NOUNWIND { $$ = Attribute::NoUnwind; }
1297 | INREG { $$ = Attribute::InReg; }
1298 | ZEROEXT { $$ = Attribute::ZExt; }
1299 | SIGNEXT { $$ = Attribute::SExt; }
1300 | READNONE { $$ = Attribute::ReadNone; }
1301 | READONLY { $$ = Attribute::ReadOnly; }
1302 | NOINLINE { $$ = Attribute::NoInline; }
1303 | ALWAYSINLINE { $$ = Attribute::AlwaysInline; }
1304 | OPTSIZE { $$ = Attribute::OptimizeForSize; }
1307 OptFuncAttrs : /* empty */ { $$ = Attribute::None; }
1308 | OptFuncAttrs FuncAttr {
1314 OptGC : /* empty */ { $$ = 0; }
1315 | GC STRINGCONSTANT {
1320 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1321 // a comma before it.
1322 OptAlign : /*empty*/ { $$ = 0; } |
1325 if ($$ != 0 && !isPowerOf2_32($$))
1326 GEN_ERROR("Alignment must be a power of two");
1329 OptCAlign : /*empty*/ { $$ = 0; } |
1330 ',' ALIGN EUINT64VAL {
1332 if ($$ != 0 && !isPowerOf2_32($$))
1333 GEN_ERROR("Alignment must be a power of two");
1339 SectionString : SECTION STRINGCONSTANT {
1340 for (unsigned i = 0, e = $2->length(); i != e; ++i)
1341 if ((*$2)[i] == '"' || (*$2)[i] == '\\')
1342 GEN_ERROR("Invalid character in section name");
1347 OptSection : /*empty*/ { $$ = 0; } |
1348 SectionString { $$ = $1; };
1350 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1351 // is set to be the global we are processing.
1353 GlobalVarAttributes : /* empty */ {} |
1354 ',' GlobalVarAttribute GlobalVarAttributes {};
1355 GlobalVarAttribute : SectionString {
1356 CurGV->setSection(*$1);
1360 | ALIGN EUINT64VAL {
1361 if ($2 != 0 && !isPowerOf2_32($2))
1362 GEN_ERROR("Alignment must be a power of two");
1363 CurGV->setAlignment($2);
1367 //===----------------------------------------------------------------------===//
1368 // Types includes all predefined types... except void, because it can only be
1369 // used in specific contexts (function returning void for example).
1371 // Derived types are added later...
1373 PrimType : INTTYPE | FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80 | LABEL ;
1377 $$ = new PATypeHolder(OpaqueType::get());
1381 $$ = new PATypeHolder($1);
1384 | Types OptAddrSpace '*' { // Pointer type?
1385 if (*$1 == Type::LabelTy)
1386 GEN_ERROR("Cannot form a pointer to a basic block");
1387 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1, $2)));
1391 | SymbolicValueRef { // Named types are also simple types...
1392 const Type* tmp = getTypeVal($1);
1394 $$ = new PATypeHolder(tmp);
1396 | '\\' EUINT64VAL { // Type UpReference
1397 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range");
1398 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1399 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1400 $$ = new PATypeHolder(OT);
1401 UR_OUT("New Upreference!\n");
1404 | Types '(' ArgTypeListI ')' OptFuncAttrs {
1405 // Allow but ignore attributes on function types; this permits auto-upgrade.
1406 // FIXME: remove in LLVM 3.0.
1407 const Type *RetTy = *$1;
1408 if (!FunctionType::isValidReturnType(RetTy))
1409 GEN_ERROR("Invalid result type for LLVM function");
1411 std::vector<const Type*> Params;
1412 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1413 for (; I != E; ++I ) {
1414 const Type *Ty = I->Ty->get();
1415 Params.push_back(Ty);
1418 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1419 if (isVarArg) Params.pop_back();
1421 for (unsigned i = 0; i != Params.size(); ++i)
1422 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1423 GEN_ERROR("Function arguments must be value types!");
1427 FunctionType *FT = FunctionType::get(RetTy, Params, isVarArg);
1428 delete $1; // Delete the return type handle
1429 $$ = new PATypeHolder(HandleUpRefs(FT));
1431 // Delete the argument list
1432 for (I = $3->begin() ; I != E; ++I ) {
1439 | VOID '(' ArgTypeListI ')' OptFuncAttrs {
1440 // Allow but ignore attributes on function types; this permits auto-upgrade.
1441 // FIXME: remove in LLVM 3.0.
1442 std::vector<const Type*> Params;
1443 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1444 for ( ; I != E; ++I ) {
1445 const Type* Ty = I->Ty->get();
1446 Params.push_back(Ty);
1449 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1450 if (isVarArg) Params.pop_back();
1452 for (unsigned i = 0; i != Params.size(); ++i)
1453 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1454 GEN_ERROR("Function arguments must be value types!");
1458 FunctionType *FT = FunctionType::get($1, Params, isVarArg);
1459 $$ = new PATypeHolder(HandleUpRefs(FT));
1461 // Delete the argument list
1462 for (I = $3->begin() ; I != E; ++I ) {
1470 | '[' EUINT64VAL 'x' Types ']' { // Sized array type?
1471 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, $2)));
1475 | '<' EUINT64VAL 'x' Types '>' { // Vector type?
1476 const llvm::Type* ElemTy = $4->get();
1477 if ((unsigned)$2 != $2)
1478 GEN_ERROR("Unsigned result not equal to signed result");
1479 if (!ElemTy->isFloatingPoint() && !ElemTy->isInteger())
1480 GEN_ERROR("Element type of a VectorType must be primitive");
1481 $$ = new PATypeHolder(HandleUpRefs(VectorType::get(*$4, (unsigned)$2)));
1485 | '{' TypeListI '}' { // Structure type?
1486 std::vector<const Type*> Elements;
1487 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1488 E = $2->end(); I != E; ++I)
1489 Elements.push_back(*I);
1491 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1495 | '{' '}' { // Empty structure type?
1496 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1499 | '<' '{' TypeListI '}' '>' {
1500 std::vector<const Type*> Elements;
1501 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1502 E = $3->end(); I != E; ++I)
1503 Elements.push_back(*I);
1505 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1509 | '<' '{' '}' '>' { // Empty structure type?
1510 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1516 : Types OptAttributes {
1517 // Allow but ignore attributes on function types; this permits auto-upgrade.
1518 // FIXME: remove in LLVM 3.0.
1520 $$.Attrs = Attribute::None;
1526 if (!UpRefs.empty())
1527 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1528 if (!(*$1)->isFirstClassType() && !isa<StructType>($1->get()))
1529 GEN_ERROR("LLVM functions cannot return aggregate types");
1533 $$ = new PATypeHolder(Type::VoidTy);
1537 ArgTypeList : ArgType {
1538 $$ = new TypeWithAttrsList();
1542 | ArgTypeList ',' ArgType {
1543 ($$=$1)->push_back($3);
1550 | ArgTypeList ',' DOTDOTDOT {
1552 TypeWithAttrs TWA; TWA.Attrs = Attribute::None;
1553 TWA.Ty = new PATypeHolder(Type::VoidTy);
1558 $$ = new TypeWithAttrsList;
1559 TypeWithAttrs TWA; TWA.Attrs = Attribute::None;
1560 TWA.Ty = new PATypeHolder(Type::VoidTy);
1565 $$ = new TypeWithAttrsList();
1569 // TypeList - Used for struct declarations and as a basis for function type
1570 // declaration type lists
1573 $$ = new std::list<PATypeHolder>();
1578 | TypeListI ',' Types {
1579 ($$=$1)->push_back(*$3);
1584 // ConstVal - The various declarations that go into the constant pool. This
1585 // production is used ONLY to represent constants that show up AFTER a 'const',
1586 // 'constant' or 'global' token at global scope. Constants that can be inlined
1587 // into other expressions (such as integers and constexprs) are handled by the
1588 // ResolvedVal, ValueRef and ConstValueRef productions.
1590 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1591 if (!UpRefs.empty())
1592 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1593 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1595 GEN_ERROR("Cannot make array constant with type: '" +
1596 (*$1)->getDescription() + "'");
1597 const Type *ETy = ATy->getElementType();
1598 uint64_t NumElements = ATy->getNumElements();
1600 // Verify that we have the correct size...
1601 if (NumElements != uint64_t(-1) && NumElements != $3->size())
1602 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1603 utostr($3->size()) + " arguments, but has size of " +
1604 utostr(NumElements) + "");
1606 // Verify all elements are correct type!
1607 for (unsigned i = 0; i < $3->size(); i++) {
1608 if (ETy != (*$3)[i]->getType())
1609 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1610 ETy->getDescription() +"' as required!\nIt is of type '"+
1611 (*$3)[i]->getType()->getDescription() + "'.");
1614 $$ = ConstantArray::get(ATy, *$3);
1615 delete $1; delete $3;
1619 if (!UpRefs.empty())
1620 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1621 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1623 GEN_ERROR("Cannot make array constant with type: '" +
1624 (*$1)->getDescription() + "'");
1626 uint64_t NumElements = ATy->getNumElements();
1627 if (NumElements != uint64_t(-1) && NumElements != 0)
1628 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1629 " arguments, but has size of " + utostr(NumElements) +"");
1630 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1634 | Types 'c' STRINGCONSTANT {
1635 if (!UpRefs.empty())
1636 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1637 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1639 GEN_ERROR("Cannot make array constant with type: '" +
1640 (*$1)->getDescription() + "'");
1642 uint64_t NumElements = ATy->getNumElements();
1643 const Type *ETy = ATy->getElementType();
1644 if (NumElements != uint64_t(-1) && NumElements != $3->length())
1645 GEN_ERROR("Can't build string constant of size " +
1646 utostr($3->length()) +
1647 " when array has size " + utostr(NumElements) + "");
1648 std::vector<Constant*> Vals;
1649 if (ETy == Type::Int8Ty) {
1650 for (uint64_t i = 0; i < $3->length(); ++i)
1651 Vals.push_back(ConstantInt::get(ETy, (*$3)[i]));
1654 GEN_ERROR("Cannot build string arrays of non byte sized elements");
1657 $$ = ConstantArray::get(ATy, Vals);
1661 | Types '<' ConstVector '>' { // Nonempty unsized arr
1662 if (!UpRefs.empty())
1663 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1664 const VectorType *PTy = dyn_cast<VectorType>($1->get());
1666 GEN_ERROR("Cannot make packed constant with type: '" +
1667 (*$1)->getDescription() + "'");
1668 const Type *ETy = PTy->getElementType();
1669 unsigned NumElements = PTy->getNumElements();
1671 // Verify that we have the correct size...
1672 if (NumElements != unsigned(-1) && NumElements != (unsigned)$3->size())
1673 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1674 utostr($3->size()) + " arguments, but has size of " +
1675 utostr(NumElements) + "");
1677 // Verify all elements are correct type!
1678 for (unsigned i = 0; i < $3->size(); i++) {
1679 if (ETy != (*$3)[i]->getType())
1680 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1681 ETy->getDescription() +"' as required!\nIt is of type '"+
1682 (*$3)[i]->getType()->getDescription() + "'.");
1685 $$ = ConstantVector::get(PTy, *$3);
1686 delete $1; delete $3;
1689 | Types '{' ConstVector '}' {
1690 const StructType *STy = dyn_cast<StructType>($1->get());
1692 GEN_ERROR("Cannot make struct constant with type: '" +
1693 (*$1)->getDescription() + "'");
1695 if ($3->size() != STy->getNumContainedTypes())
1696 GEN_ERROR("Illegal number of initializers for structure type");
1698 // Check to ensure that constants are compatible with the type initializer!
1699 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1700 if ((*$3)[i]->getType() != STy->getElementType(i))
1701 GEN_ERROR("Expected type '" +
1702 STy->getElementType(i)->getDescription() +
1703 "' for element #" + utostr(i) +
1704 " of structure initializer");
1706 // Check to ensure that Type is not packed
1707 if (STy->isPacked())
1708 GEN_ERROR("Unpacked Initializer to vector type '" +
1709 STy->getDescription() + "'");
1711 $$ = ConstantStruct::get(STy, *$3);
1712 delete $1; delete $3;
1716 if (!UpRefs.empty())
1717 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1718 const StructType *STy = dyn_cast<StructType>($1->get());
1720 GEN_ERROR("Cannot make struct constant with type: '" +
1721 (*$1)->getDescription() + "'");
1723 if (STy->getNumContainedTypes() != 0)
1724 GEN_ERROR("Illegal number of initializers for structure type");
1726 // Check to ensure that Type is not packed
1727 if (STy->isPacked())
1728 GEN_ERROR("Unpacked Initializer to vector type '" +
1729 STy->getDescription() + "'");
1731 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1735 | Types '<' '{' ConstVector '}' '>' {
1736 const StructType *STy = dyn_cast<StructType>($1->get());
1738 GEN_ERROR("Cannot make struct constant with type: '" +
1739 (*$1)->getDescription() + "'");
1741 if ($4->size() != STy->getNumContainedTypes())
1742 GEN_ERROR("Illegal number of initializers for structure type");
1744 // Check to ensure that constants are compatible with the type initializer!
1745 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1746 if ((*$4)[i]->getType() != STy->getElementType(i))
1747 GEN_ERROR("Expected type '" +
1748 STy->getElementType(i)->getDescription() +
1749 "' for element #" + utostr(i) +
1750 " of structure initializer");
1752 // Check to ensure that Type is packed
1753 if (!STy->isPacked())
1754 GEN_ERROR("Vector initializer to non-vector type '" +
1755 STy->getDescription() + "'");
1757 $$ = ConstantStruct::get(STy, *$4);
1758 delete $1; delete $4;
1761 | Types '<' '{' '}' '>' {
1762 if (!UpRefs.empty())
1763 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1764 const StructType *STy = dyn_cast<StructType>($1->get());
1766 GEN_ERROR("Cannot make struct constant with type: '" +
1767 (*$1)->getDescription() + "'");
1769 if (STy->getNumContainedTypes() != 0)
1770 GEN_ERROR("Illegal number of initializers for structure type");
1772 // Check to ensure that Type is packed
1773 if (!STy->isPacked())
1774 GEN_ERROR("Vector initializer to non-vector type '" +
1775 STy->getDescription() + "'");
1777 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1782 if (!UpRefs.empty())
1783 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1784 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1786 GEN_ERROR("Cannot make null pointer constant with type: '" +
1787 (*$1)->getDescription() + "'");
1789 $$ = ConstantPointerNull::get(PTy);
1794 if (!UpRefs.empty())
1795 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1796 $$ = UndefValue::get($1->get());
1800 | Types SymbolicValueRef {
1801 if (!UpRefs.empty())
1802 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1803 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1805 GEN_ERROR("Global const reference must be a pointer type " + (*$1)->getDescription());
1807 // ConstExprs can exist in the body of a function, thus creating
1808 // GlobalValues whenever they refer to a variable. Because we are in
1809 // the context of a function, getExistingVal will search the functions
1810 // symbol table instead of the module symbol table for the global symbol,
1811 // which throws things all off. To get around this, we just tell
1812 // getExistingVal that we are at global scope here.
1814 Function *SavedCurFn = CurFun.CurrentFunction;
1815 CurFun.CurrentFunction = 0;
1817 Value *V = getExistingVal(Ty, $2);
1820 CurFun.CurrentFunction = SavedCurFn;
1822 // If this is an initializer for a constant pointer, which is referencing a
1823 // (currently) undefined variable, create a stub now that shall be replaced
1824 // in the future with the right type of variable.
1827 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1828 const PointerType *PT = cast<PointerType>(Ty);
1830 // First check to see if the forward references value is already created!
1831 PerModuleInfo::GlobalRefsType::iterator I =
1832 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1834 if (I != CurModule.GlobalRefs.end()) {
1835 V = I->second; // Placeholder already exists, use it...
1839 if ($2.Type == ValID::GlobalName)
1840 Name = $2.getName();
1841 else if ($2.Type != ValID::GlobalID)
1842 GEN_ERROR("Invalid reference to global");
1844 // Create the forward referenced global.
1846 if (const FunctionType *FTy =
1847 dyn_cast<FunctionType>(PT->getElementType())) {
1848 GV = Function::Create(FTy, GlobalValue::ExternalWeakLinkage, Name,
1849 CurModule.CurrentModule);
1851 GV = new GlobalVariable(PT->getElementType(), false,
1852 GlobalValue::ExternalWeakLinkage, 0,
1853 Name, CurModule.CurrentModule);
1856 // Keep track of the fact that we have a forward ref to recycle it
1857 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1862 $$ = cast<GlobalValue>(V);
1863 delete $1; // Free the type handle
1867 if (!UpRefs.empty())
1868 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1869 if ($1->get() != $2->getType())
1870 GEN_ERROR("Mismatched types for constant expression: " +
1871 (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1876 | Types ZEROINITIALIZER {
1877 if (!UpRefs.empty())
1878 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1879 const Type *Ty = $1->get();
1880 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1881 GEN_ERROR("Cannot create a null initialized value of this type");
1882 $$ = Constant::getNullValue(Ty);
1886 | Types ESINT64VAL { // integral constants
1887 if (IntegerType *IT = dyn_cast<IntegerType>($1->get())) {
1888 if (!ConstantInt::isValueValidForType(IT, $2))
1889 GEN_ERROR("Constant value doesn't fit in type");
1890 $$ = ConstantInt::get(IT, $2, true);
1892 GEN_ERROR("integer constant must have integer type");
1897 | Types ESAPINTVAL { // arbitrary precision integer constants
1898 if (IntegerType *IT = dyn_cast<IntegerType>($1->get())) {
1899 if ($2->getBitWidth() > IT->getBitWidth())
1900 GEN_ERROR("Constant value does not fit in type");
1901 $2->sextOrTrunc(IT->getBitWidth());
1902 $$ = ConstantInt::get(*$2);
1904 GEN_ERROR("integer constant must have integer type");
1910 | Types EUINT64VAL { // integral constants
1911 if (IntegerType *IT = dyn_cast<IntegerType>($1->get())) {
1912 if (!ConstantInt::isValueValidForType(IT, $2))
1913 GEN_ERROR("Constant value doesn't fit in type");
1914 $$ = ConstantInt::get(IT, $2, false);
1916 GEN_ERROR("integer constant must have integer type");
1921 | Types EUAPINTVAL { // arbitrary precision integer constants
1922 if (IntegerType *IT = dyn_cast<IntegerType>($1->get())) {
1923 if ($2->getBitWidth() > IT->getBitWidth())
1924 GEN_ERROR("Constant value does not fit in type");
1925 $2->zextOrTrunc(IT->getBitWidth());
1926 $$ = ConstantInt::get(*$2);
1928 GEN_ERROR("integer constant must have integer type");
1935 | Types TRUETOK { // Boolean constants
1936 if ($1->get() != Type::Int1Ty)
1937 GEN_ERROR("Constant true must have type i1");
1938 $$ = ConstantInt::getTrue();
1942 | Types FALSETOK { // Boolean constants
1943 if ($1->get() != Type::Int1Ty)
1944 GEN_ERROR("Constant false must have type i1");
1945 $$ = ConstantInt::getFalse();
1949 | Types FPVAL { // Floating point constants
1950 if (!ConstantFP::isValueValidForType($1->get(), *$2))
1951 GEN_ERROR("Floating point constant invalid for type");
1953 // Lexer has no type info, so builds all float and double FP constants
1954 // as double. Fix this here. Long double is done right.
1955 if (&$2->getSemantics()==&APFloat::IEEEdouble && $1->get()==Type::FloatTy) {
1957 $2->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
1960 $$ = ConstantFP::get(*$2);
1967 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1968 if (!UpRefs.empty())
1969 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1971 const Type *DestTy = $5->get();
1972 if (!CastInst::castIsValid($1, $3, DestTy))
1973 GEN_ERROR("invalid cast opcode for cast from '" +
1974 Val->getType()->getDescription() + "' to '" +
1975 DestTy->getDescription() + "'");
1976 $$ = ConstantExpr::getCast($1, $3, DestTy);
1979 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1980 if (!isa<PointerType>($3->getType()))
1981 GEN_ERROR("GetElementPtr requires a pointer operand");
1984 GetElementPtrInst::getIndexedType($3->getType(), $4->begin(), $4->end());
1986 GEN_ERROR("Index list invalid for constant getelementptr");
1988 SmallVector<Constant*, 8> IdxVec;
1989 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1990 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1991 IdxVec.push_back(C);
1993 GEN_ERROR("Indices to constant getelementptr must be constants");
1997 $$ = ConstantExpr::getGetElementPtr($3, &IdxVec[0], IdxVec.size());
2000 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2001 if ($3->getType() != Type::Int1Ty)
2002 GEN_ERROR("Select condition must be of boolean type");
2003 if ($5->getType() != $7->getType())
2004 GEN_ERROR("Select operand types must match");
2005 $$ = ConstantExpr::getSelect($3, $5, $7);
2008 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
2009 if ($3->getType() != $5->getType())
2010 GEN_ERROR("Binary operator types must match");
2012 $$ = ConstantExpr::get($1, $3, $5);
2014 | LogicalOps '(' ConstVal ',' ConstVal ')' {
2015 if ($3->getType() != $5->getType())
2016 GEN_ERROR("Logical operator types must match");
2017 if (!$3->getType()->isInteger()) {
2018 if (!isa<VectorType>($3->getType()) ||
2019 !cast<VectorType>($3->getType())->getElementType()->isInteger())
2020 GEN_ERROR("Logical operator requires integral operands");
2022 $$ = ConstantExpr::get($1, $3, $5);
2025 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
2026 if ($4->getType() != $6->getType())
2027 GEN_ERROR("icmp operand types must match");
2028 $$ = ConstantExpr::getICmp($2, $4, $6);
2030 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
2031 if ($4->getType() != $6->getType())
2032 GEN_ERROR("fcmp operand types must match");
2033 $$ = ConstantExpr::getFCmp($2, $4, $6);
2035 | VICMP IPredicates '(' ConstVal ',' ConstVal ')' {
2036 if ($4->getType() != $6->getType())
2037 GEN_ERROR("vicmp operand types must match");
2038 $$ = ConstantExpr::getVICmp($2, $4, $6);
2040 | VFCMP FPredicates '(' ConstVal ',' ConstVal ')' {
2041 if ($4->getType() != $6->getType())
2042 GEN_ERROR("vfcmp operand types must match");
2043 $$ = ConstantExpr::getVFCmp($2, $4, $6);
2045 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
2046 if (!ExtractElementInst::isValidOperands($3, $5))
2047 GEN_ERROR("Invalid extractelement operands");
2048 $$ = ConstantExpr::getExtractElement($3, $5);
2051 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2052 if (!InsertElementInst::isValidOperands($3, $5, $7))
2053 GEN_ERROR("Invalid insertelement operands");
2054 $$ = ConstantExpr::getInsertElement($3, $5, $7);
2057 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2058 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
2059 GEN_ERROR("Invalid shufflevector operands");
2060 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
2063 | EXTRACTVALUE '(' ConstVal ConstantIndexList ')' {
2064 if (!isa<StructType>($3->getType()) && !isa<ArrayType>($3->getType()))
2065 GEN_ERROR("ExtractValue requires an aggregate operand");
2067 $$ = ConstantExpr::getExtractValue($3, &(*$4)[0], $4->size());
2071 | INSERTVALUE '(' ConstVal ',' ConstVal ConstantIndexList ')' {
2072 if (!isa<StructType>($3->getType()) && !isa<ArrayType>($3->getType()))
2073 GEN_ERROR("InsertValue requires an aggregate operand");
2075 $$ = ConstantExpr::getInsertValue($3, $5, &(*$6)[0], $6->size());
2081 // ConstVector - A list of comma separated constants.
2082 ConstVector : ConstVector ',' ConstVal {
2083 ($$ = $1)->push_back($3);
2087 $$ = new std::vector<Constant*>();
2093 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
2094 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
2097 ThreadLocal : THREAD_LOCAL { $$ = true; } | { $$ = false; };
2099 // AliaseeRef - Match either GlobalValue or bitcast to GlobalValue.
2100 AliaseeRef : ResultTypes SymbolicValueRef {
2101 const Type* VTy = $1->get();
2102 Value *V = getVal(VTy, $2);
2104 GlobalValue* Aliasee = dyn_cast<GlobalValue>(V);
2106 GEN_ERROR("Aliases can be created only to global values");
2112 | BITCAST '(' AliaseeRef TO Types ')' {
2114 const Type *DestTy = $5->get();
2115 if (!CastInst::castIsValid($1, $3, DestTy))
2116 GEN_ERROR("invalid cast opcode for cast from '" +
2117 Val->getType()->getDescription() + "' to '" +
2118 DestTy->getDescription() + "'");
2120 $$ = ConstantExpr::getCast($1, $3, DestTy);
2125 //===----------------------------------------------------------------------===//
2126 // Rules to match Modules
2127 //===----------------------------------------------------------------------===//
2129 // Module rule: Capture the result of parsing the whole file into a result
2134 $$ = ParserResult = CurModule.CurrentModule;
2135 CurModule.ModuleDone();
2139 $$ = ParserResult = CurModule.CurrentModule;
2140 CurModule.ModuleDone();
2147 | DefinitionList Definition
2151 : DEFINE { CurFun.isDeclare = false; } Function {
2152 CurFun.FunctionDone();
2155 | DECLARE { CurFun.isDeclare = true; } FunctionProto {
2158 | MODULE ASM_TOK AsmBlock {
2161 | OptLocalAssign TYPE Types {
2162 if (!UpRefs.empty())
2163 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2164 // Eagerly resolve types. This is not an optimization, this is a
2165 // requirement that is due to the fact that we could have this:
2167 // %list = type { %list * }
2168 // %list = type { %list * } ; repeated type decl
2170 // If types are not resolved eagerly, then the two types will not be
2171 // determined to be the same type!
2173 ResolveTypeTo($1, *$3);
2175 if (!setTypeName(*$3, $1) && !$1) {
2177 // If this is a named type that is not a redefinition, add it to the slot
2179 CurModule.Types.push_back(*$3);
2185 | OptLocalAssign TYPE VOID {
2186 ResolveTypeTo($1, $3);
2188 if (!setTypeName($3, $1) && !$1) {
2190 // If this is a named type that is not a redefinition, add it to the slot
2192 CurModule.Types.push_back($3);
2196 | OptGlobalAssign GVVisibilityStyle ThreadLocal GlobalType ConstVal
2198 /* "Externally Visible" Linkage */
2200 GEN_ERROR("Global value initializer is not a constant");
2201 CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
2202 $2, $4, $5->getType(), $5, $3, $6);
2204 } GlobalVarAttributes {
2207 | OptGlobalAssign GVInternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2208 ConstVal OptAddrSpace {
2210 GEN_ERROR("Global value initializer is not a constant");
2211 CurGV = ParseGlobalVariable($1, $2, $3, $5, $6->getType(), $6, $4, $7);
2213 } GlobalVarAttributes {
2216 | OptGlobalAssign GVExternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2217 Types OptAddrSpace {
2218 if (!UpRefs.empty())
2219 GEN_ERROR("Invalid upreference in type: " + (*$6)->getDescription());
2220 CurGV = ParseGlobalVariable($1, $2, $3, $5, *$6, 0, $4, $7);
2223 } GlobalVarAttributes {
2227 | OptGlobalAssign GVVisibilityStyle ALIAS AliasLinkage AliaseeRef {
2234 GEN_ERROR("Alias name cannot be empty");
2236 Constant* Aliasee = $5;
2238 GEN_ERROR(std::string("Invalid aliasee for alias: ") + Name);
2240 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(), $4, Name, Aliasee,
2241 CurModule.CurrentModule);
2242 GA->setVisibility($2);
2243 InsertValue(GA, CurModule.Values);
2246 // If there was a forward reference of this alias, resolve it now.
2250 ID = ValID::createGlobalName(Name);
2252 ID = ValID::createGlobalID(CurModule.Values.size()-1);
2254 if (GlobalValue *FWGV =
2255 CurModule.GetForwardRefForGlobal(GA->getType(), ID)) {
2256 // Replace uses of the fwdref with the actual alias.
2257 FWGV->replaceAllUsesWith(GA);
2258 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(FWGV))
2259 GV->eraseFromParent();
2261 cast<Function>(FWGV)->eraseFromParent();
2267 | TARGET TargetDefinition {
2270 | DEPLIBS '=' LibrariesDefinition {
2276 AsmBlock : STRINGCONSTANT {
2277 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2278 if (AsmSoFar.empty())
2279 CurModule.CurrentModule->setModuleInlineAsm(*$1);
2281 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+*$1);
2286 TargetDefinition : TRIPLE '=' STRINGCONSTANT {
2287 CurModule.CurrentModule->setTargetTriple(*$3);
2290 | DATALAYOUT '=' STRINGCONSTANT {
2291 CurModule.CurrentModule->setDataLayout(*$3);
2295 LibrariesDefinition : '[' LibList ']';
2297 LibList : LibList ',' STRINGCONSTANT {
2298 CurModule.CurrentModule->addLibrary(*$3);
2303 CurModule.CurrentModule->addLibrary(*$1);
2307 | /* empty: end of list */ {
2312 //===----------------------------------------------------------------------===//
2313 // Rules to match Function Headers
2314 //===----------------------------------------------------------------------===//
2316 ArgListH : ArgListH ',' Types OptAttributes OptLocalName {
2317 if (!UpRefs.empty())
2318 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2319 if (!(*$3)->isFirstClassType())
2320 GEN_ERROR("Argument types must be first-class");
2321 ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
2326 | Types OptAttributes OptLocalName {
2327 if (!UpRefs.empty())
2328 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2329 if (!(*$1)->isFirstClassType())
2330 GEN_ERROR("Argument types must be first-class");
2331 ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2332 $$ = new ArgListType;
2337 ArgList : ArgListH {
2341 | ArgListH ',' DOTDOTDOT {
2343 struct ArgListEntry E;
2344 E.Ty = new PATypeHolder(Type::VoidTy);
2346 E.Attrs = Attribute::None;
2351 $$ = new ArgListType;
2352 struct ArgListEntry E;
2353 E.Ty = new PATypeHolder(Type::VoidTy);
2355 E.Attrs = Attribute::None;
2364 FunctionHeaderH : OptCallingConv OptRetAttrs ResultTypes GlobalName '(' ArgList ')'
2365 OptFuncAttrs OptSection OptAlign OptGC {
2366 std::string FunctionName(*$4);
2367 delete $4; // Free strdup'd memory!
2369 // Check the function result for abstractness if this is a define. We should
2370 // have no abstract types at this point
2371 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($3))
2372 GEN_ERROR("Reference to abstract result: "+ $3->get()->getDescription());
2374 if (!FunctionType::isValidReturnType(*$3))
2375 GEN_ERROR("Invalid result type for LLVM function");
2377 std::vector<const Type*> ParamTypeList;
2378 SmallVector<AttributeWithIndex, 8> Attrs;
2379 //FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2381 Attributes RetAttrs = $2;
2382 if ($8 != Attribute::None) {
2383 if ($8 & Attribute::ZExt) {
2384 RetAttrs = RetAttrs | Attribute::ZExt;
2385 $8 = $8 ^ Attribute::ZExt;
2387 if ($8 & Attribute::SExt) {
2388 RetAttrs = RetAttrs | Attribute::SExt;
2389 $8 = $8 ^ Attribute::SExt;
2391 if ($8 & Attribute::InReg) {
2392 RetAttrs = RetAttrs | Attribute::InReg;
2393 $8 = $8 ^ Attribute::InReg;
2396 if (RetAttrs != Attribute::None)
2397 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2398 if ($6) { // If there are arguments...
2400 for (ArgListType::iterator I = $6->begin(); I != $6->end(); ++I, ++index) {
2401 const Type* Ty = I->Ty->get();
2402 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2403 GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2404 ParamTypeList.push_back(Ty);
2405 if (Ty != Type::VoidTy && I->Attrs != Attribute::None)
2406 Attrs.push_back(AttributeWithIndex::get(index, I->Attrs));
2409 if ($8 != Attribute::None)
2410 Attrs.push_back(AttributeWithIndex::get(~0, $8));
2412 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2413 if (isVarArg) ParamTypeList.pop_back();
2417 PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2419 FunctionType *FT = FunctionType::get(*$3, ParamTypeList, isVarArg);
2420 const PointerType *PFT = PointerType::getUnqual(FT);
2424 if (!FunctionName.empty()) {
2425 ID = ValID::createGlobalName((char*)FunctionName.c_str());
2427 ID = ValID::createGlobalID(CurModule.Values.size());
2431 // See if this function was forward referenced. If so, recycle the object.
2432 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2433 // Move the function to the end of the list, from whereever it was
2434 // previously inserted.
2435 Fn = cast<Function>(FWRef);
2436 assert(Fn->getAttributes().isEmpty() &&
2437 "Forward reference has parameter attributes!");
2438 CurModule.CurrentModule->getFunctionList().remove(Fn);
2439 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2440 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2441 (Fn = CurModule.CurrentModule->getFunction(FunctionName))) {
2442 if (Fn->getFunctionType() != FT ) {
2443 // The existing function doesn't have the same type. This is an overload
2445 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2446 } else if (Fn->getAttributes() != PAL) {
2447 // The existing function doesn't have the same parameter attributes.
2448 // This is an overload error.
2449 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2450 } else if (!CurFun.isDeclare && !Fn->isDeclaration()) {
2451 // Neither the existing or the current function is a declaration and they
2452 // have the same name and same type. Clearly this is a redefinition.
2453 GEN_ERROR("Redefinition of function '" + FunctionName + "'");
2454 } else if (Fn->isDeclaration()) {
2455 // Make sure to strip off any argument names so we can't get conflicts.
2456 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2460 } else { // Not already defined?
2461 Fn = Function::Create(FT, GlobalValue::ExternalWeakLinkage, FunctionName,
2462 CurModule.CurrentModule);
2463 InsertValue(Fn, CurModule.Values);
2467 CurFun.FunctionStart(Fn);
2469 if (CurFun.isDeclare) {
2470 // If we have declaration, always overwrite linkage. This will allow us to
2471 // correctly handle cases, when pointer to function is passed as argument to
2472 // another function.
2473 Fn->setLinkage(CurFun.Linkage);
2474 Fn->setVisibility(CurFun.Visibility);
2476 Fn->setCallingConv($1);
2477 Fn->setAttributes(PAL);
2478 Fn->setAlignment($10);
2480 Fn->setSection(*$9);
2484 Fn->setGC($11->c_str());
2488 // Add all of the arguments we parsed to the function...
2489 if ($6) { // Is null if empty...
2490 if (isVarArg) { // Nuke the last entry
2491 assert($6->back().Ty->get() == Type::VoidTy && $6->back().Name == 0 &&
2492 "Not a varargs marker!");
2493 delete $6->back().Ty;
2494 $6->pop_back(); // Delete the last entry
2496 Function::arg_iterator ArgIt = Fn->arg_begin();
2497 Function::arg_iterator ArgEnd = Fn->arg_end();
2499 for (ArgListType::iterator I = $6->begin();
2500 I != $6->end() && ArgIt != ArgEnd; ++I, ++ArgIt) {
2501 delete I->Ty; // Delete the typeholder...
2502 setValueName(ArgIt, I->Name); // Insert arg into symtab...
2508 delete $6; // We're now done with the argument list
2513 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2515 FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2516 $$ = CurFun.CurrentFunction;
2518 // Make sure that we keep track of the linkage type even if there was a
2519 // previous "declare".
2521 $$->setVisibility($2);
2524 END : ENDTOK | '}'; // Allow end of '}' to end a function
2526 Function : BasicBlockList END {
2531 FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2532 CurFun.CurrentFunction->setLinkage($1);
2533 CurFun.CurrentFunction->setVisibility($2);
2534 $$ = CurFun.CurrentFunction;
2535 CurFun.FunctionDone();
2539 //===----------------------------------------------------------------------===//
2540 // Rules to match Basic Blocks
2541 //===----------------------------------------------------------------------===//
2543 OptSideEffect : /* empty */ {
2552 ConstValueRef : ESINT64VAL { // A reference to a direct constant
2553 $$ = ValID::create($1);
2557 $$ = ValID::create($1);
2560 | ESAPINTVAL { // arbitrary precision integer constants
2561 $$ = ValID::create(*$1, true);
2565 | EUAPINTVAL { // arbitrary precision integer constants
2566 $$ = ValID::create(*$1, false);
2570 | FPVAL { // Perhaps it's an FP constant?
2571 $$ = ValID::create($1);
2575 $$ = ValID::create(ConstantInt::getTrue());
2579 $$ = ValID::create(ConstantInt::getFalse());
2583 $$ = ValID::createNull();
2587 $$ = ValID::createUndef();
2590 | ZEROINITIALIZER { // A vector zero constant.
2591 $$ = ValID::createZeroInit();
2594 | '<' ConstVector '>' { // Nonempty unsized packed vector
2595 const Type *ETy = (*$2)[0]->getType();
2596 unsigned NumElements = $2->size();
2598 if (!ETy->isInteger() && !ETy->isFloatingPoint())
2599 GEN_ERROR("Invalid vector element type: " + ETy->getDescription());
2601 VectorType* pt = VectorType::get(ETy, NumElements);
2602 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(pt));
2604 // Verify all elements are correct type!
2605 for (unsigned i = 0; i < $2->size(); i++) {
2606 if (ETy != (*$2)[i]->getType())
2607 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2608 ETy->getDescription() +"' as required!\nIt is of type '" +
2609 (*$2)[i]->getType()->getDescription() + "'.");
2612 $$ = ValID::create(ConstantVector::get(pt, *$2));
2613 delete PTy; delete $2;
2616 | '[' ConstVector ']' { // Nonempty unsized arr
2617 const Type *ETy = (*$2)[0]->getType();
2618 uint64_t NumElements = $2->size();
2620 if (!ETy->isFirstClassType())
2621 GEN_ERROR("Invalid array element type: " + ETy->getDescription());
2623 ArrayType *ATy = ArrayType::get(ETy, NumElements);
2624 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(ATy));
2626 // Verify all elements are correct type!
2627 for (unsigned i = 0; i < $2->size(); i++) {
2628 if (ETy != (*$2)[i]->getType())
2629 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2630 ETy->getDescription() +"' as required!\nIt is of type '"+
2631 (*$2)[i]->getType()->getDescription() + "'.");
2634 $$ = ValID::create(ConstantArray::get(ATy, *$2));
2635 delete PTy; delete $2;
2639 // Use undef instead of an array because it's inconvenient to determine
2640 // the element type at this point, there being no elements to examine.
2641 $$ = ValID::createUndef();
2644 | 'c' STRINGCONSTANT {
2645 uint64_t NumElements = $2->length();
2646 const Type *ETy = Type::Int8Ty;
2648 ArrayType *ATy = ArrayType::get(ETy, NumElements);
2650 std::vector<Constant*> Vals;
2651 for (unsigned i = 0; i < $2->length(); ++i)
2652 Vals.push_back(ConstantInt::get(ETy, (*$2)[i]));
2654 $$ = ValID::create(ConstantArray::get(ATy, Vals));
2657 | '{' ConstVector '}' {
2658 std::vector<const Type*> Elements($2->size());
2659 for (unsigned i = 0, e = $2->size(); i != e; ++i)
2660 Elements[i] = (*$2)[i]->getType();
2662 const StructType *STy = StructType::get(Elements);
2663 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(STy));
2665 $$ = ValID::create(ConstantStruct::get(STy, *$2));
2666 delete PTy; delete $2;
2670 const StructType *STy = StructType::get(std::vector<const Type*>());
2671 $$ = ValID::create(ConstantStruct::get(STy, std::vector<Constant*>()));
2674 | '<' '{' ConstVector '}' '>' {
2675 std::vector<const Type*> Elements($3->size());
2676 for (unsigned i = 0, e = $3->size(); i != e; ++i)
2677 Elements[i] = (*$3)[i]->getType();
2679 const StructType *STy = StructType::get(Elements, /*isPacked=*/true);
2680 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(STy));
2682 $$ = ValID::create(ConstantStruct::get(STy, *$3));
2683 delete PTy; delete $3;
2687 const StructType *STy = StructType::get(std::vector<const Type*>(),
2689 $$ = ValID::create(ConstantStruct::get(STy, std::vector<Constant*>()));
2693 $$ = ValID::create($1);
2696 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2697 $$ = ValID::createInlineAsm(*$3, *$5, $2);
2703 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2706 SymbolicValueRef : LOCALVAL_ID { // Is it an integer reference...?
2707 $$ = ValID::createLocalID($1);
2711 $$ = ValID::createGlobalID($1);
2714 | LocalName { // Is it a named reference...?
2715 $$ = ValID::createLocalName(*$1);
2719 | GlobalName { // Is it a named reference...?
2720 $$ = ValID::createGlobalName(*$1);
2725 // ValueRef - A reference to a definition... either constant or symbolic
2726 ValueRef : SymbolicValueRef | ConstValueRef;
2729 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2730 // type immediately preceeds the value reference, and allows complex constant
2731 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2732 ResolvedVal : Types ValueRef {
2733 if (!UpRefs.empty())
2734 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2735 $$ = getVal(*$1, $2);
2741 ReturnedVal : ResolvedVal {
2742 $$ = new std::vector<Value *>();
2746 | ReturnedVal ',' ResolvedVal {
2747 ($$=$1)->push_back($3);
2751 BasicBlockList : BasicBlockList BasicBlock {
2755 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2761 // Basic blocks are terminated by branching instructions:
2762 // br, br/cc, switch, ret
2764 BasicBlock : InstructionList OptLocalAssign BBTerminatorInst {
2765 setValueName($3, $2);
2768 $1->getInstList().push_back($3);
2773 BasicBlock : InstructionList LocalNumber BBTerminatorInst {
2775 int ValNum = InsertValue($3);
2776 if (ValNum != (int)$2)
2777 GEN_ERROR("Result value number %" + utostr($2) +
2778 " is incorrect, expected %" + utostr((unsigned)ValNum));
2780 $1->getInstList().push_back($3);
2786 InstructionList : InstructionList Inst {
2787 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2788 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2789 if (CI2->getParent() == 0)
2790 $1->getInstList().push_back(CI2);
2791 $1->getInstList().push_back($2);
2795 | /* empty */ { // Empty space between instruction lists
2796 $$ = defineBBVal(ValID::createLocalID(CurFun.NextValNum));
2799 | LABELSTR { // Labelled (named) basic block
2800 $$ = defineBBVal(ValID::createLocalName(*$1));
2807 RET ReturnedVal { // Return with a result...
2808 ValueList &VL = *$2;
2809 assert(!VL.empty() && "Invalid ret operands!");
2810 const Type *ReturnType = CurFun.CurrentFunction->getReturnType();
2811 if (VL.size() > 1 ||
2812 (isa<StructType>(ReturnType) &&
2813 (VL.empty() || VL[0]->getType() != ReturnType))) {
2814 Value *RV = UndefValue::get(ReturnType);
2815 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
2816 Instruction *I = InsertValueInst::Create(RV, VL[i], i, "mrv");
2817 ($<BasicBlockVal>-1)->getInstList().push_back(I);
2820 $$ = ReturnInst::Create(RV);
2822 $$ = ReturnInst::Create(VL[0]);
2827 | RET VOID { // Return with no result...
2828 $$ = ReturnInst::Create();
2831 | BR LABEL ValueRef { // Unconditional Branch...
2832 BasicBlock* tmpBB = getBBVal($3);
2834 $$ = BranchInst::Create(tmpBB);
2835 } // Conditional Branch...
2836 | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2837 if (cast<IntegerType>($2)->getBitWidth() != 1)
2838 GEN_ERROR("Branch condition must have type i1");
2839 BasicBlock* tmpBBA = getBBVal($6);
2841 BasicBlock* tmpBBB = getBBVal($9);
2843 Value* tmpVal = getVal(Type::Int1Ty, $3);
2845 $$ = BranchInst::Create(tmpBBA, tmpBBB, tmpVal);
2847 | SWITCH INTTYPE ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2848 Value* tmpVal = getVal($2, $3);
2850 BasicBlock* tmpBB = getBBVal($6);
2852 SwitchInst *S = SwitchInst::Create(tmpVal, tmpBB, $8->size());
2855 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2857 for (; I != E; ++I) {
2858 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2859 S->addCase(CI, I->second);
2861 GEN_ERROR("Switch case is constant, but not a simple integer");
2866 | SWITCH INTTYPE ValueRef ',' LABEL ValueRef '[' ']' {
2867 Value* tmpVal = getVal($2, $3);
2869 BasicBlock* tmpBB = getBBVal($6);
2871 SwitchInst *S = SwitchInst::Create(tmpVal, tmpBB, 0);
2875 | INVOKE OptCallingConv OptRetAttrs ResultTypes ValueRef '(' ParamList ')'
2876 OptFuncAttrs TO LABEL ValueRef UNWIND LABEL ValueRef {
2878 // Handle the short syntax
2879 const PointerType *PFTy = 0;
2880 const FunctionType *Ty = 0;
2881 if (!(PFTy = dyn_cast<PointerType>($4->get())) ||
2882 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2883 // Pull out the types of all of the arguments...
2884 std::vector<const Type*> ParamTypes;
2885 ParamList::iterator I = $7->begin(), E = $7->end();
2886 for (; I != E; ++I) {
2887 const Type *Ty = I->Val->getType();
2888 if (Ty == Type::VoidTy)
2889 GEN_ERROR("Short call syntax cannot be used with varargs");
2890 ParamTypes.push_back(Ty);
2893 if (!FunctionType::isValidReturnType(*$4))
2894 GEN_ERROR("Invalid result type for LLVM function");
2896 Ty = FunctionType::get($4->get(), ParamTypes, false);
2897 PFTy = PointerType::getUnqual(Ty);
2902 Value *V = getVal(PFTy, $5); // Get the function we're calling...
2904 BasicBlock *Normal = getBBVal($12);
2906 BasicBlock *Except = getBBVal($15);
2909 SmallVector<AttributeWithIndex, 8> Attrs;
2910 //FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2912 Attributes RetAttrs = $3;
2913 if ($9 != Attribute::None) {
2914 if ($9 & Attribute::ZExt) {
2915 RetAttrs = RetAttrs | Attribute::ZExt;
2916 $9 = $9 ^ Attribute::ZExt;
2918 if ($9 & Attribute::SExt) {
2919 RetAttrs = RetAttrs | Attribute::SExt;
2920 $9 = $9 ^ Attribute::SExt;
2922 if ($9 & Attribute::InReg) {
2923 RetAttrs = RetAttrs | Attribute::InReg;
2924 $9 = $9 ^ Attribute::InReg;
2927 if (RetAttrs != Attribute::None)
2928 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2930 // Check the arguments
2932 if ($7->empty()) { // Has no arguments?
2933 // Make sure no arguments is a good thing!
2934 if (Ty->getNumParams() != 0)
2935 GEN_ERROR("No arguments passed to a function that "
2936 "expects arguments");
2937 } else { // Has arguments?
2938 // Loop through FunctionType's arguments and ensure they are specified
2940 FunctionType::param_iterator I = Ty->param_begin();
2941 FunctionType::param_iterator E = Ty->param_end();
2942 ParamList::iterator ArgI = $7->begin(), ArgE = $7->end();
2945 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
2946 if (ArgI->Val->getType() != *I)
2947 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2948 (*I)->getDescription() + "'");
2949 Args.push_back(ArgI->Val);
2950 if (ArgI->Attrs != Attribute::None)
2951 Attrs.push_back(AttributeWithIndex::get(index, ArgI->Attrs));
2954 if (Ty->isVarArg()) {
2956 for (; ArgI != ArgE; ++ArgI, ++index) {
2957 Args.push_back(ArgI->Val); // push the remaining varargs
2958 if (ArgI->Attrs != Attribute::None)
2959 Attrs.push_back(AttributeWithIndex::get(index, ArgI->Attrs));
2961 } else if (I != E || ArgI != ArgE)
2962 GEN_ERROR("Invalid number of parameters detected");
2964 if ($9 != Attribute::None)
2965 Attrs.push_back(AttributeWithIndex::get(~0, $9));
2968 PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2970 // Create the InvokeInst
2971 InvokeInst *II = InvokeInst::Create(V, Normal, Except,
2972 Args.begin(), Args.end());
2973 II->setCallingConv($2);
2974 II->setAttributes(PAL);
2980 $$ = new UnwindInst();
2984 $$ = new UnreachableInst();
2990 JumpTable : JumpTable INTTYPE ConstValueRef ',' LABEL ValueRef {
2992 Constant *V = cast<Constant>(getExistingVal($2, $3));
2995 GEN_ERROR("May only switch on a constant pool value");
2997 BasicBlock* tmpBB = getBBVal($6);
2999 $$->push_back(std::make_pair(V, tmpBB));
3001 | INTTYPE ConstValueRef ',' LABEL ValueRef {
3002 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
3003 Constant *V = cast<Constant>(getExistingVal($1, $2));
3007 GEN_ERROR("May only switch on a constant pool value");
3009 BasicBlock* tmpBB = getBBVal($5);
3011 $$->push_back(std::make_pair(V, tmpBB));
3014 Inst : OptLocalAssign InstVal {
3015 // Is this definition named?? if so, assign the name...
3016 setValueName($2, $1);
3023 Inst : LocalNumber InstVal {
3025 int ValNum = InsertValue($2);
3027 if (ValNum != (int)$1)
3028 GEN_ERROR("Result value number %" + utostr($1) +
3029 " is incorrect, expected %" + utostr((unsigned)ValNum));
3036 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
3037 if (!UpRefs.empty())
3038 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
3039 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
3040 Value* tmpVal = getVal(*$1, $3);
3042 BasicBlock* tmpBB = getBBVal($5);
3044 $$->push_back(std::make_pair(tmpVal, tmpBB));
3047 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
3049 Value* tmpVal = getVal($1->front().first->getType(), $4);
3051 BasicBlock* tmpBB = getBBVal($6);
3053 $1->push_back(std::make_pair(tmpVal, tmpBB));
3057 ParamList : Types OptAttributes ValueRef OptAttributes {
3058 // FIXME: Remove trailing OptAttributes in LLVM 3.0, it was a mistake in 2.0
3059 if (!UpRefs.empty())
3060 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
3061 // Used for call and invoke instructions
3062 $$ = new ParamList();
3063 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getVal($1->get(), $3);
3068 | LABEL OptAttributes ValueRef OptAttributes {
3069 // FIXME: Remove trailing OptAttributes in LLVM 3.0, it was a mistake in 2.0
3070 // Labels are only valid in ASMs
3071 $$ = new ParamList();
3072 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getBBVal($3);
3076 | ParamList ',' Types OptAttributes ValueRef OptAttributes {
3077 // FIXME: Remove trailing OptAttributes in LLVM 3.0, it was a mistake in 2.0
3078 if (!UpRefs.empty())
3079 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3081 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getVal($3->get(), $5);
3086 | ParamList ',' LABEL OptAttributes ValueRef OptAttributes {
3087 // FIXME: Remove trailing OptAttributes in LLVM 3.0, it was a mistake in 2.0
3089 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getBBVal($5);
3093 | /*empty*/ { $$ = new ParamList(); };
3095 IndexList // Used for gep instructions and constant expressions
3096 : /*empty*/ { $$ = new std::vector<Value*>(); }
3097 | IndexList ',' ResolvedVal {
3104 ConstantIndexList // Used for insertvalue and extractvalue instructions
3106 $$ = new std::vector<unsigned>();
3107 if ((unsigned)$2 != $2)
3108 GEN_ERROR("Index " + utostr($2) + " is not valid for insertvalue or extractvalue.");
3111 | ConstantIndexList ',' EUINT64VAL {
3113 if ((unsigned)$3 != $3)
3114 GEN_ERROR("Index " + utostr($3) + " is not valid for insertvalue or extractvalue.");
3120 OptTailCall : TAIL CALL {
3129 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
3130 if (!UpRefs.empty())
3131 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3132 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
3133 !isa<VectorType>((*$2).get()))
3135 "Arithmetic operator requires integer, FP, or packed operands");
3136 Value* val1 = getVal(*$2, $3);
3138 Value* val2 = getVal(*$2, $5);
3140 $$ = BinaryOperator::Create($1, val1, val2);
3142 GEN_ERROR("binary operator returned null");
3145 | LogicalOps Types ValueRef ',' ValueRef {
3146 if (!UpRefs.empty())
3147 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3148 if (!(*$2)->isInteger()) {
3149 if (!isa<VectorType>($2->get()) ||
3150 !cast<VectorType>($2->get())->getElementType()->isInteger())
3151 GEN_ERROR("Logical operator requires integral operands");
3153 Value* tmpVal1 = getVal(*$2, $3);
3155 Value* tmpVal2 = getVal(*$2, $5);
3157 $$ = BinaryOperator::Create($1, tmpVal1, tmpVal2);
3159 GEN_ERROR("binary operator returned null");
3162 | ICMP IPredicates Types ValueRef ',' ValueRef {
3163 if (!UpRefs.empty())
3164 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3165 Value* tmpVal1 = getVal(*$3, $4);
3167 Value* tmpVal2 = getVal(*$3, $6);
3169 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3171 GEN_ERROR("icmp operator returned null");
3174 | FCMP FPredicates Types ValueRef ',' ValueRef {
3175 if (!UpRefs.empty())
3176 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3177 Value* tmpVal1 = getVal(*$3, $4);
3179 Value* tmpVal2 = getVal(*$3, $6);
3181 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3183 GEN_ERROR("fcmp operator returned null");
3186 | VICMP IPredicates Types ValueRef ',' ValueRef {
3187 if (!UpRefs.empty())
3188 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3189 if (!isa<VectorType>((*$3).get()))
3190 GEN_ERROR("Scalar types not supported by vicmp instruction");
3191 Value* tmpVal1 = getVal(*$3, $4);
3193 Value* tmpVal2 = getVal(*$3, $6);
3195 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3197 GEN_ERROR("vicmp operator returned null");
3200 | VFCMP FPredicates Types ValueRef ',' ValueRef {
3201 if (!UpRefs.empty())
3202 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3203 if (!isa<VectorType>((*$3).get()))
3204 GEN_ERROR("Scalar types not supported by vfcmp instruction");
3205 Value* tmpVal1 = getVal(*$3, $4);
3207 Value* tmpVal2 = getVal(*$3, $6);
3209 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3211 GEN_ERROR("vfcmp operator returned null");
3214 | CastOps ResolvedVal TO Types {
3215 if (!UpRefs.empty())
3216 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
3218 const Type* DestTy = $4->get();
3219 if (!CastInst::castIsValid($1, Val, DestTy))
3220 GEN_ERROR("invalid cast opcode for cast from '" +
3221 Val->getType()->getDescription() + "' to '" +
3222 DestTy->getDescription() + "'");
3223 $$ = CastInst::Create($1, Val, DestTy);
3226 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3227 if (isa<VectorType>($2->getType())) {
3229 if (!isa<VectorType>($4->getType())
3230 || !isa<VectorType>($6->getType()) )
3231 GEN_ERROR("vector select value types must be vector types");
3232 const VectorType* cond_type = cast<VectorType>($2->getType());
3233 const VectorType* select_type = cast<VectorType>($4->getType());
3234 if (cond_type->getElementType() != Type::Int1Ty)
3235 GEN_ERROR("vector select condition element type must be boolean");
3236 if (cond_type->getNumElements() != select_type->getNumElements())
3237 GEN_ERROR("vector select number of elements must be the same");
3239 if ($2->getType() != Type::Int1Ty)
3240 GEN_ERROR("select condition must be boolean");
3242 if ($4->getType() != $6->getType())
3243 GEN_ERROR("select value types must match");
3244 $$ = SelectInst::Create($2, $4, $6);
3247 | VAARG ResolvedVal ',' Types {
3248 if (!UpRefs.empty())
3249 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
3250 $$ = new VAArgInst($2, *$4);
3254 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
3255 if (!ExtractElementInst::isValidOperands($2, $4))
3256 GEN_ERROR("Invalid extractelement operands");
3257 $$ = new ExtractElementInst($2, $4);
3260 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3261 if (!InsertElementInst::isValidOperands($2, $4, $6))
3262 GEN_ERROR("Invalid insertelement operands");
3263 $$ = InsertElementInst::Create($2, $4, $6);
3266 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3267 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
3268 GEN_ERROR("Invalid shufflevector operands");
3269 $$ = new ShuffleVectorInst($2, $4, $6);
3273 const Type *Ty = $2->front().first->getType();
3274 if (!Ty->isFirstClassType())
3275 GEN_ERROR("PHI node operands must be of first class type");
3276 $$ = PHINode::Create(Ty);
3277 ((PHINode*)$$)->reserveOperandSpace($2->size());
3278 while ($2->begin() != $2->end()) {
3279 if ($2->front().first->getType() != Ty)
3280 GEN_ERROR("All elements of a PHI node must be of the same type");
3281 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
3284 delete $2; // Free the list...
3287 | OptTailCall OptCallingConv OptRetAttrs ResultTypes ValueRef '(' ParamList ')'
3290 // Handle the short syntax
3291 const PointerType *PFTy = 0;
3292 const FunctionType *Ty = 0;
3293 if (!(PFTy = dyn_cast<PointerType>($4->get())) ||
3294 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3295 // Pull out the types of all of the arguments...
3296 std::vector<const Type*> ParamTypes;
3297 ParamList::iterator I = $7->begin(), E = $7->end();
3298 for (; I != E; ++I) {
3299 const Type *Ty = I->Val->getType();
3300 if (Ty == Type::VoidTy)
3301 GEN_ERROR("Short call syntax cannot be used with varargs");
3302 ParamTypes.push_back(Ty);
3305 if (!FunctionType::isValidReturnType(*$4))
3306 GEN_ERROR("Invalid result type for LLVM function");
3308 Ty = FunctionType::get($4->get(), ParamTypes, false);
3309 PFTy = PointerType::getUnqual(Ty);
3312 Value *V = getVal(PFTy, $5); // Get the function we're calling...
3315 // Check for call to invalid intrinsic to avoid crashing later.
3316 if (Function *theF = dyn_cast<Function>(V)) {
3317 if (theF->hasName() && (theF->getValueName()->getKeyLength() >= 5) &&
3318 (0 == strncmp(theF->getValueName()->getKeyData(), "llvm.", 5)) &&
3319 !theF->getIntrinsicID(true))
3320 GEN_ERROR("Call to invalid LLVM intrinsic function '" +
3321 theF->getName() + "'");
3324 // Set up the Attributes for the function
3325 SmallVector<AttributeWithIndex, 8> Attrs;
3326 //FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
3328 Attributes RetAttrs = $3;
3329 if ($9 != Attribute::None) {
3330 if ($9 & Attribute::ZExt) {
3331 RetAttrs = RetAttrs | Attribute::ZExt;
3332 $9 = $9 ^ Attribute::ZExt;
3334 if ($9 & Attribute::SExt) {
3335 RetAttrs = RetAttrs | Attribute::SExt;
3336 $9 = $9 ^ Attribute::SExt;
3338 if ($9 & Attribute::InReg) {
3339 RetAttrs = RetAttrs | Attribute::InReg;
3340 $9 = $9 ^ Attribute::InReg;
3343 if (RetAttrs != Attribute::None)
3344 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3346 // Check the arguments
3348 if ($7->empty()) { // Has no arguments?
3349 // Make sure no arguments is a good thing!
3350 if (Ty->getNumParams() != 0)
3351 GEN_ERROR("No arguments passed to a function that "
3352 "expects arguments");
3353 } else { // Has arguments?
3354 // Loop through FunctionType's arguments and ensure they are specified
3355 // correctly. Also, gather any parameter attributes.
3356 FunctionType::param_iterator I = Ty->param_begin();
3357 FunctionType::param_iterator E = Ty->param_end();
3358 ParamList::iterator ArgI = $7->begin(), ArgE = $7->end();
3361 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
3362 if (ArgI->Val->getType() != *I)
3363 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
3364 (*I)->getDescription() + "'");
3365 Args.push_back(ArgI->Val);
3366 if (ArgI->Attrs != Attribute::None)
3367 Attrs.push_back(AttributeWithIndex::get(index, ArgI->Attrs));
3369 if (Ty->isVarArg()) {
3371 for (; ArgI != ArgE; ++ArgI, ++index) {
3372 Args.push_back(ArgI->Val); // push the remaining varargs
3373 if (ArgI->Attrs != Attribute::None)
3374 Attrs.push_back(AttributeWithIndex::get(index, ArgI->Attrs));
3376 } else if (I != E || ArgI != ArgE)
3377 GEN_ERROR("Invalid number of parameters detected");
3379 if ($9 != Attribute::None)
3380 Attrs.push_back(AttributeWithIndex::get(~0, $9));
3382 // Finish off the Attributes and check them
3385 PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3387 // Create the call node
3388 CallInst *CI = CallInst::Create(V, Args.begin(), Args.end());
3389 CI->setTailCall($1);
3390 CI->setCallingConv($2);
3391 CI->setAttributes(PAL);
3402 OptVolatile : VOLATILE {
3413 MemoryInst : MALLOC Types OptCAlign {
3414 if (!UpRefs.empty())
3415 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3416 $$ = new MallocInst(*$2, 0, $3);
3420 | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
3421 if (!UpRefs.empty())
3422 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3423 if ($4 != Type::Int32Ty)
3424 GEN_ERROR("Malloc array size is not a 32-bit integer!");
3425 Value* tmpVal = getVal($4, $5);
3427 $$ = new MallocInst(*$2, tmpVal, $6);
3430 | ALLOCA Types OptCAlign {
3431 if (!UpRefs.empty())
3432 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3433 $$ = new AllocaInst(*$2, 0, $3);
3437 | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
3438 if (!UpRefs.empty())
3439 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3440 if ($4 != Type::Int32Ty)
3441 GEN_ERROR("Alloca array size is not a 32-bit integer!");
3442 Value* tmpVal = getVal($4, $5);
3444 $$ = new AllocaInst(*$2, tmpVal, $6);
3447 | FREE ResolvedVal {
3448 if (!isa<PointerType>($2->getType()))
3449 GEN_ERROR("Trying to free nonpointer type " +
3450 $2->getType()->getDescription() + "");
3451 $$ = new FreeInst($2);
3455 | OptVolatile LOAD Types ValueRef OptCAlign {
3456 if (!UpRefs.empty())
3457 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3458 if (!isa<PointerType>($3->get()))
3459 GEN_ERROR("Can't load from nonpointer type: " +
3460 (*$3)->getDescription());
3461 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
3462 GEN_ERROR("Can't load from pointer of non-first-class type: " +
3463 (*$3)->getDescription());
3464 Value* tmpVal = getVal(*$3, $4);
3466 $$ = new LoadInst(tmpVal, "", $1, $5);
3469 | OptVolatile STORE ResolvedVal ',' Types ValueRef OptCAlign {
3470 if (!UpRefs.empty())
3471 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
3472 const PointerType *PT = dyn_cast<PointerType>($5->get());
3474 GEN_ERROR("Can't store to a nonpointer type: " +
3475 (*$5)->getDescription());
3476 const Type *ElTy = PT->getElementType();
3477 if (ElTy != $3->getType())
3478 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
3479 "' into space of type '" + ElTy->getDescription() + "'");
3481 Value* tmpVal = getVal(*$5, $6);
3483 $$ = new StoreInst($3, tmpVal, $1, $7);
3486 | GETRESULT Types ValueRef ',' EUINT64VAL {
3487 if (!UpRefs.empty())
3488 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3489 if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3490 GEN_ERROR("getresult insn requires an aggregate operand");
3491 if (!ExtractValueInst::getIndexedType(*$2, $5))
3492 GEN_ERROR("Invalid getresult index for type '" +
3493 (*$2)->getDescription()+ "'");
3495 Value *tmpVal = getVal(*$2, $3);
3497 $$ = ExtractValueInst::Create(tmpVal, $5);
3500 | GETELEMENTPTR Types ValueRef IndexList {
3501 if (!UpRefs.empty())
3502 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3503 if (!isa<PointerType>($2->get()))
3504 GEN_ERROR("getelementptr insn requires pointer operand");
3506 if (!GetElementPtrInst::getIndexedType(*$2, $4->begin(), $4->end()))
3507 GEN_ERROR("Invalid getelementptr indices for type '" +
3508 (*$2)->getDescription()+ "'");
3509 Value* tmpVal = getVal(*$2, $3);
3511 $$ = GetElementPtrInst::Create(tmpVal, $4->begin(), $4->end());
3515 | EXTRACTVALUE Types ValueRef ConstantIndexList {
3516 if (!UpRefs.empty())
3517 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3518 if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3519 GEN_ERROR("extractvalue insn requires an aggregate operand");
3521 if (!ExtractValueInst::getIndexedType(*$2, $4->begin(), $4->end()))
3522 GEN_ERROR("Invalid extractvalue indices for type '" +
3523 (*$2)->getDescription()+ "'");
3524 Value* tmpVal = getVal(*$2, $3);
3526 $$ = ExtractValueInst::Create(tmpVal, $4->begin(), $4->end());
3530 | INSERTVALUE Types ValueRef ',' Types ValueRef ConstantIndexList {
3531 if (!UpRefs.empty())
3532 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3533 if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3534 GEN_ERROR("extractvalue insn requires an aggregate operand");
3536 if (ExtractValueInst::getIndexedType(*$2, $7->begin(), $7->end()) != $5->get())
3537 GEN_ERROR("Invalid insertvalue indices for type '" +
3538 (*$2)->getDescription()+ "'");
3539 Value* aggVal = getVal(*$2, $3);
3540 Value* tmpVal = getVal(*$5, $6);
3542 $$ = InsertValueInst::Create(aggVal, tmpVal, $7->begin(), $7->end());
3551 // common code from the two 'RunVMAsmParser' functions
3552 static Module* RunParser(Module * M) {
3553 CurModule.CurrentModule = M;
3554 // Check to make sure the parser succeeded
3557 delete ParserResult;
3561 // Emit an error if there are any unresolved types left.
3562 if (!CurModule.LateResolveTypes.empty()) {
3563 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
3564 if (DID.Type == ValID::LocalName) {
3565 GenerateError("Undefined type remains at eof: '"+DID.getName() + "'");
3567 GenerateError("Undefined type remains at eof: #" + itostr(DID.Num));
3570 delete ParserResult;
3574 // Emit an error if there are any unresolved values left.
3575 if (!CurModule.LateResolveValues.empty()) {
3576 Value *V = CurModule.LateResolveValues.back();
3577 std::map<Value*, std::pair<ValID, int> >::iterator I =
3578 CurModule.PlaceHolderInfo.find(V);
3580 if (I != CurModule.PlaceHolderInfo.end()) {
3581 ValID &DID = I->second.first;
3582 if (DID.Type == ValID::LocalName) {
3583 GenerateError("Undefined value remains at eof: "+DID.getName() + "'");
3585 GenerateError("Undefined value remains at eof: #" + itostr(DID.Num));
3588 delete ParserResult;
3593 // Check to make sure that parsing produced a result
3597 // Reset ParserResult variable while saving its value for the result.
3598 Module *Result = ParserResult;
3604 void llvm::GenerateError(const std::string &message, int LineNo) {
3605 if (LineNo == -1) LineNo = LLLgetLineNo();
3606 // TODO: column number in exception
3608 TheParseError->setError(LLLgetFilename(), message, LineNo);
3612 int yyerror(const char *ErrorMsg) {
3613 std::string where = LLLgetFilename() + ":" + utostr(LLLgetLineNo()) + ": ";
3614 std::string errMsg = where + "error: " + std::string(ErrorMsg);
3615 if (yychar != YYEMPTY && yychar != 0) {
3616 errMsg += " while reading token: '";
3617 errMsg += std::string(LLLgetTokenStart(),
3618 LLLgetTokenStart()+LLLgetTokenLength()) + "'";
3620 GenerateError(errMsg);