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/Assembly/AutoUpgrade.h"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/Support/MathExtras.h"
29 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
30 int yylex(); // declaration" of xxx warnings.
34 std::string CurFilename;
38 static Module *ParserResult;
40 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
41 // relating to upreferences in the input stream.
43 //#define DEBUG_UPREFS 1
45 #define UR_OUT(X) std::cerr << X
50 #define YYERROR_VERBOSE 1
52 static bool ObsoleteVarArgs;
53 static bool NewVarArgs;
54 static BasicBlock *CurBB;
55 static GlobalVariable *CurGV;
58 // This contains info used when building the body of a function. It is
59 // destroyed when the function is completed.
61 typedef std::vector<Value *> ValueList; // Numbered defs
63 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
64 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
66 static struct PerModuleInfo {
67 Module *CurrentModule;
68 std::map<const Type *, ValueList> Values; // Module level numbered definitions
69 std::map<const Type *,ValueList> LateResolveValues;
70 std::vector<PATypeHolder> Types;
71 std::map<ValID, PATypeHolder> LateResolveTypes;
73 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
74 /// how they were referenced and one which line of the input they came from so
75 /// that we can resolve them later and print error messages as appropriate.
76 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
78 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
79 // references to global values. Global values may be referenced before they
80 // are defined, and if so, the temporary object that they represent is held
81 // here. This is used for forward references of GlobalValues.
83 typedef std::map<std::pair<const PointerType *,
84 ValID>, GlobalValue*> GlobalRefsType;
85 GlobalRefsType GlobalRefs;
88 // If we could not resolve some functions at function compilation time
89 // (calls to functions before they are defined), resolve them now... Types
90 // are resolved when the constant pool has been completely parsed.
92 ResolveDefinitions(LateResolveValues);
94 // Check to make sure that all global value forward references have been
97 if (!GlobalRefs.empty()) {
98 std::string UndefinedReferences = "Unresolved global references exist:\n";
100 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
102 UndefinedReferences += " " + I->first.first->getDescription() + " " +
103 I->first.second.getName() + "\n";
105 ThrowException(UndefinedReferences);
108 // Look for intrinsic functions and CallInst that need to be upgraded
109 for (Module::iterator FI = CurrentModule->begin(),FE = CurrentModule->end();
111 UpgradeCallsToIntrinsic(FI);
113 Values.clear(); // Clear out function local definitions
118 // GetForwardRefForGlobal - Check to see if there is a forward reference
119 // for this global. If so, remove it from the GlobalRefs map and return it.
120 // If not, just return null.
121 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
122 // Check to see if there is a forward reference to this global variable...
123 // if there is, eliminate it and patch the reference to use the new def'n.
124 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
125 GlobalValue *Ret = 0;
126 if (I != GlobalRefs.end()) {
134 static struct PerFunctionInfo {
135 Function *CurrentFunction; // Pointer to current function being created
137 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
138 std::map<const Type*, ValueList> LateResolveValues;
139 bool isDeclare; // Is this function a forward declararation?
141 /// BBForwardRefs - When we see forward references to basic blocks, keep
142 /// track of them here.
143 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
144 std::vector<BasicBlock*> NumberedBlocks;
147 inline PerFunctionInfo() {
152 inline void FunctionStart(Function *M) {
157 void FunctionDone() {
158 NumberedBlocks.clear();
160 // Any forward referenced blocks left?
161 if (!BBForwardRefs.empty())
162 ThrowException("Undefined reference to label " +
163 BBForwardRefs.begin()->first->getName());
165 // Resolve all forward references now.
166 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
168 Values.clear(); // Clear out function local definitions
172 } CurFun; // Info for the current function...
174 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
177 //===----------------------------------------------------------------------===//
178 // Code to handle definitions of all the types
179 //===----------------------------------------------------------------------===//
181 static int InsertValue(Value *V,
182 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
183 if (V->hasName()) return -1; // Is this a numbered definition?
185 // Yes, insert the value into the value table...
186 ValueList &List = ValueTab[V->getType()];
188 return List.size()-1;
191 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
193 case ValID::NumberVal: // Is it a numbered definition?
194 // Module constants occupy the lowest numbered slots...
195 if ((unsigned)D.Num < CurModule.Types.size())
196 return CurModule.Types[(unsigned)D.Num];
198 case ValID::NameVal: // Is it a named definition?
199 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
200 D.destroy(); // Free old strdup'd memory...
205 ThrowException("Internal parser error: Invalid symbol type reference!");
208 // If we reached here, we referenced either a symbol that we don't know about
209 // or an id number that hasn't been read yet. We may be referencing something
210 // forward, so just create an entry to be resolved later and get to it...
212 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
215 if (inFunctionScope()) {
216 if (D.Type == ValID::NameVal)
217 ThrowException("Reference to an undefined type: '" + D.getName() + "'");
219 ThrowException("Reference to an undefined type: #" + itostr(D.Num));
222 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
223 if (I != CurModule.LateResolveTypes.end())
226 Type *Typ = OpaqueType::get();
227 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
231 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
232 SymbolTable &SymTab =
233 inFunctionScope() ? CurFun.CurrentFunction->getSymbolTable() :
234 CurModule.CurrentModule->getSymbolTable();
235 return SymTab.lookup(Ty, Name);
238 // getValNonImprovising - Look up the value specified by the provided type and
239 // the provided ValID. If the value exists and has already been defined, return
240 // it. Otherwise return null.
242 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
243 if (isa<FunctionType>(Ty))
244 ThrowException("Functions are not values and "
245 "must be referenced as pointers");
248 case ValID::NumberVal: { // Is it a numbered definition?
249 unsigned Num = (unsigned)D.Num;
251 // Module constants occupy the lowest numbered slots...
252 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
253 if (VI != CurModule.Values.end()) {
254 if (Num < VI->second.size())
255 return VI->second[Num];
256 Num -= VI->second.size();
259 // Make sure that our type is within bounds
260 VI = CurFun.Values.find(Ty);
261 if (VI == CurFun.Values.end()) return 0;
263 // Check that the number is within bounds...
264 if (VI->second.size() <= Num) return 0;
266 return VI->second[Num];
269 case ValID::NameVal: { // Is it a named definition?
270 Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
271 if (N == 0) return 0;
273 D.destroy(); // Free old strdup'd memory...
277 // Check to make sure that "Ty" is an integral type, and that our
278 // value will fit into the specified type...
279 case ValID::ConstSIntVal: // Is it a constant pool reference??
280 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64))
281 ThrowException("Signed integral constant '" +
282 itostr(D.ConstPool64) + "' is invalid for type '" +
283 Ty->getDescription() + "'!");
284 return ConstantSInt::get(Ty, D.ConstPool64);
286 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
287 if (!ConstantUInt::isValueValidForType(Ty, D.UConstPool64)) {
288 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64)) {
289 ThrowException("Integral constant '" + utostr(D.UConstPool64) +
290 "' is invalid or out of range!");
291 } else { // This is really a signed reference. Transmogrify.
292 return ConstantSInt::get(Ty, D.ConstPool64);
295 return ConstantUInt::get(Ty, D.UConstPool64);
298 case ValID::ConstFPVal: // Is it a floating point const pool reference?
299 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
300 ThrowException("FP constant invalid for type!!");
301 return ConstantFP::get(Ty, D.ConstPoolFP);
303 case ValID::ConstNullVal: // Is it a null value?
304 if (!isa<PointerType>(Ty))
305 ThrowException("Cannot create a a non pointer null!");
306 return ConstantPointerNull::get(cast<PointerType>(Ty));
308 case ValID::ConstUndefVal: // Is it an undef value?
309 return UndefValue::get(Ty);
311 case ValID::ConstZeroVal: // Is it a zero value?
312 return Constant::getNullValue(Ty);
314 case ValID::ConstantVal: // Fully resolved constant?
315 if (D.ConstantValue->getType() != Ty)
316 ThrowException("Constant expression type different from required type!");
317 return D.ConstantValue;
320 assert(0 && "Unhandled case!");
324 assert(0 && "Unhandled case!");
328 // getVal - This function is identical to getValNonImprovising, except that if a
329 // value is not already defined, it "improvises" by creating a placeholder var
330 // that looks and acts just like the requested variable. When the value is
331 // defined later, all uses of the placeholder variable are replaced with the
334 static Value *getVal(const Type *Ty, const ValID &ID) {
335 if (Ty == Type::LabelTy)
336 ThrowException("Cannot use a basic block here");
338 // See if the value has already been defined.
339 Value *V = getValNonImprovising(Ty, ID);
342 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty))
343 ThrowException("Invalid use of a composite type!");
345 // If we reached here, we referenced either a symbol that we don't know about
346 // or an id number that hasn't been read yet. We may be referencing something
347 // forward, so just create an entry to be resolved later and get to it...
349 V = new Argument(Ty);
351 // Remember where this forward reference came from. FIXME, shouldn't we try
352 // to recycle these things??
353 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
356 if (inFunctionScope())
357 InsertValue(V, CurFun.LateResolveValues);
359 InsertValue(V, CurModule.LateResolveValues);
363 /// getBBVal - This is used for two purposes:
364 /// * If isDefinition is true, a new basic block with the specified ID is being
366 /// * If isDefinition is true, this is a reference to a basic block, which may
367 /// or may not be a forward reference.
369 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
370 assert(inFunctionScope() && "Can't get basic block at global scope!");
375 default: ThrowException("Illegal label reference " + ID.getName());
376 case ValID::NumberVal: // Is it a numbered definition?
377 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
378 CurFun.NumberedBlocks.resize(ID.Num+1);
379 BB = CurFun.NumberedBlocks[ID.Num];
381 case ValID::NameVal: // Is it a named definition?
383 if (Value *N = CurFun.CurrentFunction->
384 getSymbolTable().lookup(Type::LabelTy, Name))
385 BB = cast<BasicBlock>(N);
389 // See if the block has already been defined.
391 // If this is the definition of the block, make sure the existing value was
392 // just a forward reference. If it was a forward reference, there will be
393 // an entry for it in the PlaceHolderInfo map.
394 if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
395 // The existing value was a definition, not a forward reference.
396 ThrowException("Redefinition of label " + ID.getName());
398 ID.destroy(); // Free strdup'd memory.
402 // Otherwise this block has not been seen before.
403 BB = new BasicBlock("", CurFun.CurrentFunction);
404 if (ID.Type == ValID::NameVal) {
405 BB->setName(ID.Name);
407 CurFun.NumberedBlocks[ID.Num] = BB;
410 // If this is not a definition, keep track of it so we can use it as a forward
413 // Remember where this forward reference came from.
414 CurFun.BBForwardRefs[BB] = std::make_pair(ID, llvmAsmlineno);
416 // The forward declaration could have been inserted anywhere in the
417 // function: insert it into the correct place now.
418 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
419 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
426 //===----------------------------------------------------------------------===//
427 // Code to handle forward references in instructions
428 //===----------------------------------------------------------------------===//
430 // This code handles the late binding needed with statements that reference
431 // values not defined yet... for example, a forward branch, or the PHI node for
434 // This keeps a table (CurFun.LateResolveValues) of all such forward references
435 // and back patchs after we are done.
438 // ResolveDefinitions - If we could not resolve some defs at parsing
439 // time (forward branches, phi functions for loops, etc...) resolve the
443 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
444 std::map<const Type*,ValueList> *FutureLateResolvers) {
445 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
446 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
447 E = LateResolvers.end(); LRI != E; ++LRI) {
448 ValueList &List = LRI->second;
449 while (!List.empty()) {
450 Value *V = List.back();
453 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
454 CurModule.PlaceHolderInfo.find(V);
455 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
457 ValID &DID = PHI->second.first;
459 Value *TheRealValue = getValNonImprovising(LRI->first, DID);
461 V->replaceAllUsesWith(TheRealValue);
463 CurModule.PlaceHolderInfo.erase(PHI);
464 } else if (FutureLateResolvers) {
465 // Functions have their unresolved items forwarded to the module late
467 InsertValue(V, *FutureLateResolvers);
469 if (DID.Type == ValID::NameVal)
470 ThrowException("Reference to an invalid definition: '" +DID.getName()+
471 "' of type '" + V->getType()->getDescription() + "'",
474 ThrowException("Reference to an invalid definition: #" +
475 itostr(DID.Num) + " of type '" +
476 V->getType()->getDescription() + "'",
482 LateResolvers.clear();
485 // ResolveTypeTo - A brand new type was just declared. This means that (if
486 // name is not null) things referencing Name can be resolved. Otherwise, things
487 // refering to the number can be resolved. Do this now.
489 static void ResolveTypeTo(char *Name, const Type *ToTy) {
491 if (Name) D = ValID::create(Name);
492 else D = ValID::create((int)CurModule.Types.size());
494 std::map<ValID, PATypeHolder>::iterator I =
495 CurModule.LateResolveTypes.find(D);
496 if (I != CurModule.LateResolveTypes.end()) {
497 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
498 CurModule.LateResolveTypes.erase(I);
502 // setValueName - Set the specified value to the name given. The name may be
503 // null potentially, in which case this is a noop. The string passed in is
504 // assumed to be a malloc'd string buffer, and is free'd by this function.
506 static void setValueName(Value *V, char *NameStr) {
508 std::string Name(NameStr); // Copy string
509 free(NameStr); // Free old string
511 if (V->getType() == Type::VoidTy)
512 ThrowException("Can't assign name '" + Name+"' to value with void type!");
514 assert(inFunctionScope() && "Must be in function scope!");
515 SymbolTable &ST = CurFun.CurrentFunction->getSymbolTable();
516 if (ST.lookup(V->getType(), Name))
517 ThrowException("Redefinition of value named '" + Name + "' in the '" +
518 V->getType()->getDescription() + "' type plane!");
525 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
526 /// this is a declaration, otherwise it is a definition.
527 static GlobalVariable *
528 ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
529 bool isConstantGlobal, const Type *Ty,
530 Constant *Initializer) {
531 if (isa<FunctionType>(Ty))
532 ThrowException("Cannot declare global vars of function type!");
534 const PointerType *PTy = PointerType::get(Ty);
538 Name = NameStr; // Copy string
539 free(NameStr); // Free old string
542 // See if this global value was forward referenced. If so, recycle the
546 ID = ValID::create((char*)Name.c_str());
548 ID = ValID::create((int)CurModule.Values[PTy].size());
551 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
552 // Move the global to the end of the list, from whereever it was
553 // previously inserted.
554 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
555 CurModule.CurrentModule->getGlobalList().remove(GV);
556 CurModule.CurrentModule->getGlobalList().push_back(GV);
557 GV->setInitializer(Initializer);
558 GV->setLinkage(Linkage);
559 GV->setConstant(isConstantGlobal);
560 InsertValue(GV, CurModule.Values);
564 // If this global has a name, check to see if there is already a definition
565 // of this global in the module. If so, merge as appropriate. Note that
566 // this is really just a hack around problems in the CFE. :(
568 // We are a simple redefinition of a value, check to see if it is defined
569 // the same as the old one.
570 if (GlobalVariable *EGV =
571 CurModule.CurrentModule->getGlobalVariable(Name, Ty)) {
572 // We are allowed to redefine a global variable in two circumstances:
573 // 1. If at least one of the globals is uninitialized or
574 // 2. If both initializers have the same value.
576 if (!EGV->hasInitializer() || !Initializer ||
577 EGV->getInitializer() == Initializer) {
579 // Make sure the existing global version gets the initializer! Make
580 // sure that it also gets marked const if the new version is.
581 if (Initializer && !EGV->hasInitializer())
582 EGV->setInitializer(Initializer);
583 if (isConstantGlobal)
584 EGV->setConstant(true);
585 EGV->setLinkage(Linkage);
589 ThrowException("Redefinition of global variable named '" + Name +
590 "' in the '" + Ty->getDescription() + "' type plane!");
594 // Otherwise there is no existing GV to use, create one now.
596 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
597 CurModule.CurrentModule);
598 InsertValue(GV, CurModule.Values);
602 // setTypeName - Set the specified type to the name given. The name may be
603 // null potentially, in which case this is a noop. The string passed in is
604 // assumed to be a malloc'd string buffer, and is freed by this function.
606 // This function returns true if the type has already been defined, but is
607 // allowed to be redefined in the specified context. If the name is a new name
608 // for the type plane, it is inserted and false is returned.
609 static bool setTypeName(const Type *T, char *NameStr) {
610 assert(!inFunctionScope() && "Can't give types function-local names!");
611 if (NameStr == 0) return false;
613 std::string Name(NameStr); // Copy string
614 free(NameStr); // Free old string
616 // We don't allow assigning names to void type
617 if (T == Type::VoidTy)
618 ThrowException("Can't assign name '" + Name + "' to the void type!");
620 // Set the type name, checking for conflicts as we do so.
621 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
623 if (AlreadyExists) { // Inserting a name that is already defined???
624 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
625 assert(Existing && "Conflict but no matching type?");
627 // There is only one case where this is allowed: when we are refining an
628 // opaque type. In this case, Existing will be an opaque type.
629 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
630 // We ARE replacing an opaque type!
631 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
635 // Otherwise, this is an attempt to redefine a type. That's okay if
636 // the redefinition is identical to the original. This will be so if
637 // Existing and T point to the same Type object. In this one case we
638 // allow the equivalent redefinition.
639 if (Existing == T) return true; // Yes, it's equal.
641 // Any other kind of (non-equivalent) redefinition is an error.
642 ThrowException("Redefinition of type named '" + Name + "' in the '" +
643 T->getDescription() + "' type plane!");
649 //===----------------------------------------------------------------------===//
650 // Code for handling upreferences in type names...
653 // TypeContains - Returns true if Ty directly contains E in it.
655 static bool TypeContains(const Type *Ty, const Type *E) {
656 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
657 E) != Ty->subtype_end();
662 // NestingLevel - The number of nesting levels that need to be popped before
663 // this type is resolved.
664 unsigned NestingLevel;
666 // LastContainedTy - This is the type at the current binding level for the
667 // type. Every time we reduce the nesting level, this gets updated.
668 const Type *LastContainedTy;
670 // UpRefTy - This is the actual opaque type that the upreference is
674 UpRefRecord(unsigned NL, OpaqueType *URTy)
675 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
679 // UpRefs - A list of the outstanding upreferences that need to be resolved.
680 static std::vector<UpRefRecord> UpRefs;
682 /// HandleUpRefs - Every time we finish a new layer of types, this function is
683 /// called. It loops through the UpRefs vector, which is a list of the
684 /// currently active types. For each type, if the up reference is contained in
685 /// the newly completed type, we decrement the level count. When the level
686 /// count reaches zero, the upreferenced type is the type that is passed in:
687 /// thus we can complete the cycle.
689 static PATypeHolder HandleUpRefs(const Type *ty) {
690 if (!ty->isAbstract()) return ty;
692 UR_OUT("Type '" << Ty->getDescription() <<
693 "' newly formed. Resolving upreferences.\n" <<
694 UpRefs.size() << " upreferences active!\n");
696 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
697 // to zero), we resolve them all together before we resolve them to Ty. At
698 // the end of the loop, if there is anything to resolve to Ty, it will be in
700 OpaqueType *TypeToResolve = 0;
702 for (unsigned i = 0; i != UpRefs.size(); ++i) {
703 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
704 << UpRefs[i].second->getDescription() << ") = "
705 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
706 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
707 // Decrement level of upreference
708 unsigned Level = --UpRefs[i].NestingLevel;
709 UpRefs[i].LastContainedTy = Ty;
710 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
711 if (Level == 0) { // Upreference should be resolved!
712 if (!TypeToResolve) {
713 TypeToResolve = UpRefs[i].UpRefTy;
715 UR_OUT(" * Resolving upreference for "
716 << UpRefs[i].second->getDescription() << "\n";
717 std::string OldName = UpRefs[i].UpRefTy->getDescription());
718 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
719 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
720 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
722 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
723 --i; // Do not skip the next element...
729 UR_OUT(" * Resolving upreference for "
730 << UpRefs[i].second->getDescription() << "\n";
731 std::string OldName = TypeToResolve->getDescription());
732 TypeToResolve->refineAbstractTypeTo(Ty);
739 // common code from the two 'RunVMAsmParser' functions
740 static Module * RunParser(Module * M) {
742 llvmAsmlineno = 1; // Reset the current line number...
743 ObsoleteVarArgs = false;
746 CurModule.CurrentModule = M;
747 yyparse(); // Parse the file, potentially throwing exception
749 Module *Result = ParserResult;
752 //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
755 if ((F = Result->getNamedFunction("llvm.va_start"))
756 && F->getFunctionType()->getNumParams() == 0)
757 ObsoleteVarArgs = true;
758 if((F = Result->getNamedFunction("llvm.va_copy"))
759 && F->getFunctionType()->getNumParams() == 1)
760 ObsoleteVarArgs = true;
763 if (ObsoleteVarArgs && NewVarArgs)
764 ThrowException("This file is corrupt: it uses both new and old style varargs");
766 if(ObsoleteVarArgs) {
767 if(Function* F = Result->getNamedFunction("llvm.va_start")) {
768 if (F->arg_size() != 0)
769 ThrowException("Obsolete va_start takes 0 argument!");
773 //bar = alloca typeof(foo)
777 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
778 const Type* ArgTy = F->getFunctionType()->getReturnType();
779 const Type* ArgTyPtr = PointerType::get(ArgTy);
780 Function* NF = Result->getOrInsertFunction("llvm.va_start",
781 RetTy, ArgTyPtr, (Type *)0);
783 while (!F->use_empty()) {
784 CallInst* CI = cast<CallInst>(F->use_back());
785 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
786 new CallInst(NF, bar, "", CI);
787 Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
788 CI->replaceAllUsesWith(foo);
789 CI->getParent()->getInstList().erase(CI);
791 Result->getFunctionList().erase(F);
794 if(Function* F = Result->getNamedFunction("llvm.va_end")) {
795 if(F->arg_size() != 1)
796 ThrowException("Obsolete va_end takes 1 argument!");
800 //bar = alloca 1 of typeof(foo)
802 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
803 const Type* ArgTy = F->getFunctionType()->getParamType(0);
804 const Type* ArgTyPtr = PointerType::get(ArgTy);
805 Function* NF = Result->getOrInsertFunction("llvm.va_end",
806 RetTy, ArgTyPtr, (Type *)0);
808 while (!F->use_empty()) {
809 CallInst* CI = cast<CallInst>(F->use_back());
810 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
811 new StoreInst(CI->getOperand(1), bar, CI);
812 new CallInst(NF, bar, "", CI);
813 CI->getParent()->getInstList().erase(CI);
815 Result->getFunctionList().erase(F);
818 if(Function* F = Result->getNamedFunction("llvm.va_copy")) {
819 if(F->arg_size() != 1)
820 ThrowException("Obsolete va_copy takes 1 argument!");
823 //a = alloca 1 of typeof(foo)
824 //b = alloca 1 of typeof(foo)
829 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
830 const Type* ArgTy = F->getFunctionType()->getReturnType();
831 const Type* ArgTyPtr = PointerType::get(ArgTy);
832 Function* NF = Result->getOrInsertFunction("llvm.va_copy",
833 RetTy, ArgTyPtr, ArgTyPtr,
836 while (!F->use_empty()) {
837 CallInst* CI = cast<CallInst>(F->use_back());
838 AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
839 AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
840 new StoreInst(CI->getOperand(1), b, CI);
841 new CallInst(NF, a, b, "", CI);
842 Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
843 CI->replaceAllUsesWith(foo);
844 CI->getParent()->getInstList().erase(CI);
846 Result->getFunctionList().erase(F);
854 //===----------------------------------------------------------------------===//
855 // RunVMAsmParser - Define an interface to this parser
856 //===----------------------------------------------------------------------===//
858 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
861 CurFilename = Filename;
862 return RunParser(new Module(CurFilename));
865 Module *llvm::RunVMAsmParser(const char * AsmString, Module * M) {
866 set_scan_string(AsmString);
868 CurFilename = "from_memory";
870 return RunParser(new Module (CurFilename));
879 llvm::Module *ModuleVal;
880 llvm::Function *FunctionVal;
881 std::pair<llvm::PATypeHolder*, char*> *ArgVal;
882 llvm::BasicBlock *BasicBlockVal;
883 llvm::TerminatorInst *TermInstVal;
884 llvm::Instruction *InstVal;
885 llvm::Constant *ConstVal;
887 const llvm::Type *PrimType;
888 llvm::PATypeHolder *TypeVal;
889 llvm::Value *ValueVal;
891 std::vector<std::pair<llvm::PATypeHolder*,char*> > *ArgList;
892 std::vector<llvm::Value*> *ValueList;
893 std::list<llvm::PATypeHolder> *TypeList;
894 // Represent the RHS of PHI node
895 std::list<std::pair<llvm::Value*,
896 llvm::BasicBlock*> > *PHIList;
897 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
898 std::vector<llvm::Constant*> *ConstVector;
900 llvm::GlobalValue::LinkageTypes Linkage;
908 char *StrVal; // This memory is strdup'd!
909 llvm::ValID ValIDVal; // strdup'd memory maybe!
911 llvm::Instruction::BinaryOps BinaryOpVal;
912 llvm::Instruction::TermOps TermOpVal;
913 llvm::Instruction::MemoryOps MemOpVal;
914 llvm::Instruction::OtherOps OtherOpVal;
915 llvm::Module::Endianness Endianness;
918 %type <ModuleVal> Module FunctionList
919 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
920 %type <BasicBlockVal> BasicBlock InstructionList
921 %type <TermInstVal> BBTerminatorInst
922 %type <InstVal> Inst InstVal MemoryInst
923 %type <ConstVal> ConstVal ConstExpr
924 %type <ConstVector> ConstVector
925 %type <ArgList> ArgList ArgListH
926 %type <ArgVal> ArgVal
927 %type <PHIList> PHIList
928 %type <ValueList> ValueRefList ValueRefListE // For call param lists
929 %type <ValueList> IndexList // For GEP derived indices
930 %type <TypeList> TypeListI ArgTypeListI
931 %type <JumpTable> JumpTable
932 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
933 %type <BoolVal> OptVolatile // 'volatile' or not
934 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
935 %type <Linkage> OptLinkage
936 %type <Endianness> BigOrLittle
938 // ValueRef - Unresolved reference to a definition or BB
939 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
940 %type <ValueVal> ResolvedVal // <type> <valref> pair
941 // Tokens and types for handling constant integer values
943 // ESINT64VAL - A negative number within long long range
944 %token <SInt64Val> ESINT64VAL
946 // EUINT64VAL - A positive number within uns. long long range
947 %token <UInt64Val> EUINT64VAL
948 %type <SInt64Val> EINT64VAL
950 %token <SIntVal> SINTVAL // Signed 32 bit ints...
951 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
952 %type <SIntVal> INTVAL
953 %token <FPVal> FPVAL // Float or Double constant
956 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
957 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
958 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
959 %token <PrimType> FLOAT DOUBLE TYPE LABEL
961 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
962 %type <StrVal> Name OptName OptAssign
963 %type <UIntVal> OptAlign OptCAlign
964 %type <StrVal> OptSection SectionString
966 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
967 %token DECLARE GLOBAL CONSTANT SECTION VOLATILE
968 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
969 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
970 %token DEPLIBS CALL TAIL ASM_TOK MODULE
971 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK
972 %type <UIntVal> OptCallingConv
974 // Basic Block Terminating Operators
975 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
978 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
979 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
980 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comarators
982 // Memory Instructions
983 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
986 %type <OtherOpVal> ShiftOps
987 %token <OtherOpVal> PHI_TOK CAST SELECT SHL SHR VAARG
988 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT
989 %token VAARG_old VANEXT_old //OBSOLETE
995 // Handle constant integer size restriction and conversion...
999 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
1000 ThrowException("Value too large for type!");
1005 EINT64VAL : ESINT64VAL; // These have same type and can't cause problems...
1006 EINT64VAL : EUINT64VAL {
1007 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
1008 ThrowException("Value too large for type!");
1012 // Operations that are notably excluded from this list include:
1013 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1015 ArithmeticOps: ADD | SUB | MUL | DIV | REM;
1016 LogicalOps : AND | OR | XOR;
1017 SetCondOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
1019 ShiftOps : SHL | SHR;
1021 // These are some types that allow classification if we only want a particular
1022 // thing... for example, only a signed, unsigned, or integral type.
1023 SIntType : LONG | INT | SHORT | SBYTE;
1024 UIntType : ULONG | UINT | USHORT | UBYTE;
1025 IntType : SIntType | UIntType;
1026 FPType : FLOAT | DOUBLE;
1028 // OptAssign - Value producing statements have an optional assignment component
1029 OptAssign : Name '=' {
1036 OptLinkage : INTERNAL { $$ = GlobalValue::InternalLinkage; } |
1037 LINKONCE { $$ = GlobalValue::LinkOnceLinkage; } |
1038 WEAK { $$ = GlobalValue::WeakLinkage; } |
1039 APPENDING { $$ = GlobalValue::AppendingLinkage; } |
1040 /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
1042 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1043 CCC_TOK { $$ = CallingConv::C; } |
1044 FASTCC_TOK { $$ = CallingConv::Fast; } |
1045 COLDCC_TOK { $$ = CallingConv::Cold; } |
1047 if ((unsigned)$2 != $2)
1048 ThrowException("Calling conv too large!");
1052 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1053 // a comma before it.
1054 OptAlign : /*empty*/ { $$ = 0; } |
1057 if ($$ != 0 && !isPowerOf2_32($$))
1058 ThrowException("Alignment must be a power of two!");
1060 OptCAlign : /*empty*/ { $$ = 0; } |
1061 ',' ALIGN EUINT64VAL {
1063 if ($$ != 0 && !isPowerOf2_32($$))
1064 ThrowException("Alignment must be a power of two!");
1068 SectionString : SECTION STRINGCONSTANT {
1069 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1070 if ($2[i] == '"' || $2[i] == '\\')
1071 ThrowException("Invalid character in section name!");
1075 OptSection : /*empty*/ { $$ = 0; } |
1076 SectionString { $$ = $1; };
1078 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1079 // is set to be the global we are processing.
1081 GlobalVarAttributes : /* empty */ {} |
1082 ',' GlobalVarAttribute GlobalVarAttributes {};
1083 GlobalVarAttribute : SectionString {
1084 CurGV->setSection($1);
1087 | ALIGN EUINT64VAL {
1088 if ($2 != 0 && !isPowerOf2_32($2))
1089 ThrowException("Alignment must be a power of two!");
1090 CurGV->setAlignment($2);
1093 //===----------------------------------------------------------------------===//
1094 // Types includes all predefined types... except void, because it can only be
1095 // used in specific contexts (function returning void for example). To have
1096 // access to it, a user must explicitly use TypesV.
1099 // TypesV includes all of 'Types', but it also includes the void type.
1100 TypesV : Types | VOID { $$ = new PATypeHolder($1); };
1101 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
1104 if (!UpRefs.empty())
1105 ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
1110 // Derived types are added later...
1112 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT ;
1113 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL;
1115 $$ = new PATypeHolder(OpaqueType::get());
1118 $$ = new PATypeHolder($1);
1120 UpRTypes : SymbolicValueRef { // Named types are also simple types...
1121 $$ = new PATypeHolder(getTypeVal($1));
1124 // Include derived types in the Types production.
1126 UpRTypes : '\\' EUINT64VAL { // Type UpReference
1127 if ($2 > (uint64_t)~0U) ThrowException("Value out of range!");
1128 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1129 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1130 $$ = new PATypeHolder(OT);
1131 UR_OUT("New Upreference!\n");
1133 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
1134 std::vector<const Type*> Params;
1135 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1136 E = $3->end(); I != E; ++I)
1137 Params.push_back(*I);
1138 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1139 if (isVarArg) Params.pop_back();
1141 $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
1142 delete $3; // Delete the argument list
1143 delete $1; // Delete the return type handle
1145 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
1146 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1149 | '<' EUINT64VAL 'x' UpRTypes '>' { // Packed array type?
1150 const llvm::Type* ElemTy = $4->get();
1151 if ((unsigned)$2 != $2)
1152 ThrowException("Unsigned result not equal to signed result");
1153 if (!ElemTy->isPrimitiveType())
1154 ThrowException("Elemental type of a PackedType must be primitive");
1155 if (!isPowerOf2_32($2))
1156 ThrowException("Vector length should be a power of 2!");
1157 $$ = new PATypeHolder(HandleUpRefs(PackedType::get(*$4, (unsigned)$2)));
1160 | '{' TypeListI '}' { // Structure type?
1161 std::vector<const Type*> Elements;
1162 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1163 E = $2->end(); I != E; ++I)
1164 Elements.push_back(*I);
1166 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1169 | '{' '}' { // Empty structure type?
1170 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1172 | UpRTypes '*' { // Pointer type?
1173 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1177 // TypeList - Used for struct declarations and as a basis for function type
1178 // declaration type lists
1180 TypeListI : UpRTypes {
1181 $$ = new std::list<PATypeHolder>();
1182 $$->push_back(*$1); delete $1;
1184 | TypeListI ',' UpRTypes {
1185 ($$=$1)->push_back(*$3); delete $3;
1188 // ArgTypeList - List of types for a function type declaration...
1189 ArgTypeListI : TypeListI
1190 | TypeListI ',' DOTDOTDOT {
1191 ($$=$1)->push_back(Type::VoidTy);
1194 ($$ = new std::list<PATypeHolder>())->push_back(Type::VoidTy);
1197 $$ = new std::list<PATypeHolder>();
1200 // ConstVal - The various declarations that go into the constant pool. This
1201 // production is used ONLY to represent constants that show up AFTER a 'const',
1202 // 'constant' or 'global' token at global scope. Constants that can be inlined
1203 // into other expressions (such as integers and constexprs) are handled by the
1204 // ResolvedVal, ValueRef and ConstValueRef productions.
1206 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1207 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1209 ThrowException("Cannot make array constant with type: '" +
1210 (*$1)->getDescription() + "'!");
1211 const Type *ETy = ATy->getElementType();
1212 int NumElements = ATy->getNumElements();
1214 // Verify that we have the correct size...
1215 if (NumElements != -1 && NumElements != (int)$3->size())
1216 ThrowException("Type mismatch: constant sized array initialized with " +
1217 utostr($3->size()) + " arguments, but has size of " +
1218 itostr(NumElements) + "!");
1220 // Verify all elements are correct type!
1221 for (unsigned i = 0; i < $3->size(); i++) {
1222 if (ETy != (*$3)[i]->getType())
1223 ThrowException("Element #" + utostr(i) + " is not of type '" +
1224 ETy->getDescription() +"' as required!\nIt is of type '"+
1225 (*$3)[i]->getType()->getDescription() + "'.");
1228 $$ = ConstantArray::get(ATy, *$3);
1229 delete $1; delete $3;
1232 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1234 ThrowException("Cannot make array constant with type: '" +
1235 (*$1)->getDescription() + "'!");
1237 int NumElements = ATy->getNumElements();
1238 if (NumElements != -1 && NumElements != 0)
1239 ThrowException("Type mismatch: constant sized array initialized with 0"
1240 " arguments, but has size of " + itostr(NumElements) +"!");
1241 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1244 | Types 'c' STRINGCONSTANT {
1245 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1247 ThrowException("Cannot make array constant with type: '" +
1248 (*$1)->getDescription() + "'!");
1250 int NumElements = ATy->getNumElements();
1251 const Type *ETy = ATy->getElementType();
1252 char *EndStr = UnEscapeLexed($3, true);
1253 if (NumElements != -1 && NumElements != (EndStr-$3))
1254 ThrowException("Can't build string constant of size " +
1255 itostr((int)(EndStr-$3)) +
1256 " when array has size " + itostr(NumElements) + "!");
1257 std::vector<Constant*> Vals;
1258 if (ETy == Type::SByteTy) {
1259 for (signed char *C = (signed char *)$3; C != (signed char *)EndStr; ++C)
1260 Vals.push_back(ConstantSInt::get(ETy, *C));
1261 } else if (ETy == Type::UByteTy) {
1262 for (unsigned char *C = (unsigned char *)$3;
1263 C != (unsigned char*)EndStr; ++C)
1264 Vals.push_back(ConstantUInt::get(ETy, *C));
1267 ThrowException("Cannot build string arrays of non byte sized elements!");
1270 $$ = ConstantArray::get(ATy, Vals);
1273 | Types '<' ConstVector '>' { // Nonempty unsized arr
1274 const PackedType *PTy = dyn_cast<PackedType>($1->get());
1276 ThrowException("Cannot make packed constant with type: '" +
1277 (*$1)->getDescription() + "'!");
1278 const Type *ETy = PTy->getElementType();
1279 int NumElements = PTy->getNumElements();
1281 // Verify that we have the correct size...
1282 if (NumElements != -1 && NumElements != (int)$3->size())
1283 ThrowException("Type mismatch: constant sized packed initialized with " +
1284 utostr($3->size()) + " arguments, but has size of " +
1285 itostr(NumElements) + "!");
1287 // Verify all elements are correct type!
1288 for (unsigned i = 0; i < $3->size(); i++) {
1289 if (ETy != (*$3)[i]->getType())
1290 ThrowException("Element #" + utostr(i) + " is not of type '" +
1291 ETy->getDescription() +"' as required!\nIt is of type '"+
1292 (*$3)[i]->getType()->getDescription() + "'.");
1295 $$ = ConstantPacked::get(PTy, *$3);
1296 delete $1; delete $3;
1298 | Types '{' ConstVector '}' {
1299 const StructType *STy = dyn_cast<StructType>($1->get());
1301 ThrowException("Cannot make struct constant with type: '" +
1302 (*$1)->getDescription() + "'!");
1304 if ($3->size() != STy->getNumContainedTypes())
1305 ThrowException("Illegal number of initializers for structure type!");
1307 // Check to ensure that constants are compatible with the type initializer!
1308 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1309 if ((*$3)[i]->getType() != STy->getElementType(i))
1310 ThrowException("Expected type '" +
1311 STy->getElementType(i)->getDescription() +
1312 "' for element #" + utostr(i) +
1313 " of structure initializer!");
1315 $$ = ConstantStruct::get(STy, *$3);
1316 delete $1; delete $3;
1319 const StructType *STy = dyn_cast<StructType>($1->get());
1321 ThrowException("Cannot make struct constant with type: '" +
1322 (*$1)->getDescription() + "'!");
1324 if (STy->getNumContainedTypes() != 0)
1325 ThrowException("Illegal number of initializers for structure type!");
1327 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1331 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1333 ThrowException("Cannot make null pointer constant with type: '" +
1334 (*$1)->getDescription() + "'!");
1336 $$ = ConstantPointerNull::get(PTy);
1340 $$ = UndefValue::get($1->get());
1343 | Types SymbolicValueRef {
1344 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1346 ThrowException("Global const reference must be a pointer type!");
1348 // ConstExprs can exist in the body of a function, thus creating
1349 // GlobalValues whenever they refer to a variable. Because we are in
1350 // the context of a function, getValNonImprovising will search the functions
1351 // symbol table instead of the module symbol table for the global symbol,
1352 // which throws things all off. To get around this, we just tell
1353 // getValNonImprovising that we are at global scope here.
1355 Function *SavedCurFn = CurFun.CurrentFunction;
1356 CurFun.CurrentFunction = 0;
1358 Value *V = getValNonImprovising(Ty, $2);
1360 CurFun.CurrentFunction = SavedCurFn;
1362 // If this is an initializer for a constant pointer, which is referencing a
1363 // (currently) undefined variable, create a stub now that shall be replaced
1364 // in the future with the right type of variable.
1367 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1368 const PointerType *PT = cast<PointerType>(Ty);
1370 // First check to see if the forward references value is already created!
1371 PerModuleInfo::GlobalRefsType::iterator I =
1372 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1374 if (I != CurModule.GlobalRefs.end()) {
1375 V = I->second; // Placeholder already exists, use it...
1379 if ($2.Type == ValID::NameVal) Name = $2.Name;
1381 // Create the forward referenced global.
1383 if (const FunctionType *FTy =
1384 dyn_cast<FunctionType>(PT->getElementType())) {
1385 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1386 CurModule.CurrentModule);
1388 GV = new GlobalVariable(PT->getElementType(), false,
1389 GlobalValue::ExternalLinkage, 0,
1390 Name, CurModule.CurrentModule);
1393 // Keep track of the fact that we have a forward ref to recycle it
1394 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1399 $$ = cast<GlobalValue>(V);
1400 delete $1; // Free the type handle
1403 if ($1->get() != $2->getType())
1404 ThrowException("Mismatched types for constant expression!");
1408 | Types ZEROINITIALIZER {
1409 const Type *Ty = $1->get();
1410 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1411 ThrowException("Cannot create a null initialized value of this type!");
1412 $$ = Constant::getNullValue(Ty);
1416 ConstVal : SIntType EINT64VAL { // integral constants
1417 if (!ConstantSInt::isValueValidForType($1, $2))
1418 ThrowException("Constant value doesn't fit in type!");
1419 $$ = ConstantSInt::get($1, $2);
1421 | UIntType EUINT64VAL { // integral constants
1422 if (!ConstantUInt::isValueValidForType($1, $2))
1423 ThrowException("Constant value doesn't fit in type!");
1424 $$ = ConstantUInt::get($1, $2);
1426 | BOOL TRUETOK { // Boolean constants
1427 $$ = ConstantBool::True;
1429 | BOOL FALSETOK { // Boolean constants
1430 $$ = ConstantBool::False;
1432 | FPType FPVAL { // Float & Double constants
1433 if (!ConstantFP::isValueValidForType($1, $2))
1434 ThrowException("Floating point constant invalid for type!!");
1435 $$ = ConstantFP::get($1, $2);
1439 ConstExpr: CAST '(' ConstVal TO Types ')' {
1440 if (!$3->getType()->isFirstClassType())
1441 ThrowException("cast constant expression from a non-primitive type: '" +
1442 $3->getType()->getDescription() + "'!");
1443 if (!$5->get()->isFirstClassType())
1444 ThrowException("cast constant expression to a non-primitive type: '" +
1445 $5->get()->getDescription() + "'!");
1446 $$ = ConstantExpr::getCast($3, $5->get());
1449 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1450 if (!isa<PointerType>($3->getType()))
1451 ThrowException("GetElementPtr requires a pointer operand!");
1453 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
1454 // indices to uint struct indices for compatibility.
1455 generic_gep_type_iterator<std::vector<Value*>::iterator>
1456 GTI = gep_type_begin($3->getType(), $4->begin(), $4->end()),
1457 GTE = gep_type_end($3->getType(), $4->begin(), $4->end());
1458 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
1459 if (isa<StructType>(*GTI)) // Only change struct indices
1460 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
1461 if (CUI->getType() == Type::UByteTy)
1462 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
1465 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1467 ThrowException("Index list invalid for constant getelementptr!");
1469 std::vector<Constant*> IdxVec;
1470 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1471 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1472 IdxVec.push_back(C);
1474 ThrowException("Indices to constant getelementptr must be constants!");
1478 $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1480 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1481 if ($3->getType() != Type::BoolTy)
1482 ThrowException("Select condition must be of boolean type!");
1483 if ($5->getType() != $7->getType())
1484 ThrowException("Select operand types must match!");
1485 $$ = ConstantExpr::getSelect($3, $5, $7);
1487 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1488 if ($3->getType() != $5->getType())
1489 ThrowException("Binary operator types must match!");
1490 // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
1491 // To retain backward compatibility with these early compilers, we emit a
1492 // cast to the appropriate integer type automatically if we are in the
1493 // broken case. See PR424 for more information.
1494 if (!isa<PointerType>($3->getType())) {
1495 $$ = ConstantExpr::get($1, $3, $5);
1497 const Type *IntPtrTy = 0;
1498 switch (CurModule.CurrentModule->getPointerSize()) {
1499 case Module::Pointer32: IntPtrTy = Type::IntTy; break;
1500 case Module::Pointer64: IntPtrTy = Type::LongTy; break;
1501 default: ThrowException("invalid pointer binary constant expr!");
1503 $$ = ConstantExpr::get($1, ConstantExpr::getCast($3, IntPtrTy),
1504 ConstantExpr::getCast($5, IntPtrTy));
1505 $$ = ConstantExpr::getCast($$, $3->getType());
1508 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1509 if ($3->getType() != $5->getType())
1510 ThrowException("Logical operator types must match!");
1511 if (!$3->getType()->isIntegral()) {
1512 if (!isa<PackedType>($3->getType()) ||
1513 !cast<PackedType>($3->getType())->getElementType()->isIntegral())
1514 ThrowException("Logical operator requires integral operands!");
1516 $$ = ConstantExpr::get($1, $3, $5);
1518 | SetCondOps '(' ConstVal ',' ConstVal ')' {
1519 if ($3->getType() != $5->getType())
1520 ThrowException("setcc operand types must match!");
1521 $$ = ConstantExpr::get($1, $3, $5);
1523 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1524 if ($5->getType() != Type::UByteTy)
1525 ThrowException("Shift count for shift constant must be unsigned byte!");
1526 if (!$3->getType()->isInteger())
1527 ThrowException("Shift constant expression requires integer operand!");
1528 $$ = ConstantExpr::get($1, $3, $5);
1530 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1531 if (!isa<PackedType>($3->getType()))
1532 ThrowException("First operand of extractelement must be "
1534 if ($5->getType() != Type::UIntTy)
1535 ThrowException("Second operand of extractelement must be uint!");
1536 $$ = ConstantExpr::getExtractElement($3, $5);
1539 // ConstVector - A list of comma separated constants.
1540 ConstVector : ConstVector ',' ConstVal {
1541 ($$ = $1)->push_back($3);
1544 $$ = new std::vector<Constant*>();
1549 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1550 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1553 //===----------------------------------------------------------------------===//
1554 // Rules to match Modules
1555 //===----------------------------------------------------------------------===//
1557 // Module rule: Capture the result of parsing the whole file into a result
1560 Module : FunctionList {
1561 $$ = ParserResult = $1;
1562 CurModule.ModuleDone();
1565 // FunctionList - A list of functions, preceeded by a constant pool.
1567 FunctionList : FunctionList Function {
1569 CurFun.FunctionDone();
1571 | FunctionList FunctionProto {
1574 | FunctionList MODULE ASM_TOK AsmBlock {
1577 | FunctionList IMPLEMENTATION {
1581 $$ = CurModule.CurrentModule;
1582 // Emit an error if there are any unresolved types left.
1583 if (!CurModule.LateResolveTypes.empty()) {
1584 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
1585 if (DID.Type == ValID::NameVal)
1586 ThrowException("Reference to an undefined type: '"+DID.getName() + "'");
1588 ThrowException("Reference to an undefined type: #" + itostr(DID.Num));
1592 // ConstPool - Constants with optional names assigned to them.
1593 ConstPool : ConstPool OptAssign TYPE TypesV {
1594 // Eagerly resolve types. This is not an optimization, this is a
1595 // requirement that is due to the fact that we could have this:
1597 // %list = type { %list * }
1598 // %list = type { %list * } ; repeated type decl
1600 // If types are not resolved eagerly, then the two types will not be
1601 // determined to be the same type!
1603 ResolveTypeTo($2, *$4);
1605 if (!setTypeName(*$4, $2) && !$2) {
1606 // If this is a named type that is not a redefinition, add it to the slot
1608 CurModule.Types.push_back(*$4);
1613 | ConstPool FunctionProto { // Function prototypes can be in const pool
1615 | ConstPool MODULE ASM_TOK AsmBlock { // Asm blocks can be in the const pool
1617 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
1618 if ($5 == 0) ThrowException("Global value initializer is not a constant!");
1619 CurGV = ParseGlobalVariable($2, $3, $4, $5->getType(), $5);
1620 } GlobalVarAttributes {
1623 | ConstPool OptAssign EXTERNAL GlobalType Types {
1624 CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage,
1627 } GlobalVarAttributes {
1630 | ConstPool TARGET TargetDefinition {
1632 | ConstPool DEPLIBS '=' LibrariesDefinition {
1634 | /* empty: end of list */ {
1638 AsmBlock : STRINGCONSTANT {
1639 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
1640 char *EndStr = UnEscapeLexed($1, true);
1641 std::string NewAsm($1, EndStr);
1644 if (AsmSoFar.empty())
1645 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
1647 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
1650 BigOrLittle : BIG { $$ = Module::BigEndian; };
1651 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1653 TargetDefinition : ENDIAN '=' BigOrLittle {
1654 CurModule.CurrentModule->setEndianness($3);
1656 | POINTERSIZE '=' EUINT64VAL {
1658 CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1660 CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1662 ThrowException("Invalid pointer size: '" + utostr($3) + "'!");
1664 | TRIPLE '=' STRINGCONSTANT {
1665 CurModule.CurrentModule->setTargetTriple($3);
1669 LibrariesDefinition : '[' LibList ']';
1671 LibList : LibList ',' STRINGCONSTANT {
1672 CurModule.CurrentModule->addLibrary($3);
1676 CurModule.CurrentModule->addLibrary($1);
1679 | /* empty: end of list */ {
1683 //===----------------------------------------------------------------------===//
1684 // Rules to match Function Headers
1685 //===----------------------------------------------------------------------===//
1687 Name : VAR_ID | STRINGCONSTANT;
1688 OptName : Name | /*empty*/ { $$ = 0; };
1690 ArgVal : Types OptName {
1691 if (*$1 == Type::VoidTy)
1692 ThrowException("void typed arguments are invalid!");
1693 $$ = new std::pair<PATypeHolder*, char*>($1, $2);
1696 ArgListH : ArgListH ',' ArgVal {
1702 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1707 ArgList : ArgListH {
1710 | ArgListH ',' DOTDOTDOT {
1712 $$->push_back(std::pair<PATypeHolder*,
1713 char*>(new PATypeHolder(Type::VoidTy), 0));
1716 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1717 $$->push_back(std::make_pair(new PATypeHolder(Type::VoidTy), (char*)0));
1723 FunctionHeaderH : OptCallingConv TypesV Name '(' ArgList ')'
1724 OptSection OptAlign {
1726 std::string FunctionName($3);
1727 free($3); // Free strdup'd memory!
1729 if (!(*$2)->isFirstClassType() && *$2 != Type::VoidTy)
1730 ThrowException("LLVM functions cannot return aggregate types!");
1732 std::vector<const Type*> ParamTypeList;
1733 if ($5) { // If there are arguments...
1734 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
1735 I != $5->end(); ++I)
1736 ParamTypeList.push_back(I->first->get());
1739 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1740 if (isVarArg) ParamTypeList.pop_back();
1742 const FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
1743 const PointerType *PFT = PointerType::get(FT);
1747 if (!FunctionName.empty()) {
1748 ID = ValID::create((char*)FunctionName.c_str());
1750 ID = ValID::create((int)CurModule.Values[PFT].size());
1754 // See if this function was forward referenced. If so, recycle the object.
1755 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
1756 // Move the function to the end of the list, from whereever it was
1757 // previously inserted.
1758 Fn = cast<Function>(FWRef);
1759 CurModule.CurrentModule->getFunctionList().remove(Fn);
1760 CurModule.CurrentModule->getFunctionList().push_back(Fn);
1761 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
1762 (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
1763 // If this is the case, either we need to be a forward decl, or it needs
1765 if (!CurFun.isDeclare && !Fn->isExternal())
1766 ThrowException("Redefinition of function '" + FunctionName + "'!");
1768 // Make sure to strip off any argument names so we can't get conflicts.
1769 if (Fn->isExternal())
1770 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
1774 } else { // Not already defined?
1775 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
1776 CurModule.CurrentModule);
1777 InsertValue(Fn, CurModule.Values);
1780 CurFun.FunctionStart(Fn);
1781 Fn->setCallingConv($1);
1782 Fn->setAlignment($8);
1788 // Add all of the arguments we parsed to the function...
1789 if ($5) { // Is null if empty...
1790 if (isVarArg) { // Nuke the last entry
1791 assert($5->back().first->get() == Type::VoidTy && $5->back().second == 0&&
1792 "Not a varargs marker!");
1793 delete $5->back().first;
1794 $5->pop_back(); // Delete the last entry
1796 Function::arg_iterator ArgIt = Fn->arg_begin();
1797 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
1798 I != $5->end(); ++I, ++ArgIt) {
1799 delete I->first; // Delete the typeholder...
1801 setValueName(ArgIt, I->second); // Insert arg into symtab...
1805 delete $5; // We're now done with the argument list
1809 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
1811 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
1812 $$ = CurFun.CurrentFunction;
1814 // Make sure that we keep track of the linkage type even if there was a
1815 // previous "declare".
1819 END : ENDTOK | '}'; // Allow end of '}' to end a function
1821 Function : BasicBlockList END {
1825 FunctionProto : DECLARE { CurFun.isDeclare = true; } FunctionHeaderH {
1826 $$ = CurFun.CurrentFunction;
1827 CurFun.FunctionDone();
1830 //===----------------------------------------------------------------------===//
1831 // Rules to match Basic Blocks
1832 //===----------------------------------------------------------------------===//
1834 ConstValueRef : ESINT64VAL { // A reference to a direct constant
1835 $$ = ValID::create($1);
1838 $$ = ValID::create($1);
1840 | FPVAL { // Perhaps it's an FP constant?
1841 $$ = ValID::create($1);
1844 $$ = ValID::create(ConstantBool::True);
1847 $$ = ValID::create(ConstantBool::False);
1850 $$ = ValID::createNull();
1853 $$ = ValID::createUndef();
1855 | ZEROINITIALIZER { // A vector zero constant.
1856 $$ = ValID::createZeroInit();
1858 | '<' ConstVector '>' { // Nonempty unsized packed vector
1859 const Type *ETy = (*$2)[0]->getType();
1860 int NumElements = $2->size();
1862 PackedType* pt = PackedType::get(ETy, NumElements);
1863 PATypeHolder* PTy = new PATypeHolder(
1871 // Verify all elements are correct type!
1872 for (unsigned i = 0; i < $2->size(); i++) {
1873 if (ETy != (*$2)[i]->getType())
1874 ThrowException("Element #" + utostr(i) + " is not of type '" +
1875 ETy->getDescription() +"' as required!\nIt is of type '" +
1876 (*$2)[i]->getType()->getDescription() + "'.");
1879 $$ = ValID::create(ConstantPacked::get(pt, *$2));
1880 delete PTy; delete $2;
1883 $$ = ValID::create($1);
1886 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1889 SymbolicValueRef : INTVAL { // Is it an integer reference...?
1890 $$ = ValID::create($1);
1892 | Name { // Is it a named reference...?
1893 $$ = ValID::create($1);
1896 // ValueRef - A reference to a definition... either constant or symbolic
1897 ValueRef : SymbolicValueRef | ConstValueRef;
1900 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
1901 // type immediately preceeds the value reference, and allows complex constant
1902 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1903 ResolvedVal : Types ValueRef {
1904 $$ = getVal(*$1, $2); delete $1;
1907 BasicBlockList : BasicBlockList BasicBlock {
1910 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
1915 // Basic blocks are terminated by branching instructions:
1916 // br, br/cc, switch, ret
1918 BasicBlock : InstructionList OptAssign BBTerminatorInst {
1919 setValueName($3, $2);
1922 $1->getInstList().push_back($3);
1927 InstructionList : InstructionList Inst {
1928 $1->getInstList().push_back($2);
1932 $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
1934 // Make sure to move the basic block to the correct location in the
1935 // function, instead of leaving it inserted wherever it was first
1937 Function::BasicBlockListType &BBL =
1938 CurFun.CurrentFunction->getBasicBlockList();
1939 BBL.splice(BBL.end(), BBL, $$);
1942 $$ = CurBB = getBBVal(ValID::create($1), true);
1944 // Make sure to move the basic block to the correct location in the
1945 // function, instead of leaving it inserted wherever it was first
1947 Function::BasicBlockListType &BBL =
1948 CurFun.CurrentFunction->getBasicBlockList();
1949 BBL.splice(BBL.end(), BBL, $$);
1952 BBTerminatorInst : RET ResolvedVal { // Return with a result...
1953 $$ = new ReturnInst($2);
1955 | RET VOID { // Return with no result...
1956 $$ = new ReturnInst();
1958 | BR LABEL ValueRef { // Unconditional Branch...
1959 $$ = new BranchInst(getBBVal($3));
1960 } // Conditional Branch...
1961 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
1962 $$ = new BranchInst(getBBVal($6), getBBVal($9), getVal(Type::BoolTy, $3));
1964 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1965 SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6), $8->size());
1968 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
1970 for (; I != E; ++I) {
1971 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
1972 S->addCase(CI, I->second);
1974 ThrowException("Switch case is constant, but not a simple integer!");
1978 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
1979 SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6), 0);
1982 | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
1983 TO LABEL ValueRef UNWIND LABEL ValueRef {
1984 const PointerType *PFTy;
1985 const FunctionType *Ty;
1987 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
1988 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1989 // Pull out the types of all of the arguments...
1990 std::vector<const Type*> ParamTypes;
1992 for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
1994 ParamTypes.push_back((*I)->getType());
1997 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1998 if (isVarArg) ParamTypes.pop_back();
2000 Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
2001 PFTy = PointerType::get(Ty);
2004 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2006 BasicBlock *Normal = getBBVal($10);
2007 BasicBlock *Except = getBBVal($13);
2009 // Create the call node...
2010 if (!$6) { // Has no arguments?
2011 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
2012 } else { // Has arguments?
2013 // Loop through FunctionType's arguments and ensure they are specified
2016 FunctionType::param_iterator I = Ty->param_begin();
2017 FunctionType::param_iterator E = Ty->param_end();
2018 std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
2020 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2021 if ((*ArgI)->getType() != *I)
2022 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2023 (*I)->getDescription() + "'!");
2025 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2026 ThrowException("Invalid number of parameters detected!");
2028 $$ = new InvokeInst(V, Normal, Except, *$6);
2030 cast<InvokeInst>($$)->setCallingConv($2);
2036 $$ = new UnwindInst();
2039 $$ = new UnreachableInst();
2044 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2046 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
2048 ThrowException("May only switch on a constant pool value!");
2050 $$->push_back(std::make_pair(V, getBBVal($6)));
2052 | IntType ConstValueRef ',' LABEL ValueRef {
2053 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2054 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
2057 ThrowException("May only switch on a constant pool value!");
2059 $$->push_back(std::make_pair(V, getBBVal($5)));
2062 Inst : OptAssign InstVal {
2063 // Is this definition named?? if so, assign the name...
2064 setValueName($2, $1);
2069 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2070 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2071 $$->push_back(std::make_pair(getVal(*$1, $3), getBBVal($5)));
2074 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2076 $1->push_back(std::make_pair(getVal($1->front().first->getType(), $4),
2081 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
2082 $$ = new std::vector<Value*>();
2085 | ValueRefList ',' ResolvedVal {
2090 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
2091 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
2093 OptTailCall : TAIL CALL {
2102 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2103 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
2104 !isa<PackedType>((*$2).get()))
2106 "Arithmetic operator requires integer, FP, or packed operands!");
2107 if (isa<PackedType>((*$2).get()) && $1 == Instruction::Rem)
2108 ThrowException("Rem not supported on packed types!");
2109 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
2111 ThrowException("binary operator returned null!");
2114 | LogicalOps Types ValueRef ',' ValueRef {
2115 if (!(*$2)->isIntegral()) {
2116 if (!isa<PackedType>($2->get()) ||
2117 !cast<PackedType>($2->get())->getElementType()->isIntegral())
2118 ThrowException("Logical operator requires integral operands!");
2120 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
2122 ThrowException("binary operator returned null!");
2125 | SetCondOps Types ValueRef ',' ValueRef {
2126 if(isa<PackedType>((*$2).get())) {
2128 "PackedTypes currently not supported in setcc instructions!");
2130 $$ = new SetCondInst($1, getVal(*$2, $3), getVal(*$2, $5));
2132 ThrowException("binary operator returned null!");
2136 std::cerr << "WARNING: Use of eliminated 'not' instruction:"
2137 << " Replacing with 'xor'.\n";
2139 Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
2141 ThrowException("Expected integral type for not instruction!");
2143 $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
2145 ThrowException("Could not create a xor instruction!");
2147 | ShiftOps ResolvedVal ',' ResolvedVal {
2148 if ($4->getType() != Type::UByteTy)
2149 ThrowException("Shift amount must be ubyte!");
2150 if (!$2->getType()->isInteger())
2151 ThrowException("Shift constant expression requires integer operand!");
2152 $$ = new ShiftInst($1, $2, $4);
2154 | CAST ResolvedVal TO Types {
2155 if (!$4->get()->isFirstClassType())
2156 ThrowException("cast instruction to a non-primitive type: '" +
2157 $4->get()->getDescription() + "'!");
2158 $$ = new CastInst($2, *$4);
2161 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2162 if ($2->getType() != Type::BoolTy)
2163 ThrowException("select condition must be boolean!");
2164 if ($4->getType() != $6->getType())
2165 ThrowException("select value types should match!");
2166 $$ = new SelectInst($2, $4, $6);
2168 | VAARG ResolvedVal ',' Types {
2170 $$ = new VAArgInst($2, *$4);
2173 | VAARG_old ResolvedVal ',' Types {
2174 ObsoleteVarArgs = true;
2175 const Type* ArgTy = $2->getType();
2176 Function* NF = CurModule.CurrentModule->
2177 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0);
2180 //foo = alloca 1 of t
2184 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
2185 CurBB->getInstList().push_back(foo);
2186 CallInst* bar = new CallInst(NF, $2);
2187 CurBB->getInstList().push_back(bar);
2188 CurBB->getInstList().push_back(new StoreInst(bar, foo));
2189 $$ = new VAArgInst(foo, *$4);
2192 | VANEXT_old ResolvedVal ',' Types {
2193 ObsoleteVarArgs = true;
2194 const Type* ArgTy = $2->getType();
2195 Function* NF = CurModule.CurrentModule->
2196 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0);
2198 //b = vanext a, t ->
2199 //foo = alloca 1 of t
2202 //tmp = vaarg foo, t
2204 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
2205 CurBB->getInstList().push_back(foo);
2206 CallInst* bar = new CallInst(NF, $2);
2207 CurBB->getInstList().push_back(bar);
2208 CurBB->getInstList().push_back(new StoreInst(bar, foo));
2209 Instruction* tmp = new VAArgInst(foo, *$4);
2210 CurBB->getInstList().push_back(tmp);
2211 $$ = new LoadInst(foo);
2214 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2215 if (!isa<PackedType>($2->getType()))
2216 ThrowException("First operand of extractelement must be "
2218 if ($4->getType() != Type::UIntTy)
2219 ThrowException("Second operand of extractelement must be uint!");
2220 $$ = new ExtractElementInst($2, $4);
2222 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2223 if (!isa<PackedType>($2->getType()))
2224 ThrowException("First operand of insertelement must be "
2226 if ($4->getType() !=
2227 cast<PackedType>($2->getType())->getElementType())
2228 ThrowException("Second operand of insertelement must be "
2229 "packed element type!");
2230 if ($6->getType() != Type::UIntTy)
2231 ThrowException("Third operand of insertelement must be uint!");
2232 $$ = new InsertElementInst($2, $4, $6);
2235 const Type *Ty = $2->front().first->getType();
2236 if (!Ty->isFirstClassType())
2237 ThrowException("PHI node operands must be of first class type!");
2238 $$ = new PHINode(Ty);
2239 ((PHINode*)$$)->reserveOperandSpace($2->size());
2240 while ($2->begin() != $2->end()) {
2241 if ($2->front().first->getType() != Ty)
2242 ThrowException("All elements of a PHI node must be of the same type!");
2243 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2246 delete $2; // Free the list...
2248 | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')' {
2249 const PointerType *PFTy;
2250 const FunctionType *Ty;
2252 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2253 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2254 // Pull out the types of all of the arguments...
2255 std::vector<const Type*> ParamTypes;
2257 for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
2259 ParamTypes.push_back((*I)->getType());
2262 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2263 if (isVarArg) ParamTypes.pop_back();
2265 if (!(*$3)->isFirstClassType() && *$3 != Type::VoidTy)
2266 ThrowException("LLVM functions cannot return aggregate types!");
2268 Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
2269 PFTy = PointerType::get(Ty);
2272 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2274 // Create the call node...
2275 if (!$6) { // Has no arguments?
2276 // Make sure no arguments is a good thing!
2277 if (Ty->getNumParams() != 0)
2278 ThrowException("No arguments passed to a function that "
2279 "expects arguments!");
2281 $$ = new CallInst(V, std::vector<Value*>());
2282 } else { // Has arguments?
2283 // Loop through FunctionType's arguments and ensure they are specified
2286 FunctionType::param_iterator I = Ty->param_begin();
2287 FunctionType::param_iterator E = Ty->param_end();
2288 std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
2290 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2291 if ((*ArgI)->getType() != *I)
2292 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2293 (*I)->getDescription() + "'!");
2295 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2296 ThrowException("Invalid number of parameters detected!");
2298 $$ = new CallInst(V, *$6);
2300 cast<CallInst>($$)->setTailCall($1);
2301 cast<CallInst>($$)->setCallingConv($2);
2310 // IndexList - List of indices for GEP based instructions...
2311 IndexList : ',' ValueRefList {
2314 $$ = new std::vector<Value*>();
2317 OptVolatile : VOLATILE {
2326 MemoryInst : MALLOC Types OptCAlign {
2327 $$ = new MallocInst(*$2, 0, $3);
2330 | MALLOC Types ',' UINT ValueRef OptCAlign {
2331 $$ = new MallocInst(*$2, getVal($4, $5), $6);
2334 | ALLOCA Types OptCAlign {
2335 $$ = new AllocaInst(*$2, 0, $3);
2338 | ALLOCA Types ',' UINT ValueRef OptCAlign {
2339 $$ = new AllocaInst(*$2, getVal($4, $5), $6);
2342 | FREE ResolvedVal {
2343 if (!isa<PointerType>($2->getType()))
2344 ThrowException("Trying to free nonpointer type " +
2345 $2->getType()->getDescription() + "!");
2346 $$ = new FreeInst($2);
2349 | OptVolatile LOAD Types ValueRef {
2350 if (!isa<PointerType>($3->get()))
2351 ThrowException("Can't load from nonpointer type: " +
2352 (*$3)->getDescription());
2353 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
2354 ThrowException("Can't load from pointer of non-first-class type: " +
2355 (*$3)->getDescription());
2356 $$ = new LoadInst(getVal(*$3, $4), "", $1);
2359 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2360 const PointerType *PT = dyn_cast<PointerType>($5->get());
2362 ThrowException("Can't store to a nonpointer type: " +
2363 (*$5)->getDescription());
2364 const Type *ElTy = PT->getElementType();
2365 if (ElTy != $3->getType())
2366 ThrowException("Can't store '" + $3->getType()->getDescription() +
2367 "' into space of type '" + ElTy->getDescription() + "'!");
2369 $$ = new StoreInst($3, getVal(*$5, $6), $1);
2372 | GETELEMENTPTR Types ValueRef IndexList {
2373 if (!isa<PointerType>($2->get()))
2374 ThrowException("getelementptr insn requires pointer operand!");
2376 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
2377 // indices to uint struct indices for compatibility.
2378 generic_gep_type_iterator<std::vector<Value*>::iterator>
2379 GTI = gep_type_begin($2->get(), $4->begin(), $4->end()),
2380 GTE = gep_type_end($2->get(), $4->begin(), $4->end());
2381 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
2382 if (isa<StructType>(*GTI)) // Only change struct indices
2383 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
2384 if (CUI->getType() == Type::UByteTy)
2385 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
2387 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2388 ThrowException("Invalid getelementptr indices for type '" +
2389 (*$2)->getDescription()+ "'!");
2390 $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
2391 delete $2; delete $4;
2396 int yyerror(const char *ErrorMsg) {
2398 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2399 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2400 std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2401 if (yychar == YYEMPTY || yychar == 0)
2402 errMsg += "end-of-file.";
2404 errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2405 ThrowException(errMsg);