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/Instructions.h"
18 #include "llvm/Module.h"
19 #include "llvm/SymbolTable.h"
20 #include "llvm/Support/GetElementPtrTypeIterator.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/Support/MathExtras.h"
28 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
29 int yylex(); // declaration" of xxx warnings.
33 std::string CurFilename;
37 static Module *ParserResult;
39 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
40 // relating to upreferences in the input stream.
42 //#define DEBUG_UPREFS 1
44 #define UR_OUT(X) std::cerr << X
49 #define YYERROR_VERBOSE 1
51 static bool ObsoleteVarArgs;
52 static bool NewVarArgs;
53 static BasicBlock *CurBB;
54 static GlobalVariable *CurGV;
57 // This contains info used when building the body of a function. It is
58 // destroyed when the function is completed.
60 typedef std::vector<Value *> ValueList; // Numbered defs
62 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
63 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
65 static struct PerModuleInfo {
66 Module *CurrentModule;
67 std::map<const Type *, ValueList> Values; // Module level numbered definitions
68 std::map<const Type *,ValueList> LateResolveValues;
69 std::vector<PATypeHolder> Types;
70 std::map<ValID, PATypeHolder> LateResolveTypes;
72 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
73 /// how they were referenced and one which line of the input they came from so
74 /// that we can resolve them later and print error messages as appropriate.
75 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
77 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
78 // references to global values. Global values may be referenced before they
79 // are defined, and if so, the temporary object that they represent is held
80 // here. This is used for forward references of GlobalValues.
82 typedef std::map<std::pair<const PointerType *,
83 ValID>, GlobalValue*> GlobalRefsType;
84 GlobalRefsType GlobalRefs;
87 // If we could not resolve some functions at function compilation time
88 // (calls to functions before they are defined), resolve them now... Types
89 // are resolved when the constant pool has been completely parsed.
91 ResolveDefinitions(LateResolveValues);
93 // Check to make sure that all global value forward references have been
96 if (!GlobalRefs.empty()) {
97 std::string UndefinedReferences = "Unresolved global references exist:\n";
99 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
101 UndefinedReferences += " " + I->first.first->getDescription() + " " +
102 I->first.second.getName() + "\n";
104 ThrowException(UndefinedReferences);
107 Values.clear(); // Clear out function local definitions
113 // GetForwardRefForGlobal - Check to see if there is a forward reference
114 // for this global. If so, remove it from the GlobalRefs map and return it.
115 // If not, just return null.
116 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
117 // Check to see if there is a forward reference to this global variable...
118 // if there is, eliminate it and patch the reference to use the new def'n.
119 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
120 GlobalValue *Ret = 0;
121 if (I != GlobalRefs.end()) {
129 static struct PerFunctionInfo {
130 Function *CurrentFunction; // Pointer to current function being created
132 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
133 std::map<const Type*, ValueList> LateResolveValues;
134 bool isDeclare; // Is this function a forward declararation?
136 /// BBForwardRefs - When we see forward references to basic blocks, keep
137 /// track of them here.
138 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
139 std::vector<BasicBlock*> NumberedBlocks;
142 inline PerFunctionInfo() {
147 inline void FunctionStart(Function *M) {
152 void FunctionDone() {
153 NumberedBlocks.clear();
155 // Any forward referenced blocks left?
156 if (!BBForwardRefs.empty())
157 ThrowException("Undefined reference to label " +
158 BBForwardRefs.begin()->first->getName());
160 // Resolve all forward references now.
161 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
163 Values.clear(); // Clear out function local definitions
167 } CurFun; // Info for the current function...
169 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
172 //===----------------------------------------------------------------------===//
173 // Code to handle definitions of all the types
174 //===----------------------------------------------------------------------===//
176 static int InsertValue(Value *V,
177 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
178 if (V->hasName()) return -1; // Is this a numbered definition?
180 // Yes, insert the value into the value table...
181 ValueList &List = ValueTab[V->getType()];
183 return List.size()-1;
186 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
188 case ValID::NumberVal: // Is it a numbered definition?
189 // Module constants occupy the lowest numbered slots...
190 if ((unsigned)D.Num < CurModule.Types.size())
191 return CurModule.Types[(unsigned)D.Num];
193 case ValID::NameVal: // Is it a named definition?
194 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
195 D.destroy(); // Free old strdup'd memory...
200 ThrowException("Internal parser error: Invalid symbol type reference!");
203 // If we reached here, we referenced either a symbol that we don't know about
204 // or an id number that hasn't been read yet. We may be referencing something
205 // forward, so just create an entry to be resolved later and get to it...
207 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
210 if (inFunctionScope()) {
211 if (D.Type == ValID::NameVal)
212 ThrowException("Reference to an undefined type: '" + D.getName() + "'");
214 ThrowException("Reference to an undefined type: #" + itostr(D.Num));
217 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
218 if (I != CurModule.LateResolveTypes.end())
221 Type *Typ = OpaqueType::get();
222 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
226 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
227 SymbolTable &SymTab =
228 inFunctionScope() ? CurFun.CurrentFunction->getSymbolTable() :
229 CurModule.CurrentModule->getSymbolTable();
230 return SymTab.lookup(Ty, Name);
233 // getValNonImprovising - Look up the value specified by the provided type and
234 // the provided ValID. If the value exists and has already been defined, return
235 // it. Otherwise return null.
237 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
238 if (isa<FunctionType>(Ty))
239 ThrowException("Functions are not values and "
240 "must be referenced as pointers");
243 case ValID::NumberVal: { // Is it a numbered definition?
244 unsigned Num = (unsigned)D.Num;
246 // Module constants occupy the lowest numbered slots...
247 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
248 if (VI != CurModule.Values.end()) {
249 if (Num < VI->second.size())
250 return VI->second[Num];
251 Num -= VI->second.size();
254 // Make sure that our type is within bounds
255 VI = CurFun.Values.find(Ty);
256 if (VI == CurFun.Values.end()) return 0;
258 // Check that the number is within bounds...
259 if (VI->second.size() <= Num) return 0;
261 return VI->second[Num];
264 case ValID::NameVal: { // Is it a named definition?
265 Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
266 if (N == 0) return 0;
268 D.destroy(); // Free old strdup'd memory...
272 // Check to make sure that "Ty" is an integral type, and that our
273 // value will fit into the specified type...
274 case ValID::ConstSIntVal: // Is it a constant pool reference??
275 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64))
276 ThrowException("Signed integral constant '" +
277 itostr(D.ConstPool64) + "' is invalid for type '" +
278 Ty->getDescription() + "'!");
279 return ConstantSInt::get(Ty, D.ConstPool64);
281 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
282 if (!ConstantUInt::isValueValidForType(Ty, D.UConstPool64)) {
283 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64)) {
284 ThrowException("Integral constant '" + utostr(D.UConstPool64) +
285 "' is invalid or out of range!");
286 } else { // This is really a signed reference. Transmogrify.
287 return ConstantSInt::get(Ty, D.ConstPool64);
290 return ConstantUInt::get(Ty, D.UConstPool64);
293 case ValID::ConstFPVal: // Is it a floating point const pool reference?
294 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
295 ThrowException("FP constant invalid for type!!");
296 return ConstantFP::get(Ty, D.ConstPoolFP);
298 case ValID::ConstNullVal: // Is it a null value?
299 if (!isa<PointerType>(Ty))
300 ThrowException("Cannot create a a non pointer null!");
301 return ConstantPointerNull::get(cast<PointerType>(Ty));
303 case ValID::ConstUndefVal: // Is it an undef value?
304 return UndefValue::get(Ty);
306 case ValID::ConstZeroVal: // Is it a zero value?
307 return Constant::getNullValue(Ty);
309 case ValID::ConstantVal: // Fully resolved constant?
310 if (D.ConstantValue->getType() != Ty)
311 ThrowException("Constant expression type different from required type!");
312 return D.ConstantValue;
315 assert(0 && "Unhandled case!");
319 assert(0 && "Unhandled case!");
323 // getVal - This function is identical to getValNonImprovising, except that if a
324 // value is not already defined, it "improvises" by creating a placeholder var
325 // that looks and acts just like the requested variable. When the value is
326 // defined later, all uses of the placeholder variable are replaced with the
329 static Value *getVal(const Type *Ty, const ValID &ID) {
330 if (Ty == Type::LabelTy)
331 ThrowException("Cannot use a basic block here");
333 // See if the value has already been defined.
334 Value *V = getValNonImprovising(Ty, ID);
337 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty))
338 ThrowException("Invalid use of a composite type!");
340 // If we reached here, we referenced either a symbol that we don't know about
341 // or an id number that hasn't been read yet. We may be referencing something
342 // forward, so just create an entry to be resolved later and get to it...
344 V = new Argument(Ty);
346 // Remember where this forward reference came from. FIXME, shouldn't we try
347 // to recycle these things??
348 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
351 if (inFunctionScope())
352 InsertValue(V, CurFun.LateResolveValues);
354 InsertValue(V, CurModule.LateResolveValues);
358 /// getBBVal - This is used for two purposes:
359 /// * If isDefinition is true, a new basic block with the specified ID is being
361 /// * If isDefinition is true, this is a reference to a basic block, which may
362 /// or may not be a forward reference.
364 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
365 assert(inFunctionScope() && "Can't get basic block at global scope!");
370 default: ThrowException("Illegal label reference " + ID.getName());
371 case ValID::NumberVal: // Is it a numbered definition?
372 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
373 CurFun.NumberedBlocks.resize(ID.Num+1);
374 BB = CurFun.NumberedBlocks[ID.Num];
376 case ValID::NameVal: // Is it a named definition?
378 if (Value *N = CurFun.CurrentFunction->
379 getSymbolTable().lookup(Type::LabelTy, Name))
380 BB = cast<BasicBlock>(N);
384 // See if the block has already been defined.
386 // If this is the definition of the block, make sure the existing value was
387 // just a forward reference. If it was a forward reference, there will be
388 // an entry for it in the PlaceHolderInfo map.
389 if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
390 // The existing value was a definition, not a forward reference.
391 ThrowException("Redefinition of label " + ID.getName());
393 ID.destroy(); // Free strdup'd memory.
397 // Otherwise this block has not been seen before.
398 BB = new BasicBlock("", CurFun.CurrentFunction);
399 if (ID.Type == ValID::NameVal) {
400 BB->setName(ID.Name);
402 CurFun.NumberedBlocks[ID.Num] = BB;
405 // If this is not a definition, keep track of it so we can use it as a forward
408 // Remember where this forward reference came from.
409 CurFun.BBForwardRefs[BB] = std::make_pair(ID, llvmAsmlineno);
411 // The forward declaration could have been inserted anywhere in the
412 // function: insert it into the correct place now.
413 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
414 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
421 //===----------------------------------------------------------------------===//
422 // Code to handle forward references in instructions
423 //===----------------------------------------------------------------------===//
425 // This code handles the late binding needed with statements that reference
426 // values not defined yet... for example, a forward branch, or the PHI node for
429 // This keeps a table (CurFun.LateResolveValues) of all such forward references
430 // and back patchs after we are done.
433 // ResolveDefinitions - If we could not resolve some defs at parsing
434 // time (forward branches, phi functions for loops, etc...) resolve the
438 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
439 std::map<const Type*,ValueList> *FutureLateResolvers) {
440 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
441 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
442 E = LateResolvers.end(); LRI != E; ++LRI) {
443 ValueList &List = LRI->second;
444 while (!List.empty()) {
445 Value *V = List.back();
448 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
449 CurModule.PlaceHolderInfo.find(V);
450 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
452 ValID &DID = PHI->second.first;
454 Value *TheRealValue = getValNonImprovising(LRI->first, DID);
456 V->replaceAllUsesWith(TheRealValue);
458 CurModule.PlaceHolderInfo.erase(PHI);
459 } else if (FutureLateResolvers) {
460 // Functions have their unresolved items forwarded to the module late
462 InsertValue(V, *FutureLateResolvers);
464 if (DID.Type == ValID::NameVal)
465 ThrowException("Reference to an invalid definition: '" +DID.getName()+
466 "' of type '" + V->getType()->getDescription() + "'",
469 ThrowException("Reference to an invalid definition: #" +
470 itostr(DID.Num) + " of type '" +
471 V->getType()->getDescription() + "'",
477 LateResolvers.clear();
480 // ResolveTypeTo - A brand new type was just declared. This means that (if
481 // name is not null) things referencing Name can be resolved. Otherwise, things
482 // refering to the number can be resolved. Do this now.
484 static void ResolveTypeTo(char *Name, const Type *ToTy) {
486 if (Name) D = ValID::create(Name);
487 else D = ValID::create((int)CurModule.Types.size());
489 std::map<ValID, PATypeHolder>::iterator I =
490 CurModule.LateResolveTypes.find(D);
491 if (I != CurModule.LateResolveTypes.end()) {
492 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
493 CurModule.LateResolveTypes.erase(I);
497 // setValueName - Set the specified value to the name given. The name may be
498 // null potentially, in which case this is a noop. The string passed in is
499 // assumed to be a malloc'd string buffer, and is free'd by this function.
501 static void setValueName(Value *V, char *NameStr) {
503 std::string Name(NameStr); // Copy string
504 free(NameStr); // Free old string
506 if (V->getType() == Type::VoidTy)
507 ThrowException("Can't assign name '" + Name+"' to value with void type!");
509 assert(inFunctionScope() && "Must be in function scope!");
510 SymbolTable &ST = CurFun.CurrentFunction->getSymbolTable();
511 if (ST.lookup(V->getType(), Name))
512 ThrowException("Redefinition of value named '" + Name + "' in the '" +
513 V->getType()->getDescription() + "' type plane!");
520 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
521 /// this is a declaration, otherwise it is a definition.
522 static GlobalVariable *
523 ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
524 bool isConstantGlobal, const Type *Ty,
525 Constant *Initializer) {
526 if (isa<FunctionType>(Ty))
527 ThrowException("Cannot declare global vars of function type!");
529 const PointerType *PTy = PointerType::get(Ty);
533 Name = NameStr; // Copy string
534 free(NameStr); // Free old string
537 // See if this global value was forward referenced. If so, recycle the
541 ID = ValID::create((char*)Name.c_str());
543 ID = ValID::create((int)CurModule.Values[PTy].size());
546 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
547 // Move the global to the end of the list, from whereever it was
548 // previously inserted.
549 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
550 CurModule.CurrentModule->getGlobalList().remove(GV);
551 CurModule.CurrentModule->getGlobalList().push_back(GV);
552 GV->setInitializer(Initializer);
553 GV->setLinkage(Linkage);
554 GV->setConstant(isConstantGlobal);
555 InsertValue(GV, CurModule.Values);
559 // If this global has a name, check to see if there is already a definition
560 // of this global in the module. If so, merge as appropriate. Note that
561 // this is really just a hack around problems in the CFE. :(
563 // We are a simple redefinition of a value, check to see if it is defined
564 // the same as the old one.
565 if (GlobalVariable *EGV =
566 CurModule.CurrentModule->getGlobalVariable(Name, Ty)) {
567 // We are allowed to redefine a global variable in two circumstances:
568 // 1. If at least one of the globals is uninitialized or
569 // 2. If both initializers have the same value.
571 if (!EGV->hasInitializer() || !Initializer ||
572 EGV->getInitializer() == Initializer) {
574 // Make sure the existing global version gets the initializer! Make
575 // sure that it also gets marked const if the new version is.
576 if (Initializer && !EGV->hasInitializer())
577 EGV->setInitializer(Initializer);
578 if (isConstantGlobal)
579 EGV->setConstant(true);
580 EGV->setLinkage(Linkage);
584 ThrowException("Redefinition of global variable named '" + Name +
585 "' in the '" + Ty->getDescription() + "' type plane!");
589 // Otherwise there is no existing GV to use, create one now.
591 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
592 CurModule.CurrentModule);
593 InsertValue(GV, CurModule.Values);
597 // setTypeName - Set the specified type to the name given. The name may be
598 // null potentially, in which case this is a noop. The string passed in is
599 // assumed to be a malloc'd string buffer, and is freed by this function.
601 // This function returns true if the type has already been defined, but is
602 // allowed to be redefined in the specified context. If the name is a new name
603 // for the type plane, it is inserted and false is returned.
604 static bool setTypeName(const Type *T, char *NameStr) {
605 assert(!inFunctionScope() && "Can't give types function-local names!");
606 if (NameStr == 0) return false;
608 std::string Name(NameStr); // Copy string
609 free(NameStr); // Free old string
611 // We don't allow assigning names to void type
612 if (T == Type::VoidTy)
613 ThrowException("Can't assign name '" + Name + "' to the void type!");
615 // Set the type name, checking for conflicts as we do so.
616 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
618 if (AlreadyExists) { // Inserting a name that is already defined???
619 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
620 assert(Existing && "Conflict but no matching type?");
622 // There is only one case where this is allowed: when we are refining an
623 // opaque type. In this case, Existing will be an opaque type.
624 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
625 // We ARE replacing an opaque type!
626 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
630 // Otherwise, this is an attempt to redefine a type. That's okay if
631 // the redefinition is identical to the original. This will be so if
632 // Existing and T point to the same Type object. In this one case we
633 // allow the equivalent redefinition.
634 if (Existing == T) return true; // Yes, it's equal.
636 // Any other kind of (non-equivalent) redefinition is an error.
637 ThrowException("Redefinition of type named '" + Name + "' in the '" +
638 T->getDescription() + "' type plane!");
644 //===----------------------------------------------------------------------===//
645 // Code for handling upreferences in type names...
648 // TypeContains - Returns true if Ty directly contains E in it.
650 static bool TypeContains(const Type *Ty, const Type *E) {
651 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
652 E) != Ty->subtype_end();
657 // NestingLevel - The number of nesting levels that need to be popped before
658 // this type is resolved.
659 unsigned NestingLevel;
661 // LastContainedTy - This is the type at the current binding level for the
662 // type. Every time we reduce the nesting level, this gets updated.
663 const Type *LastContainedTy;
665 // UpRefTy - This is the actual opaque type that the upreference is
669 UpRefRecord(unsigned NL, OpaqueType *URTy)
670 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
674 // UpRefs - A list of the outstanding upreferences that need to be resolved.
675 static std::vector<UpRefRecord> UpRefs;
677 /// HandleUpRefs - Every time we finish a new layer of types, this function is
678 /// called. It loops through the UpRefs vector, which is a list of the
679 /// currently active types. For each type, if the up reference is contained in
680 /// the newly completed type, we decrement the level count. When the level
681 /// count reaches zero, the upreferenced type is the type that is passed in:
682 /// thus we can complete the cycle.
684 static PATypeHolder HandleUpRefs(const Type *ty) {
685 if (!ty->isAbstract()) return ty;
687 UR_OUT("Type '" << Ty->getDescription() <<
688 "' newly formed. Resolving upreferences.\n" <<
689 UpRefs.size() << " upreferences active!\n");
691 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
692 // to zero), we resolve them all together before we resolve them to Ty. At
693 // the end of the loop, if there is anything to resolve to Ty, it will be in
695 OpaqueType *TypeToResolve = 0;
697 for (unsigned i = 0; i != UpRefs.size(); ++i) {
698 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
699 << UpRefs[i].second->getDescription() << ") = "
700 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
701 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
702 // Decrement level of upreference
703 unsigned Level = --UpRefs[i].NestingLevel;
704 UpRefs[i].LastContainedTy = Ty;
705 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
706 if (Level == 0) { // Upreference should be resolved!
707 if (!TypeToResolve) {
708 TypeToResolve = UpRefs[i].UpRefTy;
710 UR_OUT(" * Resolving upreference for "
711 << UpRefs[i].second->getDescription() << "\n";
712 std::string OldName = UpRefs[i].UpRefTy->getDescription());
713 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
714 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
715 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
717 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
718 --i; // Do not skip the next element...
724 UR_OUT(" * Resolving upreference for "
725 << UpRefs[i].second->getDescription() << "\n";
726 std::string OldName = TypeToResolve->getDescription());
727 TypeToResolve->refineAbstractTypeTo(Ty);
734 // common code from the two 'RunVMAsmParser' functions
735 static Module * RunParser(Module * M) {
737 llvmAsmlineno = 1; // Reset the current line number...
738 ObsoleteVarArgs = false;
741 CurModule.CurrentModule = M;
742 yyparse(); // Parse the file, potentially throwing exception
744 Module *Result = ParserResult;
747 //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
750 if ((F = Result->getNamedFunction("llvm.va_start"))
751 && F->getFunctionType()->getNumParams() == 0)
752 ObsoleteVarArgs = true;
753 if((F = Result->getNamedFunction("llvm.va_copy"))
754 && F->getFunctionType()->getNumParams() == 1)
755 ObsoleteVarArgs = true;
758 if (ObsoleteVarArgs && NewVarArgs)
759 ThrowException("This file is corrupt: it uses both new and old style varargs");
761 if(ObsoleteVarArgs) {
762 if(Function* F = Result->getNamedFunction("llvm.va_start")) {
763 if (F->arg_size() != 0)
764 ThrowException("Obsolete va_start takes 0 argument!");
768 //bar = alloca typeof(foo)
772 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
773 const Type* ArgTy = F->getFunctionType()->getReturnType();
774 const Type* ArgTyPtr = PointerType::get(ArgTy);
775 Function* NF = Result->getOrInsertFunction("llvm.va_start",
776 RetTy, ArgTyPtr, (Type *)0);
778 while (!F->use_empty()) {
779 CallInst* CI = cast<CallInst>(F->use_back());
780 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
781 new CallInst(NF, bar, "", CI);
782 Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
783 CI->replaceAllUsesWith(foo);
784 CI->getParent()->getInstList().erase(CI);
786 Result->getFunctionList().erase(F);
789 if(Function* F = Result->getNamedFunction("llvm.va_end")) {
790 if(F->arg_size() != 1)
791 ThrowException("Obsolete va_end takes 1 argument!");
795 //bar = alloca 1 of typeof(foo)
797 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
798 const Type* ArgTy = F->getFunctionType()->getParamType(0);
799 const Type* ArgTyPtr = PointerType::get(ArgTy);
800 Function* NF = Result->getOrInsertFunction("llvm.va_end",
801 RetTy, ArgTyPtr, (Type *)0);
803 while (!F->use_empty()) {
804 CallInst* CI = cast<CallInst>(F->use_back());
805 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
806 new StoreInst(CI->getOperand(1), bar, CI);
807 new CallInst(NF, bar, "", CI);
808 CI->getParent()->getInstList().erase(CI);
810 Result->getFunctionList().erase(F);
813 if(Function* F = Result->getNamedFunction("llvm.va_copy")) {
814 if(F->arg_size() != 1)
815 ThrowException("Obsolete va_copy takes 1 argument!");
818 //a = alloca 1 of typeof(foo)
819 //b = alloca 1 of typeof(foo)
824 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
825 const Type* ArgTy = F->getFunctionType()->getReturnType();
826 const Type* ArgTyPtr = PointerType::get(ArgTy);
827 Function* NF = Result->getOrInsertFunction("llvm.va_copy",
828 RetTy, ArgTyPtr, ArgTyPtr,
831 while (!F->use_empty()) {
832 CallInst* CI = cast<CallInst>(F->use_back());
833 AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
834 AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
835 new StoreInst(CI->getOperand(1), b, CI);
836 new CallInst(NF, a, b, "", CI);
837 Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
838 CI->replaceAllUsesWith(foo);
839 CI->getParent()->getInstList().erase(CI);
841 Result->getFunctionList().erase(F);
849 //===----------------------------------------------------------------------===//
850 // RunVMAsmParser - Define an interface to this parser
851 //===----------------------------------------------------------------------===//
853 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
856 CurFilename = Filename;
857 return RunParser(new Module(CurFilename));
860 Module *llvm::RunVMAsmParser(const char * AsmString, Module * M) {
861 set_scan_string(AsmString);
863 CurFilename = "from_memory";
865 return RunParser(new Module (CurFilename));
874 llvm::Module *ModuleVal;
875 llvm::Function *FunctionVal;
876 std::pair<llvm::PATypeHolder*, char*> *ArgVal;
877 llvm::BasicBlock *BasicBlockVal;
878 llvm::TerminatorInst *TermInstVal;
879 llvm::Instruction *InstVal;
880 llvm::Constant *ConstVal;
882 const llvm::Type *PrimType;
883 llvm::PATypeHolder *TypeVal;
884 llvm::Value *ValueVal;
886 std::vector<std::pair<llvm::PATypeHolder*,char*> > *ArgList;
887 std::vector<llvm::Value*> *ValueList;
888 std::list<llvm::PATypeHolder> *TypeList;
889 // Represent the RHS of PHI node
890 std::list<std::pair<llvm::Value*,
891 llvm::BasicBlock*> > *PHIList;
892 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
893 std::vector<llvm::Constant*> *ConstVector;
895 llvm::GlobalValue::LinkageTypes Linkage;
903 char *StrVal; // This memory is strdup'd!
904 llvm::ValID ValIDVal; // strdup'd memory maybe!
906 llvm::Instruction::BinaryOps BinaryOpVal;
907 llvm::Instruction::TermOps TermOpVal;
908 llvm::Instruction::MemoryOps MemOpVal;
909 llvm::Instruction::OtherOps OtherOpVal;
910 llvm::Module::Endianness Endianness;
913 %type <ModuleVal> Module FunctionList
914 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
915 %type <BasicBlockVal> BasicBlock InstructionList
916 %type <TermInstVal> BBTerminatorInst
917 %type <InstVal> Inst InstVal MemoryInst
918 %type <ConstVal> ConstVal ConstExpr
919 %type <ConstVector> ConstVector
920 %type <ArgList> ArgList ArgListH
921 %type <ArgVal> ArgVal
922 %type <PHIList> PHIList
923 %type <ValueList> ValueRefList ValueRefListE // For call param lists
924 %type <ValueList> IndexList // For GEP derived indices
925 %type <TypeList> TypeListI ArgTypeListI
926 %type <JumpTable> JumpTable
927 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
928 %type <BoolVal> OptVolatile // 'volatile' or not
929 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
930 %type <Linkage> OptLinkage
931 %type <Endianness> BigOrLittle
933 // ValueRef - Unresolved reference to a definition or BB
934 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
935 %type <ValueVal> ResolvedVal // <type> <valref> pair
936 // Tokens and types for handling constant integer values
938 // ESINT64VAL - A negative number within long long range
939 %token <SInt64Val> ESINT64VAL
941 // EUINT64VAL - A positive number within uns. long long range
942 %token <UInt64Val> EUINT64VAL
943 %type <SInt64Val> EINT64VAL
945 %token <SIntVal> SINTVAL // Signed 32 bit ints...
946 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
947 %type <SIntVal> INTVAL
948 %token <FPVal> FPVAL // Float or Double constant
951 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
952 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
953 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
954 %token <PrimType> FLOAT DOUBLE TYPE LABEL
956 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
957 %type <StrVal> Name OptName OptAssign
958 %type <UIntVal> OptAlign OptCAlign
959 %type <StrVal> OptSection SectionString
961 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
962 %token DECLARE GLOBAL CONSTANT SECTION VOLATILE
963 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
964 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
965 %token DEPLIBS CALL TAIL
966 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK
967 %type <UIntVal> OptCallingConv
969 // Basic Block Terminating Operators
970 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
973 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
974 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
975 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comarators
977 // Memory Instructions
978 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
981 %type <OtherOpVal> ShiftOps
982 %token <OtherOpVal> PHI_TOK CAST SELECT SHL SHR VAARG
983 %token VAARG_old VANEXT_old //OBSOLETE
989 // Handle constant integer size restriction and conversion...
993 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
994 ThrowException("Value too large for type!");
999 EINT64VAL : ESINT64VAL; // These have same type and can't cause problems...
1000 EINT64VAL : EUINT64VAL {
1001 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
1002 ThrowException("Value too large for type!");
1006 // Operations that are notably excluded from this list include:
1007 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1009 ArithmeticOps: ADD | SUB | MUL | DIV | REM;
1010 LogicalOps : AND | OR | XOR;
1011 SetCondOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
1013 ShiftOps : SHL | SHR;
1015 // These are some types that allow classification if we only want a particular
1016 // thing... for example, only a signed, unsigned, or integral type.
1017 SIntType : LONG | INT | SHORT | SBYTE;
1018 UIntType : ULONG | UINT | USHORT | UBYTE;
1019 IntType : SIntType | UIntType;
1020 FPType : FLOAT | DOUBLE;
1022 // OptAssign - Value producing statements have an optional assignment component
1023 OptAssign : Name '=' {
1030 OptLinkage : INTERNAL { $$ = GlobalValue::InternalLinkage; } |
1031 LINKONCE { $$ = GlobalValue::LinkOnceLinkage; } |
1032 WEAK { $$ = GlobalValue::WeakLinkage; } |
1033 APPENDING { $$ = GlobalValue::AppendingLinkage; } |
1034 /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
1036 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1037 CCC_TOK { $$ = CallingConv::C; } |
1038 FASTCC_TOK { $$ = CallingConv::Fast; } |
1039 COLDCC_TOK { $$ = CallingConv::Cold; } |
1041 if ((unsigned)$2 != $2)
1042 ThrowException("Calling conv too large!");
1046 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1047 // a comma before it.
1048 OptAlign : /*empty*/ { $$ = 0; } |
1051 if ($$ != 0 && !isPowerOf2_32($$))
1052 ThrowException("Alignment must be a power of two!");
1054 OptCAlign : /*empty*/ { $$ = 0; } |
1055 ',' ALIGN EUINT64VAL {
1057 if ($$ != 0 && !isPowerOf2_32($$))
1058 ThrowException("Alignment must be a power of two!");
1062 SectionString : SECTION STRINGCONSTANT {
1063 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1064 if ($2[i] == '"' || $2[i] == '\\')
1065 ThrowException("Invalid character in section name!");
1069 OptSection : /*empty*/ { $$ = 0; } |
1070 SectionString { $$ = $1; };
1072 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1073 // is set to be the global we are processing.
1075 GlobalVarAttributes : /* empty */ {} |
1076 ',' GlobalVarAttribute GlobalVarAttributes {};
1077 GlobalVarAttribute : SectionString {
1078 CurGV->setSection($1);
1081 | ALIGN EUINT64VAL {
1082 if ($2 != 0 && !isPowerOf2_32($2))
1083 ThrowException("Alignment must be a power of two!");
1084 CurGV->setAlignment($2);
1087 //===----------------------------------------------------------------------===//
1088 // Types includes all predefined types... except void, because it can only be
1089 // used in specific contexts (function returning void for example). To have
1090 // access to it, a user must explicitly use TypesV.
1093 // TypesV includes all of 'Types', but it also includes the void type.
1094 TypesV : Types | VOID { $$ = new PATypeHolder($1); };
1095 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
1098 if (!UpRefs.empty())
1099 ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
1104 // Derived types are added later...
1106 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT ;
1107 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL;
1109 $$ = new PATypeHolder(OpaqueType::get());
1112 $$ = new PATypeHolder($1);
1114 UpRTypes : SymbolicValueRef { // Named types are also simple types...
1115 $$ = new PATypeHolder(getTypeVal($1));
1118 // Include derived types in the Types production.
1120 UpRTypes : '\\' EUINT64VAL { // Type UpReference
1121 if ($2 > (uint64_t)~0U) ThrowException("Value out of range!");
1122 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1123 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1124 $$ = new PATypeHolder(OT);
1125 UR_OUT("New Upreference!\n");
1127 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
1128 std::vector<const Type*> Params;
1129 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1130 E = $3->end(); I != E; ++I)
1131 Params.push_back(*I);
1132 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1133 if (isVarArg) Params.pop_back();
1135 $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
1136 delete $3; // Delete the argument list
1137 delete $1; // Delete the return type handle
1139 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
1140 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1143 | '<' EUINT64VAL 'x' UpRTypes '>' { // Packed array type?
1144 const llvm::Type* ElemTy = $4->get();
1145 if ((unsigned)$2 != $2)
1146 ThrowException("Unsigned result not equal to signed result");
1147 if (!ElemTy->isPrimitiveType())
1148 ThrowException("Elemental type of a PackedType must be primitive");
1149 if (!isPowerOf2_32($2))
1150 ThrowException("Vector length should be a power of 2!");
1151 $$ = new PATypeHolder(HandleUpRefs(PackedType::get(*$4, (unsigned)$2)));
1154 | '{' TypeListI '}' { // Structure type?
1155 std::vector<const Type*> Elements;
1156 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1157 E = $2->end(); I != E; ++I)
1158 Elements.push_back(*I);
1160 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1163 | '{' '}' { // Empty structure type?
1164 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1166 | UpRTypes '*' { // Pointer type?
1167 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1171 // TypeList - Used for struct declarations and as a basis for function type
1172 // declaration type lists
1174 TypeListI : UpRTypes {
1175 $$ = new std::list<PATypeHolder>();
1176 $$->push_back(*$1); delete $1;
1178 | TypeListI ',' UpRTypes {
1179 ($$=$1)->push_back(*$3); delete $3;
1182 // ArgTypeList - List of types for a function type declaration...
1183 ArgTypeListI : TypeListI
1184 | TypeListI ',' DOTDOTDOT {
1185 ($$=$1)->push_back(Type::VoidTy);
1188 ($$ = new std::list<PATypeHolder>())->push_back(Type::VoidTy);
1191 $$ = new std::list<PATypeHolder>();
1194 // ConstVal - The various declarations that go into the constant pool. This
1195 // production is used ONLY to represent constants that show up AFTER a 'const',
1196 // 'constant' or 'global' token at global scope. Constants that can be inlined
1197 // into other expressions (such as integers and constexprs) are handled by the
1198 // ResolvedVal, ValueRef and ConstValueRef productions.
1200 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1201 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1203 ThrowException("Cannot make array constant with type: '" +
1204 (*$1)->getDescription() + "'!");
1205 const Type *ETy = ATy->getElementType();
1206 int NumElements = ATy->getNumElements();
1208 // Verify that we have the correct size...
1209 if (NumElements != -1 && NumElements != (int)$3->size())
1210 ThrowException("Type mismatch: constant sized array initialized with " +
1211 utostr($3->size()) + " arguments, but has size of " +
1212 itostr(NumElements) + "!");
1214 // Verify all elements are correct type!
1215 for (unsigned i = 0; i < $3->size(); i++) {
1216 if (ETy != (*$3)[i]->getType())
1217 ThrowException("Element #" + utostr(i) + " is not of type '" +
1218 ETy->getDescription() +"' as required!\nIt is of type '"+
1219 (*$3)[i]->getType()->getDescription() + "'.");
1222 $$ = ConstantArray::get(ATy, *$3);
1223 delete $1; delete $3;
1226 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1228 ThrowException("Cannot make array constant with type: '" +
1229 (*$1)->getDescription() + "'!");
1231 int NumElements = ATy->getNumElements();
1232 if (NumElements != -1 && NumElements != 0)
1233 ThrowException("Type mismatch: constant sized array initialized with 0"
1234 " arguments, but has size of " + itostr(NumElements) +"!");
1235 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1238 | Types 'c' STRINGCONSTANT {
1239 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1241 ThrowException("Cannot make array constant with type: '" +
1242 (*$1)->getDescription() + "'!");
1244 int NumElements = ATy->getNumElements();
1245 const Type *ETy = ATy->getElementType();
1246 char *EndStr = UnEscapeLexed($3, true);
1247 if (NumElements != -1 && NumElements != (EndStr-$3))
1248 ThrowException("Can't build string constant of size " +
1249 itostr((int)(EndStr-$3)) +
1250 " when array has size " + itostr(NumElements) + "!");
1251 std::vector<Constant*> Vals;
1252 if (ETy == Type::SByteTy) {
1253 for (char *C = $3; C != EndStr; ++C)
1254 Vals.push_back(ConstantSInt::get(ETy, *C));
1255 } else if (ETy == Type::UByteTy) {
1256 for (char *C = $3; C != EndStr; ++C)
1257 Vals.push_back(ConstantUInt::get(ETy, (unsigned char)*C));
1260 ThrowException("Cannot build string arrays of non byte sized elements!");
1263 $$ = ConstantArray::get(ATy, Vals);
1266 | Types '<' ConstVector '>' { // Nonempty unsized arr
1267 const PackedType *PTy = dyn_cast<PackedType>($1->get());
1269 ThrowException("Cannot make packed constant with type: '" +
1270 (*$1)->getDescription() + "'!");
1271 const Type *ETy = PTy->getElementType();
1272 int NumElements = PTy->getNumElements();
1274 // Verify that we have the correct size...
1275 if (NumElements != -1 && NumElements != (int)$3->size())
1276 ThrowException("Type mismatch: constant sized packed initialized with " +
1277 utostr($3->size()) + " arguments, but has size of " +
1278 itostr(NumElements) + "!");
1280 // Verify all elements are correct type!
1281 for (unsigned i = 0; i < $3->size(); i++) {
1282 if (ETy != (*$3)[i]->getType())
1283 ThrowException("Element #" + utostr(i) + " is not of type '" +
1284 ETy->getDescription() +"' as required!\nIt is of type '"+
1285 (*$3)[i]->getType()->getDescription() + "'.");
1288 $$ = ConstantPacked::get(PTy, *$3);
1289 delete $1; delete $3;
1291 | Types '{' ConstVector '}' {
1292 const StructType *STy = dyn_cast<StructType>($1->get());
1294 ThrowException("Cannot make struct constant with type: '" +
1295 (*$1)->getDescription() + "'!");
1297 if ($3->size() != STy->getNumContainedTypes())
1298 ThrowException("Illegal number of initializers for structure type!");
1300 // Check to ensure that constants are compatible with the type initializer!
1301 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1302 if ((*$3)[i]->getType() != STy->getElementType(i))
1303 ThrowException("Expected type '" +
1304 STy->getElementType(i)->getDescription() +
1305 "' for element #" + utostr(i) +
1306 " of structure initializer!");
1308 $$ = ConstantStruct::get(STy, *$3);
1309 delete $1; delete $3;
1312 const StructType *STy = dyn_cast<StructType>($1->get());
1314 ThrowException("Cannot make struct constant with type: '" +
1315 (*$1)->getDescription() + "'!");
1317 if (STy->getNumContainedTypes() != 0)
1318 ThrowException("Illegal number of initializers for structure type!");
1320 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1324 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1326 ThrowException("Cannot make null pointer constant with type: '" +
1327 (*$1)->getDescription() + "'!");
1329 $$ = ConstantPointerNull::get(PTy);
1333 $$ = UndefValue::get($1->get());
1336 | Types SymbolicValueRef {
1337 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1339 ThrowException("Global const reference must be a pointer type!");
1341 // ConstExprs can exist in the body of a function, thus creating
1342 // GlobalValues whenever they refer to a variable. Because we are in
1343 // the context of a function, getValNonImprovising will search the functions
1344 // symbol table instead of the module symbol table for the global symbol,
1345 // which throws things all off. To get around this, we just tell
1346 // getValNonImprovising that we are at global scope here.
1348 Function *SavedCurFn = CurFun.CurrentFunction;
1349 CurFun.CurrentFunction = 0;
1351 Value *V = getValNonImprovising(Ty, $2);
1353 CurFun.CurrentFunction = SavedCurFn;
1355 // If this is an initializer for a constant pointer, which is referencing a
1356 // (currently) undefined variable, create a stub now that shall be replaced
1357 // in the future with the right type of variable.
1360 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1361 const PointerType *PT = cast<PointerType>(Ty);
1363 // First check to see if the forward references value is already created!
1364 PerModuleInfo::GlobalRefsType::iterator I =
1365 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1367 if (I != CurModule.GlobalRefs.end()) {
1368 V = I->second; // Placeholder already exists, use it...
1372 if ($2.Type == ValID::NameVal) Name = $2.Name;
1374 // Create the forward referenced global.
1376 if (const FunctionType *FTy =
1377 dyn_cast<FunctionType>(PT->getElementType())) {
1378 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1379 CurModule.CurrentModule);
1381 GV = new GlobalVariable(PT->getElementType(), false,
1382 GlobalValue::ExternalLinkage, 0,
1383 Name, CurModule.CurrentModule);
1386 // Keep track of the fact that we have a forward ref to recycle it
1387 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1392 $$ = cast<GlobalValue>(V);
1393 delete $1; // Free the type handle
1396 if ($1->get() != $2->getType())
1397 ThrowException("Mismatched types for constant expression!");
1401 | Types ZEROINITIALIZER {
1402 const Type *Ty = $1->get();
1403 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1404 ThrowException("Cannot create a null initialized value of this type!");
1405 $$ = Constant::getNullValue(Ty);
1409 ConstVal : SIntType EINT64VAL { // integral constants
1410 if (!ConstantSInt::isValueValidForType($1, $2))
1411 ThrowException("Constant value doesn't fit in type!");
1412 $$ = ConstantSInt::get($1, $2);
1414 | UIntType EUINT64VAL { // integral constants
1415 if (!ConstantUInt::isValueValidForType($1, $2))
1416 ThrowException("Constant value doesn't fit in type!");
1417 $$ = ConstantUInt::get($1, $2);
1419 | BOOL TRUETOK { // Boolean constants
1420 $$ = ConstantBool::True;
1422 | BOOL FALSETOK { // Boolean constants
1423 $$ = ConstantBool::False;
1425 | FPType FPVAL { // Float & Double constants
1426 if (!ConstantFP::isValueValidForType($1, $2))
1427 ThrowException("Floating point constant invalid for type!!");
1428 $$ = ConstantFP::get($1, $2);
1432 ConstExpr: CAST '(' ConstVal TO Types ')' {
1433 if (!$3->getType()->isFirstClassType())
1434 ThrowException("cast constant expression from a non-primitive type: '" +
1435 $3->getType()->getDescription() + "'!");
1436 if (!$5->get()->isFirstClassType())
1437 ThrowException("cast constant expression to a non-primitive type: '" +
1438 $5->get()->getDescription() + "'!");
1439 $$ = ConstantExpr::getCast($3, $5->get());
1442 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1443 if (!isa<PointerType>($3->getType()))
1444 ThrowException("GetElementPtr requires a pointer operand!");
1446 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
1447 // indices to uint struct indices for compatibility.
1448 generic_gep_type_iterator<std::vector<Value*>::iterator>
1449 GTI = gep_type_begin($3->getType(), $4->begin(), $4->end()),
1450 GTE = gep_type_end($3->getType(), $4->begin(), $4->end());
1451 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
1452 if (isa<StructType>(*GTI)) // Only change struct indices
1453 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
1454 if (CUI->getType() == Type::UByteTy)
1455 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
1458 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1460 ThrowException("Index list invalid for constant getelementptr!");
1462 std::vector<Constant*> IdxVec;
1463 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1464 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1465 IdxVec.push_back(C);
1467 ThrowException("Indices to constant getelementptr must be constants!");
1471 $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1473 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1474 if ($3->getType() != Type::BoolTy)
1475 ThrowException("Select condition must be of boolean type!");
1476 if ($5->getType() != $7->getType())
1477 ThrowException("Select operand types must match!");
1478 $$ = ConstantExpr::getSelect($3, $5, $7);
1480 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1481 if ($3->getType() != $5->getType())
1482 ThrowException("Binary operator types must match!");
1483 // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
1484 // To retain backward compatibility with these early compilers, we emit a
1485 // cast to the appropriate integer type automatically if we are in the
1486 // broken case. See PR424 for more information.
1487 if (!isa<PointerType>($3->getType())) {
1488 $$ = ConstantExpr::get($1, $3, $5);
1490 const Type *IntPtrTy = 0;
1491 switch (CurModule.CurrentModule->getPointerSize()) {
1492 case Module::Pointer32: IntPtrTy = Type::IntTy; break;
1493 case Module::Pointer64: IntPtrTy = Type::LongTy; break;
1494 default: ThrowException("invalid pointer binary constant expr!");
1496 $$ = ConstantExpr::get($1, ConstantExpr::getCast($3, IntPtrTy),
1497 ConstantExpr::getCast($5, IntPtrTy));
1498 $$ = ConstantExpr::getCast($$, $3->getType());
1501 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1502 if ($3->getType() != $5->getType())
1503 ThrowException("Logical operator types must match!");
1504 if (!$3->getType()->isIntegral()) {
1505 if (!isa<PackedType>($3->getType()) ||
1506 !cast<PackedType>($3->getType())->getElementType()->isIntegral())
1507 ThrowException("Logical operator requires integral operands!");
1509 $$ = ConstantExpr::get($1, $3, $5);
1511 | SetCondOps '(' ConstVal ',' ConstVal ')' {
1512 if ($3->getType() != $5->getType())
1513 ThrowException("setcc operand types must match!");
1514 $$ = ConstantExpr::get($1, $3, $5);
1516 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1517 if ($5->getType() != Type::UByteTy)
1518 ThrowException("Shift count for shift constant must be unsigned byte!");
1519 if (!$3->getType()->isInteger())
1520 ThrowException("Shift constant expression requires integer operand!");
1521 $$ = ConstantExpr::get($1, $3, $5);
1525 // ConstVector - A list of comma separated constants.
1526 ConstVector : ConstVector ',' ConstVal {
1527 ($$ = $1)->push_back($3);
1530 $$ = new std::vector<Constant*>();
1535 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1536 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1539 //===----------------------------------------------------------------------===//
1540 // Rules to match Modules
1541 //===----------------------------------------------------------------------===//
1543 // Module rule: Capture the result of parsing the whole file into a result
1546 Module : FunctionList {
1547 $$ = ParserResult = $1;
1548 CurModule.ModuleDone();
1551 // FunctionList - A list of functions, preceeded by a constant pool.
1553 FunctionList : FunctionList Function {
1555 CurFun.FunctionDone();
1557 | FunctionList FunctionProto {
1560 | FunctionList IMPLEMENTATION {
1564 $$ = CurModule.CurrentModule;
1565 // Emit an error if there are any unresolved types left.
1566 if (!CurModule.LateResolveTypes.empty()) {
1567 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
1568 if (DID.Type == ValID::NameVal)
1569 ThrowException("Reference to an undefined type: '"+DID.getName() + "'");
1571 ThrowException("Reference to an undefined type: #" + itostr(DID.Num));
1575 // ConstPool - Constants with optional names assigned to them.
1576 ConstPool : ConstPool OptAssign TYPE TypesV {
1577 // Eagerly resolve types. This is not an optimization, this is a
1578 // requirement that is due to the fact that we could have this:
1580 // %list = type { %list * }
1581 // %list = type { %list * } ; repeated type decl
1583 // If types are not resolved eagerly, then the two types will not be
1584 // determined to be the same type!
1586 ResolveTypeTo($2, *$4);
1588 if (!setTypeName(*$4, $2) && !$2) {
1589 // If this is a named type that is not a redefinition, add it to the slot
1591 CurModule.Types.push_back(*$4);
1596 | ConstPool FunctionProto { // Function prototypes can be in const pool
1598 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
1599 if ($5 == 0) ThrowException("Global value initializer is not a constant!");
1600 CurGV = ParseGlobalVariable($2, $3, $4, $5->getType(), $5);
1601 } GlobalVarAttributes {
1604 | ConstPool OptAssign EXTERNAL GlobalType Types {
1605 CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage,
1608 } GlobalVarAttributes {
1611 | ConstPool TARGET TargetDefinition {
1613 | ConstPool DEPLIBS '=' LibrariesDefinition {
1615 | /* empty: end of list */ {
1620 BigOrLittle : BIG { $$ = Module::BigEndian; };
1621 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1623 TargetDefinition : ENDIAN '=' BigOrLittle {
1624 CurModule.CurrentModule->setEndianness($3);
1626 | POINTERSIZE '=' EUINT64VAL {
1628 CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1630 CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1632 ThrowException("Invalid pointer size: '" + utostr($3) + "'!");
1634 | TRIPLE '=' STRINGCONSTANT {
1635 CurModule.CurrentModule->setTargetTriple($3);
1639 LibrariesDefinition : '[' LibList ']';
1641 LibList : LibList ',' STRINGCONSTANT {
1642 CurModule.CurrentModule->addLibrary($3);
1646 CurModule.CurrentModule->addLibrary($1);
1649 | /* empty: end of list */ {
1653 //===----------------------------------------------------------------------===//
1654 // Rules to match Function Headers
1655 //===----------------------------------------------------------------------===//
1657 Name : VAR_ID | STRINGCONSTANT;
1658 OptName : Name | /*empty*/ { $$ = 0; };
1660 ArgVal : Types OptName {
1661 if (*$1 == Type::VoidTy)
1662 ThrowException("void typed arguments are invalid!");
1663 $$ = new std::pair<PATypeHolder*, char*>($1, $2);
1666 ArgListH : ArgListH ',' ArgVal {
1672 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1677 ArgList : ArgListH {
1680 | ArgListH ',' DOTDOTDOT {
1682 $$->push_back(std::pair<PATypeHolder*,
1683 char*>(new PATypeHolder(Type::VoidTy), 0));
1686 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1687 $$->push_back(std::make_pair(new PATypeHolder(Type::VoidTy), (char*)0));
1693 FunctionHeaderH : OptCallingConv TypesV Name '(' ArgList ')'
1694 OptSection OptAlign {
1696 std::string FunctionName($3);
1697 free($3); // Free strdup'd memory!
1699 if (!(*$2)->isFirstClassType() && *$2 != Type::VoidTy)
1700 ThrowException("LLVM functions cannot return aggregate types!");
1702 std::vector<const Type*> ParamTypeList;
1703 if ($5) { // If there are arguments...
1704 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
1705 I != $5->end(); ++I)
1706 ParamTypeList.push_back(I->first->get());
1709 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1710 if (isVarArg) ParamTypeList.pop_back();
1712 const FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
1713 const PointerType *PFT = PointerType::get(FT);
1717 if (!FunctionName.empty()) {
1718 ID = ValID::create((char*)FunctionName.c_str());
1720 ID = ValID::create((int)CurModule.Values[PFT].size());
1724 // See if this function was forward referenced. If so, recycle the object.
1725 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
1726 // Move the function to the end of the list, from whereever it was
1727 // previously inserted.
1728 Fn = cast<Function>(FWRef);
1729 CurModule.CurrentModule->getFunctionList().remove(Fn);
1730 CurModule.CurrentModule->getFunctionList().push_back(Fn);
1731 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
1732 (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
1733 // If this is the case, either we need to be a forward decl, or it needs
1735 if (!CurFun.isDeclare && !Fn->isExternal())
1736 ThrowException("Redefinition of function '" + FunctionName + "'!");
1738 // Make sure to strip off any argument names so we can't get conflicts.
1739 if (Fn->isExternal())
1740 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
1744 } else { // Not already defined?
1745 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
1746 CurModule.CurrentModule);
1747 InsertValue(Fn, CurModule.Values);
1750 CurFun.FunctionStart(Fn);
1751 Fn->setCallingConv($1);
1752 Fn->setAlignment($8);
1758 // Add all of the arguments we parsed to the function...
1759 if ($5) { // Is null if empty...
1760 if (isVarArg) { // Nuke the last entry
1761 assert($5->back().first->get() == Type::VoidTy && $5->back().second == 0&&
1762 "Not a varargs marker!");
1763 delete $5->back().first;
1764 $5->pop_back(); // Delete the last entry
1766 Function::arg_iterator ArgIt = Fn->arg_begin();
1767 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
1768 I != $5->end(); ++I, ++ArgIt) {
1769 delete I->first; // Delete the typeholder...
1771 setValueName(ArgIt, I->second); // Insert arg into symtab...
1775 delete $5; // We're now done with the argument list
1779 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
1781 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
1782 $$ = CurFun.CurrentFunction;
1784 // Make sure that we keep track of the linkage type even if there was a
1785 // previous "declare".
1789 END : ENDTOK | '}'; // Allow end of '}' to end a function
1791 Function : BasicBlockList END {
1795 FunctionProto : DECLARE { CurFun.isDeclare = true; } FunctionHeaderH {
1796 $$ = CurFun.CurrentFunction;
1797 CurFun.FunctionDone();
1800 //===----------------------------------------------------------------------===//
1801 // Rules to match Basic Blocks
1802 //===----------------------------------------------------------------------===//
1804 ConstValueRef : ESINT64VAL { // A reference to a direct constant
1805 $$ = ValID::create($1);
1808 $$ = ValID::create($1);
1810 | FPVAL { // Perhaps it's an FP constant?
1811 $$ = ValID::create($1);
1814 $$ = ValID::create(ConstantBool::True);
1817 $$ = ValID::create(ConstantBool::False);
1820 $$ = ValID::createNull();
1823 $$ = ValID::createUndef();
1825 | ZEROINITIALIZER { // A vector zero constant.
1826 $$ = ValID::createZeroInit();
1828 | '<' ConstVector '>' { // Nonempty unsized packed vector
1829 const Type *ETy = (*$2)[0]->getType();
1830 int NumElements = $2->size();
1832 PackedType* pt = PackedType::get(ETy, NumElements);
1833 PATypeHolder* PTy = new PATypeHolder(
1841 // Verify all elements are correct type!
1842 for (unsigned i = 0; i < $2->size(); i++) {
1843 if (ETy != (*$2)[i]->getType())
1844 ThrowException("Element #" + utostr(i) + " is not of type '" +
1845 ETy->getDescription() +"' as required!\nIt is of type '" +
1846 (*$2)[i]->getType()->getDescription() + "'.");
1849 $$ = ValID::create(ConstantPacked::get(pt, *$2));
1850 delete PTy; delete $2;
1853 $$ = ValID::create($1);
1856 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1859 SymbolicValueRef : INTVAL { // Is it an integer reference...?
1860 $$ = ValID::create($1);
1862 | Name { // Is it a named reference...?
1863 $$ = ValID::create($1);
1866 // ValueRef - A reference to a definition... either constant or symbolic
1867 ValueRef : SymbolicValueRef | ConstValueRef;
1870 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
1871 // type immediately preceeds the value reference, and allows complex constant
1872 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1873 ResolvedVal : Types ValueRef {
1874 $$ = getVal(*$1, $2); delete $1;
1877 BasicBlockList : BasicBlockList BasicBlock {
1880 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
1885 // Basic blocks are terminated by branching instructions:
1886 // br, br/cc, switch, ret
1888 BasicBlock : InstructionList OptAssign BBTerminatorInst {
1889 setValueName($3, $2);
1892 $1->getInstList().push_back($3);
1897 InstructionList : InstructionList Inst {
1898 $1->getInstList().push_back($2);
1902 $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
1904 // Make sure to move the basic block to the correct location in the
1905 // function, instead of leaving it inserted wherever it was first
1907 Function::BasicBlockListType &BBL =
1908 CurFun.CurrentFunction->getBasicBlockList();
1909 BBL.splice(BBL.end(), BBL, $$);
1912 $$ = CurBB = getBBVal(ValID::create($1), true);
1914 // Make sure to move the basic block to the correct location in the
1915 // function, instead of leaving it inserted wherever it was first
1917 Function::BasicBlockListType &BBL =
1918 CurFun.CurrentFunction->getBasicBlockList();
1919 BBL.splice(BBL.end(), BBL, $$);
1922 BBTerminatorInst : RET ResolvedVal { // Return with a result...
1923 $$ = new ReturnInst($2);
1925 | RET VOID { // Return with no result...
1926 $$ = new ReturnInst();
1928 | BR LABEL ValueRef { // Unconditional Branch...
1929 $$ = new BranchInst(getBBVal($3));
1930 } // Conditional Branch...
1931 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
1932 $$ = new BranchInst(getBBVal($6), getBBVal($9), getVal(Type::BoolTy, $3));
1934 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1935 SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6), $8->size());
1938 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
1940 for (; I != E; ++I) {
1941 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
1942 S->addCase(CI, I->second);
1944 ThrowException("Switch case is constant, but not a simple integer!");
1948 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
1949 SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6), 0);
1952 | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
1953 TO LABEL ValueRef UNWIND LABEL ValueRef {
1954 const PointerType *PFTy;
1955 const FunctionType *Ty;
1957 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
1958 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1959 // Pull out the types of all of the arguments...
1960 std::vector<const Type*> ParamTypes;
1962 for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
1964 ParamTypes.push_back((*I)->getType());
1967 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1968 if (isVarArg) ParamTypes.pop_back();
1970 Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
1971 PFTy = PointerType::get(Ty);
1974 Value *V = getVal(PFTy, $4); // Get the function we're calling...
1976 BasicBlock *Normal = getBBVal($10);
1977 BasicBlock *Except = getBBVal($13);
1979 // Create the call node...
1980 if (!$6) { // Has no arguments?
1981 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
1982 } else { // Has arguments?
1983 // Loop through FunctionType's arguments and ensure they are specified
1986 FunctionType::param_iterator I = Ty->param_begin();
1987 FunctionType::param_iterator E = Ty->param_end();
1988 std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
1990 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1991 if ((*ArgI)->getType() != *I)
1992 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1993 (*I)->getDescription() + "'!");
1995 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1996 ThrowException("Invalid number of parameters detected!");
1998 $$ = new InvokeInst(V, Normal, Except, *$6);
2000 cast<InvokeInst>($$)->setCallingConv($2);
2006 $$ = new UnwindInst();
2009 $$ = new UnreachableInst();
2014 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2016 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
2018 ThrowException("May only switch on a constant pool value!");
2020 $$->push_back(std::make_pair(V, getBBVal($6)));
2022 | IntType ConstValueRef ',' LABEL ValueRef {
2023 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2024 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
2027 ThrowException("May only switch on a constant pool value!");
2029 $$->push_back(std::make_pair(V, getBBVal($5)));
2032 Inst : OptAssign InstVal {
2033 // Is this definition named?? if so, assign the name...
2034 setValueName($2, $1);
2039 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2040 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2041 $$->push_back(std::make_pair(getVal(*$1, $3), getBBVal($5)));
2044 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2046 $1->push_back(std::make_pair(getVal($1->front().first->getType(), $4),
2051 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
2052 $$ = new std::vector<Value*>();
2055 | ValueRefList ',' ResolvedVal {
2060 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
2061 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
2063 OptTailCall : TAIL CALL {
2072 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2073 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
2074 !isa<PackedType>((*$2).get()))
2076 "Arithmetic operator requires integer, FP, or packed operands!");
2077 if (isa<PackedType>((*$2).get()) && $1 == Instruction::Rem)
2078 ThrowException("Rem not supported on packed types!");
2079 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
2081 ThrowException("binary operator returned null!");
2084 | LogicalOps Types ValueRef ',' ValueRef {
2085 if (!(*$2)->isIntegral()) {
2086 if (!isa<PackedType>($2->get()) ||
2087 !cast<PackedType>($2->get())->getElementType()->isIntegral())
2088 ThrowException("Logical operator requires integral operands!");
2090 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
2092 ThrowException("binary operator returned null!");
2095 | SetCondOps Types ValueRef ',' ValueRef {
2096 if(isa<PackedType>((*$2).get())) {
2098 "PackedTypes currently not supported in setcc instructions!");
2100 $$ = new SetCondInst($1, getVal(*$2, $3), getVal(*$2, $5));
2102 ThrowException("binary operator returned null!");
2106 std::cerr << "WARNING: Use of eliminated 'not' instruction:"
2107 << " Replacing with 'xor'.\n";
2109 Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
2111 ThrowException("Expected integral type for not instruction!");
2113 $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
2115 ThrowException("Could not create a xor instruction!");
2117 | ShiftOps ResolvedVal ',' ResolvedVal {
2118 if ($4->getType() != Type::UByteTy)
2119 ThrowException("Shift amount must be ubyte!");
2120 if (!$2->getType()->isInteger())
2121 ThrowException("Shift constant expression requires integer operand!");
2122 $$ = new ShiftInst($1, $2, $4);
2124 | CAST ResolvedVal TO Types {
2125 if (!$4->get()->isFirstClassType())
2126 ThrowException("cast instruction to a non-primitive type: '" +
2127 $4->get()->getDescription() + "'!");
2128 $$ = new CastInst($2, *$4);
2131 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2132 if ($2->getType() != Type::BoolTy)
2133 ThrowException("select condition must be boolean!");
2134 if ($4->getType() != $6->getType())
2135 ThrowException("select value types should match!");
2136 $$ = new SelectInst($2, $4, $6);
2138 | VAARG ResolvedVal ',' Types {
2140 $$ = new VAArgInst($2, *$4);
2143 | VAARG_old ResolvedVal ',' Types {
2144 ObsoleteVarArgs = true;
2145 const Type* ArgTy = $2->getType();
2146 Function* NF = CurModule.CurrentModule->
2147 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0);
2150 //foo = alloca 1 of t
2154 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
2155 CurBB->getInstList().push_back(foo);
2156 CallInst* bar = new CallInst(NF, $2);
2157 CurBB->getInstList().push_back(bar);
2158 CurBB->getInstList().push_back(new StoreInst(bar, foo));
2159 $$ = new VAArgInst(foo, *$4);
2162 | VANEXT_old ResolvedVal ',' Types {
2163 ObsoleteVarArgs = true;
2164 const Type* ArgTy = $2->getType();
2165 Function* NF = CurModule.CurrentModule->
2166 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0);
2168 //b = vanext a, t ->
2169 //foo = alloca 1 of t
2172 //tmp = vaarg foo, t
2174 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
2175 CurBB->getInstList().push_back(foo);
2176 CallInst* bar = new CallInst(NF, $2);
2177 CurBB->getInstList().push_back(bar);
2178 CurBB->getInstList().push_back(new StoreInst(bar, foo));
2179 Instruction* tmp = new VAArgInst(foo, *$4);
2180 CurBB->getInstList().push_back(tmp);
2181 $$ = new LoadInst(foo);
2185 const Type *Ty = $2->front().first->getType();
2186 if (!Ty->isFirstClassType())
2187 ThrowException("PHI node operands must be of first class type!");
2188 $$ = new PHINode(Ty);
2189 ((PHINode*)$$)->reserveOperandSpace($2->size());
2190 while ($2->begin() != $2->end()) {
2191 if ($2->front().first->getType() != Ty)
2192 ThrowException("All elements of a PHI node must be of the same type!");
2193 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2196 delete $2; // Free the list...
2198 | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')' {
2199 const PointerType *PFTy;
2200 const FunctionType *Ty;
2202 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2203 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2204 // Pull out the types of all of the arguments...
2205 std::vector<const Type*> ParamTypes;
2207 for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
2209 ParamTypes.push_back((*I)->getType());
2212 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2213 if (isVarArg) ParamTypes.pop_back();
2215 if (!(*$3)->isFirstClassType() && *$3 != Type::VoidTy)
2216 ThrowException("LLVM functions cannot return aggregate types!");
2218 Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
2219 PFTy = PointerType::get(Ty);
2222 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2224 // Create the call node...
2225 if (!$6) { // Has no arguments?
2226 // Make sure no arguments is a good thing!
2227 if (Ty->getNumParams() != 0)
2228 ThrowException("No arguments passed to a function that "
2229 "expects arguments!");
2231 $$ = new CallInst(V, std::vector<Value*>());
2232 } else { // Has arguments?
2233 // Loop through FunctionType's arguments and ensure they are specified
2236 FunctionType::param_iterator I = Ty->param_begin();
2237 FunctionType::param_iterator E = Ty->param_end();
2238 std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
2240 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2241 if ((*ArgI)->getType() != *I)
2242 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2243 (*I)->getDescription() + "'!");
2245 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2246 ThrowException("Invalid number of parameters detected!");
2248 $$ = new CallInst(V, *$6);
2250 cast<CallInst>($$)->setTailCall($1);
2251 cast<CallInst>($$)->setCallingConv($2);
2260 // IndexList - List of indices for GEP based instructions...
2261 IndexList : ',' ValueRefList {
2264 $$ = new std::vector<Value*>();
2267 OptVolatile : VOLATILE {
2276 MemoryInst : MALLOC Types OptCAlign {
2277 $$ = new MallocInst(*$2, 0, $3);
2280 | MALLOC Types ',' UINT ValueRef OptCAlign {
2281 $$ = new MallocInst(*$2, getVal($4, $5), $6);
2284 | ALLOCA Types OptCAlign {
2285 $$ = new AllocaInst(*$2, 0, $3);
2288 | ALLOCA Types ',' UINT ValueRef OptCAlign {
2289 $$ = new AllocaInst(*$2, getVal($4, $5), $6);
2292 | FREE ResolvedVal {
2293 if (!isa<PointerType>($2->getType()))
2294 ThrowException("Trying to free nonpointer type " +
2295 $2->getType()->getDescription() + "!");
2296 $$ = new FreeInst($2);
2299 | OptVolatile LOAD Types ValueRef {
2300 if (!isa<PointerType>($3->get()))
2301 ThrowException("Can't load from nonpointer type: " +
2302 (*$3)->getDescription());
2303 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
2304 ThrowException("Can't load from pointer of non-first-class type: " +
2305 (*$3)->getDescription());
2306 $$ = new LoadInst(getVal(*$3, $4), "", $1);
2309 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2310 const PointerType *PT = dyn_cast<PointerType>($5->get());
2312 ThrowException("Can't store to a nonpointer type: " +
2313 (*$5)->getDescription());
2314 const Type *ElTy = PT->getElementType();
2315 if (ElTy != $3->getType())
2316 ThrowException("Can't store '" + $3->getType()->getDescription() +
2317 "' into space of type '" + ElTy->getDescription() + "'!");
2319 $$ = new StoreInst($3, getVal(*$5, $6), $1);
2322 | GETELEMENTPTR Types ValueRef IndexList {
2323 if (!isa<PointerType>($2->get()))
2324 ThrowException("getelementptr insn requires pointer operand!");
2326 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
2327 // indices to uint struct indices for compatibility.
2328 generic_gep_type_iterator<std::vector<Value*>::iterator>
2329 GTI = gep_type_begin($2->get(), $4->begin(), $4->end()),
2330 GTE = gep_type_end($2->get(), $4->begin(), $4->end());
2331 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
2332 if (isa<StructType>(*GTI)) // Only change struct indices
2333 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
2334 if (CUI->getType() == Type::UByteTy)
2335 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
2337 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2338 ThrowException("Invalid getelementptr indices for type '" +
2339 (*$2)->getDescription()+ "'!");
2340 $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
2341 delete $2; delete $4;
2346 int yyerror(const char *ErrorMsg) {
2348 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2349 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2350 std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2351 if (yychar == YYEMPTY || yychar == 0)
2352 errMsg += "end-of-file.";
2354 errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2355 ThrowException(errMsg);