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/SymbolTable.h"
17 #include "llvm/Module.h"
18 #include "llvm/iTerminators.h"
19 #include "llvm/iMemory.h"
20 #include "llvm/iOperators.h"
21 #include "llvm/iPHINode.h"
22 #include "llvm/Support/GetElementPtrTypeIterator.h"
23 #include "Support/STLExtras.h"
29 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
30 int yylex(); // declaration" of xxx warnings.
35 static Module *ParserResult;
36 std::string CurFilename;
38 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
39 // relating to upreferences in the input stream.
41 //#define DEBUG_UPREFS 1
43 #define UR_OUT(X) std::cerr << X
48 #define YYERROR_VERBOSE 1
50 // HACK ALERT: This variable is used to implement the automatic conversion of
51 // variable argument instructions from their old to new forms. When this
52 // compatiblity "Feature" is removed, this should be too.
54 static BasicBlock *CurBB;
55 static bool ObsoleteVarArgs;
58 // This contains info used when building the body of a function. It is
59 // destroyed when the function is completed.
61 typedef std::vector<Value *> ValueList; // Numbered defs
62 static void 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 ConstantPointerRefs.
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 // DeclareNewGlobalValue - Called every time a new GV has been defined. This
114 // is used to remove things from the forward declaration map, resolving them
115 // to the correct thing as needed.
117 void DeclareNewGlobalValue(GlobalValue *GV, ValID D) {
118 // Check to see if there is a forward reference to this global variable...
119 // if there is, eliminate it and patch the reference to use the new def'n.
120 GlobalRefsType::iterator I =
121 GlobalRefs.find(std::make_pair(GV->getType(), D));
123 if (I != GlobalRefs.end()) {
124 GlobalValue *OldGV = I->second; // Get the placeholder...
125 I->first.second.destroy(); // Free string memory if necessary
127 // Replace all uses of the placeholder with the new GV
128 OldGV->replaceAllUsesWith(GV);
130 // Remove OldGV from the module...
131 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(OldGV))
132 CurrentModule->getGlobalList().erase(GVar);
134 CurrentModule->getFunctionList().erase(cast<Function>(OldGV));
136 // Remove the map entry for the global now that it has been created...
143 static struct PerFunctionInfo {
144 Function *CurrentFunction; // Pointer to current function being created
146 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
147 std::map<const Type*, ValueList> LateResolveValues;
148 std::vector<PATypeHolder> Types;
149 std::map<ValID, PATypeHolder> LateResolveTypes;
150 bool isDeclare; // Is this function a forward declararation?
152 inline PerFunctionInfo() {
157 inline void FunctionStart(Function *M) {
161 void FunctionDone() {
162 // If we could not resolve some blocks at parsing time (forward branches)
163 // resolve the branches now...
164 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
166 // Make sure to resolve any constant expr references that might exist within
167 // the function we just declared itself.
169 if (CurrentFunction->hasName()) {
170 FID = ValID::create((char*)CurrentFunction->getName().c_str());
172 // Figure out which slot number if is...
173 ValueList &List = CurModule.Values[CurrentFunction->getType()];
174 for (unsigned i = 0; ; ++i) {
175 assert(i < List.size() && "Function not found!");
176 if (List[i] == CurrentFunction) {
177 FID = ValID::create((int)i);
182 CurModule.DeclareNewGlobalValue(CurrentFunction, FID);
184 Values.clear(); // Clear out function local definitions
185 Types.clear(); // Clear out function local types
189 } CurFun; // Info for the current function...
191 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
194 //===----------------------------------------------------------------------===//
195 // Code to handle definitions of all the types
196 //===----------------------------------------------------------------------===//
198 static int InsertValue(Value *V,
199 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
200 if (V->hasName()) return -1; // Is this a numbered definition?
202 // Yes, insert the value into the value table...
203 ValueList &List = ValueTab[V->getType()];
205 return List.size()-1;
208 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
210 case ValID::NumberVal: { // Is it a numbered definition?
211 unsigned Num = (unsigned)D.Num;
213 // Module constants occupy the lowest numbered slots...
214 if (Num < CurModule.Types.size())
215 return CurModule.Types[Num];
217 Num -= CurModule.Types.size();
219 // Check that the number is within bounds...
220 if (Num <= CurFun.Types.size())
221 return CurFun.Types[Num];
224 case ValID::NameVal: { // Is it a named definition?
225 std::string Name(D.Name);
226 SymbolTable *SymTab = 0;
228 if (inFunctionScope()) {
229 SymTab = &CurFun.CurrentFunction->getSymbolTable();
230 N = SymTab->lookupType(Name);
234 // Symbol table doesn't automatically chain yet... because the function
235 // hasn't been added to the module...
237 SymTab = &CurModule.CurrentModule->getSymbolTable();
238 N = SymTab->lookupType(Name);
242 D.destroy(); // Free old strdup'd memory...
243 return cast<Type>(N);
246 ThrowException("Internal parser error: Invalid symbol type reference!");
249 // If we reached here, we referenced either a symbol that we don't know about
250 // or an id number that hasn't been read yet. We may be referencing something
251 // forward, so just create an entry to be resolved later and get to it...
253 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
255 std::map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ?
256 CurFun.LateResolveTypes : CurModule.LateResolveTypes;
258 std::map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
259 if (I != LateResolver.end()) {
263 Type *Typ = OpaqueType::get();
264 LateResolver.insert(std::make_pair(D, Typ));
268 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
269 SymbolTable &SymTab =
270 inFunctionScope() ? CurFun.CurrentFunction->getSymbolTable() :
271 CurModule.CurrentModule->getSymbolTable();
272 return SymTab.lookup(Ty, Name);
275 // getValNonImprovising - Look up the value specified by the provided type and
276 // the provided ValID. If the value exists and has already been defined, return
277 // it. Otherwise return null.
279 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
280 if (isa<FunctionType>(Ty))
281 ThrowException("Functions are not values and "
282 "must be referenced as pointers");
285 case ValID::NumberVal: { // Is it a numbered definition?
286 unsigned Num = (unsigned)D.Num;
288 // Module constants occupy the lowest numbered slots...
289 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
290 if (VI != CurModule.Values.end()) {
291 if (Num < VI->second.size())
292 return VI->second[Num];
293 Num -= VI->second.size();
296 // Make sure that our type is within bounds
297 VI = CurFun.Values.find(Ty);
298 if (VI == CurFun.Values.end()) return 0;
300 // Check that the number is within bounds...
301 if (VI->second.size() <= Num) return 0;
303 return VI->second[Num];
306 case ValID::NameVal: { // Is it a named definition?
307 Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
308 if (N == 0) return 0;
310 D.destroy(); // Free old strdup'd memory...
314 // Check to make sure that "Ty" is an integral type, and that our
315 // value will fit into the specified type...
316 case ValID::ConstSIntVal: // Is it a constant pool reference??
317 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64))
318 ThrowException("Signed integral constant '" +
319 itostr(D.ConstPool64) + "' is invalid for type '" +
320 Ty->getDescription() + "'!");
321 return ConstantSInt::get(Ty, D.ConstPool64);
323 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
324 if (!ConstantUInt::isValueValidForType(Ty, D.UConstPool64)) {
325 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64)) {
326 ThrowException("Integral constant '" + utostr(D.UConstPool64) +
327 "' is invalid or out of range!");
328 } else { // This is really a signed reference. Transmogrify.
329 return ConstantSInt::get(Ty, D.ConstPool64);
332 return ConstantUInt::get(Ty, D.UConstPool64);
335 case ValID::ConstFPVal: // Is it a floating point const pool reference?
336 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
337 ThrowException("FP constant invalid for type!!");
338 return ConstantFP::get(Ty, D.ConstPoolFP);
340 case ValID::ConstNullVal: // Is it a null value?
341 if (!isa<PointerType>(Ty))
342 ThrowException("Cannot create a a non pointer null!");
343 return ConstantPointerNull::get(cast<PointerType>(Ty));
345 case ValID::ConstantVal: // Fully resolved constant?
346 if (D.ConstantValue->getType() != Ty)
347 ThrowException("Constant expression type different from required type!");
348 return D.ConstantValue;
351 assert(0 && "Unhandled case!");
355 assert(0 && "Unhandled case!");
359 // getVal - This function is identical to getValNonImprovising, except that if a
360 // value is not already defined, it "improvises" by creating a placeholder var
361 // that looks and acts just like the requested variable. When the value is
362 // defined later, all uses of the placeholder variable are replaced with the
365 static Value *getVal(const Type *Ty, const ValID &ID) {
366 if (Ty == Type::LabelTy)
367 ThrowException("Cannot use a basic block here");
369 // See if the value has already been defined.
370 Value *V = getValNonImprovising(Ty, ID);
373 // If we reached here, we referenced either a symbol that we don't know about
374 // or an id number that hasn't been read yet. We may be referencing something
375 // forward, so just create an entry to be resolved later and get to it...
377 V = new Argument(Ty);
379 // Remember where this forward reference came from. FIXME, shouldn't we try
380 // to recycle these things??
381 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
384 if (inFunctionScope())
385 InsertValue(V, CurFun.LateResolveValues);
387 InsertValue(V, CurModule.LateResolveValues);
391 static BasicBlock *getBBVal(const ValID &ID) {
392 assert(inFunctionScope() && "Can't get basic block at global scope!");
394 // See if the value has already been defined.
395 Value *V = getValNonImprovising(Type::LabelTy, ID);
396 if (V) return cast<BasicBlock>(V);
398 BasicBlock *BB = new BasicBlock();
399 // Remember where this forward reference came from. FIXME, shouldn't we try
400 // to recycle these things??
401 CurModule.PlaceHolderInfo.insert(std::make_pair(BB, std::make_pair(ID,
404 InsertValue(BB, CurFun.LateResolveValues);
409 //===----------------------------------------------------------------------===//
410 // Code to handle forward references in instructions
411 //===----------------------------------------------------------------------===//
413 // This code handles the late binding needed with statements that reference
414 // values not defined yet... for example, a forward branch, or the PHI node for
417 // This keeps a table (CurFun.LateResolveValues) of all such forward references
418 // and back patchs after we are done.
421 // ResolveDefinitions - If we could not resolve some defs at parsing
422 // time (forward branches, phi functions for loops, etc...) resolve the
425 static void ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
426 std::map<const Type*,ValueList> *FutureLateResolvers) {
427 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
428 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
429 E = LateResolvers.end(); LRI != E; ++LRI) {
430 ValueList &List = LRI->second;
431 while (!List.empty()) {
432 Value *V = List.back();
435 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
436 CurModule.PlaceHolderInfo.find(V);
437 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
439 ValID &DID = PHI->second.first;
441 Value *TheRealValue = getValNonImprovising(LRI->first, DID);
443 V->replaceAllUsesWith(TheRealValue);
445 CurModule.PlaceHolderInfo.erase(PHI);
446 } else if (FutureLateResolvers) {
447 // Functions have their unresolved items forwarded to the module late
449 InsertValue(V, *FutureLateResolvers);
451 if (DID.Type == ValID::NameVal)
452 ThrowException("Reference to an invalid definition: '" +DID.getName()+
453 "' of type '" + V->getType()->getDescription() + "'",
456 ThrowException("Reference to an invalid definition: #" +
457 itostr(DID.Num) + " of type '" +
458 V->getType()->getDescription() + "'",
464 LateResolvers.clear();
467 // ResolveTypeTo - A brand new type was just declared. This means that (if
468 // name is not null) things referencing Name can be resolved. Otherwise, things
469 // refering to the number can be resolved. Do this now.
471 static void ResolveTypeTo(char *Name, const Type *ToTy) {
472 std::vector<PATypeHolder> &Types = inFunctionScope() ?
473 CurFun.Types : CurModule.Types;
476 if (Name) D = ValID::create(Name);
477 else D = ValID::create((int)Types.size());
479 std::map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ?
480 CurFun.LateResolveTypes : CurModule.LateResolveTypes;
482 std::map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
483 if (I != LateResolver.end()) {
484 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
485 LateResolver.erase(I);
489 // ResolveTypes - At this point, all types should be resolved. Any that aren't
492 static void ResolveTypes(std::map<ValID, PATypeHolder> &LateResolveTypes) {
493 if (!LateResolveTypes.empty()) {
494 const ValID &DID = LateResolveTypes.begin()->first;
496 if (DID.Type == ValID::NameVal)
497 ThrowException("Reference to an invalid type: '" +DID.getName() + "'");
499 ThrowException("Reference to an invalid type: #" + itostr(DID.Num));
503 // setValueName - Set the specified value to the name given. The name may be
504 // null potentially, in which case this is a noop. The string passed in is
505 // assumed to be a malloc'd string buffer, and is free'd by this function.
507 static void setValueName(Value *V, char *NameStr) {
509 std::string Name(NameStr); // Copy string
510 free(NameStr); // Free old string
512 if (V->getType() == Type::VoidTy)
513 ThrowException("Can't assign name '" + Name+"' to value with void type!");
515 assert(inFunctionScope() && "Must be in function scope!");
516 SymbolTable &ST = CurFun.CurrentFunction->getSymbolTable();
517 if (ST.lookup(V->getType(), Name))
518 ThrowException("Redefinition of value named '" + Name + "' in the '" +
519 V->getType()->getDescription() + "' type plane!");
522 V->setName(Name, &ST);
526 // setValueNameMergingDuplicates - Set the specified value to the name given.
527 // The name may be null potentially, in which case this is a noop. The string
528 // passed in is assumed to be a malloc'd string buffer, and is free'd by this
531 // This function returns true if the value has already been defined, but is
532 // allowed to be redefined in the specified context. If the name is a new name
533 // for the typeplane, false is returned.
535 static bool setValueNameMergingDuplicates(Value *V, char *NameStr) {
536 assert(V->getType() != Type::VoidTy && "Global or constant of type void?");
538 if (NameStr == 0) return false;
540 std::string Name(NameStr); // Copy string
541 free(NameStr); // Free old string
543 // FIXME: If we eliminated the function constant pool (which we should), this
544 // would just unconditionally look at the module symtab.
545 SymbolTable &ST = inFunctionScope() ?
546 CurFun.CurrentFunction->getSymbolTable() :
547 CurModule.CurrentModule->getSymbolTable();
549 Value *Existing = ST.lookup(V->getType(), Name);
550 if (Existing) { // Inserting a name that is already defined???
551 // We are a simple redefinition of a value, check to see if it is defined
552 // the same as the old one...
553 if (GlobalVariable *EGV = dyn_cast<GlobalVariable>(Existing)) {
554 // We are allowed to redefine a global variable in two circumstances:
555 // 1. If at least one of the globals is uninitialized or
556 // 2. If both initializers have the same value.
558 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
559 if (!EGV->hasInitializer() || !GV->hasInitializer() ||
560 EGV->getInitializer() == GV->getInitializer()) {
562 // Make sure the existing global version gets the initializer! Make
563 // sure that it also gets marked const if the new version is.
564 if (GV->hasInitializer() && !EGV->hasInitializer())
565 EGV->setInitializer(GV->getInitializer());
566 if (GV->isConstant())
567 EGV->setConstant(true);
568 EGV->setLinkage(GV->getLinkage());
570 delete GV; // Destroy the duplicate!
571 return true; // They are equivalent!
574 } else if (const Constant *C = dyn_cast<Constant>(Existing)) {
575 if (C == V) return true; // Constants are equal to themselves
578 ThrowException("Redefinition of value named '" + Name + "' in the '" +
579 V->getType()->getDescription() + "' type plane!");
583 V->setName(Name, &ST);
589 // setTypeName - Set the specified type to the name given. The name may be
590 // null potentially, in which case this is a noop. The string passed in is
591 // assumed to be a malloc'd string buffer, and is freed by this function.
593 // This function returns true if the type has already been defined, but is
594 // allowed to be redefined in the specified context. If the name is a new name
595 // for the type plane, it is inserted and false is returned.
596 static bool setTypeName(const Type *T, char *NameStr) {
597 if (NameStr == 0) return false;
599 std::string Name(NameStr); // Copy string
600 free(NameStr); // Free old string
602 // We don't allow assigning names to void type
603 if (T == Type::VoidTy)
604 ThrowException("Can't assign name '" + Name + "' to the void type!");
606 SymbolTable &ST = inFunctionScope() ?
607 CurFun.CurrentFunction->getSymbolTable() :
608 CurModule.CurrentModule->getSymbolTable();
610 // Inserting a name that is already defined???
611 if (Type *Existing = ST.lookupType(Name)) {
612 // There is only one case where this is allowed: when we are refining an
613 // opaque type. In this case, Existing will be an opaque type.
614 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
615 // We ARE replacing an opaque type!
616 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
620 // Otherwise, this is an attempt to redefine a type. That's okay if
621 // the redefinition is identical to the original. This will be so if
622 // Existing and T point to the same Type object. In this one case we
623 // allow the equivalent redefinition.
624 if (Existing == T) return true; // Yes, it's equal.
626 // Any other kind of (non-equivalent) redefinition is an error.
627 ThrowException("Redefinition of type named '" + Name + "' in the '" +
628 T->getDescription() + "' type plane!");
631 // Okay, its a newly named type. Set its name.
632 if (!Name.empty()) ST.insert(Name, T);
637 //===----------------------------------------------------------------------===//
638 // Code for handling upreferences in type names...
641 // TypeContains - Returns true if Ty directly contains E in it.
643 static bool TypeContains(const Type *Ty, const Type *E) {
644 return find(Ty->subtype_begin(), Ty->subtype_end(), E) != Ty->subtype_end();
649 // NestingLevel - The number of nesting levels that need to be popped before
650 // this type is resolved.
651 unsigned NestingLevel;
653 // LastContainedTy - This is the type at the current binding level for the
654 // type. Every time we reduce the nesting level, this gets updated.
655 const Type *LastContainedTy;
657 // UpRefTy - This is the actual opaque type that the upreference is
661 UpRefRecord(unsigned NL, OpaqueType *URTy)
662 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
666 // UpRefs - A list of the outstanding upreferences that need to be resolved.
667 static std::vector<UpRefRecord> UpRefs;
669 /// HandleUpRefs - Every time we finish a new layer of types, this function is
670 /// called. It loops through the UpRefs vector, which is a list of the
671 /// currently active types. For each type, if the up reference is contained in
672 /// the newly completed type, we decrement the level count. When the level
673 /// count reaches zero, the upreferenced type is the type that is passed in:
674 /// thus we can complete the cycle.
676 static PATypeHolder HandleUpRefs(const Type *ty) {
677 if (!ty->isAbstract()) return ty;
679 UR_OUT("Type '" << Ty->getDescription() <<
680 "' newly formed. Resolving upreferences.\n" <<
681 UpRefs.size() << " upreferences active!\n");
683 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
684 // to zero), we resolve them all together before we resolve them to Ty. At
685 // the end of the loop, if there is anything to resolve to Ty, it will be in
687 OpaqueType *TypeToResolve = 0;
689 for (unsigned i = 0; i != UpRefs.size(); ++i) {
690 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
691 << UpRefs[i].second->getDescription() << ") = "
692 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
693 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
694 // Decrement level of upreference
695 unsigned Level = --UpRefs[i].NestingLevel;
696 UpRefs[i].LastContainedTy = Ty;
697 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
698 if (Level == 0) { // Upreference should be resolved!
699 if (!TypeToResolve) {
700 TypeToResolve = UpRefs[i].UpRefTy;
702 UR_OUT(" * Resolving upreference for "
703 << UpRefs[i].second->getDescription() << "\n";
704 std::string OldName = UpRefs[i].UpRefTy->getDescription());
705 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
706 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
707 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
709 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
710 --i; // Do not skip the next element...
716 UR_OUT(" * Resolving upreference for "
717 << UpRefs[i].second->getDescription() << "\n";
718 std::string OldName = TypeToResolve->getDescription());
719 TypeToResolve->refineAbstractTypeTo(Ty);
726 //===----------------------------------------------------------------------===//
727 // RunVMAsmParser - Define an interface to this parser
728 //===----------------------------------------------------------------------===//
730 Module *RunVMAsmParser(const std::string &Filename, FILE *F) {
732 CurFilename = Filename;
733 llvmAsmlineno = 1; // Reset the current line number...
734 ObsoleteVarArgs = false;
736 // Allocate a new module to read
737 CurModule.CurrentModule = new Module(Filename);
739 yyparse(); // Parse the file, potentially throwing exception
741 Module *Result = ParserResult;
743 // Check to see if they called va_start but not va_arg..
744 if (!ObsoleteVarArgs)
745 if (Function *F = Result->getNamedFunction("llvm.va_start"))
746 if (F->asize() == 1) {
747 std::cerr << "WARNING: this file uses obsolete features. "
748 << "Assemble and disassemble to update it.\n";
749 ObsoleteVarArgs = true;
752 if (ObsoleteVarArgs) {
753 // If the user is making use of obsolete varargs intrinsics, adjust them for
755 if (Function *F = Result->getNamedFunction("llvm.va_start")) {
756 assert(F->asize() == 1 && "Obsolete va_start takes 1 argument!");
758 const Type *RetTy = F->getFunctionType()->getParamType(0);
759 RetTy = cast<PointerType>(RetTy)->getElementType();
760 Function *NF = Result->getOrInsertFunction("llvm.va_start", RetTy, 0);
762 while (!F->use_empty()) {
763 CallInst *CI = cast<CallInst>(F->use_back());
764 Value *V = new CallInst(NF, "", CI);
765 new StoreInst(V, CI->getOperand(1), CI);
766 CI->getParent()->getInstList().erase(CI);
768 Result->getFunctionList().erase(F);
771 if (Function *F = Result->getNamedFunction("llvm.va_end")) {
772 assert(F->asize() == 1 && "Obsolete va_end takes 1 argument!");
773 const Type *ArgTy = F->getFunctionType()->getParamType(0);
774 ArgTy = cast<PointerType>(ArgTy)->getElementType();
775 Function *NF = Result->getOrInsertFunction("llvm.va_end", Type::VoidTy,
778 while (!F->use_empty()) {
779 CallInst *CI = cast<CallInst>(F->use_back());
780 Value *V = new LoadInst(CI->getOperand(1), "", CI);
781 new CallInst(NF, V, "", CI);
782 CI->getParent()->getInstList().erase(CI);
784 Result->getFunctionList().erase(F);
787 if (Function *F = Result->getNamedFunction("llvm.va_copy")) {
788 assert(F->asize() == 2 && "Obsolete va_copy takes 2 argument!");
789 const Type *ArgTy = F->getFunctionType()->getParamType(0);
790 ArgTy = cast<PointerType>(ArgTy)->getElementType();
791 Function *NF = Result->getOrInsertFunction("llvm.va_copy", ArgTy,
794 while (!F->use_empty()) {
795 CallInst *CI = cast<CallInst>(F->use_back());
796 Value *V = new CallInst(NF, CI->getOperand(2), "", CI);
797 new StoreInst(V, CI->getOperand(1), CI);
798 CI->getParent()->getInstList().erase(CI);
800 Result->getFunctionList().erase(F);
804 llvmAsmin = stdin; // F is about to go away, don't use it anymore...
810 } // End llvm namespace
812 using namespace llvm;
817 llvm::Module *ModuleVal;
818 llvm::Function *FunctionVal;
819 std::pair<llvm::PATypeHolder*, char*> *ArgVal;
820 llvm::BasicBlock *BasicBlockVal;
821 llvm::TerminatorInst *TermInstVal;
822 llvm::Instruction *InstVal;
823 llvm::Constant *ConstVal;
825 const llvm::Type *PrimType;
826 llvm::PATypeHolder *TypeVal;
827 llvm::Value *ValueVal;
829 std::vector<std::pair<llvm::PATypeHolder*,char*> > *ArgList;
830 std::vector<llvm::Value*> *ValueList;
831 std::list<llvm::PATypeHolder> *TypeList;
832 std::list<std::pair<llvm::Value*,
833 llvm::BasicBlock*> > *PHIList; // Represent the RHS of PHI node
834 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
835 std::vector<llvm::Constant*> *ConstVector;
837 llvm::GlobalValue::LinkageTypes Linkage;
845 char *StrVal; // This memory is strdup'd!
846 llvm::ValID ValIDVal; // strdup'd memory maybe!
848 llvm::Instruction::BinaryOps BinaryOpVal;
849 llvm::Instruction::TermOps TermOpVal;
850 llvm::Instruction::MemoryOps MemOpVal;
851 llvm::Instruction::OtherOps OtherOpVal;
852 llvm::Module::Endianness Endianness;
855 %type <ModuleVal> Module FunctionList
856 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
857 %type <BasicBlockVal> BasicBlock InstructionList
858 %type <TermInstVal> BBTerminatorInst
859 %type <InstVal> Inst InstVal MemoryInst
860 %type <ConstVal> ConstVal ConstExpr
861 %type <ConstVector> ConstVector
862 %type <ArgList> ArgList ArgListH
863 %type <ArgVal> ArgVal
864 %type <PHIList> PHIList
865 %type <ValueList> ValueRefList ValueRefListE // For call param lists
866 %type <ValueList> IndexList // For GEP derived indices
867 %type <TypeList> TypeListI ArgTypeListI
868 %type <JumpTable> JumpTable
869 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
870 %type <BoolVal> OptVolatile // 'volatile' or not
871 %type <Linkage> OptLinkage
872 %type <Endianness> BigOrLittle
874 // ValueRef - Unresolved reference to a definition or BB
875 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
876 %type <ValueVal> ResolvedVal // <type> <valref> pair
877 // Tokens and types for handling constant integer values
879 // ESINT64VAL - A negative number within long long range
880 %token <SInt64Val> ESINT64VAL
882 // EUINT64VAL - A positive number within uns. long long range
883 %token <UInt64Val> EUINT64VAL
884 %type <SInt64Val> EINT64VAL
886 %token <SIntVal> SINTVAL // Signed 32 bit ints...
887 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
888 %type <SIntVal> INTVAL
889 %token <FPVal> FPVAL // Float or Double constant
892 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
893 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
894 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
895 %token <PrimType> FLOAT DOUBLE TYPE LABEL
897 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
898 %type <StrVal> Name OptName OptAssign
901 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
902 %token DECLARE GLOBAL CONSTANT VOLATILE
903 %token TO DOTDOTDOT NULL_TOK CONST INTERNAL LINKONCE WEAK APPENDING
904 %token OPAQUE NOT EXTERNAL TARGET ENDIAN POINTERSIZE LITTLE BIG
906 // Basic Block Terminating Operators
907 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND
910 %type <BinaryOpVal> BinaryOps // all the binary operators
911 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
912 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
913 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comarators
915 // Memory Instructions
916 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
919 %type <OtherOpVal> ShiftOps
920 %token <OtherOpVal> PHI_TOK CALL CAST SELECT SHL SHR VAARG VANEXT
921 %token VA_ARG // FIXME: OBSOLETE
926 // Handle constant integer size restriction and conversion...
930 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
931 ThrowException("Value too large for type!");
936 EINT64VAL : ESINT64VAL; // These have same type and can't cause problems...
937 EINT64VAL : EUINT64VAL {
938 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
939 ThrowException("Value too large for type!");
943 // Operations that are notably excluded from this list include:
944 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
946 ArithmeticOps: ADD | SUB | MUL | DIV | REM;
947 LogicalOps : AND | OR | XOR;
948 SetCondOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
949 BinaryOps : ArithmeticOps | LogicalOps | SetCondOps;
951 ShiftOps : SHL | SHR;
953 // These are some types that allow classification if we only want a particular
954 // thing... for example, only a signed, unsigned, or integral type.
955 SIntType : LONG | INT | SHORT | SBYTE;
956 UIntType : ULONG | UINT | USHORT | UBYTE;
957 IntType : SIntType | UIntType;
958 FPType : FLOAT | DOUBLE;
960 // OptAssign - Value producing statements have an optional assignment component
961 OptAssign : Name '=' {
968 OptLinkage : INTERNAL { $$ = GlobalValue::InternalLinkage; } |
969 LINKONCE { $$ = GlobalValue::LinkOnceLinkage; } |
970 WEAK { $$ = GlobalValue::WeakLinkage; } |
971 APPENDING { $$ = GlobalValue::AppendingLinkage; } |
972 /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
974 //===----------------------------------------------------------------------===//
975 // Types includes all predefined types... except void, because it can only be
976 // used in specific contexts (function returning void for example). To have
977 // access to it, a user must explicitly use TypesV.
980 // TypesV includes all of 'Types', but it also includes the void type.
981 TypesV : Types | VOID { $$ = new PATypeHolder($1); };
982 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
986 ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
991 // Derived types are added later...
993 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT ;
994 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL;
996 $$ = new PATypeHolder(OpaqueType::get());
999 $$ = new PATypeHolder($1);
1001 UpRTypes : SymbolicValueRef { // Named types are also simple types...
1002 $$ = new PATypeHolder(getTypeVal($1));
1005 // Include derived types in the Types production.
1007 UpRTypes : '\\' EUINT64VAL { // Type UpReference
1008 if ($2 > (uint64_t)~0U) ThrowException("Value out of range!");
1009 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1010 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1011 $$ = new PATypeHolder(OT);
1012 UR_OUT("New Upreference!\n");
1014 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
1015 std::vector<const Type*> Params;
1016 mapto($3->begin(), $3->end(), std::back_inserter(Params),
1017 std::mem_fun_ref(&PATypeHolder::get));
1018 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1019 if (isVarArg) Params.pop_back();
1021 $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
1022 delete $3; // Delete the argument list
1023 delete $1; // Delete the return type handle
1025 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
1026 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1029 | '{' TypeListI '}' { // Structure type?
1030 std::vector<const Type*> Elements;
1031 mapto($2->begin(), $2->end(), std::back_inserter(Elements),
1032 std::mem_fun_ref(&PATypeHolder::get));
1034 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1037 | '{' '}' { // Empty structure type?
1038 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1040 | UpRTypes '*' { // Pointer type?
1041 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1045 // TypeList - Used for struct declarations and as a basis for function type
1046 // declaration type lists
1048 TypeListI : UpRTypes {
1049 $$ = new std::list<PATypeHolder>();
1050 $$->push_back(*$1); delete $1;
1052 | TypeListI ',' UpRTypes {
1053 ($$=$1)->push_back(*$3); delete $3;
1056 // ArgTypeList - List of types for a function type declaration...
1057 ArgTypeListI : TypeListI
1058 | TypeListI ',' DOTDOTDOT {
1059 ($$=$1)->push_back(Type::VoidTy);
1062 ($$ = new std::list<PATypeHolder>())->push_back(Type::VoidTy);
1065 $$ = new std::list<PATypeHolder>();
1068 // ConstVal - The various declarations that go into the constant pool. This
1069 // production is used ONLY to represent constants that show up AFTER a 'const',
1070 // 'constant' or 'global' token at global scope. Constants that can be inlined
1071 // into other expressions (such as integers and constexprs) are handled by the
1072 // ResolvedVal, ValueRef and ConstValueRef productions.
1074 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1075 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1077 ThrowException("Cannot make array constant with type: '" +
1078 (*$1)->getDescription() + "'!");
1079 const Type *ETy = ATy->getElementType();
1080 int NumElements = ATy->getNumElements();
1082 // Verify that we have the correct size...
1083 if (NumElements != -1 && NumElements != (int)$3->size())
1084 ThrowException("Type mismatch: constant sized array initialized with " +
1085 utostr($3->size()) + " arguments, but has size of " +
1086 itostr(NumElements) + "!");
1088 // Verify all elements are correct type!
1089 for (unsigned i = 0; i < $3->size(); i++) {
1090 if (ETy != (*$3)[i]->getType())
1091 ThrowException("Element #" + utostr(i) + " is not of type '" +
1092 ETy->getDescription() +"' as required!\nIt is of type '"+
1093 (*$3)[i]->getType()->getDescription() + "'.");
1096 $$ = ConstantArray::get(ATy, *$3);
1097 delete $1; delete $3;
1100 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1102 ThrowException("Cannot make array constant with type: '" +
1103 (*$1)->getDescription() + "'!");
1105 int NumElements = ATy->getNumElements();
1106 if (NumElements != -1 && NumElements != 0)
1107 ThrowException("Type mismatch: constant sized array initialized with 0"
1108 " arguments, but has size of " + itostr(NumElements) +"!");
1109 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1112 | Types 'c' STRINGCONSTANT {
1113 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1115 ThrowException("Cannot make array constant with type: '" +
1116 (*$1)->getDescription() + "'!");
1118 int NumElements = ATy->getNumElements();
1119 const Type *ETy = ATy->getElementType();
1120 char *EndStr = UnEscapeLexed($3, true);
1121 if (NumElements != -1 && NumElements != (EndStr-$3))
1122 ThrowException("Can't build string constant of size " +
1123 itostr((int)(EndStr-$3)) +
1124 " when array has size " + itostr(NumElements) + "!");
1125 std::vector<Constant*> Vals;
1126 if (ETy == Type::SByteTy) {
1127 for (char *C = $3; C != EndStr; ++C)
1128 Vals.push_back(ConstantSInt::get(ETy, *C));
1129 } else if (ETy == Type::UByteTy) {
1130 for (char *C = $3; C != EndStr; ++C)
1131 Vals.push_back(ConstantUInt::get(ETy, (unsigned char)*C));
1134 ThrowException("Cannot build string arrays of non byte sized elements!");
1137 $$ = ConstantArray::get(ATy, Vals);
1140 | Types '{' ConstVector '}' {
1141 const StructType *STy = dyn_cast<StructType>($1->get());
1143 ThrowException("Cannot make struct constant with type: '" +
1144 (*$1)->getDescription() + "'!");
1146 if ($3->size() != STy->getNumContainedTypes())
1147 ThrowException("Illegal number of initializers for structure type!");
1149 // Check to ensure that constants are compatible with the type initializer!
1150 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1151 if ((*$3)[i]->getType() != STy->getElementType(i))
1152 ThrowException("Expected type '" +
1153 STy->getElementType(i)->getDescription() +
1154 "' for element #" + utostr(i) +
1155 " of structure initializer!");
1157 $$ = ConstantStruct::get(STy, *$3);
1158 delete $1; delete $3;
1161 const StructType *STy = dyn_cast<StructType>($1->get());
1163 ThrowException("Cannot make struct constant with type: '" +
1164 (*$1)->getDescription() + "'!");
1166 if (STy->getNumContainedTypes() != 0)
1167 ThrowException("Illegal number of initializers for structure type!");
1169 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1173 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1175 ThrowException("Cannot make null pointer constant with type: '" +
1176 (*$1)->getDescription() + "'!");
1178 $$ = ConstantPointerNull::get(PTy);
1181 | Types SymbolicValueRef {
1182 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1184 ThrowException("Global const reference must be a pointer type!");
1186 // ConstExprs can exist in the body of a function, thus creating
1187 // ConstantPointerRefs whenever they refer to a variable. Because we are in
1188 // the context of a function, getValNonImprovising will search the functions
1189 // symbol table instead of the module symbol table for the global symbol,
1190 // which throws things all off. To get around this, we just tell
1191 // getValNonImprovising that we are at global scope here.
1193 Function *SavedCurFn = CurFun.CurrentFunction;
1194 CurFun.CurrentFunction = 0;
1196 Value *V = getValNonImprovising(Ty, $2);
1198 CurFun.CurrentFunction = SavedCurFn;
1200 // If this is an initializer for a constant pointer, which is referencing a
1201 // (currently) undefined variable, create a stub now that shall be replaced
1202 // in the future with the right type of variable.
1205 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1206 const PointerType *PT = cast<PointerType>(Ty);
1208 // First check to see if the forward references value is already created!
1209 PerModuleInfo::GlobalRefsType::iterator I =
1210 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1212 if (I != CurModule.GlobalRefs.end()) {
1213 V = I->second; // Placeholder already exists, use it...
1216 // Create a placeholder for the global variable reference...
1217 GlobalVariable *GV = new GlobalVariable(PT->getElementType(),
1219 GlobalValue::ExternalLinkage);
1220 // Keep track of the fact that we have a forward ref to recycle it
1221 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1223 // Must temporarily push this value into the module table...
1224 CurModule.CurrentModule->getGlobalList().push_back(GV);
1229 GlobalValue *GV = cast<GlobalValue>(V);
1230 $$ = ConstantPointerRef::get(GV);
1231 delete $1; // Free the type handle
1234 if ($1->get() != $2->getType())
1235 ThrowException("Mismatched types for constant expression!");
1239 | Types ZEROINITIALIZER {
1240 $$ = Constant::getNullValue($1->get());
1244 ConstVal : SIntType EINT64VAL { // integral constants
1245 if (!ConstantSInt::isValueValidForType($1, $2))
1246 ThrowException("Constant value doesn't fit in type!");
1247 $$ = ConstantSInt::get($1, $2);
1249 | UIntType EUINT64VAL { // integral constants
1250 if (!ConstantUInt::isValueValidForType($1, $2))
1251 ThrowException("Constant value doesn't fit in type!");
1252 $$ = ConstantUInt::get($1, $2);
1254 | BOOL TRUETOK { // Boolean constants
1255 $$ = ConstantBool::True;
1257 | BOOL FALSETOK { // Boolean constants
1258 $$ = ConstantBool::False;
1260 | FPType FPVAL { // Float & Double constants
1261 $$ = ConstantFP::get($1, $2);
1265 ConstExpr: CAST '(' ConstVal TO Types ')' {
1266 if (!$3->getType()->isFirstClassType())
1267 ThrowException("cast constant expression from a non-primitive type: '" +
1268 $3->getType()->getDescription() + "'!");
1269 if (!$5->get()->isFirstClassType())
1270 ThrowException("cast constant expression to a non-primitive type: '" +
1271 $5->get()->getDescription() + "'!");
1272 $$ = ConstantExpr::getCast($3, $5->get());
1275 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1276 if (!isa<PointerType>($3->getType()))
1277 ThrowException("GetElementPtr requires a pointer operand!");
1279 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
1280 // indices to uint struct indices for compatibility.
1281 generic_gep_type_iterator<std::vector<Value*>::iterator>
1282 GTI = gep_type_begin($3->getType(), $4->begin(), $4->end()),
1283 GTE = gep_type_end($3->getType(), $4->begin(), $4->end());
1284 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
1285 if (isa<StructType>(*GTI)) // Only change struct indices
1286 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
1287 if (CUI->getType() == Type::UByteTy)
1288 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
1291 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1293 ThrowException("Index list invalid for constant getelementptr!");
1295 std::vector<Constant*> IdxVec;
1296 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1297 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1298 IdxVec.push_back(C);
1300 ThrowException("Indices to constant getelementptr must be constants!");
1304 $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1306 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1307 if ($3->getType() != Type::BoolTy)
1308 ThrowException("Select condition must be of boolean type!");
1309 if ($5->getType() != $7->getType())
1310 ThrowException("Select operand types must match!");
1311 $$ = ConstantExpr::getSelect($3, $5, $7);
1313 | BinaryOps '(' ConstVal ',' ConstVal ')' {
1314 if ($3->getType() != $5->getType())
1315 ThrowException("Binary operator types must match!");
1316 $$ = ConstantExpr::get($1, $3, $5);
1318 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1319 if ($5->getType() != Type::UByteTy)
1320 ThrowException("Shift count for shift constant must be unsigned byte!");
1321 if (!$3->getType()->isInteger())
1322 ThrowException("Shift constant expression requires integer operand!");
1323 $$ = ConstantExpr::get($1, $3, $5);
1327 // ConstVector - A list of comma separated constants.
1328 ConstVector : ConstVector ',' ConstVal {
1329 ($$ = $1)->push_back($3);
1332 $$ = new std::vector<Constant*>();
1337 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1338 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1341 //===----------------------------------------------------------------------===//
1342 // Rules to match Modules
1343 //===----------------------------------------------------------------------===//
1345 // Module rule: Capture the result of parsing the whole file into a result
1348 Module : FunctionList {
1349 $$ = ParserResult = $1;
1350 CurModule.ModuleDone();
1353 // FunctionList - A list of functions, preceeded by a constant pool.
1355 FunctionList : FunctionList Function {
1357 CurFun.FunctionDone();
1359 | FunctionList FunctionProto {
1362 | FunctionList IMPLEMENTATION {
1366 $$ = CurModule.CurrentModule;
1367 // Resolve circular types before we parse the body of the module
1368 ResolveTypes(CurModule.LateResolveTypes);
1371 // ConstPool - Constants with optional names assigned to them.
1372 ConstPool : ConstPool OptAssign CONST ConstVal {
1373 // FIXME: THIS SHOULD REALLY BE ELIMINATED. It is totally unneeded.
1374 if (!setValueNameMergingDuplicates($4, $2))
1377 | ConstPool OptAssign TYPE TypesV { // Types can be defined in the const pool
1378 // Eagerly resolve types. This is not an optimization, this is a
1379 // requirement that is due to the fact that we could have this:
1381 // %list = type { %list * }
1382 // %list = type { %list * } ; repeated type decl
1384 // If types are not resolved eagerly, then the two types will not be
1385 // determined to be the same type!
1387 ResolveTypeTo($2, *$4);
1389 if (!setTypeName(*$4, $2) && !$2) {
1390 // If this is a named type that is not a redefinition, add it to the slot
1392 if (inFunctionScope())
1393 CurFun.Types.push_back(*$4);
1395 CurModule.Types.push_back(*$4);
1400 | ConstPool FunctionProto { // Function prototypes can be in const pool
1402 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
1403 const Type *Ty = $5->getType();
1404 // Global declarations appear in Constant Pool
1405 Constant *Initializer = $5;
1406 if (Initializer == 0)
1407 ThrowException("Global value initializer is not a constant!");
1409 GlobalVariable *GV = new GlobalVariable(Ty, $4, $3, Initializer);
1410 if (!setValueNameMergingDuplicates(GV, $2)) { // If not redefining...
1411 CurModule.CurrentModule->getGlobalList().push_back(GV);
1412 int Slot = InsertValue(GV, CurModule.Values);
1415 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1417 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1418 (char*)GV->getName().c_str()));
1422 | ConstPool OptAssign EXTERNAL GlobalType Types {
1423 const Type *Ty = *$5;
1424 // Global declarations appear in Constant Pool
1425 GlobalVariable *GV = new GlobalVariable(Ty,$4,GlobalValue::ExternalLinkage);
1426 if (!setValueNameMergingDuplicates(GV, $2)) { // If not redefining...
1427 CurModule.CurrentModule->getGlobalList().push_back(GV);
1428 int Slot = InsertValue(GV, CurModule.Values);
1431 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1433 assert(GV->hasName() && "Not named and not numbered!?");
1434 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1435 (char*)GV->getName().c_str()));
1440 | ConstPool TARGET TargetDefinition {
1442 | /* empty: end of list */ {
1447 BigOrLittle : BIG { $$ = Module::BigEndian; };
1448 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1450 TargetDefinition : ENDIAN '=' BigOrLittle {
1451 CurModule.CurrentModule->setEndianness($3);
1453 | POINTERSIZE '=' EUINT64VAL {
1455 CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1457 CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1459 ThrowException("Invalid pointer size: '" + utostr($3) + "'!");
1463 //===----------------------------------------------------------------------===//
1464 // Rules to match Function Headers
1465 //===----------------------------------------------------------------------===//
1467 Name : VAR_ID | STRINGCONSTANT;
1468 OptName : Name | /*empty*/ { $$ = 0; };
1470 ArgVal : Types OptName {
1471 if (*$1 == Type::VoidTy)
1472 ThrowException("void typed arguments are invalid!");
1473 $$ = new std::pair<PATypeHolder*, char*>($1, $2);
1476 ArgListH : ArgListH ',' ArgVal {
1482 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1487 ArgList : ArgListH {
1490 | ArgListH ',' DOTDOTDOT {
1492 $$->push_back(std::pair<PATypeHolder*,
1493 char*>(new PATypeHolder(Type::VoidTy), 0));
1496 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1497 $$->push_back(std::make_pair(new PATypeHolder(Type::VoidTy), (char*)0));
1503 FunctionHeaderH : TypesV Name '(' ArgList ')' {
1505 std::string FunctionName($2);
1507 if (!(*$1)->isFirstClassType() && *$1 != Type::VoidTy)
1508 ThrowException("LLVM functions cannot return aggregate types!");
1510 std::vector<const Type*> ParamTypeList;
1511 if ($4) { // If there are arguments...
1512 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $4->begin();
1513 I != $4->end(); ++I)
1514 ParamTypeList.push_back(I->first->get());
1517 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1518 if (isVarArg) ParamTypeList.pop_back();
1520 const FunctionType *FT = FunctionType::get(*$1, ParamTypeList, isVarArg);
1521 const PointerType *PFT = PointerType::get(FT);
1525 // Is the function already in symtab?
1526 if ((Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
1527 // Yes it is. If this is the case, either we need to be a forward decl,
1528 // or it needs to be.
1529 if (!CurFun.isDeclare && !Fn->isExternal())
1530 ThrowException("Redefinition of function '" + FunctionName + "'!");
1532 // Make sure to strip off any argument names so we can't get conflicts...
1533 for (Function::aiterator AI = Fn->abegin(), AE = Fn->aend(); AI != AE; ++AI)
1536 } else { // Not already defined?
1537 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
1538 CurModule.CurrentModule);
1539 InsertValue(Fn, CurModule.Values);
1540 CurModule.DeclareNewGlobalValue(Fn, ValID::create($2));
1542 free($2); // Free strdup'd memory!
1544 CurFun.FunctionStart(Fn);
1546 // Add all of the arguments we parsed to the function...
1547 if ($4) { // Is null if empty...
1548 if (isVarArg) { // Nuke the last entry
1549 assert($4->back().first->get() == Type::VoidTy && $4->back().second == 0&&
1550 "Not a varargs marker!");
1551 delete $4->back().first;
1552 $4->pop_back(); // Delete the last entry
1554 Function::aiterator ArgIt = Fn->abegin();
1555 for (std::vector<std::pair<PATypeHolder*, char*> >::iterator I =$4->begin();
1556 I != $4->end(); ++I, ++ArgIt) {
1557 delete I->first; // Delete the typeholder...
1559 setValueName(ArgIt, I->second); // Insert arg into symtab...
1563 delete $4; // We're now done with the argument list
1567 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
1569 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
1570 $$ = CurFun.CurrentFunction;
1572 // Make sure that we keep track of the linkage type even if there was a
1573 // previous "declare".
1576 // Resolve circular types before we parse the body of the function.
1577 ResolveTypes(CurFun.LateResolveTypes);
1580 END : ENDTOK | '}'; // Allow end of '}' to end a function
1582 Function : BasicBlockList END {
1586 FunctionProto : DECLARE { CurFun.isDeclare = true; } FunctionHeaderH {
1587 $$ = CurFun.CurrentFunction;
1588 CurFun.FunctionDone();
1591 //===----------------------------------------------------------------------===//
1592 // Rules to match Basic Blocks
1593 //===----------------------------------------------------------------------===//
1595 ConstValueRef : ESINT64VAL { // A reference to a direct constant
1596 $$ = ValID::create($1);
1599 $$ = ValID::create($1);
1601 | FPVAL { // Perhaps it's an FP constant?
1602 $$ = ValID::create($1);
1605 $$ = ValID::create(ConstantBool::True);
1608 $$ = ValID::create(ConstantBool::False);
1611 $$ = ValID::createNull();
1614 $$ = ValID::create($1);
1617 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1620 SymbolicValueRef : INTVAL { // Is it an integer reference...?
1621 $$ = ValID::create($1);
1623 | Name { // Is it a named reference...?
1624 $$ = ValID::create($1);
1627 // ValueRef - A reference to a definition... either constant or symbolic
1628 ValueRef : SymbolicValueRef | ConstValueRef;
1631 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
1632 // type immediately preceeds the value reference, and allows complex constant
1633 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1634 ResolvedVal : Types ValueRef {
1635 $$ = getVal(*$1, $2); delete $1;
1638 BasicBlockList : BasicBlockList BasicBlock {
1641 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
1646 // Basic blocks are terminated by branching instructions:
1647 // br, br/cc, switch, ret
1649 BasicBlock : InstructionList OptAssign BBTerminatorInst {
1650 setValueName($3, $2);
1653 $1->getInstList().push_back($3);
1658 InstructionList : InstructionList Inst {
1659 $1->getInstList().push_back($2);
1663 // FIXME: Should check to see if there is a forward ref'd basic block that
1664 // we can use and reuse it as appropriate. It doesn't make sense just to
1665 // make forward ref'd blocks then discard them.
1666 $$ = CurBB = new BasicBlock("", CurFun.CurrentFunction);
1669 // FIXME: Should check to see if there is a forward ref'd basic block that
1670 // we can use and reuse it as appropriate. It doesn't make sense just to
1671 // make forward ref'd blocks then discard them.
1672 $$ = CurBB = new BasicBlock("", CurFun.CurrentFunction);
1673 setValueName($$, $1);
1677 BBTerminatorInst : RET ResolvedVal { // Return with a result...
1678 $$ = new ReturnInst($2);
1680 | RET VOID { // Return with no result...
1681 $$ = new ReturnInst();
1683 | BR LABEL ValueRef { // Unconditional Branch...
1684 $$ = new BranchInst(getBBVal($3));
1685 } // Conditional Branch...
1686 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
1687 $$ = new BranchInst(getBBVal($6), getBBVal($9), getVal(Type::BoolTy, $3));
1689 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1690 SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6));
1693 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
1696 S->addCase(I->first, I->second);
1699 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
1700 SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6));
1703 | INVOKE TypesV ValueRef '(' ValueRefListE ')' TO LABEL ValueRef
1704 UNWIND LABEL ValueRef {
1705 const PointerType *PFTy;
1706 const FunctionType *Ty;
1708 if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
1709 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1710 // Pull out the types of all of the arguments...
1711 std::vector<const Type*> ParamTypes;
1713 for (std::vector<Value*>::iterator I = $5->begin(), E = $5->end();
1715 ParamTypes.push_back((*I)->getType());
1718 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1719 if (isVarArg) ParamTypes.pop_back();
1721 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1722 PFTy = PointerType::get(Ty);
1725 Value *V = getVal(PFTy, $3); // Get the function we're calling...
1727 BasicBlock *Normal = getBBVal($9);
1728 BasicBlock *Except = getBBVal($12);
1730 // Create the call node...
1731 if (!$5) { // Has no arguments?
1732 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
1733 } else { // Has arguments?
1734 // Loop through FunctionType's arguments and ensure they are specified
1737 FunctionType::param_iterator I = Ty->param_begin();
1738 FunctionType::param_iterator E = Ty->param_end();
1739 std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1741 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1742 if ((*ArgI)->getType() != *I)
1743 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1744 (*I)->getDescription() + "'!");
1746 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1747 ThrowException("Invalid number of parameters detected!");
1749 $$ = new InvokeInst(V, Normal, Except, *$5);
1755 $$ = new UnwindInst();
1760 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1762 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
1764 ThrowException("May only switch on a constant pool value!");
1766 $$->push_back(std::make_pair(V, getBBVal($6)));
1768 | IntType ConstValueRef ',' LABEL ValueRef {
1769 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
1770 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
1773 ThrowException("May only switch on a constant pool value!");
1775 $$->push_back(std::make_pair(V, getBBVal($5)));
1778 Inst : OptAssign InstVal {
1779 // Is this definition named?? if so, assign the name...
1780 setValueName($2, $1);
1785 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
1786 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
1787 $$->push_back(std::make_pair(getVal(*$1, $3), getBBVal($5)));
1790 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1792 $1->push_back(std::make_pair(getVal($1->front().first->getType(), $4),
1797 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
1798 $$ = new std::vector<Value*>();
1801 | ValueRefList ',' ResolvedVal {
1806 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1807 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
1809 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
1810 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint())
1811 ThrowException("Arithmetic operator requires integer or FP operands!");
1812 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1814 ThrowException("binary operator returned null!");
1817 | LogicalOps Types ValueRef ',' ValueRef {
1818 if (!(*$2)->isIntegral())
1819 ThrowException("Logical operator requires integral operands!");
1820 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1822 ThrowException("binary operator returned null!");
1825 | SetCondOps Types ValueRef ',' ValueRef {
1826 $$ = new SetCondInst($1, getVal(*$2, $3), getVal(*$2, $5));
1828 ThrowException("binary operator returned null!");
1832 std::cerr << "WARNING: Use of eliminated 'not' instruction:"
1833 << " Replacing with 'xor'.\n";
1835 Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
1837 ThrowException("Expected integral type for not instruction!");
1839 $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
1841 ThrowException("Could not create a xor instruction!");
1843 | ShiftOps ResolvedVal ',' ResolvedVal {
1844 if ($4->getType() != Type::UByteTy)
1845 ThrowException("Shift amount must be ubyte!");
1846 if (!$2->getType()->isInteger())
1847 ThrowException("Shift constant expression requires integer operand!");
1848 $$ = new ShiftInst($1, $2, $4);
1850 | CAST ResolvedVal TO Types {
1851 if (!$4->get()->isFirstClassType())
1852 ThrowException("cast instruction to a non-primitive type: '" +
1853 $4->get()->getDescription() + "'!");
1854 $$ = new CastInst($2, *$4);
1857 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
1858 if ($2->getType() != Type::BoolTy)
1859 ThrowException("select condition must be boolean!");
1860 if ($4->getType() != $6->getType())
1861 ThrowException("select value types should match!");
1862 $$ = new SelectInst($2, $4, $6);
1864 | VA_ARG ResolvedVal ',' Types {
1865 // FIXME: This is emulation code for an obsolete syntax. This should be
1866 // removed at some point.
1867 if (!ObsoleteVarArgs) {
1868 std::cerr << "WARNING: this file uses obsolete features. "
1869 << "Assemble and disassemble to update it.\n";
1870 ObsoleteVarArgs = true;
1873 // First, load the valist...
1874 Instruction *CurVAList = new LoadInst($2, "");
1875 CurBB->getInstList().push_back(CurVAList);
1877 // Emit the vaarg instruction.
1878 $$ = new VAArgInst(CurVAList, *$4);
1880 // Now we must advance the pointer and update it in memory.
1881 Instruction *TheVANext = new VANextInst(CurVAList, *$4);
1882 CurBB->getInstList().push_back(TheVANext);
1884 CurBB->getInstList().push_back(new StoreInst(TheVANext, $2));
1887 | VAARG ResolvedVal ',' Types {
1888 $$ = new VAArgInst($2, *$4);
1891 | VANEXT ResolvedVal ',' Types {
1892 $$ = new VANextInst($2, *$4);
1896 const Type *Ty = $2->front().first->getType();
1897 if (!Ty->isFirstClassType())
1898 ThrowException("PHI node operands must be of first class type!");
1899 $$ = new PHINode(Ty);
1900 $$->op_reserve($2->size()*2);
1901 while ($2->begin() != $2->end()) {
1902 if ($2->front().first->getType() != Ty)
1903 ThrowException("All elements of a PHI node must be of the same type!");
1904 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
1907 delete $2; // Free the list...
1909 | CALL TypesV ValueRef '(' ValueRefListE ')' {
1910 const PointerType *PFTy;
1911 const FunctionType *Ty;
1913 if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
1914 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1915 // Pull out the types of all of the arguments...
1916 std::vector<const Type*> ParamTypes;
1918 for (std::vector<Value*>::iterator I = $5->begin(), E = $5->end();
1920 ParamTypes.push_back((*I)->getType());
1923 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1924 if (isVarArg) ParamTypes.pop_back();
1926 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1927 PFTy = PointerType::get(Ty);
1930 Value *V = getVal(PFTy, $3); // Get the function we're calling...
1932 // Create the call node...
1933 if (!$5) { // Has no arguments?
1934 // Make sure no arguments is a good thing!
1935 if (Ty->getNumParams() != 0)
1936 ThrowException("No arguments passed to a function that "
1937 "expects arguments!");
1939 $$ = new CallInst(V, std::vector<Value*>());
1940 } else { // Has arguments?
1941 // Loop through FunctionType's arguments and ensure they are specified
1944 FunctionType::param_iterator I = Ty->param_begin();
1945 FunctionType::param_iterator E = Ty->param_end();
1946 std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1948 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1949 if ((*ArgI)->getType() != *I)
1950 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1951 (*I)->getDescription() + "'!");
1953 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1954 ThrowException("Invalid number of parameters detected!");
1956 $$ = new CallInst(V, *$5);
1966 // IndexList - List of indices for GEP based instructions...
1967 IndexList : ',' ValueRefList {
1970 $$ = new std::vector<Value*>();
1973 OptVolatile : VOLATILE {
1981 MemoryInst : MALLOC Types {
1982 $$ = new MallocInst(*$2);
1985 | MALLOC Types ',' UINT ValueRef {
1986 $$ = new MallocInst(*$2, getVal($4, $5));
1990 $$ = new AllocaInst(*$2);
1993 | ALLOCA Types ',' UINT ValueRef {
1994 $$ = new AllocaInst(*$2, getVal($4, $5));
1997 | FREE ResolvedVal {
1998 if (!isa<PointerType>($2->getType()))
1999 ThrowException("Trying to free nonpointer type " +
2000 $2->getType()->getDescription() + "!");
2001 $$ = new FreeInst($2);
2004 | OptVolatile LOAD Types ValueRef {
2005 if (!isa<PointerType>($3->get()))
2006 ThrowException("Can't load from nonpointer type: " +
2007 (*$3)->getDescription());
2008 $$ = new LoadInst(getVal(*$3, $4), "", $1);
2011 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2012 const PointerType *PT = dyn_cast<PointerType>($5->get());
2014 ThrowException("Can't store to a nonpointer type: " +
2015 (*$5)->getDescription());
2016 const Type *ElTy = PT->getElementType();
2017 if (ElTy != $3->getType())
2018 ThrowException("Can't store '" + $3->getType()->getDescription() +
2019 "' into space of type '" + ElTy->getDescription() + "'!");
2021 $$ = new StoreInst($3, getVal(*$5, $6), $1);
2024 | GETELEMENTPTR Types ValueRef IndexList {
2025 if (!isa<PointerType>($2->get()))
2026 ThrowException("getelementptr insn requires pointer operand!");
2028 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
2029 // indices to uint struct indices for compatibility.
2030 generic_gep_type_iterator<std::vector<Value*>::iterator>
2031 GTI = gep_type_begin($2->get(), $4->begin(), $4->end()),
2032 GTE = gep_type_end($2->get(), $4->begin(), $4->end());
2033 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
2034 if (isa<StructType>(*GTI)) // Only change struct indices
2035 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
2036 if (CUI->getType() == Type::UByteTy)
2037 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
2039 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2040 ThrowException("Invalid getelementptr indices for type '" +
2041 (*$2)->getDescription()+ "'!");
2042 $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
2043 delete $2; delete $4;
2048 int yyerror(const char *ErrorMsg) {
2050 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2051 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2052 std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2053 if (yychar == YYEMPTY || yychar == 0)
2054 errMsg += "end-of-file.";
2056 errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2057 ThrowException(errMsg);