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 &&
432 D.ConstPoolFP->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
433 return ConstantFP::get(*D.ConstPoolFP);
435 case ValID::ConstNullVal: // Is it a null value?
436 if (!isa<PointerType>(Ty)) {
437 GenerateError("Cannot create a a non pointer null");
440 return ConstantPointerNull::get(cast<PointerType>(Ty));
442 case ValID::ConstUndefVal: // Is it an undef value?
443 return UndefValue::get(Ty);
445 case ValID::ConstZeroVal: // Is it a zero value?
446 return Constant::getNullValue(Ty);
448 case ValID::ConstantVal: // Fully resolved constant?
449 if (D.ConstantValue->getType() != Ty) {
450 GenerateError("Constant expression type different from required type");
453 return D.ConstantValue;
455 case ValID::InlineAsmVal: { // Inline asm expression
456 const PointerType *PTy = dyn_cast<PointerType>(Ty);
457 const FunctionType *FTy =
458 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
459 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
460 GenerateError("Invalid type for asm constraint string");
463 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
464 D.IAD->HasSideEffects);
465 D.destroy(); // Free InlineAsmDescriptor.
469 assert(0 && "Unhandled case!");
473 assert(0 && "Unhandled case!");
477 // getVal - This function is identical to getExistingVal, except that if a
478 // value is not already defined, it "improvises" by creating a placeholder var
479 // that looks and acts just like the requested variable. When the value is
480 // defined later, all uses of the placeholder variable are replaced with the
483 static Value *getVal(const Type *Ty, const ValID &ID) {
484 if (Ty == Type::LabelTy) {
485 GenerateError("Cannot use a basic block here");
489 // See if the value has already been defined.
490 Value *V = getExistingVal(Ty, ID);
492 if (TriggerError) return 0;
494 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
495 GenerateError("Invalid use of a non-first-class type");
499 // If we reached here, we referenced either a symbol that we don't know about
500 // or an id number that hasn't been read yet. We may be referencing something
501 // forward, so just create an entry to be resolved later and get to it...
504 case ValID::GlobalName:
505 case ValID::GlobalID: {
506 const PointerType *PTy = dyn_cast<PointerType>(Ty);
508 GenerateError("Invalid type for reference to global" );
511 const Type* ElTy = PTy->getElementType();
512 if (const FunctionType *FTy = dyn_cast<FunctionType>(ElTy))
513 V = Function::Create(FTy, GlobalValue::ExternalLinkage);
515 V = new GlobalVariable(ElTy, false, GlobalValue::ExternalLinkage, 0, "",
516 (Module*)0, false, PTy->getAddressSpace());
520 V = new Argument(Ty);
523 // Remember where this forward reference came from. FIXME, shouldn't we try
524 // to recycle these things??
525 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
528 if (inFunctionScope())
529 InsertValue(V, CurFun.LateResolveValues);
531 InsertValue(V, CurModule.LateResolveValues);
535 /// defineBBVal - This is a definition of a new basic block with the specified
536 /// identifier which must be the same as CurFun.NextValNum, if its numeric.
537 static BasicBlock *defineBBVal(const ValID &ID) {
538 assert(inFunctionScope() && "Can't get basic block at global scope!");
542 // First, see if this was forward referenced
544 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
545 if (BBI != CurFun.BBForwardRefs.end()) {
547 // The forward declaration could have been inserted anywhere in the
548 // function: insert it into the correct place now.
549 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
550 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
552 // We're about to erase the entry, save the key so we can clean it up.
553 ValID Tmp = BBI->first;
555 // Erase the forward ref from the map as its no longer "forward"
556 CurFun.BBForwardRefs.erase(ID);
558 // The key has been removed from the map but so we don't want to leave
559 // strdup'd memory around so destroy it too.
562 // If its a numbered definition, bump the number and set the BB value.
563 if (ID.Type == ValID::LocalID) {
564 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
568 // We haven't seen this BB before and its first mention is a definition.
569 // Just create it and return it.
570 std::string Name (ID.Type == ValID::LocalName ? ID.getName() : "");
571 BB = BasicBlock::Create(Name, CurFun.CurrentFunction);
572 if (ID.Type == ValID::LocalID) {
573 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
582 /// getBBVal - get an existing BB value or create a forward reference for it.
584 static BasicBlock *getBBVal(const ValID &ID) {
585 assert(inFunctionScope() && "Can't get basic block at global scope!");
589 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
590 if (BBI != CurFun.BBForwardRefs.end()) {
592 } if (ID.Type == ValID::LocalName) {
593 std::string Name = ID.getName();
594 Value *N = CurFun.CurrentFunction->getValueSymbolTable().lookup(Name);
596 if (N->getType()->getTypeID() == Type::LabelTyID)
597 BB = cast<BasicBlock>(N);
599 GenerateError("Reference to label '" + Name + "' is actually of type '"+
600 N->getType()->getDescription() + "'");
602 } else if (ID.Type == ValID::LocalID) {
603 if (ID.Num < CurFun.NextValNum && ID.Num < CurFun.Values.size()) {
604 if (CurFun.Values[ID.Num]->getType()->getTypeID() == Type::LabelTyID)
605 BB = cast<BasicBlock>(CurFun.Values[ID.Num]);
607 GenerateError("Reference to label '%" + utostr(ID.Num) +
608 "' is actually of type '"+
609 CurFun.Values[ID.Num]->getType()->getDescription() + "'");
612 GenerateError("Illegal label reference " + ID.getName());
616 // If its already been defined, return it now.
618 ID.destroy(); // Free strdup'd memory.
622 // Otherwise, this block has not been seen before, create it.
624 if (ID.Type == ValID::LocalName)
626 BB = BasicBlock::Create(Name, CurFun.CurrentFunction);
628 // Insert it in the forward refs map.
629 CurFun.BBForwardRefs[ID] = BB;
635 //===----------------------------------------------------------------------===//
636 // Code to handle forward references in instructions
637 //===----------------------------------------------------------------------===//
639 // This code handles the late binding needed with statements that reference
640 // values not defined yet... for example, a forward branch, or the PHI node for
643 // This keeps a table (CurFun.LateResolveValues) of all such forward references
644 // and back patchs after we are done.
647 // ResolveDefinitions - If we could not resolve some defs at parsing
648 // time (forward branches, phi functions for loops, etc...) resolve the
652 ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers) {
653 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
654 while (!LateResolvers.empty()) {
655 Value *V = LateResolvers.back();
656 LateResolvers.pop_back();
658 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
659 CurModule.PlaceHolderInfo.find(V);
660 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
662 ValID &DID = PHI->second.first;
664 Value *TheRealValue = getExistingVal(V->getType(), DID);
668 V->replaceAllUsesWith(TheRealValue);
670 CurModule.PlaceHolderInfo.erase(PHI);
671 } else if (FutureLateResolvers) {
672 // Functions have their unresolved items forwarded to the module late
674 InsertValue(V, *FutureLateResolvers);
676 if (DID.Type == ValID::LocalName || DID.Type == ValID::GlobalName) {
677 GenerateError("Reference to an invalid definition: '" +DID.getName()+
678 "' of type '" + V->getType()->getDescription() + "'",
682 GenerateError("Reference to an invalid definition: #" +
683 itostr(DID.Num) + " of type '" +
684 V->getType()->getDescription() + "'",
690 LateResolvers.clear();
693 // ResolveTypeTo - A brand new type was just declared. This means that (if
694 // name is not null) things referencing Name can be resolved. Otherwise, things
695 // refering to the number can be resolved. Do this now.
697 static void ResolveTypeTo(std::string *Name, const Type *ToTy) {
700 D = ValID::createLocalName(*Name);
702 D = ValID::createLocalID(CurModule.Types.size());
704 std::map<ValID, PATypeHolder>::iterator I =
705 CurModule.LateResolveTypes.find(D);
706 if (I != CurModule.LateResolveTypes.end()) {
707 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
708 CurModule.LateResolveTypes.erase(I);
712 // setValueName - Set the specified value to the name given. The name may be
713 // null potentially, in which case this is a noop. The string passed in is
714 // assumed to be a malloc'd string buffer, and is free'd by this function.
716 static void setValueName(Value *V, std::string *NameStr) {
717 if (!NameStr) return;
718 std::string Name(*NameStr); // Copy string
719 delete NameStr; // Free old string
721 if (V->getType() == Type::VoidTy) {
722 GenerateError("Can't assign name '" + Name+"' to value with void type");
726 assert(inFunctionScope() && "Must be in function scope!");
727 ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
728 if (ST.lookup(Name)) {
729 GenerateError("Redefinition of value '" + Name + "' of type '" +
730 V->getType()->getDescription() + "'");
738 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
739 /// this is a declaration, otherwise it is a definition.
740 static GlobalVariable *
741 ParseGlobalVariable(std::string *NameStr,
742 GlobalValue::LinkageTypes Linkage,
743 GlobalValue::VisibilityTypes Visibility,
744 bool isConstantGlobal, const Type *Ty,
745 Constant *Initializer, bool IsThreadLocal,
746 unsigned AddressSpace = 0) {
747 if (isa<FunctionType>(Ty)) {
748 GenerateError("Cannot declare global vars of function type");
751 if (Ty == Type::LabelTy) {
752 GenerateError("Cannot declare global vars of label type");
756 const PointerType *PTy = PointerType::get(Ty, AddressSpace);
760 Name = *NameStr; // Copy string
761 delete NameStr; // Free old string
764 // See if this global value was forward referenced. If so, recycle the
768 ID = ValID::createGlobalName(Name);
770 ID = ValID::createGlobalID(CurModule.Values.size());
773 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
774 // Move the global to the end of the list, from whereever it was
775 // previously inserted.
776 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
777 CurModule.CurrentModule->getGlobalList().remove(GV);
778 CurModule.CurrentModule->getGlobalList().push_back(GV);
779 GV->setInitializer(Initializer);
780 GV->setLinkage(Linkage);
781 GV->setVisibility(Visibility);
782 GV->setConstant(isConstantGlobal);
783 GV->setThreadLocal(IsThreadLocal);
784 InsertValue(GV, CurModule.Values);
788 // If this global has a name
790 // if the global we're parsing has an initializer (is a definition) and
791 // has external linkage.
792 if (Initializer && Linkage != GlobalValue::InternalLinkage)
793 // If there is already a global with external linkage with this name
794 if (CurModule.CurrentModule->getGlobalVariable(Name, false)) {
795 // If we allow this GVar to get created, it will be renamed in the
796 // symbol table because it conflicts with an existing GVar. We can't
797 // allow redefinition of GVars whose linking indicates that their name
798 // must stay the same. Issue the error.
799 GenerateError("Redefinition of global variable named '" + Name +
800 "' of type '" + Ty->getDescription() + "'");
805 // Otherwise there is no existing GV to use, create one now.
807 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
808 CurModule.CurrentModule, IsThreadLocal, AddressSpace);
809 GV->setVisibility(Visibility);
810 InsertValue(GV, CurModule.Values);
814 // setTypeName - Set the specified type to the name given. The name may be
815 // null potentially, in which case this is a noop. The string passed in is
816 // assumed to be a malloc'd string buffer, and is freed by this function.
818 // This function returns true if the type has already been defined, but is
819 // allowed to be redefined in the specified context. If the name is a new name
820 // for the type plane, it is inserted and false is returned.
821 static bool setTypeName(const Type *T, std::string *NameStr) {
822 assert(!inFunctionScope() && "Can't give types function-local names!");
823 if (NameStr == 0) return false;
825 std::string Name(*NameStr); // Copy string
826 delete NameStr; // Free old string
828 // We don't allow assigning names to void type
829 if (T == Type::VoidTy) {
830 GenerateError("Can't assign name '" + Name + "' to the void type");
834 // Set the type name, checking for conflicts as we do so.
835 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
837 if (AlreadyExists) { // Inserting a name that is already defined???
838 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
839 assert(Existing && "Conflict but no matching type?!");
841 // There is only one case where this is allowed: when we are refining an
842 // opaque type. In this case, Existing will be an opaque type.
843 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
844 // We ARE replacing an opaque type!
845 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
849 // Otherwise, this is an attempt to redefine a type. That's okay if
850 // the redefinition is identical to the original. This will be so if
851 // Existing and T point to the same Type object. In this one case we
852 // allow the equivalent redefinition.
853 if (Existing == T) return true; // Yes, it's equal.
855 // Any other kind of (non-equivalent) redefinition is an error.
856 GenerateError("Redefinition of type named '" + Name + "' of type '" +
857 T->getDescription() + "'");
863 //===----------------------------------------------------------------------===//
864 // Code for handling upreferences in type names...
867 // TypeContains - Returns true if Ty directly contains E in it.
869 static bool TypeContains(const Type *Ty, const Type *E) {
870 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
871 E) != Ty->subtype_end();
876 // NestingLevel - The number of nesting levels that need to be popped before
877 // this type is resolved.
878 unsigned NestingLevel;
880 // LastContainedTy - This is the type at the current binding level for the
881 // type. Every time we reduce the nesting level, this gets updated.
882 const Type *LastContainedTy;
884 // UpRefTy - This is the actual opaque type that the upreference is
888 UpRefRecord(unsigned NL, OpaqueType *URTy)
889 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
893 // UpRefs - A list of the outstanding upreferences that need to be resolved.
894 static std::vector<UpRefRecord> UpRefs;
896 /// HandleUpRefs - Every time we finish a new layer of types, this function is
897 /// called. It loops through the UpRefs vector, which is a list of the
898 /// currently active types. For each type, if the up reference is contained in
899 /// the newly completed type, we decrement the level count. When the level
900 /// count reaches zero, the upreferenced type is the type that is passed in:
901 /// thus we can complete the cycle.
903 static PATypeHolder HandleUpRefs(const Type *ty) {
904 // If Ty isn't abstract, or if there are no up-references in it, then there is
905 // nothing to resolve here.
906 if (!ty->isAbstract() || UpRefs.empty()) return ty;
909 UR_OUT("Type '" << Ty->getDescription() <<
910 "' newly formed. Resolving upreferences.\n" <<
911 UpRefs.size() << " upreferences active!\n");
913 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
914 // to zero), we resolve them all together before we resolve them to Ty. At
915 // the end of the loop, if there is anything to resolve to Ty, it will be in
917 OpaqueType *TypeToResolve = 0;
919 for (unsigned i = 0; i != UpRefs.size(); ++i) {
920 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
921 << UpRefs[i].second->getDescription() << ") = "
922 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
923 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
924 // Decrement level of upreference
925 unsigned Level = --UpRefs[i].NestingLevel;
926 UpRefs[i].LastContainedTy = Ty;
927 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
928 if (Level == 0) { // Upreference should be resolved!
929 if (!TypeToResolve) {
930 TypeToResolve = UpRefs[i].UpRefTy;
932 UR_OUT(" * Resolving upreference for "
933 << UpRefs[i].second->getDescription() << "\n";
934 std::string OldName = UpRefs[i].UpRefTy->getDescription());
935 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
936 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
937 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
939 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
940 --i; // Do not skip the next element...
946 UR_OUT(" * Resolving upreference for "
947 << UpRefs[i].second->getDescription() << "\n";
948 std::string OldName = TypeToResolve->getDescription());
949 TypeToResolve->refineAbstractTypeTo(Ty);
955 //===----------------------------------------------------------------------===//
956 // RunVMAsmParser - Define an interface to this parser
957 //===----------------------------------------------------------------------===//
959 static Module* RunParser(Module * M);
961 Module *llvm::RunVMAsmParser(llvm::MemoryBuffer *MB) {
963 Module *M = RunParser(new Module(LLLgetFilename()));
971 llvm::Module *ModuleVal;
972 llvm::Function *FunctionVal;
973 llvm::BasicBlock *BasicBlockVal;
974 llvm::TerminatorInst *TermInstVal;
975 llvm::Instruction *InstVal;
976 llvm::Constant *ConstVal;
978 const llvm::Type *PrimType;
979 std::list<llvm::PATypeHolder> *TypeList;
980 llvm::PATypeHolder *TypeVal;
981 llvm::Value *ValueVal;
982 std::vector<llvm::Value*> *ValueList;
983 std::vector<unsigned> *ConstantList;
984 llvm::ArgListType *ArgList;
985 llvm::TypeWithAttrs TypeWithAttrs;
986 llvm::TypeWithAttrsList *TypeWithAttrsList;
987 llvm::ParamList *ParamList;
989 // Represent the RHS of PHI node
990 std::list<std::pair<llvm::Value*,
991 llvm::BasicBlock*> > *PHIList;
992 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
993 std::vector<llvm::Constant*> *ConstVector;
995 llvm::GlobalValue::LinkageTypes Linkage;
996 llvm::GlobalValue::VisibilityTypes Visibility;
997 llvm::ParameterAttributes ParamAttrs;
998 llvm::ParameterAttributes FunctionNotes;
999 llvm::APInt *APIntVal;
1004 llvm::APFloat *FPVal;
1007 std::string *StrVal; // This memory must be deleted
1008 llvm::ValID ValIDVal;
1010 llvm::Instruction::BinaryOps BinaryOpVal;
1011 llvm::Instruction::TermOps TermOpVal;
1012 llvm::Instruction::MemoryOps MemOpVal;
1013 llvm::Instruction::CastOps CastOpVal;
1014 llvm::Instruction::OtherOps OtherOpVal;
1015 llvm::ICmpInst::Predicate IPredicate;
1016 llvm::FCmpInst::Predicate FPredicate;
1019 %type <ModuleVal> Module
1020 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1021 %type <BasicBlockVal> BasicBlock InstructionList
1022 %type <TermInstVal> BBTerminatorInst
1023 %type <InstVal> Inst InstVal MemoryInst
1024 %type <ConstVal> ConstVal ConstExpr AliaseeRef
1025 %type <ConstVector> ConstVector
1026 %type <ArgList> ArgList ArgListH
1027 %type <PHIList> PHIList
1028 %type <ParamList> ParamList // For call param lists & GEP indices
1029 %type <ValueList> IndexList // For GEP indices
1030 %type <ConstantList> ConstantIndexList // For insertvalue/extractvalue indices
1031 %type <TypeList> TypeListI
1032 %type <TypeWithAttrsList> ArgTypeList ArgTypeListI
1033 %type <TypeWithAttrs> ArgType
1034 %type <JumpTable> JumpTable
1035 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1036 %type <BoolVal> ThreadLocal // 'thread_local' or not
1037 %type <BoolVal> OptVolatile // 'volatile' or not
1038 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1039 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
1040 %type <Linkage> GVInternalLinkage GVExternalLinkage
1041 %type <Linkage> FunctionDefineLinkage FunctionDeclareLinkage
1042 %type <Linkage> AliasLinkage
1043 %type <Visibility> GVVisibilityStyle
1045 // ValueRef - Unresolved reference to a definition or BB
1046 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1047 %type <ValueVal> ResolvedVal // <type> <valref> pair
1048 %type <ValueList> ReturnedVal
1049 // Tokens and types for handling constant integer values
1051 // ESINT64VAL - A negative number within long long range
1052 %token <SInt64Val> ESINT64VAL
1054 // EUINT64VAL - A positive number within uns. long long range
1055 %token <UInt64Val> EUINT64VAL
1057 // ESAPINTVAL - A negative number with arbitrary precision
1058 %token <APIntVal> ESAPINTVAL
1060 // EUAPINTVAL - A positive number with arbitrary precision
1061 %token <APIntVal> EUAPINTVAL
1063 %token <UIntVal> LOCALVAL_ID GLOBALVAL_ID // %123 @123
1064 %token <FPVal> FPVAL // Float or Double constant
1066 // Built in types...
1067 %type <TypeVal> Types ResultTypes
1068 %type <PrimType> IntType FPType PrimType // Classifications
1069 %token <PrimType> VOID INTTYPE
1070 %token <PrimType> FLOAT DOUBLE X86_FP80 FP128 PPC_FP128 LABEL
1074 %token<StrVal> LOCALVAR GLOBALVAR LABELSTR
1075 %token<StrVal> STRINGCONSTANT ATSTRINGCONSTANT PCTSTRINGCONSTANT
1076 %type <StrVal> LocalName OptLocalName OptLocalAssign
1077 %type <StrVal> GlobalName OptGlobalAssign GlobalAssign
1078 %type <StrVal> OptSection SectionString OptGC
1080 %type <UIntVal> OptAlign OptCAlign OptAddrSpace
1082 %token ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1083 %token DECLARE DEFINE GLOBAL CONSTANT SECTION ALIAS VOLATILE THREAD_LOCAL
1084 %token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
1085 %token DLLIMPORT DLLEXPORT EXTERN_WEAK COMMON
1086 %token OPAQUE EXTERNAL TARGET TRIPLE ALIGN ADDRSPACE
1087 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1088 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1089 %token X86_SSECALLCC_TOK
1091 %type <UIntVal> OptCallingConv LocalNumber
1092 %type <ParamAttrs> OptParamAttrs ParamAttr
1093 %type <ParamAttrs> OptFuncAttrs FuncAttr
1094 %type <ParamAttrs> OptFuncNotes FuncNote
1095 %type <ParamAttrs> FuncNoteList
1097 // Basic Block Terminating Operators
1098 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1101 %type <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
1102 %token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1103 %token <BinaryOpVal> SHL LSHR ASHR
1105 %token <OtherOpVal> ICMP FCMP VICMP VFCMP
1106 %type <IPredicate> IPredicates
1107 %type <FPredicate> FPredicates
1108 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1109 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1111 // Memory Instructions
1112 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1115 %type <CastOpVal> CastOps
1116 %token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1117 %token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1120 %token <OtherOpVal> PHI_TOK SELECT VAARG
1121 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1122 %token <OtherOpVal> GETRESULT
1123 %token <OtherOpVal> EXTRACTVALUE INSERTVALUE
1125 // Function Attributes
1126 %token SIGNEXT ZEROEXT NORETURN INREG SRET NOUNWIND NOALIAS BYVAL NEST
1127 %token READNONE READONLY GC
1130 %token FNNOTE INLINE ALWAYS NEVER OPTIMIZEFORSIZE
1132 // Visibility Styles
1133 %token DEFAULT HIDDEN PROTECTED
1139 // Operations that are notably excluded from this list include:
1140 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1142 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1143 LogicalOps : SHL | LSHR | ASHR | AND | OR | XOR;
1144 CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1145 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1148 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1149 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1150 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1151 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1152 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1156 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1157 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1158 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1159 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1160 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1161 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1162 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1163 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1164 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1167 // These are some types that allow classification if we only want a particular
1168 // thing... for example, only a signed, unsigned, or integral type.
1170 FPType : FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80;
1172 LocalName : LOCALVAR | STRINGCONSTANT | PCTSTRINGCONSTANT ;
1173 OptLocalName : LocalName | /*empty*/ { $$ = 0; };
1175 OptAddrSpace : ADDRSPACE '(' EUINT64VAL ')' { $$=$3; }
1176 | /*empty*/ { $$=0; };
1178 /// OptLocalAssign - Value producing statements have an optional assignment
1180 OptLocalAssign : LocalName '=' {
1189 LocalNumber : LOCALVAL_ID '=' {
1195 GlobalName : GLOBALVAR | ATSTRINGCONSTANT ;
1197 OptGlobalAssign : GlobalAssign
1203 GlobalAssign : GlobalName '=' {
1209 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1210 | WEAK { $$ = GlobalValue::WeakLinkage; }
1211 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1212 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1213 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1214 | COMMON { $$ = GlobalValue::CommonLinkage; }
1218 : DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1219 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1220 | EXTERNAL { $$ = GlobalValue::ExternalLinkage; }
1224 : /*empty*/ { $$ = GlobalValue::DefaultVisibility; }
1225 | DEFAULT { $$ = GlobalValue::DefaultVisibility; }
1226 | HIDDEN { $$ = GlobalValue::HiddenVisibility; }
1227 | PROTECTED { $$ = GlobalValue::ProtectedVisibility; }
1230 FunctionDeclareLinkage
1231 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1232 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1233 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1236 FunctionDefineLinkage
1237 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1238 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1239 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1240 | WEAK { $$ = GlobalValue::WeakLinkage; }
1241 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1245 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1246 | WEAK { $$ = GlobalValue::WeakLinkage; }
1247 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1250 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1251 CCC_TOK { $$ = CallingConv::C; } |
1252 FASTCC_TOK { $$ = CallingConv::Fast; } |
1253 COLDCC_TOK { $$ = CallingConv::Cold; } |
1254 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1255 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1256 X86_SSECALLCC_TOK { $$ = CallingConv::X86_SSECall; } |
1258 if ((unsigned)$2 != $2)
1259 GEN_ERROR("Calling conv too large");
1264 ParamAttr : ZEROEXT { $$ = ParamAttr::ZExt; }
1265 | ZEXT { $$ = ParamAttr::ZExt; }
1266 | SIGNEXT { $$ = ParamAttr::SExt; }
1267 | SEXT { $$ = ParamAttr::SExt; }
1268 | INREG { $$ = ParamAttr::InReg; }
1269 | SRET { $$ = ParamAttr::StructRet; }
1270 | NOALIAS { $$ = ParamAttr::NoAlias; }
1271 | BYVAL { $$ = ParamAttr::ByVal; }
1272 | NEST { $$ = ParamAttr::Nest; }
1273 | ALIGN EUINT64VAL { $$ =
1274 ParamAttr::constructAlignmentFromInt($2); }
1277 OptParamAttrs : /* empty */ { $$ = ParamAttr::None; }
1278 | OptParamAttrs ParamAttr {
1283 FuncAttr : NORETURN { $$ = ParamAttr::NoReturn; }
1284 | NOUNWIND { $$ = ParamAttr::NoUnwind; }
1285 | INREG { $$ = ParamAttr::InReg; }
1286 | ZEROEXT { $$ = ParamAttr::ZExt; }
1287 | SIGNEXT { $$ = ParamAttr::SExt; }
1288 | READNONE { $$ = ParamAttr::ReadNone; }
1289 | READONLY { $$ = ParamAttr::ReadOnly; }
1292 OptFuncAttrs : /* empty */ { $$ = ParamAttr::None; }
1293 | OptFuncAttrs FuncAttr {
1298 FuncNoteList : FuncNote { $$ = $1; }
1299 | FuncNoteList ',' FuncNote {
1300 unsigned tmp = $1 | $3;
1301 if ($3 == ParamAttr::FN_NOTE_NoInline
1302 && ($1 & ParamAttr::FN_NOTE_AlwaysInline))
1303 GEN_ERROR("Function Notes may include only one inline notes!")
1304 if ($3 == ParamAttr::FN_NOTE_AlwaysInline
1305 && ($1 & ParamAttr::FN_NOTE_NoInline))
1306 GEN_ERROR("Function Notes may include only one inline notes!")
1312 FuncNote : INLINE '=' NEVER { $$ = ParamAttr::FN_NOTE_NoInline; }
1313 | INLINE '=' ALWAYS { $$ = ParamAttr::FN_NOTE_AlwaysInline; }
1314 | OPTIMIZEFORSIZE { $$ = ParamAttr::FN_NOTE_OptimizeForSize; }
1317 OptFuncNotes : /* empty */ { $$ = ParamAttr::FN_NOTE_None; }
1318 | FNNOTE '(' FuncNoteList ')' {
1323 OptGC : /* empty */ { $$ = 0; }
1324 | GC STRINGCONSTANT {
1329 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1330 // a comma before it.
1331 OptAlign : /*empty*/ { $$ = 0; } |
1334 if ($$ != 0 && !isPowerOf2_32($$))
1335 GEN_ERROR("Alignment must be a power of two");
1338 OptCAlign : /*empty*/ { $$ = 0; } |
1339 ',' ALIGN EUINT64VAL {
1341 if ($$ != 0 && !isPowerOf2_32($$))
1342 GEN_ERROR("Alignment must be a power of two");
1348 SectionString : SECTION STRINGCONSTANT {
1349 for (unsigned i = 0, e = $2->length(); i != e; ++i)
1350 if ((*$2)[i] == '"' || (*$2)[i] == '\\')
1351 GEN_ERROR("Invalid character in section name");
1356 OptSection : /*empty*/ { $$ = 0; } |
1357 SectionString { $$ = $1; };
1359 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1360 // is set to be the global we are processing.
1362 GlobalVarAttributes : /* empty */ {} |
1363 ',' GlobalVarAttribute GlobalVarAttributes {};
1364 GlobalVarAttribute : SectionString {
1365 CurGV->setSection(*$1);
1369 | ALIGN EUINT64VAL {
1370 if ($2 != 0 && !isPowerOf2_32($2))
1371 GEN_ERROR("Alignment must be a power of two");
1372 CurGV->setAlignment($2);
1376 //===----------------------------------------------------------------------===//
1377 // Types includes all predefined types... except void, because it can only be
1378 // used in specific contexts (function returning void for example).
1380 // Derived types are added later...
1382 PrimType : INTTYPE | FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80 | LABEL ;
1386 $$ = new PATypeHolder(OpaqueType::get());
1390 $$ = new PATypeHolder($1);
1393 | Types OptAddrSpace '*' { // Pointer type?
1394 if (*$1 == Type::LabelTy)
1395 GEN_ERROR("Cannot form a pointer to a basic block");
1396 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1, $2)));
1400 | SymbolicValueRef { // Named types are also simple types...
1401 const Type* tmp = getTypeVal($1);
1403 $$ = new PATypeHolder(tmp);
1405 | '\\' EUINT64VAL { // Type UpReference
1406 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range");
1407 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1408 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1409 $$ = new PATypeHolder(OT);
1410 UR_OUT("New Upreference!\n");
1413 | Types '(' ArgTypeListI ')' OptFuncAttrs {
1414 // Allow but ignore attributes on function types; this permits auto-upgrade.
1415 // FIXME: remove in LLVM 3.0.
1416 const Type *RetTy = *$1;
1417 if (!FunctionType::isValidReturnType(RetTy))
1418 GEN_ERROR("Invalid result type for LLVM function");
1420 std::vector<const Type*> Params;
1421 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1422 for (; I != E; ++I ) {
1423 const Type *Ty = I->Ty->get();
1424 Params.push_back(Ty);
1427 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1428 if (isVarArg) Params.pop_back();
1430 for (unsigned i = 0; i != Params.size(); ++i)
1431 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1432 GEN_ERROR("Function arguments must be value types!");
1436 FunctionType *FT = FunctionType::get(RetTy, Params, isVarArg);
1437 delete $3; // Delete the argument list
1438 delete $1; // Delete the return type handle
1439 $$ = new PATypeHolder(HandleUpRefs(FT));
1442 | VOID '(' ArgTypeListI ')' OptFuncAttrs {
1443 // Allow but ignore attributes on function types; this permits auto-upgrade.
1444 // FIXME: remove in LLVM 3.0.
1445 std::vector<const Type*> Params;
1446 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1447 for ( ; I != E; ++I ) {
1448 const Type* Ty = I->Ty->get();
1449 Params.push_back(Ty);
1452 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1453 if (isVarArg) Params.pop_back();
1455 for (unsigned i = 0; i != Params.size(); ++i)
1456 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1457 GEN_ERROR("Function arguments must be value types!");
1461 FunctionType *FT = FunctionType::get($1, Params, isVarArg);
1462 delete $3; // Delete the argument list
1463 $$ = new PATypeHolder(HandleUpRefs(FT));
1467 | '[' EUINT64VAL 'x' Types ']' { // Sized array type?
1468 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, $2)));
1472 | '<' EUINT64VAL 'x' Types '>' { // Vector type?
1473 const llvm::Type* ElemTy = $4->get();
1474 if ((unsigned)$2 != $2)
1475 GEN_ERROR("Unsigned result not equal to signed result");
1476 if (!ElemTy->isFloatingPoint() && !ElemTy->isInteger())
1477 GEN_ERROR("Element type of a VectorType must be primitive");
1478 $$ = new PATypeHolder(HandleUpRefs(VectorType::get(*$4, (unsigned)$2)));
1482 | '{' TypeListI '}' { // Structure type?
1483 std::vector<const Type*> Elements;
1484 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1485 E = $2->end(); I != E; ++I)
1486 Elements.push_back(*I);
1488 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1492 | '{' '}' { // Empty structure type?
1493 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1496 | '<' '{' TypeListI '}' '>' {
1497 std::vector<const Type*> Elements;
1498 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1499 E = $3->end(); I != E; ++I)
1500 Elements.push_back(*I);
1502 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1506 | '<' '{' '}' '>' { // Empty structure type?
1507 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1513 : Types OptParamAttrs {
1514 // Allow but ignore attributes on function types; this permits auto-upgrade.
1515 // FIXME: remove in LLVM 3.0.
1517 $$.Attrs = ParamAttr::None;
1523 if (!UpRefs.empty())
1524 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1525 if (!(*$1)->isFirstClassType() && !isa<StructType>($1->get()))
1526 GEN_ERROR("LLVM functions cannot return aggregate types");
1530 $$ = new PATypeHolder(Type::VoidTy);
1534 ArgTypeList : ArgType {
1535 $$ = new TypeWithAttrsList();
1539 | ArgTypeList ',' ArgType {
1540 ($$=$1)->push_back($3);
1547 | ArgTypeList ',' DOTDOTDOT {
1549 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1550 TWA.Ty = new PATypeHolder(Type::VoidTy);
1555 $$ = new TypeWithAttrsList;
1556 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1557 TWA.Ty = new PATypeHolder(Type::VoidTy);
1562 $$ = new TypeWithAttrsList();
1566 // TypeList - Used for struct declarations and as a basis for function type
1567 // declaration type lists
1570 $$ = new std::list<PATypeHolder>();
1575 | TypeListI ',' Types {
1576 ($$=$1)->push_back(*$3);
1581 // ConstVal - The various declarations that go into the constant pool. This
1582 // production is used ONLY to represent constants that show up AFTER a 'const',
1583 // 'constant' or 'global' token at global scope. Constants that can be inlined
1584 // into other expressions (such as integers and constexprs) are handled by the
1585 // ResolvedVal, ValueRef and ConstValueRef productions.
1587 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1588 if (!UpRefs.empty())
1589 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1590 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1592 GEN_ERROR("Cannot make array constant with type: '" +
1593 (*$1)->getDescription() + "'");
1594 const Type *ETy = ATy->getElementType();
1595 uint64_t NumElements = ATy->getNumElements();
1597 // Verify that we have the correct size...
1598 if (NumElements != uint64_t(-1) && NumElements != $3->size())
1599 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1600 utostr($3->size()) + " arguments, but has size of " +
1601 utostr(NumElements) + "");
1603 // Verify all elements are correct type!
1604 for (unsigned i = 0; i < $3->size(); i++) {
1605 if (ETy != (*$3)[i]->getType())
1606 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1607 ETy->getDescription() +"' as required!\nIt is of type '"+
1608 (*$3)[i]->getType()->getDescription() + "'.");
1611 $$ = ConstantArray::get(ATy, *$3);
1612 delete $1; delete $3;
1616 if (!UpRefs.empty())
1617 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1618 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1620 GEN_ERROR("Cannot make array constant with type: '" +
1621 (*$1)->getDescription() + "'");
1623 uint64_t NumElements = ATy->getNumElements();
1624 if (NumElements != uint64_t(-1) && NumElements != 0)
1625 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1626 " arguments, but has size of " + utostr(NumElements) +"");
1627 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1631 | Types 'c' STRINGCONSTANT {
1632 if (!UpRefs.empty())
1633 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1634 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1636 GEN_ERROR("Cannot make array constant with type: '" +
1637 (*$1)->getDescription() + "'");
1639 uint64_t NumElements = ATy->getNumElements();
1640 const Type *ETy = ATy->getElementType();
1641 if (NumElements != uint64_t(-1) && NumElements != $3->length())
1642 GEN_ERROR("Can't build string constant of size " +
1643 utostr($3->length()) +
1644 " when array has size " + utostr(NumElements) + "");
1645 std::vector<Constant*> Vals;
1646 if (ETy == Type::Int8Ty) {
1647 for (uint64_t i = 0; i < $3->length(); ++i)
1648 Vals.push_back(ConstantInt::get(ETy, (*$3)[i]));
1651 GEN_ERROR("Cannot build string arrays of non byte sized elements");
1654 $$ = ConstantArray::get(ATy, Vals);
1658 | Types '<' ConstVector '>' { // Nonempty unsized arr
1659 if (!UpRefs.empty())
1660 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1661 const VectorType *PTy = dyn_cast<VectorType>($1->get());
1663 GEN_ERROR("Cannot make packed constant with type: '" +
1664 (*$1)->getDescription() + "'");
1665 const Type *ETy = PTy->getElementType();
1666 unsigned NumElements = PTy->getNumElements();
1668 // Verify that we have the correct size...
1669 if (NumElements != unsigned(-1) && NumElements != (unsigned)$3->size())
1670 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1671 utostr($3->size()) + " arguments, but has size of " +
1672 utostr(NumElements) + "");
1674 // Verify all elements are correct type!
1675 for (unsigned i = 0; i < $3->size(); i++) {
1676 if (ETy != (*$3)[i]->getType())
1677 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1678 ETy->getDescription() +"' as required!\nIt is of type '"+
1679 (*$3)[i]->getType()->getDescription() + "'.");
1682 $$ = ConstantVector::get(PTy, *$3);
1683 delete $1; delete $3;
1686 | Types '{' ConstVector '}' {
1687 const StructType *STy = dyn_cast<StructType>($1->get());
1689 GEN_ERROR("Cannot make struct constant with type: '" +
1690 (*$1)->getDescription() + "'");
1692 if ($3->size() != STy->getNumContainedTypes())
1693 GEN_ERROR("Illegal number of initializers for structure type");
1695 // Check to ensure that constants are compatible with the type initializer!
1696 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1697 if ((*$3)[i]->getType() != STy->getElementType(i))
1698 GEN_ERROR("Expected type '" +
1699 STy->getElementType(i)->getDescription() +
1700 "' for element #" + utostr(i) +
1701 " of structure initializer");
1703 // Check to ensure that Type is not packed
1704 if (STy->isPacked())
1705 GEN_ERROR("Unpacked Initializer to vector type '" +
1706 STy->getDescription() + "'");
1708 $$ = ConstantStruct::get(STy, *$3);
1709 delete $1; delete $3;
1713 if (!UpRefs.empty())
1714 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1715 const StructType *STy = dyn_cast<StructType>($1->get());
1717 GEN_ERROR("Cannot make struct constant with type: '" +
1718 (*$1)->getDescription() + "'");
1720 if (STy->getNumContainedTypes() != 0)
1721 GEN_ERROR("Illegal number of initializers for structure type");
1723 // Check to ensure that Type is not packed
1724 if (STy->isPacked())
1725 GEN_ERROR("Unpacked Initializer to vector type '" +
1726 STy->getDescription() + "'");
1728 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1732 | Types '<' '{' ConstVector '}' '>' {
1733 const StructType *STy = dyn_cast<StructType>($1->get());
1735 GEN_ERROR("Cannot make struct constant with type: '" +
1736 (*$1)->getDescription() + "'");
1738 if ($4->size() != STy->getNumContainedTypes())
1739 GEN_ERROR("Illegal number of initializers for structure type");
1741 // Check to ensure that constants are compatible with the type initializer!
1742 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1743 if ((*$4)[i]->getType() != STy->getElementType(i))
1744 GEN_ERROR("Expected type '" +
1745 STy->getElementType(i)->getDescription() +
1746 "' for element #" + utostr(i) +
1747 " of structure initializer");
1749 // Check to ensure that Type is packed
1750 if (!STy->isPacked())
1751 GEN_ERROR("Vector initializer to non-vector type '" +
1752 STy->getDescription() + "'");
1754 $$ = ConstantStruct::get(STy, *$4);
1755 delete $1; delete $4;
1758 | Types '<' '{' '}' '>' {
1759 if (!UpRefs.empty())
1760 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1761 const StructType *STy = dyn_cast<StructType>($1->get());
1763 GEN_ERROR("Cannot make struct constant with type: '" +
1764 (*$1)->getDescription() + "'");
1766 if (STy->getNumContainedTypes() != 0)
1767 GEN_ERROR("Illegal number of initializers for structure type");
1769 // Check to ensure that Type is packed
1770 if (!STy->isPacked())
1771 GEN_ERROR("Vector initializer to non-vector type '" +
1772 STy->getDescription() + "'");
1774 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1779 if (!UpRefs.empty())
1780 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1781 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1783 GEN_ERROR("Cannot make null pointer constant with type: '" +
1784 (*$1)->getDescription() + "'");
1786 $$ = ConstantPointerNull::get(PTy);
1791 if (!UpRefs.empty())
1792 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1793 $$ = UndefValue::get($1->get());
1797 | Types SymbolicValueRef {
1798 if (!UpRefs.empty())
1799 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1800 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1802 GEN_ERROR("Global const reference must be a pointer type " + (*$1)->getDescription());
1804 // ConstExprs can exist in the body of a function, thus creating
1805 // GlobalValues whenever they refer to a variable. Because we are in
1806 // the context of a function, getExistingVal will search the functions
1807 // symbol table instead of the module symbol table for the global symbol,
1808 // which throws things all off. To get around this, we just tell
1809 // getExistingVal that we are at global scope here.
1811 Function *SavedCurFn = CurFun.CurrentFunction;
1812 CurFun.CurrentFunction = 0;
1814 Value *V = getExistingVal(Ty, $2);
1817 CurFun.CurrentFunction = SavedCurFn;
1819 // If this is an initializer for a constant pointer, which is referencing a
1820 // (currently) undefined variable, create a stub now that shall be replaced
1821 // in the future with the right type of variable.
1824 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1825 const PointerType *PT = cast<PointerType>(Ty);
1827 // First check to see if the forward references value is already created!
1828 PerModuleInfo::GlobalRefsType::iterator I =
1829 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1831 if (I != CurModule.GlobalRefs.end()) {
1832 V = I->second; // Placeholder already exists, use it...
1836 if ($2.Type == ValID::GlobalName)
1837 Name = $2.getName();
1838 else if ($2.Type != ValID::GlobalID)
1839 GEN_ERROR("Invalid reference to global");
1841 // Create the forward referenced global.
1843 if (const FunctionType *FTy =
1844 dyn_cast<FunctionType>(PT->getElementType())) {
1845 GV = Function::Create(FTy, GlobalValue::ExternalWeakLinkage, Name,
1846 CurModule.CurrentModule);
1848 GV = new GlobalVariable(PT->getElementType(), false,
1849 GlobalValue::ExternalWeakLinkage, 0,
1850 Name, CurModule.CurrentModule);
1853 // Keep track of the fact that we have a forward ref to recycle it
1854 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1859 $$ = cast<GlobalValue>(V);
1860 delete $1; // Free the type handle
1864 if (!UpRefs.empty())
1865 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1866 if ($1->get() != $2->getType())
1867 GEN_ERROR("Mismatched types for constant expression: " +
1868 (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1873 | Types ZEROINITIALIZER {
1874 if (!UpRefs.empty())
1875 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1876 const Type *Ty = $1->get();
1877 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1878 GEN_ERROR("Cannot create a null initialized value of this type");
1879 $$ = Constant::getNullValue(Ty);
1883 | IntType ESINT64VAL { // integral constants
1884 if (!ConstantInt::isValueValidForType($1, $2))
1885 GEN_ERROR("Constant value doesn't fit in type");
1886 $$ = ConstantInt::get($1, $2, true);
1889 | IntType ESAPINTVAL { // arbitrary precision integer constants
1890 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1891 if ($2->getBitWidth() > BitWidth) {
1892 GEN_ERROR("Constant value does not fit in type");
1894 $2->sextOrTrunc(BitWidth);
1895 $$ = ConstantInt::get(*$2);
1899 | IntType EUINT64VAL { // integral constants
1900 if (!ConstantInt::isValueValidForType($1, $2))
1901 GEN_ERROR("Constant value doesn't fit in type");
1902 $$ = ConstantInt::get($1, $2, false);
1905 | IntType EUAPINTVAL { // arbitrary precision integer constants
1906 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1907 if ($2->getBitWidth() > BitWidth) {
1908 GEN_ERROR("Constant value does not fit in type");
1910 $2->zextOrTrunc(BitWidth);
1911 $$ = ConstantInt::get(*$2);
1915 | INTTYPE TRUETOK { // Boolean constants
1916 if (cast<IntegerType>($1)->getBitWidth() != 1)
1917 GEN_ERROR("Constant true must have type i1");
1918 $$ = ConstantInt::getTrue();
1921 | INTTYPE FALSETOK { // Boolean constants
1922 if (cast<IntegerType>($1)->getBitWidth() != 1)
1923 GEN_ERROR("Constant false must have type i1");
1924 $$ = ConstantInt::getFalse();
1927 | FPType FPVAL { // Floating point constants
1928 if (!ConstantFP::isValueValidForType($1, *$2))
1929 GEN_ERROR("Floating point constant invalid for type");
1930 // Lexer has no type info, so builds all float and double FP constants
1931 // as double. Fix this here. Long double is done right.
1932 if (&$2->getSemantics()==&APFloat::IEEEdouble && $1==Type::FloatTy)
1933 $2->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
1934 $$ = ConstantFP::get(*$2);
1940 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1941 if (!UpRefs.empty())
1942 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1944 const Type *DestTy = $5->get();
1945 if (!CastInst::castIsValid($1, $3, DestTy))
1946 GEN_ERROR("invalid cast opcode for cast from '" +
1947 Val->getType()->getDescription() + "' to '" +
1948 DestTy->getDescription() + "'");
1949 $$ = ConstantExpr::getCast($1, $3, DestTy);
1952 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1953 if (!isa<PointerType>($3->getType()))
1954 GEN_ERROR("GetElementPtr requires a pointer operand");
1957 GetElementPtrInst::getIndexedType($3->getType(), $4->begin(), $4->end());
1959 GEN_ERROR("Index list invalid for constant getelementptr");
1961 SmallVector<Constant*, 8> IdxVec;
1962 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1963 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1964 IdxVec.push_back(C);
1966 GEN_ERROR("Indices to constant getelementptr must be constants");
1970 $$ = ConstantExpr::getGetElementPtr($3, &IdxVec[0], IdxVec.size());
1973 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1974 if ($3->getType() != Type::Int1Ty)
1975 GEN_ERROR("Select condition must be of boolean type");
1976 if ($5->getType() != $7->getType())
1977 GEN_ERROR("Select operand types must match");
1978 $$ = ConstantExpr::getSelect($3, $5, $7);
1981 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1982 if ($3->getType() != $5->getType())
1983 GEN_ERROR("Binary operator types must match");
1985 $$ = ConstantExpr::get($1, $3, $5);
1987 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1988 if ($3->getType() != $5->getType())
1989 GEN_ERROR("Logical operator types must match");
1990 if (!$3->getType()->isInteger()) {
1991 if (!isa<VectorType>($3->getType()) ||
1992 !cast<VectorType>($3->getType())->getElementType()->isInteger())
1993 GEN_ERROR("Logical operator requires integral operands");
1995 $$ = ConstantExpr::get($1, $3, $5);
1998 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1999 if ($4->getType() != $6->getType())
2000 GEN_ERROR("icmp operand types must match");
2001 $$ = ConstantExpr::getICmp($2, $4, $6);
2003 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
2004 if ($4->getType() != $6->getType())
2005 GEN_ERROR("fcmp operand types must match");
2006 $$ = ConstantExpr::getFCmp($2, $4, $6);
2008 | VICMP IPredicates '(' ConstVal ',' ConstVal ')' {
2009 if ($4->getType() != $6->getType())
2010 GEN_ERROR("vicmp operand types must match");
2011 $$ = ConstantExpr::getVICmp($2, $4, $6);
2013 | VFCMP FPredicates '(' ConstVal ',' ConstVal ')' {
2014 if ($4->getType() != $6->getType())
2015 GEN_ERROR("vfcmp operand types must match");
2016 $$ = ConstantExpr::getVFCmp($2, $4, $6);
2018 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
2019 if (!ExtractElementInst::isValidOperands($3, $5))
2020 GEN_ERROR("Invalid extractelement operands");
2021 $$ = ConstantExpr::getExtractElement($3, $5);
2024 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2025 if (!InsertElementInst::isValidOperands($3, $5, $7))
2026 GEN_ERROR("Invalid insertelement operands");
2027 $$ = ConstantExpr::getInsertElement($3, $5, $7);
2030 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2031 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
2032 GEN_ERROR("Invalid shufflevector operands");
2033 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
2036 | EXTRACTVALUE '(' ConstVal ConstantIndexList ')' {
2037 if (!isa<StructType>($3->getType()) && !isa<ArrayType>($3->getType()))
2038 GEN_ERROR("ExtractValue requires an aggregate operand");
2040 $$ = ConstantExpr::getExtractValue($3, &(*$4)[0], $4->size());
2044 | INSERTVALUE '(' ConstVal ',' ConstVal ConstantIndexList ')' {
2045 if (!isa<StructType>($3->getType()) && !isa<ArrayType>($3->getType()))
2046 GEN_ERROR("InsertValue requires an aggregate operand");
2048 $$ = ConstantExpr::getInsertValue($3, $5, &(*$6)[0], $6->size());
2054 // ConstVector - A list of comma separated constants.
2055 ConstVector : ConstVector ',' ConstVal {
2056 ($$ = $1)->push_back($3);
2060 $$ = new std::vector<Constant*>();
2066 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
2067 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
2070 ThreadLocal : THREAD_LOCAL { $$ = true; } | { $$ = false; };
2072 // AliaseeRef - Match either GlobalValue or bitcast to GlobalValue.
2073 AliaseeRef : ResultTypes SymbolicValueRef {
2074 const Type* VTy = $1->get();
2075 Value *V = getVal(VTy, $2);
2077 GlobalValue* Aliasee = dyn_cast<GlobalValue>(V);
2079 GEN_ERROR("Aliases can be created only to global values");
2085 | BITCAST '(' AliaseeRef TO Types ')' {
2087 const Type *DestTy = $5->get();
2088 if (!CastInst::castIsValid($1, $3, DestTy))
2089 GEN_ERROR("invalid cast opcode for cast from '" +
2090 Val->getType()->getDescription() + "' to '" +
2091 DestTy->getDescription() + "'");
2093 $$ = ConstantExpr::getCast($1, $3, DestTy);
2098 //===----------------------------------------------------------------------===//
2099 // Rules to match Modules
2100 //===----------------------------------------------------------------------===//
2102 // Module rule: Capture the result of parsing the whole file into a result
2107 $$ = ParserResult = CurModule.CurrentModule;
2108 CurModule.ModuleDone();
2112 $$ = ParserResult = CurModule.CurrentModule;
2113 CurModule.ModuleDone();
2120 | DefinitionList Definition
2124 : DEFINE { CurFun.isDeclare = false; } Function {
2125 CurFun.FunctionDone();
2128 | DECLARE { CurFun.isDeclare = true; } FunctionProto {
2131 | MODULE ASM_TOK AsmBlock {
2134 | OptLocalAssign TYPE Types {
2135 if (!UpRefs.empty())
2136 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2137 // Eagerly resolve types. This is not an optimization, this is a
2138 // requirement that is due to the fact that we could have this:
2140 // %list = type { %list * }
2141 // %list = type { %list * } ; repeated type decl
2143 // If types are not resolved eagerly, then the two types will not be
2144 // determined to be the same type!
2146 ResolveTypeTo($1, *$3);
2148 if (!setTypeName(*$3, $1) && !$1) {
2150 // If this is a named type that is not a redefinition, add it to the slot
2152 CurModule.Types.push_back(*$3);
2158 | OptLocalAssign TYPE VOID {
2159 ResolveTypeTo($1, $3);
2161 if (!setTypeName($3, $1) && !$1) {
2163 // If this is a named type that is not a redefinition, add it to the slot
2165 CurModule.Types.push_back($3);
2169 | OptGlobalAssign GVVisibilityStyle ThreadLocal GlobalType ConstVal
2171 /* "Externally Visible" Linkage */
2173 GEN_ERROR("Global value initializer is not a constant");
2174 CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
2175 $2, $4, $5->getType(), $5, $3, $6);
2177 } GlobalVarAttributes {
2180 | OptGlobalAssign GVInternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2181 ConstVal OptAddrSpace {
2183 GEN_ERROR("Global value initializer is not a constant");
2184 CurGV = ParseGlobalVariable($1, $2, $3, $5, $6->getType(), $6, $4, $7);
2186 } GlobalVarAttributes {
2189 | OptGlobalAssign GVExternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2190 Types OptAddrSpace {
2191 if (!UpRefs.empty())
2192 GEN_ERROR("Invalid upreference in type: " + (*$6)->getDescription());
2193 CurGV = ParseGlobalVariable($1, $2, $3, $5, *$6, 0, $4, $7);
2196 } GlobalVarAttributes {
2200 | OptGlobalAssign GVVisibilityStyle ALIAS AliasLinkage AliaseeRef {
2207 GEN_ERROR("Alias name cannot be empty");
2209 Constant* Aliasee = $5;
2211 GEN_ERROR(std::string("Invalid aliasee for alias: ") + Name);
2213 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(), $4, Name, Aliasee,
2214 CurModule.CurrentModule);
2215 GA->setVisibility($2);
2216 InsertValue(GA, CurModule.Values);
2219 // If there was a forward reference of this alias, resolve it now.
2223 ID = ValID::createGlobalName(Name);
2225 ID = ValID::createGlobalID(CurModule.Values.size()-1);
2227 if (GlobalValue *FWGV =
2228 CurModule.GetForwardRefForGlobal(GA->getType(), ID)) {
2229 // Replace uses of the fwdref with the actual alias.
2230 FWGV->replaceAllUsesWith(GA);
2231 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(FWGV))
2232 GV->eraseFromParent();
2234 cast<Function>(FWGV)->eraseFromParent();
2240 | TARGET TargetDefinition {
2243 | DEPLIBS '=' LibrariesDefinition {
2249 AsmBlock : STRINGCONSTANT {
2250 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2251 if (AsmSoFar.empty())
2252 CurModule.CurrentModule->setModuleInlineAsm(*$1);
2254 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+*$1);
2259 TargetDefinition : TRIPLE '=' STRINGCONSTANT {
2260 CurModule.CurrentModule->setTargetTriple(*$3);
2263 | DATALAYOUT '=' STRINGCONSTANT {
2264 CurModule.CurrentModule->setDataLayout(*$3);
2268 LibrariesDefinition : '[' LibList ']';
2270 LibList : LibList ',' STRINGCONSTANT {
2271 CurModule.CurrentModule->addLibrary(*$3);
2276 CurModule.CurrentModule->addLibrary(*$1);
2280 | /* empty: end of list */ {
2285 //===----------------------------------------------------------------------===//
2286 // Rules to match Function Headers
2287 //===----------------------------------------------------------------------===//
2289 ArgListH : ArgListH ',' Types OptParamAttrs OptLocalName {
2290 if (!UpRefs.empty())
2291 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2292 if (!(*$3)->isFirstClassType())
2293 GEN_ERROR("Argument types must be first-class");
2294 ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
2299 | Types OptParamAttrs OptLocalName {
2300 if (!UpRefs.empty())
2301 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2302 if (!(*$1)->isFirstClassType())
2303 GEN_ERROR("Argument types must be first-class");
2304 ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2305 $$ = new ArgListType;
2310 ArgList : ArgListH {
2314 | ArgListH ',' DOTDOTDOT {
2316 struct ArgListEntry E;
2317 E.Ty = new PATypeHolder(Type::VoidTy);
2319 E.Attrs = ParamAttr::None;
2324 $$ = new ArgListType;
2325 struct ArgListEntry E;
2326 E.Ty = new PATypeHolder(Type::VoidTy);
2328 E.Attrs = ParamAttr::None;
2337 FunctionHeaderH : OptCallingConv ResultTypes GlobalName '(' ArgList ')'
2338 OptFuncAttrs OptSection OptAlign OptGC OptFuncNotes {
2339 std::string FunctionName(*$3);
2340 delete $3; // Free strdup'd memory!
2342 // Check the function result for abstractness if this is a define. We should
2343 // have no abstract types at this point
2344 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($2))
2345 GEN_ERROR("Reference to abstract result: "+ $2->get()->getDescription());
2347 if (!FunctionType::isValidReturnType(*$2))
2348 GEN_ERROR("Invalid result type for LLVM function");
2350 std::vector<const Type*> ParamTypeList;
2351 SmallVector<ParamAttrsWithIndex, 8> Attrs;
2352 if ($7 != ParamAttr::None)
2353 Attrs.push_back(ParamAttrsWithIndex::get(0, $7));
2354 if ($5) { // If there are arguments...
2356 for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I, ++index) {
2357 const Type* Ty = I->Ty->get();
2358 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2359 GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2360 ParamTypeList.push_back(Ty);
2361 if (Ty != Type::VoidTy && I->Attrs != ParamAttr::None)
2362 Attrs.push_back(ParamAttrsWithIndex::get(index, I->Attrs));
2366 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2367 if (isVarArg) ParamTypeList.pop_back();
2371 PAL = PAListPtr::get(Attrs.begin(), Attrs.end());
2373 FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
2374 const PointerType *PFT = PointerType::getUnqual(FT);
2378 if (!FunctionName.empty()) {
2379 ID = ValID::createGlobalName((char*)FunctionName.c_str());
2381 ID = ValID::createGlobalID(CurModule.Values.size());
2385 // See if this function was forward referenced. If so, recycle the object.
2386 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2387 // Move the function to the end of the list, from whereever it was
2388 // previously inserted.
2389 Fn = cast<Function>(FWRef);
2390 assert(Fn->getParamAttrs().isEmpty() &&
2391 "Forward reference has parameter attributes!");
2392 CurModule.CurrentModule->getFunctionList().remove(Fn);
2393 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2394 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2395 (Fn = CurModule.CurrentModule->getFunction(FunctionName))) {
2396 if (Fn->getFunctionType() != FT ) {
2397 // The existing function doesn't have the same type. This is an overload
2399 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2400 } else if (Fn->getParamAttrs() != PAL) {
2401 // The existing function doesn't have the same parameter attributes.
2402 // This is an overload error.
2403 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2404 } else if (!CurFun.isDeclare && !Fn->isDeclaration()) {
2405 // Neither the existing or the current function is a declaration and they
2406 // have the same name and same type. Clearly this is a redefinition.
2407 GEN_ERROR("Redefinition of function '" + FunctionName + "'");
2408 } else if (Fn->isDeclaration()) {
2409 // Make sure to strip off any argument names so we can't get conflicts.
2410 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2414 } else { // Not already defined?
2415 Fn = Function::Create(FT, GlobalValue::ExternalWeakLinkage, FunctionName,
2416 CurModule.CurrentModule);
2417 InsertValue(Fn, CurModule.Values);
2420 CurFun.FunctionStart(Fn);
2422 if (CurFun.isDeclare) {
2423 // If we have declaration, always overwrite linkage. This will allow us to
2424 // correctly handle cases, when pointer to function is passed as argument to
2425 // another function.
2426 Fn->setLinkage(CurFun.Linkage);
2427 Fn->setVisibility(CurFun.Visibility);
2429 Fn->setCallingConv($1);
2430 Fn->setParamAttrs(PAL);
2431 Fn->setAlignment($9);
2433 Fn->setSection(*$8);
2437 Fn->setGC($10->c_str());
2444 // Add all of the arguments we parsed to the function...
2445 if ($5) { // Is null if empty...
2446 if (isVarArg) { // Nuke the last entry
2447 assert($5->back().Ty->get() == Type::VoidTy && $5->back().Name == 0 &&
2448 "Not a varargs marker!");
2449 delete $5->back().Ty;
2450 $5->pop_back(); // Delete the last entry
2452 Function::arg_iterator ArgIt = Fn->arg_begin();
2453 Function::arg_iterator ArgEnd = Fn->arg_end();
2455 for (ArgListType::iterator I = $5->begin();
2456 I != $5->end() && ArgIt != ArgEnd; ++I, ++ArgIt) {
2457 delete I->Ty; // Delete the typeholder...
2458 setValueName(ArgIt, I->Name); // Insert arg into symtab...
2464 delete $5; // We're now done with the argument list
2469 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2471 FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2472 $$ = CurFun.CurrentFunction;
2474 // Make sure that we keep track of the linkage type even if there was a
2475 // previous "declare".
2477 $$->setVisibility($2);
2480 END : ENDTOK | '}'; // Allow end of '}' to end a function
2482 Function : BasicBlockList END {
2487 FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2488 CurFun.CurrentFunction->setLinkage($1);
2489 CurFun.CurrentFunction->setVisibility($2);
2490 $$ = CurFun.CurrentFunction;
2491 CurFun.FunctionDone();
2495 //===----------------------------------------------------------------------===//
2496 // Rules to match Basic Blocks
2497 //===----------------------------------------------------------------------===//
2499 OptSideEffect : /* empty */ {
2508 ConstValueRef : ESINT64VAL { // A reference to a direct constant
2509 $$ = ValID::create($1);
2513 $$ = ValID::create($1);
2516 | ESAPINTVAL { // arbitrary precision integer constants
2517 $$ = ValID::create(*$1, true);
2521 | EUAPINTVAL { // arbitrary precision integer constants
2522 $$ = ValID::create(*$1, false);
2526 | FPVAL { // Perhaps it's an FP constant?
2527 $$ = ValID::create($1);
2531 $$ = ValID::create(ConstantInt::getTrue());
2535 $$ = ValID::create(ConstantInt::getFalse());
2539 $$ = ValID::createNull();
2543 $$ = ValID::createUndef();
2546 | ZEROINITIALIZER { // A vector zero constant.
2547 $$ = ValID::createZeroInit();
2550 | '<' ConstVector '>' { // Nonempty unsized packed vector
2551 const Type *ETy = (*$2)[0]->getType();
2552 unsigned NumElements = $2->size();
2554 if (!ETy->isInteger() && !ETy->isFloatingPoint())
2555 GEN_ERROR("Invalid vector element type: " + ETy->getDescription());
2557 VectorType* pt = VectorType::get(ETy, NumElements);
2558 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(pt));
2560 // Verify all elements are correct type!
2561 for (unsigned i = 0; i < $2->size(); i++) {
2562 if (ETy != (*$2)[i]->getType())
2563 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2564 ETy->getDescription() +"' as required!\nIt is of type '" +
2565 (*$2)[i]->getType()->getDescription() + "'.");
2568 $$ = ValID::create(ConstantVector::get(pt, *$2));
2569 delete PTy; delete $2;
2572 | '[' ConstVector ']' { // Nonempty unsized arr
2573 const Type *ETy = (*$2)[0]->getType();
2574 uint64_t NumElements = $2->size();
2576 if (!ETy->isFirstClassType())
2577 GEN_ERROR("Invalid array element type: " + ETy->getDescription());
2579 ArrayType *ATy = ArrayType::get(ETy, NumElements);
2580 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(ATy));
2582 // Verify all elements are correct type!
2583 for (unsigned i = 0; i < $2->size(); i++) {
2584 if (ETy != (*$2)[i]->getType())
2585 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2586 ETy->getDescription() +"' as required!\nIt is of type '"+
2587 (*$2)[i]->getType()->getDescription() + "'.");
2590 $$ = ValID::create(ConstantArray::get(ATy, *$2));
2591 delete PTy; delete $2;
2595 // Use undef instead of an array because it's inconvenient to determine
2596 // the element type at this point, there being no elements to examine.
2597 $$ = ValID::createUndef();
2600 | 'c' STRINGCONSTANT {
2601 uint64_t NumElements = $2->length();
2602 const Type *ETy = Type::Int8Ty;
2604 ArrayType *ATy = ArrayType::get(ETy, NumElements);
2606 std::vector<Constant*> Vals;
2607 for (unsigned i = 0; i < $2->length(); ++i)
2608 Vals.push_back(ConstantInt::get(ETy, (*$2)[i]));
2610 $$ = ValID::create(ConstantArray::get(ATy, Vals));
2613 | '{' ConstVector '}' {
2614 std::vector<const Type*> Elements($2->size());
2615 for (unsigned i = 0, e = $2->size(); i != e; ++i)
2616 Elements[i] = (*$2)[i]->getType();
2618 const StructType *STy = StructType::get(Elements);
2619 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(STy));
2621 $$ = ValID::create(ConstantStruct::get(STy, *$2));
2622 delete PTy; delete $2;
2626 const StructType *STy = StructType::get(std::vector<const Type*>());
2627 $$ = ValID::create(ConstantStruct::get(STy, std::vector<Constant*>()));
2630 | '<' '{' ConstVector '}' '>' {
2631 std::vector<const Type*> Elements($3->size());
2632 for (unsigned i = 0, e = $3->size(); i != e; ++i)
2633 Elements[i] = (*$3)[i]->getType();
2635 const StructType *STy = StructType::get(Elements, /*isPacked=*/true);
2636 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(STy));
2638 $$ = ValID::create(ConstantStruct::get(STy, *$3));
2639 delete PTy; delete $3;
2643 const StructType *STy = StructType::get(std::vector<const Type*>(),
2645 $$ = ValID::create(ConstantStruct::get(STy, std::vector<Constant*>()));
2649 $$ = ValID::create($1);
2652 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2653 $$ = ValID::createInlineAsm(*$3, *$5, $2);
2659 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2662 SymbolicValueRef : LOCALVAL_ID { // Is it an integer reference...?
2663 $$ = ValID::createLocalID($1);
2667 $$ = ValID::createGlobalID($1);
2670 | LocalName { // Is it a named reference...?
2671 $$ = ValID::createLocalName(*$1);
2675 | GlobalName { // Is it a named reference...?
2676 $$ = ValID::createGlobalName(*$1);
2681 // ValueRef - A reference to a definition... either constant or symbolic
2682 ValueRef : SymbolicValueRef | ConstValueRef;
2685 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2686 // type immediately preceeds the value reference, and allows complex constant
2687 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2688 ResolvedVal : Types ValueRef {
2689 if (!UpRefs.empty())
2690 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2691 $$ = getVal(*$1, $2);
2697 ReturnedVal : ResolvedVal {
2698 $$ = new std::vector<Value *>();
2702 | ReturnedVal ',' ResolvedVal {
2703 ($$=$1)->push_back($3);
2707 BasicBlockList : BasicBlockList BasicBlock {
2711 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2717 // Basic blocks are terminated by branching instructions:
2718 // br, br/cc, switch, ret
2720 BasicBlock : InstructionList OptLocalAssign BBTerminatorInst {
2721 setValueName($3, $2);
2724 $1->getInstList().push_back($3);
2729 BasicBlock : InstructionList LocalNumber BBTerminatorInst {
2731 int ValNum = InsertValue($3);
2732 if (ValNum != (int)$2)
2733 GEN_ERROR("Result value number %" + utostr($2) +
2734 " is incorrect, expected %" + utostr((unsigned)ValNum));
2736 $1->getInstList().push_back($3);
2742 InstructionList : InstructionList Inst {
2743 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2744 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2745 if (CI2->getParent() == 0)
2746 $1->getInstList().push_back(CI2);
2747 $1->getInstList().push_back($2);
2751 | /* empty */ { // Empty space between instruction lists
2752 $$ = defineBBVal(ValID::createLocalID(CurFun.NextValNum));
2755 | LABELSTR { // Labelled (named) basic block
2756 $$ = defineBBVal(ValID::createLocalName(*$1));
2763 RET ReturnedVal { // Return with a result...
2764 ValueList &VL = *$2;
2765 assert(!VL.empty() && "Invalid ret operands!");
2766 const Type *ReturnType = CurFun.CurrentFunction->getReturnType();
2767 if (VL.size() > 1 ||
2768 (isa<StructType>(ReturnType) &&
2769 (VL.empty() || VL[0]->getType() != ReturnType))) {
2770 Value *RV = UndefValue::get(ReturnType);
2771 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
2772 Instruction *I = InsertValueInst::Create(RV, VL[i], i, "mrv");
2773 ($<BasicBlockVal>-1)->getInstList().push_back(I);
2776 $$ = ReturnInst::Create(RV);
2778 $$ = ReturnInst::Create(VL[0]);
2783 | RET VOID { // Return with no result...
2784 $$ = ReturnInst::Create();
2787 | BR LABEL ValueRef { // Unconditional Branch...
2788 BasicBlock* tmpBB = getBBVal($3);
2790 $$ = BranchInst::Create(tmpBB);
2791 } // Conditional Branch...
2792 | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2793 if (cast<IntegerType>($2)->getBitWidth() != 1)
2794 GEN_ERROR("Branch condition must have type i1");
2795 BasicBlock* tmpBBA = getBBVal($6);
2797 BasicBlock* tmpBBB = getBBVal($9);
2799 Value* tmpVal = getVal(Type::Int1Ty, $3);
2801 $$ = BranchInst::Create(tmpBBA, tmpBBB, tmpVal);
2803 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2804 Value* tmpVal = getVal($2, $3);
2806 BasicBlock* tmpBB = getBBVal($6);
2808 SwitchInst *S = SwitchInst::Create(tmpVal, tmpBB, $8->size());
2811 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2813 for (; I != E; ++I) {
2814 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2815 S->addCase(CI, I->second);
2817 GEN_ERROR("Switch case is constant, but not a simple integer");
2822 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2823 Value* tmpVal = getVal($2, $3);
2825 BasicBlock* tmpBB = getBBVal($6);
2827 SwitchInst *S = SwitchInst::Create(tmpVal, tmpBB, 0);
2831 | INVOKE OptCallingConv ResultTypes ValueRef '(' ParamList ')' OptFuncAttrs
2832 TO LABEL ValueRef UNWIND LABEL ValueRef {
2834 // Handle the short syntax
2835 const PointerType *PFTy = 0;
2836 const FunctionType *Ty = 0;
2837 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2838 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2839 // Pull out the types of all of the arguments...
2840 std::vector<const Type*> ParamTypes;
2841 ParamList::iterator I = $6->begin(), E = $6->end();
2842 for (; I != E; ++I) {
2843 const Type *Ty = I->Val->getType();
2844 if (Ty == Type::VoidTy)
2845 GEN_ERROR("Short call syntax cannot be used with varargs");
2846 ParamTypes.push_back(Ty);
2849 if (!FunctionType::isValidReturnType(*$3))
2850 GEN_ERROR("Invalid result type for LLVM function");
2852 Ty = FunctionType::get($3->get(), ParamTypes, false);
2853 PFTy = PointerType::getUnqual(Ty);
2858 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2860 BasicBlock *Normal = getBBVal($11);
2862 BasicBlock *Except = getBBVal($14);
2865 SmallVector<ParamAttrsWithIndex, 8> Attrs;
2866 if ($8 != ParamAttr::None)
2867 Attrs.push_back(ParamAttrsWithIndex::get(0, $8));
2869 // Check the arguments
2871 if ($6->empty()) { // Has no arguments?
2872 // Make sure no arguments is a good thing!
2873 if (Ty->getNumParams() != 0)
2874 GEN_ERROR("No arguments passed to a function that "
2875 "expects arguments");
2876 } else { // Has arguments?
2877 // Loop through FunctionType's arguments and ensure they are specified
2879 FunctionType::param_iterator I = Ty->param_begin();
2880 FunctionType::param_iterator E = Ty->param_end();
2881 ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
2884 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
2885 if (ArgI->Val->getType() != *I)
2886 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2887 (*I)->getDescription() + "'");
2888 Args.push_back(ArgI->Val);
2889 if (ArgI->Attrs != ParamAttr::None)
2890 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
2893 if (Ty->isVarArg()) {
2895 for (; ArgI != ArgE; ++ArgI, ++index) {
2896 Args.push_back(ArgI->Val); // push the remaining varargs
2897 if (ArgI->Attrs != ParamAttr::None)
2898 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
2900 } else if (I != E || ArgI != ArgE)
2901 GEN_ERROR("Invalid number of parameters detected");
2906 PAL = PAListPtr::get(Attrs.begin(), Attrs.end());
2908 // Create the InvokeInst
2909 InvokeInst *II = InvokeInst::Create(V, Normal, Except,
2910 Args.begin(), Args.end());
2911 II->setCallingConv($2);
2912 II->setParamAttrs(PAL);
2918 $$ = new UnwindInst();
2922 $$ = new UnreachableInst();
2928 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2930 Constant *V = cast<Constant>(getExistingVal($2, $3));
2933 GEN_ERROR("May only switch on a constant pool value");
2935 BasicBlock* tmpBB = getBBVal($6);
2937 $$->push_back(std::make_pair(V, tmpBB));
2939 | IntType ConstValueRef ',' LABEL ValueRef {
2940 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2941 Constant *V = cast<Constant>(getExistingVal($1, $2));
2945 GEN_ERROR("May only switch on a constant pool value");
2947 BasicBlock* tmpBB = getBBVal($5);
2949 $$->push_back(std::make_pair(V, tmpBB));
2952 Inst : OptLocalAssign InstVal {
2953 // Is this definition named?? if so, assign the name...
2954 setValueName($2, $1);
2961 Inst : LocalNumber InstVal {
2963 int ValNum = InsertValue($2);
2965 if (ValNum != (int)$1)
2966 GEN_ERROR("Result value number %" + utostr($1) +
2967 " is incorrect, expected %" + utostr((unsigned)ValNum));
2974 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2975 if (!UpRefs.empty())
2976 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2977 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2978 Value* tmpVal = getVal(*$1, $3);
2980 BasicBlock* tmpBB = getBBVal($5);
2982 $$->push_back(std::make_pair(tmpVal, tmpBB));
2985 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2987 Value* tmpVal = getVal($1->front().first->getType(), $4);
2989 BasicBlock* tmpBB = getBBVal($6);
2991 $1->push_back(std::make_pair(tmpVal, tmpBB));
2995 ParamList : Types OptParamAttrs ValueRef OptParamAttrs {
2996 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2997 if (!UpRefs.empty())
2998 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2999 // Used for call and invoke instructions
3000 $$ = new ParamList();
3001 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getVal($1->get(), $3);
3006 | LABEL OptParamAttrs ValueRef OptParamAttrs {
3007 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
3008 // Labels are only valid in ASMs
3009 $$ = new ParamList();
3010 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getBBVal($3);
3014 | ParamList ',' Types OptParamAttrs ValueRef OptParamAttrs {
3015 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
3016 if (!UpRefs.empty())
3017 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3019 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getVal($3->get(), $5);
3024 | ParamList ',' LABEL OptParamAttrs ValueRef OptParamAttrs {
3025 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
3027 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getBBVal($5);
3031 | /*empty*/ { $$ = new ParamList(); };
3033 IndexList // Used for gep instructions and constant expressions
3034 : /*empty*/ { $$ = new std::vector<Value*>(); }
3035 | IndexList ',' ResolvedVal {
3042 ConstantIndexList // Used for insertvalue and extractvalue instructions
3044 $$ = new std::vector<unsigned>();
3045 if ((unsigned)$2 != $2)
3046 GEN_ERROR("Index " + utostr($2) + " is not valid for insertvalue or extractvalue.");
3049 | ConstantIndexList ',' EUINT64VAL {
3051 if ((unsigned)$3 != $3)
3052 GEN_ERROR("Index " + utostr($3) + " is not valid for insertvalue or extractvalue.");
3058 OptTailCall : TAIL CALL {
3067 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
3068 if (!UpRefs.empty())
3069 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3070 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
3071 !isa<VectorType>((*$2).get()))
3073 "Arithmetic operator requires integer, FP, or packed operands");
3074 Value* val1 = getVal(*$2, $3);
3076 Value* val2 = getVal(*$2, $5);
3078 $$ = BinaryOperator::Create($1, val1, val2);
3080 GEN_ERROR("binary operator returned null");
3083 | LogicalOps Types ValueRef ',' ValueRef {
3084 if (!UpRefs.empty())
3085 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3086 if (!(*$2)->isInteger()) {
3087 if (!isa<VectorType>($2->get()) ||
3088 !cast<VectorType>($2->get())->getElementType()->isInteger())
3089 GEN_ERROR("Logical operator requires integral operands");
3091 Value* tmpVal1 = getVal(*$2, $3);
3093 Value* tmpVal2 = getVal(*$2, $5);
3095 $$ = BinaryOperator::Create($1, tmpVal1, tmpVal2);
3097 GEN_ERROR("binary operator returned null");
3100 | ICMP IPredicates Types ValueRef ',' ValueRef {
3101 if (!UpRefs.empty())
3102 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3103 Value* tmpVal1 = getVal(*$3, $4);
3105 Value* tmpVal2 = getVal(*$3, $6);
3107 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3109 GEN_ERROR("icmp operator returned null");
3112 | FCMP FPredicates Types ValueRef ',' ValueRef {
3113 if (!UpRefs.empty())
3114 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3115 Value* tmpVal1 = getVal(*$3, $4);
3117 Value* tmpVal2 = getVal(*$3, $6);
3119 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3121 GEN_ERROR("fcmp operator returned null");
3124 | VICMP IPredicates Types ValueRef ',' ValueRef {
3125 if (!UpRefs.empty())
3126 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3127 if (!isa<VectorType>((*$3).get()))
3128 GEN_ERROR("Scalar types not supported by vicmp instruction");
3129 Value* tmpVal1 = getVal(*$3, $4);
3131 Value* tmpVal2 = getVal(*$3, $6);
3133 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3135 GEN_ERROR("vicmp operator returned null");
3138 | VFCMP FPredicates Types ValueRef ',' ValueRef {
3139 if (!UpRefs.empty())
3140 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3141 if (!isa<VectorType>((*$3).get()))
3142 GEN_ERROR("Scalar types not supported by vfcmp instruction");
3143 Value* tmpVal1 = getVal(*$3, $4);
3145 Value* tmpVal2 = getVal(*$3, $6);
3147 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3149 GEN_ERROR("vfcmp operator returned null");
3152 | CastOps ResolvedVal TO Types {
3153 if (!UpRefs.empty())
3154 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
3156 const Type* DestTy = $4->get();
3157 if (!CastInst::castIsValid($1, Val, DestTy))
3158 GEN_ERROR("invalid cast opcode for cast from '" +
3159 Val->getType()->getDescription() + "' to '" +
3160 DestTy->getDescription() + "'");
3161 $$ = CastInst::Create($1, Val, DestTy);
3164 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3165 if (isa<VectorType>($2->getType())) {
3167 if (!isa<VectorType>($4->getType())
3168 || !isa<VectorType>($6->getType()) )
3169 GEN_ERROR("vector select value types must be vector types");
3170 const VectorType* cond_type = cast<VectorType>($2->getType());
3171 const VectorType* select_type = cast<VectorType>($4->getType());
3172 if (cond_type->getElementType() != Type::Int1Ty)
3173 GEN_ERROR("vector select condition element type must be boolean");
3174 if (cond_type->getNumElements() != select_type->getNumElements())
3175 GEN_ERROR("vector select number of elements must be the same");
3177 if ($2->getType() != Type::Int1Ty)
3178 GEN_ERROR("select condition must be boolean");
3180 if ($4->getType() != $6->getType())
3181 GEN_ERROR("select value types must match");
3182 $$ = SelectInst::Create($2, $4, $6);
3185 | VAARG ResolvedVal ',' Types {
3186 if (!UpRefs.empty())
3187 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
3188 $$ = new VAArgInst($2, *$4);
3192 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
3193 if (!ExtractElementInst::isValidOperands($2, $4))
3194 GEN_ERROR("Invalid extractelement operands");
3195 $$ = new ExtractElementInst($2, $4);
3198 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3199 if (!InsertElementInst::isValidOperands($2, $4, $6))
3200 GEN_ERROR("Invalid insertelement operands");
3201 $$ = InsertElementInst::Create($2, $4, $6);
3204 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3205 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
3206 GEN_ERROR("Invalid shufflevector operands");
3207 $$ = new ShuffleVectorInst($2, $4, $6);
3211 const Type *Ty = $2->front().first->getType();
3212 if (!Ty->isFirstClassType())
3213 GEN_ERROR("PHI node operands must be of first class type");
3214 $$ = PHINode::Create(Ty);
3215 ((PHINode*)$$)->reserveOperandSpace($2->size());
3216 while ($2->begin() != $2->end()) {
3217 if ($2->front().first->getType() != Ty)
3218 GEN_ERROR("All elements of a PHI node must be of the same type");
3219 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
3222 delete $2; // Free the list...
3225 | OptTailCall OptCallingConv ResultTypes ValueRef '(' ParamList ')'
3228 // Handle the short syntax
3229 const PointerType *PFTy = 0;
3230 const FunctionType *Ty = 0;
3231 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
3232 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3233 // Pull out the types of all of the arguments...
3234 std::vector<const Type*> ParamTypes;
3235 ParamList::iterator I = $6->begin(), E = $6->end();
3236 for (; I != E; ++I) {
3237 const Type *Ty = I->Val->getType();
3238 if (Ty == Type::VoidTy)
3239 GEN_ERROR("Short call syntax cannot be used with varargs");
3240 ParamTypes.push_back(Ty);
3243 if (!FunctionType::isValidReturnType(*$3))
3244 GEN_ERROR("Invalid result type for LLVM function");
3246 Ty = FunctionType::get($3->get(), ParamTypes, false);
3247 PFTy = PointerType::getUnqual(Ty);
3250 Value *V = getVal(PFTy, $4); // Get the function we're calling...
3253 // Check for call to invalid intrinsic to avoid crashing later.
3254 if (Function *theF = dyn_cast<Function>(V)) {
3255 if (theF->hasName() && (theF->getValueName()->getKeyLength() >= 5) &&
3256 (0 == strncmp(theF->getValueName()->getKeyData(), "llvm.", 5)) &&
3257 !theF->getIntrinsicID(true))
3258 GEN_ERROR("Call to invalid LLVM intrinsic function '" +
3259 theF->getName() + "'");
3262 // Set up the ParamAttrs for the function
3263 SmallVector<ParamAttrsWithIndex, 8> Attrs;
3264 if ($8 != ParamAttr::None)
3265 Attrs.push_back(ParamAttrsWithIndex::get(0, $8));
3266 // Check the arguments
3268 if ($6->empty()) { // Has no arguments?
3269 // Make sure no arguments is a good thing!
3270 if (Ty->getNumParams() != 0)
3271 GEN_ERROR("No arguments passed to a function that "
3272 "expects arguments");
3273 } else { // Has arguments?
3274 // Loop through FunctionType's arguments and ensure they are specified
3275 // correctly. Also, gather any parameter attributes.
3276 FunctionType::param_iterator I = Ty->param_begin();
3277 FunctionType::param_iterator E = Ty->param_end();
3278 ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
3281 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
3282 if (ArgI->Val->getType() != *I)
3283 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
3284 (*I)->getDescription() + "'");
3285 Args.push_back(ArgI->Val);
3286 if (ArgI->Attrs != ParamAttr::None)
3287 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
3289 if (Ty->isVarArg()) {
3291 for (; ArgI != ArgE; ++ArgI, ++index) {
3292 Args.push_back(ArgI->Val); // push the remaining varargs
3293 if (ArgI->Attrs != ParamAttr::None)
3294 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
3296 } else if (I != E || ArgI != ArgE)
3297 GEN_ERROR("Invalid number of parameters detected");
3300 // Finish off the ParamAttrs and check them
3303 PAL = PAListPtr::get(Attrs.begin(), Attrs.end());
3305 // Create the call node
3306 CallInst *CI = CallInst::Create(V, Args.begin(), Args.end());
3307 CI->setTailCall($1);
3308 CI->setCallingConv($2);
3309 CI->setParamAttrs(PAL);
3320 OptVolatile : VOLATILE {
3331 MemoryInst : MALLOC Types OptCAlign {
3332 if (!UpRefs.empty())
3333 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3334 $$ = new MallocInst(*$2, 0, $3);
3338 | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
3339 if (!UpRefs.empty())
3340 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3341 if ($4 != Type::Int32Ty)
3342 GEN_ERROR("Malloc array size is not a 32-bit integer!");
3343 Value* tmpVal = getVal($4, $5);
3345 $$ = new MallocInst(*$2, tmpVal, $6);
3348 | ALLOCA Types OptCAlign {
3349 if (!UpRefs.empty())
3350 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3351 $$ = new AllocaInst(*$2, 0, $3);
3355 | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
3356 if (!UpRefs.empty())
3357 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3358 if ($4 != Type::Int32Ty)
3359 GEN_ERROR("Alloca array size is not a 32-bit integer!");
3360 Value* tmpVal = getVal($4, $5);
3362 $$ = new AllocaInst(*$2, tmpVal, $6);
3365 | FREE ResolvedVal {
3366 if (!isa<PointerType>($2->getType()))
3367 GEN_ERROR("Trying to free nonpointer type " +
3368 $2->getType()->getDescription() + "");
3369 $$ = new FreeInst($2);
3373 | OptVolatile LOAD Types ValueRef OptCAlign {
3374 if (!UpRefs.empty())
3375 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3376 if (!isa<PointerType>($3->get()))
3377 GEN_ERROR("Can't load from nonpointer type: " +
3378 (*$3)->getDescription());
3379 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
3380 GEN_ERROR("Can't load from pointer of non-first-class type: " +
3381 (*$3)->getDescription());
3382 Value* tmpVal = getVal(*$3, $4);
3384 $$ = new LoadInst(tmpVal, "", $1, $5);
3387 | OptVolatile STORE ResolvedVal ',' Types ValueRef OptCAlign {
3388 if (!UpRefs.empty())
3389 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
3390 const PointerType *PT = dyn_cast<PointerType>($5->get());
3392 GEN_ERROR("Can't store to a nonpointer type: " +
3393 (*$5)->getDescription());
3394 const Type *ElTy = PT->getElementType();
3395 if (ElTy != $3->getType())
3396 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
3397 "' into space of type '" + ElTy->getDescription() + "'");
3399 Value* tmpVal = getVal(*$5, $6);
3401 $$ = new StoreInst($3, tmpVal, $1, $7);
3404 | GETRESULT Types ValueRef ',' EUINT64VAL {
3405 if (!UpRefs.empty())
3406 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3407 if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3408 GEN_ERROR("getresult insn requires an aggregate operand");
3409 if (!ExtractValueInst::getIndexedType(*$2, $5))
3410 GEN_ERROR("Invalid getresult index for type '" +
3411 (*$2)->getDescription()+ "'");
3413 Value *tmpVal = getVal(*$2, $3);
3415 $$ = ExtractValueInst::Create(tmpVal, $5);
3418 | GETELEMENTPTR Types ValueRef IndexList {
3419 if (!UpRefs.empty())
3420 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3421 if (!isa<PointerType>($2->get()))
3422 GEN_ERROR("getelementptr insn requires pointer operand");
3424 if (!GetElementPtrInst::getIndexedType(*$2, $4->begin(), $4->end()))
3425 GEN_ERROR("Invalid getelementptr indices for type '" +
3426 (*$2)->getDescription()+ "'");
3427 Value* tmpVal = getVal(*$2, $3);
3429 $$ = GetElementPtrInst::Create(tmpVal, $4->begin(), $4->end());
3433 | EXTRACTVALUE Types ValueRef ConstantIndexList {
3434 if (!UpRefs.empty())
3435 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3436 if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3437 GEN_ERROR("extractvalue insn requires an aggregate operand");
3439 if (!ExtractValueInst::getIndexedType(*$2, $4->begin(), $4->end()))
3440 GEN_ERROR("Invalid extractvalue indices for type '" +
3441 (*$2)->getDescription()+ "'");
3442 Value* tmpVal = getVal(*$2, $3);
3444 $$ = ExtractValueInst::Create(tmpVal, $4->begin(), $4->end());
3448 | INSERTVALUE Types ValueRef ',' Types ValueRef ConstantIndexList {
3449 if (!UpRefs.empty())
3450 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3451 if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3452 GEN_ERROR("extractvalue insn requires an aggregate operand");
3454 if (ExtractValueInst::getIndexedType(*$2, $7->begin(), $7->end()) != $5->get())
3455 GEN_ERROR("Invalid insertvalue indices for type '" +
3456 (*$2)->getDescription()+ "'");
3457 Value* aggVal = getVal(*$2, $3);
3458 Value* tmpVal = getVal(*$5, $6);
3460 $$ = InsertValueInst::Create(aggVal, tmpVal, $7->begin(), $7->end());
3469 // common code from the two 'RunVMAsmParser' functions
3470 static Module* RunParser(Module * M) {
3471 CurModule.CurrentModule = M;
3472 // Check to make sure the parser succeeded
3475 delete ParserResult;
3479 // Emit an error if there are any unresolved types left.
3480 if (!CurModule.LateResolveTypes.empty()) {
3481 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
3482 if (DID.Type == ValID::LocalName) {
3483 GenerateError("Undefined type remains at eof: '"+DID.getName() + "'");
3485 GenerateError("Undefined type remains at eof: #" + itostr(DID.Num));
3488 delete ParserResult;
3492 // Emit an error if there are any unresolved values left.
3493 if (!CurModule.LateResolveValues.empty()) {
3494 Value *V = CurModule.LateResolveValues.back();
3495 std::map<Value*, std::pair<ValID, int> >::iterator I =
3496 CurModule.PlaceHolderInfo.find(V);
3498 if (I != CurModule.PlaceHolderInfo.end()) {
3499 ValID &DID = I->second.first;
3500 if (DID.Type == ValID::LocalName) {
3501 GenerateError("Undefined value remains at eof: "+DID.getName() + "'");
3503 GenerateError("Undefined value remains at eof: #" + itostr(DID.Num));
3506 delete ParserResult;
3511 // Check to make sure that parsing produced a result
3515 // Reset ParserResult variable while saving its value for the result.
3516 Module *Result = ParserResult;
3522 void llvm::GenerateError(const std::string &message, int LineNo) {
3523 if (LineNo == -1) LineNo = LLLgetLineNo();
3524 // TODO: column number in exception
3526 TheParseError->setError(LLLgetFilename(), message, LineNo);
3530 int yyerror(const char *ErrorMsg) {
3531 std::string where = LLLgetFilename() + ":" + utostr(LLLgetLineNo()) + ": ";
3532 std::string errMsg = where + "error: " + std::string(ErrorMsg);
3533 if (yychar != YYEMPTY && yychar != 0) {
3534 errMsg += " while reading token: '";
3535 errMsg += std::string(LLLgetTokenStart(),
3536 LLLgetTokenStart()+LLLgetTokenLength()) + "'";
3538 GenerateError(errMsg);