1 //===-- llvmAsmParser.y - Parser for llvm assembly files ---------*- C++ -*--=//
3 // This file implements the bison parser for LLVM assembly languages files.
5 //===------------------------------------------------------------------------=//
8 #include "ParserInternals.h"
9 #include "llvm/SymbolTable.h"
10 #include "llvm/Module.h"
11 #include "llvm/iTerminators.h"
12 #include "llvm/iMemory.h"
13 #include "llvm/iOperators.h"
14 #include "llvm/iPHINode.h"
15 #include "Support/STLExtras.h"
16 #include "Support/DepthFirstIterator.h"
21 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
22 int yylex(); // declaration" of xxx warnings.
25 static Module *ParserResult;
26 std::string CurFilename;
28 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
29 // relating to upreferences in the input stream.
31 //#define DEBUG_UPREFS 1
33 #define UR_OUT(X) std::cerr << X
38 #define YYERROR_VERBOSE 1
40 // This contains info used when building the body of a function. It is
41 // destroyed when the function is completed.
43 typedef std::vector<Value *> ValueList; // Numbered defs
44 static void ResolveDefinitions(std::vector<ValueList> &LateResolvers,
45 std::vector<ValueList> *FutureLateResolvers = 0);
47 static struct PerModuleInfo {
48 Module *CurrentModule;
49 std::vector<ValueList> Values; // Module level numbered definitions
50 std::vector<ValueList> LateResolveValues;
51 std::vector<PATypeHolder> Types;
52 std::map<ValID, PATypeHolder> LateResolveTypes;
54 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
55 // references to global values. Global values may be referenced before they
56 // are defined, and if so, the temporary object that they represent is held
57 // here. This is used for forward references of ConstantPointerRefs.
59 typedef std::map<std::pair<const PointerType *,
60 ValID>, GlobalVariable*> GlobalRefsType;
61 GlobalRefsType GlobalRefs;
64 // If we could not resolve some functions at function compilation time
65 // (calls to functions before they are defined), resolve them now... Types
66 // are resolved when the constant pool has been completely parsed.
68 ResolveDefinitions(LateResolveValues);
70 // Check to make sure that all global value forward references have been
73 if (!GlobalRefs.empty()) {
74 std::string UndefinedReferences = "Unresolved global references exist:\n";
76 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
78 UndefinedReferences += " " + I->first.first->getDescription() + " " +
79 I->first.second.getName() + "\n";
81 ThrowException(UndefinedReferences);
84 Values.clear(); // Clear out function local definitions
90 // DeclareNewGlobalValue - Called every time a new GV has been defined. This
91 // is used to remove things from the forward declaration map, resolving them
92 // to the correct thing as needed.
94 void DeclareNewGlobalValue(GlobalValue *GV, ValID D) {
95 // Check to see if there is a forward reference to this global variable...
96 // if there is, eliminate it and patch the reference to use the new def'n.
97 GlobalRefsType::iterator I =
98 GlobalRefs.find(std::make_pair(GV->getType(), D));
100 if (I != GlobalRefs.end()) {
101 GlobalVariable *OldGV = I->second; // Get the placeholder...
102 I->first.second.destroy(); // Free string memory if necessary
104 // Loop over all of the uses of the GlobalValue. The only thing they are
105 // allowed to be is ConstantPointerRef's.
106 assert(OldGV->use_size() == 1 && "Only one reference should exist!");
107 User *U = OldGV->use_back(); // Must be a ConstantPointerRef...
108 ConstantPointerRef *CPR = cast<ConstantPointerRef>(U);
110 // Change the const pool reference to point to the real global variable
111 // now. This should drop a use from the OldGV.
112 CPR->mutateReferences(OldGV, GV);
113 assert(OldGV->use_empty() && "All uses should be gone now!");
115 // Remove OldGV from the module...
116 CurrentModule->getGlobalList().remove(OldGV);
117 delete OldGV; // Delete the old placeholder
119 // Remove the map entry for the global now that it has been created...
126 static struct PerFunctionInfo {
127 Function *CurrentFunction; // Pointer to current function being created
129 std::vector<ValueList> Values; // Keep track of numbered definitions
130 std::vector<ValueList> LateResolveValues;
131 std::vector<PATypeHolder> Types;
132 std::map<ValID, PATypeHolder> LateResolveTypes;
133 bool isDeclare; // Is this function a forward declararation?
135 inline PerFunctionInfo() {
140 inline ~PerFunctionInfo() {}
142 inline void FunctionStart(Function *M) {
146 void FunctionDone() {
147 // If we could not resolve some blocks at parsing time (forward branches)
148 // resolve the branches now...
149 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
151 // Make sure to resolve any constant expr references that might exist within
152 // the function we just declared itself.
154 if (CurrentFunction->hasName()) {
155 FID = ValID::create((char*)CurrentFunction->getName().c_str());
157 unsigned Slot = CurrentFunction->getType()->getUniqueID();
158 assert(CurModule.Values.size() > Slot && "Function not inserted?");
159 // Figure out which slot number if is...
160 for (unsigned i = 0; ; ++i) {
161 assert(i < CurModule.Values[Slot].size() && "Function not found!");
162 if (CurModule.Values[Slot][i] == CurrentFunction) {
163 FID = ValID::create((int)i);
168 CurModule.DeclareNewGlobalValue(CurrentFunction, FID);
170 Values.clear(); // Clear out function local definitions
175 } CurMeth; // Info for the current function...
177 static bool inFunctionScope() { return CurMeth.CurrentFunction != 0; }
180 //===----------------------------------------------------------------------===//
181 // Code to handle definitions of all the types
182 //===----------------------------------------------------------------------===//
184 static int InsertValue(Value *D,
185 std::vector<ValueList> &ValueTab = CurMeth.Values) {
186 if (D->hasName()) return -1; // Is this a numbered definition?
188 // Yes, insert the value into the value table...
189 unsigned type = D->getType()->getUniqueID();
190 if (ValueTab.size() <= type)
191 ValueTab.resize(type+1, ValueList());
192 //printf("Values[%d][%d] = %d\n", type, ValueTab[type].size(), D);
193 ValueTab[type].push_back(D);
194 return ValueTab[type].size()-1;
197 // TODO: FIXME when Type are not const
198 static void InsertType(const Type *Ty, std::vector<PATypeHolder> &Types) {
202 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
204 case ValID::NumberVal: { // Is it a numbered definition?
205 unsigned Num = (unsigned)D.Num;
207 // Module constants occupy the lowest numbered slots...
208 if (Num < CurModule.Types.size())
209 return CurModule.Types[Num];
211 Num -= CurModule.Types.size();
213 // Check that the number is within bounds...
214 if (Num <= CurMeth.Types.size())
215 return CurMeth.Types[Num];
218 case ValID::NameVal: { // Is it a named definition?
219 std::string Name(D.Name);
220 SymbolTable *SymTab = 0;
222 if (inFunctionScope()) {
223 SymTab = &CurMeth.CurrentFunction->getSymbolTable();
224 N = SymTab->lookup(Type::TypeTy, Name);
228 // Symbol table doesn't automatically chain yet... because the function
229 // hasn't been added to the module...
231 SymTab = &CurModule.CurrentModule->getSymbolTable();
232 N = SymTab->lookup(Type::TypeTy, Name);
236 D.destroy(); // Free old strdup'd memory...
237 return cast<Type>(N);
240 ThrowException("Internal parser error: Invalid symbol type reference!");
243 // If we reached here, we referenced either a symbol that we don't know about
244 // or an id number that hasn't been read yet. We may be referencing something
245 // forward, so just create an entry to be resolved later and get to it...
247 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
249 std::map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ?
250 CurMeth.LateResolveTypes : CurModule.LateResolveTypes;
252 std::map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
253 if (I != LateResolver.end()) {
257 Type *Typ = OpaqueType::get();
258 LateResolver.insert(std::make_pair(D, Typ));
262 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
263 SymbolTable &SymTab =
264 inFunctionScope() ? CurMeth.CurrentFunction->getSymbolTable() :
265 CurModule.CurrentModule->getSymbolTable();
266 return SymTab.lookup(Ty, Name);
269 // getValNonImprovising - Look up the value specified by the provided type and
270 // the provided ValID. If the value exists and has already been defined, return
271 // it. Otherwise return null.
273 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
274 if (isa<FunctionType>(Ty))
275 ThrowException("Functions are not values and "
276 "must be referenced as pointers");
279 case ValID::NumberVal: { // Is it a numbered definition?
280 unsigned type = Ty->getUniqueID();
281 unsigned Num = (unsigned)D.Num;
283 // Module constants occupy the lowest numbered slots...
284 if (type < CurModule.Values.size()) {
285 if (Num < CurModule.Values[type].size())
286 return CurModule.Values[type][Num];
288 Num -= CurModule.Values[type].size();
291 // Make sure that our type is within bounds
292 if (CurMeth.Values.size() <= type) return 0;
294 // Check that the number is within bounds...
295 if (CurMeth.Values[type].size() <= Num) return 0;
297 return CurMeth.Values[type][Num];
300 case ValID::NameVal: { // Is it a named definition?
301 Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
302 if (N == 0) return 0;
304 D.destroy(); // Free old strdup'd memory...
308 // Check to make sure that "Ty" is an integral type, and that our
309 // value will fit into the specified type...
310 case ValID::ConstSIntVal: // Is it a constant pool reference??
311 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64))
312 ThrowException("Signed integral constant '" +
313 itostr(D.ConstPool64) + "' is invalid for type '" +
314 Ty->getDescription() + "'!");
315 return ConstantSInt::get(Ty, D.ConstPool64);
317 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
318 if (!ConstantUInt::isValueValidForType(Ty, D.UConstPool64)) {
319 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64)) {
320 ThrowException("Integral constant '" + utostr(D.UConstPool64) +
321 "' is invalid or out of range!");
322 } else { // This is really a signed reference. Transmogrify.
323 return ConstantSInt::get(Ty, D.ConstPool64);
326 return ConstantUInt::get(Ty, D.UConstPool64);
329 case ValID::ConstFPVal: // Is it a floating point const pool reference?
330 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
331 ThrowException("FP constant invalid for type!!");
332 return ConstantFP::get(Ty, D.ConstPoolFP);
334 case ValID::ConstNullVal: // Is it a null value?
335 if (!isa<PointerType>(Ty))
336 ThrowException("Cannot create a a non pointer null!");
337 return ConstantPointerNull::get(cast<PointerType>(Ty));
339 case ValID::ConstantVal: // Fully resolved constant?
340 if (D.ConstantValue->getType() != Ty)
341 ThrowException("Constant expression type different from required type!");
342 return D.ConstantValue;
345 assert(0 && "Unhandled case!");
349 assert(0 && "Unhandled case!");
354 // getVal - This function is identical to getValNonImprovising, except that if a
355 // value is not already defined, it "improvises" by creating a placeholder var
356 // that looks and acts just like the requested variable. When the value is
357 // defined later, all uses of the placeholder variable are replaced with the
360 static Value *getVal(const Type *Ty, const ValID &D) {
361 assert(Ty != Type::TypeTy && "Should use getTypeVal for types!");
363 // See if the value has already been defined...
364 Value *V = getValNonImprovising(Ty, D);
367 // If we reached here, we referenced either a symbol that we don't know about
368 // or an id number that hasn't been read yet. We may be referencing something
369 // forward, so just create an entry to be resolved later and get to it...
372 switch (Ty->getPrimitiveID()) {
373 case Type::LabelTyID: d = new BBPlaceHolder(Ty, D); break;
374 default: d = new ValuePlaceHolder(Ty, D); break;
377 assert(d != 0 && "How did we not make something?");
378 if (inFunctionScope())
379 InsertValue(d, CurMeth.LateResolveValues);
381 InsertValue(d, CurModule.LateResolveValues);
386 //===----------------------------------------------------------------------===//
387 // Code to handle forward references in instructions
388 //===----------------------------------------------------------------------===//
390 // This code handles the late binding needed with statements that reference
391 // values not defined yet... for example, a forward branch, or the PHI node for
394 // This keeps a table (CurMeth.LateResolveValues) of all such forward references
395 // and back patchs after we are done.
398 // ResolveDefinitions - If we could not resolve some defs at parsing
399 // time (forward branches, phi functions for loops, etc...) resolve the
402 static void ResolveDefinitions(std::vector<ValueList> &LateResolvers,
403 std::vector<ValueList> *FutureLateResolvers) {
404 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
405 for (unsigned ty = 0; ty < LateResolvers.size(); ty++) {
406 while (!LateResolvers[ty].empty()) {
407 Value *V = LateResolvers[ty].back();
408 assert(!isa<Type>(V) && "Types should be in LateResolveTypes!");
410 LateResolvers[ty].pop_back();
411 ValID &DID = getValIDFromPlaceHolder(V);
413 Value *TheRealValue = getValNonImprovising(Type::getUniqueIDType(ty),DID);
415 V->replaceAllUsesWith(TheRealValue);
417 } else if (FutureLateResolvers) {
418 // Functions have their unresolved items forwarded to the module late
420 InsertValue(V, *FutureLateResolvers);
422 if (DID.Type == ValID::NameVal)
423 ThrowException("Reference to an invalid definition: '" +DID.getName()+
424 "' of type '" + V->getType()->getDescription() + "'",
425 getLineNumFromPlaceHolder(V));
427 ThrowException("Reference to an invalid definition: #" +
428 itostr(DID.Num) + " of type '" +
429 V->getType()->getDescription() + "'",
430 getLineNumFromPlaceHolder(V));
435 LateResolvers.clear();
438 // ResolveTypeTo - A brand new type was just declared. This means that (if
439 // name is not null) things referencing Name can be resolved. Otherwise, things
440 // refering to the number can be resolved. Do this now.
442 static void ResolveTypeTo(char *Name, const Type *ToTy) {
443 std::vector<PATypeHolder> &Types = inFunctionScope() ?
444 CurMeth.Types : CurModule.Types;
447 if (Name) D = ValID::create(Name);
448 else D = ValID::create((int)Types.size());
450 std::map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ?
451 CurMeth.LateResolveTypes : CurModule.LateResolveTypes;
453 std::map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
454 if (I != LateResolver.end()) {
455 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
456 LateResolver.erase(I);
460 // ResolveTypes - At this point, all types should be resolved. Any that aren't
463 static void ResolveTypes(std::map<ValID, PATypeHolder> &LateResolveTypes) {
464 if (!LateResolveTypes.empty()) {
465 const ValID &DID = LateResolveTypes.begin()->first;
467 if (DID.Type == ValID::NameVal)
468 ThrowException("Reference to an invalid type: '" +DID.getName() + "'");
470 ThrowException("Reference to an invalid type: #" + itostr(DID.Num));
475 // setValueName - Set the specified value to the name given. The name may be
476 // null potentially, in which case this is a noop. The string passed in is
477 // assumed to be a malloc'd string buffer, and is freed by this function.
479 // This function returns true if the value has already been defined, but is
480 // allowed to be redefined in the specified context. If the name is a new name
481 // for the typeplane, false is returned.
483 static bool setValueName(Value *V, char *NameStr) {
484 if (NameStr == 0) return false;
486 std::string Name(NameStr); // Copy string
487 free(NameStr); // Free old string
489 if (V->getType() == Type::VoidTy)
490 ThrowException("Can't assign name '" + Name +
491 "' to a null valued instruction!");
493 SymbolTable &ST = inFunctionScope() ?
494 CurMeth.CurrentFunction->getSymbolTable() :
495 CurModule.CurrentModule->getSymbolTable();
497 Value *Existing = ST.lookup(V->getType(), Name);
498 if (Existing) { // Inserting a name that is already defined???
499 // There is only one case where this is allowed: when we are refining an
500 // opaque type. In this case, Existing will be an opaque type.
501 if (const Type *Ty = dyn_cast<Type>(Existing)) {
502 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Ty)) {
503 // We ARE replacing an opaque type!
504 ((OpaqueType*)OpTy)->refineAbstractTypeTo(cast<Type>(V));
509 // Otherwise, we are a simple redefinition of a value, check to see if it
510 // is defined the same as the old one...
511 if (const Type *Ty = dyn_cast<Type>(Existing)) {
512 if (Ty == cast<Type>(V)) return true; // Yes, it's equal.
513 // std::cerr << "Type: " << Ty->getDescription() << " != "
514 // << cast<Type>(V)->getDescription() << "!\n";
515 } else if (const Constant *C = dyn_cast<Constant>(Existing)) {
516 if (C == V) return true; // Constants are equal to themselves
517 } else if (GlobalVariable *EGV = dyn_cast<GlobalVariable>(Existing)) {
518 // We are allowed to redefine a global variable in two circumstances:
519 // 1. If at least one of the globals is uninitialized or
520 // 2. If both initializers have the same value.
522 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
523 if (!EGV->hasInitializer() || !GV->hasInitializer() ||
524 EGV->getInitializer() == GV->getInitializer()) {
526 // Make sure the existing global version gets the initializer! Make
527 // sure that it also gets marked const if the new version is.
528 if (GV->hasInitializer() && !EGV->hasInitializer())
529 EGV->setInitializer(GV->getInitializer());
530 if (GV->isConstant())
531 EGV->setConstant(true);
532 EGV->setLinkage(GV->getLinkage());
534 delete GV; // Destroy the duplicate!
535 return true; // They are equivalent!
539 ThrowException("Redefinition of value named '" + Name + "' in the '" +
540 V->getType()->getDescription() + "' type plane!");
543 V->setName(Name, &ST);
548 //===----------------------------------------------------------------------===//
549 // Code for handling upreferences in type names...
552 // TypeContains - Returns true if Ty contains E in it.
554 static bool TypeContains(const Type *Ty, const Type *E) {
555 return find(df_begin(Ty), df_end(Ty), E) != df_end(Ty);
559 static std::vector<std::pair<unsigned, OpaqueType *> > UpRefs;
561 static PATypeHolder HandleUpRefs(const Type *ty) {
563 UR_OUT("Type '" << ty->getDescription() <<
564 "' newly formed. Resolving upreferences.\n" <<
565 UpRefs.size() << " upreferences active!\n");
566 for (unsigned i = 0; i < UpRefs.size(); ) {
567 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
568 << UpRefs[i].second->getDescription() << ") = "
569 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << endl);
570 if (TypeContains(Ty, UpRefs[i].second)) {
571 unsigned Level = --UpRefs[i].first; // Decrement level of upreference
572 UR_OUT(" Uplevel Ref Level = " << Level << endl);
573 if (Level == 0) { // Upreference should be resolved!
574 UR_OUT(" * Resolving upreference for "
575 << UpRefs[i].second->getDescription() << endl;
576 std::string OldName = UpRefs[i].second->getDescription());
577 UpRefs[i].second->refineAbstractTypeTo(Ty);
578 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
579 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
580 << (const void*)Ty << ", " << Ty->getDescription() << endl);
585 ++i; // Otherwise, no resolve, move on...
587 // FIXME: TODO: this should return the updated type
592 //===----------------------------------------------------------------------===//
593 // RunVMAsmParser - Define an interface to this parser
594 //===----------------------------------------------------------------------===//
596 Module *RunVMAsmParser(const std::string &Filename, FILE *F) {
598 CurFilename = Filename;
599 llvmAsmlineno = 1; // Reset the current line number...
601 // Allocate a new module to read
602 CurModule.CurrentModule = new Module(Filename);
603 yyparse(); // Parse the file.
604 Module *Result = ParserResult;
605 llvmAsmin = stdin; // F is about to go away, don't use it anymore...
615 Function *FunctionVal;
616 std::pair<PATypeHolder*, char*> *ArgVal;
617 BasicBlock *BasicBlockVal;
618 TerminatorInst *TermInstVal;
619 Instruction *InstVal;
622 const Type *PrimType;
623 PATypeHolder *TypeVal;
626 std::vector<std::pair<PATypeHolder*,char*> > *ArgList;
627 std::vector<Value*> *ValueList;
628 std::list<PATypeHolder> *TypeList;
629 std::list<std::pair<Value*,
630 BasicBlock*> > *PHIList; // Represent the RHS of PHI node
631 std::vector<std::pair<Constant*, BasicBlock*> > *JumpTable;
632 std::vector<Constant*> *ConstVector;
634 GlobalValue::LinkageTypes Linkage;
642 char *StrVal; // This memory is strdup'd!
643 ValID ValIDVal; // strdup'd memory maybe!
645 Instruction::BinaryOps BinaryOpVal;
646 Instruction::TermOps TermOpVal;
647 Instruction::MemoryOps MemOpVal;
648 Instruction::OtherOps OtherOpVal;
649 Module::Endianness Endianness;
652 %type <ModuleVal> Module FunctionList
653 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
654 %type <BasicBlockVal> BasicBlock InstructionList
655 %type <TermInstVal> BBTerminatorInst
656 %type <InstVal> Inst InstVal MemoryInst
657 %type <ConstVal> ConstVal ConstExpr
658 %type <ConstVector> ConstVector
659 %type <ArgList> ArgList ArgListH
660 %type <ArgVal> ArgVal
661 %type <PHIList> PHIList
662 %type <ValueList> ValueRefList ValueRefListE // For call param lists
663 %type <ValueList> IndexList // For GEP derived indices
664 %type <TypeList> TypeListI ArgTypeListI
665 %type <JumpTable> JumpTable
666 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
667 %type <BoolVal> OptVolatile // 'volatile' or not
668 %type <Linkage> OptLinkage
669 %type <Endianness> BigOrLittle
671 // ValueRef - Unresolved reference to a definition or BB
672 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
673 %type <ValueVal> ResolvedVal // <type> <valref> pair
674 // Tokens and types for handling constant integer values
676 // ESINT64VAL - A negative number within long long range
677 %token <SInt64Val> ESINT64VAL
679 // EUINT64VAL - A positive number within uns. long long range
680 %token <UInt64Val> EUINT64VAL
681 %type <SInt64Val> EINT64VAL
683 %token <SIntVal> SINTVAL // Signed 32 bit ints...
684 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
685 %type <SIntVal> INTVAL
686 %token <FPVal> FPVAL // Float or Double constant
689 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
690 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
691 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
692 %token <PrimType> FLOAT DOUBLE TYPE LABEL
694 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
695 %type <StrVal> Name OptName OptAssign
698 %token IMPLEMENTATION ZEROINITIALIZER TRUE FALSE BEGINTOK ENDTOK
699 %token DECLARE GLOBAL CONSTANT VOLATILE
700 %token TO EXCEPT DOTDOTDOT NULL_TOK CONST INTERNAL LINKONCE APPENDING
701 %token OPAQUE NOT EXTERNAL TARGET ENDIAN POINTERSIZE LITTLE BIG
703 // Basic Block Terminating Operators
704 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND
707 %type <BinaryOpVal> BinaryOps // all the binary operators
708 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
709 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
710 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comarators
712 // Memory Instructions
713 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
716 %type <OtherOpVal> ShiftOps
717 %token <OtherOpVal> PHI CALL CAST SHL SHR VA_ARG
722 // Handle constant integer size restriction and conversion...
726 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
727 ThrowException("Value too large for type!");
732 EINT64VAL : ESINT64VAL; // These have same type and can't cause problems...
733 EINT64VAL : EUINT64VAL {
734 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
735 ThrowException("Value too large for type!");
739 // Operations that are notably excluded from this list include:
740 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
742 ArithmeticOps: ADD | SUB | MUL | DIV | REM;
743 LogicalOps : AND | OR | XOR;
744 SetCondOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
745 BinaryOps : ArithmeticOps | LogicalOps | SetCondOps;
747 ShiftOps : SHL | SHR;
749 // These are some types that allow classification if we only want a particular
750 // thing... for example, only a signed, unsigned, or integral type.
751 SIntType : LONG | INT | SHORT | SBYTE;
752 UIntType : ULONG | UINT | USHORT | UBYTE;
753 IntType : SIntType | UIntType;
754 FPType : FLOAT | DOUBLE;
756 // OptAssign - Value producing statements have an optional assignment component
757 OptAssign : Name '=' {
764 OptLinkage : INTERNAL { $$ = GlobalValue::InternalLinkage; } |
765 LINKONCE { $$ = GlobalValue::LinkOnceLinkage; } |
766 APPENDING { $$ = GlobalValue::AppendingLinkage; } |
767 /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
769 //===----------------------------------------------------------------------===//
770 // Types includes all predefined types... except void, because it can only be
771 // used in specific contexts (function returning void for example). To have
772 // access to it, a user must explicitly use TypesV.
775 // TypesV includes all of 'Types', but it also includes the void type.
776 TypesV : Types | VOID { $$ = new PATypeHolder($1); };
777 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
781 ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
786 // Derived types are added later...
788 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT ;
789 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL;
791 $$ = new PATypeHolder(OpaqueType::get());
794 $$ = new PATypeHolder($1);
796 UpRTypes : SymbolicValueRef { // Named types are also simple types...
797 $$ = new PATypeHolder(getTypeVal($1));
800 // Include derived types in the Types production.
802 UpRTypes : '\\' EUINT64VAL { // Type UpReference
803 if ($2 > (uint64_t)INT64_MAX) ThrowException("Value out of range!");
804 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
805 UpRefs.push_back(std::make_pair((unsigned)$2, OT)); // Add to vector...
806 $$ = new PATypeHolder(OT);
807 UR_OUT("New Upreference!\n");
809 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
810 std::vector<const Type*> Params;
811 mapto($3->begin(), $3->end(), std::back_inserter(Params),
812 std::mem_fun_ref(&PATypeHandle::get));
813 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
814 if (isVarArg) Params.pop_back();
816 $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
817 delete $3; // Delete the argument list
818 delete $1; // Delete the old type handle
820 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
821 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
824 | '{' TypeListI '}' { // Structure type?
825 std::vector<const Type*> Elements;
826 mapto($2->begin(), $2->end(), std::back_inserter(Elements),
827 std::mem_fun_ref(&PATypeHandle::get));
829 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
832 | '{' '}' { // Empty structure type?
833 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
835 | UpRTypes '*' { // Pointer type?
836 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
840 // TypeList - Used for struct declarations and as a basis for function type
841 // declaration type lists
843 TypeListI : UpRTypes {
844 $$ = new std::list<PATypeHolder>();
845 $$->push_back(*$1); delete $1;
847 | TypeListI ',' UpRTypes {
848 ($$=$1)->push_back(*$3); delete $3;
851 // ArgTypeList - List of types for a function type declaration...
852 ArgTypeListI : TypeListI
853 | TypeListI ',' DOTDOTDOT {
854 ($$=$1)->push_back(Type::VoidTy);
857 ($$ = new std::list<PATypeHolder>())->push_back(Type::VoidTy);
860 $$ = new std::list<PATypeHolder>();
863 // ConstVal - The various declarations that go into the constant pool. This
864 // production is used ONLY to represent constants that show up AFTER a 'const',
865 // 'constant' or 'global' token at global scope. Constants that can be inlined
866 // into other expressions (such as integers and constexprs) are handled by the
867 // ResolvedVal, ValueRef and ConstValueRef productions.
869 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
870 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
872 ThrowException("Cannot make array constant with type: '" +
873 (*$1)->getDescription() + "'!");
874 const Type *ETy = ATy->getElementType();
875 int NumElements = ATy->getNumElements();
877 // Verify that we have the correct size...
878 if (NumElements != -1 && NumElements != (int)$3->size())
879 ThrowException("Type mismatch: constant sized array initialized with " +
880 utostr($3->size()) + " arguments, but has size of " +
881 itostr(NumElements) + "!");
883 // Verify all elements are correct type!
884 for (unsigned i = 0; i < $3->size(); i++) {
885 if (ETy != (*$3)[i]->getType())
886 ThrowException("Element #" + utostr(i) + " is not of type '" +
887 ETy->getDescription() +"' as required!\nIt is of type '"+
888 (*$3)[i]->getType()->getDescription() + "'.");
891 $$ = ConstantArray::get(ATy, *$3);
892 delete $1; delete $3;
895 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
897 ThrowException("Cannot make array constant with type: '" +
898 (*$1)->getDescription() + "'!");
900 int NumElements = ATy->getNumElements();
901 if (NumElements != -1 && NumElements != 0)
902 ThrowException("Type mismatch: constant sized array initialized with 0"
903 " arguments, but has size of " + itostr(NumElements) +"!");
904 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
907 | Types 'c' STRINGCONSTANT {
908 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
910 ThrowException("Cannot make array constant with type: '" +
911 (*$1)->getDescription() + "'!");
913 int NumElements = ATy->getNumElements();
914 const Type *ETy = ATy->getElementType();
915 char *EndStr = UnEscapeLexed($3, true);
916 if (NumElements != -1 && NumElements != (EndStr-$3))
917 ThrowException("Can't build string constant of size " +
918 itostr((int)(EndStr-$3)) +
919 " when array has size " + itostr(NumElements) + "!");
920 std::vector<Constant*> Vals;
921 if (ETy == Type::SByteTy) {
922 for (char *C = $3; C != EndStr; ++C)
923 Vals.push_back(ConstantSInt::get(ETy, *C));
924 } else if (ETy == Type::UByteTy) {
925 for (char *C = $3; C != EndStr; ++C)
926 Vals.push_back(ConstantUInt::get(ETy, (unsigned char)*C));
929 ThrowException("Cannot build string arrays of non byte sized elements!");
932 $$ = ConstantArray::get(ATy, Vals);
935 | Types '{' ConstVector '}' {
936 const StructType *STy = dyn_cast<StructType>($1->get());
938 ThrowException("Cannot make struct constant with type: '" +
939 (*$1)->getDescription() + "'!");
941 if ($3->size() != STy->getNumContainedTypes())
942 ThrowException("Illegal number of initializers for structure type!");
944 // Check to ensure that constants are compatible with the type initializer!
945 for (unsigned i = 0, e = $3->size(); i != e; ++i)
946 if ((*$3)[i]->getType() != STy->getElementTypes()[i])
947 ThrowException("Expected type '" +
948 STy->getElementTypes()[i]->getDescription() +
949 "' for element #" + utostr(i) +
950 " of structure initializer!");
952 $$ = ConstantStruct::get(STy, *$3);
953 delete $1; delete $3;
956 const StructType *STy = dyn_cast<StructType>($1->get());
958 ThrowException("Cannot make struct constant with type: '" +
959 (*$1)->getDescription() + "'!");
961 if (STy->getNumContainedTypes() != 0)
962 ThrowException("Illegal number of initializers for structure type!");
964 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
968 const PointerType *PTy = dyn_cast<PointerType>($1->get());
970 ThrowException("Cannot make null pointer constant with type: '" +
971 (*$1)->getDescription() + "'!");
973 $$ = ConstantPointerNull::get(PTy);
976 | Types SymbolicValueRef {
977 const PointerType *Ty = dyn_cast<PointerType>($1->get());
979 ThrowException("Global const reference must be a pointer type!");
981 // ConstExprs can exist in the body of a function, thus creating
982 // ConstantPointerRefs whenever they refer to a variable. Because we are in
983 // the context of a function, getValNonImprovising will search the functions
984 // symbol table instead of the module symbol table for the global symbol,
985 // which throws things all off. To get around this, we just tell
986 // getValNonImprovising that we are at global scope here.
988 Function *SavedCurFn = CurMeth.CurrentFunction;
989 CurMeth.CurrentFunction = 0;
991 Value *V = getValNonImprovising(Ty, $2);
993 CurMeth.CurrentFunction = SavedCurFn;
995 // If this is an initializer for a constant pointer, which is referencing a
996 // (currently) undefined variable, create a stub now that shall be replaced
997 // in the future with the right type of variable.
1000 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1001 const PointerType *PT = cast<PointerType>(Ty);
1003 // First check to see if the forward references value is already created!
1004 PerModuleInfo::GlobalRefsType::iterator I =
1005 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1007 if (I != CurModule.GlobalRefs.end()) {
1008 V = I->second; // Placeholder already exists, use it...
1010 // TODO: Include line number info by creating a subclass of
1011 // TODO: GlobalVariable here that includes the said information!
1013 // Create a placeholder for the global variable reference...
1014 GlobalVariable *GV = new GlobalVariable(PT->getElementType(),
1016 GlobalValue::ExternalLinkage);
1017 // Keep track of the fact that we have a forward ref to recycle it
1018 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1020 // Must temporarily push this value into the module table...
1021 CurModule.CurrentModule->getGlobalList().push_back(GV);
1026 GlobalValue *GV = cast<GlobalValue>(V);
1027 $$ = ConstantPointerRef::get(GV);
1028 delete $1; // Free the type handle
1031 if ($1->get() != $2->getType())
1032 ThrowException("Mismatched types for constant expression!");
1036 | Types ZEROINITIALIZER {
1037 $$ = Constant::getNullValue($1->get());
1041 ConstVal : SIntType EINT64VAL { // integral constants
1042 if (!ConstantSInt::isValueValidForType($1, $2))
1043 ThrowException("Constant value doesn't fit in type!");
1044 $$ = ConstantSInt::get($1, $2);
1046 | UIntType EUINT64VAL { // integral constants
1047 if (!ConstantUInt::isValueValidForType($1, $2))
1048 ThrowException("Constant value doesn't fit in type!");
1049 $$ = ConstantUInt::get($1, $2);
1051 | BOOL TRUE { // Boolean constants
1052 $$ = ConstantBool::True;
1054 | BOOL FALSE { // Boolean constants
1055 $$ = ConstantBool::False;
1057 | FPType FPVAL { // Float & Double constants
1058 $$ = ConstantFP::get($1, $2);
1062 ConstExpr: CAST '(' ConstVal TO Types ')' {
1063 $$ = ConstantExpr::getCast($3, $5->get());
1066 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1067 if (!isa<PointerType>($3->getType()))
1068 ThrowException("GetElementPtr requires a pointer operand!");
1071 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1073 ThrowException("Index list invalid for constant getelementptr!");
1075 std::vector<Constant*> IdxVec;
1076 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1077 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1078 IdxVec.push_back(C);
1080 ThrowException("Indices to constant getelementptr must be constants!");
1084 $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1086 | BinaryOps '(' ConstVal ',' ConstVal ')' {
1087 if ($3->getType() != $5->getType())
1088 ThrowException("Binary operator types must match!");
1089 $$ = ConstantExpr::get($1, $3, $5);
1091 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1092 if ($5->getType() != Type::UByteTy)
1093 ThrowException("Shift count for shift constant must be unsigned byte!");
1094 if (!$3->getType()->isIntegral())
1095 ThrowException("Shift constant expression requires integral operand!");
1096 $$ = ConstantExpr::getShift($1, $3, $5);
1100 // ConstVector - A list of comma separated constants.
1101 ConstVector : ConstVector ',' ConstVal {
1102 ($$ = $1)->push_back($3);
1105 $$ = new std::vector<Constant*>();
1110 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1111 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1114 //===----------------------------------------------------------------------===//
1115 // Rules to match Modules
1116 //===----------------------------------------------------------------------===//
1118 // Module rule: Capture the result of parsing the whole file into a result
1121 Module : FunctionList {
1122 $$ = ParserResult = $1;
1123 CurModule.ModuleDone();
1126 // FunctionList - A list of functions, preceeded by a constant pool.
1128 FunctionList : FunctionList Function {
1130 assert($2->getParent() == 0 && "Function already in module!");
1131 $1->getFunctionList().push_back($2);
1132 CurMeth.FunctionDone();
1134 | FunctionList FunctionProto {
1137 | FunctionList IMPLEMENTATION {
1141 $$ = CurModule.CurrentModule;
1142 // Resolve circular types before we parse the body of the module
1143 ResolveTypes(CurModule.LateResolveTypes);
1146 // ConstPool - Constants with optional names assigned to them.
1147 ConstPool : ConstPool OptAssign CONST ConstVal {
1148 if (!setValueName($4, $2))
1151 | ConstPool OptAssign TYPE TypesV { // Types can be defined in the const pool
1152 // Eagerly resolve types. This is not an optimization, this is a
1153 // requirement that is due to the fact that we could have this:
1155 // %list = type { %list * }
1156 // %list = type { %list * } ; repeated type decl
1158 // If types are not resolved eagerly, then the two types will not be
1159 // determined to be the same type!
1161 ResolveTypeTo($2, $4->get());
1163 // TODO: FIXME when Type are not const
1164 if (!setValueName(const_cast<Type*>($4->get()), $2)) {
1165 // If this is not a redefinition of a type...
1167 InsertType($4->get(),
1168 inFunctionScope() ? CurMeth.Types : CurModule.Types);
1174 | ConstPool FunctionProto { // Function prototypes can be in const pool
1176 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
1177 const Type *Ty = $5->getType();
1178 // Global declarations appear in Constant Pool
1179 Constant *Initializer = $5;
1180 if (Initializer == 0)
1181 ThrowException("Global value initializer is not a constant!");
1183 GlobalVariable *GV = new GlobalVariable(Ty, $4, $3, Initializer);
1184 if (!setValueName(GV, $2)) { // If not redefining...
1185 CurModule.CurrentModule->getGlobalList().push_back(GV);
1186 int Slot = InsertValue(GV, CurModule.Values);
1189 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1191 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1192 (char*)GV->getName().c_str()));
1196 | ConstPool OptAssign EXTERNAL GlobalType Types {
1197 const Type *Ty = *$5;
1198 // Global declarations appear in Constant Pool
1199 GlobalVariable *GV = new GlobalVariable(Ty,$4,GlobalValue::ExternalLinkage);
1200 if (!setValueName(GV, $2)) { // If not redefining...
1201 CurModule.CurrentModule->getGlobalList().push_back(GV);
1202 int Slot = InsertValue(GV, CurModule.Values);
1205 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1207 assert(GV->hasName() && "Not named and not numbered!?");
1208 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1209 (char*)GV->getName().c_str()));
1214 | ConstPool TARGET TargetDefinition {
1216 | /* empty: end of list */ {
1221 BigOrLittle : BIG { $$ = Module::BigEndian; };
1222 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1224 TargetDefinition : ENDIAN '=' BigOrLittle {
1225 CurModule.CurrentModule->setEndianness($3);
1227 | POINTERSIZE '=' EUINT64VAL {
1229 CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1231 CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1233 ThrowException("Invalid pointer size: '" + utostr($3) + "'!");
1237 //===----------------------------------------------------------------------===//
1238 // Rules to match Function Headers
1239 //===----------------------------------------------------------------------===//
1241 Name : VAR_ID | STRINGCONSTANT;
1242 OptName : Name | /*empty*/ { $$ = 0; };
1244 ArgVal : Types OptName {
1245 if (*$1 == Type::VoidTy)
1246 ThrowException("void typed arguments are invalid!");
1247 $$ = new std::pair<PATypeHolder*, char*>($1, $2);
1250 ArgListH : ArgListH ',' ArgVal {
1256 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1261 ArgList : ArgListH {
1264 | ArgListH ',' DOTDOTDOT {
1266 $$->push_back(std::pair<PATypeHolder*,
1267 char*>(new PATypeHolder(Type::VoidTy), 0));
1270 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1271 $$->push_back(std::make_pair(new PATypeHolder(Type::VoidTy), (char*)0));
1277 FunctionHeaderH : TypesV Name '(' ArgList ')' {
1279 std::string FunctionName($2);
1281 std::vector<const Type*> ParamTypeList;
1282 if ($4) { // If there are arguments...
1283 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $4->begin();
1284 I != $4->end(); ++I)
1285 ParamTypeList.push_back(I->first->get());
1288 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1289 if (isVarArg) ParamTypeList.pop_back();
1291 const FunctionType *FT = FunctionType::get(*$1, ParamTypeList, isVarArg);
1292 const PointerType *PFT = PointerType::get(FT);
1296 // Is the function already in symtab?
1297 if ((Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
1298 // Yes it is. If this is the case, either we need to be a forward decl,
1299 // or it needs to be.
1300 if (!CurMeth.isDeclare && !Fn->isExternal())
1301 ThrowException("Redefinition of function '" + FunctionName + "'!");
1303 // If we found a preexisting function prototype, remove it from the
1304 // module, so that we don't get spurious conflicts with global & local
1307 CurModule.CurrentModule->getFunctionList().remove(Fn);
1309 // Make sure to strip off any argument names so we can't get conflicts...
1310 for (Function::aiterator AI = Fn->abegin(), AE = Fn->aend(); AI != AE; ++AI)
1313 } else { // Not already defined?
1314 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName);
1315 InsertValue(Fn, CurModule.Values);
1316 CurModule.DeclareNewGlobalValue(Fn, ValID::create($2));
1318 free($2); // Free strdup'd memory!
1320 CurMeth.FunctionStart(Fn);
1322 // Add all of the arguments we parsed to the function...
1323 if ($4) { // Is null if empty...
1324 if (isVarArg) { // Nuke the last entry
1325 assert($4->back().first->get() == Type::VoidTy && $4->back().second == 0&&
1326 "Not a varargs marker!");
1327 delete $4->back().first;
1328 $4->pop_back(); // Delete the last entry
1330 Function::aiterator ArgIt = Fn->abegin();
1331 for (std::vector<std::pair<PATypeHolder*, char*> >::iterator I =$4->begin();
1332 I != $4->end(); ++I, ++ArgIt) {
1333 delete I->first; // Delete the typeholder...
1335 if (setValueName(ArgIt, I->second)) // Insert arg into symtab...
1336 assert(0 && "No arg redef allowed!");
1341 delete $4; // We're now done with the argument list
1345 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
1347 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
1348 $$ = CurMeth.CurrentFunction;
1350 // Make sure that we keep track of the linkage type even if there was a
1351 // previous "declare".
1354 // Resolve circular types before we parse the body of the function.
1355 ResolveTypes(CurMeth.LateResolveTypes);
1358 END : ENDTOK | '}'; // Allow end of '}' to end a function
1360 Function : BasicBlockList END {
1364 FunctionProto : DECLARE { CurMeth.isDeclare = true; } FunctionHeaderH {
1365 $$ = CurMeth.CurrentFunction;
1366 assert($$->getParent() == 0 && "Function already in module!");
1367 CurModule.CurrentModule->getFunctionList().push_back($$);
1368 CurMeth.FunctionDone();
1371 //===----------------------------------------------------------------------===//
1372 // Rules to match Basic Blocks
1373 //===----------------------------------------------------------------------===//
1375 ConstValueRef : ESINT64VAL { // A reference to a direct constant
1376 $$ = ValID::create($1);
1379 $$ = ValID::create($1);
1381 | FPVAL { // Perhaps it's an FP constant?
1382 $$ = ValID::create($1);
1385 $$ = ValID::create(ConstantBool::True);
1388 $$ = ValID::create(ConstantBool::False);
1391 $$ = ValID::createNull();
1394 $$ = ValID::create($1);
1397 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1400 SymbolicValueRef : INTVAL { // Is it an integer reference...?
1401 $$ = ValID::create($1);
1403 | Name { // Is it a named reference...?
1404 $$ = ValID::create($1);
1407 // ValueRef - A reference to a definition... either constant or symbolic
1408 ValueRef : SymbolicValueRef | ConstValueRef;
1411 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
1412 // type immediately preceeds the value reference, and allows complex constant
1413 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1414 ResolvedVal : Types ValueRef {
1415 $$ = getVal(*$1, $2); delete $1;
1418 BasicBlockList : BasicBlockList BasicBlock {
1419 ($$ = $1)->getBasicBlockList().push_back($2);
1421 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
1422 ($$ = $1)->getBasicBlockList().push_back($2);
1426 // Basic blocks are terminated by branching instructions:
1427 // br, br/cc, switch, ret
1429 BasicBlock : InstructionList OptAssign BBTerminatorInst {
1430 if (setValueName($3, $2)) { assert(0 && "No redefn allowed!"); }
1433 $1->getInstList().push_back($3);
1437 | LABELSTR InstructionList OptAssign BBTerminatorInst {
1438 if (setValueName($4, $3)) { assert(0 && "No redefn allowed!"); }
1441 $2->getInstList().push_back($4);
1442 if (setValueName($2, $1)) { assert(0 && "No label redef allowed!"); }
1448 InstructionList : InstructionList Inst {
1449 $1->getInstList().push_back($2);
1453 $$ = new BasicBlock();
1456 BBTerminatorInst : RET ResolvedVal { // Return with a result...
1457 $$ = new ReturnInst($2);
1459 | RET VOID { // Return with no result...
1460 $$ = new ReturnInst();
1462 | BR LABEL ValueRef { // Unconditional Branch...
1463 $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $3)));
1464 } // Conditional Branch...
1465 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
1466 $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $6)),
1467 cast<BasicBlock>(getVal(Type::LabelTy, $9)),
1468 getVal(Type::BoolTy, $3));
1470 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1471 SwitchInst *S = new SwitchInst(getVal($2, $3),
1472 cast<BasicBlock>(getVal(Type::LabelTy, $6)));
1475 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
1478 S->addCase(I->first, I->second);
1480 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
1481 SwitchInst *S = new SwitchInst(getVal($2, $3),
1482 cast<BasicBlock>(getVal(Type::LabelTy, $6)));
1485 | INVOKE TypesV ValueRef '(' ValueRefListE ')' TO ResolvedVal
1486 EXCEPT ResolvedVal {
1487 const PointerType *PFTy;
1488 const FunctionType *Ty;
1490 if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
1491 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1492 // Pull out the types of all of the arguments...
1493 std::vector<const Type*> ParamTypes;
1495 for (std::vector<Value*>::iterator I = $5->begin(), E = $5->end();
1497 ParamTypes.push_back((*I)->getType());
1500 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1501 if (isVarArg) ParamTypes.pop_back();
1503 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1504 PFTy = PointerType::get(Ty);
1508 Value *V = getVal(PFTy, $3); // Get the function we're calling...
1510 BasicBlock *Normal = dyn_cast<BasicBlock>($8);
1511 BasicBlock *Except = dyn_cast<BasicBlock>($10);
1513 if (Normal == 0 || Except == 0)
1514 ThrowException("Invoke instruction without label destinations!");
1516 // Create the call node...
1517 if (!$5) { // Has no arguments?
1518 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
1519 } else { // Has arguments?
1520 // Loop through FunctionType's arguments and ensure they are specified
1523 FunctionType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1524 FunctionType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
1525 std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1527 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1528 if ((*ArgI)->getType() != *I)
1529 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1530 (*I)->getDescription() + "'!");
1532 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1533 ThrowException("Invalid number of parameters detected!");
1535 $$ = new InvokeInst(V, Normal, Except, *$5);
1540 $$ = new UnwindInst();
1545 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1547 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
1549 ThrowException("May only switch on a constant pool value!");
1551 $$->push_back(std::make_pair(V, cast<BasicBlock>(getVal($5, $6))));
1553 | IntType ConstValueRef ',' LABEL ValueRef {
1554 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
1555 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
1558 ThrowException("May only switch on a constant pool value!");
1560 $$->push_back(std::make_pair(V, cast<BasicBlock>(getVal($4, $5))));
1563 Inst : OptAssign InstVal {
1564 // Is this definition named?? if so, assign the name...
1565 if (setValueName($2, $1)) { assert(0 && "No redefin allowed!"); }
1570 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
1571 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
1572 $$->push_back(std::make_pair(getVal(*$1, $3),
1573 cast<BasicBlock>(getVal(Type::LabelTy, $5))));
1576 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1578 $1->push_back(std::make_pair(getVal($1->front().first->getType(), $4),
1579 cast<BasicBlock>(getVal(Type::LabelTy, $6))));
1583 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
1584 $$ = new std::vector<Value*>();
1587 | ValueRefList ',' ResolvedVal {
1592 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1593 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
1595 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
1596 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint())
1597 ThrowException("Arithmetic operator requires integer or FP operands!");
1598 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1600 ThrowException("binary operator returned null!");
1603 | LogicalOps Types ValueRef ',' ValueRef {
1604 if (!(*$2)->isIntegral())
1605 ThrowException("Logical operator requires integral operands!");
1606 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1608 ThrowException("binary operator returned null!");
1611 | SetCondOps Types ValueRef ',' ValueRef {
1612 $$ = new SetCondInst($1, getVal(*$2, $3), getVal(*$2, $5));
1614 ThrowException("binary operator returned null!");
1618 std::cerr << "WARNING: Use of eliminated 'not' instruction:"
1619 << " Replacing with 'xor'.\n";
1621 Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
1623 ThrowException("Expected integral type for not instruction!");
1625 $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
1627 ThrowException("Could not create a xor instruction!");
1629 | ShiftOps ResolvedVal ',' ResolvedVal {
1630 if ($4->getType() != Type::UByteTy)
1631 ThrowException("Shift amount must be ubyte!");
1632 $$ = new ShiftInst($1, $2, $4);
1634 | CAST ResolvedVal TO Types {
1635 $$ = new CastInst($2, *$4);
1638 | VA_ARG ResolvedVal ',' Types {
1639 $$ = new VarArgInst($2, *$4);
1643 const Type *Ty = $2->front().first->getType();
1644 $$ = new PHINode(Ty);
1645 while ($2->begin() != $2->end()) {
1646 if ($2->front().first->getType() != Ty)
1647 ThrowException("All elements of a PHI node must be of the same type!");
1648 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
1651 delete $2; // Free the list...
1653 | CALL TypesV ValueRef '(' ValueRefListE ')' {
1654 const PointerType *PFTy;
1655 const FunctionType *Ty;
1657 if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
1658 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1659 // Pull out the types of all of the arguments...
1660 std::vector<const Type*> ParamTypes;
1662 for (std::vector<Value*>::iterator I = $5->begin(), E = $5->end();
1664 ParamTypes.push_back((*I)->getType());
1667 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1668 if (isVarArg) ParamTypes.pop_back();
1670 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1671 PFTy = PointerType::get(Ty);
1675 Value *V = getVal(PFTy, $3); // Get the function we're calling...
1677 // Create the call node...
1678 if (!$5) { // Has no arguments?
1679 // Make sure no arguments is a good thing!
1680 if (Ty->getNumParams() != 0)
1681 ThrowException("No arguments passed to a function that "
1682 "expects arguments!");
1684 $$ = new CallInst(V, std::vector<Value*>());
1685 } else { // Has arguments?
1686 // Loop through FunctionType's arguments and ensure they are specified
1689 FunctionType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1690 FunctionType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
1691 std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1693 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1694 if ((*ArgI)->getType() != *I)
1695 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1696 (*I)->getDescription() + "'!");
1698 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1699 ThrowException("Invalid number of parameters detected!");
1701 $$ = new CallInst(V, *$5);
1710 // IndexList - List of indices for GEP based instructions...
1711 IndexList : ',' ValueRefList {
1714 $$ = new std::vector<Value*>();
1717 OptVolatile : VOLATILE {
1725 MemoryInst : MALLOC Types {
1726 $$ = new MallocInst(*$2);
1729 | MALLOC Types ',' UINT ValueRef {
1730 $$ = new MallocInst(*$2, getVal($4, $5));
1734 $$ = new AllocaInst(*$2);
1737 | ALLOCA Types ',' UINT ValueRef {
1738 $$ = new AllocaInst(*$2, getVal($4, $5));
1741 | FREE ResolvedVal {
1742 if (!isa<PointerType>($2->getType()))
1743 ThrowException("Trying to free nonpointer type " +
1744 $2->getType()->getDescription() + "!");
1745 $$ = new FreeInst($2);
1748 | OptVolatile LOAD Types ValueRef {
1749 if (!isa<PointerType>($3->get()))
1750 ThrowException("Can't load from nonpointer type: " +
1751 (*$3)->getDescription());
1752 $$ = new LoadInst(getVal(*$3, $4), "", $1);
1755 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
1756 const PointerType *PT = dyn_cast<PointerType>($5->get());
1758 ThrowException("Can't store to a nonpointer type: " +
1759 (*$5)->getDescription());
1760 const Type *ElTy = PT->getElementType();
1761 if (ElTy != $3->getType())
1762 ThrowException("Can't store '" + $3->getType()->getDescription() +
1763 "' into space of type '" + ElTy->getDescription() + "'!");
1765 $$ = new StoreInst($3, getVal(*$5, $6), $1);
1768 | GETELEMENTPTR Types ValueRef IndexList {
1769 if (!isa<PointerType>($2->get()))
1770 ThrowException("getelementptr insn requires pointer operand!");
1771 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
1772 ThrowException("Can't get element ptr '" + (*$2)->getDescription()+ "'!");
1773 $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
1774 delete $2; delete $4;
1778 int yyerror(const char *ErrorMsg) {
1780 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
1781 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
1782 std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
1783 if (yychar == YYEMPTY)
1784 errMsg += "end-of-file.";
1786 errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
1787 ThrowException(errMsg);