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;
56 // This contains info used when building the body of a function. It is
57 // destroyed when the function is completed.
59 typedef std::vector<Value *> ValueList; // Numbered defs
61 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
62 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
64 static struct PerModuleInfo {
65 Module *CurrentModule;
66 std::map<const Type *, ValueList> Values; // Module level numbered definitions
67 std::map<const Type *,ValueList> LateResolveValues;
68 std::vector<PATypeHolder> Types;
69 std::map<ValID, PATypeHolder> LateResolveTypes;
71 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
72 /// how they were referenced and one which line of the input they came from so
73 /// that we can resolve them later and print error messages as appropriate.
74 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
76 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
77 // references to global values. Global values may be referenced before they
78 // are defined, and if so, the temporary object that they represent is held
79 // here. This is used for forward references of GlobalValues.
81 typedef std::map<std::pair<const PointerType *,
82 ValID>, GlobalValue*> GlobalRefsType;
83 GlobalRefsType GlobalRefs;
86 // If we could not resolve some functions at function compilation time
87 // (calls to functions before they are defined), resolve them now... Types
88 // are resolved when the constant pool has been completely parsed.
90 ResolveDefinitions(LateResolveValues);
92 // Check to make sure that all global value forward references have been
95 if (!GlobalRefs.empty()) {
96 std::string UndefinedReferences = "Unresolved global references exist:\n";
98 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
100 UndefinedReferences += " " + I->first.first->getDescription() + " " +
101 I->first.second.getName() + "\n";
103 ThrowException(UndefinedReferences);
106 Values.clear(); // Clear out function local definitions
112 // GetForwardRefForGlobal - Check to see if there is a forward reference
113 // for this global. If so, remove it from the GlobalRefs map and return it.
114 // If not, just return null.
115 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
116 // Check to see if there is a forward reference to this global variable...
117 // if there is, eliminate it and patch the reference to use the new def'n.
118 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
119 GlobalValue *Ret = 0;
120 if (I != GlobalRefs.end()) {
128 static struct PerFunctionInfo {
129 Function *CurrentFunction; // Pointer to current function being created
131 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
132 std::map<const Type*, ValueList> LateResolveValues;
133 bool isDeclare; // Is this function a forward declararation?
135 /// BBForwardRefs - When we see forward references to basic blocks, keep
136 /// track of them here.
137 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
138 std::vector<BasicBlock*> NumberedBlocks;
141 inline PerFunctionInfo() {
146 inline void FunctionStart(Function *M) {
151 void FunctionDone() {
152 NumberedBlocks.clear();
154 // Any forward referenced blocks left?
155 if (!BBForwardRefs.empty())
156 ThrowException("Undefined reference to label " +
157 BBForwardRefs.begin()->first->getName());
159 // Resolve all forward references now.
160 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
162 Values.clear(); // Clear out function local definitions
166 } CurFun; // Info for the current function...
168 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
171 //===----------------------------------------------------------------------===//
172 // Code to handle definitions of all the types
173 //===----------------------------------------------------------------------===//
175 static int InsertValue(Value *V,
176 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
177 if (V->hasName()) return -1; // Is this a numbered definition?
179 // Yes, insert the value into the value table...
180 ValueList &List = ValueTab[V->getType()];
182 return List.size()-1;
185 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
187 case ValID::NumberVal: // Is it a numbered definition?
188 // Module constants occupy the lowest numbered slots...
189 if ((unsigned)D.Num < CurModule.Types.size())
190 return CurModule.Types[(unsigned)D.Num];
192 case ValID::NameVal: // Is it a named definition?
193 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
194 D.destroy(); // Free old strdup'd memory...
199 ThrowException("Internal parser error: Invalid symbol type reference!");
202 // If we reached here, we referenced either a symbol that we don't know about
203 // or an id number that hasn't been read yet. We may be referencing something
204 // forward, so just create an entry to be resolved later and get to it...
206 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
209 if (inFunctionScope()) {
210 if (D.Type == ValID::NameVal)
211 ThrowException("Reference to an undefined type: '" + D.getName() + "'");
213 ThrowException("Reference to an undefined type: #" + itostr(D.Num));
216 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
217 if (I != CurModule.LateResolveTypes.end())
220 Type *Typ = OpaqueType::get();
221 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
225 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
226 SymbolTable &SymTab =
227 inFunctionScope() ? CurFun.CurrentFunction->getSymbolTable() :
228 CurModule.CurrentModule->getSymbolTable();
229 return SymTab.lookup(Ty, Name);
232 // getValNonImprovising - Look up the value specified by the provided type and
233 // the provided ValID. If the value exists and has already been defined, return
234 // it. Otherwise return null.
236 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
237 if (isa<FunctionType>(Ty))
238 ThrowException("Functions are not values and "
239 "must be referenced as pointers");
242 case ValID::NumberVal: { // Is it a numbered definition?
243 unsigned Num = (unsigned)D.Num;
245 // Module constants occupy the lowest numbered slots...
246 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
247 if (VI != CurModule.Values.end()) {
248 if (Num < VI->second.size())
249 return VI->second[Num];
250 Num -= VI->second.size();
253 // Make sure that our type is within bounds
254 VI = CurFun.Values.find(Ty);
255 if (VI == CurFun.Values.end()) return 0;
257 // Check that the number is within bounds...
258 if (VI->second.size() <= Num) return 0;
260 return VI->second[Num];
263 case ValID::NameVal: { // Is it a named definition?
264 Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
265 if (N == 0) return 0;
267 D.destroy(); // Free old strdup'd memory...
271 // Check to make sure that "Ty" is an integral type, and that our
272 // value will fit into the specified type...
273 case ValID::ConstSIntVal: // Is it a constant pool reference??
274 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64))
275 ThrowException("Signed integral constant '" +
276 itostr(D.ConstPool64) + "' is invalid for type '" +
277 Ty->getDescription() + "'!");
278 return ConstantSInt::get(Ty, D.ConstPool64);
280 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
281 if (!ConstantUInt::isValueValidForType(Ty, D.UConstPool64)) {
282 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64)) {
283 ThrowException("Integral constant '" + utostr(D.UConstPool64) +
284 "' is invalid or out of range!");
285 } else { // This is really a signed reference. Transmogrify.
286 return ConstantSInt::get(Ty, D.ConstPool64);
289 return ConstantUInt::get(Ty, D.UConstPool64);
292 case ValID::ConstFPVal: // Is it a floating point const pool reference?
293 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
294 ThrowException("FP constant invalid for type!!");
295 return ConstantFP::get(Ty, D.ConstPoolFP);
297 case ValID::ConstNullVal: // Is it a null value?
298 if (!isa<PointerType>(Ty))
299 ThrowException("Cannot create a a non pointer null!");
300 return ConstantPointerNull::get(cast<PointerType>(Ty));
302 case ValID::ConstUndefVal: // Is it an undef value?
303 return UndefValue::get(Ty);
305 case ValID::ConstantVal: // Fully resolved constant?
306 if (D.ConstantValue->getType() != Ty)
307 ThrowException("Constant expression type different from required type!");
308 return D.ConstantValue;
311 assert(0 && "Unhandled case!");
315 assert(0 && "Unhandled case!");
319 // getVal - This function is identical to getValNonImprovising, except that if a
320 // value is not already defined, it "improvises" by creating a placeholder var
321 // that looks and acts just like the requested variable. When the value is
322 // defined later, all uses of the placeholder variable are replaced with the
325 static Value *getVal(const Type *Ty, const ValID &ID) {
326 if (Ty == Type::LabelTy)
327 ThrowException("Cannot use a basic block here");
329 // See if the value has already been defined.
330 Value *V = getValNonImprovising(Ty, ID);
333 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty))
334 ThrowException("Invalid use of a composite type!");
336 // If we reached here, we referenced either a symbol that we don't know about
337 // or an id number that hasn't been read yet. We may be referencing something
338 // forward, so just create an entry to be resolved later and get to it...
340 V = new Argument(Ty);
342 // Remember where this forward reference came from. FIXME, shouldn't we try
343 // to recycle these things??
344 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
347 if (inFunctionScope())
348 InsertValue(V, CurFun.LateResolveValues);
350 InsertValue(V, CurModule.LateResolveValues);
354 /// getBBVal - This is used for two purposes:
355 /// * If isDefinition is true, a new basic block with the specified ID is being
357 /// * If isDefinition is true, this is a reference to a basic block, which may
358 /// or may not be a forward reference.
360 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
361 assert(inFunctionScope() && "Can't get basic block at global scope!");
366 default: ThrowException("Illegal label reference " + ID.getName());
367 case ValID::NumberVal: // Is it a numbered definition?
368 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
369 CurFun.NumberedBlocks.resize(ID.Num+1);
370 BB = CurFun.NumberedBlocks[ID.Num];
372 case ValID::NameVal: // Is it a named definition?
374 if (Value *N = CurFun.CurrentFunction->
375 getSymbolTable().lookup(Type::LabelTy, Name))
376 BB = cast<BasicBlock>(N);
380 // See if the block has already been defined.
382 // If this is the definition of the block, make sure the existing value was
383 // just a forward reference. If it was a forward reference, there will be
384 // an entry for it in the PlaceHolderInfo map.
385 if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
386 // The existing value was a definition, not a forward reference.
387 ThrowException("Redefinition of label " + ID.getName());
389 ID.destroy(); // Free strdup'd memory.
393 // Otherwise this block has not been seen before.
394 BB = new BasicBlock("", CurFun.CurrentFunction);
395 if (ID.Type == ValID::NameVal) {
396 BB->setName(ID.Name);
398 CurFun.NumberedBlocks[ID.Num] = BB;
401 // If this is not a definition, keep track of it so we can use it as a forward
404 // Remember where this forward reference came from.
405 CurFun.BBForwardRefs[BB] = std::make_pair(ID, llvmAsmlineno);
407 // The forward declaration could have been inserted anywhere in the
408 // function: insert it into the correct place now.
409 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
410 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
417 //===----------------------------------------------------------------------===//
418 // Code to handle forward references in instructions
419 //===----------------------------------------------------------------------===//
421 // This code handles the late binding needed with statements that reference
422 // values not defined yet... for example, a forward branch, or the PHI node for
425 // This keeps a table (CurFun.LateResolveValues) of all such forward references
426 // and back patchs after we are done.
429 // ResolveDefinitions - If we could not resolve some defs at parsing
430 // time (forward branches, phi functions for loops, etc...) resolve the
434 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
435 std::map<const Type*,ValueList> *FutureLateResolvers) {
436 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
437 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
438 E = LateResolvers.end(); LRI != E; ++LRI) {
439 ValueList &List = LRI->second;
440 while (!List.empty()) {
441 Value *V = List.back();
444 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
445 CurModule.PlaceHolderInfo.find(V);
446 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
448 ValID &DID = PHI->second.first;
450 Value *TheRealValue = getValNonImprovising(LRI->first, DID);
452 V->replaceAllUsesWith(TheRealValue);
454 CurModule.PlaceHolderInfo.erase(PHI);
455 } else if (FutureLateResolvers) {
456 // Functions have their unresolved items forwarded to the module late
458 InsertValue(V, *FutureLateResolvers);
460 if (DID.Type == ValID::NameVal)
461 ThrowException("Reference to an invalid definition: '" +DID.getName()+
462 "' of type '" + V->getType()->getDescription() + "'",
465 ThrowException("Reference to an invalid definition: #" +
466 itostr(DID.Num) + " of type '" +
467 V->getType()->getDescription() + "'",
473 LateResolvers.clear();
476 // ResolveTypeTo - A brand new type was just declared. This means that (if
477 // name is not null) things referencing Name can be resolved. Otherwise, things
478 // refering to the number can be resolved. Do this now.
480 static void ResolveTypeTo(char *Name, const Type *ToTy) {
482 if (Name) D = ValID::create(Name);
483 else D = ValID::create((int)CurModule.Types.size());
485 std::map<ValID, PATypeHolder>::iterator I =
486 CurModule.LateResolveTypes.find(D);
487 if (I != CurModule.LateResolveTypes.end()) {
488 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
489 CurModule.LateResolveTypes.erase(I);
493 // setValueName - Set the specified value to the name given. The name may be
494 // null potentially, in which case this is a noop. The string passed in is
495 // assumed to be a malloc'd string buffer, and is free'd by this function.
497 static void setValueName(Value *V, char *NameStr) {
499 std::string Name(NameStr); // Copy string
500 free(NameStr); // Free old string
502 if (V->getType() == Type::VoidTy)
503 ThrowException("Can't assign name '" + Name+"' to value with void type!");
505 assert(inFunctionScope() && "Must be in function scope!");
506 SymbolTable &ST = CurFun.CurrentFunction->getSymbolTable();
507 if (ST.lookup(V->getType(), Name))
508 ThrowException("Redefinition of value named '" + Name + "' in the '" +
509 V->getType()->getDescription() + "' type plane!");
516 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
517 /// this is a declaration, otherwise it is a definition.
518 static void ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
519 bool isConstantGlobal, const Type *Ty,
520 Constant *Initializer, char *Section,
522 if (Align != 0 && !isPowerOf2_32(Align))
523 ThrowException("Global alignment must be a power of two!");
525 if (isa<FunctionType>(Ty))
526 ThrowException("Cannot declare global vars of function type!");
528 const PointerType *PTy = PointerType::get(Ty);
532 Name = NameStr; // Copy string
533 free(NameStr); // Free old string
536 // See if this global value was forward referenced. If so, recycle the
540 ID = ValID::create((char*)Name.c_str());
542 ID = ValID::create((int)CurModule.Values[PTy].size());
545 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
546 // Move the global to the end of the list, from whereever it was
547 // previously inserted.
548 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
549 CurModule.CurrentModule->getGlobalList().remove(GV);
550 CurModule.CurrentModule->getGlobalList().push_back(GV);
551 GV->setInitializer(Initializer);
552 GV->setLinkage(Linkage);
553 GV->setConstant(isConstantGlobal);
554 GV->setAlignment(Align);
557 GV->setSection(Section);
559 InsertValue(GV, CurModule.Values);
563 // If this global has a name, check to see if there is already a definition
564 // of this global in the module. If so, merge as appropriate. Note that
565 // this is really just a hack around problems in the CFE. :(
567 // We are a simple redefinition of a value, check to see if it is defined
568 // the same as the old one.
569 if (GlobalVariable *EGV =
570 CurModule.CurrentModule->getGlobalVariable(Name, Ty)) {
571 // We are allowed to redefine a global variable in two circumstances:
572 // 1. If at least one of the globals is uninitialized or
573 // 2. If both initializers have the same value.
575 if (!EGV->hasInitializer() || !Initializer ||
576 EGV->getInitializer() == Initializer) {
578 // Make sure the existing global version gets the initializer! Make
579 // sure that it also gets marked const if the new version is.
580 if (Initializer && !EGV->hasInitializer())
581 EGV->setInitializer(Initializer);
582 if (isConstantGlobal)
583 EGV->setConstant(true);
584 EGV->setLinkage(Linkage);
585 EGV->setAlignment(Align);
588 EGV->setSection(Section);
593 ThrowException("Redefinition of global variable named '" + Name +
594 "' in the '" + Ty->getDescription() + "' type plane!");
598 // Otherwise there is no existing GV to use, create one now.
600 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
601 CurModule.CurrentModule);
602 GV->setAlignment(Align);
605 GV->setSection(Section);
607 InsertValue(GV, CurModule.Values);
610 // setTypeName - Set the specified type to the name given. The name may be
611 // null potentially, in which case this is a noop. The string passed in is
612 // assumed to be a malloc'd string buffer, and is freed by this function.
614 // This function returns true if the type has already been defined, but is
615 // allowed to be redefined in the specified context. If the name is a new name
616 // for the type plane, it is inserted and false is returned.
617 static bool setTypeName(const Type *T, char *NameStr) {
618 assert(!inFunctionScope() && "Can't give types function-local names!");
619 if (NameStr == 0) return false;
621 std::string Name(NameStr); // Copy string
622 free(NameStr); // Free old string
624 // We don't allow assigning names to void type
625 if (T == Type::VoidTy)
626 ThrowException("Can't assign name '" + Name + "' to the void type!");
628 // Set the type name, checking for conflicts as we do so.
629 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
631 if (AlreadyExists) { // Inserting a name that is already defined???
632 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
633 assert(Existing && "Conflict but no matching type?");
635 // There is only one case where this is allowed: when we are refining an
636 // opaque type. In this case, Existing will be an opaque type.
637 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
638 // We ARE replacing an opaque type!
639 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
643 // Otherwise, this is an attempt to redefine a type. That's okay if
644 // the redefinition is identical to the original. This will be so if
645 // Existing and T point to the same Type object. In this one case we
646 // allow the equivalent redefinition.
647 if (Existing == T) return true; // Yes, it's equal.
649 // Any other kind of (non-equivalent) redefinition is an error.
650 ThrowException("Redefinition of type named '" + Name + "' in the '" +
651 T->getDescription() + "' type plane!");
657 //===----------------------------------------------------------------------===//
658 // Code for handling upreferences in type names...
661 // TypeContains - Returns true if Ty directly contains E in it.
663 static bool TypeContains(const Type *Ty, const Type *E) {
664 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
665 E) != Ty->subtype_end();
670 // NestingLevel - The number of nesting levels that need to be popped before
671 // this type is resolved.
672 unsigned NestingLevel;
674 // LastContainedTy - This is the type at the current binding level for the
675 // type. Every time we reduce the nesting level, this gets updated.
676 const Type *LastContainedTy;
678 // UpRefTy - This is the actual opaque type that the upreference is
682 UpRefRecord(unsigned NL, OpaqueType *URTy)
683 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
687 // UpRefs - A list of the outstanding upreferences that need to be resolved.
688 static std::vector<UpRefRecord> UpRefs;
690 /// HandleUpRefs - Every time we finish a new layer of types, this function is
691 /// called. It loops through the UpRefs vector, which is a list of the
692 /// currently active types. For each type, if the up reference is contained in
693 /// the newly completed type, we decrement the level count. When the level
694 /// count reaches zero, the upreferenced type is the type that is passed in:
695 /// thus we can complete the cycle.
697 static PATypeHolder HandleUpRefs(const Type *ty) {
698 if (!ty->isAbstract()) return ty;
700 UR_OUT("Type '" << Ty->getDescription() <<
701 "' newly formed. Resolving upreferences.\n" <<
702 UpRefs.size() << " upreferences active!\n");
704 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
705 // to zero), we resolve them all together before we resolve them to Ty. At
706 // the end of the loop, if there is anything to resolve to Ty, it will be in
708 OpaqueType *TypeToResolve = 0;
710 for (unsigned i = 0; i != UpRefs.size(); ++i) {
711 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
712 << UpRefs[i].second->getDescription() << ") = "
713 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
714 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
715 // Decrement level of upreference
716 unsigned Level = --UpRefs[i].NestingLevel;
717 UpRefs[i].LastContainedTy = Ty;
718 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
719 if (Level == 0) { // Upreference should be resolved!
720 if (!TypeToResolve) {
721 TypeToResolve = UpRefs[i].UpRefTy;
723 UR_OUT(" * Resolving upreference for "
724 << UpRefs[i].second->getDescription() << "\n";
725 std::string OldName = UpRefs[i].UpRefTy->getDescription());
726 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
727 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
728 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
730 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
731 --i; // Do not skip the next element...
737 UR_OUT(" * Resolving upreference for "
738 << UpRefs[i].second->getDescription() << "\n";
739 std::string OldName = TypeToResolve->getDescription());
740 TypeToResolve->refineAbstractTypeTo(Ty);
747 // common code from the two 'RunVMAsmParser' functions
748 static Module * RunParser(Module * M) {
750 llvmAsmlineno = 1; // Reset the current line number...
751 ObsoleteVarArgs = false;
754 CurModule.CurrentModule = M;
755 yyparse(); // Parse the file, potentially throwing exception
757 Module *Result = ParserResult;
760 //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
763 if ((F = Result->getNamedFunction("llvm.va_start"))
764 && F->getFunctionType()->getNumParams() == 0)
765 ObsoleteVarArgs = true;
766 if((F = Result->getNamedFunction("llvm.va_copy"))
767 && F->getFunctionType()->getNumParams() == 1)
768 ObsoleteVarArgs = true;
771 if (ObsoleteVarArgs && NewVarArgs)
772 ThrowException("This file is corrupt: it uses both new and old style varargs");
774 if(ObsoleteVarArgs) {
775 if(Function* F = Result->getNamedFunction("llvm.va_start")) {
776 if (F->arg_size() != 0)
777 ThrowException("Obsolete va_start takes 0 argument!");
781 //bar = alloca typeof(foo)
785 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
786 const Type* ArgTy = F->getFunctionType()->getReturnType();
787 const Type* ArgTyPtr = PointerType::get(ArgTy);
788 Function* NF = Result->getOrInsertFunction("llvm.va_start",
789 RetTy, ArgTyPtr, (Type *)0);
791 while (!F->use_empty()) {
792 CallInst* CI = cast<CallInst>(F->use_back());
793 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
794 new CallInst(NF, bar, "", CI);
795 Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
796 CI->replaceAllUsesWith(foo);
797 CI->getParent()->getInstList().erase(CI);
799 Result->getFunctionList().erase(F);
802 if(Function* F = Result->getNamedFunction("llvm.va_end")) {
803 if(F->arg_size() != 1)
804 ThrowException("Obsolete va_end takes 1 argument!");
808 //bar = alloca 1 of typeof(foo)
810 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
811 const Type* ArgTy = F->getFunctionType()->getParamType(0);
812 const Type* ArgTyPtr = PointerType::get(ArgTy);
813 Function* NF = Result->getOrInsertFunction("llvm.va_end",
814 RetTy, ArgTyPtr, (Type *)0);
816 while (!F->use_empty()) {
817 CallInst* CI = cast<CallInst>(F->use_back());
818 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
819 new StoreInst(CI->getOperand(1), bar, CI);
820 new CallInst(NF, bar, "", CI);
821 CI->getParent()->getInstList().erase(CI);
823 Result->getFunctionList().erase(F);
826 if(Function* F = Result->getNamedFunction("llvm.va_copy")) {
827 if(F->arg_size() != 1)
828 ThrowException("Obsolete va_copy takes 1 argument!");
831 //a = alloca 1 of typeof(foo)
832 //b = alloca 1 of typeof(foo)
837 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
838 const Type* ArgTy = F->getFunctionType()->getReturnType();
839 const Type* ArgTyPtr = PointerType::get(ArgTy);
840 Function* NF = Result->getOrInsertFunction("llvm.va_copy",
841 RetTy, ArgTyPtr, ArgTyPtr,
844 while (!F->use_empty()) {
845 CallInst* CI = cast<CallInst>(F->use_back());
846 AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
847 AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
848 new StoreInst(CI->getOperand(1), b, CI);
849 new CallInst(NF, a, b, "", CI);
850 Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
851 CI->replaceAllUsesWith(foo);
852 CI->getParent()->getInstList().erase(CI);
854 Result->getFunctionList().erase(F);
862 //===----------------------------------------------------------------------===//
863 // RunVMAsmParser - Define an interface to this parser
864 //===----------------------------------------------------------------------===//
866 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
869 CurFilename = Filename;
870 return RunParser(new Module(CurFilename));
873 Module *llvm::RunVMAsmParser(const char * AsmString, Module * M) {
874 set_scan_string(AsmString);
876 CurFilename = "from_memory";
878 return RunParser(new Module (CurFilename));
887 llvm::Module *ModuleVal;
888 llvm::Function *FunctionVal;
889 std::pair<llvm::PATypeHolder*, char*> *ArgVal;
890 llvm::BasicBlock *BasicBlockVal;
891 llvm::TerminatorInst *TermInstVal;
892 llvm::Instruction *InstVal;
893 llvm::Constant *ConstVal;
895 const llvm::Type *PrimType;
896 llvm::PATypeHolder *TypeVal;
897 llvm::Value *ValueVal;
899 std::vector<std::pair<llvm::PATypeHolder*,char*> > *ArgList;
900 std::vector<llvm::Value*> *ValueList;
901 std::list<llvm::PATypeHolder> *TypeList;
902 // Represent the RHS of PHI node
903 std::list<std::pair<llvm::Value*,
904 llvm::BasicBlock*> > *PHIList;
905 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
906 std::vector<llvm::Constant*> *ConstVector;
908 llvm::GlobalValue::LinkageTypes Linkage;
916 char *StrVal; // This memory is strdup'd!
917 llvm::ValID ValIDVal; // strdup'd memory maybe!
919 llvm::Instruction::BinaryOps BinaryOpVal;
920 llvm::Instruction::TermOps TermOpVal;
921 llvm::Instruction::MemoryOps MemOpVal;
922 llvm::Instruction::OtherOps OtherOpVal;
923 llvm::Module::Endianness Endianness;
926 %type <ModuleVal> Module FunctionList
927 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
928 %type <BasicBlockVal> BasicBlock InstructionList
929 %type <TermInstVal> BBTerminatorInst
930 %type <InstVal> Inst InstVal MemoryInst
931 %type <ConstVal> ConstVal ConstExpr
932 %type <ConstVector> ConstVector
933 %type <ArgList> ArgList ArgListH
934 %type <ArgVal> ArgVal
935 %type <PHIList> PHIList
936 %type <ValueList> ValueRefList ValueRefListE // For call param lists
937 %type <ValueList> IndexList // For GEP derived indices
938 %type <TypeList> TypeListI ArgTypeListI
939 %type <JumpTable> JumpTable
940 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
941 %type <BoolVal> OptVolatile // 'volatile' or not
942 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
943 %type <Linkage> OptLinkage
944 %type <Endianness> BigOrLittle
946 // ValueRef - Unresolved reference to a definition or BB
947 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
948 %type <ValueVal> ResolvedVal // <type> <valref> pair
949 // Tokens and types for handling constant integer values
951 // ESINT64VAL - A negative number within long long range
952 %token <SInt64Val> ESINT64VAL
954 // EUINT64VAL - A positive number within uns. long long range
955 %token <UInt64Val> EUINT64VAL
956 %type <SInt64Val> EINT64VAL
958 %token <SIntVal> SINTVAL // Signed 32 bit ints...
959 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
960 %type <SIntVal> INTVAL
961 %token <FPVal> FPVAL // Float or Double constant
964 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
965 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
966 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
967 %token <PrimType> FLOAT DOUBLE TYPE LABEL
969 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
970 %type <StrVal> Name OptName OptAssign
971 %type <UIntVal> OptAlign OptCAlign
972 %type <StrVal> OptSection OptCSection SectionString
974 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
975 %token DECLARE GLOBAL CONSTANT SECTION VOLATILE
976 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
977 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
978 %token DEPLIBS CALL TAIL
979 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK
980 %type <UIntVal> OptCallingConv
982 // Basic Block Terminating Operators
983 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
986 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
987 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
988 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comarators
990 // Memory Instructions
991 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
994 %type <OtherOpVal> ShiftOps
995 %token <OtherOpVal> PHI_TOK CAST SELECT SHL SHR VAARG
996 %token VAARG_old VANEXT_old //OBSOLETE
1002 // Handle constant integer size restriction and conversion...
1006 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
1007 ThrowException("Value too large for type!");
1012 EINT64VAL : ESINT64VAL; // These have same type and can't cause problems...
1013 EINT64VAL : EUINT64VAL {
1014 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
1015 ThrowException("Value too large for type!");
1019 // Operations that are notably excluded from this list include:
1020 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1022 ArithmeticOps: ADD | SUB | MUL | DIV | REM;
1023 LogicalOps : AND | OR | XOR;
1024 SetCondOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
1026 ShiftOps : SHL | SHR;
1028 // These are some types that allow classification if we only want a particular
1029 // thing... for example, only a signed, unsigned, or integral type.
1030 SIntType : LONG | INT | SHORT | SBYTE;
1031 UIntType : ULONG | UINT | USHORT | UBYTE;
1032 IntType : SIntType | UIntType;
1033 FPType : FLOAT | DOUBLE;
1035 // OptAssign - Value producing statements have an optional assignment component
1036 OptAssign : Name '=' {
1043 OptLinkage : INTERNAL { $$ = GlobalValue::InternalLinkage; } |
1044 LINKONCE { $$ = GlobalValue::LinkOnceLinkage; } |
1045 WEAK { $$ = GlobalValue::WeakLinkage; } |
1046 APPENDING { $$ = GlobalValue::AppendingLinkage; } |
1047 /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
1049 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1050 CCC_TOK { $$ = CallingConv::C; } |
1051 FASTCC_TOK { $$ = CallingConv::Fast; } |
1052 COLDCC_TOK { $$ = CallingConv::Cold; } |
1054 if ((unsigned)$2 != $2)
1055 ThrowException("Calling conv too large!");
1059 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1060 // a comma before it.
1061 OptAlign : /*empty*/ { $$ = 0; } |
1062 ALIGN EUINT64VAL { $$ = $2; };
1063 OptCAlign : /*empty*/ { $$ = 0; } |
1064 ',' ALIGN EUINT64VAL { $$ = $3; };
1066 SectionString : SECTION STRINGCONSTANT {
1067 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1068 if ($2[i] == '"' || $2[i] == '\\')
1069 ThrowException("Invalid character in section name!");
1073 OptSection : /*empty*/ { $$ = 0; } |
1074 SectionString { $$ = $1; };
1075 OptCSection : /*empty*/ { $$ = 0; } |
1076 ',' SectionString { $$ = $2; };
1079 //===----------------------------------------------------------------------===//
1080 // Types includes all predefined types... except void, because it can only be
1081 // used in specific contexts (function returning void for example). To have
1082 // access to it, a user must explicitly use TypesV.
1085 // TypesV includes all of 'Types', but it also includes the void type.
1086 TypesV : Types | VOID { $$ = new PATypeHolder($1); };
1087 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
1090 if (!UpRefs.empty())
1091 ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
1096 // Derived types are added later...
1098 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT ;
1099 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL;
1101 $$ = new PATypeHolder(OpaqueType::get());
1104 $$ = new PATypeHolder($1);
1106 UpRTypes : SymbolicValueRef { // Named types are also simple types...
1107 $$ = new PATypeHolder(getTypeVal($1));
1110 // Include derived types in the Types production.
1112 UpRTypes : '\\' EUINT64VAL { // Type UpReference
1113 if ($2 > (uint64_t)~0U) ThrowException("Value out of range!");
1114 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1115 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1116 $$ = new PATypeHolder(OT);
1117 UR_OUT("New Upreference!\n");
1119 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
1120 std::vector<const Type*> Params;
1121 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1122 E = $3->end(); I != E; ++I)
1123 Params.push_back(*I);
1124 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1125 if (isVarArg) Params.pop_back();
1127 $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
1128 delete $3; // Delete the argument list
1129 delete $1; // Delete the return type handle
1131 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
1132 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1135 | '<' EUINT64VAL 'x' UpRTypes '>' { // Packed array type?
1136 const llvm::Type* ElemTy = $4->get();
1137 if ((unsigned)$2 != $2)
1138 ThrowException("Unsigned result not equal to signed result");
1139 if (!ElemTy->isPrimitiveType())
1140 ThrowException("Elemental type of a PackedType must be primitive");
1141 if (!isPowerOf2_32($2))
1142 ThrowException("Vector length should be a power of 2!");
1143 $$ = new PATypeHolder(HandleUpRefs(PackedType::get(*$4, (unsigned)$2)));
1146 | '{' TypeListI '}' { // Structure type?
1147 std::vector<const Type*> Elements;
1148 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1149 E = $2->end(); I != E; ++I)
1150 Elements.push_back(*I);
1152 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1155 | '{' '}' { // Empty structure type?
1156 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1158 | UpRTypes '*' { // Pointer type?
1159 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1163 // TypeList - Used for struct declarations and as a basis for function type
1164 // declaration type lists
1166 TypeListI : UpRTypes {
1167 $$ = new std::list<PATypeHolder>();
1168 $$->push_back(*$1); delete $1;
1170 | TypeListI ',' UpRTypes {
1171 ($$=$1)->push_back(*$3); delete $3;
1174 // ArgTypeList - List of types for a function type declaration...
1175 ArgTypeListI : TypeListI
1176 | TypeListI ',' DOTDOTDOT {
1177 ($$=$1)->push_back(Type::VoidTy);
1180 ($$ = new std::list<PATypeHolder>())->push_back(Type::VoidTy);
1183 $$ = new std::list<PATypeHolder>();
1186 // ConstVal - The various declarations that go into the constant pool. This
1187 // production is used ONLY to represent constants that show up AFTER a 'const',
1188 // 'constant' or 'global' token at global scope. Constants that can be inlined
1189 // into other expressions (such as integers and constexprs) are handled by the
1190 // ResolvedVal, ValueRef and ConstValueRef productions.
1192 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1193 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1195 ThrowException("Cannot make array constant with type: '" +
1196 (*$1)->getDescription() + "'!");
1197 const Type *ETy = ATy->getElementType();
1198 int NumElements = ATy->getNumElements();
1200 // Verify that we have the correct size...
1201 if (NumElements != -1 && NumElements != (int)$3->size())
1202 ThrowException("Type mismatch: constant sized array initialized with " +
1203 utostr($3->size()) + " arguments, but has size of " +
1204 itostr(NumElements) + "!");
1206 // Verify all elements are correct type!
1207 for (unsigned i = 0; i < $3->size(); i++) {
1208 if (ETy != (*$3)[i]->getType())
1209 ThrowException("Element #" + utostr(i) + " is not of type '" +
1210 ETy->getDescription() +"' as required!\nIt is of type '"+
1211 (*$3)[i]->getType()->getDescription() + "'.");
1214 $$ = ConstantArray::get(ATy, *$3);
1215 delete $1; delete $3;
1218 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1220 ThrowException("Cannot make array constant with type: '" +
1221 (*$1)->getDescription() + "'!");
1223 int NumElements = ATy->getNumElements();
1224 if (NumElements != -1 && NumElements != 0)
1225 ThrowException("Type mismatch: constant sized array initialized with 0"
1226 " arguments, but has size of " + itostr(NumElements) +"!");
1227 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1230 | Types 'c' STRINGCONSTANT {
1231 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1233 ThrowException("Cannot make array constant with type: '" +
1234 (*$1)->getDescription() + "'!");
1236 int NumElements = ATy->getNumElements();
1237 const Type *ETy = ATy->getElementType();
1238 char *EndStr = UnEscapeLexed($3, true);
1239 if (NumElements != -1 && NumElements != (EndStr-$3))
1240 ThrowException("Can't build string constant of size " +
1241 itostr((int)(EndStr-$3)) +
1242 " when array has size " + itostr(NumElements) + "!");
1243 std::vector<Constant*> Vals;
1244 if (ETy == Type::SByteTy) {
1245 for (char *C = $3; C != EndStr; ++C)
1246 Vals.push_back(ConstantSInt::get(ETy, *C));
1247 } else if (ETy == Type::UByteTy) {
1248 for (char *C = $3; C != EndStr; ++C)
1249 Vals.push_back(ConstantUInt::get(ETy, (unsigned char)*C));
1252 ThrowException("Cannot build string arrays of non byte sized elements!");
1255 $$ = ConstantArray::get(ATy, Vals);
1258 | Types '<' ConstVector '>' { // Nonempty unsized arr
1259 const PackedType *PTy = dyn_cast<PackedType>($1->get());
1261 ThrowException("Cannot make packed constant with type: '" +
1262 (*$1)->getDescription() + "'!");
1263 const Type *ETy = PTy->getElementType();
1264 int NumElements = PTy->getNumElements();
1266 // Verify that we have the correct size...
1267 if (NumElements != -1 && NumElements != (int)$3->size())
1268 ThrowException("Type mismatch: constant sized packed initialized with " +
1269 utostr($3->size()) + " arguments, but has size of " +
1270 itostr(NumElements) + "!");
1272 // Verify all elements are correct type!
1273 for (unsigned i = 0; i < $3->size(); i++) {
1274 if (ETy != (*$3)[i]->getType())
1275 ThrowException("Element #" + utostr(i) + " is not of type '" +
1276 ETy->getDescription() +"' as required!\nIt is of type '"+
1277 (*$3)[i]->getType()->getDescription() + "'.");
1280 $$ = ConstantPacked::get(PTy, *$3);
1281 delete $1; delete $3;
1283 | Types '{' ConstVector '}' {
1284 const StructType *STy = dyn_cast<StructType>($1->get());
1286 ThrowException("Cannot make struct constant with type: '" +
1287 (*$1)->getDescription() + "'!");
1289 if ($3->size() != STy->getNumContainedTypes())
1290 ThrowException("Illegal number of initializers for structure type!");
1292 // Check to ensure that constants are compatible with the type initializer!
1293 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1294 if ((*$3)[i]->getType() != STy->getElementType(i))
1295 ThrowException("Expected type '" +
1296 STy->getElementType(i)->getDescription() +
1297 "' for element #" + utostr(i) +
1298 " of structure initializer!");
1300 $$ = ConstantStruct::get(STy, *$3);
1301 delete $1; delete $3;
1304 const StructType *STy = dyn_cast<StructType>($1->get());
1306 ThrowException("Cannot make struct constant with type: '" +
1307 (*$1)->getDescription() + "'!");
1309 if (STy->getNumContainedTypes() != 0)
1310 ThrowException("Illegal number of initializers for structure type!");
1312 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1316 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1318 ThrowException("Cannot make null pointer constant with type: '" +
1319 (*$1)->getDescription() + "'!");
1321 $$ = ConstantPointerNull::get(PTy);
1325 $$ = UndefValue::get($1->get());
1328 | Types SymbolicValueRef {
1329 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1331 ThrowException("Global const reference must be a pointer type!");
1333 // ConstExprs can exist in the body of a function, thus creating
1334 // GlobalValues whenever they refer to a variable. Because we are in
1335 // the context of a function, getValNonImprovising will search the functions
1336 // symbol table instead of the module symbol table for the global symbol,
1337 // which throws things all off. To get around this, we just tell
1338 // getValNonImprovising that we are at global scope here.
1340 Function *SavedCurFn = CurFun.CurrentFunction;
1341 CurFun.CurrentFunction = 0;
1343 Value *V = getValNonImprovising(Ty, $2);
1345 CurFun.CurrentFunction = SavedCurFn;
1347 // If this is an initializer for a constant pointer, which is referencing a
1348 // (currently) undefined variable, create a stub now that shall be replaced
1349 // in the future with the right type of variable.
1352 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1353 const PointerType *PT = cast<PointerType>(Ty);
1355 // First check to see if the forward references value is already created!
1356 PerModuleInfo::GlobalRefsType::iterator I =
1357 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1359 if (I != CurModule.GlobalRefs.end()) {
1360 V = I->second; // Placeholder already exists, use it...
1364 if ($2.Type == ValID::NameVal) Name = $2.Name;
1366 // Create the forward referenced global.
1368 if (const FunctionType *FTy =
1369 dyn_cast<FunctionType>(PT->getElementType())) {
1370 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1371 CurModule.CurrentModule);
1373 GV = new GlobalVariable(PT->getElementType(), false,
1374 GlobalValue::ExternalLinkage, 0,
1375 Name, CurModule.CurrentModule);
1378 // Keep track of the fact that we have a forward ref to recycle it
1379 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1384 $$ = cast<GlobalValue>(V);
1385 delete $1; // Free the type handle
1388 if ($1->get() != $2->getType())
1389 ThrowException("Mismatched types for constant expression!");
1393 | Types ZEROINITIALIZER {
1394 const Type *Ty = $1->get();
1395 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1396 ThrowException("Cannot create a null initialized value of this type!");
1397 $$ = Constant::getNullValue(Ty);
1401 ConstVal : SIntType EINT64VAL { // integral constants
1402 if (!ConstantSInt::isValueValidForType($1, $2))
1403 ThrowException("Constant value doesn't fit in type!");
1404 $$ = ConstantSInt::get($1, $2);
1406 | UIntType EUINT64VAL { // integral constants
1407 if (!ConstantUInt::isValueValidForType($1, $2))
1408 ThrowException("Constant value doesn't fit in type!");
1409 $$ = ConstantUInt::get($1, $2);
1411 | BOOL TRUETOK { // Boolean constants
1412 $$ = ConstantBool::True;
1414 | BOOL FALSETOK { // Boolean constants
1415 $$ = ConstantBool::False;
1417 | FPType FPVAL { // Float & Double constants
1418 if (!ConstantFP::isValueValidForType($1, $2))
1419 ThrowException("Floating point constant invalid for type!!");
1420 $$ = ConstantFP::get($1, $2);
1424 ConstExpr: CAST '(' ConstVal TO Types ')' {
1425 if (!$3->getType()->isFirstClassType())
1426 ThrowException("cast constant expression from a non-primitive type: '" +
1427 $3->getType()->getDescription() + "'!");
1428 if (!$5->get()->isFirstClassType())
1429 ThrowException("cast constant expression to a non-primitive type: '" +
1430 $5->get()->getDescription() + "'!");
1431 $$ = ConstantExpr::getCast($3, $5->get());
1434 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1435 if (!isa<PointerType>($3->getType()))
1436 ThrowException("GetElementPtr requires a pointer operand!");
1438 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
1439 // indices to uint struct indices for compatibility.
1440 generic_gep_type_iterator<std::vector<Value*>::iterator>
1441 GTI = gep_type_begin($3->getType(), $4->begin(), $4->end()),
1442 GTE = gep_type_end($3->getType(), $4->begin(), $4->end());
1443 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
1444 if (isa<StructType>(*GTI)) // Only change struct indices
1445 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
1446 if (CUI->getType() == Type::UByteTy)
1447 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
1450 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1452 ThrowException("Index list invalid for constant getelementptr!");
1454 std::vector<Constant*> IdxVec;
1455 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1456 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1457 IdxVec.push_back(C);
1459 ThrowException("Indices to constant getelementptr must be constants!");
1463 $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1465 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1466 if ($3->getType() != Type::BoolTy)
1467 ThrowException("Select condition must be of boolean type!");
1468 if ($5->getType() != $7->getType())
1469 ThrowException("Select operand types must match!");
1470 $$ = ConstantExpr::getSelect($3, $5, $7);
1472 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1473 if ($3->getType() != $5->getType())
1474 ThrowException("Binary operator types must match!");
1475 // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
1476 // To retain backward compatibility with these early compilers, we emit a
1477 // cast to the appropriate integer type automatically if we are in the
1478 // broken case. See PR424 for more information.
1479 if (!isa<PointerType>($3->getType())) {
1480 $$ = ConstantExpr::get($1, $3, $5);
1482 const Type *IntPtrTy = 0;
1483 switch (CurModule.CurrentModule->getPointerSize()) {
1484 case Module::Pointer32: IntPtrTy = Type::IntTy; break;
1485 case Module::Pointer64: IntPtrTy = Type::LongTy; break;
1486 default: ThrowException("invalid pointer binary constant expr!");
1488 $$ = ConstantExpr::get($1, ConstantExpr::getCast($3, IntPtrTy),
1489 ConstantExpr::getCast($5, IntPtrTy));
1490 $$ = ConstantExpr::getCast($$, $3->getType());
1493 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1494 if ($3->getType() != $5->getType())
1495 ThrowException("Logical operator types must match!");
1496 if (!$3->getType()->isIntegral())
1497 ThrowException("Logical operands must have integral types!");
1498 $$ = ConstantExpr::get($1, $3, $5);
1500 | SetCondOps '(' ConstVal ',' ConstVal ')' {
1501 if ($3->getType() != $5->getType())
1502 ThrowException("setcc operand types must match!");
1503 $$ = ConstantExpr::get($1, $3, $5);
1505 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1506 if ($5->getType() != Type::UByteTy)
1507 ThrowException("Shift count for shift constant must be unsigned byte!");
1508 if (!$3->getType()->isInteger())
1509 ThrowException("Shift constant expression requires integer operand!");
1510 $$ = ConstantExpr::get($1, $3, $5);
1514 // ConstVector - A list of comma separated constants.
1515 ConstVector : ConstVector ',' ConstVal {
1516 ($$ = $1)->push_back($3);
1519 $$ = new std::vector<Constant*>();
1524 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1525 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1528 //===----------------------------------------------------------------------===//
1529 // Rules to match Modules
1530 //===----------------------------------------------------------------------===//
1532 // Module rule: Capture the result of parsing the whole file into a result
1535 Module : FunctionList {
1536 $$ = ParserResult = $1;
1537 CurModule.ModuleDone();
1540 // FunctionList - A list of functions, preceeded by a constant pool.
1542 FunctionList : FunctionList Function {
1544 CurFun.FunctionDone();
1546 | FunctionList FunctionProto {
1549 | FunctionList IMPLEMENTATION {
1553 $$ = CurModule.CurrentModule;
1554 // Emit an error if there are any unresolved types left.
1555 if (!CurModule.LateResolveTypes.empty()) {
1556 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
1557 if (DID.Type == ValID::NameVal)
1558 ThrowException("Reference to an undefined type: '"+DID.getName() + "'");
1560 ThrowException("Reference to an undefined type: #" + itostr(DID.Num));
1564 // ConstPool - Constants with optional names assigned to them.
1565 ConstPool : ConstPool OptAssign TYPE TypesV {
1566 // Eagerly resolve types. This is not an optimization, this is a
1567 // requirement that is due to the fact that we could have this:
1569 // %list = type { %list * }
1570 // %list = type { %list * } ; repeated type decl
1572 // If types are not resolved eagerly, then the two types will not be
1573 // determined to be the same type!
1575 ResolveTypeTo($2, *$4);
1577 if (!setTypeName(*$4, $2) && !$2) {
1578 // If this is a named type that is not a redefinition, add it to the slot
1580 CurModule.Types.push_back(*$4);
1585 | ConstPool FunctionProto { // Function prototypes can be in const pool
1587 | ConstPool OptAssign OptLinkage GlobalType ConstVal OptCSection OptCAlign {
1588 if ($5 == 0) ThrowException("Global value initializer is not a constant!");
1589 ParseGlobalVariable($2, $3, $4, $5->getType(), $5, $6, $7);
1591 | ConstPool OptAssign EXTERNAL GlobalType Types OptCSection OptCAlign {
1592 ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, *$5, 0, $6, $7);
1595 | ConstPool TARGET TargetDefinition {
1597 | ConstPool DEPLIBS '=' LibrariesDefinition {
1599 | /* empty: end of list */ {
1604 BigOrLittle : BIG { $$ = Module::BigEndian; };
1605 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1607 TargetDefinition : ENDIAN '=' BigOrLittle {
1608 CurModule.CurrentModule->setEndianness($3);
1610 | POINTERSIZE '=' EUINT64VAL {
1612 CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1614 CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1616 ThrowException("Invalid pointer size: '" + utostr($3) + "'!");
1618 | TRIPLE '=' STRINGCONSTANT {
1619 CurModule.CurrentModule->setTargetTriple($3);
1623 LibrariesDefinition : '[' LibList ']';
1625 LibList : LibList ',' STRINGCONSTANT {
1626 CurModule.CurrentModule->addLibrary($3);
1630 CurModule.CurrentModule->addLibrary($1);
1633 | /* empty: end of list */ {
1637 //===----------------------------------------------------------------------===//
1638 // Rules to match Function Headers
1639 //===----------------------------------------------------------------------===//
1641 Name : VAR_ID | STRINGCONSTANT;
1642 OptName : Name | /*empty*/ { $$ = 0; };
1644 ArgVal : Types OptName {
1645 if (*$1 == Type::VoidTy)
1646 ThrowException("void typed arguments are invalid!");
1647 $$ = new std::pair<PATypeHolder*, char*>($1, $2);
1650 ArgListH : ArgListH ',' ArgVal {
1656 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1661 ArgList : ArgListH {
1664 | ArgListH ',' DOTDOTDOT {
1666 $$->push_back(std::pair<PATypeHolder*,
1667 char*>(new PATypeHolder(Type::VoidTy), 0));
1670 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1671 $$->push_back(std::make_pair(new PATypeHolder(Type::VoidTy), (char*)0));
1677 FunctionHeaderH : OptCallingConv TypesV Name '(' ArgList ')'
1678 OptSection OptAlign {
1680 std::string FunctionName($3);
1681 free($3); // Free strdup'd memory!
1683 if (!(*$2)->isFirstClassType() && *$2 != Type::VoidTy)
1684 ThrowException("LLVM functions cannot return aggregate types!");
1685 if ($8 != 0 && !isPowerOf2_32($8))
1686 ThrowException("Function alignment must be a power of two!");
1688 std::vector<const Type*> ParamTypeList;
1689 if ($5) { // If there are arguments...
1690 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
1691 I != $5->end(); ++I)
1692 ParamTypeList.push_back(I->first->get());
1695 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1696 if (isVarArg) ParamTypeList.pop_back();
1698 const FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
1699 const PointerType *PFT = PointerType::get(FT);
1703 if (!FunctionName.empty()) {
1704 ID = ValID::create((char*)FunctionName.c_str());
1706 ID = ValID::create((int)CurModule.Values[PFT].size());
1710 // See if this function was forward referenced. If so, recycle the object.
1711 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
1712 // Move the function to the end of the list, from whereever it was
1713 // previously inserted.
1714 Fn = cast<Function>(FWRef);
1715 CurModule.CurrentModule->getFunctionList().remove(Fn);
1716 CurModule.CurrentModule->getFunctionList().push_back(Fn);
1717 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
1718 (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
1719 // If this is the case, either we need to be a forward decl, or it needs
1721 if (!CurFun.isDeclare && !Fn->isExternal())
1722 ThrowException("Redefinition of function '" + FunctionName + "'!");
1724 // Make sure to strip off any argument names so we can't get conflicts.
1725 if (Fn->isExternal())
1726 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
1730 } else { // Not already defined?
1731 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
1732 CurModule.CurrentModule);
1733 InsertValue(Fn, CurModule.Values);
1736 CurFun.FunctionStart(Fn);
1737 Fn->setCallingConv($1);
1738 Fn->setAlignment($8);
1744 // Add all of the arguments we parsed to the function...
1745 if ($5) { // Is null if empty...
1746 if (isVarArg) { // Nuke the last entry
1747 assert($5->back().first->get() == Type::VoidTy && $5->back().second == 0&&
1748 "Not a varargs marker!");
1749 delete $5->back().first;
1750 $5->pop_back(); // Delete the last entry
1752 Function::arg_iterator ArgIt = Fn->arg_begin();
1753 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
1754 I != $5->end(); ++I, ++ArgIt) {
1755 delete I->first; // Delete the typeholder...
1757 setValueName(ArgIt, I->second); // Insert arg into symtab...
1761 delete $5; // We're now done with the argument list
1765 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
1767 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
1768 $$ = CurFun.CurrentFunction;
1770 // Make sure that we keep track of the linkage type even if there was a
1771 // previous "declare".
1775 END : ENDTOK | '}'; // Allow end of '}' to end a function
1777 Function : BasicBlockList END {
1781 FunctionProto : DECLARE { CurFun.isDeclare = true; } FunctionHeaderH {
1782 $$ = CurFun.CurrentFunction;
1783 CurFun.FunctionDone();
1786 //===----------------------------------------------------------------------===//
1787 // Rules to match Basic Blocks
1788 //===----------------------------------------------------------------------===//
1790 ConstValueRef : ESINT64VAL { // A reference to a direct constant
1791 $$ = ValID::create($1);
1794 $$ = ValID::create($1);
1796 | FPVAL { // Perhaps it's an FP constant?
1797 $$ = ValID::create($1);
1800 $$ = ValID::create(ConstantBool::True);
1803 $$ = ValID::create(ConstantBool::False);
1806 $$ = ValID::createNull();
1809 $$ = ValID::createUndef();
1811 | '<' ConstVector '>' { // Nonempty unsized packed vector
1812 const Type *ETy = (*$2)[0]->getType();
1813 int NumElements = $2->size();
1815 PackedType* pt = PackedType::get(ETy, NumElements);
1816 PATypeHolder* PTy = new PATypeHolder(
1824 // Verify all elements are correct type!
1825 for (unsigned i = 0; i < $2->size(); i++) {
1826 if (ETy != (*$2)[i]->getType())
1827 ThrowException("Element #" + utostr(i) + " is not of type '" +
1828 ETy->getDescription() +"' as required!\nIt is of type '" +
1829 (*$2)[i]->getType()->getDescription() + "'.");
1832 $$ = ValID::create(ConstantPacked::get(pt, *$2));
1833 delete PTy; delete $2;
1836 $$ = ValID::create($1);
1839 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1842 SymbolicValueRef : INTVAL { // Is it an integer reference...?
1843 $$ = ValID::create($1);
1845 | Name { // Is it a named reference...?
1846 $$ = ValID::create($1);
1849 // ValueRef - A reference to a definition... either constant or symbolic
1850 ValueRef : SymbolicValueRef | ConstValueRef;
1853 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
1854 // type immediately preceeds the value reference, and allows complex constant
1855 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1856 ResolvedVal : Types ValueRef {
1857 $$ = getVal(*$1, $2); delete $1;
1860 BasicBlockList : BasicBlockList BasicBlock {
1863 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
1868 // Basic blocks are terminated by branching instructions:
1869 // br, br/cc, switch, ret
1871 BasicBlock : InstructionList OptAssign BBTerminatorInst {
1872 setValueName($3, $2);
1875 $1->getInstList().push_back($3);
1880 InstructionList : InstructionList Inst {
1881 $1->getInstList().push_back($2);
1885 $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
1887 // Make sure to move the basic block to the correct location in the
1888 // function, instead of leaving it inserted wherever it was first
1890 Function::BasicBlockListType &BBL =
1891 CurFun.CurrentFunction->getBasicBlockList();
1892 BBL.splice(BBL.end(), BBL, $$);
1895 $$ = CurBB = getBBVal(ValID::create($1), true);
1897 // Make sure to move the basic block to the correct location in the
1898 // function, instead of leaving it inserted wherever it was first
1900 Function::BasicBlockListType &BBL =
1901 CurFun.CurrentFunction->getBasicBlockList();
1902 BBL.splice(BBL.end(), BBL, $$);
1905 BBTerminatorInst : RET ResolvedVal { // Return with a result...
1906 $$ = new ReturnInst($2);
1908 | RET VOID { // Return with no result...
1909 $$ = new ReturnInst();
1911 | BR LABEL ValueRef { // Unconditional Branch...
1912 $$ = new BranchInst(getBBVal($3));
1913 } // Conditional Branch...
1914 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
1915 $$ = new BranchInst(getBBVal($6), getBBVal($9), getVal(Type::BoolTy, $3));
1917 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1918 SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6), $8->size());
1921 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
1923 for (; I != E; ++I) {
1924 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
1925 S->addCase(CI, I->second);
1927 ThrowException("Switch case is constant, but not a simple integer!");
1931 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
1932 SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6), 0);
1935 | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
1936 TO LABEL ValueRef UNWIND LABEL ValueRef {
1937 const PointerType *PFTy;
1938 const FunctionType *Ty;
1940 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
1941 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1942 // Pull out the types of all of the arguments...
1943 std::vector<const Type*> ParamTypes;
1945 for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
1947 ParamTypes.push_back((*I)->getType());
1950 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1951 if (isVarArg) ParamTypes.pop_back();
1953 Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
1954 PFTy = PointerType::get(Ty);
1957 Value *V = getVal(PFTy, $4); // Get the function we're calling...
1959 BasicBlock *Normal = getBBVal($10);
1960 BasicBlock *Except = getBBVal($13);
1962 // Create the call node...
1963 if (!$6) { // Has no arguments?
1964 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
1965 } else { // Has arguments?
1966 // Loop through FunctionType's arguments and ensure they are specified
1969 FunctionType::param_iterator I = Ty->param_begin();
1970 FunctionType::param_iterator E = Ty->param_end();
1971 std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
1973 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1974 if ((*ArgI)->getType() != *I)
1975 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1976 (*I)->getDescription() + "'!");
1978 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1979 ThrowException("Invalid number of parameters detected!");
1981 $$ = new InvokeInst(V, Normal, Except, *$6);
1983 cast<InvokeInst>($$)->setCallingConv($2);
1989 $$ = new UnwindInst();
1992 $$ = new UnreachableInst();
1997 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1999 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
2001 ThrowException("May only switch on a constant pool value!");
2003 $$->push_back(std::make_pair(V, getBBVal($6)));
2005 | IntType ConstValueRef ',' LABEL ValueRef {
2006 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2007 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
2010 ThrowException("May only switch on a constant pool value!");
2012 $$->push_back(std::make_pair(V, getBBVal($5)));
2015 Inst : OptAssign InstVal {
2016 // Is this definition named?? if so, assign the name...
2017 setValueName($2, $1);
2022 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2023 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2024 $$->push_back(std::make_pair(getVal(*$1, $3), getBBVal($5)));
2027 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2029 $1->push_back(std::make_pair(getVal($1->front().first->getType(), $4),
2034 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
2035 $$ = new std::vector<Value*>();
2038 | ValueRefList ',' ResolvedVal {
2043 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
2044 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
2046 OptTailCall : TAIL CALL {
2055 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2056 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
2057 !isa<PackedType>((*$2).get()))
2059 "Arithmetic operator requires integer, FP, or packed operands!");
2060 if (isa<PackedType>((*$2).get()) && $1 == Instruction::Rem)
2061 ThrowException("Rem not supported on packed types!");
2062 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
2064 ThrowException("binary operator returned null!");
2067 | LogicalOps Types ValueRef ',' ValueRef {
2068 if (!(*$2)->isIntegral())
2069 ThrowException("Logical operator requires integral operands!");
2070 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
2072 ThrowException("binary operator returned null!");
2075 | SetCondOps Types ValueRef ',' ValueRef {
2076 if(isa<PackedType>((*$2).get())) {
2078 "PackedTypes currently not supported in setcc instructions!");
2080 $$ = new SetCondInst($1, getVal(*$2, $3), getVal(*$2, $5));
2082 ThrowException("binary operator returned null!");
2086 std::cerr << "WARNING: Use of eliminated 'not' instruction:"
2087 << " Replacing with 'xor'.\n";
2089 Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
2091 ThrowException("Expected integral type for not instruction!");
2093 $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
2095 ThrowException("Could not create a xor instruction!");
2097 | ShiftOps ResolvedVal ',' ResolvedVal {
2098 if ($4->getType() != Type::UByteTy)
2099 ThrowException("Shift amount must be ubyte!");
2100 if (!$2->getType()->isInteger())
2101 ThrowException("Shift constant expression requires integer operand!");
2102 $$ = new ShiftInst($1, $2, $4);
2104 | CAST ResolvedVal TO Types {
2105 if (!$4->get()->isFirstClassType())
2106 ThrowException("cast instruction to a non-primitive type: '" +
2107 $4->get()->getDescription() + "'!");
2108 $$ = new CastInst($2, *$4);
2111 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2112 if ($2->getType() != Type::BoolTy)
2113 ThrowException("select condition must be boolean!");
2114 if ($4->getType() != $6->getType())
2115 ThrowException("select value types should match!");
2116 $$ = new SelectInst($2, $4, $6);
2118 | VAARG ResolvedVal ',' Types {
2120 $$ = new VAArgInst($2, *$4);
2123 | VAARG_old ResolvedVal ',' Types {
2124 ObsoleteVarArgs = true;
2125 const Type* ArgTy = $2->getType();
2126 Function* NF = CurModule.CurrentModule->
2127 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0);
2130 //foo = alloca 1 of t
2134 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
2135 CurBB->getInstList().push_back(foo);
2136 CallInst* bar = new CallInst(NF, $2);
2137 CurBB->getInstList().push_back(bar);
2138 CurBB->getInstList().push_back(new StoreInst(bar, foo));
2139 $$ = new VAArgInst(foo, *$4);
2142 | VANEXT_old ResolvedVal ',' Types {
2143 ObsoleteVarArgs = true;
2144 const Type* ArgTy = $2->getType();
2145 Function* NF = CurModule.CurrentModule->
2146 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0);
2148 //b = vanext a, t ->
2149 //foo = alloca 1 of t
2152 //tmp = vaarg foo, t
2154 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.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 Instruction* tmp = new VAArgInst(foo, *$4);
2160 CurBB->getInstList().push_back(tmp);
2161 $$ = new LoadInst(foo);
2165 const Type *Ty = $2->front().first->getType();
2166 if (!Ty->isFirstClassType())
2167 ThrowException("PHI node operands must be of first class type!");
2168 $$ = new PHINode(Ty);
2169 ((PHINode*)$$)->reserveOperandSpace($2->size());
2170 while ($2->begin() != $2->end()) {
2171 if ($2->front().first->getType() != Ty)
2172 ThrowException("All elements of a PHI node must be of the same type!");
2173 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2176 delete $2; // Free the list...
2178 | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')' {
2179 const PointerType *PFTy;
2180 const FunctionType *Ty;
2182 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2183 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2184 // Pull out the types of all of the arguments...
2185 std::vector<const Type*> ParamTypes;
2187 for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
2189 ParamTypes.push_back((*I)->getType());
2192 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2193 if (isVarArg) ParamTypes.pop_back();
2195 if (!(*$3)->isFirstClassType() && *$3 != Type::VoidTy)
2196 ThrowException("LLVM functions cannot return aggregate types!");
2198 Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
2199 PFTy = PointerType::get(Ty);
2202 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2204 // Create the call node...
2205 if (!$6) { // Has no arguments?
2206 // Make sure no arguments is a good thing!
2207 if (Ty->getNumParams() != 0)
2208 ThrowException("No arguments passed to a function that "
2209 "expects arguments!");
2211 $$ = new CallInst(V, std::vector<Value*>());
2212 } else { // Has arguments?
2213 // Loop through FunctionType's arguments and ensure they are specified
2216 FunctionType::param_iterator I = Ty->param_begin();
2217 FunctionType::param_iterator E = Ty->param_end();
2218 std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
2220 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2221 if ((*ArgI)->getType() != *I)
2222 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2223 (*I)->getDescription() + "'!");
2225 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2226 ThrowException("Invalid number of parameters detected!");
2228 $$ = new CallInst(V, *$6);
2230 cast<CallInst>($$)->setTailCall($1);
2231 cast<CallInst>($$)->setCallingConv($2);
2240 // IndexList - List of indices for GEP based instructions...
2241 IndexList : ',' ValueRefList {
2244 $$ = new std::vector<Value*>();
2247 OptVolatile : VOLATILE {
2256 MemoryInst : MALLOC Types OptCAlign {
2257 if ($3 != 0 && !isPowerOf2_32($3))
2258 ThrowException("Alignment amount '" + utostr($3) +
2259 "' is not a power of 2!");
2260 $$ = new MallocInst(*$2, 0, $3);
2263 | MALLOC Types ',' UINT ValueRef OptCAlign {
2264 if ($6 != 0 && !isPowerOf2_32($6))
2265 ThrowException("Alignment amount '" + utostr($6) +
2266 "' is not a power of 2!");
2267 $$ = new MallocInst(*$2, getVal($4, $5), $6);
2270 | ALLOCA Types OptCAlign {
2271 if ($3 != 0 && !isPowerOf2_32($3))
2272 ThrowException("Alignment amount '" + utostr($3) +
2273 "' is not a power of 2!");
2274 $$ = new AllocaInst(*$2, 0, $3);
2277 | ALLOCA Types ',' UINT ValueRef OptCAlign {
2278 if ($6 != 0 && !isPowerOf2_32($6))
2279 ThrowException("Alignment amount '" + utostr($6) +
2280 "' is not a power of 2!");
2281 $$ = new AllocaInst(*$2, getVal($4, $5), $6);
2284 | FREE ResolvedVal {
2285 if (!isa<PointerType>($2->getType()))
2286 ThrowException("Trying to free nonpointer type " +
2287 $2->getType()->getDescription() + "!");
2288 $$ = new FreeInst($2);
2291 | OptVolatile LOAD Types ValueRef {
2292 if (!isa<PointerType>($3->get()))
2293 ThrowException("Can't load from nonpointer type: " +
2294 (*$3)->getDescription());
2295 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
2296 ThrowException("Can't load from pointer of non-first-class type: " +
2297 (*$3)->getDescription());
2298 $$ = new LoadInst(getVal(*$3, $4), "", $1);
2301 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2302 const PointerType *PT = dyn_cast<PointerType>($5->get());
2304 ThrowException("Can't store to a nonpointer type: " +
2305 (*$5)->getDescription());
2306 const Type *ElTy = PT->getElementType();
2307 if (ElTy != $3->getType())
2308 ThrowException("Can't store '" + $3->getType()->getDescription() +
2309 "' into space of type '" + ElTy->getDescription() + "'!");
2311 $$ = new StoreInst($3, getVal(*$5, $6), $1);
2314 | GETELEMENTPTR Types ValueRef IndexList {
2315 if (!isa<PointerType>($2->get()))
2316 ThrowException("getelementptr insn requires pointer operand!");
2318 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
2319 // indices to uint struct indices for compatibility.
2320 generic_gep_type_iterator<std::vector<Value*>::iterator>
2321 GTI = gep_type_begin($2->get(), $4->begin(), $4->end()),
2322 GTE = gep_type_end($2->get(), $4->begin(), $4->end());
2323 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
2324 if (isa<StructType>(*GTI)) // Only change struct indices
2325 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
2326 if (CUI->getType() == Type::UByteTy)
2327 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
2329 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2330 ThrowException("Invalid getelementptr indices for type '" +
2331 (*$2)->getDescription()+ "'!");
2332 $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
2333 delete $2; delete $4;
2338 int yyerror(const char *ErrorMsg) {
2340 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2341 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2342 std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2343 if (yychar == YYEMPTY || yychar == 0)
2344 errMsg += "end-of-file.";
2346 errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2347 ThrowException(errMsg);