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 "Support/STLExtras.h"
23 #include "Support/DepthFirstIterator.h"
28 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
29 int yylex(); // declaration" of xxx warnings.
34 static Module *ParserResult;
35 std::string CurFilename;
37 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
38 // relating to upreferences in the input stream.
40 //#define DEBUG_UPREFS 1
42 #define UR_OUT(X) std::cerr << X
47 #define YYERROR_VERBOSE 1
49 // HACK ALERT: This variable is used to implement the automatic conversion of
50 // variable argument instructions from their old to new forms. When this
51 // compatiblity "Feature" is removed, this should be too.
53 static BasicBlock *CurBB;
54 static bool ObsoleteVarArgs;
57 // This contains info used when building the body of a function. It is
58 // destroyed when the function is completed.
60 typedef std::vector<Value *> ValueList; // Numbered defs
61 static void ResolveDefinitions(std::vector<ValueList> &LateResolvers,
62 std::vector<ValueList> *FutureLateResolvers = 0);
64 static struct PerModuleInfo {
65 Module *CurrentModule;
66 std::vector<ValueList> Values; // Module level numbered definitions
67 std::vector<ValueList> LateResolveValues;
68 std::vector<PATypeHolder> Types;
69 std::map<ValID, PATypeHolder> LateResolveTypes;
71 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
72 // references to global values. Global values may be referenced before they
73 // are defined, and if so, the temporary object that they represent is held
74 // here. This is used for forward references of ConstantPointerRefs.
76 typedef std::map<std::pair<const PointerType *,
77 ValID>, GlobalVariable*> GlobalRefsType;
78 GlobalRefsType GlobalRefs;
81 // If we could not resolve some functions at function compilation time
82 // (calls to functions before they are defined), resolve them now... Types
83 // are resolved when the constant pool has been completely parsed.
85 ResolveDefinitions(LateResolveValues);
87 // Check to make sure that all global value forward references have been
90 if (!GlobalRefs.empty()) {
91 std::string UndefinedReferences = "Unresolved global references exist:\n";
93 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
95 UndefinedReferences += " " + I->first.first->getDescription() + " " +
96 I->first.second.getName() + "\n";
98 ThrowException(UndefinedReferences);
101 Values.clear(); // Clear out function local definitions
107 // DeclareNewGlobalValue - Called every time a new GV has been defined. This
108 // is used to remove things from the forward declaration map, resolving them
109 // to the correct thing as needed.
111 void DeclareNewGlobalValue(GlobalValue *GV, ValID D) {
112 // Check to see if there is a forward reference to this global variable...
113 // if there is, eliminate it and patch the reference to use the new def'n.
114 GlobalRefsType::iterator I =
115 GlobalRefs.find(std::make_pair(GV->getType(), D));
117 if (I != GlobalRefs.end()) {
118 GlobalVariable *OldGV = I->second; // Get the placeholder...
119 I->first.second.destroy(); // Free string memory if necessary
121 // Loop over all of the uses of the GlobalValue. The only thing they are
122 // allowed to be is ConstantPointerRef's.
123 assert(OldGV->hasOneUse() && "Only one reference should exist!");
124 User *U = OldGV->use_back(); // Must be a ConstantPointerRef...
125 ConstantPointerRef *CPR = cast<ConstantPointerRef>(U);
127 // Change the const pool reference to point to the real global variable
128 // now. This should drop a use from the OldGV.
129 CPR->mutateReferences(OldGV, GV);
130 assert(OldGV->use_empty() && "All uses should be gone now!");
132 // Remove OldGV from the module...
133 CurrentModule->getGlobalList().remove(OldGV);
134 delete OldGV; // Delete the old placeholder
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::vector<ValueList> Values; // Keep track of numbered definitions
147 std::vector<ValueList> LateResolveValues;
148 std::vector<PATypeHolder> Types;
149 std::map<ValID, PATypeHolder> LateResolveTypes;
150 SymbolTable LocalSymtab;
151 bool isDeclare; // Is this function a forward declararation?
153 inline PerFunctionInfo() {
158 inline void FunctionStart(Function *M) {
162 void FunctionDone() {
163 // If we could not resolve some blocks at parsing time (forward branches)
164 // resolve the branches now...
165 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
167 // Make sure to resolve any constant expr references that might exist within
168 // the function we just declared itself.
170 if (CurrentFunction->hasName()) {
171 FID = ValID::create((char*)CurrentFunction->getName().c_str());
173 unsigned Slot = CurrentFunction->getType()->getUniqueID();
174 assert(CurModule.Values.size() > Slot && "Function not inserted?");
175 // Figure out which slot number if is...
176 for (unsigned i = 0; ; ++i) {
177 assert(i < CurModule.Values[Slot].size() && "Function not found!");
178 if (CurModule.Values[Slot][i] == CurrentFunction) {
179 FID = ValID::create((int)i);
184 CurModule.DeclareNewGlobalValue(CurrentFunction, FID);
186 Values.clear(); // Clear out function local definitions
187 Types.clear(); // Clear out function local types
188 LocalSymtab.clear(); // Clear out function local symbol table
192 } CurFun; // Info for the current function...
194 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
197 //===----------------------------------------------------------------------===//
198 // Code to handle definitions of all the types
199 //===----------------------------------------------------------------------===//
201 static int InsertValue(Value *D,
202 std::vector<ValueList> &ValueTab = CurFun.Values) {
203 if (D->hasName()) return -1; // Is this a numbered definition?
205 // Yes, insert the value into the value table...
206 unsigned type = D->getType()->getUniqueID();
207 if (ValueTab.size() <= type)
208 ValueTab.resize(type+1, ValueList());
209 //printf("Values[%d][%d] = %d\n", type, ValueTab[type].size(), D);
210 ValueTab[type].push_back(D);
211 return ValueTab[type].size()-1;
214 // TODO: FIXME when Type are not const
215 static void InsertType(const Type *Ty, std::vector<PATypeHolder> &Types) {
219 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
221 case ValID::NumberVal: { // Is it a numbered definition?
222 unsigned Num = (unsigned)D.Num;
224 // Module constants occupy the lowest numbered slots...
225 if (Num < CurModule.Types.size())
226 return CurModule.Types[Num];
228 Num -= CurModule.Types.size();
230 // Check that the number is within bounds...
231 if (Num <= CurFun.Types.size())
232 return CurFun.Types[Num];
235 case ValID::NameVal: { // Is it a named definition?
236 std::string Name(D.Name);
237 SymbolTable *SymTab = 0;
239 if (inFunctionScope()) {
240 SymTab = &CurFun.CurrentFunction->getSymbolTable();
241 N = SymTab->lookup(Type::TypeTy, Name);
245 // Symbol table doesn't automatically chain yet... because the function
246 // hasn't been added to the module...
248 SymTab = &CurModule.CurrentModule->getSymbolTable();
249 N = SymTab->lookup(Type::TypeTy, Name);
253 D.destroy(); // Free old strdup'd memory...
254 return cast<Type>(N);
257 ThrowException("Internal parser error: Invalid symbol type reference!");
260 // If we reached here, we referenced either a symbol that we don't know about
261 // or an id number that hasn't been read yet. We may be referencing something
262 // forward, so just create an entry to be resolved later and get to it...
264 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
266 std::map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ?
267 CurFun.LateResolveTypes : CurModule.LateResolveTypes;
269 std::map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
270 if (I != LateResolver.end()) {
274 Type *Typ = OpaqueType::get();
275 LateResolver.insert(std::make_pair(D, Typ));
279 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
280 SymbolTable &SymTab =
281 inFunctionScope() ? CurFun.CurrentFunction->getSymbolTable() :
282 CurModule.CurrentModule->getSymbolTable();
283 return SymTab.lookup(Ty, Name);
286 // getValNonImprovising - Look up the value specified by the provided type and
287 // the provided ValID. If the value exists and has already been defined, return
288 // it. Otherwise return null.
290 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
291 if (isa<FunctionType>(Ty))
292 ThrowException("Functions are not values and "
293 "must be referenced as pointers");
296 case ValID::NumberVal: { // Is it a numbered definition?
297 unsigned type = Ty->getUniqueID();
298 unsigned Num = (unsigned)D.Num;
300 // Module constants occupy the lowest numbered slots...
301 if (type < CurModule.Values.size()) {
302 if (Num < CurModule.Values[type].size())
303 return CurModule.Values[type][Num];
305 Num -= CurModule.Values[type].size();
308 // Make sure that our type is within bounds
309 if (CurFun.Values.size() <= type) return 0;
311 // Check that the number is within bounds...
312 if (CurFun.Values[type].size() <= Num) return 0;
314 return CurFun.Values[type][Num];
317 case ValID::NameVal: { // Is it a named definition?
318 Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
319 if (N == 0) return 0;
321 D.destroy(); // Free old strdup'd memory...
325 // Check to make sure that "Ty" is an integral type, and that our
326 // value will fit into the specified type...
327 case ValID::ConstSIntVal: // Is it a constant pool reference??
328 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64))
329 ThrowException("Signed integral constant '" +
330 itostr(D.ConstPool64) + "' is invalid for type '" +
331 Ty->getDescription() + "'!");
332 return ConstantSInt::get(Ty, D.ConstPool64);
334 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
335 if (!ConstantUInt::isValueValidForType(Ty, D.UConstPool64)) {
336 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64)) {
337 ThrowException("Integral constant '" + utostr(D.UConstPool64) +
338 "' is invalid or out of range!");
339 } else { // This is really a signed reference. Transmogrify.
340 return ConstantSInt::get(Ty, D.ConstPool64);
343 return ConstantUInt::get(Ty, D.UConstPool64);
346 case ValID::ConstFPVal: // Is it a floating point const pool reference?
347 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
348 ThrowException("FP constant invalid for type!!");
349 return ConstantFP::get(Ty, D.ConstPoolFP);
351 case ValID::ConstNullVal: // Is it a null value?
352 if (!isa<PointerType>(Ty))
353 ThrowException("Cannot create a a non pointer null!");
354 return ConstantPointerNull::get(cast<PointerType>(Ty));
356 case ValID::ConstantVal: // Fully resolved constant?
357 if (D.ConstantValue->getType() != Ty)
358 ThrowException("Constant expression type different from required type!");
359 return D.ConstantValue;
362 assert(0 && "Unhandled case!");
366 assert(0 && "Unhandled case!");
371 // getVal - This function is identical to getValNonImprovising, except that if a
372 // value is not already defined, it "improvises" by creating a placeholder var
373 // that looks and acts just like the requested variable. When the value is
374 // defined later, all uses of the placeholder variable are replaced with the
377 static Value *getVal(const Type *Ty, const ValID &D) {
378 assert(Ty != Type::TypeTy && "Should use getTypeVal for types!");
380 // See if the value has already been defined...
381 Value *V = getValNonImprovising(Ty, D);
384 // If we reached here, we referenced either a symbol that we don't know about
385 // or an id number that hasn't been read yet. We may be referencing something
386 // forward, so just create an entry to be resolved later and get to it...
389 switch (Ty->getPrimitiveID()) {
390 case Type::LabelTyID: d = new BBPlaceHolder(Ty, D); break;
391 default: d = new ValuePlaceHolder(Ty, D); break;
394 assert(d != 0 && "How did we not make something?");
395 if (inFunctionScope())
396 InsertValue(d, CurFun.LateResolveValues);
398 InsertValue(d, CurModule.LateResolveValues);
403 //===----------------------------------------------------------------------===//
404 // Code to handle forward references in instructions
405 //===----------------------------------------------------------------------===//
407 // This code handles the late binding needed with statements that reference
408 // values not defined yet... for example, a forward branch, or the PHI node for
411 // This keeps a table (CurFun.LateResolveValues) of all such forward references
412 // and back patchs after we are done.
415 // ResolveDefinitions - If we could not resolve some defs at parsing
416 // time (forward branches, phi functions for loops, etc...) resolve the
419 static void ResolveDefinitions(std::vector<ValueList> &LateResolvers,
420 std::vector<ValueList> *FutureLateResolvers) {
421 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
422 for (unsigned ty = 0; ty < LateResolvers.size(); ty++) {
423 while (!LateResolvers[ty].empty()) {
424 Value *V = LateResolvers[ty].back();
425 assert(!isa<Type>(V) && "Types should be in LateResolveTypes!");
427 LateResolvers[ty].pop_back();
428 ValID &DID = getValIDFromPlaceHolder(V);
430 Value *TheRealValue = getValNonImprovising(Type::getUniqueIDType(ty),DID);
432 V->replaceAllUsesWith(TheRealValue);
434 } else if (FutureLateResolvers) {
435 // Functions have their unresolved items forwarded to the module late
437 InsertValue(V, *FutureLateResolvers);
439 if (DID.Type == ValID::NameVal)
440 ThrowException("Reference to an invalid definition: '" +DID.getName()+
441 "' of type '" + V->getType()->getDescription() + "'",
442 getLineNumFromPlaceHolder(V));
444 ThrowException("Reference to an invalid definition: #" +
445 itostr(DID.Num) + " of type '" +
446 V->getType()->getDescription() + "'",
447 getLineNumFromPlaceHolder(V));
452 LateResolvers.clear();
455 // ResolveTypeTo - A brand new type was just declared. This means that (if
456 // name is not null) things referencing Name can be resolved. Otherwise, things
457 // refering to the number can be resolved. Do this now.
459 static void ResolveTypeTo(char *Name, const Type *ToTy) {
460 std::vector<PATypeHolder> &Types = inFunctionScope() ?
461 CurFun.Types : CurModule.Types;
464 if (Name) D = ValID::create(Name);
465 else D = ValID::create((int)Types.size());
467 std::map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ?
468 CurFun.LateResolveTypes : CurModule.LateResolveTypes;
470 std::map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
471 if (I != LateResolver.end()) {
472 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
473 LateResolver.erase(I);
477 // ResolveTypes - At this point, all types should be resolved. Any that aren't
480 static void ResolveTypes(std::map<ValID, PATypeHolder> &LateResolveTypes) {
481 if (!LateResolveTypes.empty()) {
482 const ValID &DID = LateResolveTypes.begin()->first;
484 if (DID.Type == ValID::NameVal)
485 ThrowException("Reference to an invalid type: '" +DID.getName() + "'");
487 ThrowException("Reference to an invalid type: #" + itostr(DID.Num));
492 // setValueName - Set the specified value to the name given. The name may be
493 // null potentially, in which case this is a noop. The string passed in is
494 // assumed to be a malloc'd string buffer, and is freed by this function.
496 // This function returns true if the value has already been defined, but is
497 // allowed to be redefined in the specified context. If the name is a new name
498 // for the typeplane, false is returned.
500 static bool setValueName(Value *V, char *NameStr) {
501 if (NameStr == 0) return false;
503 std::string Name(NameStr); // Copy string
504 free(NameStr); // Free old string
506 if (V->getType() == Type::VoidTy)
507 ThrowException("Can't assign name '" + Name +
508 "' to a null valued instruction!");
510 SymbolTable &ST = inFunctionScope() ?
511 CurFun.CurrentFunction->getSymbolTable() :
512 CurModule.CurrentModule->getSymbolTable();
514 Value *Existing = ST.lookup(V->getType(), Name);
515 if (Existing) { // Inserting a name that is already defined???
516 // There is only one case where this is allowed: when we are refining an
517 // opaque type. In this case, Existing will be an opaque type.
518 if (const Type *Ty = dyn_cast<Type>(Existing)) {
519 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Ty)) {
520 // We ARE replacing an opaque type!
521 ((OpaqueType*)OpTy)->refineAbstractTypeTo(cast<Type>(V));
526 // Otherwise, we are a simple redefinition of a value, check to see if it
527 // is defined the same as the old one...
528 if (const Type *Ty = dyn_cast<Type>(Existing)) {
529 if (Ty == cast<Type>(V)) return true; // Yes, it's equal.
530 // std::cerr << "Type: " << Ty->getDescription() << " != "
531 // << cast<Type>(V)->getDescription() << "!\n";
532 } else if (const Constant *C = dyn_cast<Constant>(Existing)) {
533 if (C == V) return true; // Constants are equal to themselves
534 } else if (GlobalVariable *EGV = dyn_cast<GlobalVariable>(Existing)) {
535 // We are allowed to redefine a global variable in two circumstances:
536 // 1. If at least one of the globals is uninitialized or
537 // 2. If both initializers have the same value.
539 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
540 if (!EGV->hasInitializer() || !GV->hasInitializer() ||
541 EGV->getInitializer() == GV->getInitializer()) {
543 // Make sure the existing global version gets the initializer! Make
544 // sure that it also gets marked const if the new version is.
545 if (GV->hasInitializer() && !EGV->hasInitializer())
546 EGV->setInitializer(GV->getInitializer());
547 if (GV->isConstant())
548 EGV->setConstant(true);
549 EGV->setLinkage(GV->getLinkage());
551 delete GV; // Destroy the duplicate!
552 return true; // They are equivalent!
557 ThrowException("Redefinition of value named '" + Name + "' in the '" +
558 V->getType()->getDescription() + "' type plane!");
562 V->setName(Name, &ST);
564 // If we're in function scope
565 if (inFunctionScope()) {
566 // Look up the symbol in the function's local symboltable
567 Existing = CurFun.LocalSymtab.lookup(V->getType(),Name);
569 // If it already exists
572 ThrowException("Redefinition of value named '" + Name + "' in the '" +
573 V->getType()->getDescription() + "' type plane!");
575 // otherwise, since it doesn't exist
578 CurFun.LocalSymtab.insert(V);
585 //===----------------------------------------------------------------------===//
586 // Code for handling upreferences in type names...
589 // TypeContains - Returns true if Ty contains E in it.
591 static bool TypeContains(const Type *Ty, const Type *E) {
592 return find(df_begin(Ty), df_end(Ty), E) != df_end(Ty);
595 // UpRefs - A list of the outstanding upreferences that need to be resolved.
596 static std::vector<std::pair<unsigned, OpaqueType *> > UpRefs;
598 /// HandleUpRefs - Every time we finish a new layer of types, this function is
599 /// called. It loops through the UpRefs vector, which is a list of the
600 /// currently active types. For each type, if the up reference is contained in
601 /// the newly completed type, we decrement the level count. When the level
602 /// count reaches zero, the upreferenced type is the type that is passed in:
603 /// thus we can complete the cycle.
605 static PATypeHolder HandleUpRefs(const Type *ty) {
606 if (!ty->isAbstract()) return ty;
608 UR_OUT("Type '" << Ty->getDescription() <<
609 "' newly formed. Resolving upreferences.\n" <<
610 UpRefs.size() << " upreferences active!\n");
611 for (unsigned i = 0; i != UpRefs.size(); ++i) {
612 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
613 << UpRefs[i].second->getDescription() << ") = "
614 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
615 if (TypeContains(Ty, UpRefs[i].second)) {
616 unsigned Level = --UpRefs[i].first; // Decrement level of upreference
617 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
618 if (Level == 0) { // Upreference should be resolved!
619 UR_OUT(" * Resolving upreference for "
620 << UpRefs[i].second->getDescription() << "\n";
621 std::string OldName = UpRefs[i].second->getDescription());
622 UpRefs[i].second->refineAbstractTypeTo(Ty);
623 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
624 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
625 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
626 --i; // Do not skip the next element...
635 //===----------------------------------------------------------------------===//
636 // RunVMAsmParser - Define an interface to this parser
637 //===----------------------------------------------------------------------===//
639 Module *RunVMAsmParser(const std::string &Filename, FILE *F) {
641 CurFilename = Filename;
642 llvmAsmlineno = 1; // Reset the current line number...
643 ObsoleteVarArgs = false;
645 // Allocate a new module to read
646 CurModule.CurrentModule = new Module(Filename);
649 yyparse(); // Parse the file.
651 // Clear the symbol table so it doesn't complain when it
653 CurFun.LocalSymtab.clear();
657 Module *Result = ParserResult;
659 // Check to see if they called va_start but not va_arg..
660 if (!ObsoleteVarArgs)
661 if (Function *F = Result->getNamedFunction("llvm.va_start"))
662 if (F->asize() == 1) {
663 std::cerr << "WARNING: this file uses obsolete features. "
664 << "Assemble and disassemble to update it.\n";
665 ObsoleteVarArgs = true;
669 if (ObsoleteVarArgs) {
670 // If the user is making use of obsolete varargs intrinsics, adjust them for
672 if (Function *F = Result->getNamedFunction("llvm.va_start")) {
673 assert(F->asize() == 1 && "Obsolete va_start takes 1 argument!");
675 const Type *RetTy = F->getFunctionType()->getParamType(0);
676 RetTy = cast<PointerType>(RetTy)->getElementType();
677 Function *NF = Result->getOrInsertFunction("llvm.va_start", RetTy, 0);
679 while (!F->use_empty()) {
680 CallInst *CI = cast<CallInst>(F->use_back());
681 Value *V = new CallInst(NF, "", CI);
682 new StoreInst(V, CI->getOperand(1), CI);
683 CI->getParent()->getInstList().erase(CI);
685 Result->getFunctionList().erase(F);
688 if (Function *F = Result->getNamedFunction("llvm.va_end")) {
689 assert(F->asize() == 1 && "Obsolete va_end takes 1 argument!");
690 const Type *ArgTy = F->getFunctionType()->getParamType(0);
691 ArgTy = cast<PointerType>(ArgTy)->getElementType();
692 Function *NF = Result->getOrInsertFunction("llvm.va_end", Type::VoidTy,
695 while (!F->use_empty()) {
696 CallInst *CI = cast<CallInst>(F->use_back());
697 Value *V = new LoadInst(CI->getOperand(1), "", CI);
698 new CallInst(NF, V, "", CI);
699 CI->getParent()->getInstList().erase(CI);
701 Result->getFunctionList().erase(F);
704 if (Function *F = Result->getNamedFunction("llvm.va_copy")) {
705 assert(F->asize() == 2 && "Obsolete va_copy takes 2 argument!");
706 const Type *ArgTy = F->getFunctionType()->getParamType(0);
707 ArgTy = cast<PointerType>(ArgTy)->getElementType();
708 Function *NF = Result->getOrInsertFunction("llvm.va_copy", ArgTy,
711 while (!F->use_empty()) {
712 CallInst *CI = cast<CallInst>(F->use_back());
713 Value *V = new CallInst(NF, CI->getOperand(2), "", CI);
714 new StoreInst(V, CI->getOperand(1), CI);
715 CI->getParent()->getInstList().erase(CI);
717 Result->getFunctionList().erase(F);
721 llvmAsmin = stdin; // F is about to go away, don't use it anymore...
727 } // End llvm namespace
729 using namespace llvm;
734 llvm::Module *ModuleVal;
735 llvm::Function *FunctionVal;
736 std::pair<llvm::PATypeHolder*, char*> *ArgVal;
737 llvm::BasicBlock *BasicBlockVal;
738 llvm::TerminatorInst *TermInstVal;
739 llvm::Instruction *InstVal;
740 llvm::Constant *ConstVal;
742 const llvm::Type *PrimType;
743 llvm::PATypeHolder *TypeVal;
744 llvm::Value *ValueVal;
746 std::vector<std::pair<llvm::PATypeHolder*,char*> > *ArgList;
747 std::vector<llvm::Value*> *ValueList;
748 std::list<llvm::PATypeHolder> *TypeList;
749 std::list<std::pair<llvm::Value*,
750 llvm::BasicBlock*> > *PHIList; // Represent the RHS of PHI node
751 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
752 std::vector<llvm::Constant*> *ConstVector;
754 llvm::GlobalValue::LinkageTypes Linkage;
762 char *StrVal; // This memory is strdup'd!
763 llvm::ValID ValIDVal; // strdup'd memory maybe!
765 llvm::Instruction::BinaryOps BinaryOpVal;
766 llvm::Instruction::TermOps TermOpVal;
767 llvm::Instruction::MemoryOps MemOpVal;
768 llvm::Instruction::OtherOps OtherOpVal;
769 llvm::Module::Endianness Endianness;
772 %type <ModuleVal> Module FunctionList
773 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
774 %type <BasicBlockVal> BasicBlock InstructionList
775 %type <TermInstVal> BBTerminatorInst
776 %type <InstVal> Inst InstVal MemoryInst
777 %type <ConstVal> ConstVal ConstExpr
778 %type <ConstVector> ConstVector
779 %type <ArgList> ArgList ArgListH
780 %type <ArgVal> ArgVal
781 %type <PHIList> PHIList
782 %type <ValueList> ValueRefList ValueRefListE // For call param lists
783 %type <ValueList> IndexList // For GEP derived indices
784 %type <TypeList> TypeListI ArgTypeListI
785 %type <JumpTable> JumpTable
786 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
787 %type <BoolVal> OptVolatile // 'volatile' or not
788 %type <Linkage> OptLinkage
789 %type <Endianness> BigOrLittle
791 // ValueRef - Unresolved reference to a definition or BB
792 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
793 %type <ValueVal> ResolvedVal // <type> <valref> pair
794 // Tokens and types for handling constant integer values
796 // ESINT64VAL - A negative number within long long range
797 %token <SInt64Val> ESINT64VAL
799 // EUINT64VAL - A positive number within uns. long long range
800 %token <UInt64Val> EUINT64VAL
801 %type <SInt64Val> EINT64VAL
803 %token <SIntVal> SINTVAL // Signed 32 bit ints...
804 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
805 %type <SIntVal> INTVAL
806 %token <FPVal> FPVAL // Float or Double constant
809 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
810 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
811 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
812 %token <PrimType> FLOAT DOUBLE TYPE LABEL
814 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
815 %type <StrVal> Name OptName OptAssign
818 %token IMPLEMENTATION ZEROINITIALIZER TRUE FALSE BEGINTOK ENDTOK
819 %token DECLARE GLOBAL CONSTANT VOLATILE
820 %token TO DOTDOTDOT NULL_TOK CONST INTERNAL LINKONCE WEAK APPENDING
821 %token OPAQUE NOT EXTERNAL TARGET ENDIAN POINTERSIZE LITTLE BIG
823 // Basic Block Terminating Operators
824 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND
827 %type <BinaryOpVal> BinaryOps // all the binary operators
828 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
829 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
830 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comarators
832 // Memory Instructions
833 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
836 %type <OtherOpVal> ShiftOps
837 %token <OtherOpVal> PHI_TOK CALL CAST SHL SHR VAARG VANEXT
838 %token VA_ARG // FIXME: OBSOLETE
843 // Handle constant integer size restriction and conversion...
847 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
848 ThrowException("Value too large for type!");
853 EINT64VAL : ESINT64VAL; // These have same type and can't cause problems...
854 EINT64VAL : EUINT64VAL {
855 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
856 ThrowException("Value too large for type!");
860 // Operations that are notably excluded from this list include:
861 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
863 ArithmeticOps: ADD | SUB | MUL | DIV | REM;
864 LogicalOps : AND | OR | XOR;
865 SetCondOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
866 BinaryOps : ArithmeticOps | LogicalOps | SetCondOps;
868 ShiftOps : SHL | SHR;
870 // These are some types that allow classification if we only want a particular
871 // thing... for example, only a signed, unsigned, or integral type.
872 SIntType : LONG | INT | SHORT | SBYTE;
873 UIntType : ULONG | UINT | USHORT | UBYTE;
874 IntType : SIntType | UIntType;
875 FPType : FLOAT | DOUBLE;
877 // OptAssign - Value producing statements have an optional assignment component
878 OptAssign : Name '=' {
885 OptLinkage : INTERNAL { $$ = GlobalValue::InternalLinkage; } |
886 LINKONCE { $$ = GlobalValue::LinkOnceLinkage; } |
887 WEAK { $$ = GlobalValue::WeakLinkage; } |
888 APPENDING { $$ = GlobalValue::AppendingLinkage; } |
889 /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
891 //===----------------------------------------------------------------------===//
892 // Types includes all predefined types... except void, because it can only be
893 // used in specific contexts (function returning void for example). To have
894 // access to it, a user must explicitly use TypesV.
897 // TypesV includes all of 'Types', but it also includes the void type.
898 TypesV : Types | VOID { $$ = new PATypeHolder($1); };
899 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
903 ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
908 // Derived types are added later...
910 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT ;
911 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL;
913 $$ = new PATypeHolder(OpaqueType::get());
916 $$ = new PATypeHolder($1);
918 UpRTypes : SymbolicValueRef { // Named types are also simple types...
919 $$ = new PATypeHolder(getTypeVal($1));
922 // Include derived types in the Types production.
924 UpRTypes : '\\' EUINT64VAL { // Type UpReference
925 if ($2 > (uint64_t)~0U) ThrowException("Value out of range!");
926 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
927 UpRefs.push_back(std::make_pair((unsigned)$2, OT)); // Add to vector...
928 $$ = new PATypeHolder(OT);
929 UR_OUT("New Upreference!\n");
931 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
932 std::vector<const Type*> Params;
933 mapto($3->begin(), $3->end(), std::back_inserter(Params),
934 std::mem_fun_ref(&PATypeHolder::get));
935 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
936 if (isVarArg) Params.pop_back();
938 $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
939 delete $3; // Delete the argument list
940 delete $1; // Delete the return type handle
942 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
943 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
946 | '{' TypeListI '}' { // Structure type?
947 std::vector<const Type*> Elements;
948 mapto($2->begin(), $2->end(), std::back_inserter(Elements),
949 std::mem_fun_ref(&PATypeHolder::get));
951 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
954 | '{' '}' { // Empty structure type?
955 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
957 | UpRTypes '*' { // Pointer type?
958 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
962 // TypeList - Used for struct declarations and as a basis for function type
963 // declaration type lists
965 TypeListI : UpRTypes {
966 $$ = new std::list<PATypeHolder>();
967 $$->push_back(*$1); delete $1;
969 | TypeListI ',' UpRTypes {
970 ($$=$1)->push_back(*$3); delete $3;
973 // ArgTypeList - List of types for a function type declaration...
974 ArgTypeListI : TypeListI
975 | TypeListI ',' DOTDOTDOT {
976 ($$=$1)->push_back(Type::VoidTy);
979 ($$ = new std::list<PATypeHolder>())->push_back(Type::VoidTy);
982 $$ = new std::list<PATypeHolder>();
985 // ConstVal - The various declarations that go into the constant pool. This
986 // production is used ONLY to represent constants that show up AFTER a 'const',
987 // 'constant' or 'global' token at global scope. Constants that can be inlined
988 // into other expressions (such as integers and constexprs) are handled by the
989 // ResolvedVal, ValueRef and ConstValueRef productions.
991 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
992 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
994 ThrowException("Cannot make array constant with type: '" +
995 (*$1)->getDescription() + "'!");
996 const Type *ETy = ATy->getElementType();
997 int NumElements = ATy->getNumElements();
999 // Verify that we have the correct size...
1000 if (NumElements != -1 && NumElements != (int)$3->size())
1001 ThrowException("Type mismatch: constant sized array initialized with " +
1002 utostr($3->size()) + " arguments, but has size of " +
1003 itostr(NumElements) + "!");
1005 // Verify all elements are correct type!
1006 for (unsigned i = 0; i < $3->size(); i++) {
1007 if (ETy != (*$3)[i]->getType())
1008 ThrowException("Element #" + utostr(i) + " is not of type '" +
1009 ETy->getDescription() +"' as required!\nIt is of type '"+
1010 (*$3)[i]->getType()->getDescription() + "'.");
1013 $$ = ConstantArray::get(ATy, *$3);
1014 delete $1; delete $3;
1017 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1019 ThrowException("Cannot make array constant with type: '" +
1020 (*$1)->getDescription() + "'!");
1022 int NumElements = ATy->getNumElements();
1023 if (NumElements != -1 && NumElements != 0)
1024 ThrowException("Type mismatch: constant sized array initialized with 0"
1025 " arguments, but has size of " + itostr(NumElements) +"!");
1026 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1029 | Types 'c' STRINGCONSTANT {
1030 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1032 ThrowException("Cannot make array constant with type: '" +
1033 (*$1)->getDescription() + "'!");
1035 int NumElements = ATy->getNumElements();
1036 const Type *ETy = ATy->getElementType();
1037 char *EndStr = UnEscapeLexed($3, true);
1038 if (NumElements != -1 && NumElements != (EndStr-$3))
1039 ThrowException("Can't build string constant of size " +
1040 itostr((int)(EndStr-$3)) +
1041 " when array has size " + itostr(NumElements) + "!");
1042 std::vector<Constant*> Vals;
1043 if (ETy == Type::SByteTy) {
1044 for (char *C = $3; C != EndStr; ++C)
1045 Vals.push_back(ConstantSInt::get(ETy, *C));
1046 } else if (ETy == Type::UByteTy) {
1047 for (char *C = $3; C != EndStr; ++C)
1048 Vals.push_back(ConstantUInt::get(ETy, (unsigned char)*C));
1051 ThrowException("Cannot build string arrays of non byte sized elements!");
1054 $$ = ConstantArray::get(ATy, Vals);
1057 | Types '{' ConstVector '}' {
1058 const StructType *STy = dyn_cast<StructType>($1->get());
1060 ThrowException("Cannot make struct constant with type: '" +
1061 (*$1)->getDescription() + "'!");
1063 if ($3->size() != STy->getNumContainedTypes())
1064 ThrowException("Illegal number of initializers for structure type!");
1066 // Check to ensure that constants are compatible with the type initializer!
1067 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1068 if ((*$3)[i]->getType() != STy->getElementTypes()[i])
1069 ThrowException("Expected type '" +
1070 STy->getElementTypes()[i]->getDescription() +
1071 "' for element #" + utostr(i) +
1072 " of structure initializer!");
1074 $$ = ConstantStruct::get(STy, *$3);
1075 delete $1; delete $3;
1078 const StructType *STy = dyn_cast<StructType>($1->get());
1080 ThrowException("Cannot make struct constant with type: '" +
1081 (*$1)->getDescription() + "'!");
1083 if (STy->getNumContainedTypes() != 0)
1084 ThrowException("Illegal number of initializers for structure type!");
1086 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1090 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1092 ThrowException("Cannot make null pointer constant with type: '" +
1093 (*$1)->getDescription() + "'!");
1095 $$ = ConstantPointerNull::get(PTy);
1098 | Types SymbolicValueRef {
1099 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1101 ThrowException("Global const reference must be a pointer type!");
1103 // ConstExprs can exist in the body of a function, thus creating
1104 // ConstantPointerRefs whenever they refer to a variable. Because we are in
1105 // the context of a function, getValNonImprovising will search the functions
1106 // symbol table instead of the module symbol table for the global symbol,
1107 // which throws things all off. To get around this, we just tell
1108 // getValNonImprovising that we are at global scope here.
1110 Function *SavedCurFn = CurFun.CurrentFunction;
1111 CurFun.CurrentFunction = 0;
1113 Value *V = getValNonImprovising(Ty, $2);
1115 CurFun.CurrentFunction = SavedCurFn;
1117 // If this is an initializer for a constant pointer, which is referencing a
1118 // (currently) undefined variable, create a stub now that shall be replaced
1119 // in the future with the right type of variable.
1122 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1123 const PointerType *PT = cast<PointerType>(Ty);
1125 // First check to see if the forward references value is already created!
1126 PerModuleInfo::GlobalRefsType::iterator I =
1127 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1129 if (I != CurModule.GlobalRefs.end()) {
1130 V = I->second; // Placeholder already exists, use it...
1133 // Create a placeholder for the global variable reference...
1134 GlobalVariable *GV = new GlobalVariable(PT->getElementType(),
1136 GlobalValue::ExternalLinkage);
1137 // Keep track of the fact that we have a forward ref to recycle it
1138 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1140 // Must temporarily push this value into the module table...
1141 CurModule.CurrentModule->getGlobalList().push_back(GV);
1146 GlobalValue *GV = cast<GlobalValue>(V);
1147 $$ = ConstantPointerRef::get(GV);
1148 delete $1; // Free the type handle
1151 if ($1->get() != $2->getType())
1152 ThrowException("Mismatched types for constant expression!");
1156 | Types ZEROINITIALIZER {
1157 $$ = Constant::getNullValue($1->get());
1161 ConstVal : SIntType EINT64VAL { // integral constants
1162 if (!ConstantSInt::isValueValidForType($1, $2))
1163 ThrowException("Constant value doesn't fit in type!");
1164 $$ = ConstantSInt::get($1, $2);
1166 | UIntType EUINT64VAL { // integral constants
1167 if (!ConstantUInt::isValueValidForType($1, $2))
1168 ThrowException("Constant value doesn't fit in type!");
1169 $$ = ConstantUInt::get($1, $2);
1171 | BOOL TRUE { // Boolean constants
1172 $$ = ConstantBool::True;
1174 | BOOL FALSE { // Boolean constants
1175 $$ = ConstantBool::False;
1177 | FPType FPVAL { // Float & Double constants
1178 $$ = ConstantFP::get($1, $2);
1182 ConstExpr: CAST '(' ConstVal TO Types ')' {
1183 if (!$3->getType()->isFirstClassType())
1184 ThrowException("cast constant expression from a non-primitive type: '" +
1185 $3->getType()->getDescription() + "'!");
1186 if (!$5->get()->isFirstClassType())
1187 ThrowException("cast constant expression to a non-primitive type: '" +
1188 $5->get()->getDescription() + "'!");
1189 $$ = ConstantExpr::getCast($3, $5->get());
1192 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1193 if (!isa<PointerType>($3->getType()))
1194 ThrowException("GetElementPtr requires a pointer operand!");
1197 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1199 ThrowException("Index list invalid for constant getelementptr!");
1201 std::vector<Constant*> IdxVec;
1202 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1203 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1204 IdxVec.push_back(C);
1206 ThrowException("Indices to constant getelementptr must be constants!");
1210 $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1212 | BinaryOps '(' ConstVal ',' ConstVal ')' {
1213 if ($3->getType() != $5->getType())
1214 ThrowException("Binary operator types must match!");
1215 $$ = ConstantExpr::get($1, $3, $5);
1217 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1218 if ($5->getType() != Type::UByteTy)
1219 ThrowException("Shift count for shift constant must be unsigned byte!");
1220 if (!$3->getType()->isInteger())
1221 ThrowException("Shift constant expression requires integer operand!");
1222 $$ = ConstantExpr::get($1, $3, $5);
1226 // ConstVector - A list of comma separated constants.
1227 ConstVector : ConstVector ',' ConstVal {
1228 ($$ = $1)->push_back($3);
1231 $$ = new std::vector<Constant*>();
1236 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1237 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1240 //===----------------------------------------------------------------------===//
1241 // Rules to match Modules
1242 //===----------------------------------------------------------------------===//
1244 // Module rule: Capture the result of parsing the whole file into a result
1247 Module : FunctionList {
1248 $$ = ParserResult = $1;
1249 CurModule.ModuleDone();
1252 // FunctionList - A list of functions, preceeded by a constant pool.
1254 FunctionList : FunctionList Function {
1256 assert($2->getParent() == 0 && "Function already in module!");
1257 $1->getFunctionList().push_back($2);
1258 CurFun.FunctionDone();
1260 | FunctionList FunctionProto {
1263 | FunctionList IMPLEMENTATION {
1267 $$ = CurModule.CurrentModule;
1268 // Resolve circular types before we parse the body of the module
1269 ResolveTypes(CurModule.LateResolveTypes);
1272 // ConstPool - Constants with optional names assigned to them.
1273 ConstPool : ConstPool OptAssign CONST ConstVal {
1274 if (!setValueName($4, $2))
1277 | ConstPool OptAssign TYPE TypesV { // Types can be defined in the const pool
1278 // Eagerly resolve types. This is not an optimization, this is a
1279 // requirement that is due to the fact that we could have this:
1281 // %list = type { %list * }
1282 // %list = type { %list * } ; repeated type decl
1284 // If types are not resolved eagerly, then the two types will not be
1285 // determined to be the same type!
1287 ResolveTypeTo($2, $4->get());
1289 // TODO: FIXME when Type are not const
1290 if (!setValueName(const_cast<Type*>($4->get()), $2)) {
1291 // If this is not a redefinition of a type...
1293 InsertType($4->get(),
1294 inFunctionScope() ? CurFun.Types : CurModule.Types);
1300 | ConstPool FunctionProto { // Function prototypes can be in const pool
1302 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
1303 const Type *Ty = $5->getType();
1304 // Global declarations appear in Constant Pool
1305 Constant *Initializer = $5;
1306 if (Initializer == 0)
1307 ThrowException("Global value initializer is not a constant!");
1309 GlobalVariable *GV = new GlobalVariable(Ty, $4, $3, Initializer);
1310 if (!setValueName(GV, $2)) { // If not redefining...
1311 CurModule.CurrentModule->getGlobalList().push_back(GV);
1312 int Slot = InsertValue(GV, CurModule.Values);
1315 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1317 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1318 (char*)GV->getName().c_str()));
1322 | ConstPool OptAssign EXTERNAL GlobalType Types {
1323 const Type *Ty = *$5;
1324 // Global declarations appear in Constant Pool
1325 GlobalVariable *GV = new GlobalVariable(Ty,$4,GlobalValue::ExternalLinkage);
1326 if (!setValueName(GV, $2)) { // If not redefining...
1327 CurModule.CurrentModule->getGlobalList().push_back(GV);
1328 int Slot = InsertValue(GV, CurModule.Values);
1331 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1333 assert(GV->hasName() && "Not named and not numbered!?");
1334 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1335 (char*)GV->getName().c_str()));
1340 | ConstPool TARGET TargetDefinition {
1342 | /* empty: end of list */ {
1347 BigOrLittle : BIG { $$ = Module::BigEndian; };
1348 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1350 TargetDefinition : ENDIAN '=' BigOrLittle {
1351 CurModule.CurrentModule->setEndianness($3);
1353 | POINTERSIZE '=' EUINT64VAL {
1355 CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1357 CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1359 ThrowException("Invalid pointer size: '" + utostr($3) + "'!");
1363 //===----------------------------------------------------------------------===//
1364 // Rules to match Function Headers
1365 //===----------------------------------------------------------------------===//
1367 Name : VAR_ID | STRINGCONSTANT;
1368 OptName : Name | /*empty*/ { $$ = 0; };
1370 ArgVal : Types OptName {
1371 if (*$1 == Type::VoidTy)
1372 ThrowException("void typed arguments are invalid!");
1373 $$ = new std::pair<PATypeHolder*, char*>($1, $2);
1376 ArgListH : ArgListH ',' ArgVal {
1382 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1387 ArgList : ArgListH {
1390 | ArgListH ',' DOTDOTDOT {
1392 $$->push_back(std::pair<PATypeHolder*,
1393 char*>(new PATypeHolder(Type::VoidTy), 0));
1396 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1397 $$->push_back(std::make_pair(new PATypeHolder(Type::VoidTy), (char*)0));
1403 FunctionHeaderH : TypesV Name '(' ArgList ')' {
1405 std::string FunctionName($2);
1407 if (!(*$1)->isFirstClassType() && *$1 != Type::VoidTy)
1408 ThrowException("LLVM functions cannot return aggregate types!");
1410 std::vector<const Type*> ParamTypeList;
1411 if ($4) { // If there are arguments...
1412 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $4->begin();
1413 I != $4->end(); ++I)
1414 ParamTypeList.push_back(I->first->get());
1417 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1418 if (isVarArg) ParamTypeList.pop_back();
1420 const FunctionType *FT = FunctionType::get(*$1, ParamTypeList, isVarArg);
1421 const PointerType *PFT = PointerType::get(FT);
1425 // Is the function already in symtab?
1426 if ((Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
1427 // Yes it is. If this is the case, either we need to be a forward decl,
1428 // or it needs to be.
1429 if (!CurFun.isDeclare && !Fn->isExternal())
1430 ThrowException("Redefinition of function '" + FunctionName + "'!");
1432 // If we found a preexisting function prototype, remove it from the
1433 // module, so that we don't get spurious conflicts with global & local
1436 CurModule.CurrentModule->getFunctionList().remove(Fn);
1438 // Make sure to strip off any argument names so we can't get conflicts...
1439 for (Function::aiterator AI = Fn->abegin(), AE = Fn->aend(); AI != AE; ++AI)
1442 } else { // Not already defined?
1443 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName);
1444 InsertValue(Fn, CurModule.Values);
1445 CurModule.DeclareNewGlobalValue(Fn, ValID::create($2));
1447 free($2); // Free strdup'd memory!
1449 CurFun.FunctionStart(Fn);
1451 // Add all of the arguments we parsed to the function...
1452 if ($4) { // Is null if empty...
1453 if (isVarArg) { // Nuke the last entry
1454 assert($4->back().first->get() == Type::VoidTy && $4->back().second == 0&&
1455 "Not a varargs marker!");
1456 delete $4->back().first;
1457 $4->pop_back(); // Delete the last entry
1459 Function::aiterator ArgIt = Fn->abegin();
1460 for (std::vector<std::pair<PATypeHolder*, char*> >::iterator I =$4->begin();
1461 I != $4->end(); ++I, ++ArgIt) {
1462 delete I->first; // Delete the typeholder...
1464 if (setValueName(ArgIt, I->second)) // Insert arg into symtab...
1465 assert(0 && "No arg redef allowed!");
1470 delete $4; // We're now done with the argument list
1474 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
1476 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
1477 $$ = CurFun.CurrentFunction;
1479 // Make sure that we keep track of the linkage type even if there was a
1480 // previous "declare".
1483 // Resolve circular types before we parse the body of the function.
1484 ResolveTypes(CurFun.LateResolveTypes);
1487 END : ENDTOK | '}'; // Allow end of '}' to end a function
1489 Function : BasicBlockList END {
1493 FunctionProto : DECLARE { CurFun.isDeclare = true; } FunctionHeaderH {
1494 $$ = CurFun.CurrentFunction;
1495 assert($$->getParent() == 0 && "Function already in module!");
1496 CurModule.CurrentModule->getFunctionList().push_back($$);
1497 CurFun.FunctionDone();
1500 //===----------------------------------------------------------------------===//
1501 // Rules to match Basic Blocks
1502 //===----------------------------------------------------------------------===//
1504 ConstValueRef : ESINT64VAL { // A reference to a direct constant
1505 $$ = ValID::create($1);
1508 $$ = ValID::create($1);
1510 | FPVAL { // Perhaps it's an FP constant?
1511 $$ = ValID::create($1);
1514 $$ = ValID::create(ConstantBool::True);
1517 $$ = ValID::create(ConstantBool::False);
1520 $$ = ValID::createNull();
1523 $$ = ValID::create($1);
1526 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1529 SymbolicValueRef : INTVAL { // Is it an integer reference...?
1530 $$ = ValID::create($1);
1532 | Name { // Is it a named reference...?
1533 $$ = ValID::create($1);
1536 // ValueRef - A reference to a definition... either constant or symbolic
1537 ValueRef : SymbolicValueRef | ConstValueRef;
1540 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
1541 // type immediately preceeds the value reference, and allows complex constant
1542 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1543 ResolvedVal : Types ValueRef {
1544 $$ = getVal(*$1, $2); delete $1;
1547 BasicBlockList : BasicBlockList BasicBlock {
1548 ($$ = $1)->getBasicBlockList().push_back($2);
1550 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
1551 ($$ = $1)->getBasicBlockList().push_back($2);
1555 // Basic blocks are terminated by branching instructions:
1556 // br, br/cc, switch, ret
1558 BasicBlock : InstructionList OptAssign BBTerminatorInst {
1559 if (setValueName($3, $2)) { assert(0 && "No redefn allowed!"); }
1562 $1->getInstList().push_back($3);
1566 | LABELSTR InstructionList OptAssign BBTerminatorInst {
1567 if (setValueName($4, $3)) { assert(0 && "No redefn allowed!"); }
1570 $2->getInstList().push_back($4);
1571 if (setValueName($2, $1)) { assert(0 && "No label redef allowed!"); }
1577 InstructionList : InstructionList Inst {
1578 $1->getInstList().push_back($2);
1582 $$ = CurBB = new BasicBlock();
1585 BBTerminatorInst : RET ResolvedVal { // Return with a result...
1586 $$ = new ReturnInst($2);
1588 | RET VOID { // Return with no result...
1589 $$ = new ReturnInst();
1591 | BR LABEL ValueRef { // Unconditional Branch...
1592 $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $3)));
1593 } // Conditional Branch...
1594 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
1595 $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $6)),
1596 cast<BasicBlock>(getVal(Type::LabelTy, $9)),
1597 getVal(Type::BoolTy, $3));
1599 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1600 SwitchInst *S = new SwitchInst(getVal($2, $3),
1601 cast<BasicBlock>(getVal(Type::LabelTy, $6)));
1604 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
1607 S->addCase(I->first, I->second);
1609 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
1610 SwitchInst *S = new SwitchInst(getVal($2, $3),
1611 cast<BasicBlock>(getVal(Type::LabelTy, $6)));
1614 | INVOKE TypesV ValueRef '(' ValueRefListE ')' TO ResolvedVal
1615 UNWIND ResolvedVal {
1616 const PointerType *PFTy;
1617 const FunctionType *Ty;
1619 if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
1620 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1621 // Pull out the types of all of the arguments...
1622 std::vector<const Type*> ParamTypes;
1624 for (std::vector<Value*>::iterator I = $5->begin(), E = $5->end();
1626 ParamTypes.push_back((*I)->getType());
1629 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1630 if (isVarArg) ParamTypes.pop_back();
1632 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1633 PFTy = PointerType::get(Ty);
1636 Value *V = getVal(PFTy, $3); // Get the function we're calling...
1638 BasicBlock *Normal = dyn_cast<BasicBlock>($8);
1639 BasicBlock *Except = dyn_cast<BasicBlock>($10);
1641 if (Normal == 0 || Except == 0)
1642 ThrowException("Invoke instruction without label destinations!");
1644 // Create the call node...
1645 if (!$5) { // Has no arguments?
1646 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
1647 } else { // Has arguments?
1648 // Loop through FunctionType's arguments and ensure they are specified
1651 FunctionType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1652 FunctionType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
1653 std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1655 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1656 if ((*ArgI)->getType() != *I)
1657 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1658 (*I)->getDescription() + "'!");
1660 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1661 ThrowException("Invalid number of parameters detected!");
1663 $$ = new InvokeInst(V, Normal, Except, *$5);
1669 $$ = new UnwindInst();
1674 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1676 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
1678 ThrowException("May only switch on a constant pool value!");
1680 $$->push_back(std::make_pair(V, cast<BasicBlock>(getVal($5, $6))));
1682 | IntType ConstValueRef ',' LABEL ValueRef {
1683 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
1684 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
1687 ThrowException("May only switch on a constant pool value!");
1689 $$->push_back(std::make_pair(V, cast<BasicBlock>(getVal($4, $5))));
1692 Inst : OptAssign InstVal {
1693 // Is this definition named?? if so, assign the name...
1694 if (setValueName($2, $1)) { assert(0 && "No redefin allowed!"); }
1699 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
1700 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
1701 $$->push_back(std::make_pair(getVal(*$1, $3),
1702 cast<BasicBlock>(getVal(Type::LabelTy, $5))));
1705 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1707 $1->push_back(std::make_pair(getVal($1->front().first->getType(), $4),
1708 cast<BasicBlock>(getVal(Type::LabelTy, $6))));
1712 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
1713 $$ = new std::vector<Value*>();
1716 | ValueRefList ',' ResolvedVal {
1721 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1722 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
1724 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
1725 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint())
1726 ThrowException("Arithmetic operator requires integer or FP operands!");
1727 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1729 ThrowException("binary operator returned null!");
1732 | LogicalOps Types ValueRef ',' ValueRef {
1733 if (!(*$2)->isIntegral())
1734 ThrowException("Logical operator requires integral operands!");
1735 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1737 ThrowException("binary operator returned null!");
1740 | SetCondOps Types ValueRef ',' ValueRef {
1741 $$ = new SetCondInst($1, getVal(*$2, $3), getVal(*$2, $5));
1743 ThrowException("binary operator returned null!");
1747 std::cerr << "WARNING: Use of eliminated 'not' instruction:"
1748 << " Replacing with 'xor'.\n";
1750 Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
1752 ThrowException("Expected integral type for not instruction!");
1754 $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
1756 ThrowException("Could not create a xor instruction!");
1758 | ShiftOps ResolvedVal ',' ResolvedVal {
1759 if ($4->getType() != Type::UByteTy)
1760 ThrowException("Shift amount must be ubyte!");
1761 if (!$2->getType()->isInteger())
1762 ThrowException("Shift constant expression requires integer operand!");
1763 $$ = new ShiftInst($1, $2, $4);
1765 | CAST ResolvedVal TO Types {
1766 if (!$4->get()->isFirstClassType())
1767 ThrowException("cast instruction to a non-primitive type: '" +
1768 $4->get()->getDescription() + "'!");
1769 $$ = new CastInst($2, *$4);
1772 | VA_ARG ResolvedVal ',' Types {
1773 // FIXME: This is emulation code for an obsolete syntax. This should be
1774 // removed at some point.
1775 if (!ObsoleteVarArgs) {
1776 std::cerr << "WARNING: this file uses obsolete features. "
1777 << "Assemble and disassemble to update it.\n";
1778 ObsoleteVarArgs = true;
1781 // First, load the valist...
1782 Instruction *CurVAList = new LoadInst($2, "");
1783 CurBB->getInstList().push_back(CurVAList);
1785 // Emit the vaarg instruction.
1786 $$ = new VAArgInst(CurVAList, *$4);
1788 // Now we must advance the pointer and update it in memory.
1789 Instruction *TheVANext = new VANextInst(CurVAList, *$4);
1790 CurBB->getInstList().push_back(TheVANext);
1792 CurBB->getInstList().push_back(new StoreInst(TheVANext, $2));
1795 | VAARG ResolvedVal ',' Types {
1796 $$ = new VAArgInst($2, *$4);
1799 | VANEXT ResolvedVal ',' Types {
1800 $$ = new VANextInst($2, *$4);
1804 const Type *Ty = $2->front().first->getType();
1805 if (!Ty->isFirstClassType())
1806 ThrowException("PHI node operands must be of first class type!");
1807 $$ = new PHINode(Ty);
1808 $$->op_reserve($2->size()*2);
1809 while ($2->begin() != $2->end()) {
1810 if ($2->front().first->getType() != Ty)
1811 ThrowException("All elements of a PHI node must be of the same type!");
1812 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
1815 delete $2; // Free the list...
1817 | CALL TypesV ValueRef '(' ValueRefListE ')' {
1818 const PointerType *PFTy;
1819 const FunctionType *Ty;
1821 if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
1822 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1823 // Pull out the types of all of the arguments...
1824 std::vector<const Type*> ParamTypes;
1826 for (std::vector<Value*>::iterator I = $5->begin(), E = $5->end();
1828 ParamTypes.push_back((*I)->getType());
1831 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1832 if (isVarArg) ParamTypes.pop_back();
1834 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1835 PFTy = PointerType::get(Ty);
1838 Value *V = getVal(PFTy, $3); // Get the function we're calling...
1840 // Create the call node...
1841 if (!$5) { // Has no arguments?
1842 // Make sure no arguments is a good thing!
1843 if (Ty->getNumParams() != 0)
1844 ThrowException("No arguments passed to a function that "
1845 "expects arguments!");
1847 $$ = new CallInst(V, std::vector<Value*>());
1848 } else { // Has arguments?
1849 // Loop through FunctionType's arguments and ensure they are specified
1852 FunctionType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1853 FunctionType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
1854 std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1856 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1857 if ((*ArgI)->getType() != *I)
1858 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1859 (*I)->getDescription() + "'!");
1861 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1862 ThrowException("Invalid number of parameters detected!");
1864 $$ = new CallInst(V, *$5);
1874 // IndexList - List of indices for GEP based instructions...
1875 IndexList : ',' ValueRefList {
1878 $$ = new std::vector<Value*>();
1881 OptVolatile : VOLATILE {
1889 MemoryInst : MALLOC Types {
1890 $$ = new MallocInst(*$2);
1893 | MALLOC Types ',' UINT ValueRef {
1894 $$ = new MallocInst(*$2, getVal($4, $5));
1898 $$ = new AllocaInst(*$2);
1901 | ALLOCA Types ',' UINT ValueRef {
1902 $$ = new AllocaInst(*$2, getVal($4, $5));
1905 | FREE ResolvedVal {
1906 if (!isa<PointerType>($2->getType()))
1907 ThrowException("Trying to free nonpointer type " +
1908 $2->getType()->getDescription() + "!");
1909 $$ = new FreeInst($2);
1912 | OptVolatile LOAD Types ValueRef {
1913 if (!isa<PointerType>($3->get()))
1914 ThrowException("Can't load from nonpointer type: " +
1915 (*$3)->getDescription());
1916 $$ = new LoadInst(getVal(*$3, $4), "", $1);
1919 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
1920 const PointerType *PT = dyn_cast<PointerType>($5->get());
1922 ThrowException("Can't store to a nonpointer type: " +
1923 (*$5)->getDescription());
1924 const Type *ElTy = PT->getElementType();
1925 if (ElTy != $3->getType())
1926 ThrowException("Can't store '" + $3->getType()->getDescription() +
1927 "' into space of type '" + ElTy->getDescription() + "'!");
1929 $$ = new StoreInst($3, getVal(*$5, $6), $1);
1932 | GETELEMENTPTR Types ValueRef IndexList {
1933 if (!isa<PointerType>($2->get()))
1934 ThrowException("getelementptr insn requires pointer operand!");
1935 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
1936 ThrowException("Can't get element ptr '" + (*$2)->getDescription()+ "'!");
1937 $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
1938 delete $2; delete $4;
1943 int yyerror(const char *ErrorMsg) {
1945 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
1946 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
1947 std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
1948 if (yychar == YYEMPTY)
1949 errMsg += "end-of-file.";
1951 errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
1952 ThrowException(errMsg);