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 static void InsertValue(Value *V, ValueList &ValueTab = CurFun.Values) {
253 // Things that have names or are void typed don't get slot numbers
254 if (V->hasName() || (V->getType() == Type::VoidTy))
257 // In the case of function values, we have to allow for the forward reference
258 // of basic blocks, which are included in the numbering. Consequently, we keep
259 // track of the next insertion location with NextValNum. When a BB gets
260 // inserted, it could change the size of the CurFun.Values vector.
261 if (&ValueTab == &CurFun.Values) {
262 if (ValueTab.size() <= CurFun.NextValNum)
263 ValueTab.resize(CurFun.NextValNum+1);
264 ValueTab[CurFun.NextValNum++] = V;
267 // For all other lists, its okay to just tack it on the back of the vector.
268 ValueTab.push_back(V);
271 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
273 case ValID::LocalID: // Is it a numbered definition?
274 // Module constants occupy the lowest numbered slots...
275 if (D.Num < CurModule.Types.size())
276 return CurModule.Types[D.Num];
278 case ValID::LocalName: // Is it a named definition?
279 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.getName())) {
280 D.destroy(); // Free old strdup'd memory...
285 GenerateError("Internal parser error: Invalid symbol type reference");
289 // If we reached here, we referenced either a symbol that we don't know about
290 // or an id number that hasn't been read yet. We may be referencing something
291 // forward, so just create an entry to be resolved later and get to it...
293 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
296 if (inFunctionScope()) {
297 if (D.Type == ValID::LocalName) {
298 GenerateError("Reference to an undefined type: '" + D.getName() + "'");
301 GenerateError("Reference to an undefined type: #" + utostr(D.Num));
306 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
307 if (I != CurModule.LateResolveTypes.end())
310 Type *Typ = OpaqueType::get();
311 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
315 // getExistingVal - Look up the value specified by the provided type and
316 // the provided ValID. If the value exists and has already been defined, return
317 // it. Otherwise return null.
319 static Value *getExistingVal(const Type *Ty, const ValID &D) {
320 if (isa<FunctionType>(Ty)) {
321 GenerateError("Functions are not values and "
322 "must be referenced as pointers");
327 case ValID::LocalID: { // Is it a numbered definition?
328 // Check that the number is within bounds.
329 if (D.Num >= CurFun.Values.size())
331 Value *Result = CurFun.Values[D.Num];
332 if (Ty != Result->getType()) {
333 GenerateError("Numbered value (%" + utostr(D.Num) + ") of type '" +
334 Result->getType()->getDescription() + "' does not match "
335 "expected type, '" + Ty->getDescription() + "'");
340 case ValID::GlobalID: { // Is it a numbered definition?
341 if (D.Num >= CurModule.Values.size())
343 Value *Result = CurModule.Values[D.Num];
344 if (Ty != Result->getType()) {
345 GenerateError("Numbered value (@" + utostr(D.Num) + ") of type '" +
346 Result->getType()->getDescription() + "' does not match "
347 "expected type, '" + Ty->getDescription() + "'");
353 case ValID::LocalName: { // Is it a named definition?
354 if (!inFunctionScope())
356 ValueSymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
357 Value *N = SymTab.lookup(D.getName());
360 if (N->getType() != Ty)
363 D.destroy(); // Free old strdup'd memory...
366 case ValID::GlobalName: { // Is it a named definition?
367 ValueSymbolTable &SymTab = CurModule.CurrentModule->getValueSymbolTable();
368 Value *N = SymTab.lookup(D.getName());
371 if (N->getType() != Ty)
374 D.destroy(); // Free old strdup'd memory...
378 // Check to make sure that "Ty" is an integral type, and that our
379 // value will fit into the specified type...
380 case ValID::ConstSIntVal: // Is it a constant pool reference??
381 if (!isa<IntegerType>(Ty) ||
382 !ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
383 GenerateError("Signed integral constant '" +
384 itostr(D.ConstPool64) + "' is invalid for type '" +
385 Ty->getDescription() + "'");
388 return ConstantInt::get(Ty, D.ConstPool64, true);
390 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
391 if (isa<IntegerType>(Ty) &&
392 ConstantInt::isValueValidForType(Ty, D.UConstPool64))
393 return ConstantInt::get(Ty, D.UConstPool64);
395 if (!isa<IntegerType>(Ty) ||
396 !ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
397 GenerateError("Integral constant '" + utostr(D.UConstPool64) +
398 "' is invalid or out of range for type '" +
399 Ty->getDescription() + "'");
402 // This is really a signed reference. Transmogrify.
403 return ConstantInt::get(Ty, D.ConstPool64, true);
405 case ValID::ConstAPInt: // Is it an unsigned const pool reference?
406 if (!isa<IntegerType>(Ty)) {
407 GenerateError("Integral constant '" + D.getName() +
408 "' is invalid or out of range for type '" +
409 Ty->getDescription() + "'");
414 APSInt Tmp = *D.ConstPoolInt;
415 Tmp.extOrTrunc(Ty->getPrimitiveSizeInBits());
416 return ConstantInt::get(Tmp);
419 case ValID::ConstFPVal: // Is it a floating point const pool reference?
420 if (!Ty->isFloatingPoint() ||
421 !ConstantFP::isValueValidForType(Ty, *D.ConstPoolFP)) {
422 GenerateError("FP constant invalid for type");
425 // Lexer has no type info, so builds all float and double FP constants
426 // as double. Fix this here. Long double does not need this.
427 if (&D.ConstPoolFP->getSemantics() == &APFloat::IEEEdouble &&
429 D.ConstPoolFP->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
430 return ConstantFP::get(*D.ConstPoolFP);
432 case ValID::ConstNullVal: // Is it a null value?
433 if (!isa<PointerType>(Ty)) {
434 GenerateError("Cannot create a a non pointer null");
437 return ConstantPointerNull::get(cast<PointerType>(Ty));
439 case ValID::ConstUndefVal: // Is it an undef value?
440 return UndefValue::get(Ty);
442 case ValID::ConstZeroVal: // Is it a zero value?
443 return Constant::getNullValue(Ty);
445 case ValID::ConstantVal: // Fully resolved constant?
446 if (D.ConstantValue->getType() != Ty) {
447 GenerateError("Constant expression type different from required type");
450 return D.ConstantValue;
452 case ValID::InlineAsmVal: { // Inline asm expression
453 const PointerType *PTy = dyn_cast<PointerType>(Ty);
454 const FunctionType *FTy =
455 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
456 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
457 GenerateError("Invalid type for asm constraint string");
460 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
461 D.IAD->HasSideEffects);
462 D.destroy(); // Free InlineAsmDescriptor.
466 assert(0 && "Unhandled case!");
470 assert(0 && "Unhandled case!");
474 // getVal - This function is identical to getExistingVal, except that if a
475 // value is not already defined, it "improvises" by creating a placeholder var
476 // that looks and acts just like the requested variable. When the value is
477 // defined later, all uses of the placeholder variable are replaced with the
480 static Value *getVal(const Type *Ty, const ValID &ID) {
481 if (Ty == Type::LabelTy) {
482 GenerateError("Cannot use a basic block here");
486 // See if the value has already been defined.
487 Value *V = getExistingVal(Ty, ID);
489 if (TriggerError) return 0;
491 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
492 GenerateError("Invalid use of a non-first-class type");
496 // If we reached here, we referenced either a symbol that we don't know about
497 // or an id number that hasn't been read yet. We may be referencing something
498 // forward, so just create an entry to be resolved later and get to it...
501 case ValID::GlobalName:
502 case ValID::GlobalID: {
503 const PointerType *PTy = dyn_cast<PointerType>(Ty);
505 GenerateError("Invalid type for reference to global" );
508 const Type* ElTy = PTy->getElementType();
509 if (const FunctionType *FTy = dyn_cast<FunctionType>(ElTy))
510 V = Function::Create(FTy, GlobalValue::ExternalLinkage);
512 V = new GlobalVariable(ElTy, false, GlobalValue::ExternalLinkage, 0, "",
513 (Module*)0, false, PTy->getAddressSpace());
517 V = new Argument(Ty);
520 // Remember where this forward reference came from. FIXME, shouldn't we try
521 // to recycle these things??
522 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
525 if (inFunctionScope())
526 InsertValue(V, CurFun.LateResolveValues);
528 InsertValue(V, CurModule.LateResolveValues);
532 /// defineBBVal - This is a definition of a new basic block with the specified
533 /// identifier which must be the same as CurFun.NextValNum, if its numeric.
534 static BasicBlock *defineBBVal(const ValID &ID) {
535 assert(inFunctionScope() && "Can't get basic block at global scope!");
539 // First, see if this was forward referenced
541 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
542 if (BBI != CurFun.BBForwardRefs.end()) {
544 // The forward declaration could have been inserted anywhere in the
545 // function: insert it into the correct place now.
546 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
547 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
549 // We're about to erase the entry, save the key so we can clean it up.
550 ValID Tmp = BBI->first;
552 // Erase the forward ref from the map as its no longer "forward"
553 CurFun.BBForwardRefs.erase(ID);
555 // The key has been removed from the map but so we don't want to leave
556 // strdup'd memory around so destroy it too.
559 // If its a numbered definition, bump the number and set the BB value.
560 if (ID.Type == ValID::LocalID) {
561 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
565 // We haven't seen this BB before and its first mention is a definition.
566 // Just create it and return it.
567 std::string Name (ID.Type == ValID::LocalName ? ID.getName() : "");
568 BB = BasicBlock::Create(Name, CurFun.CurrentFunction);
569 if (ID.Type == ValID::LocalID) {
570 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
579 /// getBBVal - get an existing BB value or create a forward reference for it.
581 static BasicBlock *getBBVal(const ValID &ID) {
582 assert(inFunctionScope() && "Can't get basic block at global scope!");
586 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
587 if (BBI != CurFun.BBForwardRefs.end()) {
589 } if (ID.Type == ValID::LocalName) {
590 std::string Name = ID.getName();
591 Value *N = CurFun.CurrentFunction->getValueSymbolTable().lookup(Name);
593 if (N->getType()->getTypeID() == Type::LabelTyID)
594 BB = cast<BasicBlock>(N);
596 GenerateError("Reference to label '" + Name + "' is actually of type '"+
597 N->getType()->getDescription() + "'");
599 } else if (ID.Type == ValID::LocalID) {
600 if (ID.Num < CurFun.NextValNum && ID.Num < CurFun.Values.size()) {
601 if (CurFun.Values[ID.Num]->getType()->getTypeID() == Type::LabelTyID)
602 BB = cast<BasicBlock>(CurFun.Values[ID.Num]);
604 GenerateError("Reference to label '%" + utostr(ID.Num) +
605 "' is actually of type '"+
606 CurFun.Values[ID.Num]->getType()->getDescription() + "'");
609 GenerateError("Illegal label reference " + ID.getName());
613 // If its already been defined, return it now.
615 ID.destroy(); // Free strdup'd memory.
619 // Otherwise, this block has not been seen before, create it.
621 if (ID.Type == ValID::LocalName)
623 BB = BasicBlock::Create(Name, CurFun.CurrentFunction);
625 // Insert it in the forward refs map.
626 CurFun.BBForwardRefs[ID] = BB;
632 //===----------------------------------------------------------------------===//
633 // Code to handle forward references in instructions
634 //===----------------------------------------------------------------------===//
636 // This code handles the late binding needed with statements that reference
637 // values not defined yet... for example, a forward branch, or the PHI node for
640 // This keeps a table (CurFun.LateResolveValues) of all such forward references
641 // and back patchs after we are done.
644 // ResolveDefinitions - If we could not resolve some defs at parsing
645 // time (forward branches, phi functions for loops, etc...) resolve the
649 ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers) {
650 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
651 while (!LateResolvers.empty()) {
652 Value *V = LateResolvers.back();
653 LateResolvers.pop_back();
655 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
656 CurModule.PlaceHolderInfo.find(V);
657 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
659 ValID &DID = PHI->second.first;
661 Value *TheRealValue = getExistingVal(V->getType(), DID);
665 V->replaceAllUsesWith(TheRealValue);
667 CurModule.PlaceHolderInfo.erase(PHI);
668 } else if (FutureLateResolvers) {
669 // Functions have their unresolved items forwarded to the module late
671 InsertValue(V, *FutureLateResolvers);
673 if (DID.Type == ValID::LocalName || DID.Type == ValID::GlobalName) {
674 GenerateError("Reference to an invalid definition: '" +DID.getName()+
675 "' of type '" + V->getType()->getDescription() + "'",
679 GenerateError("Reference to an invalid definition: #" +
680 itostr(DID.Num) + " of type '" +
681 V->getType()->getDescription() + "'",
687 LateResolvers.clear();
690 // ResolveTypeTo - A brand new type was just declared. This means that (if
691 // name is not null) things referencing Name can be resolved. Otherwise, things
692 // refering to the number can be resolved. Do this now.
694 static void ResolveTypeTo(std::string *Name, const Type *ToTy) {
697 D = ValID::createLocalName(*Name);
699 D = ValID::createLocalID(CurModule.Types.size());
701 std::map<ValID, PATypeHolder>::iterator I =
702 CurModule.LateResolveTypes.find(D);
703 if (I != CurModule.LateResolveTypes.end()) {
704 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
705 CurModule.LateResolveTypes.erase(I);
709 // setValueName - Set the specified value to the name given. The name may be
710 // null potentially, in which case this is a noop. The string passed in is
711 // assumed to be a malloc'd string buffer, and is free'd by this function.
713 static void setValueName(Value *V, std::string *NameStr) {
714 if (!NameStr) return;
715 std::string Name(*NameStr); // Copy string
716 delete NameStr; // Free old string
718 if (V->getType() == Type::VoidTy) {
719 GenerateError("Can't assign name '" + Name+"' to value with void type");
723 assert(inFunctionScope() && "Must be in function scope!");
724 ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
725 if (ST.lookup(Name)) {
726 GenerateError("Redefinition of value '" + Name + "' of type '" +
727 V->getType()->getDescription() + "'");
735 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
736 /// this is a declaration, otherwise it is a definition.
737 static GlobalVariable *
738 ParseGlobalVariable(std::string *NameStr,
739 GlobalValue::LinkageTypes Linkage,
740 GlobalValue::VisibilityTypes Visibility,
741 bool isConstantGlobal, const Type *Ty,
742 Constant *Initializer, bool IsThreadLocal,
743 unsigned AddressSpace = 0) {
744 if (isa<FunctionType>(Ty)) {
745 GenerateError("Cannot declare global vars of function type");
748 if (Ty == Type::LabelTy) {
749 GenerateError("Cannot declare global vars of label type");
753 const PointerType *PTy = PointerType::get(Ty, AddressSpace);
757 Name = *NameStr; // Copy string
758 delete NameStr; // Free old string
761 // See if this global value was forward referenced. If so, recycle the
765 ID = ValID::createGlobalName(Name);
767 ID = ValID::createGlobalID(CurModule.Values.size());
770 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
771 // Move the global to the end of the list, from whereever it was
772 // previously inserted.
773 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
774 CurModule.CurrentModule->getGlobalList().remove(GV);
775 CurModule.CurrentModule->getGlobalList().push_back(GV);
776 GV->setInitializer(Initializer);
777 GV->setLinkage(Linkage);
778 GV->setVisibility(Visibility);
779 GV->setConstant(isConstantGlobal);
780 GV->setThreadLocal(IsThreadLocal);
781 InsertValue(GV, CurModule.Values);
785 // If this global has a name
787 // if the global we're parsing has an initializer (is a definition) and
788 // has external linkage.
789 if (Initializer && Linkage != GlobalValue::InternalLinkage)
790 // If there is already a global with external linkage with this name
791 if (CurModule.CurrentModule->getGlobalVariable(Name, false)) {
792 // If we allow this GVar to get created, it will be renamed in the
793 // symbol table because it conflicts with an existing GVar. We can't
794 // allow redefinition of GVars whose linking indicates that their name
795 // must stay the same. Issue the error.
796 GenerateError("Redefinition of global variable named '" + Name +
797 "' of type '" + Ty->getDescription() + "'");
802 // Otherwise there is no existing GV to use, create one now.
804 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
805 CurModule.CurrentModule, IsThreadLocal, AddressSpace);
806 GV->setVisibility(Visibility);
807 InsertValue(GV, CurModule.Values);
811 // setTypeName - Set the specified type to the name given. The name may be
812 // null potentially, in which case this is a noop. The string passed in is
813 // assumed to be a malloc'd string buffer, and is freed by this function.
815 // This function returns true if the type has already been defined, but is
816 // allowed to be redefined in the specified context. If the name is a new name
817 // for the type plane, it is inserted and false is returned.
818 static bool setTypeName(const Type *T, std::string *NameStr) {
819 assert(!inFunctionScope() && "Can't give types function-local names!");
820 if (NameStr == 0) return false;
822 std::string Name(*NameStr); // Copy string
823 delete NameStr; // Free old string
825 // We don't allow assigning names to void type
826 if (T == Type::VoidTy) {
827 GenerateError("Can't assign name '" + Name + "' to the void type");
831 // Set the type name, checking for conflicts as we do so.
832 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
834 if (AlreadyExists) { // Inserting a name that is already defined???
835 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
836 assert(Existing && "Conflict but no matching type?!");
838 // There is only one case where this is allowed: when we are refining an
839 // opaque type. In this case, Existing will be an opaque type.
840 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
841 // We ARE replacing an opaque type!
842 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
846 // Otherwise, this is an attempt to redefine a type. That's okay if
847 // the redefinition is identical to the original. This will be so if
848 // Existing and T point to the same Type object. In this one case we
849 // allow the equivalent redefinition.
850 if (Existing == T) return true; // Yes, it's equal.
852 // Any other kind of (non-equivalent) redefinition is an error.
853 GenerateError("Redefinition of type named '" + Name + "' of type '" +
854 T->getDescription() + "'");
860 //===----------------------------------------------------------------------===//
861 // Code for handling upreferences in type names...
864 // TypeContains - Returns true if Ty directly contains E in it.
866 static bool TypeContains(const Type *Ty, const Type *E) {
867 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
868 E) != Ty->subtype_end();
873 // NestingLevel - The number of nesting levels that need to be popped before
874 // this type is resolved.
875 unsigned NestingLevel;
877 // LastContainedTy - This is the type at the current binding level for the
878 // type. Every time we reduce the nesting level, this gets updated.
879 const Type *LastContainedTy;
881 // UpRefTy - This is the actual opaque type that the upreference is
885 UpRefRecord(unsigned NL, OpaqueType *URTy)
886 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
890 // UpRefs - A list of the outstanding upreferences that need to be resolved.
891 static std::vector<UpRefRecord> UpRefs;
893 /// HandleUpRefs - Every time we finish a new layer of types, this function is
894 /// called. It loops through the UpRefs vector, which is a list of the
895 /// currently active types. For each type, if the up reference is contained in
896 /// the newly completed type, we decrement the level count. When the level
897 /// count reaches zero, the upreferenced type is the type that is passed in:
898 /// thus we can complete the cycle.
900 static PATypeHolder HandleUpRefs(const Type *ty) {
901 // If Ty isn't abstract, or if there are no up-references in it, then there is
902 // nothing to resolve here.
903 if (!ty->isAbstract() || UpRefs.empty()) return ty;
906 UR_OUT("Type '" << Ty->getDescription() <<
907 "' newly formed. Resolving upreferences.\n" <<
908 UpRefs.size() << " upreferences active!\n");
910 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
911 // to zero), we resolve them all together before we resolve them to Ty. At
912 // the end of the loop, if there is anything to resolve to Ty, it will be in
914 OpaqueType *TypeToResolve = 0;
916 for (unsigned i = 0; i != UpRefs.size(); ++i) {
917 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
918 << UpRefs[i].second->getDescription() << ") = "
919 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
920 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
921 // Decrement level of upreference
922 unsigned Level = --UpRefs[i].NestingLevel;
923 UpRefs[i].LastContainedTy = Ty;
924 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
925 if (Level == 0) { // Upreference should be resolved!
926 if (!TypeToResolve) {
927 TypeToResolve = UpRefs[i].UpRefTy;
929 UR_OUT(" * Resolving upreference for "
930 << UpRefs[i].second->getDescription() << "\n";
931 std::string OldName = UpRefs[i].UpRefTy->getDescription());
932 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
933 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
934 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
936 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
937 --i; // Do not skip the next element...
943 UR_OUT(" * Resolving upreference for "
944 << UpRefs[i].second->getDescription() << "\n";
945 std::string OldName = TypeToResolve->getDescription());
946 TypeToResolve->refineAbstractTypeTo(Ty);
952 //===----------------------------------------------------------------------===//
953 // RunVMAsmParser - Define an interface to this parser
954 //===----------------------------------------------------------------------===//
956 static Module* RunParser(Module * M);
958 Module *llvm::RunVMAsmParser(llvm::MemoryBuffer *MB) {
960 Module *M = RunParser(new Module(LLLgetFilename()));
968 llvm::Module *ModuleVal;
969 llvm::Function *FunctionVal;
970 llvm::BasicBlock *BasicBlockVal;
971 llvm::TerminatorInst *TermInstVal;
972 llvm::Instruction *InstVal;
973 llvm::Constant *ConstVal;
975 const llvm::Type *PrimType;
976 std::list<llvm::PATypeHolder> *TypeList;
977 llvm::PATypeHolder *TypeVal;
978 llvm::Value *ValueVal;
979 std::vector<llvm::Value*> *ValueList;
980 std::vector<unsigned> *ConstantList;
981 llvm::ArgListType *ArgList;
982 llvm::TypeWithAttrs TypeWithAttrs;
983 llvm::TypeWithAttrsList *TypeWithAttrsList;
984 llvm::ParamList *ParamList;
986 // Represent the RHS of PHI node
987 std::list<std::pair<llvm::Value*,
988 llvm::BasicBlock*> > *PHIList;
989 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
990 std::vector<llvm::Constant*> *ConstVector;
992 llvm::GlobalValue::LinkageTypes Linkage;
993 llvm::GlobalValue::VisibilityTypes Visibility;
994 llvm::ParameterAttributes ParamAttrs;
995 llvm::APInt *APIntVal;
1000 llvm::APFloat *FPVal;
1003 std::string *StrVal; // This memory must be deleted
1004 llvm::ValID ValIDVal;
1006 llvm::Instruction::BinaryOps BinaryOpVal;
1007 llvm::Instruction::TermOps TermOpVal;
1008 llvm::Instruction::MemoryOps MemOpVal;
1009 llvm::Instruction::CastOps CastOpVal;
1010 llvm::Instruction::OtherOps OtherOpVal;
1011 llvm::ICmpInst::Predicate IPredicate;
1012 llvm::FCmpInst::Predicate FPredicate;
1015 %type <ModuleVal> Module
1016 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1017 %type <BasicBlockVal> BasicBlock InstructionList
1018 %type <TermInstVal> BBTerminatorInst
1019 %type <InstVal> Inst InstVal MemoryInst
1020 %type <ConstVal> ConstVal ConstExpr AliaseeRef
1021 %type <ConstVector> ConstVector
1022 %type <ArgList> ArgList ArgListH
1023 %type <PHIList> PHIList
1024 %type <ParamList> ParamList // For call param lists & GEP indices
1025 %type <ValueList> IndexList // For GEP indices
1026 %type <ConstantList> ConstantIndexList // For insertvalue/extractvalue indices
1027 %type <TypeList> TypeListI
1028 %type <TypeWithAttrsList> ArgTypeList ArgTypeListI
1029 %type <TypeWithAttrs> ArgType
1030 %type <JumpTable> JumpTable
1031 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1032 %type <BoolVal> ThreadLocal // 'thread_local' or not
1033 %type <BoolVal> OptVolatile // 'volatile' or not
1034 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1035 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
1036 %type <Linkage> GVInternalLinkage GVExternalLinkage
1037 %type <Linkage> FunctionDefineLinkage FunctionDeclareLinkage
1038 %type <Linkage> AliasLinkage
1039 %type <Visibility> GVVisibilityStyle
1041 // ValueRef - Unresolved reference to a definition or BB
1042 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1043 %type <ValueVal> ResolvedVal // <type> <valref> pair
1044 %type <ValueList> ReturnedVal
1045 // Tokens and types for handling constant integer values
1047 // ESINT64VAL - A negative number within long long range
1048 %token <SInt64Val> ESINT64VAL
1050 // EUINT64VAL - A positive number within uns. long long range
1051 %token <UInt64Val> EUINT64VAL
1053 // ESAPINTVAL - A negative number with arbitrary precision
1054 %token <APIntVal> ESAPINTVAL
1056 // EUAPINTVAL - A positive number with arbitrary precision
1057 %token <APIntVal> EUAPINTVAL
1059 %token <UIntVal> LOCALVAL_ID GLOBALVAL_ID // %123 @123
1060 %token <FPVal> FPVAL // Float or Double constant
1062 // Built in types...
1063 %type <TypeVal> Types ResultTypes
1064 %type <PrimType> IntType FPType PrimType // Classifications
1065 %token <PrimType> VOID INTTYPE
1066 %token <PrimType> FLOAT DOUBLE X86_FP80 FP128 PPC_FP128 LABEL
1070 %token<StrVal> LOCALVAR GLOBALVAR LABELSTR
1071 %token<StrVal> STRINGCONSTANT ATSTRINGCONSTANT PCTSTRINGCONSTANT
1072 %type <StrVal> LocalName OptLocalName OptLocalAssign
1073 %type <StrVal> GlobalName OptGlobalAssign GlobalAssign
1074 %type <StrVal> OptSection SectionString OptGC
1076 %type <UIntVal> OptAlign OptCAlign OptAddrSpace
1078 %token ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1079 %token DECLARE DEFINE GLOBAL CONSTANT SECTION ALIAS VOLATILE THREAD_LOCAL
1080 %token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
1081 %token DLLIMPORT DLLEXPORT EXTERN_WEAK COMMON
1082 %token OPAQUE EXTERNAL TARGET TRIPLE ALIGN ADDRSPACE
1083 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1084 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1085 %token X86_SSECALLCC_TOK
1087 %type <UIntVal> OptCallingConv
1088 %type <ParamAttrs> OptParamAttrs ParamAttr
1089 %type <ParamAttrs> OptFuncAttrs FuncAttr
1091 // Basic Block Terminating Operators
1092 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1095 %type <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
1096 %token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1097 %token <BinaryOpVal> SHL LSHR ASHR
1099 %token <OtherOpVal> ICMP FCMP VICMP VFCMP
1100 %type <IPredicate> IPredicates
1101 %type <FPredicate> FPredicates
1102 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1103 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1105 // Memory Instructions
1106 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1109 %type <CastOpVal> CastOps
1110 %token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1111 %token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1114 %token <OtherOpVal> PHI_TOK SELECT VAARG
1115 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1116 %token <OtherOpVal> GETRESULT
1117 %token <OtherOpVal> EXTRACTVALUE INSERTVALUE
1119 // Function Attributes
1120 %token SIGNEXT ZEROEXT NORETURN INREG SRET NOUNWIND NOALIAS BYVAL NEST
1121 %token READNONE READONLY GC
1123 // Visibility Styles
1124 %token DEFAULT HIDDEN PROTECTED
1130 // Operations that are notably excluded from this list include:
1131 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1133 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1134 LogicalOps : SHL | LSHR | ASHR | AND | OR | XOR;
1135 CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1136 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1139 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1140 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1141 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1142 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1143 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1147 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1148 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1149 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1150 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1151 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1152 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1153 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1154 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1155 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1158 // These are some types that allow classification if we only want a particular
1159 // thing... for example, only a signed, unsigned, or integral type.
1161 FPType : FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80;
1163 LocalName : LOCALVAR | STRINGCONSTANT | PCTSTRINGCONSTANT ;
1164 OptLocalName : LocalName | /*empty*/ { $$ = 0; };
1166 OptAddrSpace : ADDRSPACE '(' EUINT64VAL ')' { $$=$3; }
1167 | /*empty*/ { $$=0; };
1169 /// OptLocalAssign - Value producing statements have an optional assignment
1171 OptLocalAssign : LocalName '=' {
1180 GlobalName : GLOBALVAR | ATSTRINGCONSTANT ;
1182 OptGlobalAssign : GlobalAssign
1188 GlobalAssign : GlobalName '=' {
1194 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1195 | WEAK { $$ = GlobalValue::WeakLinkage; }
1196 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1197 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1198 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1199 | COMMON { $$ = GlobalValue::CommonLinkage; }
1203 : DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1204 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1205 | EXTERNAL { $$ = GlobalValue::ExternalLinkage; }
1209 : /*empty*/ { $$ = GlobalValue::DefaultVisibility; }
1210 | DEFAULT { $$ = GlobalValue::DefaultVisibility; }
1211 | HIDDEN { $$ = GlobalValue::HiddenVisibility; }
1212 | PROTECTED { $$ = GlobalValue::ProtectedVisibility; }
1215 FunctionDeclareLinkage
1216 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1217 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1218 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1221 FunctionDefineLinkage
1222 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1223 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1224 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1225 | WEAK { $$ = GlobalValue::WeakLinkage; }
1226 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1230 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1231 | WEAK { $$ = GlobalValue::WeakLinkage; }
1232 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1235 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1236 CCC_TOK { $$ = CallingConv::C; } |
1237 FASTCC_TOK { $$ = CallingConv::Fast; } |
1238 COLDCC_TOK { $$ = CallingConv::Cold; } |
1239 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1240 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1241 X86_SSECALLCC_TOK { $$ = CallingConv::X86_SSECall; } |
1243 if ((unsigned)$2 != $2)
1244 GEN_ERROR("Calling conv too large");
1249 ParamAttr : ZEROEXT { $$ = ParamAttr::ZExt; }
1250 | ZEXT { $$ = ParamAttr::ZExt; }
1251 | SIGNEXT { $$ = ParamAttr::SExt; }
1252 | SEXT { $$ = ParamAttr::SExt; }
1253 | INREG { $$ = ParamAttr::InReg; }
1254 | SRET { $$ = ParamAttr::StructRet; }
1255 | NOALIAS { $$ = ParamAttr::NoAlias; }
1256 | BYVAL { $$ = ParamAttr::ByVal; }
1257 | NEST { $$ = ParamAttr::Nest; }
1258 | ALIGN EUINT64VAL { $$ =
1259 ParamAttr::constructAlignmentFromInt($2); }
1262 OptParamAttrs : /* empty */ { $$ = ParamAttr::None; }
1263 | OptParamAttrs ParamAttr {
1268 FuncAttr : NORETURN { $$ = ParamAttr::NoReturn; }
1269 | NOUNWIND { $$ = ParamAttr::NoUnwind; }
1270 | ZEROEXT { $$ = ParamAttr::ZExt; }
1271 | SIGNEXT { $$ = ParamAttr::SExt; }
1272 | READNONE { $$ = ParamAttr::ReadNone; }
1273 | READONLY { $$ = ParamAttr::ReadOnly; }
1276 OptFuncAttrs : /* empty */ { $$ = ParamAttr::None; }
1277 | OptFuncAttrs FuncAttr {
1282 OptGC : /* empty */ { $$ = 0; }
1283 | GC STRINGCONSTANT {
1288 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1289 // a comma before it.
1290 OptAlign : /*empty*/ { $$ = 0; } |
1293 if ($$ != 0 && !isPowerOf2_32($$))
1294 GEN_ERROR("Alignment must be a power of two");
1297 OptCAlign : /*empty*/ { $$ = 0; } |
1298 ',' ALIGN EUINT64VAL {
1300 if ($$ != 0 && !isPowerOf2_32($$))
1301 GEN_ERROR("Alignment must be a power of two");
1307 SectionString : SECTION STRINGCONSTANT {
1308 for (unsigned i = 0, e = $2->length(); i != e; ++i)
1309 if ((*$2)[i] == '"' || (*$2)[i] == '\\')
1310 GEN_ERROR("Invalid character in section name");
1315 OptSection : /*empty*/ { $$ = 0; } |
1316 SectionString { $$ = $1; };
1318 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1319 // is set to be the global we are processing.
1321 GlobalVarAttributes : /* empty */ {} |
1322 ',' GlobalVarAttribute GlobalVarAttributes {};
1323 GlobalVarAttribute : SectionString {
1324 CurGV->setSection(*$1);
1328 | ALIGN EUINT64VAL {
1329 if ($2 != 0 && !isPowerOf2_32($2))
1330 GEN_ERROR("Alignment must be a power of two");
1331 CurGV->setAlignment($2);
1335 //===----------------------------------------------------------------------===//
1336 // Types includes all predefined types... except void, because it can only be
1337 // used in specific contexts (function returning void for example).
1339 // Derived types are added later...
1341 PrimType : INTTYPE | FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80 | LABEL ;
1345 $$ = new PATypeHolder(OpaqueType::get());
1349 $$ = new PATypeHolder($1);
1352 | Types OptAddrSpace '*' { // Pointer type?
1353 if (*$1 == Type::LabelTy)
1354 GEN_ERROR("Cannot form a pointer to a basic block");
1355 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1, $2)));
1359 | SymbolicValueRef { // Named types are also simple types...
1360 const Type* tmp = getTypeVal($1);
1362 $$ = new PATypeHolder(tmp);
1364 | '\\' EUINT64VAL { // Type UpReference
1365 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range");
1366 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1367 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1368 $$ = new PATypeHolder(OT);
1369 UR_OUT("New Upreference!\n");
1372 | Types '(' ArgTypeListI ')' OptFuncAttrs {
1373 // Allow but ignore attributes on function types; this permits auto-upgrade.
1374 // FIXME: remove in LLVM 3.0.
1375 const Type *RetTy = *$1;
1376 if (!FunctionType::isValidReturnType(RetTy))
1377 GEN_ERROR("Invalid result type for LLVM function");
1379 std::vector<const Type*> Params;
1380 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1381 for (; I != E; ++I ) {
1382 const Type *Ty = I->Ty->get();
1383 Params.push_back(Ty);
1386 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1387 if (isVarArg) Params.pop_back();
1389 for (unsigned i = 0; i != Params.size(); ++i)
1390 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1391 GEN_ERROR("Function arguments must be value types!");
1395 FunctionType *FT = FunctionType::get(RetTy, Params, isVarArg);
1396 delete $3; // Delete the argument list
1397 delete $1; // Delete the return type handle
1398 $$ = new PATypeHolder(HandleUpRefs(FT));
1401 | VOID '(' ArgTypeListI ')' OptFuncAttrs {
1402 // Allow but ignore attributes on function types; this permits auto-upgrade.
1403 // FIXME: remove in LLVM 3.0.
1404 std::vector<const Type*> Params;
1405 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1406 for ( ; I != E; ++I ) {
1407 const Type* Ty = I->Ty->get();
1408 Params.push_back(Ty);
1411 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1412 if (isVarArg) Params.pop_back();
1414 for (unsigned i = 0; i != Params.size(); ++i)
1415 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1416 GEN_ERROR("Function arguments must be value types!");
1420 FunctionType *FT = FunctionType::get($1, Params, isVarArg);
1421 delete $3; // Delete the argument list
1422 $$ = new PATypeHolder(HandleUpRefs(FT));
1426 | '[' EUINT64VAL 'x' Types ']' { // Sized array type?
1427 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, $2)));
1431 | '<' EUINT64VAL 'x' Types '>' { // Vector type?
1432 const llvm::Type* ElemTy = $4->get();
1433 if ((unsigned)$2 != $2)
1434 GEN_ERROR("Unsigned result not equal to signed result");
1435 if (!ElemTy->isFloatingPoint() && !ElemTy->isInteger())
1436 GEN_ERROR("Element type of a VectorType must be primitive");
1437 $$ = new PATypeHolder(HandleUpRefs(VectorType::get(*$4, (unsigned)$2)));
1441 | '{' TypeListI '}' { // Structure type?
1442 std::vector<const Type*> Elements;
1443 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1444 E = $2->end(); I != E; ++I)
1445 Elements.push_back(*I);
1447 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1451 | '{' '}' { // Empty structure type?
1452 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1455 | '<' '{' TypeListI '}' '>' {
1456 std::vector<const Type*> Elements;
1457 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1458 E = $3->end(); I != E; ++I)
1459 Elements.push_back(*I);
1461 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1465 | '<' '{' '}' '>' { // Empty structure type?
1466 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1472 : Types OptParamAttrs {
1473 // Allow but ignore attributes on function types; this permits auto-upgrade.
1474 // FIXME: remove in LLVM 3.0.
1476 $$.Attrs = ParamAttr::None;
1482 if (!UpRefs.empty())
1483 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1484 if (!(*$1)->isFirstClassType() && !isa<StructType>($1->get()))
1485 GEN_ERROR("LLVM functions cannot return aggregate types");
1489 $$ = new PATypeHolder(Type::VoidTy);
1493 ArgTypeList : ArgType {
1494 $$ = new TypeWithAttrsList();
1498 | ArgTypeList ',' ArgType {
1499 ($$=$1)->push_back($3);
1506 | ArgTypeList ',' DOTDOTDOT {
1508 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1509 TWA.Ty = new PATypeHolder(Type::VoidTy);
1514 $$ = new TypeWithAttrsList;
1515 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1516 TWA.Ty = new PATypeHolder(Type::VoidTy);
1521 $$ = new TypeWithAttrsList();
1525 // TypeList - Used for struct declarations and as a basis for function type
1526 // declaration type lists
1529 $$ = new std::list<PATypeHolder>();
1534 | TypeListI ',' Types {
1535 ($$=$1)->push_back(*$3);
1540 // ConstVal - The various declarations that go into the constant pool. This
1541 // production is used ONLY to represent constants that show up AFTER a 'const',
1542 // 'constant' or 'global' token at global scope. Constants that can be inlined
1543 // into other expressions (such as integers and constexprs) are handled by the
1544 // ResolvedVal, ValueRef and ConstValueRef productions.
1546 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1547 if (!UpRefs.empty())
1548 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1549 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1551 GEN_ERROR("Cannot make array constant with type: '" +
1552 (*$1)->getDescription() + "'");
1553 const Type *ETy = ATy->getElementType();
1554 uint64_t NumElements = ATy->getNumElements();
1556 // Verify that we have the correct size...
1557 if (NumElements != uint64_t(-1) && NumElements != $3->size())
1558 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1559 utostr($3->size()) + " arguments, but has size of " +
1560 utostr(NumElements) + "");
1562 // Verify all elements are correct type!
1563 for (unsigned i = 0; i < $3->size(); i++) {
1564 if (ETy != (*$3)[i]->getType())
1565 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1566 ETy->getDescription() +"' as required!\nIt is of type '"+
1567 (*$3)[i]->getType()->getDescription() + "'.");
1570 $$ = ConstantArray::get(ATy, *$3);
1571 delete $1; delete $3;
1575 if (!UpRefs.empty())
1576 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1577 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1579 GEN_ERROR("Cannot make array constant with type: '" +
1580 (*$1)->getDescription() + "'");
1582 uint64_t NumElements = ATy->getNumElements();
1583 if (NumElements != uint64_t(-1) && NumElements != 0)
1584 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1585 " arguments, but has size of " + utostr(NumElements) +"");
1586 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1590 | Types 'c' STRINGCONSTANT {
1591 if (!UpRefs.empty())
1592 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1593 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1595 GEN_ERROR("Cannot make array constant with type: '" +
1596 (*$1)->getDescription() + "'");
1598 uint64_t NumElements = ATy->getNumElements();
1599 const Type *ETy = ATy->getElementType();
1600 if (NumElements != uint64_t(-1) && NumElements != $3->length())
1601 GEN_ERROR("Can't build string constant of size " +
1602 utostr($3->length()) +
1603 " when array has size " + utostr(NumElements) + "");
1604 std::vector<Constant*> Vals;
1605 if (ETy == Type::Int8Ty) {
1606 for (uint64_t i = 0; i < $3->length(); ++i)
1607 Vals.push_back(ConstantInt::get(ETy, (*$3)[i]));
1610 GEN_ERROR("Cannot build string arrays of non byte sized elements");
1613 $$ = ConstantArray::get(ATy, Vals);
1617 | Types '<' ConstVector '>' { // Nonempty unsized arr
1618 if (!UpRefs.empty())
1619 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1620 const VectorType *PTy = dyn_cast<VectorType>($1->get());
1622 GEN_ERROR("Cannot make packed constant with type: '" +
1623 (*$1)->getDescription() + "'");
1624 const Type *ETy = PTy->getElementType();
1625 unsigned NumElements = PTy->getNumElements();
1627 // Verify that we have the correct size...
1628 if (NumElements != unsigned(-1) && NumElements != (unsigned)$3->size())
1629 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1630 utostr($3->size()) + " arguments, but has size of " +
1631 utostr(NumElements) + "");
1633 // Verify all elements are correct type!
1634 for (unsigned i = 0; i < $3->size(); i++) {
1635 if (ETy != (*$3)[i]->getType())
1636 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1637 ETy->getDescription() +"' as required!\nIt is of type '"+
1638 (*$3)[i]->getType()->getDescription() + "'.");
1641 $$ = ConstantVector::get(PTy, *$3);
1642 delete $1; delete $3;
1645 | Types '{' ConstVector '}' {
1646 const StructType *STy = dyn_cast<StructType>($1->get());
1648 GEN_ERROR("Cannot make struct constant with type: '" +
1649 (*$1)->getDescription() + "'");
1651 if ($3->size() != STy->getNumContainedTypes())
1652 GEN_ERROR("Illegal number of initializers for structure type");
1654 // Check to ensure that constants are compatible with the type initializer!
1655 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1656 if ((*$3)[i]->getType() != STy->getElementType(i))
1657 GEN_ERROR("Expected type '" +
1658 STy->getElementType(i)->getDescription() +
1659 "' for element #" + utostr(i) +
1660 " of structure initializer");
1662 // Check to ensure that Type is not packed
1663 if (STy->isPacked())
1664 GEN_ERROR("Unpacked Initializer to vector type '" +
1665 STy->getDescription() + "'");
1667 $$ = ConstantStruct::get(STy, *$3);
1668 delete $1; delete $3;
1672 if (!UpRefs.empty())
1673 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1674 const StructType *STy = dyn_cast<StructType>($1->get());
1676 GEN_ERROR("Cannot make struct constant with type: '" +
1677 (*$1)->getDescription() + "'");
1679 if (STy->getNumContainedTypes() != 0)
1680 GEN_ERROR("Illegal number of initializers for structure type");
1682 // Check to ensure that Type is not packed
1683 if (STy->isPacked())
1684 GEN_ERROR("Unpacked Initializer to vector type '" +
1685 STy->getDescription() + "'");
1687 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1691 | Types '<' '{' ConstVector '}' '>' {
1692 const StructType *STy = dyn_cast<StructType>($1->get());
1694 GEN_ERROR("Cannot make struct constant with type: '" +
1695 (*$1)->getDescription() + "'");
1697 if ($4->size() != STy->getNumContainedTypes())
1698 GEN_ERROR("Illegal number of initializers for structure type");
1700 // Check to ensure that constants are compatible with the type initializer!
1701 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1702 if ((*$4)[i]->getType() != STy->getElementType(i))
1703 GEN_ERROR("Expected type '" +
1704 STy->getElementType(i)->getDescription() +
1705 "' for element #" + utostr(i) +
1706 " of structure initializer");
1708 // Check to ensure that Type is packed
1709 if (!STy->isPacked())
1710 GEN_ERROR("Vector initializer to non-vector type '" +
1711 STy->getDescription() + "'");
1713 $$ = ConstantStruct::get(STy, *$4);
1714 delete $1; delete $4;
1717 | Types '<' '{' '}' '>' {
1718 if (!UpRefs.empty())
1719 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1720 const StructType *STy = dyn_cast<StructType>($1->get());
1722 GEN_ERROR("Cannot make struct constant with type: '" +
1723 (*$1)->getDescription() + "'");
1725 if (STy->getNumContainedTypes() != 0)
1726 GEN_ERROR("Illegal number of initializers for structure type");
1728 // Check to ensure that Type is packed
1729 if (!STy->isPacked())
1730 GEN_ERROR("Vector initializer to non-vector type '" +
1731 STy->getDescription() + "'");
1733 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1738 if (!UpRefs.empty())
1739 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1740 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1742 GEN_ERROR("Cannot make null pointer constant with type: '" +
1743 (*$1)->getDescription() + "'");
1745 $$ = ConstantPointerNull::get(PTy);
1750 if (!UpRefs.empty())
1751 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1752 $$ = UndefValue::get($1->get());
1756 | Types SymbolicValueRef {
1757 if (!UpRefs.empty())
1758 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1759 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1761 GEN_ERROR("Global const reference must be a pointer type " + (*$1)->getDescription());
1763 // ConstExprs can exist in the body of a function, thus creating
1764 // GlobalValues whenever they refer to a variable. Because we are in
1765 // the context of a function, getExistingVal will search the functions
1766 // symbol table instead of the module symbol table for the global symbol,
1767 // which throws things all off. To get around this, we just tell
1768 // getExistingVal that we are at global scope here.
1770 Function *SavedCurFn = CurFun.CurrentFunction;
1771 CurFun.CurrentFunction = 0;
1773 Value *V = getExistingVal(Ty, $2);
1776 CurFun.CurrentFunction = SavedCurFn;
1778 // If this is an initializer for a constant pointer, which is referencing a
1779 // (currently) undefined variable, create a stub now that shall be replaced
1780 // in the future with the right type of variable.
1783 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1784 const PointerType *PT = cast<PointerType>(Ty);
1786 // First check to see if the forward references value is already created!
1787 PerModuleInfo::GlobalRefsType::iterator I =
1788 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1790 if (I != CurModule.GlobalRefs.end()) {
1791 V = I->second; // Placeholder already exists, use it...
1795 if ($2.Type == ValID::GlobalName)
1796 Name = $2.getName();
1797 else if ($2.Type != ValID::GlobalID)
1798 GEN_ERROR("Invalid reference to global");
1800 // Create the forward referenced global.
1802 if (const FunctionType *FTy =
1803 dyn_cast<FunctionType>(PT->getElementType())) {
1804 GV = Function::Create(FTy, GlobalValue::ExternalWeakLinkage, Name,
1805 CurModule.CurrentModule);
1807 GV = new GlobalVariable(PT->getElementType(), false,
1808 GlobalValue::ExternalWeakLinkage, 0,
1809 Name, CurModule.CurrentModule);
1812 // Keep track of the fact that we have a forward ref to recycle it
1813 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1818 $$ = cast<GlobalValue>(V);
1819 delete $1; // Free the type handle
1823 if (!UpRefs.empty())
1824 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1825 if ($1->get() != $2->getType())
1826 GEN_ERROR("Mismatched types for constant expression: " +
1827 (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1832 | Types ZEROINITIALIZER {
1833 if (!UpRefs.empty())
1834 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1835 const Type *Ty = $1->get();
1836 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1837 GEN_ERROR("Cannot create a null initialized value of this type");
1838 $$ = Constant::getNullValue(Ty);
1842 | IntType ESINT64VAL { // integral constants
1843 if (!ConstantInt::isValueValidForType($1, $2))
1844 GEN_ERROR("Constant value doesn't fit in type");
1845 $$ = ConstantInt::get($1, $2, true);
1848 | IntType ESAPINTVAL { // arbitrary precision integer constants
1849 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1850 if ($2->getBitWidth() > BitWidth) {
1851 GEN_ERROR("Constant value does not fit in type");
1853 $2->sextOrTrunc(BitWidth);
1854 $$ = ConstantInt::get(*$2);
1858 | IntType EUINT64VAL { // integral constants
1859 if (!ConstantInt::isValueValidForType($1, $2))
1860 GEN_ERROR("Constant value doesn't fit in type");
1861 $$ = ConstantInt::get($1, $2, false);
1864 | IntType EUAPINTVAL { // arbitrary precision integer constants
1865 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1866 if ($2->getBitWidth() > BitWidth) {
1867 GEN_ERROR("Constant value does not fit in type");
1869 $2->zextOrTrunc(BitWidth);
1870 $$ = ConstantInt::get(*$2);
1874 | INTTYPE TRUETOK { // Boolean constants
1875 if (cast<IntegerType>($1)->getBitWidth() != 1)
1876 GEN_ERROR("Constant true must have type i1");
1877 $$ = ConstantInt::getTrue();
1880 | INTTYPE FALSETOK { // Boolean constants
1881 if (cast<IntegerType>($1)->getBitWidth() != 1)
1882 GEN_ERROR("Constant false must have type i1");
1883 $$ = ConstantInt::getFalse();
1886 | FPType FPVAL { // Floating point constants
1887 if (!ConstantFP::isValueValidForType($1, *$2))
1888 GEN_ERROR("Floating point constant invalid for type");
1889 // Lexer has no type info, so builds all float and double FP constants
1890 // as double. Fix this here. Long double is done right.
1891 if (&$2->getSemantics()==&APFloat::IEEEdouble && $1==Type::FloatTy)
1892 $2->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
1893 $$ = ConstantFP::get(*$2);
1899 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1900 if (!UpRefs.empty())
1901 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1903 const Type *DestTy = $5->get();
1904 if (!CastInst::castIsValid($1, $3, DestTy))
1905 GEN_ERROR("invalid cast opcode for cast from '" +
1906 Val->getType()->getDescription() + "' to '" +
1907 DestTy->getDescription() + "'");
1908 $$ = ConstantExpr::getCast($1, $3, DestTy);
1911 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1912 if (!isa<PointerType>($3->getType()))
1913 GEN_ERROR("GetElementPtr requires a pointer operand");
1916 GetElementPtrInst::getIndexedType($3->getType(), $4->begin(), $4->end());
1918 GEN_ERROR("Index list invalid for constant getelementptr");
1920 SmallVector<Constant*, 8> IdxVec;
1921 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1922 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1923 IdxVec.push_back(C);
1925 GEN_ERROR("Indices to constant getelementptr must be constants");
1929 $$ = ConstantExpr::getGetElementPtr($3, &IdxVec[0], IdxVec.size());
1932 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1933 if ($3->getType() != Type::Int1Ty)
1934 GEN_ERROR("Select condition must be of boolean type");
1935 if ($5->getType() != $7->getType())
1936 GEN_ERROR("Select operand types must match");
1937 $$ = ConstantExpr::getSelect($3, $5, $7);
1940 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1941 if ($3->getType() != $5->getType())
1942 GEN_ERROR("Binary operator types must match");
1944 $$ = ConstantExpr::get($1, $3, $5);
1946 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1947 if ($3->getType() != $5->getType())
1948 GEN_ERROR("Logical operator types must match");
1949 if (!$3->getType()->isInteger()) {
1950 if (!isa<VectorType>($3->getType()) ||
1951 !cast<VectorType>($3->getType())->getElementType()->isInteger())
1952 GEN_ERROR("Logical operator requires integral operands");
1954 $$ = ConstantExpr::get($1, $3, $5);
1957 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1958 if ($4->getType() != $6->getType())
1959 GEN_ERROR("icmp operand types must match");
1960 $$ = ConstantExpr::getICmp($2, $4, $6);
1962 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1963 if ($4->getType() != $6->getType())
1964 GEN_ERROR("fcmp operand types must match");
1965 $$ = ConstantExpr::getFCmp($2, $4, $6);
1967 | VICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1968 if ($4->getType() != $6->getType())
1969 GEN_ERROR("vicmp operand types must match");
1970 $$ = ConstantExpr::getVICmp($2, $4, $6);
1972 | VFCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1973 if ($4->getType() != $6->getType())
1974 GEN_ERROR("vfcmp operand types must match");
1975 $$ = ConstantExpr::getVFCmp($2, $4, $6);
1977 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1978 if (!ExtractElementInst::isValidOperands($3, $5))
1979 GEN_ERROR("Invalid extractelement operands");
1980 $$ = ConstantExpr::getExtractElement($3, $5);
1983 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1984 if (!InsertElementInst::isValidOperands($3, $5, $7))
1985 GEN_ERROR("Invalid insertelement operands");
1986 $$ = ConstantExpr::getInsertElement($3, $5, $7);
1989 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1990 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1991 GEN_ERROR("Invalid shufflevector operands");
1992 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1995 | EXTRACTVALUE '(' ConstVal ConstantIndexList ')' {
1996 if (!isa<StructType>($3->getType()) && !isa<ArrayType>($3->getType()))
1997 GEN_ERROR("ExtractValue requires an aggregate operand");
1999 $$ = ConstantExpr::getExtractValue($3, &(*$4)[0], $4->size());
2003 | INSERTVALUE '(' ConstVal ',' ConstVal ConstantIndexList ')' {
2004 if (!isa<StructType>($3->getType()) && !isa<ArrayType>($3->getType()))
2005 GEN_ERROR("InsertValue requires an aggregate operand");
2007 $$ = ConstantExpr::getInsertValue($3, $5, &(*$6)[0], $6->size());
2013 // ConstVector - A list of comma separated constants.
2014 ConstVector : ConstVector ',' ConstVal {
2015 ($$ = $1)->push_back($3);
2019 $$ = new std::vector<Constant*>();
2025 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
2026 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
2029 ThreadLocal : THREAD_LOCAL { $$ = true; } | { $$ = false; };
2031 // AliaseeRef - Match either GlobalValue or bitcast to GlobalValue.
2032 AliaseeRef : ResultTypes SymbolicValueRef {
2033 const Type* VTy = $1->get();
2034 Value *V = getVal(VTy, $2);
2036 GlobalValue* Aliasee = dyn_cast<GlobalValue>(V);
2038 GEN_ERROR("Aliases can be created only to global values");
2044 | BITCAST '(' AliaseeRef TO Types ')' {
2046 const Type *DestTy = $5->get();
2047 if (!CastInst::castIsValid($1, $3, DestTy))
2048 GEN_ERROR("invalid cast opcode for cast from '" +
2049 Val->getType()->getDescription() + "' to '" +
2050 DestTy->getDescription() + "'");
2052 $$ = ConstantExpr::getCast($1, $3, DestTy);
2057 //===----------------------------------------------------------------------===//
2058 // Rules to match Modules
2059 //===----------------------------------------------------------------------===//
2061 // Module rule: Capture the result of parsing the whole file into a result
2066 $$ = ParserResult = CurModule.CurrentModule;
2067 CurModule.ModuleDone();
2071 $$ = ParserResult = CurModule.CurrentModule;
2072 CurModule.ModuleDone();
2079 | DefinitionList Definition
2083 : DEFINE { CurFun.isDeclare = false; } Function {
2084 CurFun.FunctionDone();
2087 | DECLARE { CurFun.isDeclare = true; } FunctionProto {
2090 | MODULE ASM_TOK AsmBlock {
2093 | OptLocalAssign TYPE Types {
2094 if (!UpRefs.empty())
2095 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2096 // Eagerly resolve types. This is not an optimization, this is a
2097 // requirement that is due to the fact that we could have this:
2099 // %list = type { %list * }
2100 // %list = type { %list * } ; repeated type decl
2102 // If types are not resolved eagerly, then the two types will not be
2103 // determined to be the same type!
2105 ResolveTypeTo($1, *$3);
2107 if (!setTypeName(*$3, $1) && !$1) {
2109 // If this is a named type that is not a redefinition, add it to the slot
2111 CurModule.Types.push_back(*$3);
2117 | OptLocalAssign TYPE VOID {
2118 ResolveTypeTo($1, $3);
2120 if (!setTypeName($3, $1) && !$1) {
2122 // If this is a named type that is not a redefinition, add it to the slot
2124 CurModule.Types.push_back($3);
2128 | OptGlobalAssign GVVisibilityStyle ThreadLocal GlobalType ConstVal
2130 /* "Externally Visible" Linkage */
2132 GEN_ERROR("Global value initializer is not a constant");
2133 CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
2134 $2, $4, $5->getType(), $5, $3, $6);
2136 } GlobalVarAttributes {
2139 | OptGlobalAssign GVInternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2140 ConstVal OptAddrSpace {
2142 GEN_ERROR("Global value initializer is not a constant");
2143 CurGV = ParseGlobalVariable($1, $2, $3, $5, $6->getType(), $6, $4, $7);
2145 } GlobalVarAttributes {
2148 | OptGlobalAssign GVExternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2149 Types OptAddrSpace {
2150 if (!UpRefs.empty())
2151 GEN_ERROR("Invalid upreference in type: " + (*$6)->getDescription());
2152 CurGV = ParseGlobalVariable($1, $2, $3, $5, *$6, 0, $4, $7);
2155 } GlobalVarAttributes {
2159 | OptGlobalAssign GVVisibilityStyle ALIAS AliasLinkage AliaseeRef {
2166 GEN_ERROR("Alias name cannot be empty");
2168 Constant* Aliasee = $5;
2170 GEN_ERROR(std::string("Invalid aliasee for alias: ") + Name);
2172 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(), $4, Name, Aliasee,
2173 CurModule.CurrentModule);
2174 GA->setVisibility($2);
2175 InsertValue(GA, CurModule.Values);
2178 // If there was a forward reference of this alias, resolve it now.
2182 ID = ValID::createGlobalName(Name);
2184 ID = ValID::createGlobalID(CurModule.Values.size()-1);
2186 if (GlobalValue *FWGV =
2187 CurModule.GetForwardRefForGlobal(GA->getType(), ID)) {
2188 // Replace uses of the fwdref with the actual alias.
2189 FWGV->replaceAllUsesWith(GA);
2190 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(FWGV))
2191 GV->eraseFromParent();
2193 cast<Function>(FWGV)->eraseFromParent();
2199 | TARGET TargetDefinition {
2202 | DEPLIBS '=' LibrariesDefinition {
2208 AsmBlock : STRINGCONSTANT {
2209 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2210 if (AsmSoFar.empty())
2211 CurModule.CurrentModule->setModuleInlineAsm(*$1);
2213 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+*$1);
2218 TargetDefinition : TRIPLE '=' STRINGCONSTANT {
2219 CurModule.CurrentModule->setTargetTriple(*$3);
2222 | DATALAYOUT '=' STRINGCONSTANT {
2223 CurModule.CurrentModule->setDataLayout(*$3);
2227 LibrariesDefinition : '[' LibList ']';
2229 LibList : LibList ',' STRINGCONSTANT {
2230 CurModule.CurrentModule->addLibrary(*$3);
2235 CurModule.CurrentModule->addLibrary(*$1);
2239 | /* empty: end of list */ {
2244 //===----------------------------------------------------------------------===//
2245 // Rules to match Function Headers
2246 //===----------------------------------------------------------------------===//
2248 ArgListH : ArgListH ',' Types OptParamAttrs OptLocalName {
2249 if (!UpRefs.empty())
2250 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2251 if (!(*$3)->isFirstClassType())
2252 GEN_ERROR("Argument types must be first-class");
2253 ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
2258 | Types OptParamAttrs OptLocalName {
2259 if (!UpRefs.empty())
2260 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2261 if (!(*$1)->isFirstClassType())
2262 GEN_ERROR("Argument types must be first-class");
2263 ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2264 $$ = new ArgListType;
2269 ArgList : ArgListH {
2273 | ArgListH ',' DOTDOTDOT {
2275 struct ArgListEntry E;
2276 E.Ty = new PATypeHolder(Type::VoidTy);
2278 E.Attrs = ParamAttr::None;
2283 $$ = new ArgListType;
2284 struct ArgListEntry E;
2285 E.Ty = new PATypeHolder(Type::VoidTy);
2287 E.Attrs = ParamAttr::None;
2296 FunctionHeaderH : OptCallingConv ResultTypes GlobalName '(' ArgList ')'
2297 OptFuncAttrs OptSection OptAlign OptGC {
2298 std::string FunctionName(*$3);
2299 delete $3; // Free strdup'd memory!
2301 // Check the function result for abstractness if this is a define. We should
2302 // have no abstract types at this point
2303 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($2))
2304 GEN_ERROR("Reference to abstract result: "+ $2->get()->getDescription());
2306 if (!FunctionType::isValidReturnType(*$2))
2307 GEN_ERROR("Invalid result type for LLVM function");
2309 std::vector<const Type*> ParamTypeList;
2310 SmallVector<ParamAttrsWithIndex, 8> Attrs;
2311 if ($7 != ParamAttr::None)
2312 Attrs.push_back(ParamAttrsWithIndex::get(0, $7));
2313 if ($5) { // If there are arguments...
2315 for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I, ++index) {
2316 const Type* Ty = I->Ty->get();
2317 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2318 GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2319 ParamTypeList.push_back(Ty);
2320 if (Ty != Type::VoidTy && I->Attrs != ParamAttr::None)
2321 Attrs.push_back(ParamAttrsWithIndex::get(index, I->Attrs));
2325 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2326 if (isVarArg) ParamTypeList.pop_back();
2330 PAL = PAListPtr::get(Attrs.begin(), Attrs.end());
2332 FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
2333 const PointerType *PFT = PointerType::getUnqual(FT);
2337 if (!FunctionName.empty()) {
2338 ID = ValID::createGlobalName((char*)FunctionName.c_str());
2340 ID = ValID::createGlobalID(CurModule.Values.size());
2344 // See if this function was forward referenced. If so, recycle the object.
2345 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2346 // Move the function to the end of the list, from whereever it was
2347 // previously inserted.
2348 Fn = cast<Function>(FWRef);
2349 assert(Fn->getParamAttrs().isEmpty() &&
2350 "Forward reference has parameter attributes!");
2351 CurModule.CurrentModule->getFunctionList().remove(Fn);
2352 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2353 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2354 (Fn = CurModule.CurrentModule->getFunction(FunctionName))) {
2355 if (Fn->getFunctionType() != FT ) {
2356 // The existing function doesn't have the same type. This is an overload
2358 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2359 } else if (Fn->getParamAttrs() != PAL) {
2360 // The existing function doesn't have the same parameter attributes.
2361 // This is an overload error.
2362 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2363 } else if (!CurFun.isDeclare && !Fn->isDeclaration()) {
2364 // Neither the existing or the current function is a declaration and they
2365 // have the same name and same type. Clearly this is a redefinition.
2366 GEN_ERROR("Redefinition of function '" + FunctionName + "'");
2367 } else if (Fn->isDeclaration()) {
2368 // Make sure to strip off any argument names so we can't get conflicts.
2369 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2373 } else { // Not already defined?
2374 Fn = Function::Create(FT, GlobalValue::ExternalWeakLinkage, FunctionName,
2375 CurModule.CurrentModule);
2376 InsertValue(Fn, CurModule.Values);
2379 CurFun.FunctionStart(Fn);
2381 if (CurFun.isDeclare) {
2382 // If we have declaration, always overwrite linkage. This will allow us to
2383 // correctly handle cases, when pointer to function is passed as argument to
2384 // another function.
2385 Fn->setLinkage(CurFun.Linkage);
2386 Fn->setVisibility(CurFun.Visibility);
2388 Fn->setCallingConv($1);
2389 Fn->setParamAttrs(PAL);
2390 Fn->setAlignment($9);
2392 Fn->setSection(*$8);
2396 Fn->setCollector($10->c_str());
2400 // Add all of the arguments we parsed to the function...
2401 if ($5) { // Is null if empty...
2402 if (isVarArg) { // Nuke the last entry
2403 assert($5->back().Ty->get() == Type::VoidTy && $5->back().Name == 0 &&
2404 "Not a varargs marker!");
2405 delete $5->back().Ty;
2406 $5->pop_back(); // Delete the last entry
2408 Function::arg_iterator ArgIt = Fn->arg_begin();
2409 Function::arg_iterator ArgEnd = Fn->arg_end();
2411 for (ArgListType::iterator I = $5->begin();
2412 I != $5->end() && ArgIt != ArgEnd; ++I, ++ArgIt) {
2413 delete I->Ty; // Delete the typeholder...
2414 setValueName(ArgIt, I->Name); // Insert arg into symtab...
2420 delete $5; // We're now done with the argument list
2425 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2427 FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2428 $$ = CurFun.CurrentFunction;
2430 // Make sure that we keep track of the linkage type even if there was a
2431 // previous "declare".
2433 $$->setVisibility($2);
2436 END : ENDTOK | '}'; // Allow end of '}' to end a function
2438 Function : BasicBlockList END {
2443 FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2444 CurFun.CurrentFunction->setLinkage($1);
2445 CurFun.CurrentFunction->setVisibility($2);
2446 $$ = CurFun.CurrentFunction;
2447 CurFun.FunctionDone();
2451 //===----------------------------------------------------------------------===//
2452 // Rules to match Basic Blocks
2453 //===----------------------------------------------------------------------===//
2455 OptSideEffect : /* empty */ {
2464 ConstValueRef : ESINT64VAL { // A reference to a direct constant
2465 $$ = ValID::create($1);
2469 $$ = ValID::create($1);
2472 | ESAPINTVAL { // arbitrary precision integer constants
2473 $$ = ValID::create(*$1, true);
2477 | EUAPINTVAL { // arbitrary precision integer constants
2478 $$ = ValID::create(*$1, false);
2482 | FPVAL { // Perhaps it's an FP constant?
2483 $$ = ValID::create($1);
2487 $$ = ValID::create(ConstantInt::getTrue());
2491 $$ = ValID::create(ConstantInt::getFalse());
2495 $$ = ValID::createNull();
2499 $$ = ValID::createUndef();
2502 | ZEROINITIALIZER { // A vector zero constant.
2503 $$ = ValID::createZeroInit();
2506 | '<' ConstVector '>' { // Nonempty unsized packed vector
2507 const Type *ETy = (*$2)[0]->getType();
2508 unsigned NumElements = $2->size();
2510 if (!ETy->isInteger() && !ETy->isFloatingPoint())
2511 GEN_ERROR("Invalid vector element type: " + ETy->getDescription());
2513 VectorType* pt = VectorType::get(ETy, NumElements);
2514 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(pt));
2516 // Verify all elements are correct type!
2517 for (unsigned i = 0; i < $2->size(); i++) {
2518 if (ETy != (*$2)[i]->getType())
2519 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2520 ETy->getDescription() +"' as required!\nIt is of type '" +
2521 (*$2)[i]->getType()->getDescription() + "'.");
2524 $$ = ValID::create(ConstantVector::get(pt, *$2));
2525 delete PTy; delete $2;
2528 | '[' ConstVector ']' { // Nonempty unsized arr
2529 const Type *ETy = (*$2)[0]->getType();
2530 uint64_t NumElements = $2->size();
2532 if (!ETy->isFirstClassType())
2533 GEN_ERROR("Invalid array element type: " + ETy->getDescription());
2535 ArrayType *ATy = ArrayType::get(ETy, NumElements);
2536 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(ATy));
2538 // Verify all elements are correct type!
2539 for (unsigned i = 0; i < $2->size(); i++) {
2540 if (ETy != (*$2)[i]->getType())
2541 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2542 ETy->getDescription() +"' as required!\nIt is of type '"+
2543 (*$2)[i]->getType()->getDescription() + "'.");
2546 $$ = ValID::create(ConstantArray::get(ATy, *$2));
2547 delete PTy; delete $2;
2551 // Use undef instead of an array because it's inconvenient to determine
2552 // the element type at this point, there being no elements to examine.
2553 $$ = ValID::createUndef();
2556 | 'c' STRINGCONSTANT {
2557 uint64_t NumElements = $2->length();
2558 const Type *ETy = Type::Int8Ty;
2560 ArrayType *ATy = ArrayType::get(ETy, NumElements);
2562 std::vector<Constant*> Vals;
2563 for (unsigned i = 0; i < $2->length(); ++i)
2564 Vals.push_back(ConstantInt::get(ETy, (*$2)[i]));
2566 $$ = ValID::create(ConstantArray::get(ATy, Vals));
2569 | '{' ConstVector '}' {
2570 std::vector<const Type*> Elements($2->size());
2571 for (unsigned i = 0, e = $2->size(); i != e; ++i)
2572 Elements[i] = (*$2)[i]->getType();
2574 const StructType *STy = StructType::get(Elements);
2575 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(STy));
2577 $$ = ValID::create(ConstantStruct::get(STy, *$2));
2578 delete PTy; delete $2;
2582 const StructType *STy = StructType::get(std::vector<const Type*>());
2583 $$ = ValID::create(ConstantStruct::get(STy, std::vector<Constant*>()));
2586 | '<' '{' ConstVector '}' '>' {
2587 std::vector<const Type*> Elements($3->size());
2588 for (unsigned i = 0, e = $3->size(); i != e; ++i)
2589 Elements[i] = (*$3)[i]->getType();
2591 const StructType *STy = StructType::get(Elements, /*isPacked=*/true);
2592 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(STy));
2594 $$ = ValID::create(ConstantStruct::get(STy, *$3));
2595 delete PTy; delete $3;
2599 const StructType *STy = StructType::get(std::vector<const Type*>(),
2601 $$ = ValID::create(ConstantStruct::get(STy, std::vector<Constant*>()));
2605 $$ = ValID::create($1);
2608 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2609 $$ = ValID::createInlineAsm(*$3, *$5, $2);
2615 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2618 SymbolicValueRef : LOCALVAL_ID { // Is it an integer reference...?
2619 $$ = ValID::createLocalID($1);
2623 $$ = ValID::createGlobalID($1);
2626 | LocalName { // Is it a named reference...?
2627 $$ = ValID::createLocalName(*$1);
2631 | GlobalName { // Is it a named reference...?
2632 $$ = ValID::createGlobalName(*$1);
2637 // ValueRef - A reference to a definition... either constant or symbolic
2638 ValueRef : SymbolicValueRef | ConstValueRef;
2641 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2642 // type immediately preceeds the value reference, and allows complex constant
2643 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2644 ResolvedVal : Types ValueRef {
2645 if (!UpRefs.empty())
2646 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2647 $$ = getVal(*$1, $2);
2653 ReturnedVal : ResolvedVal {
2654 $$ = new std::vector<Value *>();
2658 | ReturnedVal ',' ResolvedVal {
2659 ($$=$1)->push_back($3);
2663 BasicBlockList : BasicBlockList BasicBlock {
2667 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2673 // Basic blocks are terminated by branching instructions:
2674 // br, br/cc, switch, ret
2676 BasicBlock : InstructionList OptLocalAssign BBTerminatorInst {
2677 setValueName($3, $2);
2680 $1->getInstList().push_back($3);
2685 InstructionList : InstructionList Inst {
2686 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2687 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2688 if (CI2->getParent() == 0)
2689 $1->getInstList().push_back(CI2);
2690 $1->getInstList().push_back($2);
2694 | /* empty */ { // Empty space between instruction lists
2695 $$ = defineBBVal(ValID::createLocalID(CurFun.NextValNum));
2698 | LABELSTR { // Labelled (named) basic block
2699 $$ = defineBBVal(ValID::createLocalName(*$1));
2706 RET ReturnedVal { // Return with a result...
2707 ValueList &VL = *$2;
2708 assert(!VL.empty() && "Invalid ret operands!");
2709 const Type *ReturnType = CurFun.CurrentFunction->getReturnType();
2710 if (VL.size() > 1 ||
2711 (isa<StructType>(ReturnType) &&
2712 (VL.empty() || VL[0]->getType() != ReturnType))) {
2713 Value *RV = UndefValue::get(ReturnType);
2714 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
2715 Instruction *I = InsertValueInst::Create(RV, VL[i], i, "mrv");
2716 ($<BasicBlockVal>-1)->getInstList().push_back(I);
2719 $$ = ReturnInst::Create(RV);
2721 $$ = ReturnInst::Create(VL[0]);
2726 | RET VOID { // Return with no result...
2727 $$ = ReturnInst::Create();
2730 | BR LABEL ValueRef { // Unconditional Branch...
2731 BasicBlock* tmpBB = getBBVal($3);
2733 $$ = BranchInst::Create(tmpBB);
2734 } // Conditional Branch...
2735 | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2736 if (cast<IntegerType>($2)->getBitWidth() != 1)
2737 GEN_ERROR("Branch condition must have type i1");
2738 BasicBlock* tmpBBA = getBBVal($6);
2740 BasicBlock* tmpBBB = getBBVal($9);
2742 Value* tmpVal = getVal(Type::Int1Ty, $3);
2744 $$ = BranchInst::Create(tmpBBA, tmpBBB, tmpVal);
2746 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2747 Value* tmpVal = getVal($2, $3);
2749 BasicBlock* tmpBB = getBBVal($6);
2751 SwitchInst *S = SwitchInst::Create(tmpVal, tmpBB, $8->size());
2754 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2756 for (; I != E; ++I) {
2757 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2758 S->addCase(CI, I->second);
2760 GEN_ERROR("Switch case is constant, but not a simple integer");
2765 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2766 Value* tmpVal = getVal($2, $3);
2768 BasicBlock* tmpBB = getBBVal($6);
2770 SwitchInst *S = SwitchInst::Create(tmpVal, tmpBB, 0);
2774 | INVOKE OptCallingConv ResultTypes ValueRef '(' ParamList ')' OptFuncAttrs
2775 TO LABEL ValueRef UNWIND LABEL ValueRef {
2777 // Handle the short syntax
2778 const PointerType *PFTy = 0;
2779 const FunctionType *Ty = 0;
2780 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2781 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2782 // Pull out the types of all of the arguments...
2783 std::vector<const Type*> ParamTypes;
2784 ParamList::iterator I = $6->begin(), E = $6->end();
2785 for (; I != E; ++I) {
2786 const Type *Ty = I->Val->getType();
2787 if (Ty == Type::VoidTy)
2788 GEN_ERROR("Short call syntax cannot be used with varargs");
2789 ParamTypes.push_back(Ty);
2792 if (!FunctionType::isValidReturnType(*$3))
2793 GEN_ERROR("Invalid result type for LLVM function");
2795 Ty = FunctionType::get($3->get(), ParamTypes, false);
2796 PFTy = PointerType::getUnqual(Ty);
2801 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2803 BasicBlock *Normal = getBBVal($11);
2805 BasicBlock *Except = getBBVal($14);
2808 SmallVector<ParamAttrsWithIndex, 8> Attrs;
2809 if ($8 != ParamAttr::None)
2810 Attrs.push_back(ParamAttrsWithIndex::get(0, $8));
2812 // Check the arguments
2814 if ($6->empty()) { // Has no arguments?
2815 // Make sure no arguments is a good thing!
2816 if (Ty->getNumParams() != 0)
2817 GEN_ERROR("No arguments passed to a function that "
2818 "expects arguments");
2819 } else { // Has arguments?
2820 // Loop through FunctionType's arguments and ensure they are specified
2822 FunctionType::param_iterator I = Ty->param_begin();
2823 FunctionType::param_iterator E = Ty->param_end();
2824 ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
2827 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
2828 if (ArgI->Val->getType() != *I)
2829 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2830 (*I)->getDescription() + "'");
2831 Args.push_back(ArgI->Val);
2832 if (ArgI->Attrs != ParamAttr::None)
2833 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
2836 if (Ty->isVarArg()) {
2838 for (; ArgI != ArgE; ++ArgI, ++index) {
2839 Args.push_back(ArgI->Val); // push the remaining varargs
2840 if (ArgI->Attrs != ParamAttr::None)
2841 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
2843 } else if (I != E || ArgI != ArgE)
2844 GEN_ERROR("Invalid number of parameters detected");
2849 PAL = PAListPtr::get(Attrs.begin(), Attrs.end());
2851 // Create the InvokeInst
2852 InvokeInst *II = InvokeInst::Create(V, Normal, Except,
2853 Args.begin(), Args.end());
2854 II->setCallingConv($2);
2855 II->setParamAttrs(PAL);
2861 $$ = new UnwindInst();
2865 $$ = new UnreachableInst();
2871 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2873 Constant *V = cast<Constant>(getExistingVal($2, $3));
2876 GEN_ERROR("May only switch on a constant pool value");
2878 BasicBlock* tmpBB = getBBVal($6);
2880 $$->push_back(std::make_pair(V, tmpBB));
2882 | IntType ConstValueRef ',' LABEL ValueRef {
2883 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2884 Constant *V = cast<Constant>(getExistingVal($1, $2));
2888 GEN_ERROR("May only switch on a constant pool value");
2890 BasicBlock* tmpBB = getBBVal($5);
2892 $$->push_back(std::make_pair(V, tmpBB));
2895 Inst : OptLocalAssign InstVal {
2896 // Is this definition named?? if so, assign the name...
2897 setValueName($2, $1);
2905 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2906 if (!UpRefs.empty())
2907 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2908 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2909 Value* tmpVal = getVal(*$1, $3);
2911 BasicBlock* tmpBB = getBBVal($5);
2913 $$->push_back(std::make_pair(tmpVal, tmpBB));
2916 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2918 Value* tmpVal = getVal($1->front().first->getType(), $4);
2920 BasicBlock* tmpBB = getBBVal($6);
2922 $1->push_back(std::make_pair(tmpVal, tmpBB));
2926 ParamList : Types OptParamAttrs ValueRef OptParamAttrs {
2927 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2928 if (!UpRefs.empty())
2929 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2930 // Used for call and invoke instructions
2931 $$ = new ParamList();
2932 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getVal($1->get(), $3);
2937 | LABEL OptParamAttrs ValueRef OptParamAttrs {
2938 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2939 // Labels are only valid in ASMs
2940 $$ = new ParamList();
2941 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getBBVal($3);
2945 | ParamList ',' Types OptParamAttrs ValueRef OptParamAttrs {
2946 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2947 if (!UpRefs.empty())
2948 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2950 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getVal($3->get(), $5);
2955 | ParamList ',' LABEL OptParamAttrs ValueRef OptParamAttrs {
2956 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2958 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getBBVal($5);
2962 | /*empty*/ { $$ = new ParamList(); };
2964 IndexList // Used for gep instructions and constant expressions
2965 : /*empty*/ { $$ = new std::vector<Value*>(); }
2966 | IndexList ',' ResolvedVal {
2973 ConstantIndexList // Used for insertvalue and extractvalue instructions
2975 $$ = new std::vector<unsigned>();
2976 if ((unsigned)$2 != $2)
2977 GEN_ERROR("Index " + utostr($2) + " is not valid for insertvalue or extractvalue.");
2980 | ConstantIndexList ',' EUINT64VAL {
2982 if ((unsigned)$3 != $3)
2983 GEN_ERROR("Index " + utostr($3) + " is not valid for insertvalue or extractvalue.");
2989 OptTailCall : TAIL CALL {
2998 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2999 if (!UpRefs.empty())
3000 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3001 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
3002 !isa<VectorType>((*$2).get()))
3004 "Arithmetic operator requires integer, FP, or packed operands");
3005 Value* val1 = getVal(*$2, $3);
3007 Value* val2 = getVal(*$2, $5);
3009 $$ = BinaryOperator::Create($1, val1, val2);
3011 GEN_ERROR("binary operator returned null");
3014 | LogicalOps Types ValueRef ',' ValueRef {
3015 if (!UpRefs.empty())
3016 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3017 if (!(*$2)->isInteger()) {
3018 if (!isa<VectorType>($2->get()) ||
3019 !cast<VectorType>($2->get())->getElementType()->isInteger())
3020 GEN_ERROR("Logical operator requires integral operands");
3022 Value* tmpVal1 = getVal(*$2, $3);
3024 Value* tmpVal2 = getVal(*$2, $5);
3026 $$ = BinaryOperator::Create($1, tmpVal1, tmpVal2);
3028 GEN_ERROR("binary operator returned null");
3031 | ICMP IPredicates Types ValueRef ',' ValueRef {
3032 if (!UpRefs.empty())
3033 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3034 if (isa<VectorType>((*$3).get()))
3035 GEN_ERROR("Vector types not supported by icmp instruction");
3036 Value* tmpVal1 = getVal(*$3, $4);
3038 Value* tmpVal2 = getVal(*$3, $6);
3040 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3042 GEN_ERROR("icmp operator returned null");
3045 | FCMP FPredicates Types ValueRef ',' ValueRef {
3046 if (!UpRefs.empty())
3047 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3048 if (isa<VectorType>((*$3).get()))
3049 GEN_ERROR("Vector types not supported by fcmp instruction");
3050 Value* tmpVal1 = getVal(*$3, $4);
3052 Value* tmpVal2 = getVal(*$3, $6);
3054 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3056 GEN_ERROR("fcmp operator returned null");
3059 | VICMP IPredicates Types ValueRef ',' ValueRef {
3060 if (!UpRefs.empty())
3061 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3062 if (!isa<VectorType>((*$3).get()))
3063 GEN_ERROR("Scalar types not supported by vicmp instruction");
3064 Value* tmpVal1 = getVal(*$3, $4);
3066 Value* tmpVal2 = getVal(*$3, $6);
3068 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3070 GEN_ERROR("icmp operator returned null");
3073 | VFCMP FPredicates Types ValueRef ',' ValueRef {
3074 if (!UpRefs.empty())
3075 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3076 if (!isa<VectorType>((*$3).get()))
3077 GEN_ERROR("Scalar types not supported by vfcmp instruction");
3078 Value* tmpVal1 = getVal(*$3, $4);
3080 Value* tmpVal2 = getVal(*$3, $6);
3082 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3084 GEN_ERROR("fcmp operator returned null");
3087 | CastOps ResolvedVal TO Types {
3088 if (!UpRefs.empty())
3089 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
3091 const Type* DestTy = $4->get();
3092 if (!CastInst::castIsValid($1, Val, DestTy))
3093 GEN_ERROR("invalid cast opcode for cast from '" +
3094 Val->getType()->getDescription() + "' to '" +
3095 DestTy->getDescription() + "'");
3096 $$ = CastInst::Create($1, Val, DestTy);
3099 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3100 if ($2->getType() != Type::Int1Ty)
3101 GEN_ERROR("select condition must be boolean");
3102 if ($4->getType() != $6->getType())
3103 GEN_ERROR("select value types should match");
3104 $$ = SelectInst::Create($2, $4, $6);
3107 | VAARG ResolvedVal ',' Types {
3108 if (!UpRefs.empty())
3109 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
3110 $$ = new VAArgInst($2, *$4);
3114 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
3115 if (!ExtractElementInst::isValidOperands($2, $4))
3116 GEN_ERROR("Invalid extractelement operands");
3117 $$ = new ExtractElementInst($2, $4);
3120 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3121 if (!InsertElementInst::isValidOperands($2, $4, $6))
3122 GEN_ERROR("Invalid insertelement operands");
3123 $$ = InsertElementInst::Create($2, $4, $6);
3126 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3127 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
3128 GEN_ERROR("Invalid shufflevector operands");
3129 $$ = new ShuffleVectorInst($2, $4, $6);
3133 const Type *Ty = $2->front().first->getType();
3134 if (!Ty->isFirstClassType())
3135 GEN_ERROR("PHI node operands must be of first class type");
3136 $$ = PHINode::Create(Ty);
3137 ((PHINode*)$$)->reserveOperandSpace($2->size());
3138 while ($2->begin() != $2->end()) {
3139 if ($2->front().first->getType() != Ty)
3140 GEN_ERROR("All elements of a PHI node must be of the same type");
3141 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
3144 delete $2; // Free the list...
3147 | OptTailCall OptCallingConv ResultTypes ValueRef '(' ParamList ')'
3150 // Handle the short syntax
3151 const PointerType *PFTy = 0;
3152 const FunctionType *Ty = 0;
3153 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
3154 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3155 // Pull out the types of all of the arguments...
3156 std::vector<const Type*> ParamTypes;
3157 ParamList::iterator I = $6->begin(), E = $6->end();
3158 for (; I != E; ++I) {
3159 const Type *Ty = I->Val->getType();
3160 if (Ty == Type::VoidTy)
3161 GEN_ERROR("Short call syntax cannot be used with varargs");
3162 ParamTypes.push_back(Ty);
3165 if (!FunctionType::isValidReturnType(*$3))
3166 GEN_ERROR("Invalid result type for LLVM function");
3168 Ty = FunctionType::get($3->get(), ParamTypes, false);
3169 PFTy = PointerType::getUnqual(Ty);
3172 Value *V = getVal(PFTy, $4); // Get the function we're calling...
3175 // Check for call to invalid intrinsic to avoid crashing later.
3176 if (Function *theF = dyn_cast<Function>(V)) {
3177 if (theF->hasName() && (theF->getValueName()->getKeyLength() >= 5) &&
3178 (0 == strncmp(theF->getValueName()->getKeyData(), "llvm.", 5)) &&
3179 !theF->getIntrinsicID(true))
3180 GEN_ERROR("Call to invalid LLVM intrinsic function '" +
3181 theF->getName() + "'");
3184 // Set up the ParamAttrs for the function
3185 SmallVector<ParamAttrsWithIndex, 8> Attrs;
3186 if ($8 != ParamAttr::None)
3187 Attrs.push_back(ParamAttrsWithIndex::get(0, $8));
3188 // Check the arguments
3190 if ($6->empty()) { // Has no arguments?
3191 // Make sure no arguments is a good thing!
3192 if (Ty->getNumParams() != 0)
3193 GEN_ERROR("No arguments passed to a function that "
3194 "expects arguments");
3195 } else { // Has arguments?
3196 // Loop through FunctionType's arguments and ensure they are specified
3197 // correctly. Also, gather any parameter attributes.
3198 FunctionType::param_iterator I = Ty->param_begin();
3199 FunctionType::param_iterator E = Ty->param_end();
3200 ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
3203 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
3204 if (ArgI->Val->getType() != *I)
3205 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
3206 (*I)->getDescription() + "'");
3207 Args.push_back(ArgI->Val);
3208 if (ArgI->Attrs != ParamAttr::None)
3209 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
3211 if (Ty->isVarArg()) {
3213 for (; ArgI != ArgE; ++ArgI, ++index) {
3214 Args.push_back(ArgI->Val); // push the remaining varargs
3215 if (ArgI->Attrs != ParamAttr::None)
3216 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
3218 } else if (I != E || ArgI != ArgE)
3219 GEN_ERROR("Invalid number of parameters detected");
3222 // Finish off the ParamAttrs and check them
3225 PAL = PAListPtr::get(Attrs.begin(), Attrs.end());
3227 // Create the call node
3228 CallInst *CI = CallInst::Create(V, Args.begin(), Args.end());
3229 CI->setTailCall($1);
3230 CI->setCallingConv($2);
3231 CI->setParamAttrs(PAL);
3242 OptVolatile : VOLATILE {
3253 MemoryInst : MALLOC Types OptCAlign {
3254 if (!UpRefs.empty())
3255 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3256 $$ = new MallocInst(*$2, 0, $3);
3260 | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
3261 if (!UpRefs.empty())
3262 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3263 if ($4 != Type::Int32Ty)
3264 GEN_ERROR("Malloc array size is not a 32-bit integer!");
3265 Value* tmpVal = getVal($4, $5);
3267 $$ = new MallocInst(*$2, tmpVal, $6);
3270 | ALLOCA Types OptCAlign {
3271 if (!UpRefs.empty())
3272 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3273 $$ = new AllocaInst(*$2, 0, $3);
3277 | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
3278 if (!UpRefs.empty())
3279 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3280 if ($4 != Type::Int32Ty)
3281 GEN_ERROR("Alloca array size is not a 32-bit integer!");
3282 Value* tmpVal = getVal($4, $5);
3284 $$ = new AllocaInst(*$2, tmpVal, $6);
3287 | FREE ResolvedVal {
3288 if (!isa<PointerType>($2->getType()))
3289 GEN_ERROR("Trying to free nonpointer type " +
3290 $2->getType()->getDescription() + "");
3291 $$ = new FreeInst($2);
3295 | OptVolatile LOAD Types ValueRef OptCAlign {
3296 if (!UpRefs.empty())
3297 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3298 if (!isa<PointerType>($3->get()))
3299 GEN_ERROR("Can't load from nonpointer type: " +
3300 (*$3)->getDescription());
3301 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
3302 GEN_ERROR("Can't load from pointer of non-first-class type: " +
3303 (*$3)->getDescription());
3304 Value* tmpVal = getVal(*$3, $4);
3306 $$ = new LoadInst(tmpVal, "", $1, $5);
3309 | OptVolatile STORE ResolvedVal ',' Types ValueRef OptCAlign {
3310 if (!UpRefs.empty())
3311 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
3312 const PointerType *PT = dyn_cast<PointerType>($5->get());
3314 GEN_ERROR("Can't store to a nonpointer type: " +
3315 (*$5)->getDescription());
3316 const Type *ElTy = PT->getElementType();
3317 if (ElTy != $3->getType())
3318 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
3319 "' into space of type '" + ElTy->getDescription() + "'");
3321 Value* tmpVal = getVal(*$5, $6);
3323 $$ = new StoreInst($3, tmpVal, $1, $7);
3326 | GETRESULT Types ValueRef ',' EUINT64VAL {
3327 if (!UpRefs.empty())
3328 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3329 if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3330 GEN_ERROR("getresult insn requires an aggregate operand");
3331 if (!ExtractValueInst::getIndexedType(*$2, $5))
3332 GEN_ERROR("Invalid getresult index for type '" +
3333 (*$2)->getDescription()+ "'");
3335 Value *tmpVal = getVal(*$2, $3);
3337 $$ = ExtractValueInst::Create(tmpVal, $5);
3340 | GETELEMENTPTR Types ValueRef IndexList {
3341 if (!UpRefs.empty())
3342 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3343 if (!isa<PointerType>($2->get()))
3344 GEN_ERROR("getelementptr insn requires pointer operand");
3346 if (!GetElementPtrInst::getIndexedType(*$2, $4->begin(), $4->end()))
3347 GEN_ERROR("Invalid getelementptr indices for type '" +
3348 (*$2)->getDescription()+ "'");
3349 Value* tmpVal = getVal(*$2, $3);
3351 $$ = GetElementPtrInst::Create(tmpVal, $4->begin(), $4->end());
3355 | EXTRACTVALUE Types ValueRef ConstantIndexList {
3356 if (!UpRefs.empty())
3357 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3358 if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3359 GEN_ERROR("extractvalue insn requires an aggregate operand");
3361 if (!ExtractValueInst::getIndexedType(*$2, $4->begin(), $4->end()))
3362 GEN_ERROR("Invalid extractvalue indices for type '" +
3363 (*$2)->getDescription()+ "'");
3364 Value* tmpVal = getVal(*$2, $3);
3366 $$ = ExtractValueInst::Create(tmpVal, $4->begin(), $4->end());
3370 | INSERTVALUE Types ValueRef ',' Types ValueRef ConstantIndexList {
3371 if (!UpRefs.empty())
3372 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3373 if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3374 GEN_ERROR("extractvalue insn requires an aggregate operand");
3376 if (ExtractValueInst::getIndexedType(*$2, $7->begin(), $7->end()) != $5->get())
3377 GEN_ERROR("Invalid insertvalue indices for type '" +
3378 (*$2)->getDescription()+ "'");
3379 Value* aggVal = getVal(*$2, $3);
3380 Value* tmpVal = getVal(*$5, $6);
3382 $$ = InsertValueInst::Create(aggVal, tmpVal, $7->begin(), $7->end());
3391 // common code from the two 'RunVMAsmParser' functions
3392 static Module* RunParser(Module * M) {
3393 CurModule.CurrentModule = M;
3394 // Check to make sure the parser succeeded
3397 delete ParserResult;
3401 // Emit an error if there are any unresolved types left.
3402 if (!CurModule.LateResolveTypes.empty()) {
3403 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
3404 if (DID.Type == ValID::LocalName) {
3405 GenerateError("Undefined type remains at eof: '"+DID.getName() + "'");
3407 GenerateError("Undefined type remains at eof: #" + itostr(DID.Num));
3410 delete ParserResult;
3414 // Emit an error if there are any unresolved values left.
3415 if (!CurModule.LateResolveValues.empty()) {
3416 Value *V = CurModule.LateResolveValues.back();
3417 std::map<Value*, std::pair<ValID, int> >::iterator I =
3418 CurModule.PlaceHolderInfo.find(V);
3420 if (I != CurModule.PlaceHolderInfo.end()) {
3421 ValID &DID = I->second.first;
3422 if (DID.Type == ValID::LocalName) {
3423 GenerateError("Undefined value remains at eof: "+DID.getName() + "'");
3425 GenerateError("Undefined value remains at eof: #" + itostr(DID.Num));
3428 delete ParserResult;
3433 // Check to make sure that parsing produced a result
3437 // Reset ParserResult variable while saving its value for the result.
3438 Module *Result = ParserResult;
3444 void llvm::GenerateError(const std::string &message, int LineNo) {
3445 if (LineNo == -1) LineNo = LLLgetLineNo();
3446 // TODO: column number in exception
3448 TheParseError->setError(LLLgetFilename(), message, LineNo);
3452 int yyerror(const char *ErrorMsg) {
3453 std::string where = LLLgetFilename() + ":" + utostr(LLLgetLineNo()) + ": ";
3454 std::string errMsg = where + "error: " + std::string(ErrorMsg);
3455 if (yychar != YYEMPTY && yychar != 0) {
3456 errMsg += " while reading token: '";
3457 errMsg += std::string(LLLgetTokenStart(),
3458 LLLgetTokenStart()+LLLgetTokenLength()) + "'";
3460 GenerateError(errMsg);