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())
313 Type *Typ = OpaqueType::get();
314 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
318 // getExistingVal - Look up the value specified by the provided type and
319 // the provided ValID. If the value exists and has already been defined, return
320 // it. Otherwise return null.
322 static Value *getExistingVal(const Type *Ty, const ValID &D) {
323 if (isa<FunctionType>(Ty)) {
324 GenerateError("Functions are not values and "
325 "must be referenced as pointers");
330 case ValID::LocalID: { // Is it a numbered definition?
331 // Check that the number is within bounds.
332 if (D.Num >= CurFun.Values.size())
334 Value *Result = CurFun.Values[D.Num];
335 if (Ty != Result->getType()) {
336 GenerateError("Numbered value (%" + utostr(D.Num) + ") of type '" +
337 Result->getType()->getDescription() + "' does not match "
338 "expected type, '" + Ty->getDescription() + "'");
343 case ValID::GlobalID: { // Is it a numbered definition?
344 if (D.Num >= CurModule.Values.size())
346 Value *Result = CurModule.Values[D.Num];
347 if (Ty != Result->getType()) {
348 GenerateError("Numbered value (@" + utostr(D.Num) + ") of type '" +
349 Result->getType()->getDescription() + "' does not match "
350 "expected type, '" + Ty->getDescription() + "'");
356 case ValID::LocalName: { // Is it a named definition?
357 if (!inFunctionScope())
359 ValueSymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
360 Value *N = SymTab.lookup(D.getName());
363 if (N->getType() != Ty)
366 D.destroy(); // Free old strdup'd memory...
369 case ValID::GlobalName: { // Is it a named definition?
370 ValueSymbolTable &SymTab = CurModule.CurrentModule->getValueSymbolTable();
371 Value *N = SymTab.lookup(D.getName());
374 if (N->getType() != Ty)
377 D.destroy(); // Free old strdup'd memory...
381 // Check to make sure that "Ty" is an integral type, and that our
382 // value will fit into the specified type...
383 case ValID::ConstSIntVal: // Is it a constant pool reference??
384 if (!isa<IntegerType>(Ty) ||
385 !ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
386 GenerateError("Signed integral constant '" +
387 itostr(D.ConstPool64) + "' is invalid for type '" +
388 Ty->getDescription() + "'");
391 return ConstantInt::get(Ty, D.ConstPool64, true);
393 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
394 if (isa<IntegerType>(Ty) &&
395 ConstantInt::isValueValidForType(Ty, D.UConstPool64))
396 return ConstantInt::get(Ty, D.UConstPool64);
398 if (!isa<IntegerType>(Ty) ||
399 !ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
400 GenerateError("Integral constant '" + utostr(D.UConstPool64) +
401 "' is invalid or out of range for type '" +
402 Ty->getDescription() + "'");
405 // This is really a signed reference. Transmogrify.
406 return ConstantInt::get(Ty, D.ConstPool64, true);
408 case ValID::ConstAPInt: // Is it an unsigned const pool reference?
409 if (!isa<IntegerType>(Ty)) {
410 GenerateError("Integral constant '" + D.getName() +
411 "' is invalid or out of range for type '" +
412 Ty->getDescription() + "'");
417 APSInt Tmp = *D.ConstPoolInt;
418 Tmp.extOrTrunc(Ty->getPrimitiveSizeInBits());
419 return ConstantInt::get(Tmp);
422 case ValID::ConstFPVal: // Is it a floating point const pool reference?
423 if (!Ty->isFloatingPoint() ||
424 !ConstantFP::isValueValidForType(Ty, *D.ConstPoolFP)) {
425 GenerateError("FP constant invalid for type");
428 // Lexer has no type info, so builds all float and double FP constants
429 // as double. Fix this here. Long double does not need this.
430 if (&D.ConstPoolFP->getSemantics() == &APFloat::IEEEdouble &&
433 D.ConstPoolFP->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
436 return ConstantFP::get(*D.ConstPoolFP);
438 case ValID::ConstNullVal: // Is it a null value?
439 if (!isa<PointerType>(Ty)) {
440 GenerateError("Cannot create a a non pointer null");
443 return ConstantPointerNull::get(cast<PointerType>(Ty));
445 case ValID::ConstUndefVal: // Is it an undef value?
446 return UndefValue::get(Ty);
448 case ValID::ConstZeroVal: // Is it a zero value?
449 return Constant::getNullValue(Ty);
451 case ValID::ConstantVal: // Fully resolved constant?
452 if (D.ConstantValue->getType() != Ty) {
453 GenerateError("Constant expression type different from required type");
456 return D.ConstantValue;
458 case ValID::InlineAsmVal: { // Inline asm expression
459 const PointerType *PTy = dyn_cast<PointerType>(Ty);
460 const FunctionType *FTy =
461 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
462 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
463 GenerateError("Invalid type for asm constraint string");
466 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
467 D.IAD->HasSideEffects);
468 D.destroy(); // Free InlineAsmDescriptor.
472 assert(0 && "Unhandled case!");
476 assert(0 && "Unhandled case!");
480 // getVal - This function is identical to getExistingVal, except that if a
481 // value is not already defined, it "improvises" by creating a placeholder var
482 // that looks and acts just like the requested variable. When the value is
483 // defined later, all uses of the placeholder variable are replaced with the
486 static Value *getVal(const Type *Ty, const ValID &ID) {
487 if (Ty == Type::LabelTy) {
488 GenerateError("Cannot use a basic block here");
492 // See if the value has already been defined.
493 Value *V = getExistingVal(Ty, ID);
495 if (TriggerError) return 0;
497 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
498 GenerateError("Invalid use of a non-first-class type");
502 // If we reached here, we referenced either a symbol that we don't know about
503 // or an id number that hasn't been read yet. We may be referencing something
504 // forward, so just create an entry to be resolved later and get to it...
507 case ValID::GlobalName:
508 case ValID::GlobalID: {
509 const PointerType *PTy = dyn_cast<PointerType>(Ty);
511 GenerateError("Invalid type for reference to global" );
514 const Type* ElTy = PTy->getElementType();
515 if (const FunctionType *FTy = dyn_cast<FunctionType>(ElTy))
516 V = Function::Create(FTy, GlobalValue::ExternalLinkage);
518 V = new GlobalVariable(ElTy, false, GlobalValue::ExternalLinkage, 0, "",
519 (Module*)0, false, PTy->getAddressSpace());
523 V = new Argument(Ty);
526 // Remember where this forward reference came from. FIXME, shouldn't we try
527 // to recycle these things??
528 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
531 if (inFunctionScope())
532 InsertValue(V, CurFun.LateResolveValues);
534 InsertValue(V, CurModule.LateResolveValues);
538 /// defineBBVal - This is a definition of a new basic block with the specified
539 /// identifier which must be the same as CurFun.NextValNum, if its numeric.
540 static BasicBlock *defineBBVal(const ValID &ID) {
541 assert(inFunctionScope() && "Can't get basic block at global scope!");
545 // First, see if this was forward referenced
547 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
548 if (BBI != CurFun.BBForwardRefs.end()) {
550 // The forward declaration could have been inserted anywhere in the
551 // function: insert it into the correct place now.
552 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
553 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
555 // We're about to erase the entry, save the key so we can clean it up.
556 ValID Tmp = BBI->first;
558 // Erase the forward ref from the map as its no longer "forward"
559 CurFun.BBForwardRefs.erase(ID);
561 // The key has been removed from the map but so we don't want to leave
562 // strdup'd memory around so destroy it too.
565 // If its a numbered definition, bump the number and set the BB value.
566 if (ID.Type == ValID::LocalID) {
567 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
571 // We haven't seen this BB before and its first mention is a definition.
572 // Just create it and return it.
573 std::string Name (ID.Type == ValID::LocalName ? ID.getName() : "");
574 BB = BasicBlock::Create(Name, CurFun.CurrentFunction);
575 if (ID.Type == ValID::LocalID) {
576 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
585 /// getBBVal - get an existing BB value or create a forward reference for it.
587 static BasicBlock *getBBVal(const ValID &ID) {
588 assert(inFunctionScope() && "Can't get basic block at global scope!");
592 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
593 if (BBI != CurFun.BBForwardRefs.end()) {
595 } if (ID.Type == ValID::LocalName) {
596 std::string Name = ID.getName();
597 Value *N = CurFun.CurrentFunction->getValueSymbolTable().lookup(Name);
599 if (N->getType()->getTypeID() == Type::LabelTyID)
600 BB = cast<BasicBlock>(N);
602 GenerateError("Reference to label '" + Name + "' is actually of type '"+
603 N->getType()->getDescription() + "'");
605 } else if (ID.Type == ValID::LocalID) {
606 if (ID.Num < CurFun.NextValNum && ID.Num < CurFun.Values.size()) {
607 if (CurFun.Values[ID.Num]->getType()->getTypeID() == Type::LabelTyID)
608 BB = cast<BasicBlock>(CurFun.Values[ID.Num]);
610 GenerateError("Reference to label '%" + utostr(ID.Num) +
611 "' is actually of type '"+
612 CurFun.Values[ID.Num]->getType()->getDescription() + "'");
615 GenerateError("Illegal label reference " + ID.getName());
619 // If its already been defined, return it now.
621 ID.destroy(); // Free strdup'd memory.
625 // Otherwise, this block has not been seen before, create it.
627 if (ID.Type == ValID::LocalName)
629 BB = BasicBlock::Create(Name, CurFun.CurrentFunction);
631 // Insert it in the forward refs map.
632 CurFun.BBForwardRefs[ID] = BB;
638 //===----------------------------------------------------------------------===//
639 // Code to handle forward references in instructions
640 //===----------------------------------------------------------------------===//
642 // This code handles the late binding needed with statements that reference
643 // values not defined yet... for example, a forward branch, or the PHI node for
646 // This keeps a table (CurFun.LateResolveValues) of all such forward references
647 // and back patchs after we are done.
650 // ResolveDefinitions - If we could not resolve some defs at parsing
651 // time (forward branches, phi functions for loops, etc...) resolve the
655 ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers) {
656 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
657 while (!LateResolvers.empty()) {
658 Value *V = LateResolvers.back();
659 LateResolvers.pop_back();
661 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
662 CurModule.PlaceHolderInfo.find(V);
663 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
665 ValID &DID = PHI->second.first;
667 Value *TheRealValue = getExistingVal(V->getType(), DID);
671 V->replaceAllUsesWith(TheRealValue);
673 CurModule.PlaceHolderInfo.erase(PHI);
674 } else if (FutureLateResolvers) {
675 // Functions have their unresolved items forwarded to the module late
677 InsertValue(V, *FutureLateResolvers);
679 if (DID.Type == ValID::LocalName || DID.Type == ValID::GlobalName) {
680 GenerateError("Reference to an invalid definition: '" +DID.getName()+
681 "' of type '" + V->getType()->getDescription() + "'",
685 GenerateError("Reference to an invalid definition: #" +
686 itostr(DID.Num) + " of type '" +
687 V->getType()->getDescription() + "'",
693 LateResolvers.clear();
696 // ResolveTypeTo - A brand new type was just declared. This means that (if
697 // name is not null) things referencing Name can be resolved. Otherwise, things
698 // refering to the number can be resolved. Do this now.
700 static void ResolveTypeTo(std::string *Name, const Type *ToTy) {
703 D = ValID::createLocalName(*Name);
705 D = ValID::createLocalID(CurModule.Types.size());
707 std::map<ValID, PATypeHolder>::iterator I =
708 CurModule.LateResolveTypes.find(D);
709 if (I != CurModule.LateResolveTypes.end()) {
710 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
712 CurModule.LateResolveTypes.erase(I);
717 // setValueName - Set the specified value to the name given. The name may be
718 // null potentially, in which case this is a noop. The string passed in is
719 // assumed to be a malloc'd string buffer, and is free'd by this function.
721 static void setValueName(Value *V, std::string *NameStr) {
722 if (!NameStr) return;
723 std::string Name(*NameStr); // Copy string
724 delete NameStr; // Free old string
726 if (V->getType() == Type::VoidTy) {
727 GenerateError("Can't assign name '" + Name+"' to value with void type");
731 assert(inFunctionScope() && "Must be in function scope!");
732 ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
733 if (ST.lookup(Name)) {
734 GenerateError("Redefinition of value '" + Name + "' of type '" +
735 V->getType()->getDescription() + "'");
743 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
744 /// this is a declaration, otherwise it is a definition.
745 static GlobalVariable *
746 ParseGlobalVariable(std::string *NameStr,
747 GlobalValue::LinkageTypes Linkage,
748 GlobalValue::VisibilityTypes Visibility,
749 bool isConstantGlobal, const Type *Ty,
750 Constant *Initializer, bool IsThreadLocal,
751 unsigned AddressSpace = 0) {
752 if (isa<FunctionType>(Ty)) {
753 GenerateError("Cannot declare global vars of function type");
756 if (Ty == Type::LabelTy) {
757 GenerateError("Cannot declare global vars of label type");
761 const PointerType *PTy = PointerType::get(Ty, AddressSpace);
765 Name = *NameStr; // Copy string
766 delete NameStr; // Free old string
769 // See if this global value was forward referenced. If so, recycle the
773 ID = ValID::createGlobalName(Name);
775 ID = ValID::createGlobalID(CurModule.Values.size());
778 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
779 // Move the global to the end of the list, from whereever it was
780 // previously inserted.
781 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
782 CurModule.CurrentModule->getGlobalList().remove(GV);
783 CurModule.CurrentModule->getGlobalList().push_back(GV);
784 GV->setInitializer(Initializer);
785 GV->setLinkage(Linkage);
786 GV->setVisibility(Visibility);
787 GV->setConstant(isConstantGlobal);
788 GV->setThreadLocal(IsThreadLocal);
789 InsertValue(GV, CurModule.Values);
796 // If this global has a name
798 // if the global we're parsing has an initializer (is a definition) and
799 // has external linkage.
800 if (Initializer && Linkage != GlobalValue::InternalLinkage)
801 // If there is already a global with external linkage with this name
802 if (CurModule.CurrentModule->getGlobalVariable(Name, false)) {
803 // If we allow this GVar to get created, it will be renamed in the
804 // symbol table because it conflicts with an existing GVar. We can't
805 // allow redefinition of GVars whose linking indicates that their name
806 // must stay the same. Issue the error.
807 GenerateError("Redefinition of global variable named '" + Name +
808 "' of type '" + Ty->getDescription() + "'");
813 // Otherwise there is no existing GV to use, create one now.
815 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
816 CurModule.CurrentModule, IsThreadLocal, AddressSpace);
817 GV->setVisibility(Visibility);
818 InsertValue(GV, CurModule.Values);
822 // setTypeName - Set the specified type to the name given. The name may be
823 // null potentially, in which case this is a noop. The string passed in is
824 // assumed to be a malloc'd string buffer, and is freed by this function.
826 // This function returns true if the type has already been defined, but is
827 // allowed to be redefined in the specified context. If the name is a new name
828 // for the type plane, it is inserted and false is returned.
829 static bool setTypeName(const Type *T, std::string *NameStr) {
830 assert(!inFunctionScope() && "Can't give types function-local names!");
831 if (NameStr == 0) return false;
833 std::string Name(*NameStr); // Copy string
834 delete NameStr; // Free old string
836 // We don't allow assigning names to void type
837 if (T == Type::VoidTy) {
838 GenerateError("Can't assign name '" + Name + "' to the void type");
842 // Set the type name, checking for conflicts as we do so.
843 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
845 if (AlreadyExists) { // Inserting a name that is already defined???
846 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
847 assert(Existing && "Conflict but no matching type?!");
849 // There is only one case where this is allowed: when we are refining an
850 // opaque type. In this case, Existing will be an opaque type.
851 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
852 // We ARE replacing an opaque type!
853 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
857 // Otherwise, this is an attempt to redefine a type. That's okay if
858 // the redefinition is identical to the original. This will be so if
859 // Existing and T point to the same Type object. In this one case we
860 // allow the equivalent redefinition.
861 if (Existing == T) return true; // Yes, it's equal.
863 // Any other kind of (non-equivalent) redefinition is an error.
864 GenerateError("Redefinition of type named '" + Name + "' of type '" +
865 T->getDescription() + "'");
871 //===----------------------------------------------------------------------===//
872 // Code for handling upreferences in type names...
875 // TypeContains - Returns true if Ty directly contains E in it.
877 static bool TypeContains(const Type *Ty, const Type *E) {
878 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
879 E) != Ty->subtype_end();
884 // NestingLevel - The number of nesting levels that need to be popped before
885 // this type is resolved.
886 unsigned NestingLevel;
888 // LastContainedTy - This is the type at the current binding level for the
889 // type. Every time we reduce the nesting level, this gets updated.
890 const Type *LastContainedTy;
892 // UpRefTy - This is the actual opaque type that the upreference is
896 UpRefRecord(unsigned NL, OpaqueType *URTy)
897 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
901 // UpRefs - A list of the outstanding upreferences that need to be resolved.
902 static std::vector<UpRefRecord> UpRefs;
904 /// HandleUpRefs - Every time we finish a new layer of types, this function is
905 /// called. It loops through the UpRefs vector, which is a list of the
906 /// currently active types. For each type, if the up reference is contained in
907 /// the newly completed type, we decrement the level count. When the level
908 /// count reaches zero, the upreferenced type is the type that is passed in:
909 /// thus we can complete the cycle.
911 static PATypeHolder HandleUpRefs(const Type *ty) {
912 // If Ty isn't abstract, or if there are no up-references in it, then there is
913 // nothing to resolve here.
914 if (!ty->isAbstract() || UpRefs.empty()) return ty;
917 UR_OUT("Type '" << Ty->getDescription() <<
918 "' newly formed. Resolving upreferences.\n" <<
919 UpRefs.size() << " upreferences active!\n");
921 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
922 // to zero), we resolve them all together before we resolve them to Ty. At
923 // the end of the loop, if there is anything to resolve to Ty, it will be in
925 OpaqueType *TypeToResolve = 0;
927 for (unsigned i = 0; i != UpRefs.size(); ++i) {
928 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
929 << UpRefs[i].second->getDescription() << ") = "
930 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
931 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
932 // Decrement level of upreference
933 unsigned Level = --UpRefs[i].NestingLevel;
934 UpRefs[i].LastContainedTy = Ty;
935 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
936 if (Level == 0) { // Upreference should be resolved!
937 if (!TypeToResolve) {
938 TypeToResolve = UpRefs[i].UpRefTy;
940 UR_OUT(" * Resolving upreference for "
941 << UpRefs[i].second->getDescription() << "\n";
942 std::string OldName = UpRefs[i].UpRefTy->getDescription());
943 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
944 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
945 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
947 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
948 --i; // Do not skip the next element...
954 UR_OUT(" * Resolving upreference for "
955 << UpRefs[i].second->getDescription() << "\n";
956 std::string OldName = TypeToResolve->getDescription());
957 TypeToResolve->refineAbstractTypeTo(Ty);
963 //===----------------------------------------------------------------------===//
964 // RunVMAsmParser - Define an interface to this parser
965 //===----------------------------------------------------------------------===//
967 static Module* RunParser(Module * M);
969 Module *llvm::RunVMAsmParser(llvm::MemoryBuffer *MB) {
971 Module *M = RunParser(new Module(LLLgetFilename()));
979 llvm::Module *ModuleVal;
980 llvm::Function *FunctionVal;
981 llvm::BasicBlock *BasicBlockVal;
982 llvm::TerminatorInst *TermInstVal;
983 llvm::Instruction *InstVal;
984 llvm::Constant *ConstVal;
986 const llvm::Type *PrimType;
987 std::list<llvm::PATypeHolder> *TypeList;
988 llvm::PATypeHolder *TypeVal;
989 llvm::Value *ValueVal;
990 std::vector<llvm::Value*> *ValueList;
991 std::vector<unsigned> *ConstantList;
992 llvm::ArgListType *ArgList;
993 llvm::TypeWithAttrs TypeWithAttrs;
994 llvm::TypeWithAttrsList *TypeWithAttrsList;
995 llvm::ParamList *ParamList;
997 // Represent the RHS of PHI node
998 std::list<std::pair<llvm::Value*,
999 llvm::BasicBlock*> > *PHIList;
1000 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
1001 std::vector<llvm::Constant*> *ConstVector;
1003 llvm::GlobalValue::LinkageTypes Linkage;
1004 llvm::GlobalValue::VisibilityTypes Visibility;
1005 llvm::Attributes Attributes;
1006 llvm::APInt *APIntVal;
1011 llvm::APFloat *FPVal;
1014 std::string *StrVal; // This memory must be deleted
1015 llvm::ValID ValIDVal;
1017 llvm::Instruction::BinaryOps BinaryOpVal;
1018 llvm::Instruction::TermOps TermOpVal;
1019 llvm::Instruction::MemoryOps MemOpVal;
1020 llvm::Instruction::CastOps CastOpVal;
1021 llvm::Instruction::OtherOps OtherOpVal;
1022 llvm::ICmpInst::Predicate IPredicate;
1023 llvm::FCmpInst::Predicate FPredicate;
1026 %type <ModuleVal> Module
1027 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1028 %type <BasicBlockVal> BasicBlock InstructionList
1029 %type <TermInstVal> BBTerminatorInst
1030 %type <InstVal> Inst InstVal MemoryInst
1031 %type <ConstVal> ConstVal ConstExpr AliaseeRef
1032 %type <ConstVector> ConstVector
1033 %type <ArgList> ArgList ArgListH
1034 %type <PHIList> PHIList
1035 %type <ParamList> ParamList // For call param lists & GEP indices
1036 %type <ValueList> IndexList // For GEP indices
1037 %type <ConstantList> ConstantIndexList // For insertvalue/extractvalue indices
1038 %type <TypeList> TypeListI
1039 %type <TypeWithAttrsList> ArgTypeList ArgTypeListI
1040 %type <TypeWithAttrs> ArgType
1041 %type <JumpTable> JumpTable
1042 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1043 %type <BoolVal> ThreadLocal // 'thread_local' or not
1044 %type <BoolVal> OptVolatile // 'volatile' or not
1045 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1046 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
1047 %type <Linkage> GVInternalLinkage GVExternalLinkage
1048 %type <Linkage> FunctionDefineLinkage FunctionDeclareLinkage
1049 %type <Linkage> AliasLinkage
1050 %type <Visibility> GVVisibilityStyle
1052 // ValueRef - Unresolved reference to a definition or BB
1053 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1054 %type <ValueVal> ResolvedVal // <type> <valref> pair
1055 %type <ValueList> ReturnedVal
1056 // Tokens and types for handling constant integer values
1058 // ESINT64VAL - A negative number within long long range
1059 %token <SInt64Val> ESINT64VAL
1061 // EUINT64VAL - A positive number within uns. long long range
1062 %token <UInt64Val> EUINT64VAL
1064 // ESAPINTVAL - A negative number with arbitrary precision
1065 %token <APIntVal> ESAPINTVAL
1067 // EUAPINTVAL - A positive number with arbitrary precision
1068 %token <APIntVal> EUAPINTVAL
1070 %token <UIntVal> LOCALVAL_ID GLOBALVAL_ID // %123 @123
1071 %token <FPVal> FPVAL // Float or Double constant
1073 // Built in types...
1074 %type <TypeVal> Types ResultTypes
1075 %type <PrimType> PrimType // Classifications
1076 %token <PrimType> VOID INTTYPE
1077 %token <PrimType> FLOAT DOUBLE X86_FP80 FP128 PPC_FP128 LABEL
1081 %token<StrVal> LOCALVAR GLOBALVAR LABELSTR
1082 %token<StrVal> STRINGCONSTANT ATSTRINGCONSTANT PCTSTRINGCONSTANT
1083 %type <StrVal> LocalName OptLocalName OptLocalAssign
1084 %type <StrVal> GlobalName OptGlobalAssign GlobalAssign
1085 %type <StrVal> OptSection SectionString OptGC
1087 %type <UIntVal> OptAlign OptCAlign OptAddrSpace
1089 %token ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1090 %token DECLARE DEFINE GLOBAL CONSTANT SECTION ALIAS VOLATILE THREAD_LOCAL
1091 %token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
1092 %token DLLIMPORT DLLEXPORT EXTERN_WEAK COMMON
1093 %token OPAQUE EXTERNAL TARGET TRIPLE ALIGN ADDRSPACE
1094 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1095 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1097 %type <UIntVal> OptCallingConv LocalNumber
1098 %type <Attributes> OptAttributes Attribute
1099 %type <Attributes> OptFuncAttrs FuncAttr
1100 %type <Attributes> OptRetAttrs RetAttr
1102 // Basic Block Terminating Operators
1103 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1106 %type <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
1107 %token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1108 %token <BinaryOpVal> SHL LSHR ASHR
1110 %token <OtherOpVal> ICMP FCMP VICMP VFCMP
1111 %type <IPredicate> IPredicates
1112 %type <FPredicate> FPredicates
1113 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1114 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1116 // Memory Instructions
1117 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1120 %type <CastOpVal> CastOps
1121 %token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1122 %token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1125 %token <OtherOpVal> PHI_TOK SELECT VAARG
1126 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1127 %token <OtherOpVal> GETRESULT
1128 %token <OtherOpVal> EXTRACTVALUE INSERTVALUE
1130 // Function Attributes
1131 %token SIGNEXT ZEROEXT NORETURN INREG SRET NOUNWIND NOALIAS BYVAL NEST
1132 %token READNONE READONLY GC OPTSIZE NOINLINE ALWAYSINLINE
1134 // Visibility Styles
1135 %token DEFAULT HIDDEN PROTECTED
1141 // Operations that are notably excluded from this list include:
1142 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1144 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1145 LogicalOps : SHL | LSHR | ASHR | AND | OR | XOR;
1146 CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1147 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1150 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1151 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1152 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1153 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1154 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1158 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1159 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1160 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1161 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1162 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1163 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1164 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1165 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1166 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1169 LocalName : LOCALVAR | STRINGCONSTANT | PCTSTRINGCONSTANT ;
1170 OptLocalName : LocalName | /*empty*/ { $$ = 0; };
1172 OptAddrSpace : ADDRSPACE '(' EUINT64VAL ')' { $$=$3; }
1173 | /*empty*/ { $$=0; };
1175 /// OptLocalAssign - Value producing statements have an optional assignment
1177 OptLocalAssign : LocalName '=' {
1186 LocalNumber : LOCALVAL_ID '=' {
1192 GlobalName : GLOBALVAR | ATSTRINGCONSTANT ;
1194 OptGlobalAssign : GlobalAssign
1200 GlobalAssign : GlobalName '=' {
1206 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1207 | WEAK { $$ = GlobalValue::WeakLinkage; }
1208 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1209 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1210 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1211 | COMMON { $$ = GlobalValue::CommonLinkage; }
1215 : DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1216 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1217 | EXTERNAL { $$ = GlobalValue::ExternalLinkage; }
1221 : /*empty*/ { $$ = GlobalValue::DefaultVisibility; }
1222 | DEFAULT { $$ = GlobalValue::DefaultVisibility; }
1223 | HIDDEN { $$ = GlobalValue::HiddenVisibility; }
1224 | PROTECTED { $$ = GlobalValue::ProtectedVisibility; }
1227 FunctionDeclareLinkage
1228 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1229 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1230 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1233 FunctionDefineLinkage
1234 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1235 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1236 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1237 | WEAK { $$ = GlobalValue::WeakLinkage; }
1238 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1242 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1243 | WEAK { $$ = GlobalValue::WeakLinkage; }
1244 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1247 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1248 CCC_TOK { $$ = CallingConv::C; } |
1249 FASTCC_TOK { $$ = CallingConv::Fast; } |
1250 COLDCC_TOK { $$ = CallingConv::Cold; } |
1251 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1252 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1254 if ((unsigned)$2 != $2)
1255 GEN_ERROR("Calling conv too large");
1260 Attribute : ZEROEXT { $$ = Attribute::ZExt; }
1261 | ZEXT { $$ = Attribute::ZExt; }
1262 | SIGNEXT { $$ = Attribute::SExt; }
1263 | SEXT { $$ = Attribute::SExt; }
1264 | INREG { $$ = Attribute::InReg; }
1265 | SRET { $$ = Attribute::StructRet; }
1266 | NOALIAS { $$ = Attribute::NoAlias; }
1267 | BYVAL { $$ = Attribute::ByVal; }
1268 | NEST { $$ = Attribute::Nest; }
1269 | ALIGN EUINT64VAL { $$ =
1270 Attribute::constructAlignmentFromInt($2); }
1273 OptAttributes : /* empty */ { $$ = Attribute::None; }
1274 | OptAttributes Attribute {
1279 RetAttr : INREG { $$ = Attribute::InReg; }
1280 | ZEROEXT { $$ = Attribute::ZExt; }
1281 | SIGNEXT { $$ = Attribute::SExt; }
1284 OptRetAttrs : /* empty */ { $$ = Attribute::None; }
1285 | OptRetAttrs RetAttr {
1291 FuncAttr : NORETURN { $$ = Attribute::NoReturn; }
1292 | NOUNWIND { $$ = Attribute::NoUnwind; }
1293 | INREG { $$ = Attribute::InReg; }
1294 | ZEROEXT { $$ = Attribute::ZExt; }
1295 | SIGNEXT { $$ = Attribute::SExt; }
1296 | READNONE { $$ = Attribute::ReadNone; }
1297 | READONLY { $$ = Attribute::ReadOnly; }
1298 | NOINLINE { $$ = Attribute::NoInline; }
1299 | ALWAYSINLINE { $$ = Attribute::AlwaysInline; }
1300 | OPTSIZE { $$ = Attribute::OptimizeForSize; }
1303 OptFuncAttrs : /* empty */ { $$ = Attribute::None; }
1304 | OptFuncAttrs FuncAttr {
1310 OptGC : /* empty */ { $$ = 0; }
1311 | GC STRINGCONSTANT {
1316 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1317 // a comma before it.
1318 OptAlign : /*empty*/ { $$ = 0; } |
1321 if ($$ != 0 && !isPowerOf2_32($$))
1322 GEN_ERROR("Alignment must be a power of two");
1325 OptCAlign : /*empty*/ { $$ = 0; } |
1326 ',' ALIGN EUINT64VAL {
1328 if ($$ != 0 && !isPowerOf2_32($$))
1329 GEN_ERROR("Alignment must be a power of two");
1335 SectionString : SECTION STRINGCONSTANT {
1336 for (unsigned i = 0, e = $2->length(); i != e; ++i)
1337 if ((*$2)[i] == '"' || (*$2)[i] == '\\')
1338 GEN_ERROR("Invalid character in section name");
1343 OptSection : /*empty*/ { $$ = 0; } |
1344 SectionString { $$ = $1; };
1346 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1347 // is set to be the global we are processing.
1349 GlobalVarAttributes : /* empty */ {} |
1350 ',' GlobalVarAttribute GlobalVarAttributes {};
1351 GlobalVarAttribute : SectionString {
1352 CurGV->setSection(*$1);
1356 | ALIGN EUINT64VAL {
1357 if ($2 != 0 && !isPowerOf2_32($2))
1358 GEN_ERROR("Alignment must be a power of two");
1359 CurGV->setAlignment($2);
1363 //===----------------------------------------------------------------------===//
1364 // Types includes all predefined types... except void, because it can only be
1365 // used in specific contexts (function returning void for example).
1367 // Derived types are added later...
1369 PrimType : INTTYPE | FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80 | LABEL ;
1373 $$ = new PATypeHolder(OpaqueType::get());
1377 $$ = new PATypeHolder($1);
1380 | Types OptAddrSpace '*' { // Pointer type?
1381 if (*$1 == Type::LabelTy)
1382 GEN_ERROR("Cannot form a pointer to a basic block");
1383 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1, $2)));
1387 | SymbolicValueRef { // Named types are also simple types...
1388 const Type* tmp = getTypeVal($1);
1390 $$ = new PATypeHolder(tmp);
1392 | '\\' EUINT64VAL { // Type UpReference
1393 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range");
1394 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1395 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1396 $$ = new PATypeHolder(OT);
1397 UR_OUT("New Upreference!\n");
1400 | Types '(' ArgTypeListI ')' OptFuncAttrs {
1401 // Allow but ignore attributes on function types; this permits auto-upgrade.
1402 // FIXME: remove in LLVM 3.0.
1403 const Type *RetTy = *$1;
1404 if (!FunctionType::isValidReturnType(RetTy))
1405 GEN_ERROR("Invalid result type for LLVM function");
1407 std::vector<const Type*> Params;
1408 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1409 for (; I != E; ++I ) {
1410 const Type *Ty = I->Ty->get();
1411 Params.push_back(Ty);
1414 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1415 if (isVarArg) Params.pop_back();
1417 for (unsigned i = 0; i != Params.size(); ++i)
1418 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1419 GEN_ERROR("Function arguments must be value types!");
1423 FunctionType *FT = FunctionType::get(RetTy, Params, isVarArg);
1424 delete $1; // Delete the return type handle
1425 $$ = new PATypeHolder(HandleUpRefs(FT));
1427 // Delete the argument list
1428 for (I = $3->begin() ; I != E; ++I ) {
1435 | VOID '(' ArgTypeListI ')' OptFuncAttrs {
1436 // Allow but ignore attributes on function types; this permits auto-upgrade.
1437 // FIXME: remove in LLVM 3.0.
1438 std::vector<const Type*> Params;
1439 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1440 for ( ; I != E; ++I ) {
1441 const Type* Ty = I->Ty->get();
1442 Params.push_back(Ty);
1445 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1446 if (isVarArg) Params.pop_back();
1448 for (unsigned i = 0; i != Params.size(); ++i)
1449 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1450 GEN_ERROR("Function arguments must be value types!");
1454 FunctionType *FT = FunctionType::get($1, Params, isVarArg);
1455 $$ = new PATypeHolder(HandleUpRefs(FT));
1457 // Delete the argument list
1458 for (I = $3->begin() ; I != E; ++I ) {
1466 | '[' EUINT64VAL 'x' Types ']' { // Sized array type?
1467 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, $2)));
1471 | '<' EUINT64VAL 'x' Types '>' { // Vector type?
1472 const llvm::Type* ElemTy = $4->get();
1473 if ((unsigned)$2 != $2)
1474 GEN_ERROR("Unsigned result not equal to signed result");
1475 if (!ElemTy->isFloatingPoint() && !ElemTy->isInteger())
1476 GEN_ERROR("Element type of a VectorType must be primitive");
1477 $$ = new PATypeHolder(HandleUpRefs(VectorType::get(*$4, (unsigned)$2)));
1481 | '{' TypeListI '}' { // Structure type?
1482 std::vector<const Type*> Elements;
1483 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1484 E = $2->end(); I != E; ++I)
1485 Elements.push_back(*I);
1487 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1491 | '{' '}' { // Empty structure type?
1492 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1495 | '<' '{' TypeListI '}' '>' {
1496 std::vector<const Type*> Elements;
1497 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1498 E = $3->end(); I != E; ++I)
1499 Elements.push_back(*I);
1501 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1505 | '<' '{' '}' '>' { // Empty structure type?
1506 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1512 : Types OptAttributes {
1513 // Allow but ignore attributes on function types; this permits auto-upgrade.
1514 // FIXME: remove in LLVM 3.0.
1516 $$.Attrs = Attribute::None;
1522 if (!UpRefs.empty())
1523 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1524 if (!(*$1)->isFirstClassType() && !isa<StructType>($1->get()))
1525 GEN_ERROR("LLVM functions cannot return aggregate types");
1529 $$ = new PATypeHolder(Type::VoidTy);
1533 ArgTypeList : ArgType {
1534 $$ = new TypeWithAttrsList();
1538 | ArgTypeList ',' ArgType {
1539 ($$=$1)->push_back($3);
1546 | ArgTypeList ',' DOTDOTDOT {
1548 TypeWithAttrs TWA; TWA.Attrs = Attribute::None;
1549 TWA.Ty = new PATypeHolder(Type::VoidTy);
1554 $$ = new TypeWithAttrsList;
1555 TypeWithAttrs TWA; TWA.Attrs = Attribute::None;
1556 TWA.Ty = new PATypeHolder(Type::VoidTy);
1561 $$ = new TypeWithAttrsList();
1565 // TypeList - Used for struct declarations and as a basis for function type
1566 // declaration type lists
1569 $$ = new std::list<PATypeHolder>();
1574 | TypeListI ',' Types {
1575 ($$=$1)->push_back(*$3);
1580 // ConstVal - The various declarations that go into the constant pool. This
1581 // production is used ONLY to represent constants that show up AFTER a 'const',
1582 // 'constant' or 'global' token at global scope. Constants that can be inlined
1583 // into other expressions (such as integers and constexprs) are handled by the
1584 // ResolvedVal, ValueRef and ConstValueRef productions.
1586 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1587 if (!UpRefs.empty())
1588 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1589 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1591 GEN_ERROR("Cannot make array constant with type: '" +
1592 (*$1)->getDescription() + "'");
1593 const Type *ETy = ATy->getElementType();
1594 uint64_t NumElements = ATy->getNumElements();
1596 // Verify that we have the correct size...
1597 if (NumElements != uint64_t(-1) && NumElements != $3->size())
1598 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1599 utostr($3->size()) + " arguments, but has size of " +
1600 utostr(NumElements) + "");
1602 // Verify all elements are correct type!
1603 for (unsigned i = 0; i < $3->size(); i++) {
1604 if (ETy != (*$3)[i]->getType())
1605 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1606 ETy->getDescription() +"' as required!\nIt is of type '"+
1607 (*$3)[i]->getType()->getDescription() + "'.");
1610 $$ = ConstantArray::get(ATy, *$3);
1611 delete $1; delete $3;
1615 if (!UpRefs.empty())
1616 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1617 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1619 GEN_ERROR("Cannot make array constant with type: '" +
1620 (*$1)->getDescription() + "'");
1622 uint64_t NumElements = ATy->getNumElements();
1623 if (NumElements != uint64_t(-1) && NumElements != 0)
1624 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1625 " arguments, but has size of " + utostr(NumElements) +"");
1626 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1630 | Types 'c' STRINGCONSTANT {
1631 if (!UpRefs.empty())
1632 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1633 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1635 GEN_ERROR("Cannot make array constant with type: '" +
1636 (*$1)->getDescription() + "'");
1638 uint64_t NumElements = ATy->getNumElements();
1639 const Type *ETy = ATy->getElementType();
1640 if (NumElements != uint64_t(-1) && NumElements != $3->length())
1641 GEN_ERROR("Can't build string constant of size " +
1642 utostr($3->length()) +
1643 " when array has size " + utostr(NumElements) + "");
1644 std::vector<Constant*> Vals;
1645 if (ETy == Type::Int8Ty) {
1646 for (uint64_t i = 0; i < $3->length(); ++i)
1647 Vals.push_back(ConstantInt::get(ETy, (*$3)[i]));
1650 GEN_ERROR("Cannot build string arrays of non byte sized elements");
1653 $$ = ConstantArray::get(ATy, Vals);
1657 | Types '<' ConstVector '>' { // Nonempty unsized arr
1658 if (!UpRefs.empty())
1659 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1660 const VectorType *PTy = dyn_cast<VectorType>($1->get());
1662 GEN_ERROR("Cannot make packed constant with type: '" +
1663 (*$1)->getDescription() + "'");
1664 const Type *ETy = PTy->getElementType();
1665 unsigned NumElements = PTy->getNumElements();
1667 // Verify that we have the correct size...
1668 if (NumElements != unsigned(-1) && NumElements != (unsigned)$3->size())
1669 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1670 utostr($3->size()) + " arguments, but has size of " +
1671 utostr(NumElements) + "");
1673 // Verify all elements are correct type!
1674 for (unsigned i = 0; i < $3->size(); i++) {
1675 if (ETy != (*$3)[i]->getType())
1676 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1677 ETy->getDescription() +"' as required!\nIt is of type '"+
1678 (*$3)[i]->getType()->getDescription() + "'.");
1681 $$ = ConstantVector::get(PTy, *$3);
1682 delete $1; delete $3;
1685 | Types '{' ConstVector '}' {
1686 const StructType *STy = dyn_cast<StructType>($1->get());
1688 GEN_ERROR("Cannot make struct constant with type: '" +
1689 (*$1)->getDescription() + "'");
1691 if ($3->size() != STy->getNumContainedTypes())
1692 GEN_ERROR("Illegal number of initializers for structure type");
1694 // Check to ensure that constants are compatible with the type initializer!
1695 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1696 if ((*$3)[i]->getType() != STy->getElementType(i))
1697 GEN_ERROR("Expected type '" +
1698 STy->getElementType(i)->getDescription() +
1699 "' for element #" + utostr(i) +
1700 " of structure initializer");
1702 // Check to ensure that Type is not packed
1703 if (STy->isPacked())
1704 GEN_ERROR("Unpacked Initializer to vector type '" +
1705 STy->getDescription() + "'");
1707 $$ = ConstantStruct::get(STy, *$3);
1708 delete $1; delete $3;
1712 if (!UpRefs.empty())
1713 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1714 const StructType *STy = dyn_cast<StructType>($1->get());
1716 GEN_ERROR("Cannot make struct constant with type: '" +
1717 (*$1)->getDescription() + "'");
1719 if (STy->getNumContainedTypes() != 0)
1720 GEN_ERROR("Illegal number of initializers for structure type");
1722 // Check to ensure that Type is not packed
1723 if (STy->isPacked())
1724 GEN_ERROR("Unpacked Initializer to vector type '" +
1725 STy->getDescription() + "'");
1727 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1731 | Types '<' '{' ConstVector '}' '>' {
1732 const StructType *STy = dyn_cast<StructType>($1->get());
1734 GEN_ERROR("Cannot make struct constant with type: '" +
1735 (*$1)->getDescription() + "'");
1737 if ($4->size() != STy->getNumContainedTypes())
1738 GEN_ERROR("Illegal number of initializers for structure type");
1740 // Check to ensure that constants are compatible with the type initializer!
1741 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1742 if ((*$4)[i]->getType() != STy->getElementType(i))
1743 GEN_ERROR("Expected type '" +
1744 STy->getElementType(i)->getDescription() +
1745 "' for element #" + utostr(i) +
1746 " of structure initializer");
1748 // Check to ensure that Type is packed
1749 if (!STy->isPacked())
1750 GEN_ERROR("Vector initializer to non-vector type '" +
1751 STy->getDescription() + "'");
1753 $$ = ConstantStruct::get(STy, *$4);
1754 delete $1; delete $4;
1757 | Types '<' '{' '}' '>' {
1758 if (!UpRefs.empty())
1759 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1760 const StructType *STy = dyn_cast<StructType>($1->get());
1762 GEN_ERROR("Cannot make struct constant with type: '" +
1763 (*$1)->getDescription() + "'");
1765 if (STy->getNumContainedTypes() != 0)
1766 GEN_ERROR("Illegal number of initializers for structure type");
1768 // Check to ensure that Type is packed
1769 if (!STy->isPacked())
1770 GEN_ERROR("Vector initializer to non-vector type '" +
1771 STy->getDescription() + "'");
1773 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1778 if (!UpRefs.empty())
1779 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1780 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1782 GEN_ERROR("Cannot make null pointer constant with type: '" +
1783 (*$1)->getDescription() + "'");
1785 $$ = ConstantPointerNull::get(PTy);
1790 if (!UpRefs.empty())
1791 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1792 $$ = UndefValue::get($1->get());
1796 | Types SymbolicValueRef {
1797 if (!UpRefs.empty())
1798 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1799 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1801 GEN_ERROR("Global const reference must be a pointer type " + (*$1)->getDescription());
1803 // ConstExprs can exist in the body of a function, thus creating
1804 // GlobalValues whenever they refer to a variable. Because we are in
1805 // the context of a function, getExistingVal will search the functions
1806 // symbol table instead of the module symbol table for the global symbol,
1807 // which throws things all off. To get around this, we just tell
1808 // getExistingVal that we are at global scope here.
1810 Function *SavedCurFn = CurFun.CurrentFunction;
1811 CurFun.CurrentFunction = 0;
1813 Value *V = getExistingVal(Ty, $2);
1816 CurFun.CurrentFunction = SavedCurFn;
1818 // If this is an initializer for a constant pointer, which is referencing a
1819 // (currently) undefined variable, create a stub now that shall be replaced
1820 // in the future with the right type of variable.
1823 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1824 const PointerType *PT = cast<PointerType>(Ty);
1826 // First check to see if the forward references value is already created!
1827 PerModuleInfo::GlobalRefsType::iterator I =
1828 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1830 if (I != CurModule.GlobalRefs.end()) {
1831 V = I->second; // Placeholder already exists, use it...
1835 if ($2.Type == ValID::GlobalName)
1836 Name = $2.getName();
1837 else if ($2.Type != ValID::GlobalID)
1838 GEN_ERROR("Invalid reference to global");
1840 // Create the forward referenced global.
1842 if (const FunctionType *FTy =
1843 dyn_cast<FunctionType>(PT->getElementType())) {
1844 GV = Function::Create(FTy, GlobalValue::ExternalWeakLinkage, Name,
1845 CurModule.CurrentModule);
1847 GV = new GlobalVariable(PT->getElementType(), false,
1848 GlobalValue::ExternalWeakLinkage, 0,
1849 Name, CurModule.CurrentModule);
1852 // Keep track of the fact that we have a forward ref to recycle it
1853 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1858 $$ = cast<GlobalValue>(V);
1859 delete $1; // Free the type handle
1863 if (!UpRefs.empty())
1864 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1865 if ($1->get() != $2->getType())
1866 GEN_ERROR("Mismatched types for constant expression: " +
1867 (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1872 | Types ZEROINITIALIZER {
1873 if (!UpRefs.empty())
1874 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1875 const Type *Ty = $1->get();
1876 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1877 GEN_ERROR("Cannot create a null initialized value of this type");
1878 $$ = Constant::getNullValue(Ty);
1882 | Types ESINT64VAL { // integral constants
1883 if (IntegerType *IT = dyn_cast<IntegerType>($1->get())) {
1884 if (!ConstantInt::isValueValidForType(IT, $2))
1885 GEN_ERROR("Constant value doesn't fit in type");
1886 $$ = ConstantInt::get(IT, $2, true);
1888 GEN_ERROR("integer constant must have integer type");
1893 | Types ESAPINTVAL { // arbitrary precision integer constants
1894 if (IntegerType *IT = dyn_cast<IntegerType>($1->get())) {
1895 if ($2->getBitWidth() > IT->getBitWidth())
1896 GEN_ERROR("Constant value does not fit in type");
1897 $2->sextOrTrunc(IT->getBitWidth());
1898 $$ = ConstantInt::get(*$2);
1900 GEN_ERROR("integer constant must have integer type");
1906 | Types EUINT64VAL { // integral constants
1907 if (IntegerType *IT = dyn_cast<IntegerType>($1->get())) {
1908 if (!ConstantInt::isValueValidForType(IT, $2))
1909 GEN_ERROR("Constant value doesn't fit in type");
1910 $$ = ConstantInt::get(IT, $2, false);
1912 GEN_ERROR("integer constant must have integer type");
1917 | Types EUAPINTVAL { // arbitrary precision integer constants
1918 if (IntegerType *IT = dyn_cast<IntegerType>($1->get())) {
1919 if ($2->getBitWidth() > IT->getBitWidth())
1920 GEN_ERROR("Constant value does not fit in type");
1921 $2->zextOrTrunc(IT->getBitWidth());
1922 $$ = ConstantInt::get(*$2);
1924 GEN_ERROR("integer constant must have integer type");
1931 | Types TRUETOK { // Boolean constants
1932 if ($1->get() != Type::Int1Ty)
1933 GEN_ERROR("Constant true must have type i1");
1934 $$ = ConstantInt::getTrue();
1938 | Types FALSETOK { // Boolean constants
1939 if ($1->get() != Type::Int1Ty)
1940 GEN_ERROR("Constant false must have type i1");
1941 $$ = ConstantInt::getFalse();
1945 | Types FPVAL { // Floating point constants
1946 if (!ConstantFP::isValueValidForType($1->get(), *$2))
1947 GEN_ERROR("Floating point constant invalid for type");
1949 // Lexer has no type info, so builds all float and double FP constants
1950 // as double. Fix this here. Long double is done right.
1951 if (&$2->getSemantics()==&APFloat::IEEEdouble && $1->get()==Type::FloatTy) {
1953 $2->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
1956 $$ = ConstantFP::get(*$2);
1963 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1964 if (!UpRefs.empty())
1965 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1967 const Type *DestTy = $5->get();
1968 if (!CastInst::castIsValid($1, $3, DestTy))
1969 GEN_ERROR("invalid cast opcode for cast from '" +
1970 Val->getType()->getDescription() + "' to '" +
1971 DestTy->getDescription() + "'");
1972 $$ = ConstantExpr::getCast($1, $3, DestTy);
1975 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1976 if (!isa<PointerType>($3->getType()))
1977 GEN_ERROR("GetElementPtr requires a pointer operand");
1980 GetElementPtrInst::getIndexedType($3->getType(), $4->begin(), $4->end());
1982 GEN_ERROR("Index list invalid for constant getelementptr");
1984 SmallVector<Constant*, 8> IdxVec;
1985 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1986 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1987 IdxVec.push_back(C);
1989 GEN_ERROR("Indices to constant getelementptr must be constants");
1993 $$ = ConstantExpr::getGetElementPtr($3, &IdxVec[0], IdxVec.size());
1996 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1997 if ($3->getType() != Type::Int1Ty)
1998 GEN_ERROR("Select condition must be of boolean type");
1999 if ($5->getType() != $7->getType())
2000 GEN_ERROR("Select operand types must match");
2001 $$ = ConstantExpr::getSelect($3, $5, $7);
2004 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
2005 if ($3->getType() != $5->getType())
2006 GEN_ERROR("Binary operator types must match");
2008 $$ = ConstantExpr::get($1, $3, $5);
2010 | LogicalOps '(' ConstVal ',' ConstVal ')' {
2011 if ($3->getType() != $5->getType())
2012 GEN_ERROR("Logical operator types must match");
2013 if (!$3->getType()->isInteger()) {
2014 if (!isa<VectorType>($3->getType()) ||
2015 !cast<VectorType>($3->getType())->getElementType()->isInteger())
2016 GEN_ERROR("Logical operator requires integral operands");
2018 $$ = ConstantExpr::get($1, $3, $5);
2021 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
2022 if ($4->getType() != $6->getType())
2023 GEN_ERROR("icmp operand types must match");
2024 $$ = ConstantExpr::getICmp($2, $4, $6);
2026 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
2027 if ($4->getType() != $6->getType())
2028 GEN_ERROR("fcmp operand types must match");
2029 $$ = ConstantExpr::getFCmp($2, $4, $6);
2031 | VICMP IPredicates '(' ConstVal ',' ConstVal ')' {
2032 if ($4->getType() != $6->getType())
2033 GEN_ERROR("vicmp operand types must match");
2034 $$ = ConstantExpr::getVICmp($2, $4, $6);
2036 | VFCMP FPredicates '(' ConstVal ',' ConstVal ')' {
2037 if ($4->getType() != $6->getType())
2038 GEN_ERROR("vfcmp operand types must match");
2039 $$ = ConstantExpr::getVFCmp($2, $4, $6);
2041 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
2042 if (!ExtractElementInst::isValidOperands($3, $5))
2043 GEN_ERROR("Invalid extractelement operands");
2044 $$ = ConstantExpr::getExtractElement($3, $5);
2047 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2048 if (!InsertElementInst::isValidOperands($3, $5, $7))
2049 GEN_ERROR("Invalid insertelement operands");
2050 $$ = ConstantExpr::getInsertElement($3, $5, $7);
2053 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2054 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
2055 GEN_ERROR("Invalid shufflevector operands");
2056 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
2059 | EXTRACTVALUE '(' ConstVal ConstantIndexList ')' {
2060 if (!isa<StructType>($3->getType()) && !isa<ArrayType>($3->getType()))
2061 GEN_ERROR("ExtractValue requires an aggregate operand");
2063 $$ = ConstantExpr::getExtractValue($3, &(*$4)[0], $4->size());
2067 | INSERTVALUE '(' ConstVal ',' ConstVal ConstantIndexList ')' {
2068 if (!isa<StructType>($3->getType()) && !isa<ArrayType>($3->getType()))
2069 GEN_ERROR("InsertValue requires an aggregate operand");
2071 $$ = ConstantExpr::getInsertValue($3, $5, &(*$6)[0], $6->size());
2077 // ConstVector - A list of comma separated constants.
2078 ConstVector : ConstVector ',' ConstVal {
2079 ($$ = $1)->push_back($3);
2083 $$ = new std::vector<Constant*>();
2089 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
2090 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
2093 ThreadLocal : THREAD_LOCAL { $$ = true; } | { $$ = false; };
2095 // AliaseeRef - Match either GlobalValue or bitcast to GlobalValue.
2096 AliaseeRef : ResultTypes SymbolicValueRef {
2097 const Type* VTy = $1->get();
2098 Value *V = getVal(VTy, $2);
2100 GlobalValue* Aliasee = dyn_cast<GlobalValue>(V);
2102 GEN_ERROR("Aliases can be created only to global values");
2108 | BITCAST '(' AliaseeRef TO Types ')' {
2110 const Type *DestTy = $5->get();
2111 if (!CastInst::castIsValid($1, $3, DestTy))
2112 GEN_ERROR("invalid cast opcode for cast from '" +
2113 Val->getType()->getDescription() + "' to '" +
2114 DestTy->getDescription() + "'");
2116 $$ = ConstantExpr::getCast($1, $3, DestTy);
2121 //===----------------------------------------------------------------------===//
2122 // Rules to match Modules
2123 //===----------------------------------------------------------------------===//
2125 // Module rule: Capture the result of parsing the whole file into a result
2130 $$ = ParserResult = CurModule.CurrentModule;
2131 CurModule.ModuleDone();
2135 $$ = ParserResult = CurModule.CurrentModule;
2136 CurModule.ModuleDone();
2143 | DefinitionList Definition
2147 : DEFINE { CurFun.isDeclare = false; } Function {
2148 CurFun.FunctionDone();
2151 | DECLARE { CurFun.isDeclare = true; } FunctionProto {
2154 | MODULE ASM_TOK AsmBlock {
2157 | OptLocalAssign TYPE Types {
2158 if (!UpRefs.empty())
2159 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2160 // Eagerly resolve types. This is not an optimization, this is a
2161 // requirement that is due to the fact that we could have this:
2163 // %list = type { %list * }
2164 // %list = type { %list * } ; repeated type decl
2166 // If types are not resolved eagerly, then the two types will not be
2167 // determined to be the same type!
2169 ResolveTypeTo($1, *$3);
2171 if (!setTypeName(*$3, $1) && !$1) {
2173 // If this is a named type that is not a redefinition, add it to the slot
2175 CurModule.Types.push_back(*$3);
2181 | OptLocalAssign TYPE VOID {
2182 ResolveTypeTo($1, $3);
2184 if (!setTypeName($3, $1) && !$1) {
2186 // If this is a named type that is not a redefinition, add it to the slot
2188 CurModule.Types.push_back($3);
2192 | OptGlobalAssign GVVisibilityStyle ThreadLocal GlobalType ConstVal
2194 /* "Externally Visible" Linkage */
2196 GEN_ERROR("Global value initializer is not a constant");
2197 CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
2198 $2, $4, $5->getType(), $5, $3, $6);
2200 } GlobalVarAttributes {
2203 | OptGlobalAssign GVInternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2204 ConstVal OptAddrSpace {
2206 GEN_ERROR("Global value initializer is not a constant");
2207 CurGV = ParseGlobalVariable($1, $2, $3, $5, $6->getType(), $6, $4, $7);
2209 } GlobalVarAttributes {
2212 | OptGlobalAssign GVExternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2213 Types OptAddrSpace {
2214 if (!UpRefs.empty())
2215 GEN_ERROR("Invalid upreference in type: " + (*$6)->getDescription());
2216 CurGV = ParseGlobalVariable($1, $2, $3, $5, *$6, 0, $4, $7);
2219 } GlobalVarAttributes {
2223 | OptGlobalAssign GVVisibilityStyle ALIAS AliasLinkage AliaseeRef {
2230 GEN_ERROR("Alias name cannot be empty");
2232 Constant* Aliasee = $5;
2234 GEN_ERROR(std::string("Invalid aliasee for alias: ") + Name);
2236 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(), $4, Name, Aliasee,
2237 CurModule.CurrentModule);
2238 GA->setVisibility($2);
2239 InsertValue(GA, CurModule.Values);
2242 // If there was a forward reference of this alias, resolve it now.
2246 ID = ValID::createGlobalName(Name);
2248 ID = ValID::createGlobalID(CurModule.Values.size()-1);
2250 if (GlobalValue *FWGV =
2251 CurModule.GetForwardRefForGlobal(GA->getType(), ID)) {
2252 // Replace uses of the fwdref with the actual alias.
2253 FWGV->replaceAllUsesWith(GA);
2254 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(FWGV))
2255 GV->eraseFromParent();
2257 cast<Function>(FWGV)->eraseFromParent();
2263 | TARGET TargetDefinition {
2266 | DEPLIBS '=' LibrariesDefinition {
2272 AsmBlock : STRINGCONSTANT {
2273 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2274 if (AsmSoFar.empty())
2275 CurModule.CurrentModule->setModuleInlineAsm(*$1);
2277 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+*$1);
2282 TargetDefinition : TRIPLE '=' STRINGCONSTANT {
2283 CurModule.CurrentModule->setTargetTriple(*$3);
2286 | DATALAYOUT '=' STRINGCONSTANT {
2287 CurModule.CurrentModule->setDataLayout(*$3);
2291 LibrariesDefinition : '[' LibList ']';
2293 LibList : LibList ',' STRINGCONSTANT {
2294 CurModule.CurrentModule->addLibrary(*$3);
2299 CurModule.CurrentModule->addLibrary(*$1);
2303 | /* empty: end of list */ {
2308 //===----------------------------------------------------------------------===//
2309 // Rules to match Function Headers
2310 //===----------------------------------------------------------------------===//
2312 ArgListH : ArgListH ',' Types OptAttributes OptLocalName {
2313 if (!UpRefs.empty())
2314 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2315 if (!(*$3)->isFirstClassType())
2316 GEN_ERROR("Argument types must be first-class");
2317 ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
2322 | Types OptAttributes OptLocalName {
2323 if (!UpRefs.empty())
2324 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2325 if (!(*$1)->isFirstClassType())
2326 GEN_ERROR("Argument types must be first-class");
2327 ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2328 $$ = new ArgListType;
2333 ArgList : ArgListH {
2337 | ArgListH ',' DOTDOTDOT {
2339 struct ArgListEntry E;
2340 E.Ty = new PATypeHolder(Type::VoidTy);
2342 E.Attrs = Attribute::None;
2347 $$ = new ArgListType;
2348 struct ArgListEntry E;
2349 E.Ty = new PATypeHolder(Type::VoidTy);
2351 E.Attrs = Attribute::None;
2360 FunctionHeaderH : OptCallingConv OptRetAttrs ResultTypes GlobalName '(' ArgList ')'
2361 OptFuncAttrs OptSection OptAlign OptGC {
2362 std::string FunctionName(*$4);
2363 delete $4; // Free strdup'd memory!
2365 // Check the function result for abstractness if this is a define. We should
2366 // have no abstract types at this point
2367 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($3))
2368 GEN_ERROR("Reference to abstract result: "+ $3->get()->getDescription());
2370 if (!FunctionType::isValidReturnType(*$3))
2371 GEN_ERROR("Invalid result type for LLVM function");
2373 std::vector<const Type*> ParamTypeList;
2374 SmallVector<AttributeWithIndex, 8> Attrs;
2375 //FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2377 Attributes RetAttrs = $2;
2378 if ($8 != Attribute::None) {
2379 if ($8 & Attribute::ZExt) {
2380 RetAttrs = RetAttrs | Attribute::ZExt;
2381 $8 = $8 ^ Attribute::ZExt;
2383 if ($8 & Attribute::SExt) {
2384 RetAttrs = RetAttrs | Attribute::SExt;
2385 $8 = $8 ^ Attribute::SExt;
2387 if ($8 & Attribute::InReg) {
2388 RetAttrs = RetAttrs | Attribute::InReg;
2389 $8 = $8 ^ Attribute::InReg;
2392 if (RetAttrs != Attribute::None)
2393 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2394 if ($6) { // If there are arguments...
2396 for (ArgListType::iterator I = $6->begin(); I != $6->end(); ++I, ++index) {
2397 const Type* Ty = I->Ty->get();
2398 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2399 GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2400 ParamTypeList.push_back(Ty);
2401 if (Ty != Type::VoidTy && I->Attrs != Attribute::None)
2402 Attrs.push_back(AttributeWithIndex::get(index, I->Attrs));
2405 if ($8 != Attribute::None)
2406 Attrs.push_back(AttributeWithIndex::get(~0, $8));
2408 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2409 if (isVarArg) ParamTypeList.pop_back();
2413 PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2415 FunctionType *FT = FunctionType::get(*$3, ParamTypeList, isVarArg);
2416 const PointerType *PFT = PointerType::getUnqual(FT);
2420 if (!FunctionName.empty()) {
2421 ID = ValID::createGlobalName((char*)FunctionName.c_str());
2423 ID = ValID::createGlobalID(CurModule.Values.size());
2427 // See if this function was forward referenced. If so, recycle the object.
2428 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2429 // Move the function to the end of the list, from whereever it was
2430 // previously inserted.
2431 Fn = cast<Function>(FWRef);
2432 assert(Fn->getAttributes().isEmpty() &&
2433 "Forward reference has parameter attributes!");
2434 CurModule.CurrentModule->getFunctionList().remove(Fn);
2435 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2436 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2437 (Fn = CurModule.CurrentModule->getFunction(FunctionName))) {
2438 if (Fn->getFunctionType() != FT ) {
2439 // The existing function doesn't have the same type. This is an overload
2441 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2442 } else if (Fn->getAttributes() != PAL) {
2443 // The existing function doesn't have the same parameter attributes.
2444 // This is an overload error.
2445 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2446 } else if (!CurFun.isDeclare && !Fn->isDeclaration()) {
2447 // Neither the existing or the current function is a declaration and they
2448 // have the same name and same type. Clearly this is a redefinition.
2449 GEN_ERROR("Redefinition of function '" + FunctionName + "'");
2450 } else if (Fn->isDeclaration()) {
2451 // Make sure to strip off any argument names so we can't get conflicts.
2452 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2456 } else { // Not already defined?
2457 Fn = Function::Create(FT, GlobalValue::ExternalWeakLinkage, FunctionName,
2458 CurModule.CurrentModule);
2459 InsertValue(Fn, CurModule.Values);
2463 CurFun.FunctionStart(Fn);
2465 if (CurFun.isDeclare) {
2466 // If we have declaration, always overwrite linkage. This will allow us to
2467 // correctly handle cases, when pointer to function is passed as argument to
2468 // another function.
2469 Fn->setLinkage(CurFun.Linkage);
2470 Fn->setVisibility(CurFun.Visibility);
2472 Fn->setCallingConv($1);
2473 Fn->setAttributes(PAL);
2474 Fn->setAlignment($10);
2476 Fn->setSection(*$9);
2480 Fn->setGC($11->c_str());
2484 // Add all of the arguments we parsed to the function...
2485 if ($6) { // Is null if empty...
2486 if (isVarArg) { // Nuke the last entry
2487 assert($6->back().Ty->get() == Type::VoidTy && $6->back().Name == 0 &&
2488 "Not a varargs marker!");
2489 delete $6->back().Ty;
2490 $6->pop_back(); // Delete the last entry
2492 Function::arg_iterator ArgIt = Fn->arg_begin();
2493 Function::arg_iterator ArgEnd = Fn->arg_end();
2495 for (ArgListType::iterator I = $6->begin();
2496 I != $6->end() && ArgIt != ArgEnd; ++I, ++ArgIt) {
2497 delete I->Ty; // Delete the typeholder...
2498 setValueName(ArgIt, I->Name); // Insert arg into symtab...
2504 delete $6; // We're now done with the argument list
2509 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2511 FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2512 $$ = CurFun.CurrentFunction;
2514 // Make sure that we keep track of the linkage type even if there was a
2515 // previous "declare".
2517 $$->setVisibility($2);
2520 END : ENDTOK | '}'; // Allow end of '}' to end a function
2522 Function : BasicBlockList END {
2527 FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2528 CurFun.CurrentFunction->setLinkage($1);
2529 CurFun.CurrentFunction->setVisibility($2);
2530 $$ = CurFun.CurrentFunction;
2531 CurFun.FunctionDone();
2535 //===----------------------------------------------------------------------===//
2536 // Rules to match Basic Blocks
2537 //===----------------------------------------------------------------------===//
2539 OptSideEffect : /* empty */ {
2548 ConstValueRef : ESINT64VAL { // A reference to a direct constant
2549 $$ = ValID::create($1);
2553 $$ = ValID::create($1);
2556 | ESAPINTVAL { // arbitrary precision integer constants
2557 $$ = ValID::create(*$1, true);
2561 | EUAPINTVAL { // arbitrary precision integer constants
2562 $$ = ValID::create(*$1, false);
2566 | FPVAL { // Perhaps it's an FP constant?
2567 $$ = ValID::create($1);
2571 $$ = ValID::create(ConstantInt::getTrue());
2575 $$ = ValID::create(ConstantInt::getFalse());
2579 $$ = ValID::createNull();
2583 $$ = ValID::createUndef();
2586 | ZEROINITIALIZER { // A vector zero constant.
2587 $$ = ValID::createZeroInit();
2590 | '<' ConstVector '>' { // Nonempty unsized packed vector
2591 const Type *ETy = (*$2)[0]->getType();
2592 unsigned NumElements = $2->size();
2594 if (!ETy->isInteger() && !ETy->isFloatingPoint())
2595 GEN_ERROR("Invalid vector element type: " + ETy->getDescription());
2597 VectorType* pt = VectorType::get(ETy, NumElements);
2598 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(pt));
2600 // Verify all elements are correct type!
2601 for (unsigned i = 0; i < $2->size(); i++) {
2602 if (ETy != (*$2)[i]->getType())
2603 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2604 ETy->getDescription() +"' as required!\nIt is of type '" +
2605 (*$2)[i]->getType()->getDescription() + "'.");
2608 $$ = ValID::create(ConstantVector::get(pt, *$2));
2609 delete PTy; delete $2;
2612 | '[' ConstVector ']' { // Nonempty unsized arr
2613 const Type *ETy = (*$2)[0]->getType();
2614 uint64_t NumElements = $2->size();
2616 if (!ETy->isFirstClassType())
2617 GEN_ERROR("Invalid array element type: " + ETy->getDescription());
2619 ArrayType *ATy = ArrayType::get(ETy, NumElements);
2620 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(ATy));
2622 // Verify all elements are correct type!
2623 for (unsigned i = 0; i < $2->size(); i++) {
2624 if (ETy != (*$2)[i]->getType())
2625 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2626 ETy->getDescription() +"' as required!\nIt is of type '"+
2627 (*$2)[i]->getType()->getDescription() + "'.");
2630 $$ = ValID::create(ConstantArray::get(ATy, *$2));
2631 delete PTy; delete $2;
2635 // Use undef instead of an array because it's inconvenient to determine
2636 // the element type at this point, there being no elements to examine.
2637 $$ = ValID::createUndef();
2640 | 'c' STRINGCONSTANT {
2641 uint64_t NumElements = $2->length();
2642 const Type *ETy = Type::Int8Ty;
2644 ArrayType *ATy = ArrayType::get(ETy, NumElements);
2646 std::vector<Constant*> Vals;
2647 for (unsigned i = 0; i < $2->length(); ++i)
2648 Vals.push_back(ConstantInt::get(ETy, (*$2)[i]));
2650 $$ = ValID::create(ConstantArray::get(ATy, Vals));
2653 | '{' ConstVector '}' {
2654 std::vector<const Type*> Elements($2->size());
2655 for (unsigned i = 0, e = $2->size(); i != e; ++i)
2656 Elements[i] = (*$2)[i]->getType();
2658 const StructType *STy = StructType::get(Elements);
2659 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(STy));
2661 $$ = ValID::create(ConstantStruct::get(STy, *$2));
2662 delete PTy; delete $2;
2666 const StructType *STy = StructType::get(std::vector<const Type*>());
2667 $$ = ValID::create(ConstantStruct::get(STy, std::vector<Constant*>()));
2670 | '<' '{' ConstVector '}' '>' {
2671 std::vector<const Type*> Elements($3->size());
2672 for (unsigned i = 0, e = $3->size(); i != e; ++i)
2673 Elements[i] = (*$3)[i]->getType();
2675 const StructType *STy = StructType::get(Elements, /*isPacked=*/true);
2676 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(STy));
2678 $$ = ValID::create(ConstantStruct::get(STy, *$3));
2679 delete PTy; delete $3;
2683 const StructType *STy = StructType::get(std::vector<const Type*>(),
2685 $$ = ValID::create(ConstantStruct::get(STy, std::vector<Constant*>()));
2689 $$ = ValID::create($1);
2692 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2693 $$ = ValID::createInlineAsm(*$3, *$5, $2);
2699 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2702 SymbolicValueRef : LOCALVAL_ID { // Is it an integer reference...?
2703 $$ = ValID::createLocalID($1);
2707 $$ = ValID::createGlobalID($1);
2710 | LocalName { // Is it a named reference...?
2711 $$ = ValID::createLocalName(*$1);
2715 | GlobalName { // Is it a named reference...?
2716 $$ = ValID::createGlobalName(*$1);
2721 // ValueRef - A reference to a definition... either constant or symbolic
2722 ValueRef : SymbolicValueRef | ConstValueRef;
2725 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2726 // type immediately preceeds the value reference, and allows complex constant
2727 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2728 ResolvedVal : Types ValueRef {
2729 if (!UpRefs.empty())
2730 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2731 $$ = getVal(*$1, $2);
2737 ReturnedVal : ResolvedVal {
2738 $$ = new std::vector<Value *>();
2742 | ReturnedVal ',' ResolvedVal {
2743 ($$=$1)->push_back($3);
2747 BasicBlockList : BasicBlockList BasicBlock {
2751 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2757 // Basic blocks are terminated by branching instructions:
2758 // br, br/cc, switch, ret
2760 BasicBlock : InstructionList OptLocalAssign BBTerminatorInst {
2761 setValueName($3, $2);
2764 $1->getInstList().push_back($3);
2769 BasicBlock : InstructionList LocalNumber BBTerminatorInst {
2771 int ValNum = InsertValue($3);
2772 if (ValNum != (int)$2)
2773 GEN_ERROR("Result value number %" + utostr($2) +
2774 " is incorrect, expected %" + utostr((unsigned)ValNum));
2776 $1->getInstList().push_back($3);
2782 InstructionList : InstructionList Inst {
2783 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2784 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2785 if (CI2->getParent() == 0)
2786 $1->getInstList().push_back(CI2);
2787 $1->getInstList().push_back($2);
2791 | /* empty */ { // Empty space between instruction lists
2792 $$ = defineBBVal(ValID::createLocalID(CurFun.NextValNum));
2795 | LABELSTR { // Labelled (named) basic block
2796 $$ = defineBBVal(ValID::createLocalName(*$1));
2803 RET ReturnedVal { // Return with a result...
2804 ValueList &VL = *$2;
2805 assert(!VL.empty() && "Invalid ret operands!");
2806 const Type *ReturnType = CurFun.CurrentFunction->getReturnType();
2807 if (VL.size() > 1 ||
2808 (isa<StructType>(ReturnType) &&
2809 (VL.empty() || VL[0]->getType() != ReturnType))) {
2810 Value *RV = UndefValue::get(ReturnType);
2811 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
2812 Instruction *I = InsertValueInst::Create(RV, VL[i], i, "mrv");
2813 ($<BasicBlockVal>-1)->getInstList().push_back(I);
2816 $$ = ReturnInst::Create(RV);
2818 $$ = ReturnInst::Create(VL[0]);
2823 | RET VOID { // Return with no result...
2824 $$ = ReturnInst::Create();
2827 | BR LABEL ValueRef { // Unconditional Branch...
2828 BasicBlock* tmpBB = getBBVal($3);
2830 $$ = BranchInst::Create(tmpBB);
2831 } // Conditional Branch...
2832 | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2833 if (cast<IntegerType>($2)->getBitWidth() != 1)
2834 GEN_ERROR("Branch condition must have type i1");
2835 BasicBlock* tmpBBA = getBBVal($6);
2837 BasicBlock* tmpBBB = getBBVal($9);
2839 Value* tmpVal = getVal(Type::Int1Ty, $3);
2841 $$ = BranchInst::Create(tmpBBA, tmpBBB, tmpVal);
2843 | SWITCH INTTYPE ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2844 Value* tmpVal = getVal($2, $3);
2846 BasicBlock* tmpBB = getBBVal($6);
2848 SwitchInst *S = SwitchInst::Create(tmpVal, tmpBB, $8->size());
2851 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2853 for (; I != E; ++I) {
2854 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2855 S->addCase(CI, I->second);
2857 GEN_ERROR("Switch case is constant, but not a simple integer");
2862 | SWITCH INTTYPE ValueRef ',' LABEL ValueRef '[' ']' {
2863 Value* tmpVal = getVal($2, $3);
2865 BasicBlock* tmpBB = getBBVal($6);
2867 SwitchInst *S = SwitchInst::Create(tmpVal, tmpBB, 0);
2871 | INVOKE OptCallingConv OptRetAttrs ResultTypes ValueRef '(' ParamList ')'
2872 OptFuncAttrs TO LABEL ValueRef UNWIND LABEL ValueRef {
2874 // Handle the short syntax
2875 const PointerType *PFTy = 0;
2876 const FunctionType *Ty = 0;
2877 if (!(PFTy = dyn_cast<PointerType>($4->get())) ||
2878 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2879 // Pull out the types of all of the arguments...
2880 std::vector<const Type*> ParamTypes;
2881 ParamList::iterator I = $7->begin(), E = $7->end();
2882 for (; I != E; ++I) {
2883 const Type *Ty = I->Val->getType();
2884 if (Ty == Type::VoidTy)
2885 GEN_ERROR("Short call syntax cannot be used with varargs");
2886 ParamTypes.push_back(Ty);
2889 if (!FunctionType::isValidReturnType(*$4))
2890 GEN_ERROR("Invalid result type for LLVM function");
2892 Ty = FunctionType::get($4->get(), ParamTypes, false);
2893 PFTy = PointerType::getUnqual(Ty);
2898 Value *V = getVal(PFTy, $5); // Get the function we're calling...
2900 BasicBlock *Normal = getBBVal($12);
2902 BasicBlock *Except = getBBVal($15);
2905 SmallVector<AttributeWithIndex, 8> Attrs;
2906 //FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2908 Attributes RetAttrs = $3;
2909 if ($9 != Attribute::None) {
2910 if ($9 & Attribute::ZExt) {
2911 RetAttrs = RetAttrs | Attribute::ZExt;
2912 $9 = $9 ^ Attribute::ZExt;
2914 if ($9 & Attribute::SExt) {
2915 RetAttrs = RetAttrs | Attribute::SExt;
2916 $9 = $9 ^ Attribute::SExt;
2918 if ($9 & Attribute::InReg) {
2919 RetAttrs = RetAttrs | Attribute::InReg;
2920 $9 = $9 ^ Attribute::InReg;
2923 if (RetAttrs != Attribute::None)
2924 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2926 // Check the arguments
2928 if ($7->empty()) { // Has no arguments?
2929 // Make sure no arguments is a good thing!
2930 if (Ty->getNumParams() != 0)
2931 GEN_ERROR("No arguments passed to a function that "
2932 "expects arguments");
2933 } else { // Has arguments?
2934 // Loop through FunctionType's arguments and ensure they are specified
2936 FunctionType::param_iterator I = Ty->param_begin();
2937 FunctionType::param_iterator E = Ty->param_end();
2938 ParamList::iterator ArgI = $7->begin(), ArgE = $7->end();
2941 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
2942 if (ArgI->Val->getType() != *I)
2943 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2944 (*I)->getDescription() + "'");
2945 Args.push_back(ArgI->Val);
2946 if (ArgI->Attrs != Attribute::None)
2947 Attrs.push_back(AttributeWithIndex::get(index, ArgI->Attrs));
2950 if (Ty->isVarArg()) {
2952 for (; ArgI != ArgE; ++ArgI, ++index) {
2953 Args.push_back(ArgI->Val); // push the remaining varargs
2954 if (ArgI->Attrs != Attribute::None)
2955 Attrs.push_back(AttributeWithIndex::get(index, ArgI->Attrs));
2957 } else if (I != E || ArgI != ArgE)
2958 GEN_ERROR("Invalid number of parameters detected");
2960 if ($9 != Attribute::None)
2961 Attrs.push_back(AttributeWithIndex::get(~0, $9));
2964 PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2966 // Create the InvokeInst
2967 InvokeInst *II = InvokeInst::Create(V, Normal, Except,
2968 Args.begin(), Args.end());
2969 II->setCallingConv($2);
2970 II->setAttributes(PAL);
2976 $$ = new UnwindInst();
2980 $$ = new UnreachableInst();
2986 JumpTable : JumpTable INTTYPE ConstValueRef ',' LABEL ValueRef {
2988 Constant *V = cast<Constant>(getExistingVal($2, $3));
2991 GEN_ERROR("May only switch on a constant pool value");
2993 BasicBlock* tmpBB = getBBVal($6);
2995 $$->push_back(std::make_pair(V, tmpBB));
2997 | INTTYPE ConstValueRef ',' LABEL ValueRef {
2998 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2999 Constant *V = cast<Constant>(getExistingVal($1, $2));
3003 GEN_ERROR("May only switch on a constant pool value");
3005 BasicBlock* tmpBB = getBBVal($5);
3007 $$->push_back(std::make_pair(V, tmpBB));
3010 Inst : OptLocalAssign InstVal {
3011 // Is this definition named?? if so, assign the name...
3012 setValueName($2, $1);
3019 Inst : LocalNumber InstVal {
3021 int ValNum = InsertValue($2);
3023 if (ValNum != (int)$1)
3024 GEN_ERROR("Result value number %" + utostr($1) +
3025 " is incorrect, expected %" + utostr((unsigned)ValNum));
3032 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
3033 if (!UpRefs.empty())
3034 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
3035 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
3036 Value* tmpVal = getVal(*$1, $3);
3038 BasicBlock* tmpBB = getBBVal($5);
3040 $$->push_back(std::make_pair(tmpVal, tmpBB));
3043 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
3045 Value* tmpVal = getVal($1->front().first->getType(), $4);
3047 BasicBlock* tmpBB = getBBVal($6);
3049 $1->push_back(std::make_pair(tmpVal, tmpBB));
3053 ParamList : Types OptAttributes ValueRef OptAttributes {
3054 // FIXME: Remove trailing OptAttributes in LLVM 3.0, it was a mistake in 2.0
3055 if (!UpRefs.empty())
3056 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
3057 // Used for call and invoke instructions
3058 $$ = new ParamList();
3059 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getVal($1->get(), $3);
3064 | LABEL OptAttributes ValueRef OptAttributes {
3065 // FIXME: Remove trailing OptAttributes in LLVM 3.0, it was a mistake in 2.0
3066 // Labels are only valid in ASMs
3067 $$ = new ParamList();
3068 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getBBVal($3);
3072 | ParamList ',' Types OptAttributes ValueRef OptAttributes {
3073 // FIXME: Remove trailing OptAttributes in LLVM 3.0, it was a mistake in 2.0
3074 if (!UpRefs.empty())
3075 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3077 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getVal($3->get(), $5);
3082 | ParamList ',' LABEL OptAttributes ValueRef OptAttributes {
3083 // FIXME: Remove trailing OptAttributes in LLVM 3.0, it was a mistake in 2.0
3085 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getBBVal($5);
3089 | /*empty*/ { $$ = new ParamList(); };
3091 IndexList // Used for gep instructions and constant expressions
3092 : /*empty*/ { $$ = new std::vector<Value*>(); }
3093 | IndexList ',' ResolvedVal {
3100 ConstantIndexList // Used for insertvalue and extractvalue instructions
3102 $$ = new std::vector<unsigned>();
3103 if ((unsigned)$2 != $2)
3104 GEN_ERROR("Index " + utostr($2) + " is not valid for insertvalue or extractvalue.");
3107 | ConstantIndexList ',' EUINT64VAL {
3109 if ((unsigned)$3 != $3)
3110 GEN_ERROR("Index " + utostr($3) + " is not valid for insertvalue or extractvalue.");
3116 OptTailCall : TAIL CALL {
3125 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
3126 if (!UpRefs.empty())
3127 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3128 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
3129 !isa<VectorType>((*$2).get()))
3131 "Arithmetic operator requires integer, FP, or packed operands");
3132 Value* val1 = getVal(*$2, $3);
3134 Value* val2 = getVal(*$2, $5);
3136 $$ = BinaryOperator::Create($1, val1, val2);
3138 GEN_ERROR("binary operator returned null");
3141 | LogicalOps Types ValueRef ',' ValueRef {
3142 if (!UpRefs.empty())
3143 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3144 if (!(*$2)->isInteger()) {
3145 if (!isa<VectorType>($2->get()) ||
3146 !cast<VectorType>($2->get())->getElementType()->isInteger())
3147 GEN_ERROR("Logical operator requires integral operands");
3149 Value* tmpVal1 = getVal(*$2, $3);
3151 Value* tmpVal2 = getVal(*$2, $5);
3153 $$ = BinaryOperator::Create($1, tmpVal1, tmpVal2);
3155 GEN_ERROR("binary operator returned null");
3158 | ICMP IPredicates Types ValueRef ',' ValueRef {
3159 if (!UpRefs.empty())
3160 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3161 Value* tmpVal1 = getVal(*$3, $4);
3163 Value* tmpVal2 = getVal(*$3, $6);
3165 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3167 GEN_ERROR("icmp operator returned null");
3170 | FCMP FPredicates Types ValueRef ',' ValueRef {
3171 if (!UpRefs.empty())
3172 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3173 Value* tmpVal1 = getVal(*$3, $4);
3175 Value* tmpVal2 = getVal(*$3, $6);
3177 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3179 GEN_ERROR("fcmp operator returned null");
3182 | VICMP IPredicates Types ValueRef ',' ValueRef {
3183 if (!UpRefs.empty())
3184 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3185 if (!isa<VectorType>((*$3).get()))
3186 GEN_ERROR("Scalar types not supported by vicmp instruction");
3187 Value* tmpVal1 = getVal(*$3, $4);
3189 Value* tmpVal2 = getVal(*$3, $6);
3191 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3193 GEN_ERROR("vicmp operator returned null");
3196 | VFCMP FPredicates Types ValueRef ',' ValueRef {
3197 if (!UpRefs.empty())
3198 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3199 if (!isa<VectorType>((*$3).get()))
3200 GEN_ERROR("Scalar types not supported by vfcmp instruction");
3201 Value* tmpVal1 = getVal(*$3, $4);
3203 Value* tmpVal2 = getVal(*$3, $6);
3205 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3207 GEN_ERROR("vfcmp operator returned null");
3210 | CastOps ResolvedVal TO Types {
3211 if (!UpRefs.empty())
3212 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
3214 const Type* DestTy = $4->get();
3215 if (!CastInst::castIsValid($1, Val, DestTy))
3216 GEN_ERROR("invalid cast opcode for cast from '" +
3217 Val->getType()->getDescription() + "' to '" +
3218 DestTy->getDescription() + "'");
3219 $$ = CastInst::Create($1, Val, DestTy);
3222 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3223 if (isa<VectorType>($2->getType())) {
3225 if (!isa<VectorType>($4->getType())
3226 || !isa<VectorType>($6->getType()) )
3227 GEN_ERROR("vector select value types must be vector types");
3228 const VectorType* cond_type = cast<VectorType>($2->getType());
3229 const VectorType* select_type = cast<VectorType>($4->getType());
3230 if (cond_type->getElementType() != Type::Int1Ty)
3231 GEN_ERROR("vector select condition element type must be boolean");
3232 if (cond_type->getNumElements() != select_type->getNumElements())
3233 GEN_ERROR("vector select number of elements must be the same");
3235 if ($2->getType() != Type::Int1Ty)
3236 GEN_ERROR("select condition must be boolean");
3238 if ($4->getType() != $6->getType())
3239 GEN_ERROR("select value types must match");
3240 $$ = SelectInst::Create($2, $4, $6);
3243 | VAARG ResolvedVal ',' Types {
3244 if (!UpRefs.empty())
3245 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
3246 $$ = new VAArgInst($2, *$4);
3250 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
3251 if (!ExtractElementInst::isValidOperands($2, $4))
3252 GEN_ERROR("Invalid extractelement operands");
3253 $$ = new ExtractElementInst($2, $4);
3256 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3257 if (!InsertElementInst::isValidOperands($2, $4, $6))
3258 GEN_ERROR("Invalid insertelement operands");
3259 $$ = InsertElementInst::Create($2, $4, $6);
3262 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3263 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
3264 GEN_ERROR("Invalid shufflevector operands");
3265 $$ = new ShuffleVectorInst($2, $4, $6);
3269 const Type *Ty = $2->front().first->getType();
3270 if (!Ty->isFirstClassType())
3271 GEN_ERROR("PHI node operands must be of first class type");
3272 $$ = PHINode::Create(Ty);
3273 ((PHINode*)$$)->reserveOperandSpace($2->size());
3274 while ($2->begin() != $2->end()) {
3275 if ($2->front().first->getType() != Ty)
3276 GEN_ERROR("All elements of a PHI node must be of the same type");
3277 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
3280 delete $2; // Free the list...
3283 | OptTailCall OptCallingConv OptRetAttrs ResultTypes ValueRef '(' ParamList ')'
3286 // Handle the short syntax
3287 const PointerType *PFTy = 0;
3288 const FunctionType *Ty = 0;
3289 if (!(PFTy = dyn_cast<PointerType>($4->get())) ||
3290 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3291 // Pull out the types of all of the arguments...
3292 std::vector<const Type*> ParamTypes;
3293 ParamList::iterator I = $7->begin(), E = $7->end();
3294 for (; I != E; ++I) {
3295 const Type *Ty = I->Val->getType();
3296 if (Ty == Type::VoidTy)
3297 GEN_ERROR("Short call syntax cannot be used with varargs");
3298 ParamTypes.push_back(Ty);
3301 if (!FunctionType::isValidReturnType(*$4))
3302 GEN_ERROR("Invalid result type for LLVM function");
3304 Ty = FunctionType::get($4->get(), ParamTypes, false);
3305 PFTy = PointerType::getUnqual(Ty);
3308 Value *V = getVal(PFTy, $5); // Get the function we're calling...
3311 // Check for call to invalid intrinsic to avoid crashing later.
3312 if (Function *theF = dyn_cast<Function>(V)) {
3313 if (theF->hasName() && (theF->getValueName()->getKeyLength() >= 5) &&
3314 (0 == strncmp(theF->getValueName()->getKeyData(), "llvm.", 5)) &&
3315 !theF->getIntrinsicID(true))
3316 GEN_ERROR("Call to invalid LLVM intrinsic function '" +
3317 theF->getName() + "'");
3320 // Set up the Attributes for the function
3321 SmallVector<AttributeWithIndex, 8> Attrs;
3322 //FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
3324 Attributes RetAttrs = $3;
3325 if ($9 != Attribute::None) {
3326 if ($9 & Attribute::ZExt) {
3327 RetAttrs = RetAttrs | Attribute::ZExt;
3328 $9 = $9 ^ Attribute::ZExt;
3330 if ($9 & Attribute::SExt) {
3331 RetAttrs = RetAttrs | Attribute::SExt;
3332 $9 = $9 ^ Attribute::SExt;
3334 if ($9 & Attribute::InReg) {
3335 RetAttrs = RetAttrs | Attribute::InReg;
3336 $9 = $9 ^ Attribute::InReg;
3339 if (RetAttrs != Attribute::None)
3340 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3342 // Check the arguments
3344 if ($7->empty()) { // Has no arguments?
3345 // Make sure no arguments is a good thing!
3346 if (Ty->getNumParams() != 0)
3347 GEN_ERROR("No arguments passed to a function that "
3348 "expects arguments");
3349 } else { // Has arguments?
3350 // Loop through FunctionType's arguments and ensure they are specified
3351 // correctly. Also, gather any parameter attributes.
3352 FunctionType::param_iterator I = Ty->param_begin();
3353 FunctionType::param_iterator E = Ty->param_end();
3354 ParamList::iterator ArgI = $7->begin(), ArgE = $7->end();
3357 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
3358 if (ArgI->Val->getType() != *I)
3359 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
3360 (*I)->getDescription() + "'");
3361 Args.push_back(ArgI->Val);
3362 if (ArgI->Attrs != Attribute::None)
3363 Attrs.push_back(AttributeWithIndex::get(index, ArgI->Attrs));
3365 if (Ty->isVarArg()) {
3367 for (; ArgI != ArgE; ++ArgI, ++index) {
3368 Args.push_back(ArgI->Val); // push the remaining varargs
3369 if (ArgI->Attrs != Attribute::None)
3370 Attrs.push_back(AttributeWithIndex::get(index, ArgI->Attrs));
3372 } else if (I != E || ArgI != ArgE)
3373 GEN_ERROR("Invalid number of parameters detected");
3375 if ($9 != Attribute::None)
3376 Attrs.push_back(AttributeWithIndex::get(~0, $9));
3378 // Finish off the Attributes and check them
3381 PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3383 // Create the call node
3384 CallInst *CI = CallInst::Create(V, Args.begin(), Args.end());
3385 CI->setTailCall($1);
3386 CI->setCallingConv($2);
3387 CI->setAttributes(PAL);
3398 OptVolatile : VOLATILE {
3409 MemoryInst : MALLOC Types OptCAlign {
3410 if (!UpRefs.empty())
3411 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3412 $$ = new MallocInst(*$2, 0, $3);
3416 | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
3417 if (!UpRefs.empty())
3418 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3419 if ($4 != Type::Int32Ty)
3420 GEN_ERROR("Malloc array size is not a 32-bit integer!");
3421 Value* tmpVal = getVal($4, $5);
3423 $$ = new MallocInst(*$2, tmpVal, $6);
3426 | ALLOCA Types OptCAlign {
3427 if (!UpRefs.empty())
3428 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3429 $$ = new AllocaInst(*$2, 0, $3);
3433 | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
3434 if (!UpRefs.empty())
3435 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3436 if ($4 != Type::Int32Ty)
3437 GEN_ERROR("Alloca array size is not a 32-bit integer!");
3438 Value* tmpVal = getVal($4, $5);
3440 $$ = new AllocaInst(*$2, tmpVal, $6);
3443 | FREE ResolvedVal {
3444 if (!isa<PointerType>($2->getType()))
3445 GEN_ERROR("Trying to free nonpointer type " +
3446 $2->getType()->getDescription() + "");
3447 $$ = new FreeInst($2);
3451 | OptVolatile LOAD Types ValueRef OptCAlign {
3452 if (!UpRefs.empty())
3453 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3454 if (!isa<PointerType>($3->get()))
3455 GEN_ERROR("Can't load from nonpointer type: " +
3456 (*$3)->getDescription());
3457 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
3458 GEN_ERROR("Can't load from pointer of non-first-class type: " +
3459 (*$3)->getDescription());
3460 Value* tmpVal = getVal(*$3, $4);
3462 $$ = new LoadInst(tmpVal, "", $1, $5);
3465 | OptVolatile STORE ResolvedVal ',' Types ValueRef OptCAlign {
3466 if (!UpRefs.empty())
3467 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
3468 const PointerType *PT = dyn_cast<PointerType>($5->get());
3470 GEN_ERROR("Can't store to a nonpointer type: " +
3471 (*$5)->getDescription());
3472 const Type *ElTy = PT->getElementType();
3473 if (ElTy != $3->getType())
3474 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
3475 "' into space of type '" + ElTy->getDescription() + "'");
3477 Value* tmpVal = getVal(*$5, $6);
3479 $$ = new StoreInst($3, tmpVal, $1, $7);
3482 | GETRESULT Types ValueRef ',' EUINT64VAL {
3483 if (!UpRefs.empty())
3484 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3485 if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3486 GEN_ERROR("getresult insn requires an aggregate operand");
3487 if (!ExtractValueInst::getIndexedType(*$2, $5))
3488 GEN_ERROR("Invalid getresult index for type '" +
3489 (*$2)->getDescription()+ "'");
3491 Value *tmpVal = getVal(*$2, $3);
3493 $$ = ExtractValueInst::Create(tmpVal, $5);
3496 | GETELEMENTPTR Types ValueRef IndexList {
3497 if (!UpRefs.empty())
3498 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3499 if (!isa<PointerType>($2->get()))
3500 GEN_ERROR("getelementptr insn requires pointer operand");
3502 if (!GetElementPtrInst::getIndexedType(*$2, $4->begin(), $4->end()))
3503 GEN_ERROR("Invalid getelementptr indices for type '" +
3504 (*$2)->getDescription()+ "'");
3505 Value* tmpVal = getVal(*$2, $3);
3507 $$ = GetElementPtrInst::Create(tmpVal, $4->begin(), $4->end());
3511 | EXTRACTVALUE Types ValueRef ConstantIndexList {
3512 if (!UpRefs.empty())
3513 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3514 if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3515 GEN_ERROR("extractvalue insn requires an aggregate operand");
3517 if (!ExtractValueInst::getIndexedType(*$2, $4->begin(), $4->end()))
3518 GEN_ERROR("Invalid extractvalue indices for type '" +
3519 (*$2)->getDescription()+ "'");
3520 Value* tmpVal = getVal(*$2, $3);
3522 $$ = ExtractValueInst::Create(tmpVal, $4->begin(), $4->end());
3526 | INSERTVALUE Types ValueRef ',' Types ValueRef ConstantIndexList {
3527 if (!UpRefs.empty())
3528 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3529 if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3530 GEN_ERROR("extractvalue insn requires an aggregate operand");
3532 if (ExtractValueInst::getIndexedType(*$2, $7->begin(), $7->end()) != $5->get())
3533 GEN_ERROR("Invalid insertvalue indices for type '" +
3534 (*$2)->getDescription()+ "'");
3535 Value* aggVal = getVal(*$2, $3);
3536 Value* tmpVal = getVal(*$5, $6);
3538 $$ = InsertValueInst::Create(aggVal, tmpVal, $7->begin(), $7->end());
3547 // common code from the two 'RunVMAsmParser' functions
3548 static Module* RunParser(Module * M) {
3549 CurModule.CurrentModule = M;
3550 // Check to make sure the parser succeeded
3553 delete ParserResult;
3557 // Emit an error if there are any unresolved types left.
3558 if (!CurModule.LateResolveTypes.empty()) {
3559 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
3560 if (DID.Type == ValID::LocalName) {
3561 GenerateError("Undefined type remains at eof: '"+DID.getName() + "'");
3563 GenerateError("Undefined type remains at eof: #" + itostr(DID.Num));
3566 delete ParserResult;
3570 // Emit an error if there are any unresolved values left.
3571 if (!CurModule.LateResolveValues.empty()) {
3572 Value *V = CurModule.LateResolveValues.back();
3573 std::map<Value*, std::pair<ValID, int> >::iterator I =
3574 CurModule.PlaceHolderInfo.find(V);
3576 if (I != CurModule.PlaceHolderInfo.end()) {
3577 ValID &DID = I->second.first;
3578 if (DID.Type == ValID::LocalName) {
3579 GenerateError("Undefined value remains at eof: "+DID.getName() + "'");
3581 GenerateError("Undefined value remains at eof: #" + itostr(DID.Num));
3584 delete ParserResult;
3589 // Check to make sure that parsing produced a result
3593 // Reset ParserResult variable while saving its value for the result.
3594 Module *Result = ParserResult;
3600 void llvm::GenerateError(const std::string &message, int LineNo) {
3601 if (LineNo == -1) LineNo = LLLgetLineNo();
3602 // TODO: column number in exception
3604 TheParseError->setError(LLLgetFilename(), message, LineNo);
3608 int yyerror(const char *ErrorMsg) {
3609 std::string where = LLLgetFilename() + ":" + utostr(LLLgetLineNo()) + ": ";
3610 std::string errMsg = where + "error: " + std::string(ErrorMsg);
3611 if (yychar != YYEMPTY && yychar != 0) {
3612 errMsg += " while reading token: '";
3613 errMsg += std::string(LLLgetTokenStart(),
3614 LLLgetTokenStart()+LLLgetTokenLength()) + "'";
3616 GenerateError(errMsg);