1 //===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the bison parser for LLVM assembly languages files.
12 //===----------------------------------------------------------------------===//
15 #include "ParserInternals.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Module.h"
19 #include "llvm/SymbolTable.h"
20 #include "llvm/Support/GetElementPtrTypeIterator.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/Support/MathExtras.h"
28 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
29 int yylex(); // declaration" of xxx warnings.
33 std::string CurFilename;
37 static Module *ParserResult;
39 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
40 // relating to upreferences in the input stream.
42 //#define DEBUG_UPREFS 1
44 #define UR_OUT(X) std::cerr << X
49 #define YYERROR_VERBOSE 1
51 static bool ObsoleteVarArgs;
52 static bool NewVarArgs;
53 static BasicBlock *CurBB;
54 static GlobalVariable *CurGV;
57 // This contains info used when building the body of a function. It is
58 // destroyed when the function is completed.
60 typedef std::vector<Value *> ValueList; // Numbered defs
62 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
63 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
65 static struct PerModuleInfo {
66 Module *CurrentModule;
67 std::map<const Type *, ValueList> Values; // Module level numbered definitions
68 std::map<const Type *,ValueList> LateResolveValues;
69 std::vector<PATypeHolder> Types;
70 std::map<ValID, PATypeHolder> LateResolveTypes;
72 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
73 /// how they were referenced and one which line of the input they came from so
74 /// that we can resolve them later and print error messages as appropriate.
75 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
77 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
78 // references to global values. Global values may be referenced before they
79 // are defined, and if so, the temporary object that they represent is held
80 // here. This is used for forward references of GlobalValues.
82 typedef std::map<std::pair<const PointerType *,
83 ValID>, GlobalValue*> GlobalRefsType;
84 GlobalRefsType GlobalRefs;
87 // If we could not resolve some functions at function compilation time
88 // (calls to functions before they are defined), resolve them now... Types
89 // are resolved when the constant pool has been completely parsed.
91 ResolveDefinitions(LateResolveValues);
93 // Check to make sure that all global value forward references have been
96 if (!GlobalRefs.empty()) {
97 std::string UndefinedReferences = "Unresolved global references exist:\n";
99 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
101 UndefinedReferences += " " + I->first.first->getDescription() + " " +
102 I->first.second.getName() + "\n";
104 ThrowException(UndefinedReferences);
107 Values.clear(); // Clear out function local definitions
113 // GetForwardRefForGlobal - Check to see if there is a forward reference
114 // for this global. If so, remove it from the GlobalRefs map and return it.
115 // If not, just return null.
116 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
117 // Check to see if there is a forward reference to this global variable...
118 // if there is, eliminate it and patch the reference to use the new def'n.
119 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
120 GlobalValue *Ret = 0;
121 if (I != GlobalRefs.end()) {
129 static struct PerFunctionInfo {
130 Function *CurrentFunction; // Pointer to current function being created
132 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
133 std::map<const Type*, ValueList> LateResolveValues;
134 bool isDeclare; // Is this function a forward declararation?
136 /// BBForwardRefs - When we see forward references to basic blocks, keep
137 /// track of them here.
138 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
139 std::vector<BasicBlock*> NumberedBlocks;
142 inline PerFunctionInfo() {
147 inline void FunctionStart(Function *M) {
152 void FunctionDone() {
153 NumberedBlocks.clear();
155 // Any forward referenced blocks left?
156 if (!BBForwardRefs.empty())
157 ThrowException("Undefined reference to label " +
158 BBForwardRefs.begin()->first->getName());
160 // Resolve all forward references now.
161 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
163 Values.clear(); // Clear out function local definitions
167 } CurFun; // Info for the current function...
169 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
172 //===----------------------------------------------------------------------===//
173 // Code to handle definitions of all the types
174 //===----------------------------------------------------------------------===//
176 static int InsertValue(Value *V,
177 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
178 if (V->hasName()) return -1; // Is this a numbered definition?
180 // Yes, insert the value into the value table...
181 ValueList &List = ValueTab[V->getType()];
183 return List.size()-1;
186 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
188 case ValID::NumberVal: // Is it a numbered definition?
189 // Module constants occupy the lowest numbered slots...
190 if ((unsigned)D.Num < CurModule.Types.size())
191 return CurModule.Types[(unsigned)D.Num];
193 case ValID::NameVal: // Is it a named definition?
194 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
195 D.destroy(); // Free old strdup'd memory...
200 ThrowException("Internal parser error: Invalid symbol type reference!");
203 // If we reached here, we referenced either a symbol that we don't know about
204 // or an id number that hasn't been read yet. We may be referencing something
205 // forward, so just create an entry to be resolved later and get to it...
207 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
210 if (inFunctionScope()) {
211 if (D.Type == ValID::NameVal)
212 ThrowException("Reference to an undefined type: '" + D.getName() + "'");
214 ThrowException("Reference to an undefined type: #" + itostr(D.Num));
217 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
218 if (I != CurModule.LateResolveTypes.end())
221 Type *Typ = OpaqueType::get();
222 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
226 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
227 SymbolTable &SymTab =
228 inFunctionScope() ? CurFun.CurrentFunction->getSymbolTable() :
229 CurModule.CurrentModule->getSymbolTable();
230 return SymTab.lookup(Ty, Name);
233 // getValNonImprovising - Look up the value specified by the provided type and
234 // the provided ValID. If the value exists and has already been defined, return
235 // it. Otherwise return null.
237 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
238 if (isa<FunctionType>(Ty))
239 ThrowException("Functions are not values and "
240 "must be referenced as pointers");
243 case ValID::NumberVal: { // Is it a numbered definition?
244 unsigned Num = (unsigned)D.Num;
246 // Module constants occupy the lowest numbered slots...
247 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
248 if (VI != CurModule.Values.end()) {
249 if (Num < VI->second.size())
250 return VI->second[Num];
251 Num -= VI->second.size();
254 // Make sure that our type is within bounds
255 VI = CurFun.Values.find(Ty);
256 if (VI == CurFun.Values.end()) return 0;
258 // Check that the number is within bounds...
259 if (VI->second.size() <= Num) return 0;
261 return VI->second[Num];
264 case ValID::NameVal: { // Is it a named definition?
265 Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
266 if (N == 0) return 0;
268 D.destroy(); // Free old strdup'd memory...
272 // Check to make sure that "Ty" is an integral type, and that our
273 // value will fit into the specified type...
274 case ValID::ConstSIntVal: // Is it a constant pool reference??
275 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64))
276 ThrowException("Signed integral constant '" +
277 itostr(D.ConstPool64) + "' is invalid for type '" +
278 Ty->getDescription() + "'!");
279 return ConstantSInt::get(Ty, D.ConstPool64);
281 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
282 if (!ConstantUInt::isValueValidForType(Ty, D.UConstPool64)) {
283 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64)) {
284 ThrowException("Integral constant '" + utostr(D.UConstPool64) +
285 "' is invalid or out of range!");
286 } else { // This is really a signed reference. Transmogrify.
287 return ConstantSInt::get(Ty, D.ConstPool64);
290 return ConstantUInt::get(Ty, D.UConstPool64);
293 case ValID::ConstFPVal: // Is it a floating point const pool reference?
294 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
295 ThrowException("FP constant invalid for type!!");
296 return ConstantFP::get(Ty, D.ConstPoolFP);
298 case ValID::ConstNullVal: // Is it a null value?
299 if (!isa<PointerType>(Ty))
300 ThrowException("Cannot create a a non pointer null!");
301 return ConstantPointerNull::get(cast<PointerType>(Ty));
303 case ValID::ConstUndefVal: // Is it an undef value?
304 return UndefValue::get(Ty);
306 case ValID::ConstantVal: // Fully resolved constant?
307 if (D.ConstantValue->getType() != Ty)
308 ThrowException("Constant expression type different from required type!");
309 return D.ConstantValue;
312 assert(0 && "Unhandled case!");
316 assert(0 && "Unhandled case!");
320 // getVal - This function is identical to getValNonImprovising, except that if a
321 // value is not already defined, it "improvises" by creating a placeholder var
322 // that looks and acts just like the requested variable. When the value is
323 // defined later, all uses of the placeholder variable are replaced with the
326 static Value *getVal(const Type *Ty, const ValID &ID) {
327 if (Ty == Type::LabelTy)
328 ThrowException("Cannot use a basic block here");
330 // See if the value has already been defined.
331 Value *V = getValNonImprovising(Ty, ID);
334 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty))
335 ThrowException("Invalid use of a composite type!");
337 // If we reached here, we referenced either a symbol that we don't know about
338 // or an id number that hasn't been read yet. We may be referencing something
339 // forward, so just create an entry to be resolved later and get to it...
341 V = new Argument(Ty);
343 // Remember where this forward reference came from. FIXME, shouldn't we try
344 // to recycle these things??
345 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
348 if (inFunctionScope())
349 InsertValue(V, CurFun.LateResolveValues);
351 InsertValue(V, CurModule.LateResolveValues);
355 /// getBBVal - This is used for two purposes:
356 /// * If isDefinition is true, a new basic block with the specified ID is being
358 /// * If isDefinition is true, this is a reference to a basic block, which may
359 /// or may not be a forward reference.
361 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
362 assert(inFunctionScope() && "Can't get basic block at global scope!");
367 default: ThrowException("Illegal label reference " + ID.getName());
368 case ValID::NumberVal: // Is it a numbered definition?
369 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
370 CurFun.NumberedBlocks.resize(ID.Num+1);
371 BB = CurFun.NumberedBlocks[ID.Num];
373 case ValID::NameVal: // Is it a named definition?
375 if (Value *N = CurFun.CurrentFunction->
376 getSymbolTable().lookup(Type::LabelTy, Name))
377 BB = cast<BasicBlock>(N);
381 // See if the block has already been defined.
383 // If this is the definition of the block, make sure the existing value was
384 // just a forward reference. If it was a forward reference, there will be
385 // an entry for it in the PlaceHolderInfo map.
386 if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
387 // The existing value was a definition, not a forward reference.
388 ThrowException("Redefinition of label " + ID.getName());
390 ID.destroy(); // Free strdup'd memory.
394 // Otherwise this block has not been seen before.
395 BB = new BasicBlock("", CurFun.CurrentFunction);
396 if (ID.Type == ValID::NameVal) {
397 BB->setName(ID.Name);
399 CurFun.NumberedBlocks[ID.Num] = BB;
402 // If this is not a definition, keep track of it so we can use it as a forward
405 // Remember where this forward reference came from.
406 CurFun.BBForwardRefs[BB] = std::make_pair(ID, llvmAsmlineno);
408 // The forward declaration could have been inserted anywhere in the
409 // function: insert it into the correct place now.
410 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
411 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
418 //===----------------------------------------------------------------------===//
419 // Code to handle forward references in instructions
420 //===----------------------------------------------------------------------===//
422 // This code handles the late binding needed with statements that reference
423 // values not defined yet... for example, a forward branch, or the PHI node for
426 // This keeps a table (CurFun.LateResolveValues) of all such forward references
427 // and back patchs after we are done.
430 // ResolveDefinitions - If we could not resolve some defs at parsing
431 // time (forward branches, phi functions for loops, etc...) resolve the
435 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
436 std::map<const Type*,ValueList> *FutureLateResolvers) {
437 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
438 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
439 E = LateResolvers.end(); LRI != E; ++LRI) {
440 ValueList &List = LRI->second;
441 while (!List.empty()) {
442 Value *V = List.back();
445 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
446 CurModule.PlaceHolderInfo.find(V);
447 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
449 ValID &DID = PHI->second.first;
451 Value *TheRealValue = getValNonImprovising(LRI->first, DID);
453 V->replaceAllUsesWith(TheRealValue);
455 CurModule.PlaceHolderInfo.erase(PHI);
456 } else if (FutureLateResolvers) {
457 // Functions have their unresolved items forwarded to the module late
459 InsertValue(V, *FutureLateResolvers);
461 if (DID.Type == ValID::NameVal)
462 ThrowException("Reference to an invalid definition: '" +DID.getName()+
463 "' of type '" + V->getType()->getDescription() + "'",
466 ThrowException("Reference to an invalid definition: #" +
467 itostr(DID.Num) + " of type '" +
468 V->getType()->getDescription() + "'",
474 LateResolvers.clear();
477 // ResolveTypeTo - A brand new type was just declared. This means that (if
478 // name is not null) things referencing Name can be resolved. Otherwise, things
479 // refering to the number can be resolved. Do this now.
481 static void ResolveTypeTo(char *Name, const Type *ToTy) {
483 if (Name) D = ValID::create(Name);
484 else D = ValID::create((int)CurModule.Types.size());
486 std::map<ValID, PATypeHolder>::iterator I =
487 CurModule.LateResolveTypes.find(D);
488 if (I != CurModule.LateResolveTypes.end()) {
489 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
490 CurModule.LateResolveTypes.erase(I);
494 // setValueName - Set the specified value to the name given. The name may be
495 // null potentially, in which case this is a noop. The string passed in is
496 // assumed to be a malloc'd string buffer, and is free'd by this function.
498 static void setValueName(Value *V, char *NameStr) {
500 std::string Name(NameStr); // Copy string
501 free(NameStr); // Free old string
503 if (V->getType() == Type::VoidTy)
504 ThrowException("Can't assign name '" + Name+"' to value with void type!");
506 assert(inFunctionScope() && "Must be in function scope!");
507 SymbolTable &ST = CurFun.CurrentFunction->getSymbolTable();
508 if (ST.lookup(V->getType(), Name))
509 ThrowException("Redefinition of value named '" + Name + "' in the '" +
510 V->getType()->getDescription() + "' type plane!");
517 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
518 /// this is a declaration, otherwise it is a definition.
519 static GlobalVariable *
520 ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
521 bool isConstantGlobal, const Type *Ty,
522 Constant *Initializer) {
523 if (isa<FunctionType>(Ty))
524 ThrowException("Cannot declare global vars of function type!");
526 const PointerType *PTy = PointerType::get(Ty);
530 Name = NameStr; // Copy string
531 free(NameStr); // Free old string
534 // See if this global value was forward referenced. If so, recycle the
538 ID = ValID::create((char*)Name.c_str());
540 ID = ValID::create((int)CurModule.Values[PTy].size());
543 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
544 // Move the global to the end of the list, from whereever it was
545 // previously inserted.
546 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
547 CurModule.CurrentModule->getGlobalList().remove(GV);
548 CurModule.CurrentModule->getGlobalList().push_back(GV);
549 GV->setInitializer(Initializer);
550 GV->setLinkage(Linkage);
551 GV->setConstant(isConstantGlobal);
552 InsertValue(GV, CurModule.Values);
556 // If this global has a name, check to see if there is already a definition
557 // of this global in the module. If so, merge as appropriate. Note that
558 // this is really just a hack around problems in the CFE. :(
560 // We are a simple redefinition of a value, check to see if it is defined
561 // the same as the old one.
562 if (GlobalVariable *EGV =
563 CurModule.CurrentModule->getGlobalVariable(Name, Ty)) {
564 // We are allowed to redefine a global variable in two circumstances:
565 // 1. If at least one of the globals is uninitialized or
566 // 2. If both initializers have the same value.
568 if (!EGV->hasInitializer() || !Initializer ||
569 EGV->getInitializer() == Initializer) {
571 // Make sure the existing global version gets the initializer! Make
572 // sure that it also gets marked const if the new version is.
573 if (Initializer && !EGV->hasInitializer())
574 EGV->setInitializer(Initializer);
575 if (isConstantGlobal)
576 EGV->setConstant(true);
577 EGV->setLinkage(Linkage);
581 ThrowException("Redefinition of global variable named '" + Name +
582 "' in the '" + Ty->getDescription() + "' type plane!");
586 // Otherwise there is no existing GV to use, create one now.
588 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
589 CurModule.CurrentModule);
590 InsertValue(GV, CurModule.Values);
594 // setTypeName - Set the specified type to the name given. The name may be
595 // null potentially, in which case this is a noop. The string passed in is
596 // assumed to be a malloc'd string buffer, and is freed by this function.
598 // This function returns true if the type has already been defined, but is
599 // allowed to be redefined in the specified context. If the name is a new name
600 // for the type plane, it is inserted and false is returned.
601 static bool setTypeName(const Type *T, char *NameStr) {
602 assert(!inFunctionScope() && "Can't give types function-local names!");
603 if (NameStr == 0) return false;
605 std::string Name(NameStr); // Copy string
606 free(NameStr); // Free old string
608 // We don't allow assigning names to void type
609 if (T == Type::VoidTy)
610 ThrowException("Can't assign name '" + Name + "' to the void type!");
612 // Set the type name, checking for conflicts as we do so.
613 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
615 if (AlreadyExists) { // Inserting a name that is already defined???
616 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
617 assert(Existing && "Conflict but no matching type?");
619 // There is only one case where this is allowed: when we are refining an
620 // opaque type. In this case, Existing will be an opaque type.
621 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
622 // We ARE replacing an opaque type!
623 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
627 // Otherwise, this is an attempt to redefine a type. That's okay if
628 // the redefinition is identical to the original. This will be so if
629 // Existing and T point to the same Type object. In this one case we
630 // allow the equivalent redefinition.
631 if (Existing == T) return true; // Yes, it's equal.
633 // Any other kind of (non-equivalent) redefinition is an error.
634 ThrowException("Redefinition of type named '" + Name + "' in the '" +
635 T->getDescription() + "' type plane!");
641 //===----------------------------------------------------------------------===//
642 // Code for handling upreferences in type names...
645 // TypeContains - Returns true if Ty directly contains E in it.
647 static bool TypeContains(const Type *Ty, const Type *E) {
648 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
649 E) != Ty->subtype_end();
654 // NestingLevel - The number of nesting levels that need to be popped before
655 // this type is resolved.
656 unsigned NestingLevel;
658 // LastContainedTy - This is the type at the current binding level for the
659 // type. Every time we reduce the nesting level, this gets updated.
660 const Type *LastContainedTy;
662 // UpRefTy - This is the actual opaque type that the upreference is
666 UpRefRecord(unsigned NL, OpaqueType *URTy)
667 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
671 // UpRefs - A list of the outstanding upreferences that need to be resolved.
672 static std::vector<UpRefRecord> UpRefs;
674 /// HandleUpRefs - Every time we finish a new layer of types, this function is
675 /// called. It loops through the UpRefs vector, which is a list of the
676 /// currently active types. For each type, if the up reference is contained in
677 /// the newly completed type, we decrement the level count. When the level
678 /// count reaches zero, the upreferenced type is the type that is passed in:
679 /// thus we can complete the cycle.
681 static PATypeHolder HandleUpRefs(const Type *ty) {
682 if (!ty->isAbstract()) return ty;
684 UR_OUT("Type '" << Ty->getDescription() <<
685 "' newly formed. Resolving upreferences.\n" <<
686 UpRefs.size() << " upreferences active!\n");
688 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
689 // to zero), we resolve them all together before we resolve them to Ty. At
690 // the end of the loop, if there is anything to resolve to Ty, it will be in
692 OpaqueType *TypeToResolve = 0;
694 for (unsigned i = 0; i != UpRefs.size(); ++i) {
695 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
696 << UpRefs[i].second->getDescription() << ") = "
697 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
698 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
699 // Decrement level of upreference
700 unsigned Level = --UpRefs[i].NestingLevel;
701 UpRefs[i].LastContainedTy = Ty;
702 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
703 if (Level == 0) { // Upreference should be resolved!
704 if (!TypeToResolve) {
705 TypeToResolve = UpRefs[i].UpRefTy;
707 UR_OUT(" * Resolving upreference for "
708 << UpRefs[i].second->getDescription() << "\n";
709 std::string OldName = UpRefs[i].UpRefTy->getDescription());
710 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
711 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
712 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
714 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
715 --i; // Do not skip the next element...
721 UR_OUT(" * Resolving upreference for "
722 << UpRefs[i].second->getDescription() << "\n";
723 std::string OldName = TypeToResolve->getDescription());
724 TypeToResolve->refineAbstractTypeTo(Ty);
731 // common code from the two 'RunVMAsmParser' functions
732 static Module * RunParser(Module * M) {
734 llvmAsmlineno = 1; // Reset the current line number...
735 ObsoleteVarArgs = false;
738 CurModule.CurrentModule = M;
739 yyparse(); // Parse the file, potentially throwing exception
741 Module *Result = ParserResult;
744 //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
747 if ((F = Result->getNamedFunction("llvm.va_start"))
748 && F->getFunctionType()->getNumParams() == 0)
749 ObsoleteVarArgs = true;
750 if((F = Result->getNamedFunction("llvm.va_copy"))
751 && F->getFunctionType()->getNumParams() == 1)
752 ObsoleteVarArgs = true;
755 if (ObsoleteVarArgs && NewVarArgs)
756 ThrowException("This file is corrupt: it uses both new and old style varargs");
758 if(ObsoleteVarArgs) {
759 if(Function* F = Result->getNamedFunction("llvm.va_start")) {
760 if (F->arg_size() != 0)
761 ThrowException("Obsolete va_start takes 0 argument!");
765 //bar = alloca typeof(foo)
769 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
770 const Type* ArgTy = F->getFunctionType()->getReturnType();
771 const Type* ArgTyPtr = PointerType::get(ArgTy);
772 Function* NF = Result->getOrInsertFunction("llvm.va_start",
773 RetTy, ArgTyPtr, (Type *)0);
775 while (!F->use_empty()) {
776 CallInst* CI = cast<CallInst>(F->use_back());
777 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
778 new CallInst(NF, bar, "", CI);
779 Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
780 CI->replaceAllUsesWith(foo);
781 CI->getParent()->getInstList().erase(CI);
783 Result->getFunctionList().erase(F);
786 if(Function* F = Result->getNamedFunction("llvm.va_end")) {
787 if(F->arg_size() != 1)
788 ThrowException("Obsolete va_end takes 1 argument!");
792 //bar = alloca 1 of typeof(foo)
794 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
795 const Type* ArgTy = F->getFunctionType()->getParamType(0);
796 const Type* ArgTyPtr = PointerType::get(ArgTy);
797 Function* NF = Result->getOrInsertFunction("llvm.va_end",
798 RetTy, ArgTyPtr, (Type *)0);
800 while (!F->use_empty()) {
801 CallInst* CI = cast<CallInst>(F->use_back());
802 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
803 new StoreInst(CI->getOperand(1), bar, CI);
804 new CallInst(NF, bar, "", CI);
805 CI->getParent()->getInstList().erase(CI);
807 Result->getFunctionList().erase(F);
810 if(Function* F = Result->getNamedFunction("llvm.va_copy")) {
811 if(F->arg_size() != 1)
812 ThrowException("Obsolete va_copy takes 1 argument!");
815 //a = alloca 1 of typeof(foo)
816 //b = alloca 1 of typeof(foo)
821 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
822 const Type* ArgTy = F->getFunctionType()->getReturnType();
823 const Type* ArgTyPtr = PointerType::get(ArgTy);
824 Function* NF = Result->getOrInsertFunction("llvm.va_copy",
825 RetTy, ArgTyPtr, ArgTyPtr,
828 while (!F->use_empty()) {
829 CallInst* CI = cast<CallInst>(F->use_back());
830 AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
831 AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
832 new StoreInst(CI->getOperand(1), b, CI);
833 new CallInst(NF, a, b, "", CI);
834 Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
835 CI->replaceAllUsesWith(foo);
836 CI->getParent()->getInstList().erase(CI);
838 Result->getFunctionList().erase(F);
846 //===----------------------------------------------------------------------===//
847 // RunVMAsmParser - Define an interface to this parser
848 //===----------------------------------------------------------------------===//
850 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
853 CurFilename = Filename;
854 return RunParser(new Module(CurFilename));
857 Module *llvm::RunVMAsmParser(const char * AsmString, Module * M) {
858 set_scan_string(AsmString);
860 CurFilename = "from_memory";
862 return RunParser(new Module (CurFilename));
871 llvm::Module *ModuleVal;
872 llvm::Function *FunctionVal;
873 std::pair<llvm::PATypeHolder*, char*> *ArgVal;
874 llvm::BasicBlock *BasicBlockVal;
875 llvm::TerminatorInst *TermInstVal;
876 llvm::Instruction *InstVal;
877 llvm::Constant *ConstVal;
879 const llvm::Type *PrimType;
880 llvm::PATypeHolder *TypeVal;
881 llvm::Value *ValueVal;
883 std::vector<std::pair<llvm::PATypeHolder*,char*> > *ArgList;
884 std::vector<llvm::Value*> *ValueList;
885 std::list<llvm::PATypeHolder> *TypeList;
886 // Represent the RHS of PHI node
887 std::list<std::pair<llvm::Value*,
888 llvm::BasicBlock*> > *PHIList;
889 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
890 std::vector<llvm::Constant*> *ConstVector;
892 llvm::GlobalValue::LinkageTypes Linkage;
900 char *StrVal; // This memory is strdup'd!
901 llvm::ValID ValIDVal; // strdup'd memory maybe!
903 llvm::Instruction::BinaryOps BinaryOpVal;
904 llvm::Instruction::TermOps TermOpVal;
905 llvm::Instruction::MemoryOps MemOpVal;
906 llvm::Instruction::OtherOps OtherOpVal;
907 llvm::Module::Endianness Endianness;
910 %type <ModuleVal> Module FunctionList
911 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
912 %type <BasicBlockVal> BasicBlock InstructionList
913 %type <TermInstVal> BBTerminatorInst
914 %type <InstVal> Inst InstVal MemoryInst
915 %type <ConstVal> ConstVal ConstExpr
916 %type <ConstVector> ConstVector
917 %type <ArgList> ArgList ArgListH
918 %type <ArgVal> ArgVal
919 %type <PHIList> PHIList
920 %type <ValueList> ValueRefList ValueRefListE // For call param lists
921 %type <ValueList> IndexList // For GEP derived indices
922 %type <TypeList> TypeListI ArgTypeListI
923 %type <JumpTable> JumpTable
924 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
925 %type <BoolVal> OptVolatile // 'volatile' or not
926 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
927 %type <Linkage> OptLinkage
928 %type <Endianness> BigOrLittle
930 // ValueRef - Unresolved reference to a definition or BB
931 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
932 %type <ValueVal> ResolvedVal // <type> <valref> pair
933 // Tokens and types for handling constant integer values
935 // ESINT64VAL - A negative number within long long range
936 %token <SInt64Val> ESINT64VAL
938 // EUINT64VAL - A positive number within uns. long long range
939 %token <UInt64Val> EUINT64VAL
940 %type <SInt64Val> EINT64VAL
942 %token <SIntVal> SINTVAL // Signed 32 bit ints...
943 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
944 %type <SIntVal> INTVAL
945 %token <FPVal> FPVAL // Float or Double constant
948 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
949 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
950 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
951 %token <PrimType> FLOAT DOUBLE TYPE LABEL
953 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
954 %type <StrVal> Name OptName OptAssign
955 %type <UIntVal> OptAlign OptCAlign
956 %type <StrVal> OptSection SectionString
958 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
959 %token DECLARE GLOBAL CONSTANT SECTION VOLATILE
960 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
961 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
962 %token DEPLIBS CALL TAIL
963 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK
964 %type <UIntVal> OptCallingConv
966 // Basic Block Terminating Operators
967 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
970 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
971 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
972 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comarators
974 // Memory Instructions
975 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
978 %type <OtherOpVal> ShiftOps
979 %token <OtherOpVal> PHI_TOK CAST SELECT SHL SHR VAARG
980 %token VAARG_old VANEXT_old //OBSOLETE
986 // Handle constant integer size restriction and conversion...
990 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
991 ThrowException("Value too large for type!");
996 EINT64VAL : ESINT64VAL; // These have same type and can't cause problems...
997 EINT64VAL : EUINT64VAL {
998 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
999 ThrowException("Value too large for type!");
1003 // Operations that are notably excluded from this list include:
1004 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1006 ArithmeticOps: ADD | SUB | MUL | DIV | REM;
1007 LogicalOps : AND | OR | XOR;
1008 SetCondOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
1010 ShiftOps : SHL | SHR;
1012 // These are some types that allow classification if we only want a particular
1013 // thing... for example, only a signed, unsigned, or integral type.
1014 SIntType : LONG | INT | SHORT | SBYTE;
1015 UIntType : ULONG | UINT | USHORT | UBYTE;
1016 IntType : SIntType | UIntType;
1017 FPType : FLOAT | DOUBLE;
1019 // OptAssign - Value producing statements have an optional assignment component
1020 OptAssign : Name '=' {
1027 OptLinkage : INTERNAL { $$ = GlobalValue::InternalLinkage; } |
1028 LINKONCE { $$ = GlobalValue::LinkOnceLinkage; } |
1029 WEAK { $$ = GlobalValue::WeakLinkage; } |
1030 APPENDING { $$ = GlobalValue::AppendingLinkage; } |
1031 /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
1033 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1034 CCC_TOK { $$ = CallingConv::C; } |
1035 FASTCC_TOK { $$ = CallingConv::Fast; } |
1036 COLDCC_TOK { $$ = CallingConv::Cold; } |
1038 if ((unsigned)$2 != $2)
1039 ThrowException("Calling conv too large!");
1043 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1044 // a comma before it.
1045 OptAlign : /*empty*/ { $$ = 0; } |
1048 if ($$ != 0 && !isPowerOf2_32($$))
1049 ThrowException("Alignment must be a power of two!");
1051 OptCAlign : /*empty*/ { $$ = 0; } |
1052 ',' ALIGN EUINT64VAL {
1054 if ($$ != 0 && !isPowerOf2_32($$))
1055 ThrowException("Alignment must be a power of two!");
1059 SectionString : SECTION STRINGCONSTANT {
1060 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1061 if ($2[i] == '"' || $2[i] == '\\')
1062 ThrowException("Invalid character in section name!");
1066 OptSection : /*empty*/ { $$ = 0; } |
1067 SectionString { $$ = $1; };
1069 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1070 // is set to be the global we are processing.
1072 GlobalVarAttributes : /* empty */ {} |
1073 ',' GlobalVarAttribute GlobalVarAttributes {};
1074 GlobalVarAttribute : SectionString {
1075 CurGV->setSection($1);
1078 | ALIGN EUINT64VAL {
1079 if ($2 != 0 && !isPowerOf2_32($2))
1080 ThrowException("Alignment must be a power of two!");
1081 CurGV->setAlignment($2);
1084 //===----------------------------------------------------------------------===//
1085 // Types includes all predefined types... except void, because it can only be
1086 // used in specific contexts (function returning void for example). To have
1087 // access to it, a user must explicitly use TypesV.
1090 // TypesV includes all of 'Types', but it also includes the void type.
1091 TypesV : Types | VOID { $$ = new PATypeHolder($1); };
1092 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
1095 if (!UpRefs.empty())
1096 ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
1101 // Derived types are added later...
1103 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT ;
1104 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL;
1106 $$ = new PATypeHolder(OpaqueType::get());
1109 $$ = new PATypeHolder($1);
1111 UpRTypes : SymbolicValueRef { // Named types are also simple types...
1112 $$ = new PATypeHolder(getTypeVal($1));
1115 // Include derived types in the Types production.
1117 UpRTypes : '\\' EUINT64VAL { // Type UpReference
1118 if ($2 > (uint64_t)~0U) ThrowException("Value out of range!");
1119 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1120 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1121 $$ = new PATypeHolder(OT);
1122 UR_OUT("New Upreference!\n");
1124 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
1125 std::vector<const Type*> Params;
1126 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1127 E = $3->end(); I != E; ++I)
1128 Params.push_back(*I);
1129 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1130 if (isVarArg) Params.pop_back();
1132 $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
1133 delete $3; // Delete the argument list
1134 delete $1; // Delete the return type handle
1136 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
1137 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1140 | '<' EUINT64VAL 'x' UpRTypes '>' { // Packed array type?
1141 const llvm::Type* ElemTy = $4->get();
1142 if ((unsigned)$2 != $2)
1143 ThrowException("Unsigned result not equal to signed result");
1144 if (!ElemTy->isPrimitiveType())
1145 ThrowException("Elemental type of a PackedType must be primitive");
1146 if (!isPowerOf2_32($2))
1147 ThrowException("Vector length should be a power of 2!");
1148 $$ = new PATypeHolder(HandleUpRefs(PackedType::get(*$4, (unsigned)$2)));
1151 | '{' TypeListI '}' { // Structure type?
1152 std::vector<const Type*> Elements;
1153 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1154 E = $2->end(); I != E; ++I)
1155 Elements.push_back(*I);
1157 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1160 | '{' '}' { // Empty structure type?
1161 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1163 | UpRTypes '*' { // Pointer type?
1164 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1168 // TypeList - Used for struct declarations and as a basis for function type
1169 // declaration type lists
1171 TypeListI : UpRTypes {
1172 $$ = new std::list<PATypeHolder>();
1173 $$->push_back(*$1); delete $1;
1175 | TypeListI ',' UpRTypes {
1176 ($$=$1)->push_back(*$3); delete $3;
1179 // ArgTypeList - List of types for a function type declaration...
1180 ArgTypeListI : TypeListI
1181 | TypeListI ',' DOTDOTDOT {
1182 ($$=$1)->push_back(Type::VoidTy);
1185 ($$ = new std::list<PATypeHolder>())->push_back(Type::VoidTy);
1188 $$ = new std::list<PATypeHolder>();
1191 // ConstVal - The various declarations that go into the constant pool. This
1192 // production is used ONLY to represent constants that show up AFTER a 'const',
1193 // 'constant' or 'global' token at global scope. Constants that can be inlined
1194 // into other expressions (such as integers and constexprs) are handled by the
1195 // ResolvedVal, ValueRef and ConstValueRef productions.
1197 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1198 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1200 ThrowException("Cannot make array constant with type: '" +
1201 (*$1)->getDescription() + "'!");
1202 const Type *ETy = ATy->getElementType();
1203 int NumElements = ATy->getNumElements();
1205 // Verify that we have the correct size...
1206 if (NumElements != -1 && NumElements != (int)$3->size())
1207 ThrowException("Type mismatch: constant sized array initialized with " +
1208 utostr($3->size()) + " arguments, but has size of " +
1209 itostr(NumElements) + "!");
1211 // Verify all elements are correct type!
1212 for (unsigned i = 0; i < $3->size(); i++) {
1213 if (ETy != (*$3)[i]->getType())
1214 ThrowException("Element #" + utostr(i) + " is not of type '" +
1215 ETy->getDescription() +"' as required!\nIt is of type '"+
1216 (*$3)[i]->getType()->getDescription() + "'.");
1219 $$ = ConstantArray::get(ATy, *$3);
1220 delete $1; delete $3;
1223 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1225 ThrowException("Cannot make array constant with type: '" +
1226 (*$1)->getDescription() + "'!");
1228 int NumElements = ATy->getNumElements();
1229 if (NumElements != -1 && NumElements != 0)
1230 ThrowException("Type mismatch: constant sized array initialized with 0"
1231 " arguments, but has size of " + itostr(NumElements) +"!");
1232 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1235 | Types 'c' STRINGCONSTANT {
1236 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1238 ThrowException("Cannot make array constant with type: '" +
1239 (*$1)->getDescription() + "'!");
1241 int NumElements = ATy->getNumElements();
1242 const Type *ETy = ATy->getElementType();
1243 char *EndStr = UnEscapeLexed($3, true);
1244 if (NumElements != -1 && NumElements != (EndStr-$3))
1245 ThrowException("Can't build string constant of size " +
1246 itostr((int)(EndStr-$3)) +
1247 " when array has size " + itostr(NumElements) + "!");
1248 std::vector<Constant*> Vals;
1249 if (ETy == Type::SByteTy) {
1250 for (char *C = $3; C != EndStr; ++C)
1251 Vals.push_back(ConstantSInt::get(ETy, *C));
1252 } else if (ETy == Type::UByteTy) {
1253 for (char *C = $3; C != EndStr; ++C)
1254 Vals.push_back(ConstantUInt::get(ETy, (unsigned char)*C));
1257 ThrowException("Cannot build string arrays of non byte sized elements!");
1260 $$ = ConstantArray::get(ATy, Vals);
1263 | Types '<' ConstVector '>' { // Nonempty unsized arr
1264 const PackedType *PTy = dyn_cast<PackedType>($1->get());
1266 ThrowException("Cannot make packed constant with type: '" +
1267 (*$1)->getDescription() + "'!");
1268 const Type *ETy = PTy->getElementType();
1269 int NumElements = PTy->getNumElements();
1271 // Verify that we have the correct size...
1272 if (NumElements != -1 && NumElements != (int)$3->size())
1273 ThrowException("Type mismatch: constant sized packed initialized with " +
1274 utostr($3->size()) + " arguments, but has size of " +
1275 itostr(NumElements) + "!");
1277 // Verify all elements are correct type!
1278 for (unsigned i = 0; i < $3->size(); i++) {
1279 if (ETy != (*$3)[i]->getType())
1280 ThrowException("Element #" + utostr(i) + " is not of type '" +
1281 ETy->getDescription() +"' as required!\nIt is of type '"+
1282 (*$3)[i]->getType()->getDescription() + "'.");
1285 $$ = ConstantPacked::get(PTy, *$3);
1286 delete $1; delete $3;
1288 | Types '{' ConstVector '}' {
1289 const StructType *STy = dyn_cast<StructType>($1->get());
1291 ThrowException("Cannot make struct constant with type: '" +
1292 (*$1)->getDescription() + "'!");
1294 if ($3->size() != STy->getNumContainedTypes())
1295 ThrowException("Illegal number of initializers for structure type!");
1297 // Check to ensure that constants are compatible with the type initializer!
1298 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1299 if ((*$3)[i]->getType() != STy->getElementType(i))
1300 ThrowException("Expected type '" +
1301 STy->getElementType(i)->getDescription() +
1302 "' for element #" + utostr(i) +
1303 " of structure initializer!");
1305 $$ = ConstantStruct::get(STy, *$3);
1306 delete $1; delete $3;
1309 const StructType *STy = dyn_cast<StructType>($1->get());
1311 ThrowException("Cannot make struct constant with type: '" +
1312 (*$1)->getDescription() + "'!");
1314 if (STy->getNumContainedTypes() != 0)
1315 ThrowException("Illegal number of initializers for structure type!");
1317 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1321 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1323 ThrowException("Cannot make null pointer constant with type: '" +
1324 (*$1)->getDescription() + "'!");
1326 $$ = ConstantPointerNull::get(PTy);
1330 $$ = UndefValue::get($1->get());
1333 | Types SymbolicValueRef {
1334 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1336 ThrowException("Global const reference must be a pointer type!");
1338 // ConstExprs can exist in the body of a function, thus creating
1339 // GlobalValues whenever they refer to a variable. Because we are in
1340 // the context of a function, getValNonImprovising will search the functions
1341 // symbol table instead of the module symbol table for the global symbol,
1342 // which throws things all off. To get around this, we just tell
1343 // getValNonImprovising that we are at global scope here.
1345 Function *SavedCurFn = CurFun.CurrentFunction;
1346 CurFun.CurrentFunction = 0;
1348 Value *V = getValNonImprovising(Ty, $2);
1350 CurFun.CurrentFunction = SavedCurFn;
1352 // If this is an initializer for a constant pointer, which is referencing a
1353 // (currently) undefined variable, create a stub now that shall be replaced
1354 // in the future with the right type of variable.
1357 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1358 const PointerType *PT = cast<PointerType>(Ty);
1360 // First check to see if the forward references value is already created!
1361 PerModuleInfo::GlobalRefsType::iterator I =
1362 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1364 if (I != CurModule.GlobalRefs.end()) {
1365 V = I->second; // Placeholder already exists, use it...
1369 if ($2.Type == ValID::NameVal) Name = $2.Name;
1371 // Create the forward referenced global.
1373 if (const FunctionType *FTy =
1374 dyn_cast<FunctionType>(PT->getElementType())) {
1375 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1376 CurModule.CurrentModule);
1378 GV = new GlobalVariable(PT->getElementType(), false,
1379 GlobalValue::ExternalLinkage, 0,
1380 Name, CurModule.CurrentModule);
1383 // Keep track of the fact that we have a forward ref to recycle it
1384 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1389 $$ = cast<GlobalValue>(V);
1390 delete $1; // Free the type handle
1393 if ($1->get() != $2->getType())
1394 ThrowException("Mismatched types for constant expression!");
1398 | Types ZEROINITIALIZER {
1399 const Type *Ty = $1->get();
1400 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1401 ThrowException("Cannot create a null initialized value of this type!");
1402 $$ = Constant::getNullValue(Ty);
1406 ConstVal : SIntType EINT64VAL { // integral constants
1407 if (!ConstantSInt::isValueValidForType($1, $2))
1408 ThrowException("Constant value doesn't fit in type!");
1409 $$ = ConstantSInt::get($1, $2);
1411 | UIntType EUINT64VAL { // integral constants
1412 if (!ConstantUInt::isValueValidForType($1, $2))
1413 ThrowException("Constant value doesn't fit in type!");
1414 $$ = ConstantUInt::get($1, $2);
1416 | BOOL TRUETOK { // Boolean constants
1417 $$ = ConstantBool::True;
1419 | BOOL FALSETOK { // Boolean constants
1420 $$ = ConstantBool::False;
1422 | FPType FPVAL { // Float & Double constants
1423 if (!ConstantFP::isValueValidForType($1, $2))
1424 ThrowException("Floating point constant invalid for type!!");
1425 $$ = ConstantFP::get($1, $2);
1429 ConstExpr: CAST '(' ConstVal TO Types ')' {
1430 if (!$3->getType()->isFirstClassType())
1431 ThrowException("cast constant expression from a non-primitive type: '" +
1432 $3->getType()->getDescription() + "'!");
1433 if (!$5->get()->isFirstClassType())
1434 ThrowException("cast constant expression to a non-primitive type: '" +
1435 $5->get()->getDescription() + "'!");
1436 $$ = ConstantExpr::getCast($3, $5->get());
1439 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1440 if (!isa<PointerType>($3->getType()))
1441 ThrowException("GetElementPtr requires a pointer operand!");
1443 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
1444 // indices to uint struct indices for compatibility.
1445 generic_gep_type_iterator<std::vector<Value*>::iterator>
1446 GTI = gep_type_begin($3->getType(), $4->begin(), $4->end()),
1447 GTE = gep_type_end($3->getType(), $4->begin(), $4->end());
1448 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
1449 if (isa<StructType>(*GTI)) // Only change struct indices
1450 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
1451 if (CUI->getType() == Type::UByteTy)
1452 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
1455 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1457 ThrowException("Index list invalid for constant getelementptr!");
1459 std::vector<Constant*> IdxVec;
1460 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1461 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1462 IdxVec.push_back(C);
1464 ThrowException("Indices to constant getelementptr must be constants!");
1468 $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1470 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1471 if ($3->getType() != Type::BoolTy)
1472 ThrowException("Select condition must be of boolean type!");
1473 if ($5->getType() != $7->getType())
1474 ThrowException("Select operand types must match!");
1475 $$ = ConstantExpr::getSelect($3, $5, $7);
1477 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1478 if ($3->getType() != $5->getType())
1479 ThrowException("Binary operator types must match!");
1480 // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
1481 // To retain backward compatibility with these early compilers, we emit a
1482 // cast to the appropriate integer type automatically if we are in the
1483 // broken case. See PR424 for more information.
1484 if (!isa<PointerType>($3->getType())) {
1485 $$ = ConstantExpr::get($1, $3, $5);
1487 const Type *IntPtrTy = 0;
1488 switch (CurModule.CurrentModule->getPointerSize()) {
1489 case Module::Pointer32: IntPtrTy = Type::IntTy; break;
1490 case Module::Pointer64: IntPtrTy = Type::LongTy; break;
1491 default: ThrowException("invalid pointer binary constant expr!");
1493 $$ = ConstantExpr::get($1, ConstantExpr::getCast($3, IntPtrTy),
1494 ConstantExpr::getCast($5, IntPtrTy));
1495 $$ = ConstantExpr::getCast($$, $3->getType());
1498 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1499 if ($3->getType() != $5->getType())
1500 ThrowException("Logical operator types must match!");
1501 if (!$3->getType()->isIntegral())
1502 ThrowException("Logical operands must have integral types!");
1503 $$ = ConstantExpr::get($1, $3, $5);
1505 | SetCondOps '(' ConstVal ',' ConstVal ')' {
1506 if ($3->getType() != $5->getType())
1507 ThrowException("setcc operand types must match!");
1508 $$ = ConstantExpr::get($1, $3, $5);
1510 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1511 if ($5->getType() != Type::UByteTy)
1512 ThrowException("Shift count for shift constant must be unsigned byte!");
1513 if (!$3->getType()->isInteger())
1514 ThrowException("Shift constant expression requires integer operand!");
1515 $$ = ConstantExpr::get($1, $3, $5);
1519 // ConstVector - A list of comma separated constants.
1520 ConstVector : ConstVector ',' ConstVal {
1521 ($$ = $1)->push_back($3);
1524 $$ = new std::vector<Constant*>();
1529 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1530 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1533 //===----------------------------------------------------------------------===//
1534 // Rules to match Modules
1535 //===----------------------------------------------------------------------===//
1537 // Module rule: Capture the result of parsing the whole file into a result
1540 Module : FunctionList {
1541 $$ = ParserResult = $1;
1542 CurModule.ModuleDone();
1545 // FunctionList - A list of functions, preceeded by a constant pool.
1547 FunctionList : FunctionList Function {
1549 CurFun.FunctionDone();
1551 | FunctionList FunctionProto {
1554 | FunctionList IMPLEMENTATION {
1558 $$ = CurModule.CurrentModule;
1559 // Emit an error if there are any unresolved types left.
1560 if (!CurModule.LateResolveTypes.empty()) {
1561 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
1562 if (DID.Type == ValID::NameVal)
1563 ThrowException("Reference to an undefined type: '"+DID.getName() + "'");
1565 ThrowException("Reference to an undefined type: #" + itostr(DID.Num));
1569 // ConstPool - Constants with optional names assigned to them.
1570 ConstPool : ConstPool OptAssign TYPE TypesV {
1571 // Eagerly resolve types. This is not an optimization, this is a
1572 // requirement that is due to the fact that we could have this:
1574 // %list = type { %list * }
1575 // %list = type { %list * } ; repeated type decl
1577 // If types are not resolved eagerly, then the two types will not be
1578 // determined to be the same type!
1580 ResolveTypeTo($2, *$4);
1582 if (!setTypeName(*$4, $2) && !$2) {
1583 // If this is a named type that is not a redefinition, add it to the slot
1585 CurModule.Types.push_back(*$4);
1590 | ConstPool FunctionProto { // Function prototypes can be in const pool
1592 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
1593 if ($5 == 0) ThrowException("Global value initializer is not a constant!");
1594 CurGV = ParseGlobalVariable($2, $3, $4, $5->getType(), $5);
1595 } GlobalVarAttributes {
1598 | ConstPool OptAssign EXTERNAL GlobalType Types {
1599 CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage,
1602 } GlobalVarAttributes {
1605 | ConstPool TARGET TargetDefinition {
1607 | ConstPool DEPLIBS '=' LibrariesDefinition {
1609 | /* empty: end of list */ {
1614 BigOrLittle : BIG { $$ = Module::BigEndian; };
1615 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1617 TargetDefinition : ENDIAN '=' BigOrLittle {
1618 CurModule.CurrentModule->setEndianness($3);
1620 | POINTERSIZE '=' EUINT64VAL {
1622 CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1624 CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1626 ThrowException("Invalid pointer size: '" + utostr($3) + "'!");
1628 | TRIPLE '=' STRINGCONSTANT {
1629 CurModule.CurrentModule->setTargetTriple($3);
1633 LibrariesDefinition : '[' LibList ']';
1635 LibList : LibList ',' STRINGCONSTANT {
1636 CurModule.CurrentModule->addLibrary($3);
1640 CurModule.CurrentModule->addLibrary($1);
1643 | /* empty: end of list */ {
1647 //===----------------------------------------------------------------------===//
1648 // Rules to match Function Headers
1649 //===----------------------------------------------------------------------===//
1651 Name : VAR_ID | STRINGCONSTANT;
1652 OptName : Name | /*empty*/ { $$ = 0; };
1654 ArgVal : Types OptName {
1655 if (*$1 == Type::VoidTy)
1656 ThrowException("void typed arguments are invalid!");
1657 $$ = new std::pair<PATypeHolder*, char*>($1, $2);
1660 ArgListH : ArgListH ',' ArgVal {
1666 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1671 ArgList : ArgListH {
1674 | ArgListH ',' DOTDOTDOT {
1676 $$->push_back(std::pair<PATypeHolder*,
1677 char*>(new PATypeHolder(Type::VoidTy), 0));
1680 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1681 $$->push_back(std::make_pair(new PATypeHolder(Type::VoidTy), (char*)0));
1687 FunctionHeaderH : OptCallingConv TypesV Name '(' ArgList ')'
1688 OptSection OptAlign {
1690 std::string FunctionName($3);
1691 free($3); // Free strdup'd memory!
1693 if (!(*$2)->isFirstClassType() && *$2 != Type::VoidTy)
1694 ThrowException("LLVM functions cannot return aggregate types!");
1696 std::vector<const Type*> ParamTypeList;
1697 if ($5) { // If there are arguments...
1698 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
1699 I != $5->end(); ++I)
1700 ParamTypeList.push_back(I->first->get());
1703 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1704 if (isVarArg) ParamTypeList.pop_back();
1706 const FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
1707 const PointerType *PFT = PointerType::get(FT);
1711 if (!FunctionName.empty()) {
1712 ID = ValID::create((char*)FunctionName.c_str());
1714 ID = ValID::create((int)CurModule.Values[PFT].size());
1718 // See if this function was forward referenced. If so, recycle the object.
1719 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
1720 // Move the function to the end of the list, from whereever it was
1721 // previously inserted.
1722 Fn = cast<Function>(FWRef);
1723 CurModule.CurrentModule->getFunctionList().remove(Fn);
1724 CurModule.CurrentModule->getFunctionList().push_back(Fn);
1725 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
1726 (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
1727 // If this is the case, either we need to be a forward decl, or it needs
1729 if (!CurFun.isDeclare && !Fn->isExternal())
1730 ThrowException("Redefinition of function '" + FunctionName + "'!");
1732 // Make sure to strip off any argument names so we can't get conflicts.
1733 if (Fn->isExternal())
1734 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
1738 } else { // Not already defined?
1739 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
1740 CurModule.CurrentModule);
1741 InsertValue(Fn, CurModule.Values);
1744 CurFun.FunctionStart(Fn);
1745 Fn->setCallingConv($1);
1746 Fn->setAlignment($8);
1752 // Add all of the arguments we parsed to the function...
1753 if ($5) { // Is null if empty...
1754 if (isVarArg) { // Nuke the last entry
1755 assert($5->back().first->get() == Type::VoidTy && $5->back().second == 0&&
1756 "Not a varargs marker!");
1757 delete $5->back().first;
1758 $5->pop_back(); // Delete the last entry
1760 Function::arg_iterator ArgIt = Fn->arg_begin();
1761 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
1762 I != $5->end(); ++I, ++ArgIt) {
1763 delete I->first; // Delete the typeholder...
1765 setValueName(ArgIt, I->second); // Insert arg into symtab...
1769 delete $5; // We're now done with the argument list
1773 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
1775 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
1776 $$ = CurFun.CurrentFunction;
1778 // Make sure that we keep track of the linkage type even if there was a
1779 // previous "declare".
1783 END : ENDTOK | '}'; // Allow end of '}' to end a function
1785 Function : BasicBlockList END {
1789 FunctionProto : DECLARE { CurFun.isDeclare = true; } FunctionHeaderH {
1790 $$ = CurFun.CurrentFunction;
1791 CurFun.FunctionDone();
1794 //===----------------------------------------------------------------------===//
1795 // Rules to match Basic Blocks
1796 //===----------------------------------------------------------------------===//
1798 ConstValueRef : ESINT64VAL { // A reference to a direct constant
1799 $$ = ValID::create($1);
1802 $$ = ValID::create($1);
1804 | FPVAL { // Perhaps it's an FP constant?
1805 $$ = ValID::create($1);
1808 $$ = ValID::create(ConstantBool::True);
1811 $$ = ValID::create(ConstantBool::False);
1814 $$ = ValID::createNull();
1817 $$ = ValID::createUndef();
1819 | '<' ConstVector '>' { // Nonempty unsized packed vector
1820 const Type *ETy = (*$2)[0]->getType();
1821 int NumElements = $2->size();
1823 PackedType* pt = PackedType::get(ETy, NumElements);
1824 PATypeHolder* PTy = new PATypeHolder(
1832 // Verify all elements are correct type!
1833 for (unsigned i = 0; i < $2->size(); i++) {
1834 if (ETy != (*$2)[i]->getType())
1835 ThrowException("Element #" + utostr(i) + " is not of type '" +
1836 ETy->getDescription() +"' as required!\nIt is of type '" +
1837 (*$2)[i]->getType()->getDescription() + "'.");
1840 $$ = ValID::create(ConstantPacked::get(pt, *$2));
1841 delete PTy; delete $2;
1844 $$ = ValID::create($1);
1847 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1850 SymbolicValueRef : INTVAL { // Is it an integer reference...?
1851 $$ = ValID::create($1);
1853 | Name { // Is it a named reference...?
1854 $$ = ValID::create($1);
1857 // ValueRef - A reference to a definition... either constant or symbolic
1858 ValueRef : SymbolicValueRef | ConstValueRef;
1861 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
1862 // type immediately preceeds the value reference, and allows complex constant
1863 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1864 ResolvedVal : Types ValueRef {
1865 $$ = getVal(*$1, $2); delete $1;
1868 BasicBlockList : BasicBlockList BasicBlock {
1871 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
1876 // Basic blocks are terminated by branching instructions:
1877 // br, br/cc, switch, ret
1879 BasicBlock : InstructionList OptAssign BBTerminatorInst {
1880 setValueName($3, $2);
1883 $1->getInstList().push_back($3);
1888 InstructionList : InstructionList Inst {
1889 $1->getInstList().push_back($2);
1893 $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
1895 // Make sure to move the basic block to the correct location in the
1896 // function, instead of leaving it inserted wherever it was first
1898 Function::BasicBlockListType &BBL =
1899 CurFun.CurrentFunction->getBasicBlockList();
1900 BBL.splice(BBL.end(), BBL, $$);
1903 $$ = CurBB = getBBVal(ValID::create($1), true);
1905 // Make sure to move the basic block to the correct location in the
1906 // function, instead of leaving it inserted wherever it was first
1908 Function::BasicBlockListType &BBL =
1909 CurFun.CurrentFunction->getBasicBlockList();
1910 BBL.splice(BBL.end(), BBL, $$);
1913 BBTerminatorInst : RET ResolvedVal { // Return with a result...
1914 $$ = new ReturnInst($2);
1916 | RET VOID { // Return with no result...
1917 $$ = new ReturnInst();
1919 | BR LABEL ValueRef { // Unconditional Branch...
1920 $$ = new BranchInst(getBBVal($3));
1921 } // Conditional Branch...
1922 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
1923 $$ = new BranchInst(getBBVal($6), getBBVal($9), getVal(Type::BoolTy, $3));
1925 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1926 SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6), $8->size());
1929 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
1931 for (; I != E; ++I) {
1932 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
1933 S->addCase(CI, I->second);
1935 ThrowException("Switch case is constant, but not a simple integer!");
1939 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
1940 SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6), 0);
1943 | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
1944 TO LABEL ValueRef UNWIND LABEL ValueRef {
1945 const PointerType *PFTy;
1946 const FunctionType *Ty;
1948 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
1949 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1950 // Pull out the types of all of the arguments...
1951 std::vector<const Type*> ParamTypes;
1953 for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
1955 ParamTypes.push_back((*I)->getType());
1958 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1959 if (isVarArg) ParamTypes.pop_back();
1961 Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
1962 PFTy = PointerType::get(Ty);
1965 Value *V = getVal(PFTy, $4); // Get the function we're calling...
1967 BasicBlock *Normal = getBBVal($10);
1968 BasicBlock *Except = getBBVal($13);
1970 // Create the call node...
1971 if (!$6) { // Has no arguments?
1972 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
1973 } else { // Has arguments?
1974 // Loop through FunctionType's arguments and ensure they are specified
1977 FunctionType::param_iterator I = Ty->param_begin();
1978 FunctionType::param_iterator E = Ty->param_end();
1979 std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
1981 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1982 if ((*ArgI)->getType() != *I)
1983 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1984 (*I)->getDescription() + "'!");
1986 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1987 ThrowException("Invalid number of parameters detected!");
1989 $$ = new InvokeInst(V, Normal, Except, *$6);
1991 cast<InvokeInst>($$)->setCallingConv($2);
1997 $$ = new UnwindInst();
2000 $$ = new UnreachableInst();
2005 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2007 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
2009 ThrowException("May only switch on a constant pool value!");
2011 $$->push_back(std::make_pair(V, getBBVal($6)));
2013 | IntType ConstValueRef ',' LABEL ValueRef {
2014 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2015 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
2018 ThrowException("May only switch on a constant pool value!");
2020 $$->push_back(std::make_pair(V, getBBVal($5)));
2023 Inst : OptAssign InstVal {
2024 // Is this definition named?? if so, assign the name...
2025 setValueName($2, $1);
2030 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2031 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2032 $$->push_back(std::make_pair(getVal(*$1, $3), getBBVal($5)));
2035 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2037 $1->push_back(std::make_pair(getVal($1->front().first->getType(), $4),
2042 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
2043 $$ = new std::vector<Value*>();
2046 | ValueRefList ',' ResolvedVal {
2051 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
2052 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
2054 OptTailCall : TAIL CALL {
2063 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2064 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
2065 !isa<PackedType>((*$2).get()))
2067 "Arithmetic operator requires integer, FP, or packed operands!");
2068 if (isa<PackedType>((*$2).get()) && $1 == Instruction::Rem)
2069 ThrowException("Rem not supported on packed types!");
2070 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
2072 ThrowException("binary operator returned null!");
2075 | LogicalOps Types ValueRef ',' ValueRef {
2076 if (!(*$2)->isIntegral())
2077 ThrowException("Logical operator requires integral operands!");
2078 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
2080 ThrowException("binary operator returned null!");
2083 | SetCondOps Types ValueRef ',' ValueRef {
2084 if(isa<PackedType>((*$2).get())) {
2086 "PackedTypes currently not supported in setcc instructions!");
2088 $$ = new SetCondInst($1, getVal(*$2, $3), getVal(*$2, $5));
2090 ThrowException("binary operator returned null!");
2094 std::cerr << "WARNING: Use of eliminated 'not' instruction:"
2095 << " Replacing with 'xor'.\n";
2097 Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
2099 ThrowException("Expected integral type for not instruction!");
2101 $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
2103 ThrowException("Could not create a xor instruction!");
2105 | ShiftOps ResolvedVal ',' ResolvedVal {
2106 if ($4->getType() != Type::UByteTy)
2107 ThrowException("Shift amount must be ubyte!");
2108 if (!$2->getType()->isInteger())
2109 ThrowException("Shift constant expression requires integer operand!");
2110 $$ = new ShiftInst($1, $2, $4);
2112 | CAST ResolvedVal TO Types {
2113 if (!$4->get()->isFirstClassType())
2114 ThrowException("cast instruction to a non-primitive type: '" +
2115 $4->get()->getDescription() + "'!");
2116 $$ = new CastInst($2, *$4);
2119 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2120 if ($2->getType() != Type::BoolTy)
2121 ThrowException("select condition must be boolean!");
2122 if ($4->getType() != $6->getType())
2123 ThrowException("select value types should match!");
2124 $$ = new SelectInst($2, $4, $6);
2126 | VAARG ResolvedVal ',' Types {
2128 $$ = new VAArgInst($2, *$4);
2131 | VAARG_old ResolvedVal ',' Types {
2132 ObsoleteVarArgs = true;
2133 const Type* ArgTy = $2->getType();
2134 Function* NF = CurModule.CurrentModule->
2135 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0);
2138 //foo = alloca 1 of t
2142 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
2143 CurBB->getInstList().push_back(foo);
2144 CallInst* bar = new CallInst(NF, $2);
2145 CurBB->getInstList().push_back(bar);
2146 CurBB->getInstList().push_back(new StoreInst(bar, foo));
2147 $$ = new VAArgInst(foo, *$4);
2150 | VANEXT_old ResolvedVal ',' Types {
2151 ObsoleteVarArgs = true;
2152 const Type* ArgTy = $2->getType();
2153 Function* NF = CurModule.CurrentModule->
2154 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0);
2156 //b = vanext a, t ->
2157 //foo = alloca 1 of t
2160 //tmp = vaarg foo, t
2162 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
2163 CurBB->getInstList().push_back(foo);
2164 CallInst* bar = new CallInst(NF, $2);
2165 CurBB->getInstList().push_back(bar);
2166 CurBB->getInstList().push_back(new StoreInst(bar, foo));
2167 Instruction* tmp = new VAArgInst(foo, *$4);
2168 CurBB->getInstList().push_back(tmp);
2169 $$ = new LoadInst(foo);
2173 const Type *Ty = $2->front().first->getType();
2174 if (!Ty->isFirstClassType())
2175 ThrowException("PHI node operands must be of first class type!");
2176 $$ = new PHINode(Ty);
2177 ((PHINode*)$$)->reserveOperandSpace($2->size());
2178 while ($2->begin() != $2->end()) {
2179 if ($2->front().first->getType() != Ty)
2180 ThrowException("All elements of a PHI node must be of the same type!");
2181 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2184 delete $2; // Free the list...
2186 | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')' {
2187 const PointerType *PFTy;
2188 const FunctionType *Ty;
2190 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2191 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2192 // Pull out the types of all of the arguments...
2193 std::vector<const Type*> ParamTypes;
2195 for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
2197 ParamTypes.push_back((*I)->getType());
2200 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2201 if (isVarArg) ParamTypes.pop_back();
2203 if (!(*$3)->isFirstClassType() && *$3 != Type::VoidTy)
2204 ThrowException("LLVM functions cannot return aggregate types!");
2206 Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
2207 PFTy = PointerType::get(Ty);
2210 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2212 // Create the call node...
2213 if (!$6) { // Has no arguments?
2214 // Make sure no arguments is a good thing!
2215 if (Ty->getNumParams() != 0)
2216 ThrowException("No arguments passed to a function that "
2217 "expects arguments!");
2219 $$ = new CallInst(V, std::vector<Value*>());
2220 } else { // Has arguments?
2221 // Loop through FunctionType's arguments and ensure they are specified
2224 FunctionType::param_iterator I = Ty->param_begin();
2225 FunctionType::param_iterator E = Ty->param_end();
2226 std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
2228 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2229 if ((*ArgI)->getType() != *I)
2230 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2231 (*I)->getDescription() + "'!");
2233 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2234 ThrowException("Invalid number of parameters detected!");
2236 $$ = new CallInst(V, *$6);
2238 cast<CallInst>($$)->setTailCall($1);
2239 cast<CallInst>($$)->setCallingConv($2);
2248 // IndexList - List of indices for GEP based instructions...
2249 IndexList : ',' ValueRefList {
2252 $$ = new std::vector<Value*>();
2255 OptVolatile : VOLATILE {
2264 MemoryInst : MALLOC Types OptCAlign {
2265 $$ = new MallocInst(*$2, 0, $3);
2268 | MALLOC Types ',' UINT ValueRef OptCAlign {
2269 $$ = new MallocInst(*$2, getVal($4, $5), $6);
2272 | ALLOCA Types OptCAlign {
2273 $$ = new AllocaInst(*$2, 0, $3);
2276 | ALLOCA Types ',' UINT ValueRef OptCAlign {
2277 $$ = new AllocaInst(*$2, getVal($4, $5), $6);
2280 | FREE ResolvedVal {
2281 if (!isa<PointerType>($2->getType()))
2282 ThrowException("Trying to free nonpointer type " +
2283 $2->getType()->getDescription() + "!");
2284 $$ = new FreeInst($2);
2287 | OptVolatile LOAD Types ValueRef {
2288 if (!isa<PointerType>($3->get()))
2289 ThrowException("Can't load from nonpointer type: " +
2290 (*$3)->getDescription());
2291 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
2292 ThrowException("Can't load from pointer of non-first-class type: " +
2293 (*$3)->getDescription());
2294 $$ = new LoadInst(getVal(*$3, $4), "", $1);
2297 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2298 const PointerType *PT = dyn_cast<PointerType>($5->get());
2300 ThrowException("Can't store to a nonpointer type: " +
2301 (*$5)->getDescription());
2302 const Type *ElTy = PT->getElementType();
2303 if (ElTy != $3->getType())
2304 ThrowException("Can't store '" + $3->getType()->getDescription() +
2305 "' into space of type '" + ElTy->getDescription() + "'!");
2307 $$ = new StoreInst($3, getVal(*$5, $6), $1);
2310 | GETELEMENTPTR Types ValueRef IndexList {
2311 if (!isa<PointerType>($2->get()))
2312 ThrowException("getelementptr insn requires pointer operand!");
2314 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
2315 // indices to uint struct indices for compatibility.
2316 generic_gep_type_iterator<std::vector<Value*>::iterator>
2317 GTI = gep_type_begin($2->get(), $4->begin(), $4->end()),
2318 GTE = gep_type_end($2->get(), $4->begin(), $4->end());
2319 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
2320 if (isa<StructType>(*GTI)) // Only change struct indices
2321 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
2322 if (CUI->getType() == Type::UByteTy)
2323 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
2325 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2326 ThrowException("Invalid getelementptr indices for type '" +
2327 (*$2)->getDescription()+ "'!");
2328 $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
2329 delete $2; delete $4;
2334 int yyerror(const char *ErrorMsg) {
2336 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2337 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2338 std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2339 if (yychar == YYEMPTY || yychar == 0)
2340 errMsg += "end-of-file.";
2342 errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2343 ThrowException(errMsg);