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()) {
148 bool TypeIsUnresolved(PATypeHolder* PATy) {
149 // If it isn't abstract, its resolved
150 const Type* Ty = PATy->get();
151 if (!Ty->isAbstract())
153 // Traverse the type looking for abstract types. If it isn't abstract then
154 // we don't need to traverse that leg of the type.
155 std::vector<const Type*> WorkList, SeenList;
156 WorkList.push_back(Ty);
157 while (!WorkList.empty()) {
158 const Type* Ty = WorkList.back();
159 SeenList.push_back(Ty);
161 if (const OpaqueType* OpTy = dyn_cast<OpaqueType>(Ty)) {
162 // Check to see if this is an unresolved type
163 std::map<ValID, PATypeHolder>::iterator I = LateResolveTypes.begin();
164 std::map<ValID, PATypeHolder>::iterator E = LateResolveTypes.end();
165 for ( ; I != E; ++I) {
166 if (I->second.get() == OpTy)
169 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(Ty)) {
170 const Type* TheTy = SeqTy->getElementType();
171 if (TheTy->isAbstract() && TheTy != Ty) {
172 std::vector<const Type*>::iterator I = SeenList.begin(),
178 WorkList.push_back(TheTy);
180 } else if (const StructType* StrTy = dyn_cast<StructType>(Ty)) {
181 for (unsigned i = 0; i < StrTy->getNumElements(); ++i) {
182 const Type* TheTy = StrTy->getElementType(i);
183 if (TheTy->isAbstract() && TheTy != Ty) {
184 std::vector<const Type*>::iterator I = SeenList.begin(),
190 WorkList.push_back(TheTy);
199 static struct PerFunctionInfo {
200 Function *CurrentFunction; // Pointer to current function being created
202 ValueList Values; // Keep track of #'d definitions
204 ValueList LateResolveValues;
205 bool isDeclare; // Is this function a forward declararation?
206 GlobalValue::LinkageTypes Linkage; // Linkage for forward declaration.
207 GlobalValue::VisibilityTypes Visibility;
209 /// BBForwardRefs - When we see forward references to basic blocks, keep
210 /// track of them here.
211 std::map<ValID, BasicBlock*> BBForwardRefs;
213 inline PerFunctionInfo() {
216 Linkage = GlobalValue::ExternalLinkage;
217 Visibility = GlobalValue::DefaultVisibility;
220 inline void FunctionStart(Function *M) {
225 void FunctionDone() {
226 // Any forward referenced blocks left?
227 if (!BBForwardRefs.empty()) {
228 GenerateError("Undefined reference to label " +
229 BBForwardRefs.begin()->second->getName());
233 // Resolve all forward references now.
234 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
236 Values.clear(); // Clear out function local definitions
237 BBForwardRefs.clear();
240 Linkage = GlobalValue::ExternalLinkage;
241 Visibility = GlobalValue::DefaultVisibility;
243 } CurFun; // Info for the current function...
245 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
248 //===----------------------------------------------------------------------===//
249 // Code to handle definitions of all the types
250 //===----------------------------------------------------------------------===//
252 /// InsertValue - Insert a value into the value table. If it is named, this
253 /// returns -1, otherwise it returns the slot number for the value.
254 static int InsertValue(Value *V, ValueList &ValueTab = CurFun.Values) {
255 // Things that have names or are void typed don't get slot numbers
256 if (V->hasName() || (V->getType() == Type::VoidTy))
259 // In the case of function values, we have to allow for the forward reference
260 // of basic blocks, which are included in the numbering. Consequently, we keep
261 // track of the next insertion location with NextValNum. When a BB gets
262 // inserted, it could change the size of the CurFun.Values vector.
263 if (&ValueTab == &CurFun.Values) {
264 if (ValueTab.size() <= CurFun.NextValNum)
265 ValueTab.resize(CurFun.NextValNum+1);
266 ValueTab[CurFun.NextValNum++] = V;
267 return CurFun.NextValNum-1;
269 // For all other lists, its okay to just tack it on the back of the vector.
270 ValueTab.push_back(V);
271 return ValueTab.size()-1;
274 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
276 case ValID::LocalID: // Is it a numbered definition?
277 // Module constants occupy the lowest numbered slots...
278 if (D.Num < CurModule.Types.size())
279 return CurModule.Types[D.Num];
281 case ValID::LocalName: // Is it a named definition?
282 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.getName())) {
283 D.destroy(); // Free old strdup'd memory...
288 GenerateError("Internal parser error: Invalid symbol type reference");
292 // If we reached here, we referenced either a symbol that we don't know about
293 // or an id number that hasn't been read yet. We may be referencing something
294 // forward, so just create an entry to be resolved later and get to it...
296 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
299 if (inFunctionScope()) {
300 if (D.Type == ValID::LocalName) {
301 GenerateError("Reference to an undefined type: '" + D.getName() + "'");
304 GenerateError("Reference to an undefined type: #" + utostr(D.Num));
309 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
310 if (I != CurModule.LateResolveTypes.end()) {
315 Type *Typ = OpaqueType::get();
316 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
320 // getExistingVal - Look up the value specified by the provided type and
321 // the provided ValID. If the value exists and has already been defined, return
322 // it. Otherwise return null.
324 static Value *getExistingVal(const Type *Ty, const ValID &D) {
325 if (isa<FunctionType>(Ty)) {
326 GenerateError("Functions are not values and "
327 "must be referenced as pointers");
332 case ValID::LocalID: { // Is it a numbered definition?
333 // Check that the number is within bounds.
334 if (D.Num >= CurFun.Values.size())
336 Value *Result = CurFun.Values[D.Num];
337 if (Ty != Result->getType()) {
338 GenerateError("Numbered value (%" + utostr(D.Num) + ") of type '" +
339 Result->getType()->getDescription() + "' does not match "
340 "expected type, '" + Ty->getDescription() + "'");
345 case ValID::GlobalID: { // Is it a numbered definition?
346 if (D.Num >= CurModule.Values.size())
348 Value *Result = CurModule.Values[D.Num];
349 if (Ty != Result->getType()) {
350 GenerateError("Numbered value (@" + utostr(D.Num) + ") of type '" +
351 Result->getType()->getDescription() + "' does not match "
352 "expected type, '" + Ty->getDescription() + "'");
358 case ValID::LocalName: { // Is it a named definition?
359 if (!inFunctionScope())
361 ValueSymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
362 Value *N = SymTab.lookup(D.getName());
365 if (N->getType() != Ty)
368 D.destroy(); // Free old strdup'd memory...
371 case ValID::GlobalName: { // Is it a named definition?
372 ValueSymbolTable &SymTab = CurModule.CurrentModule->getValueSymbolTable();
373 Value *N = SymTab.lookup(D.getName());
376 if (N->getType() != Ty)
379 D.destroy(); // Free old strdup'd memory...
383 // Check to make sure that "Ty" is an integral type, and that our
384 // value will fit into the specified type...
385 case ValID::ConstSIntVal: // Is it a constant pool reference??
386 if (!isa<IntegerType>(Ty) ||
387 !ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
388 GenerateError("Signed integral constant '" +
389 itostr(D.ConstPool64) + "' is invalid for type '" +
390 Ty->getDescription() + "'");
393 return ConstantInt::get(Ty, D.ConstPool64, true);
395 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
396 if (isa<IntegerType>(Ty) &&
397 ConstantInt::isValueValidForType(Ty, D.UConstPool64))
398 return ConstantInt::get(Ty, D.UConstPool64);
400 if (!isa<IntegerType>(Ty) ||
401 !ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
402 GenerateError("Integral constant '" + utostr(D.UConstPool64) +
403 "' is invalid or out of range for type '" +
404 Ty->getDescription() + "'");
407 // This is really a signed reference. Transmogrify.
408 return ConstantInt::get(Ty, D.ConstPool64, true);
410 case ValID::ConstAPInt: // Is it an unsigned const pool reference?
411 if (!isa<IntegerType>(Ty)) {
412 GenerateError("Integral constant '" + D.getName() +
413 "' is invalid or out of range for type '" +
414 Ty->getDescription() + "'");
419 APSInt Tmp = *D.ConstPoolInt;
420 Tmp.extOrTrunc(Ty->getPrimitiveSizeInBits());
421 return ConstantInt::get(Tmp);
424 case ValID::ConstFPVal: // Is it a floating point const pool reference?
425 if (!Ty->isFloatingPoint() ||
426 !ConstantFP::isValueValidForType(Ty, *D.ConstPoolFP)) {
427 GenerateError("FP constant invalid for type");
430 // Lexer has no type info, so builds all float and double FP constants
431 // as double. Fix this here. Long double does not need this.
432 if (&D.ConstPoolFP->getSemantics() == &APFloat::IEEEdouble &&
435 D.ConstPoolFP->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
438 return ConstantFP::get(*D.ConstPoolFP);
440 case ValID::ConstNullVal: // Is it a null value?
441 if (!isa<PointerType>(Ty)) {
442 GenerateError("Cannot create a a non pointer null");
445 return ConstantPointerNull::get(cast<PointerType>(Ty));
447 case ValID::ConstUndefVal: // Is it an undef value?
448 return UndefValue::get(Ty);
450 case ValID::ConstZeroVal: // Is it a zero value?
451 return Constant::getNullValue(Ty);
453 case ValID::ConstantVal: // Fully resolved constant?
454 if (D.ConstantValue->getType() != Ty) {
455 GenerateError("Constant expression type different from required type");
458 return D.ConstantValue;
460 case ValID::InlineAsmVal: { // Inline asm expression
461 const PointerType *PTy = dyn_cast<PointerType>(Ty);
462 const FunctionType *FTy =
463 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
464 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
465 GenerateError("Invalid type for asm constraint string");
468 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
469 D.IAD->HasSideEffects);
470 D.destroy(); // Free InlineAsmDescriptor.
474 assert(0 && "Unhandled case!");
478 assert(0 && "Unhandled case!");
482 // getVal - This function is identical to getExistingVal, except that if a
483 // value is not already defined, it "improvises" by creating a placeholder var
484 // that looks and acts just like the requested variable. When the value is
485 // defined later, all uses of the placeholder variable are replaced with the
488 static Value *getVal(const Type *Ty, const ValID &ID) {
489 if (Ty == Type::LabelTy) {
490 GenerateError("Cannot use a basic block here");
494 // See if the value has already been defined.
495 Value *V = getExistingVal(Ty, ID);
497 if (TriggerError) return 0;
499 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
500 GenerateError("Invalid use of a non-first-class type");
504 // If we reached here, we referenced either a symbol that we don't know about
505 // or an id number that hasn't been read yet. We may be referencing something
506 // forward, so just create an entry to be resolved later and get to it...
509 case ValID::GlobalName:
510 case ValID::GlobalID: {
511 const PointerType *PTy = dyn_cast<PointerType>(Ty);
513 GenerateError("Invalid type for reference to global" );
516 const Type* ElTy = PTy->getElementType();
517 if (const FunctionType *FTy = dyn_cast<FunctionType>(ElTy))
518 V = Function::Create(FTy, GlobalValue::ExternalLinkage);
520 V = new GlobalVariable(ElTy, false, GlobalValue::ExternalLinkage, 0, "",
521 (Module*)0, false, PTy->getAddressSpace());
525 V = new Argument(Ty);
528 // Remember where this forward reference came from. FIXME, shouldn't we try
529 // to recycle these things??
530 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
533 if (inFunctionScope())
534 InsertValue(V, CurFun.LateResolveValues);
536 InsertValue(V, CurModule.LateResolveValues);
540 /// defineBBVal - This is a definition of a new basic block with the specified
541 /// identifier which must be the same as CurFun.NextValNum, if its numeric.
542 static BasicBlock *defineBBVal(const ValID &ID) {
543 assert(inFunctionScope() && "Can't get basic block at global scope!");
547 // First, see if this was forward referenced
549 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
550 if (BBI != CurFun.BBForwardRefs.end()) {
552 // The forward declaration could have been inserted anywhere in the
553 // function: insert it into the correct place now.
554 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
555 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
557 // We're about to erase the entry, save the key so we can clean it up.
558 ValID Tmp = BBI->first;
560 // Erase the forward ref from the map as its no longer "forward"
561 CurFun.BBForwardRefs.erase(ID);
563 // The key has been removed from the map but so we don't want to leave
564 // strdup'd memory around so destroy it too.
567 // If its a numbered definition, bump the number and set the BB value.
568 if (ID.Type == ValID::LocalID) {
569 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
573 // We haven't seen this BB before and its first mention is a definition.
574 // Just create it and return it.
575 std::string Name (ID.Type == ValID::LocalName ? ID.getName() : "");
576 BB = BasicBlock::Create(Name, CurFun.CurrentFunction);
577 if (ID.Type == ValID::LocalID) {
578 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
587 /// getBBVal - get an existing BB value or create a forward reference for it.
589 static BasicBlock *getBBVal(const ValID &ID) {
590 assert(inFunctionScope() && "Can't get basic block at global scope!");
594 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
595 if (BBI != CurFun.BBForwardRefs.end()) {
597 } if (ID.Type == ValID::LocalName) {
598 std::string Name = ID.getName();
599 Value *N = CurFun.CurrentFunction->getValueSymbolTable().lookup(Name);
601 if (N->getType()->getTypeID() == Type::LabelTyID)
602 BB = cast<BasicBlock>(N);
604 GenerateError("Reference to label '" + Name + "' is actually of type '"+
605 N->getType()->getDescription() + "'");
607 } else if (ID.Type == ValID::LocalID) {
608 if (ID.Num < CurFun.NextValNum && ID.Num < CurFun.Values.size()) {
609 if (CurFun.Values[ID.Num]->getType()->getTypeID() == Type::LabelTyID)
610 BB = cast<BasicBlock>(CurFun.Values[ID.Num]);
612 GenerateError("Reference to label '%" + utostr(ID.Num) +
613 "' is actually of type '"+
614 CurFun.Values[ID.Num]->getType()->getDescription() + "'");
617 GenerateError("Illegal label reference " + ID.getName());
621 // If its already been defined, return it now.
623 ID.destroy(); // Free strdup'd memory.
627 // Otherwise, this block has not been seen before, create it.
629 if (ID.Type == ValID::LocalName)
631 BB = BasicBlock::Create(Name, CurFun.CurrentFunction);
633 // Insert it in the forward refs map.
634 CurFun.BBForwardRefs[ID] = BB;
640 //===----------------------------------------------------------------------===//
641 // Code to handle forward references in instructions
642 //===----------------------------------------------------------------------===//
644 // This code handles the late binding needed with statements that reference
645 // values not defined yet... for example, a forward branch, or the PHI node for
648 // This keeps a table (CurFun.LateResolveValues) of all such forward references
649 // and back patchs after we are done.
652 // ResolveDefinitions - If we could not resolve some defs at parsing
653 // time (forward branches, phi functions for loops, etc...) resolve the
657 ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers) {
658 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
659 while (!LateResolvers.empty()) {
660 Value *V = LateResolvers.back();
661 LateResolvers.pop_back();
663 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
664 CurModule.PlaceHolderInfo.find(V);
665 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
667 ValID &DID = PHI->second.first;
669 Value *TheRealValue = getExistingVal(V->getType(), DID);
673 V->replaceAllUsesWith(TheRealValue);
675 CurModule.PlaceHolderInfo.erase(PHI);
676 } else if (FutureLateResolvers) {
677 // Functions have their unresolved items forwarded to the module late
679 InsertValue(V, *FutureLateResolvers);
681 if (DID.Type == ValID::LocalName || DID.Type == ValID::GlobalName) {
682 GenerateError("Reference to an invalid definition: '" +DID.getName()+
683 "' of type '" + V->getType()->getDescription() + "'",
687 GenerateError("Reference to an invalid definition: #" +
688 itostr(DID.Num) + " of type '" +
689 V->getType()->getDescription() + "'",
695 LateResolvers.clear();
698 // ResolveTypeTo - A brand new type was just declared. This means that (if
699 // name is not null) things referencing Name can be resolved. Otherwise, things
700 // refering to the number can be resolved. Do this now.
702 static void ResolveTypeTo(std::string *Name, const Type *ToTy) {
705 D = ValID::createLocalName(*Name);
707 D = ValID::createLocalID(CurModule.Types.size());
709 std::map<ValID, PATypeHolder>::iterator I =
710 CurModule.LateResolveTypes.find(D);
711 if (I != CurModule.LateResolveTypes.end()) {
712 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
714 CurModule.LateResolveTypes.erase(I);
719 // setValueName - Set the specified value to the name given. The name may be
720 // null potentially, in which case this is a noop. The string passed in is
721 // assumed to be a malloc'd string buffer, and is free'd by this function.
723 static void setValueName(Value *V, std::string *NameStr) {
724 if (!NameStr) return;
725 std::string Name(*NameStr); // Copy string
726 delete NameStr; // Free old string
728 if (V->getType() == Type::VoidTy) {
729 GenerateError("Can't assign name '" + Name+"' to value with void type");
733 assert(inFunctionScope() && "Must be in function scope!");
734 ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
735 if (ST.lookup(Name)) {
736 GenerateError("Redefinition of value '" + Name + "' of type '" +
737 V->getType()->getDescription() + "'");
745 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
746 /// this is a declaration, otherwise it is a definition.
747 static GlobalVariable *
748 ParseGlobalVariable(std::string *NameStr,
749 GlobalValue::LinkageTypes Linkage,
750 GlobalValue::VisibilityTypes Visibility,
751 bool isConstantGlobal, const Type *Ty,
752 Constant *Initializer, bool IsThreadLocal,
753 unsigned AddressSpace = 0) {
754 if (isa<FunctionType>(Ty)) {
755 GenerateError("Cannot declare global vars of function type");
758 if (Ty == Type::LabelTy) {
759 GenerateError("Cannot declare global vars of label type");
763 const PointerType *PTy = PointerType::get(Ty, AddressSpace);
767 Name = *NameStr; // Copy string
768 delete NameStr; // Free old string
771 // See if this global value was forward referenced. If so, recycle the
775 ID = ValID::createGlobalName(Name);
777 ID = ValID::createGlobalID(CurModule.Values.size());
780 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
781 // Move the global to the end of the list, from whereever it was
782 // previously inserted.
783 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
784 CurModule.CurrentModule->getGlobalList().remove(GV);
785 CurModule.CurrentModule->getGlobalList().push_back(GV);
786 GV->setInitializer(Initializer);
787 GV->setLinkage(Linkage);
788 GV->setVisibility(Visibility);
789 GV->setConstant(isConstantGlobal);
790 GV->setThreadLocal(IsThreadLocal);
791 InsertValue(GV, CurModule.Values);
798 // If this global has a name
800 // if the global we're parsing has an initializer (is a definition) and
801 // has external linkage.
802 if (Initializer && Linkage != GlobalValue::InternalLinkage)
803 // If there is already a global with external linkage with this name
804 if (CurModule.CurrentModule->getGlobalVariable(Name, false)) {
805 // If we allow this GVar to get created, it will be renamed in the
806 // symbol table because it conflicts with an existing GVar. We can't
807 // allow redefinition of GVars whose linking indicates that their name
808 // must stay the same. Issue the error.
809 GenerateError("Redefinition of global variable named '" + Name +
810 "' of type '" + Ty->getDescription() + "'");
815 // Otherwise there is no existing GV to use, create one now.
817 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
818 CurModule.CurrentModule, IsThreadLocal, AddressSpace);
819 GV->setVisibility(Visibility);
820 InsertValue(GV, CurModule.Values);
824 // setTypeName - Set the specified type to the name given. The name may be
825 // null potentially, in which case this is a noop. The string passed in is
826 // assumed to be a malloc'd string buffer, and is freed by this function.
828 // This function returns true if the type has already been defined, but is
829 // allowed to be redefined in the specified context. If the name is a new name
830 // for the type plane, it is inserted and false is returned.
831 static bool setTypeName(const Type *T, std::string *NameStr) {
832 assert(!inFunctionScope() && "Can't give types function-local names!");
833 if (NameStr == 0) return false;
835 std::string Name(*NameStr); // Copy string
836 delete NameStr; // Free old string
838 // We don't allow assigning names to void type
839 if (T == Type::VoidTy) {
840 GenerateError("Can't assign name '" + Name + "' to the void type");
844 // Set the type name, checking for conflicts as we do so.
845 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
847 if (AlreadyExists) { // Inserting a name that is already defined???
848 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
849 assert(Existing && "Conflict but no matching type?!");
851 // There is only one case where this is allowed: when we are refining an
852 // opaque type. In this case, Existing will be an opaque type.
853 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
854 // We ARE replacing an opaque type!
855 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
859 // Otherwise, this is an attempt to redefine a type. That's okay if
860 // the redefinition is identical to the original. This will be so if
861 // Existing and T point to the same Type object. In this one case we
862 // allow the equivalent redefinition.
863 if (Existing == T) return true; // Yes, it's equal.
865 // Any other kind of (non-equivalent) redefinition is an error.
866 GenerateError("Redefinition of type named '" + Name + "' of type '" +
867 T->getDescription() + "'");
873 //===----------------------------------------------------------------------===//
874 // Code for handling upreferences in type names...
877 // TypeContains - Returns true if Ty directly contains E in it.
879 static bool TypeContains(const Type *Ty, const Type *E) {
880 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
881 E) != Ty->subtype_end();
886 // NestingLevel - The number of nesting levels that need to be popped before
887 // this type is resolved.
888 unsigned NestingLevel;
890 // LastContainedTy - This is the type at the current binding level for the
891 // type. Every time we reduce the nesting level, this gets updated.
892 const Type *LastContainedTy;
894 // UpRefTy - This is the actual opaque type that the upreference is
898 UpRefRecord(unsigned NL, OpaqueType *URTy)
899 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
903 // UpRefs - A list of the outstanding upreferences that need to be resolved.
904 static std::vector<UpRefRecord> UpRefs;
906 /// HandleUpRefs - Every time we finish a new layer of types, this function is
907 /// called. It loops through the UpRefs vector, which is a list of the
908 /// currently active types. For each type, if the up reference is contained in
909 /// the newly completed type, we decrement the level count. When the level
910 /// count reaches zero, the upreferenced type is the type that is passed in:
911 /// thus we can complete the cycle.
913 static PATypeHolder HandleUpRefs(const Type *ty) {
914 // If Ty isn't abstract, or if there are no up-references in it, then there is
915 // nothing to resolve here.
916 if (!ty->isAbstract() || UpRefs.empty()) return ty;
919 UR_OUT("Type '" << Ty->getDescription() <<
920 "' newly formed. Resolving upreferences.\n" <<
921 UpRefs.size() << " upreferences active!\n");
923 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
924 // to zero), we resolve them all together before we resolve them to Ty. At
925 // the end of the loop, if there is anything to resolve to Ty, it will be in
927 OpaqueType *TypeToResolve = 0;
929 for (unsigned i = 0; i != UpRefs.size(); ++i) {
930 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
931 << UpRefs[i].second->getDescription() << ") = "
932 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
933 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
934 // Decrement level of upreference
935 unsigned Level = --UpRefs[i].NestingLevel;
936 UpRefs[i].LastContainedTy = Ty;
937 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
938 if (Level == 0) { // Upreference should be resolved!
939 if (!TypeToResolve) {
940 TypeToResolve = UpRefs[i].UpRefTy;
942 UR_OUT(" * Resolving upreference for "
943 << UpRefs[i].second->getDescription() << "\n";
944 std::string OldName = UpRefs[i].UpRefTy->getDescription());
945 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
946 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
947 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
949 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
950 --i; // Do not skip the next element...
956 UR_OUT(" * Resolving upreference for "
957 << UpRefs[i].second->getDescription() << "\n";
958 std::string OldName = TypeToResolve->getDescription());
959 TypeToResolve->refineAbstractTypeTo(Ty);
965 //===----------------------------------------------------------------------===//
966 // RunVMAsmParser - Define an interface to this parser
967 //===----------------------------------------------------------------------===//
969 static Module* RunParser(Module * M);
971 Module *llvm::RunVMAsmParser(llvm::MemoryBuffer *MB) {
973 Module *M = RunParser(new Module(LLLgetFilename()));
981 llvm::Module *ModuleVal;
982 llvm::Function *FunctionVal;
983 llvm::BasicBlock *BasicBlockVal;
984 llvm::TerminatorInst *TermInstVal;
985 llvm::Instruction *InstVal;
986 llvm::Constant *ConstVal;
988 const llvm::Type *PrimType;
989 std::list<llvm::PATypeHolder> *TypeList;
990 llvm::PATypeHolder *TypeVal;
991 llvm::Value *ValueVal;
992 std::vector<llvm::Value*> *ValueList;
993 std::vector<unsigned> *ConstantList;
994 llvm::ArgListType *ArgList;
995 llvm::TypeWithAttrs TypeWithAttrs;
996 llvm::TypeWithAttrsList *TypeWithAttrsList;
997 llvm::ParamList *ParamList;
999 // Represent the RHS of PHI node
1000 std::list<std::pair<llvm::Value*,
1001 llvm::BasicBlock*> > *PHIList;
1002 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
1003 std::vector<llvm::Constant*> *ConstVector;
1005 llvm::GlobalValue::LinkageTypes Linkage;
1006 llvm::GlobalValue::VisibilityTypes Visibility;
1007 llvm::Attributes Attributes;
1008 llvm::APInt *APIntVal;
1013 llvm::APFloat *FPVal;
1016 std::string *StrVal; // This memory must be deleted
1017 llvm::ValID ValIDVal;
1019 llvm::Instruction::BinaryOps BinaryOpVal;
1020 llvm::Instruction::TermOps TermOpVal;
1021 llvm::Instruction::MemoryOps MemOpVal;
1022 llvm::Instruction::CastOps CastOpVal;
1023 llvm::Instruction::OtherOps OtherOpVal;
1024 llvm::ICmpInst::Predicate IPredicate;
1025 llvm::FCmpInst::Predicate FPredicate;
1028 %type <ModuleVal> Module
1029 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1030 %type <BasicBlockVal> BasicBlock InstructionList
1031 %type <TermInstVal> BBTerminatorInst
1032 %type <InstVal> Inst InstVal MemoryInst
1033 %type <ConstVal> ConstVal ConstExpr AliaseeRef
1034 %type <ConstVector> ConstVector
1035 %type <ArgList> ArgList ArgListH
1036 %type <PHIList> PHIList
1037 %type <ParamList> ParamList // For call param lists & GEP indices
1038 %type <ValueList> IndexList // For GEP indices
1039 %type <ConstantList> ConstantIndexList // For insertvalue/extractvalue indices
1040 %type <TypeList> TypeListI
1041 %type <TypeWithAttrsList> ArgTypeList ArgTypeListI
1042 %type <TypeWithAttrs> ArgType
1043 %type <JumpTable> JumpTable
1044 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1045 %type <BoolVal> ThreadLocal // 'thread_local' or not
1046 %type <BoolVal> OptVolatile // 'volatile' or not
1047 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1048 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
1049 %type <Linkage> GVInternalLinkage GVExternalLinkage
1050 %type <Linkage> FunctionDefineLinkage FunctionDeclareLinkage
1051 %type <Linkage> AliasLinkage
1052 %type <Visibility> GVVisibilityStyle
1054 // ValueRef - Unresolved reference to a definition or BB
1055 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1056 %type <ValueVal> ResolvedVal // <type> <valref> pair
1057 %type <ValueList> ReturnedVal
1058 // Tokens and types for handling constant integer values
1060 // ESINT64VAL - A negative number within long long range
1061 %token <SInt64Val> ESINT64VAL
1063 // EUINT64VAL - A positive number within uns. long long range
1064 %token <UInt64Val> EUINT64VAL
1066 // ESAPINTVAL - A negative number with arbitrary precision
1067 %token <APIntVal> ESAPINTVAL
1069 // EUAPINTVAL - A positive number with arbitrary precision
1070 %token <APIntVal> EUAPINTVAL
1072 %token <UIntVal> LOCALVAL_ID GLOBALVAL_ID // %123 @123
1073 %token <FPVal> FPVAL // Float or Double constant
1075 // Built in types...
1076 %type <TypeVal> Types ResultTypes
1077 %type <PrimType> PrimType // Classifications
1078 %token <PrimType> VOID INTTYPE
1079 %token <PrimType> FLOAT DOUBLE X86_FP80 FP128 PPC_FP128 LABEL
1083 %token<StrVal> LOCALVAR GLOBALVAR LABELSTR
1084 %token<StrVal> STRINGCONSTANT ATSTRINGCONSTANT PCTSTRINGCONSTANT
1085 %type <StrVal> LocalName OptLocalName OptLocalAssign
1086 %type <StrVal> GlobalName OptGlobalAssign GlobalAssign
1087 %type <StrVal> OptSection SectionString OptGC
1089 %type <UIntVal> OptAlign OptCAlign OptAddrSpace
1091 %token ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1092 %token DECLARE DEFINE GLOBAL CONSTANT SECTION ALIAS VOLATILE THREAD_LOCAL
1093 %token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
1094 %token DLLIMPORT DLLEXPORT EXTERN_WEAK COMMON
1095 %token OPAQUE EXTERNAL TARGET TRIPLE ALIGN ADDRSPACE
1096 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1097 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1099 %type <UIntVal> OptCallingConv LocalNumber
1100 %type <Attributes> OptAttributes Attribute
1101 %type <Attributes> OptFuncAttrs FuncAttr
1102 %type <Attributes> OptRetAttrs RetAttr
1104 // Basic Block Terminating Operators
1105 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1108 %type <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
1109 %token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1110 %token <BinaryOpVal> SHL LSHR ASHR
1112 %token <OtherOpVal> ICMP FCMP VICMP VFCMP
1113 %type <IPredicate> IPredicates
1114 %type <FPredicate> FPredicates
1115 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1116 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1118 // Memory Instructions
1119 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1122 %type <CastOpVal> CastOps
1123 %token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1124 %token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1127 %token <OtherOpVal> PHI_TOK SELECT VAARG
1128 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1129 %token <OtherOpVal> GETRESULT
1130 %token <OtherOpVal> EXTRACTVALUE INSERTVALUE
1132 // Function Attributes
1133 %token SIGNEXT ZEROEXT NORETURN INREG SRET NOUNWIND NOALIAS BYVAL NEST
1134 %token READNONE READONLY GC OPTSIZE NOINLINE ALWAYSINLINE
1136 // Visibility Styles
1137 %token DEFAULT HIDDEN PROTECTED
1143 // Operations that are notably excluded from this list include:
1144 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1146 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1147 LogicalOps : SHL | LSHR | ASHR | AND | OR | XOR;
1148 CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1149 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1152 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1153 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1154 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1155 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1156 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1160 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1161 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1162 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1163 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1164 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1165 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1166 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1167 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1168 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1171 LocalName : LOCALVAR | STRINGCONSTANT | PCTSTRINGCONSTANT ;
1172 OptLocalName : LocalName | /*empty*/ { $$ = 0; };
1174 OptAddrSpace : ADDRSPACE '(' EUINT64VAL ')' { $$=$3; }
1175 | /*empty*/ { $$=0; };
1177 /// OptLocalAssign - Value producing statements have an optional assignment
1179 OptLocalAssign : LocalName '=' {
1188 LocalNumber : LOCALVAL_ID '=' {
1194 GlobalName : GLOBALVAR | ATSTRINGCONSTANT ;
1196 OptGlobalAssign : GlobalAssign
1202 GlobalAssign : GlobalName '=' {
1208 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1209 | WEAK { $$ = GlobalValue::WeakLinkage; }
1210 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1211 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1212 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1213 | COMMON { $$ = GlobalValue::CommonLinkage; }
1217 : DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1218 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1219 | EXTERNAL { $$ = GlobalValue::ExternalLinkage; }
1223 : /*empty*/ { $$ = GlobalValue::DefaultVisibility; }
1224 | DEFAULT { $$ = GlobalValue::DefaultVisibility; }
1225 | HIDDEN { $$ = GlobalValue::HiddenVisibility; }
1226 | PROTECTED { $$ = GlobalValue::ProtectedVisibility; }
1229 FunctionDeclareLinkage
1230 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1231 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1232 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1235 FunctionDefineLinkage
1236 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1237 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1238 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1239 | WEAK { $$ = GlobalValue::WeakLinkage; }
1240 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1244 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1245 | WEAK { $$ = GlobalValue::WeakLinkage; }
1246 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1249 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1250 CCC_TOK { $$ = CallingConv::C; } |
1251 FASTCC_TOK { $$ = CallingConv::Fast; } |
1252 COLDCC_TOK { $$ = CallingConv::Cold; } |
1253 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1254 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1256 if ((unsigned)$2 != $2)
1257 GEN_ERROR("Calling conv too large");
1262 Attribute : ZEROEXT { $$ = Attribute::ZExt; }
1263 | ZEXT { $$ = Attribute::ZExt; }
1264 | SIGNEXT { $$ = Attribute::SExt; }
1265 | SEXT { $$ = Attribute::SExt; }
1266 | INREG { $$ = Attribute::InReg; }
1267 | SRET { $$ = Attribute::StructRet; }
1268 | NOALIAS { $$ = Attribute::NoAlias; }
1269 | BYVAL { $$ = Attribute::ByVal; }
1270 | NEST { $$ = Attribute::Nest; }
1271 | ALIGN EUINT64VAL { $$ =
1272 Attribute::constructAlignmentFromInt($2); }
1275 OptAttributes : /* empty */ { $$ = Attribute::None; }
1276 | OptAttributes Attribute {
1281 RetAttr : INREG { $$ = Attribute::InReg; }
1282 | ZEROEXT { $$ = Attribute::ZExt; }
1283 | SIGNEXT { $$ = Attribute::SExt; }
1286 OptRetAttrs : /* empty */ { $$ = Attribute::None; }
1287 | OptRetAttrs RetAttr {
1293 FuncAttr : NORETURN { $$ = Attribute::NoReturn; }
1294 | NOUNWIND { $$ = Attribute::NoUnwind; }
1295 | INREG { $$ = Attribute::InReg; }
1296 | ZEROEXT { $$ = Attribute::ZExt; }
1297 | SIGNEXT { $$ = Attribute::SExt; }
1298 | READNONE { $$ = Attribute::ReadNone; }
1299 | READONLY { $$ = Attribute::ReadOnly; }
1300 | NOINLINE { $$ = Attribute::NoInline; }
1301 | ALWAYSINLINE { $$ = Attribute::AlwaysInline; }
1302 | OPTSIZE { $$ = Attribute::OptimizeForSize; }
1305 OptFuncAttrs : /* empty */ { $$ = Attribute::None; }
1306 | OptFuncAttrs FuncAttr {
1312 OptGC : /* empty */ { $$ = 0; }
1313 | GC STRINGCONSTANT {
1318 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1319 // a comma before it.
1320 OptAlign : /*empty*/ { $$ = 0; } |
1323 if ($$ != 0 && !isPowerOf2_32($$))
1324 GEN_ERROR("Alignment must be a power of two");
1327 OptCAlign : /*empty*/ { $$ = 0; } |
1328 ',' ALIGN EUINT64VAL {
1330 if ($$ != 0 && !isPowerOf2_32($$))
1331 GEN_ERROR("Alignment must be a power of two");
1337 SectionString : SECTION STRINGCONSTANT {
1338 for (unsigned i = 0, e = $2->length(); i != e; ++i)
1339 if ((*$2)[i] == '"' || (*$2)[i] == '\\')
1340 GEN_ERROR("Invalid character in section name");
1345 OptSection : /*empty*/ { $$ = 0; } |
1346 SectionString { $$ = $1; };
1348 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1349 // is set to be the global we are processing.
1351 GlobalVarAttributes : /* empty */ {} |
1352 ',' GlobalVarAttribute GlobalVarAttributes {};
1353 GlobalVarAttribute : SectionString {
1354 CurGV->setSection(*$1);
1358 | ALIGN EUINT64VAL {
1359 if ($2 != 0 && !isPowerOf2_32($2))
1360 GEN_ERROR("Alignment must be a power of two");
1361 CurGV->setAlignment($2);
1365 //===----------------------------------------------------------------------===//
1366 // Types includes all predefined types... except void, because it can only be
1367 // used in specific contexts (function returning void for example).
1369 // Derived types are added later...
1371 PrimType : INTTYPE | FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80 | LABEL ;
1375 $$ = new PATypeHolder(OpaqueType::get());
1379 $$ = new PATypeHolder($1);
1382 | Types OptAddrSpace '*' { // Pointer type?
1383 if (*$1 == Type::LabelTy)
1384 GEN_ERROR("Cannot form a pointer to a basic block");
1385 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1, $2)));
1389 | SymbolicValueRef { // Named types are also simple types...
1390 const Type* tmp = getTypeVal($1);
1392 $$ = new PATypeHolder(tmp);
1394 | '\\' EUINT64VAL { // Type UpReference
1395 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range");
1396 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1397 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1398 $$ = new PATypeHolder(OT);
1399 UR_OUT("New Upreference!\n");
1402 | Types '(' ArgTypeListI ')' OptFuncAttrs {
1403 // Allow but ignore attributes on function types; this permits auto-upgrade.
1404 // FIXME: remove in LLVM 3.0.
1405 const Type *RetTy = *$1;
1406 if (!FunctionType::isValidReturnType(RetTy))
1407 GEN_ERROR("Invalid result type for LLVM function");
1409 std::vector<const Type*> Params;
1410 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1411 for (; I != E; ++I ) {
1412 const Type *Ty = I->Ty->get();
1413 Params.push_back(Ty);
1416 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1417 if (isVarArg) Params.pop_back();
1419 for (unsigned i = 0; i != Params.size(); ++i)
1420 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1421 GEN_ERROR("Function arguments must be value types!");
1425 FunctionType *FT = FunctionType::get(RetTy, Params, isVarArg);
1426 delete $1; // Delete the return type handle
1427 $$ = new PATypeHolder(HandleUpRefs(FT));
1429 // Delete the argument list
1430 for (I = $3->begin() ; I != E; ++I ) {
1437 | VOID '(' ArgTypeListI ')' OptFuncAttrs {
1438 // Allow but ignore attributes on function types; this permits auto-upgrade.
1439 // FIXME: remove in LLVM 3.0.
1440 std::vector<const Type*> Params;
1441 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1442 for ( ; I != E; ++I ) {
1443 const Type* Ty = I->Ty->get();
1444 Params.push_back(Ty);
1447 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1448 if (isVarArg) Params.pop_back();
1450 for (unsigned i = 0; i != Params.size(); ++i)
1451 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1452 GEN_ERROR("Function arguments must be value types!");
1456 FunctionType *FT = FunctionType::get($1, Params, isVarArg);
1457 $$ = new PATypeHolder(HandleUpRefs(FT));
1459 // Delete the argument list
1460 for (I = $3->begin() ; I != E; ++I ) {
1468 | '[' EUINT64VAL 'x' Types ']' { // Sized array type?
1469 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, $2)));
1473 | '<' EUINT64VAL 'x' Types '>' { // Vector type?
1474 const llvm::Type* ElemTy = $4->get();
1475 if ((unsigned)$2 != $2)
1476 GEN_ERROR("Unsigned result not equal to signed result");
1477 if (!ElemTy->isFloatingPoint() && !ElemTy->isInteger())
1478 GEN_ERROR("Element type of a VectorType must be primitive");
1479 $$ = new PATypeHolder(HandleUpRefs(VectorType::get(*$4, (unsigned)$2)));
1483 | '{' TypeListI '}' { // Structure type?
1484 std::vector<const Type*> Elements;
1485 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1486 E = $2->end(); I != E; ++I)
1487 Elements.push_back(*I);
1489 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1493 | '{' '}' { // Empty structure type?
1494 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1497 | '<' '{' TypeListI '}' '>' {
1498 std::vector<const Type*> Elements;
1499 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1500 E = $3->end(); I != E; ++I)
1501 Elements.push_back(*I);
1503 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1507 | '<' '{' '}' '>' { // Empty structure type?
1508 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1514 : Types OptAttributes {
1515 // Allow but ignore attributes on function types; this permits auto-upgrade.
1516 // FIXME: remove in LLVM 3.0.
1518 $$.Attrs = Attribute::None;
1524 if (!UpRefs.empty())
1525 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1526 if (!(*$1)->isFirstClassType() && !isa<StructType>($1->get()))
1527 GEN_ERROR("LLVM functions cannot return aggregate types");
1531 $$ = new PATypeHolder(Type::VoidTy);
1535 ArgTypeList : ArgType {
1536 $$ = new TypeWithAttrsList();
1540 | ArgTypeList ',' ArgType {
1541 ($$=$1)->push_back($3);
1548 | ArgTypeList ',' DOTDOTDOT {
1550 TypeWithAttrs TWA; TWA.Attrs = Attribute::None;
1551 TWA.Ty = new PATypeHolder(Type::VoidTy);
1556 $$ = new TypeWithAttrsList;
1557 TypeWithAttrs TWA; TWA.Attrs = Attribute::None;
1558 TWA.Ty = new PATypeHolder(Type::VoidTy);
1563 $$ = new TypeWithAttrsList();
1567 // TypeList - Used for struct declarations and as a basis for function type
1568 // declaration type lists
1571 $$ = new std::list<PATypeHolder>();
1576 | TypeListI ',' Types {
1577 ($$=$1)->push_back(*$3);
1582 // ConstVal - The various declarations that go into the constant pool. This
1583 // production is used ONLY to represent constants that show up AFTER a 'const',
1584 // 'constant' or 'global' token at global scope. Constants that can be inlined
1585 // into other expressions (such as integers and constexprs) are handled by the
1586 // ResolvedVal, ValueRef and ConstValueRef productions.
1588 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1589 if (!UpRefs.empty())
1590 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1591 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1593 GEN_ERROR("Cannot make array constant with type: '" +
1594 (*$1)->getDescription() + "'");
1595 const Type *ETy = ATy->getElementType();
1596 uint64_t NumElements = ATy->getNumElements();
1598 // Verify that we have the correct size...
1599 if (NumElements != uint64_t(-1) && NumElements != $3->size())
1600 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1601 utostr($3->size()) + " arguments, but has size of " +
1602 utostr(NumElements) + "");
1604 // Verify all elements are correct type!
1605 for (unsigned i = 0; i < $3->size(); i++) {
1606 if (ETy != (*$3)[i]->getType())
1607 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1608 ETy->getDescription() +"' as required!\nIt is of type '"+
1609 (*$3)[i]->getType()->getDescription() + "'.");
1612 $$ = ConstantArray::get(ATy, *$3);
1613 delete $1; delete $3;
1617 if (!UpRefs.empty())
1618 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1619 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1621 GEN_ERROR("Cannot make array constant with type: '" +
1622 (*$1)->getDescription() + "'");
1624 uint64_t NumElements = ATy->getNumElements();
1625 if (NumElements != uint64_t(-1) && NumElements != 0)
1626 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1627 " arguments, but has size of " + utostr(NumElements) +"");
1628 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1632 | Types 'c' STRINGCONSTANT {
1633 if (!UpRefs.empty())
1634 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1635 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1637 GEN_ERROR("Cannot make array constant with type: '" +
1638 (*$1)->getDescription() + "'");
1640 uint64_t NumElements = ATy->getNumElements();
1641 const Type *ETy = ATy->getElementType();
1642 if (NumElements != uint64_t(-1) && NumElements != $3->length())
1643 GEN_ERROR("Can't build string constant of size " +
1644 utostr($3->length()) +
1645 " when array has size " + utostr(NumElements) + "");
1646 std::vector<Constant*> Vals;
1647 if (ETy == Type::Int8Ty) {
1648 for (uint64_t i = 0; i < $3->length(); ++i)
1649 Vals.push_back(ConstantInt::get(ETy, (*$3)[i]));
1652 GEN_ERROR("Cannot build string arrays of non byte sized elements");
1655 $$ = ConstantArray::get(ATy, Vals);
1659 | Types '<' ConstVector '>' { // Nonempty unsized arr
1660 if (!UpRefs.empty())
1661 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1662 const VectorType *PTy = dyn_cast<VectorType>($1->get());
1664 GEN_ERROR("Cannot make packed constant with type: '" +
1665 (*$1)->getDescription() + "'");
1666 const Type *ETy = PTy->getElementType();
1667 unsigned NumElements = PTy->getNumElements();
1669 // Verify that we have the correct size...
1670 if (NumElements != unsigned(-1) && NumElements != (unsigned)$3->size())
1671 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1672 utostr($3->size()) + " arguments, but has size of " +
1673 utostr(NumElements) + "");
1675 // Verify all elements are correct type!
1676 for (unsigned i = 0; i < $3->size(); i++) {
1677 if (ETy != (*$3)[i]->getType())
1678 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1679 ETy->getDescription() +"' as required!\nIt is of type '"+
1680 (*$3)[i]->getType()->getDescription() + "'.");
1683 $$ = ConstantVector::get(PTy, *$3);
1684 delete $1; delete $3;
1687 | Types '{' ConstVector '}' {
1688 const StructType *STy = dyn_cast<StructType>($1->get());
1690 GEN_ERROR("Cannot make struct constant with type: '" +
1691 (*$1)->getDescription() + "'");
1693 if ($3->size() != STy->getNumContainedTypes())
1694 GEN_ERROR("Illegal number of initializers for structure type");
1696 // Check to ensure that constants are compatible with the type initializer!
1697 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1698 if ((*$3)[i]->getType() != STy->getElementType(i))
1699 GEN_ERROR("Expected type '" +
1700 STy->getElementType(i)->getDescription() +
1701 "' for element #" + utostr(i) +
1702 " of structure initializer");
1704 // Check to ensure that Type is not packed
1705 if (STy->isPacked())
1706 GEN_ERROR("Unpacked Initializer to vector type '" +
1707 STy->getDescription() + "'");
1709 $$ = ConstantStruct::get(STy, *$3);
1710 delete $1; delete $3;
1714 if (!UpRefs.empty())
1715 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1716 const StructType *STy = dyn_cast<StructType>($1->get());
1718 GEN_ERROR("Cannot make struct constant with type: '" +
1719 (*$1)->getDescription() + "'");
1721 if (STy->getNumContainedTypes() != 0)
1722 GEN_ERROR("Illegal number of initializers for structure type");
1724 // Check to ensure that Type is not packed
1725 if (STy->isPacked())
1726 GEN_ERROR("Unpacked Initializer to vector type '" +
1727 STy->getDescription() + "'");
1729 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1733 | Types '<' '{' ConstVector '}' '>' {
1734 const StructType *STy = dyn_cast<StructType>($1->get());
1736 GEN_ERROR("Cannot make struct constant with type: '" +
1737 (*$1)->getDescription() + "'");
1739 if ($4->size() != STy->getNumContainedTypes())
1740 GEN_ERROR("Illegal number of initializers for structure type");
1742 // Check to ensure that constants are compatible with the type initializer!
1743 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1744 if ((*$4)[i]->getType() != STy->getElementType(i))
1745 GEN_ERROR("Expected type '" +
1746 STy->getElementType(i)->getDescription() +
1747 "' for element #" + utostr(i) +
1748 " of structure initializer");
1750 // Check to ensure that Type is packed
1751 if (!STy->isPacked())
1752 GEN_ERROR("Vector initializer to non-vector type '" +
1753 STy->getDescription() + "'");
1755 $$ = ConstantStruct::get(STy, *$4);
1756 delete $1; delete $4;
1759 | Types '<' '{' '}' '>' {
1760 if (!UpRefs.empty())
1761 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1762 const StructType *STy = dyn_cast<StructType>($1->get());
1764 GEN_ERROR("Cannot make struct constant with type: '" +
1765 (*$1)->getDescription() + "'");
1767 if (STy->getNumContainedTypes() != 0)
1768 GEN_ERROR("Illegal number of initializers for structure type");
1770 // Check to ensure that Type is packed
1771 if (!STy->isPacked())
1772 GEN_ERROR("Vector initializer to non-vector type '" +
1773 STy->getDescription() + "'");
1775 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1780 if (!UpRefs.empty())
1781 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1782 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1784 GEN_ERROR("Cannot make null pointer constant with type: '" +
1785 (*$1)->getDescription() + "'");
1787 $$ = ConstantPointerNull::get(PTy);
1792 if (!UpRefs.empty())
1793 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1794 $$ = UndefValue::get($1->get());
1798 | Types SymbolicValueRef {
1799 if (!UpRefs.empty())
1800 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1801 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1803 GEN_ERROR("Global const reference must be a pointer type " + (*$1)->getDescription());
1805 // ConstExprs can exist in the body of a function, thus creating
1806 // GlobalValues whenever they refer to a variable. Because we are in
1807 // the context of a function, getExistingVal will search the functions
1808 // symbol table instead of the module symbol table for the global symbol,
1809 // which throws things all off. To get around this, we just tell
1810 // getExistingVal that we are at global scope here.
1812 Function *SavedCurFn = CurFun.CurrentFunction;
1813 CurFun.CurrentFunction = 0;
1815 Value *V = getExistingVal(Ty, $2);
1818 CurFun.CurrentFunction = SavedCurFn;
1820 // If this is an initializer for a constant pointer, which is referencing a
1821 // (currently) undefined variable, create a stub now that shall be replaced
1822 // in the future with the right type of variable.
1825 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1826 const PointerType *PT = cast<PointerType>(Ty);
1828 // First check to see if the forward references value is already created!
1829 PerModuleInfo::GlobalRefsType::iterator I =
1830 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1832 if (I != CurModule.GlobalRefs.end()) {
1833 V = I->second; // Placeholder already exists, use it...
1837 if ($2.Type == ValID::GlobalName)
1838 Name = $2.getName();
1839 else if ($2.Type != ValID::GlobalID)
1840 GEN_ERROR("Invalid reference to global");
1842 // Create the forward referenced global.
1844 if (const FunctionType *FTy =
1845 dyn_cast<FunctionType>(PT->getElementType())) {
1846 GV = Function::Create(FTy, GlobalValue::ExternalWeakLinkage, Name,
1847 CurModule.CurrentModule);
1849 GV = new GlobalVariable(PT->getElementType(), false,
1850 GlobalValue::ExternalWeakLinkage, 0,
1851 Name, CurModule.CurrentModule);
1854 // Keep track of the fact that we have a forward ref to recycle it
1855 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1860 $$ = cast<GlobalValue>(V);
1861 delete $1; // Free the type handle
1865 if (!UpRefs.empty())
1866 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1867 if ($1->get() != $2->getType())
1868 GEN_ERROR("Mismatched types for constant expression: " +
1869 (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1874 | Types ZEROINITIALIZER {
1875 if (!UpRefs.empty())
1876 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1877 const Type *Ty = $1->get();
1878 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1879 GEN_ERROR("Cannot create a null initialized value of this type");
1880 $$ = Constant::getNullValue(Ty);
1884 | Types ESINT64VAL { // integral constants
1885 if (IntegerType *IT = dyn_cast<IntegerType>($1->get())) {
1886 if (!ConstantInt::isValueValidForType(IT, $2))
1887 GEN_ERROR("Constant value doesn't fit in type");
1888 $$ = ConstantInt::get(IT, $2, true);
1890 GEN_ERROR("integer constant must have integer type");
1895 | Types ESAPINTVAL { // arbitrary precision integer constants
1896 if (IntegerType *IT = dyn_cast<IntegerType>($1->get())) {
1897 if ($2->getBitWidth() > IT->getBitWidth())
1898 GEN_ERROR("Constant value does not fit in type");
1899 $2->sextOrTrunc(IT->getBitWidth());
1900 $$ = ConstantInt::get(*$2);
1902 GEN_ERROR("integer constant must have integer type");
1908 | Types EUINT64VAL { // integral constants
1909 if (IntegerType *IT = dyn_cast<IntegerType>($1->get())) {
1910 if (!ConstantInt::isValueValidForType(IT, $2))
1911 GEN_ERROR("Constant value doesn't fit in type");
1912 $$ = ConstantInt::get(IT, $2, false);
1914 GEN_ERROR("integer constant must have integer type");
1919 | Types EUAPINTVAL { // arbitrary precision integer constants
1920 if (IntegerType *IT = dyn_cast<IntegerType>($1->get())) {
1921 if ($2->getBitWidth() > IT->getBitWidth())
1922 GEN_ERROR("Constant value does not fit in type");
1923 $2->zextOrTrunc(IT->getBitWidth());
1924 $$ = ConstantInt::get(*$2);
1926 GEN_ERROR("integer constant must have integer type");
1933 | Types TRUETOK { // Boolean constants
1934 if ($1->get() != Type::Int1Ty)
1935 GEN_ERROR("Constant true must have type i1");
1936 $$ = ConstantInt::getTrue();
1940 | Types FALSETOK { // Boolean constants
1941 if ($1->get() != Type::Int1Ty)
1942 GEN_ERROR("Constant false must have type i1");
1943 $$ = ConstantInt::getFalse();
1947 | Types FPVAL { // Floating point constants
1948 if (!ConstantFP::isValueValidForType($1->get(), *$2))
1949 GEN_ERROR("Floating point constant invalid for type");
1951 // Lexer has no type info, so builds all float and double FP constants
1952 // as double. Fix this here. Long double is done right.
1953 if (&$2->getSemantics()==&APFloat::IEEEdouble && $1->get()==Type::FloatTy) {
1955 $2->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
1958 $$ = ConstantFP::get(*$2);
1965 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1966 if (!UpRefs.empty())
1967 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1969 const Type *DestTy = $5->get();
1970 if (!CastInst::castIsValid($1, $3, DestTy))
1971 GEN_ERROR("invalid cast opcode for cast from '" +
1972 Val->getType()->getDescription() + "' to '" +
1973 DestTy->getDescription() + "'");
1974 $$ = ConstantExpr::getCast($1, $3, DestTy);
1977 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1978 if (!isa<PointerType>($3->getType()))
1979 GEN_ERROR("GetElementPtr requires a pointer operand");
1982 GetElementPtrInst::getIndexedType($3->getType(), $4->begin(), $4->end());
1984 GEN_ERROR("Index list invalid for constant getelementptr");
1986 SmallVector<Constant*, 8> IdxVec;
1987 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1988 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1989 IdxVec.push_back(C);
1991 GEN_ERROR("Indices to constant getelementptr must be constants");
1995 $$ = ConstantExpr::getGetElementPtr($3, &IdxVec[0], IdxVec.size());
1998 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1999 if ($3->getType() != Type::Int1Ty)
2000 GEN_ERROR("Select condition must be of boolean type");
2001 if ($5->getType() != $7->getType())
2002 GEN_ERROR("Select operand types must match");
2003 $$ = ConstantExpr::getSelect($3, $5, $7);
2006 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
2007 if ($3->getType() != $5->getType())
2008 GEN_ERROR("Binary operator types must match");
2010 $$ = ConstantExpr::get($1, $3, $5);
2012 | LogicalOps '(' ConstVal ',' ConstVal ')' {
2013 if ($3->getType() != $5->getType())
2014 GEN_ERROR("Logical operator types must match");
2015 if (!$3->getType()->isInteger()) {
2016 if (!isa<VectorType>($3->getType()) ||
2017 !cast<VectorType>($3->getType())->getElementType()->isInteger())
2018 GEN_ERROR("Logical operator requires integral operands");
2020 $$ = ConstantExpr::get($1, $3, $5);
2023 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
2024 if ($4->getType() != $6->getType())
2025 GEN_ERROR("icmp operand types must match");
2026 $$ = ConstantExpr::getICmp($2, $4, $6);
2028 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
2029 if ($4->getType() != $6->getType())
2030 GEN_ERROR("fcmp operand types must match");
2031 $$ = ConstantExpr::getFCmp($2, $4, $6);
2033 | VICMP IPredicates '(' ConstVal ',' ConstVal ')' {
2034 if ($4->getType() != $6->getType())
2035 GEN_ERROR("vicmp operand types must match");
2036 $$ = ConstantExpr::getVICmp($2, $4, $6);
2038 | VFCMP FPredicates '(' ConstVal ',' ConstVal ')' {
2039 if ($4->getType() != $6->getType())
2040 GEN_ERROR("vfcmp operand types must match");
2041 $$ = ConstantExpr::getVFCmp($2, $4, $6);
2043 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
2044 if (!ExtractElementInst::isValidOperands($3, $5))
2045 GEN_ERROR("Invalid extractelement operands");
2046 $$ = ConstantExpr::getExtractElement($3, $5);
2049 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2050 if (!InsertElementInst::isValidOperands($3, $5, $7))
2051 GEN_ERROR("Invalid insertelement operands");
2052 $$ = ConstantExpr::getInsertElement($3, $5, $7);
2055 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2056 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
2057 GEN_ERROR("Invalid shufflevector operands");
2058 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
2061 | EXTRACTVALUE '(' ConstVal ConstantIndexList ')' {
2062 if (!isa<StructType>($3->getType()) && !isa<ArrayType>($3->getType()))
2063 GEN_ERROR("ExtractValue requires an aggregate operand");
2065 $$ = ConstantExpr::getExtractValue($3, &(*$4)[0], $4->size());
2069 | INSERTVALUE '(' ConstVal ',' ConstVal ConstantIndexList ')' {
2070 if (!isa<StructType>($3->getType()) && !isa<ArrayType>($3->getType()))
2071 GEN_ERROR("InsertValue requires an aggregate operand");
2073 $$ = ConstantExpr::getInsertValue($3, $5, &(*$6)[0], $6->size());
2079 // ConstVector - A list of comma separated constants.
2080 ConstVector : ConstVector ',' ConstVal {
2081 ($$ = $1)->push_back($3);
2085 $$ = new std::vector<Constant*>();
2091 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
2092 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
2095 ThreadLocal : THREAD_LOCAL { $$ = true; } | { $$ = false; };
2097 // AliaseeRef - Match either GlobalValue or bitcast to GlobalValue.
2098 AliaseeRef : ResultTypes SymbolicValueRef {
2099 const Type* VTy = $1->get();
2100 Value *V = getVal(VTy, $2);
2102 GlobalValue* Aliasee = dyn_cast<GlobalValue>(V);
2104 GEN_ERROR("Aliases can be created only to global values");
2110 | BITCAST '(' AliaseeRef TO Types ')' {
2112 const Type *DestTy = $5->get();
2113 if (!CastInst::castIsValid($1, $3, DestTy))
2114 GEN_ERROR("invalid cast opcode for cast from '" +
2115 Val->getType()->getDescription() + "' to '" +
2116 DestTy->getDescription() + "'");
2118 $$ = ConstantExpr::getCast($1, $3, DestTy);
2123 //===----------------------------------------------------------------------===//
2124 // Rules to match Modules
2125 //===----------------------------------------------------------------------===//
2127 // Module rule: Capture the result of parsing the whole file into a result
2132 $$ = ParserResult = CurModule.CurrentModule;
2133 CurModule.ModuleDone();
2137 $$ = ParserResult = CurModule.CurrentModule;
2138 CurModule.ModuleDone();
2145 | DefinitionList Definition
2149 : DEFINE { CurFun.isDeclare = false; } Function {
2150 CurFun.FunctionDone();
2153 | DECLARE { CurFun.isDeclare = true; } FunctionProto {
2156 | MODULE ASM_TOK AsmBlock {
2159 | OptLocalAssign TYPE Types {
2160 if (!UpRefs.empty())
2161 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2162 // Eagerly resolve types. This is not an optimization, this is a
2163 // requirement that is due to the fact that we could have this:
2165 // %list = type { %list * }
2166 // %list = type { %list * } ; repeated type decl
2168 // If types are not resolved eagerly, then the two types will not be
2169 // determined to be the same type!
2171 ResolveTypeTo($1, *$3);
2173 if (!setTypeName(*$3, $1) && !$1) {
2175 // If this is a named type that is not a redefinition, add it to the slot
2177 CurModule.Types.push_back(*$3);
2183 | OptLocalAssign TYPE VOID {
2184 ResolveTypeTo($1, $3);
2186 if (!setTypeName($3, $1) && !$1) {
2188 // If this is a named type that is not a redefinition, add it to the slot
2190 CurModule.Types.push_back($3);
2194 | OptGlobalAssign GVVisibilityStyle ThreadLocal GlobalType ConstVal
2196 /* "Externally Visible" Linkage */
2198 GEN_ERROR("Global value initializer is not a constant");
2199 CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
2200 $2, $4, $5->getType(), $5, $3, $6);
2202 } GlobalVarAttributes {
2205 | OptGlobalAssign GVInternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2206 ConstVal OptAddrSpace {
2208 GEN_ERROR("Global value initializer is not a constant");
2209 CurGV = ParseGlobalVariable($1, $2, $3, $5, $6->getType(), $6, $4, $7);
2211 } GlobalVarAttributes {
2214 | OptGlobalAssign GVExternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2215 Types OptAddrSpace {
2216 if (!UpRefs.empty())
2217 GEN_ERROR("Invalid upreference in type: " + (*$6)->getDescription());
2218 CurGV = ParseGlobalVariable($1, $2, $3, $5, *$6, 0, $4, $7);
2221 } GlobalVarAttributes {
2225 | OptGlobalAssign GVVisibilityStyle ALIAS AliasLinkage AliaseeRef {
2232 GEN_ERROR("Alias name cannot be empty");
2234 Constant* Aliasee = $5;
2236 GEN_ERROR(std::string("Invalid aliasee for alias: ") + Name);
2238 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(), $4, Name, Aliasee,
2239 CurModule.CurrentModule);
2240 GA->setVisibility($2);
2241 InsertValue(GA, CurModule.Values);
2244 // If there was a forward reference of this alias, resolve it now.
2248 ID = ValID::createGlobalName(Name);
2250 ID = ValID::createGlobalID(CurModule.Values.size()-1);
2252 if (GlobalValue *FWGV =
2253 CurModule.GetForwardRefForGlobal(GA->getType(), ID)) {
2254 // Replace uses of the fwdref with the actual alias.
2255 FWGV->replaceAllUsesWith(GA);
2256 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(FWGV))
2257 GV->eraseFromParent();
2259 cast<Function>(FWGV)->eraseFromParent();
2265 | TARGET TargetDefinition {
2268 | DEPLIBS '=' LibrariesDefinition {
2274 AsmBlock : STRINGCONSTANT {
2275 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2276 if (AsmSoFar.empty())
2277 CurModule.CurrentModule->setModuleInlineAsm(*$1);
2279 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+*$1);
2284 TargetDefinition : TRIPLE '=' STRINGCONSTANT {
2285 CurModule.CurrentModule->setTargetTriple(*$3);
2288 | DATALAYOUT '=' STRINGCONSTANT {
2289 CurModule.CurrentModule->setDataLayout(*$3);
2293 LibrariesDefinition : '[' LibList ']';
2295 LibList : LibList ',' STRINGCONSTANT {
2296 CurModule.CurrentModule->addLibrary(*$3);
2301 CurModule.CurrentModule->addLibrary(*$1);
2305 | /* empty: end of list */ {
2310 //===----------------------------------------------------------------------===//
2311 // Rules to match Function Headers
2312 //===----------------------------------------------------------------------===//
2314 ArgListH : ArgListH ',' Types OptAttributes OptLocalName {
2315 if (!UpRefs.empty())
2316 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2317 if (!(*$3)->isFirstClassType())
2318 GEN_ERROR("Argument types must be first-class");
2319 ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
2324 | Types OptAttributes OptLocalName {
2325 if (!UpRefs.empty())
2326 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2327 if (!(*$1)->isFirstClassType())
2328 GEN_ERROR("Argument types must be first-class");
2329 ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2330 $$ = new ArgListType;
2335 ArgList : ArgListH {
2339 | ArgListH ',' DOTDOTDOT {
2341 struct ArgListEntry E;
2342 E.Ty = new PATypeHolder(Type::VoidTy);
2344 E.Attrs = Attribute::None;
2349 $$ = new ArgListType;
2350 struct ArgListEntry E;
2351 E.Ty = new PATypeHolder(Type::VoidTy);
2353 E.Attrs = Attribute::None;
2362 FunctionHeaderH : OptCallingConv OptRetAttrs ResultTypes GlobalName '(' ArgList ')'
2363 OptFuncAttrs OptSection OptAlign OptGC {
2364 std::string FunctionName(*$4);
2365 delete $4; // Free strdup'd memory!
2367 // Check the function result for abstractness if this is a define. We should
2368 // have no abstract types at this point
2369 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($3))
2370 GEN_ERROR("Reference to abstract result: "+ $3->get()->getDescription());
2372 if (!FunctionType::isValidReturnType(*$3))
2373 GEN_ERROR("Invalid result type for LLVM function");
2375 std::vector<const Type*> ParamTypeList;
2376 SmallVector<AttributeWithIndex, 8> Attrs;
2377 //FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2379 Attributes RetAttrs = $2;
2380 if ($8 != Attribute::None) {
2381 if ($8 & Attribute::ZExt) {
2382 RetAttrs = RetAttrs | Attribute::ZExt;
2383 $8 = $8 ^ Attribute::ZExt;
2385 if ($8 & Attribute::SExt) {
2386 RetAttrs = RetAttrs | Attribute::SExt;
2387 $8 = $8 ^ Attribute::SExt;
2389 if ($8 & Attribute::InReg) {
2390 RetAttrs = RetAttrs | Attribute::InReg;
2391 $8 = $8 ^ Attribute::InReg;
2394 if (RetAttrs != Attribute::None)
2395 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2396 if ($6) { // If there are arguments...
2398 for (ArgListType::iterator I = $6->begin(); I != $6->end(); ++I, ++index) {
2399 const Type* Ty = I->Ty->get();
2400 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2401 GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2402 ParamTypeList.push_back(Ty);
2403 if (Ty != Type::VoidTy && I->Attrs != Attribute::None)
2404 Attrs.push_back(AttributeWithIndex::get(index, I->Attrs));
2407 if ($8 != Attribute::None)
2408 Attrs.push_back(AttributeWithIndex::get(~0, $8));
2410 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2411 if (isVarArg) ParamTypeList.pop_back();
2415 PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2417 FunctionType *FT = FunctionType::get(*$3, ParamTypeList, isVarArg);
2418 const PointerType *PFT = PointerType::getUnqual(FT);
2422 if (!FunctionName.empty()) {
2423 ID = ValID::createGlobalName((char*)FunctionName.c_str());
2425 ID = ValID::createGlobalID(CurModule.Values.size());
2429 // See if this function was forward referenced. If so, recycle the object.
2430 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2431 // Move the function to the end of the list, from whereever it was
2432 // previously inserted.
2433 Fn = cast<Function>(FWRef);
2434 assert(Fn->getAttributes().isEmpty() &&
2435 "Forward reference has parameter attributes!");
2436 CurModule.CurrentModule->getFunctionList().remove(Fn);
2437 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2438 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2439 (Fn = CurModule.CurrentModule->getFunction(FunctionName))) {
2440 if (Fn->getFunctionType() != FT ) {
2441 // The existing function doesn't have the same type. This is an overload
2443 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2444 } else if (Fn->getAttributes() != PAL) {
2445 // The existing function doesn't have the same parameter attributes.
2446 // This is an overload error.
2447 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2448 } else if (!CurFun.isDeclare && !Fn->isDeclaration()) {
2449 // Neither the existing or the current function is a declaration and they
2450 // have the same name and same type. Clearly this is a redefinition.
2451 GEN_ERROR("Redefinition of function '" + FunctionName + "'");
2452 } else if (Fn->isDeclaration()) {
2453 // Make sure to strip off any argument names so we can't get conflicts.
2454 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2458 } else { // Not already defined?
2459 Fn = Function::Create(FT, GlobalValue::ExternalWeakLinkage, FunctionName,
2460 CurModule.CurrentModule);
2461 InsertValue(Fn, CurModule.Values);
2465 CurFun.FunctionStart(Fn);
2467 if (CurFun.isDeclare) {
2468 // If we have declaration, always overwrite linkage. This will allow us to
2469 // correctly handle cases, when pointer to function is passed as argument to
2470 // another function.
2471 Fn->setLinkage(CurFun.Linkage);
2472 Fn->setVisibility(CurFun.Visibility);
2474 Fn->setCallingConv($1);
2475 Fn->setAttributes(PAL);
2476 Fn->setAlignment($10);
2478 Fn->setSection(*$9);
2482 Fn->setGC($11->c_str());
2486 // Add all of the arguments we parsed to the function...
2487 if ($6) { // Is null if empty...
2488 if (isVarArg) { // Nuke the last entry
2489 assert($6->back().Ty->get() == Type::VoidTy && $6->back().Name == 0 &&
2490 "Not a varargs marker!");
2491 delete $6->back().Ty;
2492 $6->pop_back(); // Delete the last entry
2494 Function::arg_iterator ArgIt = Fn->arg_begin();
2495 Function::arg_iterator ArgEnd = Fn->arg_end();
2497 for (ArgListType::iterator I = $6->begin();
2498 I != $6->end() && ArgIt != ArgEnd; ++I, ++ArgIt) {
2499 delete I->Ty; // Delete the typeholder...
2500 setValueName(ArgIt, I->Name); // Insert arg into symtab...
2506 delete $6; // We're now done with the argument list
2511 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2513 FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2514 $$ = CurFun.CurrentFunction;
2516 // Make sure that we keep track of the linkage type even if there was a
2517 // previous "declare".
2519 $$->setVisibility($2);
2522 END : ENDTOK | '}'; // Allow end of '}' to end a function
2524 Function : BasicBlockList END {
2529 FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2530 CurFun.CurrentFunction->setLinkage($1);
2531 CurFun.CurrentFunction->setVisibility($2);
2532 $$ = CurFun.CurrentFunction;
2533 CurFun.FunctionDone();
2537 //===----------------------------------------------------------------------===//
2538 // Rules to match Basic Blocks
2539 //===----------------------------------------------------------------------===//
2541 OptSideEffect : /* empty */ {
2550 ConstValueRef : ESINT64VAL { // A reference to a direct constant
2551 $$ = ValID::create($1);
2555 $$ = ValID::create($1);
2558 | ESAPINTVAL { // arbitrary precision integer constants
2559 $$ = ValID::create(*$1, true);
2563 | EUAPINTVAL { // arbitrary precision integer constants
2564 $$ = ValID::create(*$1, false);
2568 | FPVAL { // Perhaps it's an FP constant?
2569 $$ = ValID::create($1);
2573 $$ = ValID::create(ConstantInt::getTrue());
2577 $$ = ValID::create(ConstantInt::getFalse());
2581 $$ = ValID::createNull();
2585 $$ = ValID::createUndef();
2588 | ZEROINITIALIZER { // A vector zero constant.
2589 $$ = ValID::createZeroInit();
2592 | '<' ConstVector '>' { // Nonempty unsized packed vector
2593 const Type *ETy = (*$2)[0]->getType();
2594 unsigned NumElements = $2->size();
2596 if (!ETy->isInteger() && !ETy->isFloatingPoint())
2597 GEN_ERROR("Invalid vector element type: " + ETy->getDescription());
2599 VectorType* pt = VectorType::get(ETy, NumElements);
2600 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(pt));
2602 // Verify all elements are correct type!
2603 for (unsigned i = 0; i < $2->size(); i++) {
2604 if (ETy != (*$2)[i]->getType())
2605 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2606 ETy->getDescription() +"' as required!\nIt is of type '" +
2607 (*$2)[i]->getType()->getDescription() + "'.");
2610 $$ = ValID::create(ConstantVector::get(pt, *$2));
2611 delete PTy; delete $2;
2614 | '[' ConstVector ']' { // Nonempty unsized arr
2615 const Type *ETy = (*$2)[0]->getType();
2616 uint64_t NumElements = $2->size();
2618 if (!ETy->isFirstClassType())
2619 GEN_ERROR("Invalid array element type: " + ETy->getDescription());
2621 ArrayType *ATy = ArrayType::get(ETy, NumElements);
2622 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(ATy));
2624 // Verify all elements are correct type!
2625 for (unsigned i = 0; i < $2->size(); i++) {
2626 if (ETy != (*$2)[i]->getType())
2627 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2628 ETy->getDescription() +"' as required!\nIt is of type '"+
2629 (*$2)[i]->getType()->getDescription() + "'.");
2632 $$ = ValID::create(ConstantArray::get(ATy, *$2));
2633 delete PTy; delete $2;
2637 // Use undef instead of an array because it's inconvenient to determine
2638 // the element type at this point, there being no elements to examine.
2639 $$ = ValID::createUndef();
2642 | 'c' STRINGCONSTANT {
2643 uint64_t NumElements = $2->length();
2644 const Type *ETy = Type::Int8Ty;
2646 ArrayType *ATy = ArrayType::get(ETy, NumElements);
2648 std::vector<Constant*> Vals;
2649 for (unsigned i = 0; i < $2->length(); ++i)
2650 Vals.push_back(ConstantInt::get(ETy, (*$2)[i]));
2652 $$ = ValID::create(ConstantArray::get(ATy, Vals));
2655 | '{' ConstVector '}' {
2656 std::vector<const Type*> Elements($2->size());
2657 for (unsigned i = 0, e = $2->size(); i != e; ++i)
2658 Elements[i] = (*$2)[i]->getType();
2660 const StructType *STy = StructType::get(Elements);
2661 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(STy));
2663 $$ = ValID::create(ConstantStruct::get(STy, *$2));
2664 delete PTy; delete $2;
2668 const StructType *STy = StructType::get(std::vector<const Type*>());
2669 $$ = ValID::create(ConstantStruct::get(STy, std::vector<Constant*>()));
2672 | '<' '{' ConstVector '}' '>' {
2673 std::vector<const Type*> Elements($3->size());
2674 for (unsigned i = 0, e = $3->size(); i != e; ++i)
2675 Elements[i] = (*$3)[i]->getType();
2677 const StructType *STy = StructType::get(Elements, /*isPacked=*/true);
2678 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(STy));
2680 $$ = ValID::create(ConstantStruct::get(STy, *$3));
2681 delete PTy; delete $3;
2685 const StructType *STy = StructType::get(std::vector<const Type*>(),
2687 $$ = ValID::create(ConstantStruct::get(STy, std::vector<Constant*>()));
2691 $$ = ValID::create($1);
2694 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2695 $$ = ValID::createInlineAsm(*$3, *$5, $2);
2701 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2704 SymbolicValueRef : LOCALVAL_ID { // Is it an integer reference...?
2705 $$ = ValID::createLocalID($1);
2709 $$ = ValID::createGlobalID($1);
2712 | LocalName { // Is it a named reference...?
2713 $$ = ValID::createLocalName(*$1);
2717 | GlobalName { // Is it a named reference...?
2718 $$ = ValID::createGlobalName(*$1);
2723 // ValueRef - A reference to a definition... either constant or symbolic
2724 ValueRef : SymbolicValueRef | ConstValueRef;
2727 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2728 // type immediately preceeds the value reference, and allows complex constant
2729 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2730 ResolvedVal : Types ValueRef {
2731 if (!UpRefs.empty())
2732 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2733 $$ = getVal(*$1, $2);
2739 ReturnedVal : ResolvedVal {
2740 $$ = new std::vector<Value *>();
2744 | ReturnedVal ',' ResolvedVal {
2745 ($$=$1)->push_back($3);
2749 BasicBlockList : BasicBlockList BasicBlock {
2753 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2759 // Basic blocks are terminated by branching instructions:
2760 // br, br/cc, switch, ret
2762 BasicBlock : InstructionList OptLocalAssign BBTerminatorInst {
2763 setValueName($3, $2);
2766 $1->getInstList().push_back($3);
2771 BasicBlock : InstructionList LocalNumber BBTerminatorInst {
2773 int ValNum = InsertValue($3);
2774 if (ValNum != (int)$2)
2775 GEN_ERROR("Result value number %" + utostr($2) +
2776 " is incorrect, expected %" + utostr((unsigned)ValNum));
2778 $1->getInstList().push_back($3);
2784 InstructionList : InstructionList Inst {
2785 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2786 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2787 if (CI2->getParent() == 0)
2788 $1->getInstList().push_back(CI2);
2789 $1->getInstList().push_back($2);
2793 | /* empty */ { // Empty space between instruction lists
2794 $$ = defineBBVal(ValID::createLocalID(CurFun.NextValNum));
2797 | LABELSTR { // Labelled (named) basic block
2798 $$ = defineBBVal(ValID::createLocalName(*$1));
2805 RET ReturnedVal { // Return with a result...
2806 ValueList &VL = *$2;
2807 assert(!VL.empty() && "Invalid ret operands!");
2808 const Type *ReturnType = CurFun.CurrentFunction->getReturnType();
2809 if (VL.size() > 1 ||
2810 (isa<StructType>(ReturnType) &&
2811 (VL.empty() || VL[0]->getType() != ReturnType))) {
2812 Value *RV = UndefValue::get(ReturnType);
2813 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
2814 Instruction *I = InsertValueInst::Create(RV, VL[i], i, "mrv");
2815 ($<BasicBlockVal>-1)->getInstList().push_back(I);
2818 $$ = ReturnInst::Create(RV);
2820 $$ = ReturnInst::Create(VL[0]);
2825 | RET VOID { // Return with no result...
2826 $$ = ReturnInst::Create();
2829 | BR LABEL ValueRef { // Unconditional Branch...
2830 BasicBlock* tmpBB = getBBVal($3);
2832 $$ = BranchInst::Create(tmpBB);
2833 } // Conditional Branch...
2834 | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2835 if (cast<IntegerType>($2)->getBitWidth() != 1)
2836 GEN_ERROR("Branch condition must have type i1");
2837 BasicBlock* tmpBBA = getBBVal($6);
2839 BasicBlock* tmpBBB = getBBVal($9);
2841 Value* tmpVal = getVal(Type::Int1Ty, $3);
2843 $$ = BranchInst::Create(tmpBBA, tmpBBB, tmpVal);
2845 | SWITCH INTTYPE ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2846 Value* tmpVal = getVal($2, $3);
2848 BasicBlock* tmpBB = getBBVal($6);
2850 SwitchInst *S = SwitchInst::Create(tmpVal, tmpBB, $8->size());
2853 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2855 for (; I != E; ++I) {
2856 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2857 S->addCase(CI, I->second);
2859 GEN_ERROR("Switch case is constant, but not a simple integer");
2864 | SWITCH INTTYPE ValueRef ',' LABEL ValueRef '[' ']' {
2865 Value* tmpVal = getVal($2, $3);
2867 BasicBlock* tmpBB = getBBVal($6);
2869 SwitchInst *S = SwitchInst::Create(tmpVal, tmpBB, 0);
2873 | INVOKE OptCallingConv OptRetAttrs ResultTypes ValueRef '(' ParamList ')'
2874 OptFuncAttrs TO LABEL ValueRef UNWIND LABEL ValueRef {
2876 // Handle the short syntax
2877 const PointerType *PFTy = 0;
2878 const FunctionType *Ty = 0;
2879 if (!(PFTy = dyn_cast<PointerType>($4->get())) ||
2880 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2881 // Pull out the types of all of the arguments...
2882 std::vector<const Type*> ParamTypes;
2883 ParamList::iterator I = $7->begin(), E = $7->end();
2884 for (; I != E; ++I) {
2885 const Type *Ty = I->Val->getType();
2886 if (Ty == Type::VoidTy)
2887 GEN_ERROR("Short call syntax cannot be used with varargs");
2888 ParamTypes.push_back(Ty);
2891 if (!FunctionType::isValidReturnType(*$4))
2892 GEN_ERROR("Invalid result type for LLVM function");
2894 Ty = FunctionType::get($4->get(), ParamTypes, false);
2895 PFTy = PointerType::getUnqual(Ty);
2900 Value *V = getVal(PFTy, $5); // Get the function we're calling...
2902 BasicBlock *Normal = getBBVal($12);
2904 BasicBlock *Except = getBBVal($15);
2907 SmallVector<AttributeWithIndex, 8> Attrs;
2908 //FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2910 Attributes RetAttrs = $3;
2911 if ($9 != Attribute::None) {
2912 if ($9 & Attribute::ZExt) {
2913 RetAttrs = RetAttrs | Attribute::ZExt;
2914 $9 = $9 ^ Attribute::ZExt;
2916 if ($9 & Attribute::SExt) {
2917 RetAttrs = RetAttrs | Attribute::SExt;
2918 $9 = $9 ^ Attribute::SExt;
2920 if ($9 & Attribute::InReg) {
2921 RetAttrs = RetAttrs | Attribute::InReg;
2922 $9 = $9 ^ Attribute::InReg;
2925 if (RetAttrs != Attribute::None)
2926 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2928 // Check the arguments
2930 if ($7->empty()) { // Has no arguments?
2931 // Make sure no arguments is a good thing!
2932 if (Ty->getNumParams() != 0)
2933 GEN_ERROR("No arguments passed to a function that "
2934 "expects arguments");
2935 } else { // Has arguments?
2936 // Loop through FunctionType's arguments and ensure they are specified
2938 FunctionType::param_iterator I = Ty->param_begin();
2939 FunctionType::param_iterator E = Ty->param_end();
2940 ParamList::iterator ArgI = $7->begin(), ArgE = $7->end();
2943 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
2944 if (ArgI->Val->getType() != *I)
2945 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2946 (*I)->getDescription() + "'");
2947 Args.push_back(ArgI->Val);
2948 if (ArgI->Attrs != Attribute::None)
2949 Attrs.push_back(AttributeWithIndex::get(index, ArgI->Attrs));
2952 if (Ty->isVarArg()) {
2954 for (; ArgI != ArgE; ++ArgI, ++index) {
2955 Args.push_back(ArgI->Val); // push the remaining varargs
2956 if (ArgI->Attrs != Attribute::None)
2957 Attrs.push_back(AttributeWithIndex::get(index, ArgI->Attrs));
2959 } else if (I != E || ArgI != ArgE)
2960 GEN_ERROR("Invalid number of parameters detected");
2962 if ($9 != Attribute::None)
2963 Attrs.push_back(AttributeWithIndex::get(~0, $9));
2966 PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2968 // Create the InvokeInst
2969 InvokeInst *II = InvokeInst::Create(V, Normal, Except,
2970 Args.begin(), Args.end());
2971 II->setCallingConv($2);
2972 II->setAttributes(PAL);
2978 $$ = new UnwindInst();
2982 $$ = new UnreachableInst();
2988 JumpTable : JumpTable INTTYPE ConstValueRef ',' LABEL ValueRef {
2990 Constant *V = cast<Constant>(getExistingVal($2, $3));
2993 GEN_ERROR("May only switch on a constant pool value");
2995 BasicBlock* tmpBB = getBBVal($6);
2997 $$->push_back(std::make_pair(V, tmpBB));
2999 | INTTYPE ConstValueRef ',' LABEL ValueRef {
3000 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
3001 Constant *V = cast<Constant>(getExistingVal($1, $2));
3005 GEN_ERROR("May only switch on a constant pool value");
3007 BasicBlock* tmpBB = getBBVal($5);
3009 $$->push_back(std::make_pair(V, tmpBB));
3012 Inst : OptLocalAssign InstVal {
3013 // Is this definition named?? if so, assign the name...
3014 setValueName($2, $1);
3021 Inst : LocalNumber InstVal {
3023 int ValNum = InsertValue($2);
3025 if (ValNum != (int)$1)
3026 GEN_ERROR("Result value number %" + utostr($1) +
3027 " is incorrect, expected %" + utostr((unsigned)ValNum));
3034 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
3035 if (!UpRefs.empty())
3036 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
3037 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
3038 Value* tmpVal = getVal(*$1, $3);
3040 BasicBlock* tmpBB = getBBVal($5);
3042 $$->push_back(std::make_pair(tmpVal, tmpBB));
3045 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
3047 Value* tmpVal = getVal($1->front().first->getType(), $4);
3049 BasicBlock* tmpBB = getBBVal($6);
3051 $1->push_back(std::make_pair(tmpVal, tmpBB));
3055 ParamList : Types OptAttributes ValueRef OptAttributes {
3056 // FIXME: Remove trailing OptAttributes in LLVM 3.0, it was a mistake in 2.0
3057 if (!UpRefs.empty())
3058 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
3059 // Used for call and invoke instructions
3060 $$ = new ParamList();
3061 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getVal($1->get(), $3);
3066 | LABEL OptAttributes ValueRef OptAttributes {
3067 // FIXME: Remove trailing OptAttributes in LLVM 3.0, it was a mistake in 2.0
3068 // Labels are only valid in ASMs
3069 $$ = new ParamList();
3070 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getBBVal($3);
3074 | ParamList ',' Types OptAttributes ValueRef OptAttributes {
3075 // FIXME: Remove trailing OptAttributes in LLVM 3.0, it was a mistake in 2.0
3076 if (!UpRefs.empty())
3077 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3079 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getVal($3->get(), $5);
3084 | ParamList ',' LABEL OptAttributes ValueRef OptAttributes {
3085 // FIXME: Remove trailing OptAttributes in LLVM 3.0, it was a mistake in 2.0
3087 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getBBVal($5);
3091 | /*empty*/ { $$ = new ParamList(); };
3093 IndexList // Used for gep instructions and constant expressions
3094 : /*empty*/ { $$ = new std::vector<Value*>(); }
3095 | IndexList ',' ResolvedVal {
3102 ConstantIndexList // Used for insertvalue and extractvalue instructions
3104 $$ = new std::vector<unsigned>();
3105 if ((unsigned)$2 != $2)
3106 GEN_ERROR("Index " + utostr($2) + " is not valid for insertvalue or extractvalue.");
3109 | ConstantIndexList ',' EUINT64VAL {
3111 if ((unsigned)$3 != $3)
3112 GEN_ERROR("Index " + utostr($3) + " is not valid for insertvalue or extractvalue.");
3118 OptTailCall : TAIL CALL {
3127 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
3128 if (!UpRefs.empty())
3129 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3130 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
3131 !isa<VectorType>((*$2).get()))
3133 "Arithmetic operator requires integer, FP, or packed operands");
3134 Value* val1 = getVal(*$2, $3);
3136 Value* val2 = getVal(*$2, $5);
3138 $$ = BinaryOperator::Create($1, val1, val2);
3140 GEN_ERROR("binary operator returned null");
3143 | LogicalOps Types ValueRef ',' ValueRef {
3144 if (!UpRefs.empty())
3145 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3146 if (!(*$2)->isInteger()) {
3147 if (!isa<VectorType>($2->get()) ||
3148 !cast<VectorType>($2->get())->getElementType()->isInteger())
3149 GEN_ERROR("Logical operator requires integral operands");
3151 Value* tmpVal1 = getVal(*$2, $3);
3153 Value* tmpVal2 = getVal(*$2, $5);
3155 $$ = BinaryOperator::Create($1, tmpVal1, tmpVal2);
3157 GEN_ERROR("binary operator returned null");
3160 | ICMP IPredicates Types ValueRef ',' ValueRef {
3161 if (!UpRefs.empty())
3162 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3163 Value* tmpVal1 = getVal(*$3, $4);
3165 Value* tmpVal2 = getVal(*$3, $6);
3167 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3169 GEN_ERROR("icmp operator returned null");
3172 | FCMP FPredicates Types ValueRef ',' ValueRef {
3173 if (!UpRefs.empty())
3174 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3175 Value* tmpVal1 = getVal(*$3, $4);
3177 Value* tmpVal2 = getVal(*$3, $6);
3179 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3181 GEN_ERROR("fcmp operator returned null");
3184 | VICMP IPredicates Types ValueRef ',' ValueRef {
3185 if (!UpRefs.empty())
3186 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3187 if (!isa<VectorType>((*$3).get()))
3188 GEN_ERROR("Scalar types not supported by vicmp instruction");
3189 Value* tmpVal1 = getVal(*$3, $4);
3191 Value* tmpVal2 = getVal(*$3, $6);
3193 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3195 GEN_ERROR("vicmp operator returned null");
3198 | VFCMP FPredicates Types ValueRef ',' ValueRef {
3199 if (!UpRefs.empty())
3200 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3201 if (!isa<VectorType>((*$3).get()))
3202 GEN_ERROR("Scalar types not supported by vfcmp instruction");
3203 Value* tmpVal1 = getVal(*$3, $4);
3205 Value* tmpVal2 = getVal(*$3, $6);
3207 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3209 GEN_ERROR("vfcmp operator returned null");
3212 | CastOps ResolvedVal TO Types {
3213 if (!UpRefs.empty())
3214 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
3216 const Type* DestTy = $4->get();
3217 if (!CastInst::castIsValid($1, Val, DestTy))
3218 GEN_ERROR("invalid cast opcode for cast from '" +
3219 Val->getType()->getDescription() + "' to '" +
3220 DestTy->getDescription() + "'");
3221 $$ = CastInst::Create($1, Val, DestTy);
3224 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3225 if (isa<VectorType>($2->getType())) {
3227 if (!isa<VectorType>($4->getType())
3228 || !isa<VectorType>($6->getType()) )
3229 GEN_ERROR("vector select value types must be vector types");
3230 const VectorType* cond_type = cast<VectorType>($2->getType());
3231 const VectorType* select_type = cast<VectorType>($4->getType());
3232 if (cond_type->getElementType() != Type::Int1Ty)
3233 GEN_ERROR("vector select condition element type must be boolean");
3234 if (cond_type->getNumElements() != select_type->getNumElements())
3235 GEN_ERROR("vector select number of elements must be the same");
3237 if ($2->getType() != Type::Int1Ty)
3238 GEN_ERROR("select condition must be boolean");
3240 if ($4->getType() != $6->getType())
3241 GEN_ERROR("select value types must match");
3242 $$ = SelectInst::Create($2, $4, $6);
3245 | VAARG ResolvedVal ',' Types {
3246 if (!UpRefs.empty())
3247 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
3248 $$ = new VAArgInst($2, *$4);
3252 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
3253 if (!ExtractElementInst::isValidOperands($2, $4))
3254 GEN_ERROR("Invalid extractelement operands");
3255 $$ = new ExtractElementInst($2, $4);
3258 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3259 if (!InsertElementInst::isValidOperands($2, $4, $6))
3260 GEN_ERROR("Invalid insertelement operands");
3261 $$ = InsertElementInst::Create($2, $4, $6);
3264 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3265 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
3266 GEN_ERROR("Invalid shufflevector operands");
3267 $$ = new ShuffleVectorInst($2, $4, $6);
3271 const Type *Ty = $2->front().first->getType();
3272 if (!Ty->isFirstClassType())
3273 GEN_ERROR("PHI node operands must be of first class type");
3274 $$ = PHINode::Create(Ty);
3275 ((PHINode*)$$)->reserveOperandSpace($2->size());
3276 while ($2->begin() != $2->end()) {
3277 if ($2->front().first->getType() != Ty)
3278 GEN_ERROR("All elements of a PHI node must be of the same type");
3279 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
3282 delete $2; // Free the list...
3285 | OptTailCall OptCallingConv OptRetAttrs ResultTypes ValueRef '(' ParamList ')'
3288 // Handle the short syntax
3289 const PointerType *PFTy = 0;
3290 const FunctionType *Ty = 0;
3291 if (!(PFTy = dyn_cast<PointerType>($4->get())) ||
3292 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3293 // Pull out the types of all of the arguments...
3294 std::vector<const Type*> ParamTypes;
3295 ParamList::iterator I = $7->begin(), E = $7->end();
3296 for (; I != E; ++I) {
3297 const Type *Ty = I->Val->getType();
3298 if (Ty == Type::VoidTy)
3299 GEN_ERROR("Short call syntax cannot be used with varargs");
3300 ParamTypes.push_back(Ty);
3303 if (!FunctionType::isValidReturnType(*$4))
3304 GEN_ERROR("Invalid result type for LLVM function");
3306 Ty = FunctionType::get($4->get(), ParamTypes, false);
3307 PFTy = PointerType::getUnqual(Ty);
3310 Value *V = getVal(PFTy, $5); // Get the function we're calling...
3313 // Check for call to invalid intrinsic to avoid crashing later.
3314 if (Function *theF = dyn_cast<Function>(V)) {
3315 if (theF->hasName() && (theF->getValueName()->getKeyLength() >= 5) &&
3316 (0 == strncmp(theF->getValueName()->getKeyData(), "llvm.", 5)) &&
3317 !theF->getIntrinsicID(true))
3318 GEN_ERROR("Call to invalid LLVM intrinsic function '" +
3319 theF->getName() + "'");
3322 // Set up the Attributes for the function
3323 SmallVector<AttributeWithIndex, 8> Attrs;
3324 //FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
3326 Attributes RetAttrs = $3;
3327 if ($9 != Attribute::None) {
3328 if ($9 & Attribute::ZExt) {
3329 RetAttrs = RetAttrs | Attribute::ZExt;
3330 $9 = $9 ^ Attribute::ZExt;
3332 if ($9 & Attribute::SExt) {
3333 RetAttrs = RetAttrs | Attribute::SExt;
3334 $9 = $9 ^ Attribute::SExt;
3336 if ($9 & Attribute::InReg) {
3337 RetAttrs = RetAttrs | Attribute::InReg;
3338 $9 = $9 ^ Attribute::InReg;
3341 if (RetAttrs != Attribute::None)
3342 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3344 // Check the arguments
3346 if ($7->empty()) { // Has no arguments?
3347 // Make sure no arguments is a good thing!
3348 if (Ty->getNumParams() != 0)
3349 GEN_ERROR("No arguments passed to a function that "
3350 "expects arguments");
3351 } else { // Has arguments?
3352 // Loop through FunctionType's arguments and ensure they are specified
3353 // correctly. Also, gather any parameter attributes.
3354 FunctionType::param_iterator I = Ty->param_begin();
3355 FunctionType::param_iterator E = Ty->param_end();
3356 ParamList::iterator ArgI = $7->begin(), ArgE = $7->end();
3359 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
3360 if (ArgI->Val->getType() != *I)
3361 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
3362 (*I)->getDescription() + "'");
3363 Args.push_back(ArgI->Val);
3364 if (ArgI->Attrs != Attribute::None)
3365 Attrs.push_back(AttributeWithIndex::get(index, ArgI->Attrs));
3367 if (Ty->isVarArg()) {
3369 for (; ArgI != ArgE; ++ArgI, ++index) {
3370 Args.push_back(ArgI->Val); // push the remaining varargs
3371 if (ArgI->Attrs != Attribute::None)
3372 Attrs.push_back(AttributeWithIndex::get(index, ArgI->Attrs));
3374 } else if (I != E || ArgI != ArgE)
3375 GEN_ERROR("Invalid number of parameters detected");
3377 if ($9 != Attribute::None)
3378 Attrs.push_back(AttributeWithIndex::get(~0, $9));
3380 // Finish off the Attributes and check them
3383 PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3385 // Create the call node
3386 CallInst *CI = CallInst::Create(V, Args.begin(), Args.end());
3387 CI->setTailCall($1);
3388 CI->setCallingConv($2);
3389 CI->setAttributes(PAL);
3400 OptVolatile : VOLATILE {
3411 MemoryInst : MALLOC Types OptCAlign {
3412 if (!UpRefs.empty())
3413 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3414 $$ = new MallocInst(*$2, 0, $3);
3418 | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
3419 if (!UpRefs.empty())
3420 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3421 if ($4 != Type::Int32Ty)
3422 GEN_ERROR("Malloc array size is not a 32-bit integer!");
3423 Value* tmpVal = getVal($4, $5);
3425 $$ = new MallocInst(*$2, tmpVal, $6);
3428 | ALLOCA Types OptCAlign {
3429 if (!UpRefs.empty())
3430 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3431 $$ = new AllocaInst(*$2, 0, $3);
3435 | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
3436 if (!UpRefs.empty())
3437 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3438 if ($4 != Type::Int32Ty)
3439 GEN_ERROR("Alloca array size is not a 32-bit integer!");
3440 Value* tmpVal = getVal($4, $5);
3442 $$ = new AllocaInst(*$2, tmpVal, $6);
3445 | FREE ResolvedVal {
3446 if (!isa<PointerType>($2->getType()))
3447 GEN_ERROR("Trying to free nonpointer type " +
3448 $2->getType()->getDescription() + "");
3449 $$ = new FreeInst($2);
3453 | OptVolatile LOAD Types ValueRef OptCAlign {
3454 if (!UpRefs.empty())
3455 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3456 if (!isa<PointerType>($3->get()))
3457 GEN_ERROR("Can't load from nonpointer type: " +
3458 (*$3)->getDescription());
3459 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
3460 GEN_ERROR("Can't load from pointer of non-first-class type: " +
3461 (*$3)->getDescription());
3462 Value* tmpVal = getVal(*$3, $4);
3464 $$ = new LoadInst(tmpVal, "", $1, $5);
3467 | OptVolatile STORE ResolvedVal ',' Types ValueRef OptCAlign {
3468 if (!UpRefs.empty())
3469 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
3470 const PointerType *PT = dyn_cast<PointerType>($5->get());
3472 GEN_ERROR("Can't store to a nonpointer type: " +
3473 (*$5)->getDescription());
3474 const Type *ElTy = PT->getElementType();
3475 if (ElTy != $3->getType())
3476 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
3477 "' into space of type '" + ElTy->getDescription() + "'");
3479 Value* tmpVal = getVal(*$5, $6);
3481 $$ = new StoreInst($3, tmpVal, $1, $7);
3484 | GETRESULT Types ValueRef ',' EUINT64VAL {
3485 if (!UpRefs.empty())
3486 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3487 if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3488 GEN_ERROR("getresult insn requires an aggregate operand");
3489 if (!ExtractValueInst::getIndexedType(*$2, $5))
3490 GEN_ERROR("Invalid getresult index for type '" +
3491 (*$2)->getDescription()+ "'");
3493 Value *tmpVal = getVal(*$2, $3);
3495 $$ = ExtractValueInst::Create(tmpVal, $5);
3498 | GETELEMENTPTR Types ValueRef IndexList {
3499 if (!UpRefs.empty())
3500 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3501 if (!isa<PointerType>($2->get()))
3502 GEN_ERROR("getelementptr insn requires pointer operand");
3504 if (!GetElementPtrInst::getIndexedType(*$2, $4->begin(), $4->end()))
3505 GEN_ERROR("Invalid getelementptr indices for type '" +
3506 (*$2)->getDescription()+ "'");
3507 Value* tmpVal = getVal(*$2, $3);
3509 $$ = GetElementPtrInst::Create(tmpVal, $4->begin(), $4->end());
3513 | EXTRACTVALUE Types ValueRef ConstantIndexList {
3514 if (!UpRefs.empty())
3515 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3516 if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3517 GEN_ERROR("extractvalue insn requires an aggregate operand");
3519 if (!ExtractValueInst::getIndexedType(*$2, $4->begin(), $4->end()))
3520 GEN_ERROR("Invalid extractvalue indices for type '" +
3521 (*$2)->getDescription()+ "'");
3522 Value* tmpVal = getVal(*$2, $3);
3524 $$ = ExtractValueInst::Create(tmpVal, $4->begin(), $4->end());
3528 | INSERTVALUE Types ValueRef ',' Types ValueRef ConstantIndexList {
3529 if (!UpRefs.empty())
3530 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3531 if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3532 GEN_ERROR("extractvalue insn requires an aggregate operand");
3534 if (ExtractValueInst::getIndexedType(*$2, $7->begin(), $7->end()) != $5->get())
3535 GEN_ERROR("Invalid insertvalue indices for type '" +
3536 (*$2)->getDescription()+ "'");
3537 Value* aggVal = getVal(*$2, $3);
3538 Value* tmpVal = getVal(*$5, $6);
3540 $$ = InsertValueInst::Create(aggVal, tmpVal, $7->begin(), $7->end());
3549 // common code from the two 'RunVMAsmParser' functions
3550 static Module* RunParser(Module * M) {
3551 CurModule.CurrentModule = M;
3552 // Check to make sure the parser succeeded
3555 delete ParserResult;
3559 // Emit an error if there are any unresolved types left.
3560 if (!CurModule.LateResolveTypes.empty()) {
3561 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
3562 if (DID.Type == ValID::LocalName) {
3563 GenerateError("Undefined type remains at eof: '"+DID.getName() + "'");
3565 GenerateError("Undefined type remains at eof: #" + itostr(DID.Num));
3568 delete ParserResult;
3572 // Emit an error if there are any unresolved values left.
3573 if (!CurModule.LateResolveValues.empty()) {
3574 Value *V = CurModule.LateResolveValues.back();
3575 std::map<Value*, std::pair<ValID, int> >::iterator I =
3576 CurModule.PlaceHolderInfo.find(V);
3578 if (I != CurModule.PlaceHolderInfo.end()) {
3579 ValID &DID = I->second.first;
3580 if (DID.Type == ValID::LocalName) {
3581 GenerateError("Undefined value remains at eof: "+DID.getName() + "'");
3583 GenerateError("Undefined value remains at eof: #" + itostr(DID.Num));
3586 delete ParserResult;
3591 // Check to make sure that parsing produced a result
3595 // Reset ParserResult variable while saving its value for the result.
3596 Module *Result = ParserResult;
3602 void llvm::GenerateError(const std::string &message, int LineNo) {
3603 if (LineNo == -1) LineNo = LLLgetLineNo();
3604 // TODO: column number in exception
3606 TheParseError->setError(LLLgetFilename(), message, LineNo);
3610 int yyerror(const char *ErrorMsg) {
3611 std::string where = LLLgetFilename() + ":" + utostr(LLLgetLineNo()) + ": ";
3612 std::string errMsg = where + "error: " + std::string(ErrorMsg);
3613 if (yychar != YYEMPTY && yychar != 0) {
3614 errMsg += " while reading token: '";
3615 errMsg += std::string(LLLgetTokenStart(),
3616 LLLgetTokenStart()+LLLgetTokenLength()) + "'";
3618 GenerateError(errMsg);