1 //===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/Streams.h"
35 // The following is a gross hack. In order to rid the libAsmParser library of
36 // exceptions, we have to have a way of getting the yyparse function to go into
37 // an error situation. So, whenever we want an error to occur, the GenerateError
38 // function (see bottom of file) sets TriggerError. Then, at the end of each
39 // production in the grammer we use CHECK_FOR_ERROR which will invoke YYERROR
40 // (a goto) to put YACC in error state. Furthermore, several calls to
41 // GenerateError are made from inside productions and they must simulate the
42 // previous exception behavior by exiting the production immediately. We have
43 // replaced these with the GEN_ERROR macro which calls GeneratError and then
44 // immediately invokes YYERROR. This would be so much cleaner if it was a
45 // recursive descent parser.
46 static bool TriggerError = false;
47 #define CHECK_FOR_ERROR { if (TriggerError) { TriggerError = false; YYABORT; } }
48 #define GEN_ERROR(msg) { GenerateError(msg); YYERROR; }
50 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
51 int yylex(); // declaration" of xxx warnings.
55 std::string CurFilename;
58 Debug("debug-yacc", cl::desc("Print yacc debug state changes"),
59 cl::Hidden, cl::init(false));
64 static Module *ParserResult;
66 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
67 // relating to upreferences in the input stream.
69 //#define DEBUG_UPREFS 1
71 #define UR_OUT(X) cerr << X
76 #define YYERROR_VERBOSE 1
78 static GlobalVariable *CurGV;
81 // This contains info used when building the body of a function. It is
82 // destroyed when the function is completed.
84 typedef std::vector<Value *> ValueList; // Numbered defs
87 ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers=0);
89 static struct PerModuleInfo {
90 Module *CurrentModule;
91 ValueList Values; // Module level numbered definitions
92 ValueList LateResolveValues;
93 std::vector<PATypeHolder> Types;
94 std::map<ValID, PATypeHolder> LateResolveTypes;
96 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
97 /// how they were referenced and on which line of the input they came from so
98 /// that we can resolve them later and print error messages as appropriate.
99 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
101 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
102 // references to global values. Global values may be referenced before they
103 // are defined, and if so, the temporary object that they represent is held
104 // here. This is used for forward references of GlobalValues.
106 typedef std::map<std::pair<const PointerType *,
107 ValID>, GlobalValue*> GlobalRefsType;
108 GlobalRefsType GlobalRefs;
111 // If we could not resolve some functions at function compilation time
112 // (calls to functions before they are defined), resolve them now... Types
113 // are resolved when the constant pool has been completely parsed.
115 ResolveDefinitions(LateResolveValues);
119 // Check to make sure that all global value forward references have been
122 if (!GlobalRefs.empty()) {
123 std::string UndefinedReferences = "Unresolved global references exist:\n";
125 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
127 UndefinedReferences += " " + I->first.first->getDescription() + " " +
128 I->first.second.getName() + "\n";
130 GenerateError(UndefinedReferences);
134 Values.clear(); // Clear out function local definitions
139 // GetForwardRefForGlobal - Check to see if there is a forward reference
140 // for this global. If so, remove it from the GlobalRefs map and return it.
141 // If not, just return null.
142 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
143 // Check to see if there is a forward reference to this global variable...
144 // if there is, eliminate it and patch the reference to use the new def'n.
145 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
146 GlobalValue *Ret = 0;
147 if (I != GlobalRefs.end()) {
154 bool TypeIsUnresolved(PATypeHolder* PATy) {
155 // If it isn't abstract, its resolved
156 const Type* Ty = PATy->get();
157 if (!Ty->isAbstract())
159 // Traverse the type looking for abstract types. If it isn't abstract then
160 // we don't need to traverse that leg of the type.
161 std::vector<const Type*> WorkList, SeenList;
162 WorkList.push_back(Ty);
163 while (!WorkList.empty()) {
164 const Type* Ty = WorkList.back();
165 SeenList.push_back(Ty);
167 if (const OpaqueType* OpTy = dyn_cast<OpaqueType>(Ty)) {
168 // Check to see if this is an unresolved type
169 std::map<ValID, PATypeHolder>::iterator I = LateResolveTypes.begin();
170 std::map<ValID, PATypeHolder>::iterator E = LateResolveTypes.end();
171 for ( ; I != E; ++I) {
172 if (I->second.get() == OpTy)
175 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(Ty)) {
176 const Type* TheTy = SeqTy->getElementType();
177 if (TheTy->isAbstract() && TheTy != Ty) {
178 std::vector<const Type*>::iterator I = SeenList.begin(),
184 WorkList.push_back(TheTy);
186 } else if (const StructType* StrTy = dyn_cast<StructType>(Ty)) {
187 for (unsigned i = 0; i < StrTy->getNumElements(); ++i) {
188 const Type* TheTy = StrTy->getElementType(i);
189 if (TheTy->isAbstract() && TheTy != Ty) {
190 std::vector<const Type*>::iterator I = SeenList.begin(),
196 WorkList.push_back(TheTy);
205 static struct PerFunctionInfo {
206 Function *CurrentFunction; // Pointer to current function being created
208 ValueList Values; // Keep track of #'d definitions
210 ValueList LateResolveValues;
211 bool isDeclare; // Is this function a forward declararation?
212 GlobalValue::LinkageTypes Linkage; // Linkage for forward declaration.
213 GlobalValue::VisibilityTypes Visibility;
215 /// BBForwardRefs - When we see forward references to basic blocks, keep
216 /// track of them here.
217 std::map<ValID, BasicBlock*> BBForwardRefs;
219 inline PerFunctionInfo() {
222 Linkage = GlobalValue::ExternalLinkage;
223 Visibility = GlobalValue::DefaultVisibility;
226 inline void FunctionStart(Function *M) {
231 void FunctionDone() {
232 // Any forward referenced blocks left?
233 if (!BBForwardRefs.empty()) {
234 GenerateError("Undefined reference to label " +
235 BBForwardRefs.begin()->second->getName());
239 // Resolve all forward references now.
240 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
242 Values.clear(); // Clear out function local definitions
243 BBForwardRefs.clear();
246 Linkage = GlobalValue::ExternalLinkage;
247 Visibility = GlobalValue::DefaultVisibility;
249 } CurFun; // Info for the current function...
251 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
254 //===----------------------------------------------------------------------===//
255 // Code to handle definitions of all the types
256 //===----------------------------------------------------------------------===//
258 static void InsertValue(Value *V, ValueList &ValueTab = CurFun.Values) {
259 // Things that have names or are void typed don't get slot numbers
260 if (V->hasName() || (V->getType() == Type::VoidTy))
263 // In the case of function values, we have to allow for the forward reference
264 // of basic blocks, which are included in the numbering. Consequently, we keep
265 // track of the next insertion location with NextValNum. When a BB gets
266 // inserted, it could change the size of the CurFun.Values vector.
267 if (&ValueTab == &CurFun.Values) {
268 if (ValueTab.size() <= CurFun.NextValNum)
269 ValueTab.resize(CurFun.NextValNum+1);
270 ValueTab[CurFun.NextValNum++] = V;
273 // For all other lists, its okay to just tack it on the back of the vector.
274 ValueTab.push_back(V);
277 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
279 case ValID::LocalID: // Is it a numbered definition?
280 // Module constants occupy the lowest numbered slots...
281 if (D.Num < CurModule.Types.size())
282 return CurModule.Types[D.Num];
284 case ValID::LocalName: // Is it a named definition?
285 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
286 D.destroy(); // Free old strdup'd memory...
291 GenerateError("Internal parser error: Invalid symbol type reference");
295 // If we reached here, we referenced either a symbol that we don't know about
296 // or an id number that hasn't been read yet. We may be referencing something
297 // forward, so just create an entry to be resolved later and get to it...
299 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
302 if (inFunctionScope()) {
303 if (D.Type == ValID::LocalName) {
304 GenerateError("Reference to an undefined type: '" + D.getName() + "'");
307 GenerateError("Reference to an undefined type: #" + utostr(D.Num));
312 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
313 if (I != CurModule.LateResolveTypes.end())
316 Type *Typ = OpaqueType::get();
317 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
321 // getExistingVal - Look up the value specified by the provided type and
322 // the provided ValID. If the value exists and has already been defined, return
323 // it. Otherwise return null.
325 static Value *getExistingVal(const Type *Ty, const ValID &D) {
326 if (isa<FunctionType>(Ty)) {
327 GenerateError("Functions are not values and "
328 "must be referenced as pointers");
333 case ValID::LocalID: { // Is it a numbered definition?
334 // Check that the number is within bounds.
335 if (D.Num >= CurFun.Values.size())
337 Value *Result = CurFun.Values[D.Num];
338 if (Ty != Result->getType()) {
339 GenerateError("Numbered value (%" + utostr(D.Num) + ") of type '" +
340 Result->getType()->getDescription() + "' does not match "
341 "expected type, '" + Ty->getDescription() + "'");
346 case ValID::GlobalID: { // Is it a numbered definition?
347 if (D.Num >= CurModule.Values.size())
349 Value *Result = CurModule.Values[D.Num];
350 if (Ty != Result->getType()) {
351 GenerateError("Numbered value (@" + utostr(D.Num) + ") of type '" +
352 Result->getType()->getDescription() + "' does not match "
353 "expected type, '" + Ty->getDescription() + "'");
359 case ValID::LocalName: { // Is it a named definition?
360 if (!inFunctionScope())
362 ValueSymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
363 Value *N = SymTab.lookup(D.Name);
366 if (N->getType() != Ty)
369 D.destroy(); // Free old strdup'd memory...
372 case ValID::GlobalName: { // Is it a named definition?
373 ValueSymbolTable &SymTab = CurModule.CurrentModule->getValueSymbolTable();
374 Value *N = SymTab.lookup(D.Name);
377 if (N->getType() != Ty)
380 D.destroy(); // Free old strdup'd memory...
384 // Check to make sure that "Ty" is an integral type, and that our
385 // value will fit into the specified type...
386 case ValID::ConstSIntVal: // Is it a constant pool reference??
387 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
388 GenerateError("Signed integral constant '" +
389 itostr(D.ConstPool64) + "' is invalid for type '" +
390 Ty->getDescription() + "'");
393 return ConstantInt::get(Ty, D.ConstPool64, true);
395 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
396 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
397 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
398 GenerateError("Integral constant '" + utostr(D.UConstPool64) +
399 "' is invalid or out of range");
401 } else { // This is really a signed reference. Transmogrify.
402 return ConstantInt::get(Ty, D.ConstPool64, true);
405 return ConstantInt::get(Ty, D.UConstPool64);
408 case ValID::ConstFPVal: // Is it a floating point const pool reference?
409 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP)) {
410 GenerateError("FP constant invalid for type");
413 return ConstantFP::get(Ty, D.ConstPoolFP);
415 case ValID::ConstNullVal: // Is it a null value?
416 if (!isa<PointerType>(Ty)) {
417 GenerateError("Cannot create a a non pointer null");
420 return ConstantPointerNull::get(cast<PointerType>(Ty));
422 case ValID::ConstUndefVal: // Is it an undef value?
423 return UndefValue::get(Ty);
425 case ValID::ConstZeroVal: // Is it a zero value?
426 return Constant::getNullValue(Ty);
428 case ValID::ConstantVal: // Fully resolved constant?
429 if (D.ConstantValue->getType() != Ty) {
430 GenerateError("Constant expression type different from required type");
433 return D.ConstantValue;
435 case ValID::InlineAsmVal: { // Inline asm expression
436 const PointerType *PTy = dyn_cast<PointerType>(Ty);
437 const FunctionType *FTy =
438 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
439 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
440 GenerateError("Invalid type for asm constraint string");
443 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
444 D.IAD->HasSideEffects);
445 D.destroy(); // Free InlineAsmDescriptor.
449 assert(0 && "Unhandled case!");
453 assert(0 && "Unhandled case!");
457 // getVal - This function is identical to getExistingVal, except that if a
458 // value is not already defined, it "improvises" by creating a placeholder var
459 // that looks and acts just like the requested variable. When the value is
460 // defined later, all uses of the placeholder variable are replaced with the
463 static Value *getVal(const Type *Ty, const ValID &ID) {
464 if (Ty == Type::LabelTy) {
465 GenerateError("Cannot use a basic block here");
469 // See if the value has already been defined.
470 Value *V = getExistingVal(Ty, ID);
472 if (TriggerError) return 0;
474 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
475 GenerateError("Invalid use of a composite type");
479 // If we reached here, we referenced either a symbol that we don't know about
480 // or an id number that hasn't been read yet. We may be referencing something
481 // forward, so just create an entry to be resolved later and get to it...
483 V = new Argument(Ty);
485 // Remember where this forward reference came from. FIXME, shouldn't we try
486 // to recycle these things??
487 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
490 if (inFunctionScope())
491 InsertValue(V, CurFun.LateResolveValues);
493 InsertValue(V, CurModule.LateResolveValues);
497 /// defineBBVal - This is a definition of a new basic block with the specified
498 /// identifier which must be the same as CurFun.NextValNum, if its numeric.
499 static BasicBlock *defineBBVal(const ValID &ID) {
500 assert(inFunctionScope() && "Can't get basic block at global scope!");
504 // First, see if this was forward referenced
506 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
507 if (BBI != CurFun.BBForwardRefs.end()) {
509 // The forward declaration could have been inserted anywhere in the
510 // function: insert it into the correct place now.
511 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
512 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
514 // We're about to erase the entry, save the key so we can clean it up.
515 ValID Tmp = BBI->first;
517 // Erase the forward ref from the map as its no longer "forward"
518 CurFun.BBForwardRefs.erase(ID);
520 // The key has been removed from the map but so we don't want to leave
521 // strdup'd memory around so destroy it too.
524 // If its a numbered definition, bump the number and set the BB value.
525 if (ID.Type == ValID::LocalID) {
526 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
534 // We haven't seen this BB before and its first mention is a definition.
535 // Just create it and return it.
536 std::string Name (ID.Type == ValID::LocalName ? ID.Name : "");
537 BB = new BasicBlock(Name, CurFun.CurrentFunction);
538 if (ID.Type == ValID::LocalID) {
539 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
543 ID.destroy(); // Free strdup'd memory
547 /// getBBVal - get an existing BB value or create a forward reference for it.
549 static BasicBlock *getBBVal(const ValID &ID) {
550 assert(inFunctionScope() && "Can't get basic block at global scope!");
554 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
555 if (BBI != CurFun.BBForwardRefs.end()) {
557 } if (ID.Type == ValID::LocalName) {
558 std::string Name = ID.Name;
559 Value *N = CurFun.CurrentFunction->getValueSymbolTable().lookup(Name);
561 if (N->getType()->getTypeID() == Type::LabelTyID)
562 BB = cast<BasicBlock>(N);
564 GenerateError("Reference to label '" + Name + "' is actually of type '"+
565 N->getType()->getDescription() + "'");
566 } else if (ID.Type == ValID::LocalID) {
567 if (ID.Num < CurFun.NextValNum && ID.Num < CurFun.Values.size()) {
568 if (CurFun.Values[ID.Num]->getType()->getTypeID() == Type::LabelTyID)
569 BB = cast<BasicBlock>(CurFun.Values[ID.Num]);
571 GenerateError("Reference to label '%" + utostr(ID.Num) +
572 "' is actually of type '"+
573 CurFun.Values[ID.Num]->getType()->getDescription() + "'");
576 GenerateError("Illegal label reference " + ID.getName());
580 // If its already been defined, return it now.
582 ID.destroy(); // Free strdup'd memory.
586 // Otherwise, this block has not been seen before, create it.
588 if (ID.Type == ValID::LocalName)
590 BB = new BasicBlock(Name, CurFun.CurrentFunction);
592 // Insert it in the forward refs map.
593 CurFun.BBForwardRefs[ID] = BB;
599 //===----------------------------------------------------------------------===//
600 // Code to handle forward references in instructions
601 //===----------------------------------------------------------------------===//
603 // This code handles the late binding needed with statements that reference
604 // values not defined yet... for example, a forward branch, or the PHI node for
607 // This keeps a table (CurFun.LateResolveValues) of all such forward references
608 // and back patchs after we are done.
611 // ResolveDefinitions - If we could not resolve some defs at parsing
612 // time (forward branches, phi functions for loops, etc...) resolve the
616 ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers) {
617 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
618 while (!LateResolvers.empty()) {
619 Value *V = LateResolvers.back();
620 LateResolvers.pop_back();
622 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
623 CurModule.PlaceHolderInfo.find(V);
624 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
626 ValID &DID = PHI->second.first;
628 Value *TheRealValue = getExistingVal(V->getType(), DID);
632 V->replaceAllUsesWith(TheRealValue);
634 CurModule.PlaceHolderInfo.erase(PHI);
635 } else if (FutureLateResolvers) {
636 // Functions have their unresolved items forwarded to the module late
638 InsertValue(V, *FutureLateResolvers);
640 if (DID.Type == ValID::LocalName || DID.Type == ValID::GlobalName) {
641 GenerateError("Reference to an invalid definition: '" +DID.getName()+
642 "' of type '" + V->getType()->getDescription() + "'",
646 GenerateError("Reference to an invalid definition: #" +
647 itostr(DID.Num) + " of type '" +
648 V->getType()->getDescription() + "'",
654 LateResolvers.clear();
657 // ResolveTypeTo - A brand new type was just declared. This means that (if
658 // name is not null) things referencing Name can be resolved. Otherwise, things
659 // refering to the number can be resolved. Do this now.
661 static void ResolveTypeTo(char *Name, const Type *ToTy) {
663 if (Name) D = ValID::createLocalName(Name);
664 else D = ValID::createLocalID(CurModule.Types.size());
666 std::map<ValID, PATypeHolder>::iterator I =
667 CurModule.LateResolveTypes.find(D);
668 if (I != CurModule.LateResolveTypes.end()) {
669 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
670 CurModule.LateResolveTypes.erase(I);
674 // setValueName - Set the specified value to the name given. The name may be
675 // null potentially, in which case this is a noop. The string passed in is
676 // assumed to be a malloc'd string buffer, and is free'd by this function.
678 static void setValueName(Value *V, char *NameStr) {
679 if (!NameStr) return;
680 std::string Name(NameStr); // Copy string
681 free(NameStr); // Free old string
683 if (V->getType() == Type::VoidTy) {
684 GenerateError("Can't assign name '" + Name+"' to value with void type");
688 assert(inFunctionScope() && "Must be in function scope!");
689 ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
690 if (ST.lookup(Name)) {
691 GenerateError("Redefinition of value '" + Name + "' of type '" +
692 V->getType()->getDescription() + "'");
700 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
701 /// this is a declaration, otherwise it is a definition.
702 static GlobalVariable *
703 ParseGlobalVariable(char *NameStr,
704 GlobalValue::LinkageTypes Linkage,
705 GlobalValue::VisibilityTypes Visibility,
706 bool isConstantGlobal, const Type *Ty,
707 Constant *Initializer, bool IsThreadLocal) {
708 if (isa<FunctionType>(Ty)) {
709 GenerateError("Cannot declare global vars of function type");
713 const PointerType *PTy = PointerType::get(Ty);
717 Name = NameStr; // Copy string
718 free(NameStr); // Free old string
721 // See if this global value was forward referenced. If so, recycle the
725 ID = ValID::createGlobalName((char*)Name.c_str());
727 ID = ValID::createGlobalID(CurModule.Values.size());
730 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
731 // Move the global to the end of the list, from whereever it was
732 // previously inserted.
733 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
734 CurModule.CurrentModule->getGlobalList().remove(GV);
735 CurModule.CurrentModule->getGlobalList().push_back(GV);
736 GV->setInitializer(Initializer);
737 GV->setLinkage(Linkage);
738 GV->setVisibility(Visibility);
739 GV->setConstant(isConstantGlobal);
740 GV->setThreadLocal(IsThreadLocal);
741 InsertValue(GV, CurModule.Values);
745 // If this global has a name
747 // if the global we're parsing has an initializer (is a definition) and
748 // has external linkage.
749 if (Initializer && Linkage != GlobalValue::InternalLinkage)
750 // If there is already a global with external linkage with this name
751 if (CurModule.CurrentModule->getGlobalVariable(Name, false)) {
752 // If we allow this GVar to get created, it will be renamed in the
753 // symbol table because it conflicts with an existing GVar. We can't
754 // allow redefinition of GVars whose linking indicates that their name
755 // must stay the same. Issue the error.
756 GenerateError("Redefinition of global variable named '" + Name +
757 "' of type '" + Ty->getDescription() + "'");
762 // Otherwise there is no existing GV to use, create one now.
764 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
765 CurModule.CurrentModule, IsThreadLocal);
766 GV->setVisibility(Visibility);
767 InsertValue(GV, CurModule.Values);
771 // setTypeName - Set the specified type to the name given. The name may be
772 // null potentially, in which case this is a noop. The string passed in is
773 // assumed to be a malloc'd string buffer, and is freed by this function.
775 // This function returns true if the type has already been defined, but is
776 // allowed to be redefined in the specified context. If the name is a new name
777 // for the type plane, it is inserted and false is returned.
778 static bool setTypeName(const Type *T, char *NameStr) {
779 assert(!inFunctionScope() && "Can't give types function-local names!");
780 if (NameStr == 0) return false;
782 std::string Name(NameStr); // Copy string
783 free(NameStr); // Free old string
785 // We don't allow assigning names to void type
786 if (T == Type::VoidTy) {
787 GenerateError("Can't assign name '" + Name + "' to the void type");
791 // Set the type name, checking for conflicts as we do so.
792 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
794 if (AlreadyExists) { // Inserting a name that is already defined???
795 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
796 assert(Existing && "Conflict but no matching type?!");
798 // There is only one case where this is allowed: when we are refining an
799 // opaque type. In this case, Existing will be an opaque type.
800 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
801 // We ARE replacing an opaque type!
802 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
806 // Otherwise, this is an attempt to redefine a type. That's okay if
807 // the redefinition is identical to the original. This will be so if
808 // Existing and T point to the same Type object. In this one case we
809 // allow the equivalent redefinition.
810 if (Existing == T) return true; // Yes, it's equal.
812 // Any other kind of (non-equivalent) redefinition is an error.
813 GenerateError("Redefinition of type named '" + Name + "' of type '" +
814 T->getDescription() + "'");
820 //===----------------------------------------------------------------------===//
821 // Code for handling upreferences in type names...
824 // TypeContains - Returns true if Ty directly contains E in it.
826 static bool TypeContains(const Type *Ty, const Type *E) {
827 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
828 E) != Ty->subtype_end();
833 // NestingLevel - The number of nesting levels that need to be popped before
834 // this type is resolved.
835 unsigned NestingLevel;
837 // LastContainedTy - This is the type at the current binding level for the
838 // type. Every time we reduce the nesting level, this gets updated.
839 const Type *LastContainedTy;
841 // UpRefTy - This is the actual opaque type that the upreference is
845 UpRefRecord(unsigned NL, OpaqueType *URTy)
846 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
850 // UpRefs - A list of the outstanding upreferences that need to be resolved.
851 static std::vector<UpRefRecord> UpRefs;
853 /// HandleUpRefs - Every time we finish a new layer of types, this function is
854 /// called. It loops through the UpRefs vector, which is a list of the
855 /// currently active types. For each type, if the up reference is contained in
856 /// the newly completed type, we decrement the level count. When the level
857 /// count reaches zero, the upreferenced type is the type that is passed in:
858 /// thus we can complete the cycle.
860 static PATypeHolder HandleUpRefs(const Type *ty) {
861 // If Ty isn't abstract, or if there are no up-references in it, then there is
862 // nothing to resolve here.
863 if (!ty->isAbstract() || UpRefs.empty()) return ty;
866 UR_OUT("Type '" << Ty->getDescription() <<
867 "' newly formed. Resolving upreferences.\n" <<
868 UpRefs.size() << " upreferences active!\n");
870 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
871 // to zero), we resolve them all together before we resolve them to Ty. At
872 // the end of the loop, if there is anything to resolve to Ty, it will be in
874 OpaqueType *TypeToResolve = 0;
876 for (unsigned i = 0; i != UpRefs.size(); ++i) {
877 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
878 << UpRefs[i].second->getDescription() << ") = "
879 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
880 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
881 // Decrement level of upreference
882 unsigned Level = --UpRefs[i].NestingLevel;
883 UpRefs[i].LastContainedTy = Ty;
884 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
885 if (Level == 0) { // Upreference should be resolved!
886 if (!TypeToResolve) {
887 TypeToResolve = UpRefs[i].UpRefTy;
889 UR_OUT(" * Resolving upreference for "
890 << UpRefs[i].second->getDescription() << "\n";
891 std::string OldName = UpRefs[i].UpRefTy->getDescription());
892 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
893 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
894 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
896 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
897 --i; // Do not skip the next element...
903 UR_OUT(" * Resolving upreference for "
904 << UpRefs[i].second->getDescription() << "\n";
905 std::string OldName = TypeToResolve->getDescription());
906 TypeToResolve->refineAbstractTypeTo(Ty);
912 //===----------------------------------------------------------------------===//
913 // RunVMAsmParser - Define an interface to this parser
914 //===----------------------------------------------------------------------===//
916 static Module* RunParser(Module * M);
918 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
921 CurFilename = Filename;
922 return RunParser(new Module(CurFilename));
925 Module *llvm::RunVMAsmParser(const char * AsmString, Module * M) {
926 set_scan_string(AsmString);
928 CurFilename = "from_memory";
930 return RunParser(new Module (CurFilename));
939 llvm::Module *ModuleVal;
940 llvm::Function *FunctionVal;
941 llvm::BasicBlock *BasicBlockVal;
942 llvm::TerminatorInst *TermInstVal;
943 llvm::Instruction *InstVal;
944 llvm::Constant *ConstVal;
946 const llvm::Type *PrimType;
947 std::list<llvm::PATypeHolder> *TypeList;
948 llvm::PATypeHolder *TypeVal;
949 llvm::Value *ValueVal;
950 std::vector<llvm::Value*> *ValueList;
951 llvm::ArgListType *ArgList;
952 llvm::TypeWithAttrs TypeWithAttrs;
953 llvm::TypeWithAttrsList *TypeWithAttrsList;
954 llvm::ValueRefList *ValueRefList;
956 // Represent the RHS of PHI node
957 std::list<std::pair<llvm::Value*,
958 llvm::BasicBlock*> > *PHIList;
959 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
960 std::vector<llvm::Constant*> *ConstVector;
962 llvm::GlobalValue::LinkageTypes Linkage;
963 llvm::GlobalValue::VisibilityTypes Visibility;
965 llvm::APInt *APIntVal;
973 char *StrVal; // This memory is strdup'd!
974 llvm::ValID ValIDVal; // strdup'd memory maybe!
976 llvm::Instruction::BinaryOps BinaryOpVal;
977 llvm::Instruction::TermOps TermOpVal;
978 llvm::Instruction::MemoryOps MemOpVal;
979 llvm::Instruction::CastOps CastOpVal;
980 llvm::Instruction::OtherOps OtherOpVal;
981 llvm::ICmpInst::Predicate IPredicate;
982 llvm::FCmpInst::Predicate FPredicate;
985 %type <ModuleVal> Module
986 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
987 %type <BasicBlockVal> BasicBlock InstructionList
988 %type <TermInstVal> BBTerminatorInst
989 %type <InstVal> Inst InstVal MemoryInst
990 %type <ConstVal> ConstVal ConstExpr
991 %type <ConstVector> ConstVector
992 %type <ArgList> ArgList ArgListH
993 %type <PHIList> PHIList
994 %type <ValueRefList> ValueRefList // For call param lists & GEP indices
995 %type <ValueList> IndexList // For GEP indices
996 %type <TypeList> TypeListI
997 %type <TypeWithAttrsList> ArgTypeList ArgTypeListI
998 %type <TypeWithAttrs> ArgType
999 %type <JumpTable> JumpTable
1000 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1001 %type <BoolVal> ThreadLocal // 'thread_local' or not
1002 %type <BoolVal> OptVolatile // 'volatile' or not
1003 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1004 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
1005 %type <Linkage> GVInternalLinkage GVExternalLinkage
1006 %type <Linkage> FunctionDefineLinkage FunctionDeclareLinkage
1007 %type <Visibility> GVVisibilityStyle
1009 // ValueRef - Unresolved reference to a definition or BB
1010 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1011 %type <ValueVal> ResolvedVal // <type> <valref> pair
1012 // Tokens and types for handling constant integer values
1014 // ESINT64VAL - A negative number within long long range
1015 %token <SInt64Val> ESINT64VAL
1017 // EUINT64VAL - A positive number within uns. long long range
1018 %token <UInt64Val> EUINT64VAL
1020 // ESAPINTVAL - A negative number with arbitrary precision
1021 %token <APIntVal> ESAPINTVAL
1023 // EUAPINTVAL - A positive number with arbitrary precision
1024 %token <APIntVal> EUAPINTVAL
1026 %token <UIntVal> LOCALVAL_ID GLOBALVAL_ID // %123 @123
1027 %token <FPVal> FPVAL // Float or Double constant
1029 // Built in types...
1030 %type <TypeVal> Types ResultTypes
1031 %type <PrimType> IntType FPType PrimType // Classifications
1032 %token <PrimType> VOID INTTYPE
1033 %token <PrimType> FLOAT DOUBLE LABEL
1036 %token<StrVal> LOCALVAR GLOBALVAR LABELSTR STRINGCONSTANT ATSTRINGCONSTANT
1037 %type <StrVal> LocalName OptLocalName OptLocalAssign
1038 %type <StrVal> GlobalName OptGlobalAssign
1039 %type <UIntVal> OptAlign OptCAlign
1040 %type <StrVal> OptSection SectionString
1042 %token ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1043 %token DECLARE DEFINE GLOBAL CONSTANT SECTION VOLATILE THREAD_LOCAL
1044 %token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
1045 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
1046 %token OPAQUE EXTERNAL TARGET TRIPLE ALIGN
1047 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1048 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1050 %type <UIntVal> OptCallingConv
1051 %type <ParamAttrs> OptParamAttrs ParamAttr
1052 %type <ParamAttrs> OptFuncAttrs FuncAttr
1054 // Basic Block Terminating Operators
1055 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1058 %type <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
1059 %token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1060 %token <BinaryOpVal> SHL LSHR ASHR
1062 %token <OtherOpVal> ICMP FCMP
1063 %type <IPredicate> IPredicates
1064 %type <FPredicate> FPredicates
1065 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1066 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1068 // Memory Instructions
1069 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1072 %type <CastOpVal> CastOps
1073 %token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1074 %token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1077 %token <OtherOpVal> PHI_TOK SELECT VAARG
1078 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1080 // Function Attributes
1081 %token NORETURN INREG SRET NOUNWIND
1083 // Visibility Styles
1084 %token DEFAULT HIDDEN
1090 // Operations that are notably excluded from this list include:
1091 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1093 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1094 LogicalOps : SHL | LSHR | ASHR | AND | OR | XOR;
1095 CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1096 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1099 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1100 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1101 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1102 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1103 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1107 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1108 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1109 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1110 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1111 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1112 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1113 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1114 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1115 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1118 // These are some types that allow classification if we only want a particular
1119 // thing... for example, only a signed, unsigned, or integral type.
1121 FPType : FLOAT | DOUBLE;
1123 LocalName : LOCALVAR | STRINGCONSTANT;
1124 OptLocalName : LocalName | /*empty*/ { $$ = 0; };
1126 /// OptLocalAssign - Value producing statements have an optional assignment
1128 OptLocalAssign : LocalName '=' {
1137 GlobalName : GLOBALVAR | ATSTRINGCONSTANT;
1139 OptGlobalAssign : GlobalName '=' {
1149 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1150 | WEAK { $$ = GlobalValue::WeakLinkage; }
1151 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1152 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1153 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1157 : DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1158 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1159 | EXTERNAL { $$ = GlobalValue::ExternalLinkage; }
1163 : /*empty*/ { $$ = GlobalValue::DefaultVisibility; }
1164 | HIDDEN { $$ = GlobalValue::HiddenVisibility; }
1167 FunctionDeclareLinkage
1168 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1169 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1170 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1173 FunctionDefineLinkage
1174 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1175 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1176 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1177 | WEAK { $$ = GlobalValue::WeakLinkage; }
1178 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1181 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1182 CCC_TOK { $$ = CallingConv::C; } |
1183 FASTCC_TOK { $$ = CallingConv::Fast; } |
1184 COLDCC_TOK { $$ = CallingConv::Cold; } |
1185 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1186 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1188 if ((unsigned)$2 != $2)
1189 GEN_ERROR("Calling conv too large");
1194 ParamAttr : ZEXT { $$ = ParamAttr::ZExt; }
1195 | SEXT { $$ = ParamAttr::SExt; }
1196 | INREG { $$ = ParamAttr::InReg; }
1197 | SRET { $$ = ParamAttr::StructRet; }
1200 OptParamAttrs : /* empty */ { $$ = ParamAttr::None; }
1201 | OptParamAttrs ParamAttr {
1206 FuncAttr : NORETURN { $$ = ParamAttr::NoReturn; }
1207 | NOUNWIND { $$ = ParamAttr::NoUnwind; }
1211 OptFuncAttrs : /* empty */ { $$ = ParamAttr::None; }
1212 | OptFuncAttrs FuncAttr {
1217 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1218 // a comma before it.
1219 OptAlign : /*empty*/ { $$ = 0; } |
1222 if ($$ != 0 && !isPowerOf2_32($$))
1223 GEN_ERROR("Alignment must be a power of two");
1226 OptCAlign : /*empty*/ { $$ = 0; } |
1227 ',' ALIGN EUINT64VAL {
1229 if ($$ != 0 && !isPowerOf2_32($$))
1230 GEN_ERROR("Alignment must be a power of two");
1235 SectionString : SECTION STRINGCONSTANT {
1236 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1237 if ($2[i] == '"' || $2[i] == '\\')
1238 GEN_ERROR("Invalid character in section name");
1243 OptSection : /*empty*/ { $$ = 0; } |
1244 SectionString { $$ = $1; };
1246 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1247 // is set to be the global we are processing.
1249 GlobalVarAttributes : /* empty */ {} |
1250 ',' GlobalVarAttribute GlobalVarAttributes {};
1251 GlobalVarAttribute : SectionString {
1252 CurGV->setSection($1);
1256 | ALIGN EUINT64VAL {
1257 if ($2 != 0 && !isPowerOf2_32($2))
1258 GEN_ERROR("Alignment must be a power of two");
1259 CurGV->setAlignment($2);
1263 //===----------------------------------------------------------------------===//
1264 // Types includes all predefined types... except void, because it can only be
1265 // used in specific contexts (function returning void for example).
1267 // Derived types are added later...
1269 PrimType : INTTYPE | FLOAT | DOUBLE | LABEL ;
1273 $$ = new PATypeHolder(OpaqueType::get());
1277 $$ = new PATypeHolder($1);
1280 | Types '*' { // Pointer type?
1281 if (*$1 == Type::LabelTy)
1282 GEN_ERROR("Cannot form a pointer to a basic block");
1283 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1287 | SymbolicValueRef { // Named types are also simple types...
1288 const Type* tmp = getTypeVal($1);
1290 $$ = new PATypeHolder(tmp);
1292 | '\\' EUINT64VAL { // Type UpReference
1293 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range");
1294 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1295 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1296 $$ = new PATypeHolder(OT);
1297 UR_OUT("New Upreference!\n");
1300 | Types '(' ArgTypeListI ')' OptFuncAttrs {
1301 std::vector<const Type*> Params;
1302 ParamAttrsVector Attrs;
1303 if ($5 != ParamAttr::None) {
1304 ParamAttrsWithIndex X; X.index = 0; X.attrs = $5;
1308 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1309 for (; I != E; ++I, ++index) {
1310 const Type *Ty = I->Ty->get();
1311 Params.push_back(Ty);
1312 if (Ty != Type::VoidTy)
1313 if (I->Attrs != ParamAttr::None) {
1314 ParamAttrsWithIndex X; X.index = index; X.attrs = I->Attrs;
1318 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1319 if (isVarArg) Params.pop_back();
1321 ParamAttrsList *ActualAttrs = 0;
1323 ActualAttrs = ParamAttrsList::get(Attrs);
1324 FunctionType *FT = FunctionType::get(*$1, Params, isVarArg, ActualAttrs);
1325 delete $3; // Delete the argument list
1326 delete $1; // Delete the return type handle
1327 $$ = new PATypeHolder(HandleUpRefs(FT));
1330 | VOID '(' ArgTypeListI ')' OptFuncAttrs {
1331 std::vector<const Type*> Params;
1332 ParamAttrsVector Attrs;
1333 if ($5 != ParamAttr::None) {
1334 ParamAttrsWithIndex X; X.index = 0; X.attrs = $5;
1337 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1339 for ( ; I != E; ++I, ++index) {
1340 const Type* Ty = I->Ty->get();
1341 Params.push_back(Ty);
1342 if (Ty != Type::VoidTy)
1343 if (I->Attrs != ParamAttr::None) {
1344 ParamAttrsWithIndex X; X.index = index; X.attrs = I->Attrs;
1348 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1349 if (isVarArg) Params.pop_back();
1351 ParamAttrsList *ActualAttrs = 0;
1353 ActualAttrs = ParamAttrsList::get(Attrs);
1355 FunctionType *FT = FunctionType::get($1, Params, isVarArg, ActualAttrs);
1356 delete $3; // Delete the argument list
1357 $$ = new PATypeHolder(HandleUpRefs(FT));
1361 | '[' EUINT64VAL 'x' Types ']' { // Sized array type?
1362 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1366 | '<' EUINT64VAL 'x' Types '>' { // Vector type?
1367 const llvm::Type* ElemTy = $4->get();
1368 if ((unsigned)$2 != $2)
1369 GEN_ERROR("Unsigned result not equal to signed result");
1370 if (!ElemTy->isFloatingPoint() && !ElemTy->isInteger())
1371 GEN_ERROR("Element type of a VectorType must be primitive");
1372 if (!isPowerOf2_32($2))
1373 GEN_ERROR("Vector length should be a power of 2");
1374 $$ = new PATypeHolder(HandleUpRefs(VectorType::get(*$4, (unsigned)$2)));
1378 | '{' TypeListI '}' { // Structure type?
1379 std::vector<const Type*> Elements;
1380 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1381 E = $2->end(); I != E; ++I)
1382 Elements.push_back(*I);
1384 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1388 | '{' '}' { // Empty structure type?
1389 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1392 | '<' '{' TypeListI '}' '>' {
1393 std::vector<const Type*> Elements;
1394 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1395 E = $3->end(); I != E; ++I)
1396 Elements.push_back(*I);
1398 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1402 | '<' '{' '}' '>' { // Empty structure type?
1403 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1409 : Types OptParamAttrs {
1417 if (!UpRefs.empty())
1418 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1419 if (!(*$1)->isFirstClassType())
1420 GEN_ERROR("LLVM functions cannot return aggregate types");
1424 $$ = new PATypeHolder(Type::VoidTy);
1428 ArgTypeList : ArgType {
1429 $$ = new TypeWithAttrsList();
1433 | ArgTypeList ',' ArgType {
1434 ($$=$1)->push_back($3);
1441 | ArgTypeList ',' DOTDOTDOT {
1443 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1444 TWA.Ty = new PATypeHolder(Type::VoidTy);
1449 $$ = new TypeWithAttrsList;
1450 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1451 TWA.Ty = new PATypeHolder(Type::VoidTy);
1456 $$ = new TypeWithAttrsList();
1460 // TypeList - Used for struct declarations and as a basis for function type
1461 // declaration type lists
1464 $$ = new std::list<PATypeHolder>();
1469 | TypeListI ',' Types {
1470 ($$=$1)->push_back(*$3);
1475 // ConstVal - The various declarations that go into the constant pool. This
1476 // production is used ONLY to represent constants that show up AFTER a 'const',
1477 // 'constant' or 'global' token at global scope. Constants that can be inlined
1478 // into other expressions (such as integers and constexprs) are handled by the
1479 // ResolvedVal, ValueRef and ConstValueRef productions.
1481 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1482 if (!UpRefs.empty())
1483 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1484 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1486 GEN_ERROR("Cannot make array constant with type: '" +
1487 (*$1)->getDescription() + "'");
1488 const Type *ETy = ATy->getElementType();
1489 int NumElements = ATy->getNumElements();
1491 // Verify that we have the correct size...
1492 if (NumElements != -1 && NumElements != (int)$3->size())
1493 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1494 utostr($3->size()) + " arguments, but has size of " +
1495 itostr(NumElements) + "");
1497 // Verify all elements are correct type!
1498 for (unsigned i = 0; i < $3->size(); i++) {
1499 if (ETy != (*$3)[i]->getType())
1500 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1501 ETy->getDescription() +"' as required!\nIt is of type '"+
1502 (*$3)[i]->getType()->getDescription() + "'.");
1505 $$ = ConstantArray::get(ATy, *$3);
1506 delete $1; delete $3;
1510 if (!UpRefs.empty())
1511 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1512 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1514 GEN_ERROR("Cannot make array constant with type: '" +
1515 (*$1)->getDescription() + "'");
1517 int NumElements = ATy->getNumElements();
1518 if (NumElements != -1 && NumElements != 0)
1519 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1520 " arguments, but has size of " + itostr(NumElements) +"");
1521 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1525 | Types 'c' STRINGCONSTANT {
1526 if (!UpRefs.empty())
1527 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1528 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1530 GEN_ERROR("Cannot make array constant with type: '" +
1531 (*$1)->getDescription() + "'");
1533 int NumElements = ATy->getNumElements();
1534 const Type *ETy = ATy->getElementType();
1535 char *EndStr = UnEscapeLexed($3, true);
1536 if (NumElements != -1 && NumElements != (EndStr-$3))
1537 GEN_ERROR("Can't build string constant of size " +
1538 itostr((int)(EndStr-$3)) +
1539 " when array has size " + itostr(NumElements) + "");
1540 std::vector<Constant*> Vals;
1541 if (ETy == Type::Int8Ty) {
1542 for (unsigned char *C = (unsigned char *)$3;
1543 C != (unsigned char*)EndStr; ++C)
1544 Vals.push_back(ConstantInt::get(ETy, *C));
1547 GEN_ERROR("Cannot build string arrays of non byte sized elements");
1550 $$ = ConstantArray::get(ATy, Vals);
1554 | Types '<' ConstVector '>' { // Nonempty unsized arr
1555 if (!UpRefs.empty())
1556 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1557 const VectorType *PTy = dyn_cast<VectorType>($1->get());
1559 GEN_ERROR("Cannot make packed constant with type: '" +
1560 (*$1)->getDescription() + "'");
1561 const Type *ETy = PTy->getElementType();
1562 int NumElements = PTy->getNumElements();
1564 // Verify that we have the correct size...
1565 if (NumElements != -1 && NumElements != (int)$3->size())
1566 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1567 utostr($3->size()) + " arguments, but has size of " +
1568 itostr(NumElements) + "");
1570 // Verify all elements are correct type!
1571 for (unsigned i = 0; i < $3->size(); i++) {
1572 if (ETy != (*$3)[i]->getType())
1573 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1574 ETy->getDescription() +"' as required!\nIt is of type '"+
1575 (*$3)[i]->getType()->getDescription() + "'.");
1578 $$ = ConstantVector::get(PTy, *$3);
1579 delete $1; delete $3;
1582 | Types '{' ConstVector '}' {
1583 const StructType *STy = dyn_cast<StructType>($1->get());
1585 GEN_ERROR("Cannot make struct constant with type: '" +
1586 (*$1)->getDescription() + "'");
1588 if ($3->size() != STy->getNumContainedTypes())
1589 GEN_ERROR("Illegal number of initializers for structure type");
1591 // Check to ensure that constants are compatible with the type initializer!
1592 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1593 if ((*$3)[i]->getType() != STy->getElementType(i))
1594 GEN_ERROR("Expected type '" +
1595 STy->getElementType(i)->getDescription() +
1596 "' for element #" + utostr(i) +
1597 " of structure initializer");
1599 // Check to ensure that Type is not packed
1600 if (STy->isPacked())
1601 GEN_ERROR("Unpacked Initializer to vector type '" + STy->getDescription() + "'");
1603 $$ = ConstantStruct::get(STy, *$3);
1604 delete $1; delete $3;
1608 if (!UpRefs.empty())
1609 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1610 const StructType *STy = dyn_cast<StructType>($1->get());
1612 GEN_ERROR("Cannot make struct constant with type: '" +
1613 (*$1)->getDescription() + "'");
1615 if (STy->getNumContainedTypes() != 0)
1616 GEN_ERROR("Illegal number of initializers for structure type");
1618 // Check to ensure that Type is not packed
1619 if (STy->isPacked())
1620 GEN_ERROR("Unpacked Initializer to vector type '" + STy->getDescription() + "'");
1622 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1626 | Types '<' '{' ConstVector '}' '>' {
1627 const StructType *STy = dyn_cast<StructType>($1->get());
1629 GEN_ERROR("Cannot make struct constant with type: '" +
1630 (*$1)->getDescription() + "'");
1632 if ($4->size() != STy->getNumContainedTypes())
1633 GEN_ERROR("Illegal number of initializers for structure type");
1635 // Check to ensure that constants are compatible with the type initializer!
1636 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1637 if ((*$4)[i]->getType() != STy->getElementType(i))
1638 GEN_ERROR("Expected type '" +
1639 STy->getElementType(i)->getDescription() +
1640 "' for element #" + utostr(i) +
1641 " of structure initializer");
1643 // Check to ensure that Type is packed
1644 if (!STy->isPacked())
1645 GEN_ERROR("Vector initializer to non-vector type '" +
1646 STy->getDescription() + "'");
1648 $$ = ConstantStruct::get(STy, *$4);
1649 delete $1; delete $4;
1652 | Types '<' '{' '}' '>' {
1653 if (!UpRefs.empty())
1654 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1655 const StructType *STy = dyn_cast<StructType>($1->get());
1657 GEN_ERROR("Cannot make struct constant with type: '" +
1658 (*$1)->getDescription() + "'");
1660 if (STy->getNumContainedTypes() != 0)
1661 GEN_ERROR("Illegal number of initializers for structure type");
1663 // Check to ensure that Type is packed
1664 if (!STy->isPacked())
1665 GEN_ERROR("Vector initializer to non-vector type '" +
1666 STy->getDescription() + "'");
1668 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1673 if (!UpRefs.empty())
1674 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1675 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1677 GEN_ERROR("Cannot make null pointer constant with type: '" +
1678 (*$1)->getDescription() + "'");
1680 $$ = ConstantPointerNull::get(PTy);
1685 if (!UpRefs.empty())
1686 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1687 $$ = UndefValue::get($1->get());
1691 | Types SymbolicValueRef {
1692 if (!UpRefs.empty())
1693 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1694 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1696 GEN_ERROR("Global const reference must be a pointer type");
1698 // ConstExprs can exist in the body of a function, thus creating
1699 // GlobalValues whenever they refer to a variable. Because we are in
1700 // the context of a function, getExistingVal will search the functions
1701 // symbol table instead of the module symbol table for the global symbol,
1702 // which throws things all off. To get around this, we just tell
1703 // getExistingVal that we are at global scope here.
1705 Function *SavedCurFn = CurFun.CurrentFunction;
1706 CurFun.CurrentFunction = 0;
1708 Value *V = getExistingVal(Ty, $2);
1711 CurFun.CurrentFunction = SavedCurFn;
1713 // If this is an initializer for a constant pointer, which is referencing a
1714 // (currently) undefined variable, create a stub now that shall be replaced
1715 // in the future with the right type of variable.
1718 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1719 const PointerType *PT = cast<PointerType>(Ty);
1721 // First check to see if the forward references value is already created!
1722 PerModuleInfo::GlobalRefsType::iterator I =
1723 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1725 if (I != CurModule.GlobalRefs.end()) {
1726 V = I->second; // Placeholder already exists, use it...
1730 if ($2.Type == ValID::GlobalName)
1732 else if ($2.Type != ValID::GlobalID)
1733 GEN_ERROR("Invalid reference to global");
1735 // Create the forward referenced global.
1737 if (const FunctionType *FTy =
1738 dyn_cast<FunctionType>(PT->getElementType())) {
1739 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1740 CurModule.CurrentModule);
1742 GV = new GlobalVariable(PT->getElementType(), false,
1743 GlobalValue::ExternalLinkage, 0,
1744 Name, CurModule.CurrentModule);
1747 // Keep track of the fact that we have a forward ref to recycle it
1748 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1753 $$ = cast<GlobalValue>(V);
1754 delete $1; // Free the type handle
1758 if (!UpRefs.empty())
1759 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1760 if ($1->get() != $2->getType())
1761 GEN_ERROR("Mismatched types for constant expression: " +
1762 (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1767 | Types ZEROINITIALIZER {
1768 if (!UpRefs.empty())
1769 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1770 const Type *Ty = $1->get();
1771 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1772 GEN_ERROR("Cannot create a null initialized value of this type");
1773 $$ = Constant::getNullValue(Ty);
1777 | IntType ESINT64VAL { // integral constants
1778 if (!ConstantInt::isValueValidForType($1, $2))
1779 GEN_ERROR("Constant value doesn't fit in type");
1780 $$ = ConstantInt::get($1, $2, true);
1783 | IntType ESAPINTVAL { // arbitrary precision integer constants
1784 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1785 if ($2->getBitWidth() > BitWidth) {
1786 GEN_ERROR("Constant value does not fit in type");
1788 $2->sextOrTrunc(BitWidth);
1789 $$ = ConstantInt::get(*$2);
1793 | IntType EUINT64VAL { // integral constants
1794 if (!ConstantInt::isValueValidForType($1, $2))
1795 GEN_ERROR("Constant value doesn't fit in type");
1796 $$ = ConstantInt::get($1, $2, false);
1799 | IntType EUAPINTVAL { // arbitrary precision integer constants
1800 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1801 if ($2->getBitWidth() > BitWidth) {
1802 GEN_ERROR("Constant value does not fit in type");
1804 $2->zextOrTrunc(BitWidth);
1805 $$ = ConstantInt::get(*$2);
1809 | INTTYPE TRUETOK { // Boolean constants
1810 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1811 $$ = ConstantInt::getTrue();
1814 | INTTYPE FALSETOK { // Boolean constants
1815 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1816 $$ = ConstantInt::getFalse();
1819 | FPType FPVAL { // Float & Double constants
1820 if (!ConstantFP::isValueValidForType($1, $2))
1821 GEN_ERROR("Floating point constant invalid for type");
1822 $$ = ConstantFP::get($1, $2);
1827 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1828 if (!UpRefs.empty())
1829 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1831 const Type *DestTy = $5->get();
1832 if (!CastInst::castIsValid($1, $3, DestTy))
1833 GEN_ERROR("invalid cast opcode for cast from '" +
1834 Val->getType()->getDescription() + "' to '" +
1835 DestTy->getDescription() + "'");
1836 $$ = ConstantExpr::getCast($1, $3, DestTy);
1839 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1840 if (!isa<PointerType>($3->getType()))
1841 GEN_ERROR("GetElementPtr requires a pointer operand");
1844 GetElementPtrInst::getIndexedType($3->getType(), &(*$4)[0], $4->size(),
1847 GEN_ERROR("Index list invalid for constant getelementptr");
1849 SmallVector<Constant*, 8> IdxVec;
1850 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1851 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1852 IdxVec.push_back(C);
1854 GEN_ERROR("Indices to constant getelementptr must be constants");
1858 $$ = ConstantExpr::getGetElementPtr($3, &IdxVec[0], IdxVec.size());
1861 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1862 if ($3->getType() != Type::Int1Ty)
1863 GEN_ERROR("Select condition must be of boolean type");
1864 if ($5->getType() != $7->getType())
1865 GEN_ERROR("Select operand types must match");
1866 $$ = ConstantExpr::getSelect($3, $5, $7);
1869 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1870 if ($3->getType() != $5->getType())
1871 GEN_ERROR("Binary operator types must match");
1873 $$ = ConstantExpr::get($1, $3, $5);
1875 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1876 if ($3->getType() != $5->getType())
1877 GEN_ERROR("Logical operator types must match");
1878 if (!$3->getType()->isInteger()) {
1879 if (Instruction::isShift($1) || !isa<VectorType>($3->getType()) ||
1880 !cast<VectorType>($3->getType())->getElementType()->isInteger())
1881 GEN_ERROR("Logical operator requires integral operands");
1883 $$ = ConstantExpr::get($1, $3, $5);
1886 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1887 if ($4->getType() != $6->getType())
1888 GEN_ERROR("icmp operand types must match");
1889 $$ = ConstantExpr::getICmp($2, $4, $6);
1891 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1892 if ($4->getType() != $6->getType())
1893 GEN_ERROR("fcmp operand types must match");
1894 $$ = ConstantExpr::getFCmp($2, $4, $6);
1896 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1897 if (!ExtractElementInst::isValidOperands($3, $5))
1898 GEN_ERROR("Invalid extractelement operands");
1899 $$ = ConstantExpr::getExtractElement($3, $5);
1902 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1903 if (!InsertElementInst::isValidOperands($3, $5, $7))
1904 GEN_ERROR("Invalid insertelement operands");
1905 $$ = ConstantExpr::getInsertElement($3, $5, $7);
1908 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1909 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1910 GEN_ERROR("Invalid shufflevector operands");
1911 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1916 // ConstVector - A list of comma separated constants.
1917 ConstVector : ConstVector ',' ConstVal {
1918 ($$ = $1)->push_back($3);
1922 $$ = new std::vector<Constant*>();
1928 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1929 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1932 ThreadLocal : THREAD_LOCAL { $$ = true; } | { $$ = false; };
1935 //===----------------------------------------------------------------------===//
1936 // Rules to match Modules
1937 //===----------------------------------------------------------------------===//
1939 // Module rule: Capture the result of parsing the whole file into a result
1944 $$ = ParserResult = CurModule.CurrentModule;
1945 CurModule.ModuleDone();
1949 $$ = ParserResult = CurModule.CurrentModule;
1950 CurModule.ModuleDone();
1957 | DefinitionList Definition
1961 : DEFINE { CurFun.isDeclare = false; } Function {
1962 CurFun.FunctionDone();
1965 | DECLARE { CurFun.isDeclare = true; } FunctionProto {
1968 | MODULE ASM_TOK AsmBlock {
1971 | OptLocalAssign TYPE Types {
1972 if (!UpRefs.empty())
1973 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
1974 // Eagerly resolve types. This is not an optimization, this is a
1975 // requirement that is due to the fact that we could have this:
1977 // %list = type { %list * }
1978 // %list = type { %list * } ; repeated type decl
1980 // If types are not resolved eagerly, then the two types will not be
1981 // determined to be the same type!
1983 ResolveTypeTo($1, *$3);
1985 if (!setTypeName(*$3, $1) && !$1) {
1987 // If this is a named type that is not a redefinition, add it to the slot
1989 CurModule.Types.push_back(*$3);
1995 | OptLocalAssign TYPE VOID {
1996 ResolveTypeTo($1, $3);
1998 if (!setTypeName($3, $1) && !$1) {
2000 // If this is a named type that is not a redefinition, add it to the slot
2002 CurModule.Types.push_back($3);
2006 | OptGlobalAssign GVVisibilityStyle ThreadLocal GlobalType ConstVal {
2007 /* "Externally Visible" Linkage */
2009 GEN_ERROR("Global value initializer is not a constant");
2010 CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
2011 $2, $4, $5->getType(), $5, $3);
2013 } GlobalVarAttributes {
2016 | OptGlobalAssign GVInternalLinkage GVVisibilityStyle ThreadLocal GlobalType ConstVal {
2018 GEN_ERROR("Global value initializer is not a constant");
2019 CurGV = ParseGlobalVariable($1, $2, $3, $5, $6->getType(), $6, $4);
2021 } GlobalVarAttributes {
2024 | OptGlobalAssign GVExternalLinkage GVVisibilityStyle ThreadLocal GlobalType Types {
2025 if (!UpRefs.empty())
2026 GEN_ERROR("Invalid upreference in type: " + (*$6)->getDescription());
2027 CurGV = ParseGlobalVariable($1, $2, $3, $5, *$6, 0, $4);
2030 } GlobalVarAttributes {
2034 | TARGET TargetDefinition {
2037 | DEPLIBS '=' LibrariesDefinition {
2043 AsmBlock : STRINGCONSTANT {
2044 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2045 char *EndStr = UnEscapeLexed($1, true);
2046 std::string NewAsm($1, EndStr);
2049 if (AsmSoFar.empty())
2050 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
2052 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
2056 TargetDefinition : TRIPLE '=' STRINGCONSTANT {
2057 CurModule.CurrentModule->setTargetTriple($3);
2060 | DATALAYOUT '=' STRINGCONSTANT {
2061 CurModule.CurrentModule->setDataLayout($3);
2065 LibrariesDefinition : '[' LibList ']';
2067 LibList : LibList ',' STRINGCONSTANT {
2068 CurModule.CurrentModule->addLibrary($3);
2073 CurModule.CurrentModule->addLibrary($1);
2077 | /* empty: end of list */ {
2082 //===----------------------------------------------------------------------===//
2083 // Rules to match Function Headers
2084 //===----------------------------------------------------------------------===//
2086 ArgListH : ArgListH ',' Types OptParamAttrs OptLocalName {
2087 if (!UpRefs.empty())
2088 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2089 if (*$3 == Type::VoidTy)
2090 GEN_ERROR("void typed arguments are invalid");
2091 ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
2096 | Types OptParamAttrs OptLocalName {
2097 if (!UpRefs.empty())
2098 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2099 if (*$1 == Type::VoidTy)
2100 GEN_ERROR("void typed arguments are invalid");
2101 ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2102 $$ = new ArgListType;
2107 ArgList : ArgListH {
2111 | ArgListH ',' DOTDOTDOT {
2113 struct ArgListEntry E;
2114 E.Ty = new PATypeHolder(Type::VoidTy);
2116 E.Attrs = ParamAttr::None;
2121 $$ = new ArgListType;
2122 struct ArgListEntry E;
2123 E.Ty = new PATypeHolder(Type::VoidTy);
2125 E.Attrs = ParamAttr::None;
2134 FunctionHeaderH : OptCallingConv ResultTypes GlobalName '(' ArgList ')'
2135 OptFuncAttrs OptSection OptAlign {
2137 std::string FunctionName($3);
2138 free($3); // Free strdup'd memory!
2140 // Check the function result for abstractness if this is a define. We should
2141 // have no abstract types at this point
2142 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($2))
2143 GEN_ERROR("Reference to abstract result: "+ $2->get()->getDescription());
2145 std::vector<const Type*> ParamTypeList;
2146 ParamAttrsVector Attrs;
2147 if ($7 != ParamAttr::None) {
2148 ParamAttrsWithIndex PAWI; PAWI.index = 0; PAWI.attrs = $7;
2149 Attrs.push_back(PAWI);
2151 if ($5) { // If there are arguments...
2153 for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I, ++index) {
2154 const Type* Ty = I->Ty->get();
2155 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2156 GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2157 ParamTypeList.push_back(Ty);
2158 if (Ty != Type::VoidTy)
2159 if (I->Attrs != ParamAttr::None) {
2160 ParamAttrsWithIndex PAWI; PAWI.index = index; PAWI.attrs = I->Attrs;
2161 Attrs.push_back(PAWI);
2166 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2167 if (isVarArg) ParamTypeList.pop_back();
2169 ParamAttrsList *PAL = 0;
2171 PAL = ParamAttrsList::get(Attrs);
2173 FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg, PAL);
2174 const PointerType *PFT = PointerType::get(FT);
2178 if (!FunctionName.empty()) {
2179 ID = ValID::createGlobalName((char*)FunctionName.c_str());
2181 ID = ValID::createGlobalID(CurModule.Values.size());
2185 // See if this function was forward referenced. If so, recycle the object.
2186 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2187 // Move the function to the end of the list, from whereever it was
2188 // previously inserted.
2189 Fn = cast<Function>(FWRef);
2190 CurModule.CurrentModule->getFunctionList().remove(Fn);
2191 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2192 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2193 (Fn = CurModule.CurrentModule->getFunction(FunctionName))) {
2194 if (Fn->getFunctionType() != FT ) {
2195 // The existing function doesn't have the same type. This is an overload
2197 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2198 } else if (!CurFun.isDeclare && !Fn->isDeclaration()) {
2199 // Neither the existing or the current function is a declaration and they
2200 // have the same name and same type. Clearly this is a redefinition.
2201 GEN_ERROR("Redefinition of function '" + FunctionName + "'");
2202 } if (Fn->isDeclaration()) {
2203 // Make sure to strip off any argument names so we can't get conflicts.
2204 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2208 } else { // Not already defined?
2209 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
2210 CurModule.CurrentModule);
2212 InsertValue(Fn, CurModule.Values);
2215 CurFun.FunctionStart(Fn);
2217 if (CurFun.isDeclare) {
2218 // If we have declaration, always overwrite linkage. This will allow us to
2219 // correctly handle cases, when pointer to function is passed as argument to
2220 // another function.
2221 Fn->setLinkage(CurFun.Linkage);
2222 Fn->setVisibility(CurFun.Visibility);
2224 Fn->setCallingConv($1);
2225 Fn->setAlignment($9);
2231 // Add all of the arguments we parsed to the function...
2232 if ($5) { // Is null if empty...
2233 if (isVarArg) { // Nuke the last entry
2234 assert($5->back().Ty->get() == Type::VoidTy && $5->back().Name == 0 &&
2235 "Not a varargs marker!");
2236 delete $5->back().Ty;
2237 $5->pop_back(); // Delete the last entry
2239 Function::arg_iterator ArgIt = Fn->arg_begin();
2240 Function::arg_iterator ArgEnd = Fn->arg_end();
2242 for (ArgListType::iterator I = $5->begin();
2243 I != $5->end() && ArgIt != ArgEnd; ++I, ++ArgIt) {
2244 delete I->Ty; // Delete the typeholder...
2245 setValueName(ArgIt, I->Name); // Insert arg into symtab...
2251 delete $5; // We're now done with the argument list
2256 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2258 FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2259 $$ = CurFun.CurrentFunction;
2261 // Make sure that we keep track of the linkage type even if there was a
2262 // previous "declare".
2264 $$->setVisibility($2);
2267 END : ENDTOK | '}'; // Allow end of '}' to end a function
2269 Function : BasicBlockList END {
2274 FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2275 CurFun.CurrentFunction->setLinkage($1);
2276 CurFun.CurrentFunction->setVisibility($2);
2277 $$ = CurFun.CurrentFunction;
2278 CurFun.FunctionDone();
2282 //===----------------------------------------------------------------------===//
2283 // Rules to match Basic Blocks
2284 //===----------------------------------------------------------------------===//
2286 OptSideEffect : /* empty */ {
2295 ConstValueRef : ESINT64VAL { // A reference to a direct constant
2296 $$ = ValID::create($1);
2300 $$ = ValID::create($1);
2303 | FPVAL { // Perhaps it's an FP constant?
2304 $$ = ValID::create($1);
2308 $$ = ValID::create(ConstantInt::getTrue());
2312 $$ = ValID::create(ConstantInt::getFalse());
2316 $$ = ValID::createNull();
2320 $$ = ValID::createUndef();
2323 | ZEROINITIALIZER { // A vector zero constant.
2324 $$ = ValID::createZeroInit();
2327 | '<' ConstVector '>' { // Nonempty unsized packed vector
2328 const Type *ETy = (*$2)[0]->getType();
2329 int NumElements = $2->size();
2331 VectorType* pt = VectorType::get(ETy, NumElements);
2332 PATypeHolder* PTy = new PATypeHolder(
2340 // Verify all elements are correct type!
2341 for (unsigned i = 0; i < $2->size(); i++) {
2342 if (ETy != (*$2)[i]->getType())
2343 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2344 ETy->getDescription() +"' as required!\nIt is of type '" +
2345 (*$2)[i]->getType()->getDescription() + "'.");
2348 $$ = ValID::create(ConstantVector::get(pt, *$2));
2349 delete PTy; delete $2;
2353 $$ = ValID::create($1);
2356 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2357 char *End = UnEscapeLexed($3, true);
2358 std::string AsmStr = std::string($3, End);
2359 End = UnEscapeLexed($5, true);
2360 std::string Constraints = std::string($5, End);
2361 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2367 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2370 SymbolicValueRef : LOCALVAL_ID { // Is it an integer reference...?
2371 $$ = ValID::createLocalID($1);
2375 $$ = ValID::createGlobalID($1);
2378 | LocalName { // Is it a named reference...?
2379 $$ = ValID::createLocalName($1);
2382 | GlobalName { // Is it a named reference...?
2383 $$ = ValID::createGlobalName($1);
2387 // ValueRef - A reference to a definition... either constant or symbolic
2388 ValueRef : SymbolicValueRef | ConstValueRef;
2391 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2392 // type immediately preceeds the value reference, and allows complex constant
2393 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2394 ResolvedVal : Types ValueRef {
2395 if (!UpRefs.empty())
2396 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2397 $$ = getVal(*$1, $2);
2403 BasicBlockList : BasicBlockList BasicBlock {
2407 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2413 // Basic blocks are terminated by branching instructions:
2414 // br, br/cc, switch, ret
2416 BasicBlock : InstructionList OptLocalAssign BBTerminatorInst {
2417 setValueName($3, $2);
2420 $1->getInstList().push_back($3);
2425 InstructionList : InstructionList Inst {
2426 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2427 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2428 if (CI2->getParent() == 0)
2429 $1->getInstList().push_back(CI2);
2430 $1->getInstList().push_back($2);
2434 | /* empty */ { // Empty space between instruction lists
2435 $$ = defineBBVal(ValID::createLocalID(CurFun.NextValNum));
2438 | LABELSTR { // Labelled (named) basic block
2439 $$ = defineBBVal(ValID::createLocalName($1));
2443 BBTerminatorInst : RET ResolvedVal { // Return with a result...
2444 $$ = new ReturnInst($2);
2447 | RET VOID { // Return with no result...
2448 $$ = new ReturnInst();
2451 | BR LABEL ValueRef { // Unconditional Branch...
2452 BasicBlock* tmpBB = getBBVal($3);
2454 $$ = new BranchInst(tmpBB);
2455 } // Conditional Branch...
2456 | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2457 assert(cast<IntegerType>($2)->getBitWidth() == 1 && "Not Bool?");
2458 BasicBlock* tmpBBA = getBBVal($6);
2460 BasicBlock* tmpBBB = getBBVal($9);
2462 Value* tmpVal = getVal(Type::Int1Ty, $3);
2464 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2466 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2467 Value* tmpVal = getVal($2, $3);
2469 BasicBlock* tmpBB = getBBVal($6);
2471 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2474 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2476 for (; I != E; ++I) {
2477 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2478 S->addCase(CI, I->second);
2480 GEN_ERROR("Switch case is constant, but not a simple integer");
2485 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2486 Value* tmpVal = getVal($2, $3);
2488 BasicBlock* tmpBB = getBBVal($6);
2490 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2494 | INVOKE OptCallingConv ResultTypes ValueRef '(' ValueRefList ')' OptFuncAttrs
2495 TO LABEL ValueRef UNWIND LABEL ValueRef {
2497 // Handle the short syntax
2498 const PointerType *PFTy = 0;
2499 const FunctionType *Ty = 0;
2500 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2501 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2502 // Pull out the types of all of the arguments...
2503 std::vector<const Type*> ParamTypes;
2504 ParamAttrsVector Attrs;
2505 if ($8 != ParamAttr::None) {
2506 ParamAttrsWithIndex PAWI; PAWI.index = 0; PAWI.attrs = 8;
2507 Attrs.push_back(PAWI);
2509 ValueRefList::iterator I = $6->begin(), E = $6->end();
2511 for (; I != E; ++I, ++index) {
2512 const Type *Ty = I->Val->getType();
2513 if (Ty == Type::VoidTy)
2514 GEN_ERROR("Short call syntax cannot be used with varargs");
2515 ParamTypes.push_back(Ty);
2516 if (I->Attrs != ParamAttr::None) {
2517 ParamAttrsWithIndex PAWI; PAWI.index = index; PAWI.attrs = I->Attrs;
2518 Attrs.push_back(PAWI);
2522 ParamAttrsList *PAL = 0;
2524 PAL = ParamAttrsList::get(Attrs);
2525 Ty = FunctionType::get($3->get(), ParamTypes, false, PAL);
2526 PFTy = PointerType::get(Ty);
2531 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2533 BasicBlock *Normal = getBBVal($11);
2535 BasicBlock *Except = getBBVal($14);
2538 // Check the arguments
2540 if ($6->empty()) { // Has no arguments?
2541 // Make sure no arguments is a good thing!
2542 if (Ty->getNumParams() != 0)
2543 GEN_ERROR("No arguments passed to a function that "
2544 "expects arguments");
2545 } else { // Has arguments?
2546 // Loop through FunctionType's arguments and ensure they are specified
2548 FunctionType::param_iterator I = Ty->param_begin();
2549 FunctionType::param_iterator E = Ty->param_end();
2550 ValueRefList::iterator ArgI = $6->begin(), ArgE = $6->end();
2552 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2553 if (ArgI->Val->getType() != *I)
2554 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2555 (*I)->getDescription() + "'");
2556 Args.push_back(ArgI->Val);
2559 if (Ty->isVarArg()) {
2561 for (; ArgI != ArgE; ++ArgI)
2562 Args.push_back(ArgI->Val); // push the remaining varargs
2563 } else if (I != E || ArgI != ArgE)
2564 GEN_ERROR("Invalid number of parameters detected");
2567 // Create the InvokeInst
2568 InvokeInst *II = new InvokeInst(V, Normal, Except, &Args[0], Args.size());
2569 II->setCallingConv($2);
2575 $$ = new UnwindInst();
2579 $$ = new UnreachableInst();
2585 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2587 Constant *V = cast<Constant>(getExistingVal($2, $3));
2590 GEN_ERROR("May only switch on a constant pool value");
2592 BasicBlock* tmpBB = getBBVal($6);
2594 $$->push_back(std::make_pair(V, tmpBB));
2596 | IntType ConstValueRef ',' LABEL ValueRef {
2597 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2598 Constant *V = cast<Constant>(getExistingVal($1, $2));
2602 GEN_ERROR("May only switch on a constant pool value");
2604 BasicBlock* tmpBB = getBBVal($5);
2606 $$->push_back(std::make_pair(V, tmpBB));
2609 Inst : OptLocalAssign InstVal {
2610 // Is this definition named?? if so, assign the name...
2611 setValueName($2, $1);
2619 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2620 if (!UpRefs.empty())
2621 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2622 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2623 Value* tmpVal = getVal(*$1, $3);
2625 BasicBlock* tmpBB = getBBVal($5);
2627 $$->push_back(std::make_pair(tmpVal, tmpBB));
2630 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2632 Value* tmpVal = getVal($1->front().first->getType(), $4);
2634 BasicBlock* tmpBB = getBBVal($6);
2636 $1->push_back(std::make_pair(tmpVal, tmpBB));
2640 ValueRefList : Types ValueRef OptParamAttrs {
2641 if (!UpRefs.empty())
2642 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2643 // Used for call and invoke instructions
2644 $$ = new ValueRefList();
2645 ValueRefListEntry E; E.Attrs = $3; E.Val = getVal($1->get(), $2);
2649 | ValueRefList ',' Types ValueRef OptParamAttrs {
2650 if (!UpRefs.empty())
2651 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2653 ValueRefListEntry E; E.Attrs = $5; E.Val = getVal($3->get(), $4);
2658 | /*empty*/ { $$ = new ValueRefList(); };
2660 IndexList // Used for gep instructions and constant expressions
2661 : /*empty*/ { $$ = new std::vector<Value*>(); }
2662 | IndexList ',' ResolvedVal {
2669 OptTailCall : TAIL CALL {
2678 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2679 if (!UpRefs.empty())
2680 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2681 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
2682 !isa<VectorType>((*$2).get()))
2684 "Arithmetic operator requires integer, FP, or packed operands");
2685 if (isa<VectorType>((*$2).get()) &&
2686 ($1 == Instruction::URem ||
2687 $1 == Instruction::SRem ||
2688 $1 == Instruction::FRem))
2689 GEN_ERROR("Remainder not supported on vector types");
2690 Value* val1 = getVal(*$2, $3);
2692 Value* val2 = getVal(*$2, $5);
2694 $$ = BinaryOperator::create($1, val1, val2);
2696 GEN_ERROR("binary operator returned null");
2699 | LogicalOps Types ValueRef ',' ValueRef {
2700 if (!UpRefs.empty())
2701 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2702 if (!(*$2)->isInteger()) {
2703 if (Instruction::isShift($1) || !isa<VectorType>($2->get()) ||
2704 !cast<VectorType>($2->get())->getElementType()->isInteger())
2705 GEN_ERROR("Logical operator requires integral operands");
2707 Value* tmpVal1 = getVal(*$2, $3);
2709 Value* tmpVal2 = getVal(*$2, $5);
2711 $$ = BinaryOperator::create($1, tmpVal1, tmpVal2);
2713 GEN_ERROR("binary operator returned null");
2716 | ICMP IPredicates Types ValueRef ',' ValueRef {
2717 if (!UpRefs.empty())
2718 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2719 if (isa<VectorType>((*$3).get()))
2720 GEN_ERROR("Vector types not supported by icmp instruction");
2721 Value* tmpVal1 = getVal(*$3, $4);
2723 Value* tmpVal2 = getVal(*$3, $6);
2725 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2727 GEN_ERROR("icmp operator returned null");
2730 | FCMP FPredicates Types ValueRef ',' ValueRef {
2731 if (!UpRefs.empty())
2732 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2733 if (isa<VectorType>((*$3).get()))
2734 GEN_ERROR("Vector types not supported by fcmp instruction");
2735 Value* tmpVal1 = getVal(*$3, $4);
2737 Value* tmpVal2 = getVal(*$3, $6);
2739 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2741 GEN_ERROR("fcmp operator returned null");
2744 | CastOps ResolvedVal TO Types {
2745 if (!UpRefs.empty())
2746 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2748 const Type* DestTy = $4->get();
2749 if (!CastInst::castIsValid($1, Val, DestTy))
2750 GEN_ERROR("invalid cast opcode for cast from '" +
2751 Val->getType()->getDescription() + "' to '" +
2752 DestTy->getDescription() + "'");
2753 $$ = CastInst::create($1, Val, DestTy);
2756 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2757 if ($2->getType() != Type::Int1Ty)
2758 GEN_ERROR("select condition must be boolean");
2759 if ($4->getType() != $6->getType())
2760 GEN_ERROR("select value types should match");
2761 $$ = new SelectInst($2, $4, $6);
2764 | VAARG ResolvedVal ',' Types {
2765 if (!UpRefs.empty())
2766 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2767 $$ = new VAArgInst($2, *$4);
2771 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2772 if (!ExtractElementInst::isValidOperands($2, $4))
2773 GEN_ERROR("Invalid extractelement operands");
2774 $$ = new ExtractElementInst($2, $4);
2777 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2778 if (!InsertElementInst::isValidOperands($2, $4, $6))
2779 GEN_ERROR("Invalid insertelement operands");
2780 $$ = new InsertElementInst($2, $4, $6);
2783 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2784 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
2785 GEN_ERROR("Invalid shufflevector operands");
2786 $$ = new ShuffleVectorInst($2, $4, $6);
2790 const Type *Ty = $2->front().first->getType();
2791 if (!Ty->isFirstClassType())
2792 GEN_ERROR("PHI node operands must be of first class type");
2793 $$ = new PHINode(Ty);
2794 ((PHINode*)$$)->reserveOperandSpace($2->size());
2795 while ($2->begin() != $2->end()) {
2796 if ($2->front().first->getType() != Ty)
2797 GEN_ERROR("All elements of a PHI node must be of the same type");
2798 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2801 delete $2; // Free the list...
2804 | OptTailCall OptCallingConv ResultTypes ValueRef '(' ValueRefList ')'
2807 // Handle the short syntax
2808 const PointerType *PFTy = 0;
2809 const FunctionType *Ty = 0;
2810 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2811 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2812 // Pull out the types of all of the arguments...
2813 std::vector<const Type*> ParamTypes;
2814 ParamAttrsVector Attrs;
2815 if ($8 != ParamAttr::None) {
2816 ParamAttrsWithIndex PAWI; PAWI.index = 0; PAWI.attrs = $8;
2817 Attrs.push_back(PAWI);
2820 ValueRefList::iterator I = $6->begin(), E = $6->end();
2821 for (; I != E; ++I, ++index) {
2822 const Type *Ty = I->Val->getType();
2823 if (Ty == Type::VoidTy)
2824 GEN_ERROR("Short call syntax cannot be used with varargs");
2825 ParamTypes.push_back(Ty);
2826 if (I->Attrs != ParamAttr::None) {
2827 ParamAttrsWithIndex PAWI; PAWI.index = index; PAWI.attrs = I->Attrs;
2828 Attrs.push_back(PAWI);
2832 ParamAttrsList *PAL = 0;
2834 PAL = ParamAttrsList::get(Attrs);
2836 Ty = FunctionType::get($3->get(), ParamTypes, false, PAL);
2837 PFTy = PointerType::get(Ty);
2840 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2843 // Check for call to invalid intrinsic to avoid crashing later.
2844 if (Function *theF = dyn_cast<Function>(V)) {
2845 if (theF->hasName() && (theF->getValueName()->getKeyLength() >= 5) &&
2846 (0 == strncmp(theF->getValueName()->getKeyData(), "llvm.", 5)) &&
2847 !theF->getIntrinsicID(true))
2848 GEN_ERROR("Call to invalid LLVM intrinsic function '" +
2849 theF->getName() + "'");
2852 // Check the arguments
2854 if ($6->empty()) { // Has no arguments?
2855 // Make sure no arguments is a good thing!
2856 if (Ty->getNumParams() != 0)
2857 GEN_ERROR("No arguments passed to a function that "
2858 "expects arguments");
2859 } else { // Has arguments?
2860 // Loop through FunctionType's arguments and ensure they are specified
2863 FunctionType::param_iterator I = Ty->param_begin();
2864 FunctionType::param_iterator E = Ty->param_end();
2865 ValueRefList::iterator ArgI = $6->begin(), ArgE = $6->end();
2867 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2868 if (ArgI->Val->getType() != *I)
2869 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2870 (*I)->getDescription() + "'");
2871 Args.push_back(ArgI->Val);
2873 if (Ty->isVarArg()) {
2875 for (; ArgI != ArgE; ++ArgI)
2876 Args.push_back(ArgI->Val); // push the remaining varargs
2877 } else if (I != E || ArgI != ArgE)
2878 GEN_ERROR("Invalid number of parameters detected");
2880 // Create the call node
2881 CallInst *CI = new CallInst(V, &Args[0], Args.size());
2882 CI->setTailCall($1);
2883 CI->setCallingConv($2);
2894 OptVolatile : VOLATILE {
2905 MemoryInst : MALLOC Types OptCAlign {
2906 if (!UpRefs.empty())
2907 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2908 $$ = new MallocInst(*$2, 0, $3);
2912 | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
2913 if (!UpRefs.empty())
2914 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2915 Value* tmpVal = getVal($4, $5);
2917 $$ = new MallocInst(*$2, tmpVal, $6);
2920 | ALLOCA Types OptCAlign {
2921 if (!UpRefs.empty())
2922 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2923 $$ = new AllocaInst(*$2, 0, $3);
2927 | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
2928 if (!UpRefs.empty())
2929 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2930 Value* tmpVal = getVal($4, $5);
2932 $$ = new AllocaInst(*$2, tmpVal, $6);
2935 | FREE ResolvedVal {
2936 if (!isa<PointerType>($2->getType()))
2937 GEN_ERROR("Trying to free nonpointer type " +
2938 $2->getType()->getDescription() + "");
2939 $$ = new FreeInst($2);
2943 | OptVolatile LOAD Types ValueRef OptCAlign {
2944 if (!UpRefs.empty())
2945 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2946 if (!isa<PointerType>($3->get()))
2947 GEN_ERROR("Can't load from nonpointer type: " +
2948 (*$3)->getDescription());
2949 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
2950 GEN_ERROR("Can't load from pointer of non-first-class type: " +
2951 (*$3)->getDescription());
2952 Value* tmpVal = getVal(*$3, $4);
2954 $$ = new LoadInst(tmpVal, "", $1, $5);
2957 | OptVolatile STORE ResolvedVal ',' Types ValueRef OptCAlign {
2958 if (!UpRefs.empty())
2959 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
2960 const PointerType *PT = dyn_cast<PointerType>($5->get());
2962 GEN_ERROR("Can't store to a nonpointer type: " +
2963 (*$5)->getDescription());
2964 const Type *ElTy = PT->getElementType();
2965 if (ElTy != $3->getType())
2966 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
2967 "' into space of type '" + ElTy->getDescription() + "'");
2969 Value* tmpVal = getVal(*$5, $6);
2971 $$ = new StoreInst($3, tmpVal, $1, $7);
2974 | GETELEMENTPTR Types ValueRef IndexList {
2975 if (!UpRefs.empty())
2976 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2977 if (!isa<PointerType>($2->get()))
2978 GEN_ERROR("getelementptr insn requires pointer operand");
2980 if (!GetElementPtrInst::getIndexedType(*$2, &(*$4)[0], $4->size(), true))
2981 GEN_ERROR("Invalid getelementptr indices for type '" +
2982 (*$2)->getDescription()+ "'");
2983 Value* tmpVal = getVal(*$2, $3);
2985 $$ = new GetElementPtrInst(tmpVal, &(*$4)[0], $4->size());
2993 // common code from the two 'RunVMAsmParser' functions
2994 static Module* RunParser(Module * M) {
2996 llvmAsmlineno = 1; // Reset the current line number...
2997 CurModule.CurrentModule = M;
3002 // Check to make sure the parser succeeded
3005 delete ParserResult;
3009 // Emit an error if there are any unresolved types left.
3010 if (!CurModule.LateResolveTypes.empty()) {
3011 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
3012 if (DID.Type == ValID::LocalName) {
3013 GenerateError("Undefined type remains at eof: '"+DID.getName() + "'");
3015 GenerateError("Undefined type remains at eof: #" + itostr(DID.Num));
3018 delete ParserResult;
3022 // Emit an error if there are any unresolved values left.
3023 if (!CurModule.LateResolveValues.empty()) {
3024 Value *V = CurModule.LateResolveValues.back();
3025 std::map<Value*, std::pair<ValID, int> >::iterator I =
3026 CurModule.PlaceHolderInfo.find(V);
3028 if (I != CurModule.PlaceHolderInfo.end()) {
3029 ValID &DID = I->second.first;
3030 if (DID.Type == ValID::LocalName) {
3031 GenerateError("Undefined value remains at eof: "+DID.getName() + "'");
3033 GenerateError("Undefined value remains at eof: #" + itostr(DID.Num));
3036 delete ParserResult;
3041 // Check to make sure that parsing produced a result
3045 // Reset ParserResult variable while saving its value for the result.
3046 Module *Result = ParserResult;
3052 void llvm::GenerateError(const std::string &message, int LineNo) {
3053 if (LineNo == -1) LineNo = llvmAsmlineno;
3054 // TODO: column number in exception
3056 TheParseError->setError(CurFilename, message, LineNo);
3060 int yyerror(const char *ErrorMsg) {
3062 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3063 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
3064 std::string errMsg = where + "error: " + std::string(ErrorMsg);
3065 if (yychar != YYEMPTY && yychar != 0)
3066 errMsg += " while reading token: '" + std::string(llvmAsmtext, llvmAsmleng)+
3068 GenerateError(errMsg);