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/InlineAsm.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/SymbolTable.h"
21 #include "llvm/Assembly/AutoUpgrade.h"
22 #include "llvm/Support/GetElementPtrTypeIterator.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/Support/MathExtras.h"
30 // The following is a gross hack. In order to rid the libAsmParser library of
31 // exceptions, we have to have a way of getting the yyparse function to go into
32 // an error situation. So, whenever we want an error to occur, the GenerateError
33 // function (see bottom of file) sets TriggerError. Then, at the end of each
34 // production in the grammer we use CHECK_FOR_ERROR which will invoke YYERROR
35 // (a goto) to put YACC in error state. Furthermore, several calls to
36 // GenerateError are made from inside productions and they must simulate the
37 // previous exception behavior by exiting the production immediately. We have
38 // replaced these with the GEN_ERROR macro which calls GeneratError and then
39 // immediately invokes YYERROR. This would be so much cleaner if it was a
40 // recursive descent parser.
41 static bool TriggerError = false;
42 #define CHECK_FOR_ERROR { if (TriggerError) { TriggerError = false; YYABORT; } }
43 #define GEN_ERROR(msg) { GenerateError(msg); YYERROR; }
45 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
46 int yylex(); // declaration" of xxx warnings.
50 std::string CurFilename;
54 static Module *ParserResult;
56 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
57 // relating to upreferences in the input stream.
59 //#define DEBUG_UPREFS 1
61 #define UR_OUT(X) std::cerr << X
66 #define YYERROR_VERBOSE 1
68 static bool ObsoleteVarArgs;
69 static bool NewVarArgs;
70 static BasicBlock *CurBB;
71 static GlobalVariable *CurGV;
74 // This contains info used when building the body of a function. It is
75 // destroyed when the function is completed.
77 typedef std::vector<Value *> ValueList; // Numbered defs
79 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
80 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
82 static struct PerModuleInfo {
83 Module *CurrentModule;
84 std::map<const Type *, ValueList> Values; // Module level numbered definitions
85 std::map<const Type *,ValueList> LateResolveValues;
86 std::vector<PATypeHolder> Types;
87 std::map<ValID, PATypeHolder> LateResolveTypes;
89 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
90 /// how they were referenced and on which line of the input they came from so
91 /// that we can resolve them later and print error messages as appropriate.
92 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
94 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
95 // references to global values. Global values may be referenced before they
96 // are defined, and if so, the temporary object that they represent is held
97 // here. This is used for forward references of GlobalValues.
99 typedef std::map<std::pair<const PointerType *,
100 ValID>, GlobalValue*> GlobalRefsType;
101 GlobalRefsType GlobalRefs;
104 // If we could not resolve some functions at function compilation time
105 // (calls to functions before they are defined), resolve them now... Types
106 // are resolved when the constant pool has been completely parsed.
108 ResolveDefinitions(LateResolveValues);
112 // Check to make sure that all global value forward references have been
115 if (!GlobalRefs.empty()) {
116 std::string UndefinedReferences = "Unresolved global references exist:\n";
118 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
120 UndefinedReferences += " " + I->first.first->getDescription() + " " +
121 I->first.second.getName() + "\n";
123 GenerateError(UndefinedReferences);
127 // Look for intrinsic functions and CallInst that need to be upgraded
128 for (Module::iterator FI = CurrentModule->begin(),
129 FE = CurrentModule->end(); FI != FE; )
130 UpgradeCallsToIntrinsic(FI++);
132 Values.clear(); // Clear out function local definitions
137 // GetForwardRefForGlobal - Check to see if there is a forward reference
138 // for this global. If so, remove it from the GlobalRefs map and return it.
139 // If not, just return null.
140 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
141 // Check to see if there is a forward reference to this global variable...
142 // if there is, eliminate it and patch the reference to use the new def'n.
143 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
144 GlobalValue *Ret = 0;
145 if (I != GlobalRefs.end()) {
153 static struct PerFunctionInfo {
154 Function *CurrentFunction; // Pointer to current function being created
156 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
157 std::map<const Type*, ValueList> LateResolveValues;
158 bool isDeclare; // Is this function a forward declararation?
159 GlobalValue::LinkageTypes Linkage; // Linkage for forward declaration.
161 /// BBForwardRefs - When we see forward references to basic blocks, keep
162 /// track of them here.
163 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
164 std::vector<BasicBlock*> NumberedBlocks;
167 inline PerFunctionInfo() {
170 Linkage = GlobalValue::ExternalLinkage;
173 inline void FunctionStart(Function *M) {
178 void FunctionDone() {
179 NumberedBlocks.clear();
181 // Any forward referenced blocks left?
182 if (!BBForwardRefs.empty()) {
183 GenerateError("Undefined reference to label " +
184 BBForwardRefs.begin()->first->getName());
188 // Resolve all forward references now.
189 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
191 Values.clear(); // Clear out function local definitions
194 Linkage = GlobalValue::ExternalLinkage;
196 } CurFun; // Info for the current function...
198 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
201 //===----------------------------------------------------------------------===//
202 // Code to handle definitions of all the types
203 //===----------------------------------------------------------------------===//
205 static int InsertValue(Value *V,
206 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
207 if (V->hasName()) return -1; // Is this a numbered definition?
209 // Yes, insert the value into the value table...
210 ValueList &List = ValueTab[V->getType()];
212 return List.size()-1;
215 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
217 case ValID::NumberVal: // Is it a numbered definition?
218 // Module constants occupy the lowest numbered slots...
219 if ((unsigned)D.Num < CurModule.Types.size())
220 return CurModule.Types[(unsigned)D.Num];
222 case ValID::NameVal: // Is it a named definition?
223 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
224 D.destroy(); // Free old strdup'd memory...
229 GenerateError("Internal parser error: Invalid symbol type reference!");
233 // If we reached here, we referenced either a symbol that we don't know about
234 // or an id number that hasn't been read yet. We may be referencing something
235 // forward, so just create an entry to be resolved later and get to it...
237 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
240 if (inFunctionScope()) {
241 if (D.Type == ValID::NameVal) {
242 GenerateError("Reference to an undefined type: '" + D.getName() + "'");
245 GenerateError("Reference to an undefined type: #" + itostr(D.Num));
250 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
251 if (I != CurModule.LateResolveTypes.end())
254 Type *Typ = OpaqueType::get();
255 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
259 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
260 SymbolTable &SymTab =
261 inFunctionScope() ? CurFun.CurrentFunction->getSymbolTable() :
262 CurModule.CurrentModule->getSymbolTable();
263 return SymTab.lookup(Ty, Name);
266 // getValNonImprovising - Look up the value specified by the provided type and
267 // the provided ValID. If the value exists and has already been defined, return
268 // it. Otherwise return null.
270 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
271 if (isa<FunctionType>(Ty)) {
272 GenerateError("Functions are not values and "
273 "must be referenced as pointers");
278 case ValID::NumberVal: { // Is it a numbered definition?
279 unsigned Num = (unsigned)D.Num;
281 // Module constants occupy the lowest numbered slots...
282 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
283 if (VI != CurModule.Values.end()) {
284 if (Num < VI->second.size())
285 return VI->second[Num];
286 Num -= VI->second.size();
289 // Make sure that our type is within bounds
290 VI = CurFun.Values.find(Ty);
291 if (VI == CurFun.Values.end()) return 0;
293 // Check that the number is within bounds...
294 if (VI->second.size() <= Num) return 0;
296 return VI->second[Num];
299 case ValID::NameVal: { // Is it a named definition?
300 Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
301 if (N == 0) return 0;
303 D.destroy(); // Free old strdup'd memory...
307 // Check to make sure that "Ty" is an integral type, and that our
308 // value will fit into the specified type...
309 case ValID::ConstSIntVal: // Is it a constant pool reference??
310 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64)) {
311 GenerateError("Signed integral constant '" +
312 itostr(D.ConstPool64) + "' is invalid for type '" +
313 Ty->getDescription() + "'!");
316 return ConstantSInt::get(Ty, D.ConstPool64);
318 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
319 if (!ConstantUInt::isValueValidForType(Ty, D.UConstPool64)) {
320 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64)) {
321 GenerateError("Integral constant '" + utostr(D.UConstPool64) +
322 "' is invalid or out of range!");
324 } else { // This is really a signed reference. Transmogrify.
325 return ConstantSInt::get(Ty, D.ConstPool64);
328 return ConstantUInt::get(Ty, D.UConstPool64);
331 case ValID::ConstFPVal: // Is it a floating point const pool reference?
332 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP)) {
333 GenerateError("FP constant invalid for type!!");
336 return ConstantFP::get(Ty, D.ConstPoolFP);
338 case ValID::ConstNullVal: // Is it a null value?
339 if (!isa<PointerType>(Ty)) {
340 GenerateError("Cannot create a a non pointer null!");
343 return ConstantPointerNull::get(cast<PointerType>(Ty));
345 case ValID::ConstUndefVal: // Is it an undef value?
346 return UndefValue::get(Ty);
348 case ValID::ConstZeroVal: // Is it a zero value?
349 return Constant::getNullValue(Ty);
351 case ValID::ConstantVal: // Fully resolved constant?
352 if (D.ConstantValue->getType() != Ty) {
353 GenerateError("Constant expression type different from required type!");
356 return D.ConstantValue;
358 case ValID::InlineAsmVal: { // Inline asm expression
359 const PointerType *PTy = dyn_cast<PointerType>(Ty);
360 const FunctionType *FTy =
361 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
362 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
363 GenerateError("Invalid type for asm constraint string!");
366 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
367 D.IAD->HasSideEffects);
368 D.destroy(); // Free InlineAsmDescriptor.
372 assert(0 && "Unhandled case!");
376 assert(0 && "Unhandled case!");
380 // getVal - This function is identical to getValNonImprovising, except that if a
381 // value is not already defined, it "improvises" by creating a placeholder var
382 // that looks and acts just like the requested variable. When the value is
383 // defined later, all uses of the placeholder variable are replaced with the
386 static Value *getVal(const Type *Ty, const ValID &ID) {
387 if (Ty == Type::LabelTy) {
388 GenerateError("Cannot use a basic block here");
392 // See if the value has already been defined.
393 Value *V = getValNonImprovising(Ty, ID);
395 if (TriggerError) return 0;
397 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
398 GenerateError("Invalid use of a composite type!");
402 // If we reached here, we referenced either a symbol that we don't know about
403 // or an id number that hasn't been read yet. We may be referencing something
404 // forward, so just create an entry to be resolved later and get to it...
406 V = new Argument(Ty);
408 // Remember where this forward reference came from. FIXME, shouldn't we try
409 // to recycle these things??
410 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
413 if (inFunctionScope())
414 InsertValue(V, CurFun.LateResolveValues);
416 InsertValue(V, CurModule.LateResolveValues);
420 /// getBBVal - This is used for two purposes:
421 /// * If isDefinition is true, a new basic block with the specified ID is being
423 /// * If isDefinition is true, this is a reference to a basic block, which may
424 /// or may not be a forward reference.
426 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
427 assert(inFunctionScope() && "Can't get basic block at global scope!");
433 GenerateError("Illegal label reference " + ID.getName());
435 case ValID::NumberVal: // Is it a numbered definition?
436 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
437 CurFun.NumberedBlocks.resize(ID.Num+1);
438 BB = CurFun.NumberedBlocks[ID.Num];
440 case ValID::NameVal: // Is it a named definition?
442 if (Value *N = CurFun.CurrentFunction->
443 getSymbolTable().lookup(Type::LabelTy, Name))
444 BB = cast<BasicBlock>(N);
448 // See if the block has already been defined.
450 // If this is the definition of the block, make sure the existing value was
451 // just a forward reference. If it was a forward reference, there will be
452 // an entry for it in the PlaceHolderInfo map.
453 if (isDefinition && !CurFun.BBForwardRefs.erase(BB)) {
454 // The existing value was a definition, not a forward reference.
455 GenerateError("Redefinition of label " + ID.getName());
459 ID.destroy(); // Free strdup'd memory.
463 // Otherwise this block has not been seen before.
464 BB = new BasicBlock("", CurFun.CurrentFunction);
465 if (ID.Type == ValID::NameVal) {
466 BB->setName(ID.Name);
468 CurFun.NumberedBlocks[ID.Num] = BB;
471 // If this is not a definition, keep track of it so we can use it as a forward
474 // Remember where this forward reference came from.
475 CurFun.BBForwardRefs[BB] = std::make_pair(ID, llvmAsmlineno);
477 // The forward declaration could have been inserted anywhere in the
478 // function: insert it into the correct place now.
479 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
480 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
487 //===----------------------------------------------------------------------===//
488 // Code to handle forward references in instructions
489 //===----------------------------------------------------------------------===//
491 // This code handles the late binding needed with statements that reference
492 // values not defined yet... for example, a forward branch, or the PHI node for
495 // This keeps a table (CurFun.LateResolveValues) of all such forward references
496 // and back patchs after we are done.
499 // ResolveDefinitions - If we could not resolve some defs at parsing
500 // time (forward branches, phi functions for loops, etc...) resolve the
504 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
505 std::map<const Type*,ValueList> *FutureLateResolvers) {
506 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
507 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
508 E = LateResolvers.end(); LRI != E; ++LRI) {
509 ValueList &List = LRI->second;
510 while (!List.empty()) {
511 Value *V = List.back();
514 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
515 CurModule.PlaceHolderInfo.find(V);
516 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
518 ValID &DID = PHI->second.first;
520 Value *TheRealValue = getValNonImprovising(LRI->first, DID);
524 V->replaceAllUsesWith(TheRealValue);
526 CurModule.PlaceHolderInfo.erase(PHI);
527 } else if (FutureLateResolvers) {
528 // Functions have their unresolved items forwarded to the module late
530 InsertValue(V, *FutureLateResolvers);
532 if (DID.Type == ValID::NameVal) {
533 GenerateError("Reference to an invalid definition: '" +DID.getName()+
534 "' of type '" + V->getType()->getDescription() + "'",
538 GenerateError("Reference to an invalid definition: #" +
539 itostr(DID.Num) + " of type '" +
540 V->getType()->getDescription() + "'",
548 LateResolvers.clear();
551 // ResolveTypeTo - A brand new type was just declared. This means that (if
552 // name is not null) things referencing Name can be resolved. Otherwise, things
553 // refering to the number can be resolved. Do this now.
555 static void ResolveTypeTo(char *Name, const Type *ToTy) {
557 if (Name) D = ValID::create(Name);
558 else D = ValID::create((int)CurModule.Types.size());
560 std::map<ValID, PATypeHolder>::iterator I =
561 CurModule.LateResolveTypes.find(D);
562 if (I != CurModule.LateResolveTypes.end()) {
563 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
564 CurModule.LateResolveTypes.erase(I);
568 // setValueName - Set the specified value to the name given. The name may be
569 // null potentially, in which case this is a noop. The string passed in is
570 // assumed to be a malloc'd string buffer, and is free'd by this function.
572 static void setValueName(Value *V, char *NameStr) {
574 std::string Name(NameStr); // Copy string
575 free(NameStr); // Free old string
577 if (V->getType() == Type::VoidTy) {
578 GenerateError("Can't assign name '" + Name+"' to value with void type!");
582 assert(inFunctionScope() && "Must be in function scope!");
583 SymbolTable &ST = CurFun.CurrentFunction->getSymbolTable();
584 if (ST.lookup(V->getType(), Name)) {
585 GenerateError("Redefinition of value named '" + Name + "' in the '" +
586 V->getType()->getDescription() + "' type plane!");
595 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
596 /// this is a declaration, otherwise it is a definition.
597 static GlobalVariable *
598 ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
599 bool isConstantGlobal, const Type *Ty,
600 Constant *Initializer) {
601 if (isa<FunctionType>(Ty)) {
602 GenerateError("Cannot declare global vars of function type!");
606 const PointerType *PTy = PointerType::get(Ty);
610 Name = NameStr; // Copy string
611 free(NameStr); // Free old string
614 // See if this global value was forward referenced. If so, recycle the
618 ID = ValID::create((char*)Name.c_str());
620 ID = ValID::create((int)CurModule.Values[PTy].size());
623 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
624 // Move the global to the end of the list, from whereever it was
625 // previously inserted.
626 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
627 CurModule.CurrentModule->getGlobalList().remove(GV);
628 CurModule.CurrentModule->getGlobalList().push_back(GV);
629 GV->setInitializer(Initializer);
630 GV->setLinkage(Linkage);
631 GV->setConstant(isConstantGlobal);
632 InsertValue(GV, CurModule.Values);
636 // If this global has a name, check to see if there is already a definition
637 // of this global in the module. If so, merge as appropriate. Note that
638 // this is really just a hack around problems in the CFE. :(
640 // We are a simple redefinition of a value, check to see if it is defined
641 // the same as the old one.
642 if (GlobalVariable *EGV =
643 CurModule.CurrentModule->getGlobalVariable(Name, Ty)) {
644 // We are allowed to redefine a global variable in two circumstances:
645 // 1. If at least one of the globals is uninitialized or
646 // 2. If both initializers have the same value.
648 if (!EGV->hasInitializer() || !Initializer ||
649 EGV->getInitializer() == Initializer) {
651 // Make sure the existing global version gets the initializer! Make
652 // sure that it also gets marked const if the new version is.
653 if (Initializer && !EGV->hasInitializer())
654 EGV->setInitializer(Initializer);
655 if (isConstantGlobal)
656 EGV->setConstant(true);
657 EGV->setLinkage(Linkage);
661 GenerateError("Redefinition of global variable named '" + Name +
662 "' in the '" + Ty->getDescription() + "' type plane!");
667 // Otherwise there is no existing GV to use, create one now.
669 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
670 CurModule.CurrentModule);
671 InsertValue(GV, CurModule.Values);
675 // setTypeName - Set the specified type to the name given. The name may be
676 // null potentially, in which case this is a noop. The string passed in is
677 // assumed to be a malloc'd string buffer, and is freed by this function.
679 // This function returns true if the type has already been defined, but is
680 // allowed to be redefined in the specified context. If the name is a new name
681 // for the type plane, it is inserted and false is returned.
682 static bool setTypeName(const Type *T, char *NameStr) {
683 assert(!inFunctionScope() && "Can't give types function-local names!");
684 if (NameStr == 0) return false;
686 std::string Name(NameStr); // Copy string
687 free(NameStr); // Free old string
689 // We don't allow assigning names to void type
690 if (T == Type::VoidTy) {
691 GenerateError("Can't assign name '" + Name + "' to the void type!");
695 // Set the type name, checking for conflicts as we do so.
696 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
698 if (AlreadyExists) { // Inserting a name that is already defined???
699 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
700 assert(Existing && "Conflict but no matching type?");
702 // There is only one case where this is allowed: when we are refining an
703 // opaque type. In this case, Existing will be an opaque type.
704 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
705 // We ARE replacing an opaque type!
706 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
710 // Otherwise, this is an attempt to redefine a type. That's okay if
711 // the redefinition is identical to the original. This will be so if
712 // Existing and T point to the same Type object. In this one case we
713 // allow the equivalent redefinition.
714 if (Existing == T) return true; // Yes, it's equal.
716 // Any other kind of (non-equivalent) redefinition is an error.
717 GenerateError("Redefinition of type named '" + Name + "' in the '" +
718 T->getDescription() + "' type plane!");
724 //===----------------------------------------------------------------------===//
725 // Code for handling upreferences in type names...
728 // TypeContains - Returns true if Ty directly contains E in it.
730 static bool TypeContains(const Type *Ty, const Type *E) {
731 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
732 E) != Ty->subtype_end();
737 // NestingLevel - The number of nesting levels that need to be popped before
738 // this type is resolved.
739 unsigned NestingLevel;
741 // LastContainedTy - This is the type at the current binding level for the
742 // type. Every time we reduce the nesting level, this gets updated.
743 const Type *LastContainedTy;
745 // UpRefTy - This is the actual opaque type that the upreference is
749 UpRefRecord(unsigned NL, OpaqueType *URTy)
750 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
754 // UpRefs - A list of the outstanding upreferences that need to be resolved.
755 static std::vector<UpRefRecord> UpRefs;
757 /// HandleUpRefs - Every time we finish a new layer of types, this function is
758 /// called. It loops through the UpRefs vector, which is a list of the
759 /// currently active types. For each type, if the up reference is contained in
760 /// the newly completed type, we decrement the level count. When the level
761 /// count reaches zero, the upreferenced type is the type that is passed in:
762 /// thus we can complete the cycle.
764 static PATypeHolder HandleUpRefs(const Type *ty) {
765 // If Ty isn't abstract, or if there are no up-references in it, then there is
766 // nothing to resolve here.
767 if (!ty->isAbstract() || UpRefs.empty()) return ty;
770 UR_OUT("Type '" << Ty->getDescription() <<
771 "' newly formed. Resolving upreferences.\n" <<
772 UpRefs.size() << " upreferences active!\n");
774 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
775 // to zero), we resolve them all together before we resolve them to Ty. At
776 // the end of the loop, if there is anything to resolve to Ty, it will be in
778 OpaqueType *TypeToResolve = 0;
780 for (unsigned i = 0; i != UpRefs.size(); ++i) {
781 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
782 << UpRefs[i].second->getDescription() << ") = "
783 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
784 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
785 // Decrement level of upreference
786 unsigned Level = --UpRefs[i].NestingLevel;
787 UpRefs[i].LastContainedTy = Ty;
788 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
789 if (Level == 0) { // Upreference should be resolved!
790 if (!TypeToResolve) {
791 TypeToResolve = UpRefs[i].UpRefTy;
793 UR_OUT(" * Resolving upreference for "
794 << UpRefs[i].second->getDescription() << "\n";
795 std::string OldName = UpRefs[i].UpRefTy->getDescription());
796 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
797 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
798 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
800 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
801 --i; // Do not skip the next element...
807 UR_OUT(" * Resolving upreference for "
808 << UpRefs[i].second->getDescription() << "\n";
809 std::string OldName = TypeToResolve->getDescription());
810 TypeToResolve->refineAbstractTypeTo(Ty);
817 // common code from the two 'RunVMAsmParser' functions
818 static Module* RunParser(Module * M) {
820 llvmAsmlineno = 1; // Reset the current line number...
821 ObsoleteVarArgs = false;
823 CurModule.CurrentModule = M;
825 // Check to make sure the parser succeeded
832 // Check to make sure that parsing produced a result
836 // Reset ParserResult variable while saving its value for the result.
837 Module *Result = ParserResult;
840 //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
843 if ((F = Result->getNamedFunction("llvm.va_start"))
844 && F->getFunctionType()->getNumParams() == 0)
845 ObsoleteVarArgs = true;
846 if((F = Result->getNamedFunction("llvm.va_copy"))
847 && F->getFunctionType()->getNumParams() == 1)
848 ObsoleteVarArgs = true;
851 if (ObsoleteVarArgs && NewVarArgs) {
853 "This file is corrupt: it uses both new and old style varargs");
857 if(ObsoleteVarArgs) {
858 if(Function* F = Result->getNamedFunction("llvm.va_start")) {
859 if (F->arg_size() != 0) {
860 GenerateError("Obsolete va_start takes 0 argument!");
866 //bar = alloca typeof(foo)
870 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
871 const Type* ArgTy = F->getFunctionType()->getReturnType();
872 const Type* ArgTyPtr = PointerType::get(ArgTy);
873 Function* NF = Result->getOrInsertFunction("llvm.va_start",
874 RetTy, ArgTyPtr, (Type *)0);
876 while (!F->use_empty()) {
877 CallInst* CI = cast<CallInst>(F->use_back());
878 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
879 new CallInst(NF, bar, "", CI);
880 Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
881 CI->replaceAllUsesWith(foo);
882 CI->getParent()->getInstList().erase(CI);
884 Result->getFunctionList().erase(F);
887 if(Function* F = Result->getNamedFunction("llvm.va_end")) {
888 if(F->arg_size() != 1) {
889 GenerateError("Obsolete va_end takes 1 argument!");
895 //bar = alloca 1 of typeof(foo)
897 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
898 const Type* ArgTy = F->getFunctionType()->getParamType(0);
899 const Type* ArgTyPtr = PointerType::get(ArgTy);
900 Function* NF = Result->getOrInsertFunction("llvm.va_end",
901 RetTy, ArgTyPtr, (Type *)0);
903 while (!F->use_empty()) {
904 CallInst* CI = cast<CallInst>(F->use_back());
905 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
906 new StoreInst(CI->getOperand(1), bar, CI);
907 new CallInst(NF, bar, "", CI);
908 CI->getParent()->getInstList().erase(CI);
910 Result->getFunctionList().erase(F);
913 if(Function* F = Result->getNamedFunction("llvm.va_copy")) {
914 if(F->arg_size() != 1) {
915 GenerateError("Obsolete va_copy takes 1 argument!");
920 //a = alloca 1 of typeof(foo)
921 //b = alloca 1 of typeof(foo)
926 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
927 const Type* ArgTy = F->getFunctionType()->getReturnType();
928 const Type* ArgTyPtr = PointerType::get(ArgTy);
929 Function* NF = Result->getOrInsertFunction("llvm.va_copy",
930 RetTy, ArgTyPtr, ArgTyPtr,
933 while (!F->use_empty()) {
934 CallInst* CI = cast<CallInst>(F->use_back());
935 AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
936 AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
937 new StoreInst(CI->getOperand(1), b, CI);
938 new CallInst(NF, a, b, "", CI);
939 Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
940 CI->replaceAllUsesWith(foo);
941 CI->getParent()->getInstList().erase(CI);
943 Result->getFunctionList().erase(F);
950 //===----------------------------------------------------------------------===//
951 // RunVMAsmParser - Define an interface to this parser
952 //===----------------------------------------------------------------------===//
954 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
957 CurFilename = Filename;
958 return RunParser(new Module(CurFilename));
961 Module *llvm::RunVMAsmParser(const char * AsmString, Module * M) {
962 set_scan_string(AsmString);
964 CurFilename = "from_memory";
966 return RunParser(new Module (CurFilename));
975 llvm::Module *ModuleVal;
976 llvm::Function *FunctionVal;
977 std::pair<llvm::PATypeHolder*, char*> *ArgVal;
978 llvm::BasicBlock *BasicBlockVal;
979 llvm::TerminatorInst *TermInstVal;
980 llvm::Instruction *InstVal;
981 llvm::Constant *ConstVal;
983 const llvm::Type *PrimType;
984 llvm::PATypeHolder *TypeVal;
985 llvm::Value *ValueVal;
987 std::vector<std::pair<llvm::PATypeHolder*,char*> > *ArgList;
988 std::vector<llvm::Value*> *ValueList;
989 std::list<llvm::PATypeHolder> *TypeList;
990 // Represent the RHS of PHI node
991 std::list<std::pair<llvm::Value*,
992 llvm::BasicBlock*> > *PHIList;
993 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
994 std::vector<llvm::Constant*> *ConstVector;
996 llvm::GlobalValue::LinkageTypes Linkage;
1004 char *StrVal; // This memory is strdup'd!
1005 llvm::ValID ValIDVal; // strdup'd memory maybe!
1007 llvm::Instruction::BinaryOps BinaryOpVal;
1008 llvm::Instruction::TermOps TermOpVal;
1009 llvm::Instruction::MemoryOps MemOpVal;
1010 llvm::Instruction::OtherOps OtherOpVal;
1011 llvm::Module::Endianness Endianness;
1014 %type <ModuleVal> Module FunctionList
1015 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1016 %type <BasicBlockVal> BasicBlock InstructionList
1017 %type <TermInstVal> BBTerminatorInst
1018 %type <InstVal> Inst InstVal MemoryInst
1019 %type <ConstVal> ConstVal ConstExpr
1020 %type <ConstVector> ConstVector
1021 %type <ArgList> ArgList ArgListH
1022 %type <ArgVal> ArgVal
1023 %type <PHIList> PHIList
1024 %type <ValueList> ValueRefList ValueRefListE // For call param lists
1025 %type <ValueList> IndexList // For GEP derived indices
1026 %type <TypeList> TypeListI ArgTypeListI
1027 %type <JumpTable> JumpTable
1028 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1029 %type <BoolVal> OptVolatile // 'volatile' or not
1030 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1031 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
1032 %type <Linkage> OptLinkage
1033 %type <Endianness> BigOrLittle
1035 // ValueRef - Unresolved reference to a definition or BB
1036 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1037 %type <ValueVal> ResolvedVal // <type> <valref> pair
1038 // Tokens and types for handling constant integer values
1040 // ESINT64VAL - A negative number within long long range
1041 %token <SInt64Val> ESINT64VAL
1043 // EUINT64VAL - A positive number within uns. long long range
1044 %token <UInt64Val> EUINT64VAL
1045 %type <SInt64Val> EINT64VAL
1047 %token <SIntVal> SINTVAL // Signed 32 bit ints...
1048 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
1049 %type <SIntVal> INTVAL
1050 %token <FPVal> FPVAL // Float or Double constant
1052 // Built in types...
1053 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
1054 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
1055 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
1056 %token <PrimType> FLOAT DOUBLE TYPE LABEL
1058 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
1059 %type <StrVal> Name OptName OptAssign
1060 %type <UIntVal> OptAlign OptCAlign
1061 %type <StrVal> OptSection SectionString
1063 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1064 %token DECLARE GLOBAL CONSTANT SECTION VOLATILE
1065 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
1066 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
1067 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
1068 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1069 %token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
1070 %token X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1071 %type <UIntVal> OptCallingConv
1073 // Basic Block Terminating Operators
1074 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1077 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
1078 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
1079 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comarators
1081 // Memory Instructions
1082 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1085 %type <OtherOpVal> ShiftOps
1086 %token <OtherOpVal> PHI_TOK CAST SELECT SHL SHR VAARG
1087 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1088 %token VAARG_old VANEXT_old //OBSOLETE
1094 // Handle constant integer size restriction and conversion...
1098 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
1099 GEN_ERROR("Value too large for type!");
1105 EINT64VAL : ESINT64VAL; // These have same type and can't cause problems...
1106 EINT64VAL : EUINT64VAL {
1107 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
1108 GEN_ERROR("Value too large for type!");
1113 // Operations that are notably excluded from this list include:
1114 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1116 ArithmeticOps: ADD | SUB | MUL | DIV | REM;
1117 LogicalOps : AND | OR | XOR;
1118 SetCondOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
1120 ShiftOps : SHL | SHR;
1122 // These are some types that allow classification if we only want a particular
1123 // thing... for example, only a signed, unsigned, or integral type.
1124 SIntType : LONG | INT | SHORT | SBYTE;
1125 UIntType : ULONG | UINT | USHORT | UBYTE;
1126 IntType : SIntType | UIntType;
1127 FPType : FLOAT | DOUBLE;
1129 // OptAssign - Value producing statements have an optional assignment component
1130 OptAssign : Name '=' {
1139 OptLinkage : INTERNAL { $$ = GlobalValue::InternalLinkage; } |
1140 LINKONCE { $$ = GlobalValue::LinkOnceLinkage; } |
1141 WEAK { $$ = GlobalValue::WeakLinkage; } |
1142 APPENDING { $$ = GlobalValue::AppendingLinkage; } |
1143 DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; } |
1144 DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; } |
1145 EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; } |
1146 /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
1148 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1149 CCC_TOK { $$ = CallingConv::C; } |
1150 CSRETCC_TOK { $$ = CallingConv::CSRet; } |
1151 FASTCC_TOK { $$ = CallingConv::Fast; } |
1152 COLDCC_TOK { $$ = CallingConv::Cold; } |
1153 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1154 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1156 if ((unsigned)$2 != $2)
1157 GEN_ERROR("Calling conv too large!");
1162 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1163 // a comma before it.
1164 OptAlign : /*empty*/ { $$ = 0; } |
1167 if ($$ != 0 && !isPowerOf2_32($$))
1168 GEN_ERROR("Alignment must be a power of two!");
1171 OptCAlign : /*empty*/ { $$ = 0; } |
1172 ',' ALIGN EUINT64VAL {
1174 if ($$ != 0 && !isPowerOf2_32($$))
1175 GEN_ERROR("Alignment must be a power of two!");
1180 SectionString : SECTION STRINGCONSTANT {
1181 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1182 if ($2[i] == '"' || $2[i] == '\\')
1183 GEN_ERROR("Invalid character in section name!");
1188 OptSection : /*empty*/ { $$ = 0; } |
1189 SectionString { $$ = $1; };
1191 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1192 // is set to be the global we are processing.
1194 GlobalVarAttributes : /* empty */ {} |
1195 ',' GlobalVarAttribute GlobalVarAttributes {};
1196 GlobalVarAttribute : SectionString {
1197 CurGV->setSection($1);
1201 | ALIGN EUINT64VAL {
1202 if ($2 != 0 && !isPowerOf2_32($2))
1203 GEN_ERROR("Alignment must be a power of two!");
1204 CurGV->setAlignment($2);
1208 //===----------------------------------------------------------------------===//
1209 // Types includes all predefined types... except void, because it can only be
1210 // used in specific contexts (function returning void for example). To have
1211 // access to it, a user must explicitly use TypesV.
1214 // TypesV includes all of 'Types', but it also includes the void type.
1215 TypesV : Types | VOID { $$ = new PATypeHolder($1); };
1216 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
1219 if (!UpRefs.empty())
1220 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1226 // Derived types are added later...
1228 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT ;
1229 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL;
1231 $$ = new PATypeHolder(OpaqueType::get());
1235 $$ = new PATypeHolder($1);
1238 UpRTypes : SymbolicValueRef { // Named types are also simple types...
1239 const Type* tmp = getTypeVal($1);
1241 $$ = new PATypeHolder(tmp);
1244 // Include derived types in the Types production.
1246 UpRTypes : '\\' EUINT64VAL { // Type UpReference
1247 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range!");
1248 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1249 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1250 $$ = new PATypeHolder(OT);
1251 UR_OUT("New Upreference!\n");
1254 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
1255 std::vector<const Type*> Params;
1256 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1257 E = $3->end(); I != E; ++I)
1258 Params.push_back(*I);
1259 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1260 if (isVarArg) Params.pop_back();
1262 $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
1263 delete $3; // Delete the argument list
1264 delete $1; // Delete the return type handle
1267 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
1268 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1272 | '<' EUINT64VAL 'x' UpRTypes '>' { // Packed array type?
1273 const llvm::Type* ElemTy = $4->get();
1274 if ((unsigned)$2 != $2)
1275 GEN_ERROR("Unsigned result not equal to signed result");
1276 if (!ElemTy->isPrimitiveType())
1277 GEN_ERROR("Elemental type of a PackedType must be primitive");
1278 if (!isPowerOf2_32($2))
1279 GEN_ERROR("Vector length should be a power of 2!");
1280 $$ = new PATypeHolder(HandleUpRefs(PackedType::get(*$4, (unsigned)$2)));
1284 | '{' TypeListI '}' { // Structure type?
1285 std::vector<const Type*> Elements;
1286 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1287 E = $2->end(); I != E; ++I)
1288 Elements.push_back(*I);
1290 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1294 | '{' '}' { // Empty structure type?
1295 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1298 | UpRTypes '*' { // Pointer type?
1299 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1304 // TypeList - Used for struct declarations and as a basis for function type
1305 // declaration type lists
1307 TypeListI : UpRTypes {
1308 $$ = new std::list<PATypeHolder>();
1309 $$->push_back(*$1); delete $1;
1312 | TypeListI ',' UpRTypes {
1313 ($$=$1)->push_back(*$3); delete $3;
1317 // ArgTypeList - List of types for a function type declaration...
1318 ArgTypeListI : TypeListI
1319 | TypeListI ',' DOTDOTDOT {
1320 ($$=$1)->push_back(Type::VoidTy);
1324 ($$ = new std::list<PATypeHolder>())->push_back(Type::VoidTy);
1328 $$ = new std::list<PATypeHolder>();
1332 // ConstVal - The various declarations that go into the constant pool. This
1333 // production is used ONLY to represent constants that show up AFTER a 'const',
1334 // 'constant' or 'global' token at global scope. Constants that can be inlined
1335 // into other expressions (such as integers and constexprs) are handled by the
1336 // ResolvedVal, ValueRef and ConstValueRef productions.
1338 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1339 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1341 GEN_ERROR("Cannot make array constant with type: '" +
1342 (*$1)->getDescription() + "'!");
1343 const Type *ETy = ATy->getElementType();
1344 int NumElements = ATy->getNumElements();
1346 // Verify that we have the correct size...
1347 if (NumElements != -1 && NumElements != (int)$3->size())
1348 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1349 utostr($3->size()) + " arguments, but has size of " +
1350 itostr(NumElements) + "!");
1352 // Verify all elements are correct type!
1353 for (unsigned i = 0; i < $3->size(); i++) {
1354 if (ETy != (*$3)[i]->getType())
1355 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1356 ETy->getDescription() +"' as required!\nIt is of type '"+
1357 (*$3)[i]->getType()->getDescription() + "'.");
1360 $$ = ConstantArray::get(ATy, *$3);
1361 delete $1; delete $3;
1365 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1367 GEN_ERROR("Cannot make array constant with type: '" +
1368 (*$1)->getDescription() + "'!");
1370 int NumElements = ATy->getNumElements();
1371 if (NumElements != -1 && NumElements != 0)
1372 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1373 " arguments, but has size of " + itostr(NumElements) +"!");
1374 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1378 | Types 'c' STRINGCONSTANT {
1379 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1381 GEN_ERROR("Cannot make array constant with type: '" +
1382 (*$1)->getDescription() + "'!");
1384 int NumElements = ATy->getNumElements();
1385 const Type *ETy = ATy->getElementType();
1386 char *EndStr = UnEscapeLexed($3, true);
1387 if (NumElements != -1 && NumElements != (EndStr-$3))
1388 GEN_ERROR("Can't build string constant of size " +
1389 itostr((int)(EndStr-$3)) +
1390 " when array has size " + itostr(NumElements) + "!");
1391 std::vector<Constant*> Vals;
1392 if (ETy == Type::SByteTy) {
1393 for (signed char *C = (signed char *)$3; C != (signed char *)EndStr; ++C)
1394 Vals.push_back(ConstantSInt::get(ETy, *C));
1395 } else if (ETy == Type::UByteTy) {
1396 for (unsigned char *C = (unsigned char *)$3;
1397 C != (unsigned char*)EndStr; ++C)
1398 Vals.push_back(ConstantUInt::get(ETy, *C));
1401 GEN_ERROR("Cannot build string arrays of non byte sized elements!");
1404 $$ = ConstantArray::get(ATy, Vals);
1408 | Types '<' ConstVector '>' { // Nonempty unsized arr
1409 const PackedType *PTy = dyn_cast<PackedType>($1->get());
1411 GEN_ERROR("Cannot make packed constant with type: '" +
1412 (*$1)->getDescription() + "'!");
1413 const Type *ETy = PTy->getElementType();
1414 int NumElements = PTy->getNumElements();
1416 // Verify that we have the correct size...
1417 if (NumElements != -1 && NumElements != (int)$3->size())
1418 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1419 utostr($3->size()) + " arguments, but has size of " +
1420 itostr(NumElements) + "!");
1422 // Verify all elements are correct type!
1423 for (unsigned i = 0; i < $3->size(); i++) {
1424 if (ETy != (*$3)[i]->getType())
1425 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1426 ETy->getDescription() +"' as required!\nIt is of type '"+
1427 (*$3)[i]->getType()->getDescription() + "'.");
1430 $$ = ConstantPacked::get(PTy, *$3);
1431 delete $1; delete $3;
1434 | Types '{' ConstVector '}' {
1435 const StructType *STy = dyn_cast<StructType>($1->get());
1437 GEN_ERROR("Cannot make struct constant with type: '" +
1438 (*$1)->getDescription() + "'!");
1440 if ($3->size() != STy->getNumContainedTypes())
1441 GEN_ERROR("Illegal number of initializers for structure type!");
1443 // Check to ensure that constants are compatible with the type initializer!
1444 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1445 if ((*$3)[i]->getType() != STy->getElementType(i))
1446 GEN_ERROR("Expected type '" +
1447 STy->getElementType(i)->getDescription() +
1448 "' for element #" + utostr(i) +
1449 " of structure initializer!");
1451 $$ = ConstantStruct::get(STy, *$3);
1452 delete $1; delete $3;
1456 const StructType *STy = dyn_cast<StructType>($1->get());
1458 GEN_ERROR("Cannot make struct constant with type: '" +
1459 (*$1)->getDescription() + "'!");
1461 if (STy->getNumContainedTypes() != 0)
1462 GEN_ERROR("Illegal number of initializers for structure type!");
1464 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1469 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1471 GEN_ERROR("Cannot make null pointer constant with type: '" +
1472 (*$1)->getDescription() + "'!");
1474 $$ = ConstantPointerNull::get(PTy);
1479 $$ = UndefValue::get($1->get());
1483 | Types SymbolicValueRef {
1484 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1486 GEN_ERROR("Global const reference must be a pointer type!");
1488 // ConstExprs can exist in the body of a function, thus creating
1489 // GlobalValues whenever they refer to a variable. Because we are in
1490 // the context of a function, getValNonImprovising will search the functions
1491 // symbol table instead of the module symbol table for the global symbol,
1492 // which throws things all off. To get around this, we just tell
1493 // getValNonImprovising that we are at global scope here.
1495 Function *SavedCurFn = CurFun.CurrentFunction;
1496 CurFun.CurrentFunction = 0;
1498 Value *V = getValNonImprovising(Ty, $2);
1501 CurFun.CurrentFunction = SavedCurFn;
1503 // If this is an initializer for a constant pointer, which is referencing a
1504 // (currently) undefined variable, create a stub now that shall be replaced
1505 // in the future with the right type of variable.
1508 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1509 const PointerType *PT = cast<PointerType>(Ty);
1511 // First check to see if the forward references value is already created!
1512 PerModuleInfo::GlobalRefsType::iterator I =
1513 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1515 if (I != CurModule.GlobalRefs.end()) {
1516 V = I->second; // Placeholder already exists, use it...
1520 if ($2.Type == ValID::NameVal) Name = $2.Name;
1522 // Create the forward referenced global.
1524 if (const FunctionType *FTy =
1525 dyn_cast<FunctionType>(PT->getElementType())) {
1526 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1527 CurModule.CurrentModule);
1529 GV = new GlobalVariable(PT->getElementType(), false,
1530 GlobalValue::ExternalLinkage, 0,
1531 Name, CurModule.CurrentModule);
1534 // Keep track of the fact that we have a forward ref to recycle it
1535 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1540 $$ = cast<GlobalValue>(V);
1541 delete $1; // Free the type handle
1545 if ($1->get() != $2->getType())
1546 GEN_ERROR("Mismatched types for constant expression!");
1551 | Types ZEROINITIALIZER {
1552 const Type *Ty = $1->get();
1553 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1554 GEN_ERROR("Cannot create a null initialized value of this type!");
1555 $$ = Constant::getNullValue(Ty);
1560 ConstVal : SIntType EINT64VAL { // integral constants
1561 if (!ConstantSInt::isValueValidForType($1, $2))
1562 GEN_ERROR("Constant value doesn't fit in type!");
1563 $$ = ConstantSInt::get($1, $2);
1566 | UIntType EUINT64VAL { // integral constants
1567 if (!ConstantUInt::isValueValidForType($1, $2))
1568 GEN_ERROR("Constant value doesn't fit in type!");
1569 $$ = ConstantUInt::get($1, $2);
1572 | BOOL TRUETOK { // Boolean constants
1573 $$ = ConstantBool::getTrue();
1576 | BOOL FALSETOK { // Boolean constants
1577 $$ = ConstantBool::getFalse();
1580 | FPType FPVAL { // Float & Double constants
1581 if (!ConstantFP::isValueValidForType($1, $2))
1582 GEN_ERROR("Floating point constant invalid for type!!");
1583 $$ = ConstantFP::get($1, $2);
1588 ConstExpr: CAST '(' ConstVal TO Types ')' {
1589 if (!$3->getType()->isFirstClassType())
1590 GEN_ERROR("cast constant expression from a non-primitive type: '" +
1591 $3->getType()->getDescription() + "'!");
1592 if (!$5->get()->isFirstClassType())
1593 GEN_ERROR("cast constant expression to a non-primitive type: '" +
1594 $5->get()->getDescription() + "'!");
1595 $$ = ConstantExpr::getCast($3, $5->get());
1599 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1600 if (!isa<PointerType>($3->getType()))
1601 GEN_ERROR("GetElementPtr requires a pointer operand!");
1603 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
1604 // indices to uint struct indices for compatibility.
1605 generic_gep_type_iterator<std::vector<Value*>::iterator>
1606 GTI = gep_type_begin($3->getType(), $4->begin(), $4->end()),
1607 GTE = gep_type_end($3->getType(), $4->begin(), $4->end());
1608 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
1609 if (isa<StructType>(*GTI)) // Only change struct indices
1610 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
1611 if (CUI->getType() == Type::UByteTy)
1612 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
1615 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1617 GEN_ERROR("Index list invalid for constant getelementptr!");
1619 std::vector<Constant*> IdxVec;
1620 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1621 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1622 IdxVec.push_back(C);
1624 GEN_ERROR("Indices to constant getelementptr must be constants!");
1628 $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1631 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1632 if ($3->getType() != Type::BoolTy)
1633 GEN_ERROR("Select condition must be of boolean type!");
1634 if ($5->getType() != $7->getType())
1635 GEN_ERROR("Select operand types must match!");
1636 $$ = ConstantExpr::getSelect($3, $5, $7);
1639 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1640 if ($3->getType() != $5->getType())
1641 GEN_ERROR("Binary operator types must match!");
1642 // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
1643 // To retain backward compatibility with these early compilers, we emit a
1644 // cast to the appropriate integer type automatically if we are in the
1645 // broken case. See PR424 for more information.
1646 if (!isa<PointerType>($3->getType())) {
1647 $$ = ConstantExpr::get($1, $3, $5);
1649 const Type *IntPtrTy = 0;
1650 switch (CurModule.CurrentModule->getPointerSize()) {
1651 case Module::Pointer32: IntPtrTy = Type::IntTy; break;
1652 case Module::Pointer64: IntPtrTy = Type::LongTy; break;
1653 default: GEN_ERROR("invalid pointer binary constant expr!");
1655 $$ = ConstantExpr::get($1, ConstantExpr::getCast($3, IntPtrTy),
1656 ConstantExpr::getCast($5, IntPtrTy));
1657 $$ = ConstantExpr::getCast($$, $3->getType());
1661 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1662 if ($3->getType() != $5->getType())
1663 GEN_ERROR("Logical operator types must match!");
1664 if (!$3->getType()->isIntegral()) {
1665 if (!isa<PackedType>($3->getType()) ||
1666 !cast<PackedType>($3->getType())->getElementType()->isIntegral())
1667 GEN_ERROR("Logical operator requires integral operands!");
1669 $$ = ConstantExpr::get($1, $3, $5);
1672 | SetCondOps '(' ConstVal ',' ConstVal ')' {
1673 if ($3->getType() != $5->getType())
1674 GEN_ERROR("setcc operand types must match!");
1675 $$ = ConstantExpr::get($1, $3, $5);
1678 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1679 if ($5->getType() != Type::UByteTy)
1680 GEN_ERROR("Shift count for shift constant must be unsigned byte!");
1681 if (!$3->getType()->isInteger())
1682 GEN_ERROR("Shift constant expression requires integer operand!");
1683 $$ = ConstantExpr::get($1, $3, $5);
1686 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1687 if (!ExtractElementInst::isValidOperands($3, $5))
1688 GEN_ERROR("Invalid extractelement operands!");
1689 $$ = ConstantExpr::getExtractElement($3, $5);
1692 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1693 if (!InsertElementInst::isValidOperands($3, $5, $7))
1694 GEN_ERROR("Invalid insertelement operands!");
1695 $$ = ConstantExpr::getInsertElement($3, $5, $7);
1698 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1699 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1700 GEN_ERROR("Invalid shufflevector operands!");
1701 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1706 // ConstVector - A list of comma separated constants.
1707 ConstVector : ConstVector ',' ConstVal {
1708 ($$ = $1)->push_back($3);
1712 $$ = new std::vector<Constant*>();
1718 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1719 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1722 //===----------------------------------------------------------------------===//
1723 // Rules to match Modules
1724 //===----------------------------------------------------------------------===//
1726 // Module rule: Capture the result of parsing the whole file into a result
1729 Module : FunctionList {
1730 $$ = ParserResult = $1;
1731 CurModule.ModuleDone();
1735 // FunctionList - A list of functions, preceeded by a constant pool.
1737 FunctionList : FunctionList Function {
1739 CurFun.FunctionDone();
1742 | FunctionList FunctionProto {
1746 | FunctionList MODULE ASM_TOK AsmBlock {
1750 | FunctionList IMPLEMENTATION {
1755 $$ = CurModule.CurrentModule;
1756 // Emit an error if there are any unresolved types left.
1757 if (!CurModule.LateResolveTypes.empty()) {
1758 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
1759 if (DID.Type == ValID::NameVal) {
1760 GEN_ERROR("Reference to an undefined type: '"+DID.getName() + "'");
1762 GEN_ERROR("Reference to an undefined type: #" + itostr(DID.Num));
1768 // ConstPool - Constants with optional names assigned to them.
1769 ConstPool : ConstPool OptAssign TYPE TypesV {
1770 // Eagerly resolve types. This is not an optimization, this is a
1771 // requirement that is due to the fact that we could have this:
1773 // %list = type { %list * }
1774 // %list = type { %list * } ; repeated type decl
1776 // If types are not resolved eagerly, then the two types will not be
1777 // determined to be the same type!
1779 ResolveTypeTo($2, *$4);
1781 if (!setTypeName(*$4, $2) && !$2) {
1783 // If this is a named type that is not a redefinition, add it to the slot
1785 CurModule.Types.push_back(*$4);
1791 | ConstPool FunctionProto { // Function prototypes can be in const pool
1794 | ConstPool MODULE ASM_TOK AsmBlock { // Asm blocks can be in the const pool
1797 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
1799 GEN_ERROR("Global value initializer is not a constant!");
1800 CurGV = ParseGlobalVariable($2, $3, $4, $5->getType(), $5);
1802 } GlobalVarAttributes {
1805 | ConstPool OptAssign EXTERNAL GlobalType Types {
1806 CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, *$5, 0);
1809 } GlobalVarAttributes {
1813 | ConstPool OptAssign DLLIMPORT GlobalType Types {
1814 CurGV = ParseGlobalVariable($2, GlobalValue::DLLImportLinkage, $4, *$5, 0);
1817 } GlobalVarAttributes {
1821 | ConstPool OptAssign EXTERN_WEAK GlobalType Types {
1823 ParseGlobalVariable($2, GlobalValue::ExternalWeakLinkage, $4, *$5, 0);
1826 } GlobalVarAttributes {
1830 | ConstPool TARGET TargetDefinition {
1833 | ConstPool DEPLIBS '=' LibrariesDefinition {
1836 | /* empty: end of list */ {
1840 AsmBlock : STRINGCONSTANT {
1841 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
1842 char *EndStr = UnEscapeLexed($1, true);
1843 std::string NewAsm($1, EndStr);
1846 if (AsmSoFar.empty())
1847 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
1849 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
1853 BigOrLittle : BIG { $$ = Module::BigEndian; };
1854 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1856 TargetDefinition : ENDIAN '=' BigOrLittle {
1857 CurModule.CurrentModule->setEndianness($3);
1860 | POINTERSIZE '=' EUINT64VAL {
1862 CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1864 CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1866 GEN_ERROR("Invalid pointer size: '" + utostr($3) + "'!");
1869 | TRIPLE '=' STRINGCONSTANT {
1870 CurModule.CurrentModule->setTargetTriple($3);
1875 LibrariesDefinition : '[' LibList ']';
1877 LibList : LibList ',' STRINGCONSTANT {
1878 CurModule.CurrentModule->addLibrary($3);
1883 CurModule.CurrentModule->addLibrary($1);
1887 | /* empty: end of list */ {
1892 //===----------------------------------------------------------------------===//
1893 // Rules to match Function Headers
1894 //===----------------------------------------------------------------------===//
1896 Name : VAR_ID | STRINGCONSTANT;
1897 OptName : Name | /*empty*/ { $$ = 0; };
1899 ArgVal : Types OptName {
1900 if (*$1 == Type::VoidTy)
1901 GEN_ERROR("void typed arguments are invalid!");
1902 $$ = new std::pair<PATypeHolder*, char*>($1, $2);
1906 ArgListH : ArgListH ',' ArgVal {
1913 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1919 ArgList : ArgListH {
1923 | ArgListH ',' DOTDOTDOT {
1925 $$->push_back(std::pair<PATypeHolder*,
1926 char*>(new PATypeHolder(Type::VoidTy), 0));
1930 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1931 $$->push_back(std::make_pair(new PATypeHolder(Type::VoidTy), (char*)0));
1939 FunctionHeaderH : OptCallingConv TypesV Name '(' ArgList ')'
1940 OptSection OptAlign {
1942 std::string FunctionName($3);
1943 free($3); // Free strdup'd memory!
1945 if (!(*$2)->isFirstClassType() && *$2 != Type::VoidTy)
1946 GEN_ERROR("LLVM functions cannot return aggregate types!");
1948 std::vector<const Type*> ParamTypeList;
1949 if ($5) { // If there are arguments...
1950 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
1951 I != $5->end(); ++I)
1952 ParamTypeList.push_back(I->first->get());
1955 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1956 if (isVarArg) ParamTypeList.pop_back();
1958 const FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
1959 const PointerType *PFT = PointerType::get(FT);
1963 if (!FunctionName.empty()) {
1964 ID = ValID::create((char*)FunctionName.c_str());
1966 ID = ValID::create((int)CurModule.Values[PFT].size());
1970 // See if this function was forward referenced. If so, recycle the object.
1971 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
1972 // Move the function to the end of the list, from whereever it was
1973 // previously inserted.
1974 Fn = cast<Function>(FWRef);
1975 CurModule.CurrentModule->getFunctionList().remove(Fn);
1976 CurModule.CurrentModule->getFunctionList().push_back(Fn);
1977 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
1978 (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
1979 // If this is the case, either we need to be a forward decl, or it needs
1981 if (!CurFun.isDeclare && !Fn->isExternal())
1982 GEN_ERROR("Redefinition of function '" + FunctionName + "'!");
1984 // Make sure to strip off any argument names so we can't get conflicts.
1985 if (Fn->isExternal())
1986 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
1989 } else { // Not already defined?
1990 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
1991 CurModule.CurrentModule);
1993 InsertValue(Fn, CurModule.Values);
1996 CurFun.FunctionStart(Fn);
1998 if (CurFun.isDeclare) {
1999 // If we have declaration, always overwrite linkage. This will allow us to
2000 // correctly handle cases, when pointer to function is passed as argument to
2001 // another function.
2002 Fn->setLinkage(CurFun.Linkage);
2004 Fn->setCallingConv($1);
2005 Fn->setAlignment($8);
2011 // Add all of the arguments we parsed to the function...
2012 if ($5) { // Is null if empty...
2013 if (isVarArg) { // Nuke the last entry
2014 assert($5->back().first->get() == Type::VoidTy && $5->back().second == 0&&
2015 "Not a varargs marker!");
2016 delete $5->back().first;
2017 $5->pop_back(); // Delete the last entry
2019 Function::arg_iterator ArgIt = Fn->arg_begin();
2020 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
2021 I != $5->end(); ++I, ++ArgIt) {
2022 delete I->first; // Delete the typeholder...
2024 setValueName(ArgIt, I->second); // Insert arg into symtab...
2029 delete $5; // We're now done with the argument list
2034 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2036 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
2037 $$ = CurFun.CurrentFunction;
2039 // Make sure that we keep track of the linkage type even if there was a
2040 // previous "declare".
2044 END : ENDTOK | '}'; // Allow end of '}' to end a function
2046 Function : BasicBlockList END {
2051 FnDeclareLinkage: /*default*/ |
2052 DLLIMPORT { CurFun.Linkage = GlobalValue::DLLImportLinkage } |
2053 EXTERN_WEAK { CurFun.Linkage = GlobalValue::DLLImportLinkage };
2055 FunctionProto : DECLARE { CurFun.isDeclare = true; } FnDeclareLinkage FunctionHeaderH {
2056 $$ = CurFun.CurrentFunction;
2057 CurFun.FunctionDone();
2061 //===----------------------------------------------------------------------===//
2062 // Rules to match Basic Blocks
2063 //===----------------------------------------------------------------------===//
2065 OptSideEffect : /* empty */ {
2074 ConstValueRef : ESINT64VAL { // A reference to a direct constant
2075 $$ = ValID::create($1);
2079 $$ = ValID::create($1);
2082 | FPVAL { // Perhaps it's an FP constant?
2083 $$ = ValID::create($1);
2087 $$ = ValID::create(ConstantBool::getTrue());
2091 $$ = ValID::create(ConstantBool::getFalse());
2095 $$ = ValID::createNull();
2099 $$ = ValID::createUndef();
2102 | ZEROINITIALIZER { // A vector zero constant.
2103 $$ = ValID::createZeroInit();
2106 | '<' ConstVector '>' { // Nonempty unsized packed vector
2107 const Type *ETy = (*$2)[0]->getType();
2108 int NumElements = $2->size();
2110 PackedType* pt = PackedType::get(ETy, NumElements);
2111 PATypeHolder* PTy = new PATypeHolder(
2119 // Verify all elements are correct type!
2120 for (unsigned i = 0; i < $2->size(); i++) {
2121 if (ETy != (*$2)[i]->getType())
2122 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2123 ETy->getDescription() +"' as required!\nIt is of type '" +
2124 (*$2)[i]->getType()->getDescription() + "'.");
2127 $$ = ValID::create(ConstantPacked::get(pt, *$2));
2128 delete PTy; delete $2;
2132 $$ = ValID::create($1);
2135 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2136 char *End = UnEscapeLexed($3, true);
2137 std::string AsmStr = std::string($3, End);
2138 End = UnEscapeLexed($5, true);
2139 std::string Constraints = std::string($5, End);
2140 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2146 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2149 SymbolicValueRef : INTVAL { // Is it an integer reference...?
2150 $$ = ValID::create($1);
2153 | Name { // Is it a named reference...?
2154 $$ = ValID::create($1);
2158 // ValueRef - A reference to a definition... either constant or symbolic
2159 ValueRef : SymbolicValueRef | ConstValueRef;
2162 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2163 // type immediately preceeds the value reference, and allows complex constant
2164 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2165 ResolvedVal : Types ValueRef {
2166 $$ = getVal(*$1, $2); delete $1;
2170 BasicBlockList : BasicBlockList BasicBlock {
2174 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2180 // Basic blocks are terminated by branching instructions:
2181 // br, br/cc, switch, ret
2183 BasicBlock : InstructionList OptAssign BBTerminatorInst {
2184 setValueName($3, $2);
2188 $1->getInstList().push_back($3);
2194 InstructionList : InstructionList Inst {
2195 $1->getInstList().push_back($2);
2200 $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
2203 // Make sure to move the basic block to the correct location in the
2204 // function, instead of leaving it inserted wherever it was first
2206 Function::BasicBlockListType &BBL =
2207 CurFun.CurrentFunction->getBasicBlockList();
2208 BBL.splice(BBL.end(), BBL, $$);
2212 $$ = CurBB = getBBVal(ValID::create($1), true);
2215 // Make sure to move the basic block to the correct location in the
2216 // function, instead of leaving it inserted wherever it was first
2218 Function::BasicBlockListType &BBL =
2219 CurFun.CurrentFunction->getBasicBlockList();
2220 BBL.splice(BBL.end(), BBL, $$);
2224 BBTerminatorInst : RET ResolvedVal { // Return with a result...
2225 $$ = new ReturnInst($2);
2228 | RET VOID { // Return with no result...
2229 $$ = new ReturnInst();
2232 | BR LABEL ValueRef { // Unconditional Branch...
2233 BasicBlock* tmpBB = getBBVal($3);
2235 $$ = new BranchInst(tmpBB);
2236 } // Conditional Branch...
2237 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2238 BasicBlock* tmpBBA = getBBVal($6);
2240 BasicBlock* tmpBBB = getBBVal($9);
2242 Value* tmpVal = getVal(Type::BoolTy, $3);
2244 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2246 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2247 Value* tmpVal = getVal($2, $3);
2249 BasicBlock* tmpBB = getBBVal($6);
2251 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2254 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2256 for (; I != E; ++I) {
2257 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2258 S->addCase(CI, I->second);
2260 GEN_ERROR("Switch case is constant, but not a simple integer!");
2265 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2266 Value* tmpVal = getVal($2, $3);
2268 BasicBlock* tmpBB = getBBVal($6);
2270 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2274 | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
2275 TO LABEL ValueRef UNWIND LABEL ValueRef {
2276 const PointerType *PFTy;
2277 const FunctionType *Ty;
2279 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2280 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2281 // Pull out the types of all of the arguments...
2282 std::vector<const Type*> ParamTypes;
2284 for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
2286 ParamTypes.push_back((*I)->getType());
2289 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2290 if (isVarArg) ParamTypes.pop_back();
2292 Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
2293 PFTy = PointerType::get(Ty);
2296 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2298 BasicBlock *Normal = getBBVal($10);
2300 BasicBlock *Except = getBBVal($13);
2303 // Create the call node...
2304 if (!$6) { // Has no arguments?
2305 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
2306 } else { // Has arguments?
2307 // Loop through FunctionType's arguments and ensure they are specified
2310 FunctionType::param_iterator I = Ty->param_begin();
2311 FunctionType::param_iterator E = Ty->param_end();
2312 std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
2314 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2315 if ((*ArgI)->getType() != *I)
2316 GEN_ERROR("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2317 (*I)->getDescription() + "'!");
2319 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2320 GEN_ERROR("Invalid number of parameters detected!");
2322 $$ = new InvokeInst(V, Normal, Except, *$6);
2324 cast<InvokeInst>($$)->setCallingConv($2);
2331 $$ = new UnwindInst();
2335 $$ = new UnreachableInst();
2341 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2343 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
2346 GEN_ERROR("May only switch on a constant pool value!");
2348 BasicBlock* tmpBB = getBBVal($6);
2350 $$->push_back(std::make_pair(V, tmpBB));
2352 | IntType ConstValueRef ',' LABEL ValueRef {
2353 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2354 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
2358 GEN_ERROR("May only switch on a constant pool value!");
2360 BasicBlock* tmpBB = getBBVal($5);
2362 $$->push_back(std::make_pair(V, tmpBB));
2365 Inst : OptAssign InstVal {
2366 // Is this definition named?? if so, assign the name...
2367 setValueName($2, $1);
2374 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2375 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2376 Value* tmpVal = getVal(*$1, $3);
2378 BasicBlock* tmpBB = getBBVal($5);
2380 $$->push_back(std::make_pair(tmpVal, tmpBB));
2383 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2385 Value* tmpVal = getVal($1->front().first->getType(), $4);
2387 BasicBlock* tmpBB = getBBVal($6);
2389 $1->push_back(std::make_pair(tmpVal, tmpBB));
2393 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
2394 $$ = new std::vector<Value*>();
2397 | ValueRefList ',' ResolvedVal {
2403 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
2404 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
2406 OptTailCall : TAIL CALL {
2415 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2416 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
2417 !isa<PackedType>((*$2).get()))
2419 "Arithmetic operator requires integer, FP, or packed operands!");
2420 if (isa<PackedType>((*$2).get()) && $1 == Instruction::Rem)
2421 GEN_ERROR("Rem not supported on packed types!");
2422 Value* val1 = getVal(*$2, $3);
2424 Value* val2 = getVal(*$2, $5);
2426 $$ = BinaryOperator::create($1, val1, val2);
2428 GEN_ERROR("binary operator returned null!");
2431 | LogicalOps Types ValueRef ',' ValueRef {
2432 if (!(*$2)->isIntegral()) {
2433 if (!isa<PackedType>($2->get()) ||
2434 !cast<PackedType>($2->get())->getElementType()->isIntegral())
2435 GEN_ERROR("Logical operator requires integral operands!");
2437 Value* tmpVal1 = getVal(*$2, $3);
2439 Value* tmpVal2 = getVal(*$2, $5);
2441 $$ = BinaryOperator::create($1, tmpVal1, tmpVal2);
2443 GEN_ERROR("binary operator returned null!");
2446 | SetCondOps Types ValueRef ',' ValueRef {
2447 if(isa<PackedType>((*$2).get())) {
2449 "PackedTypes currently not supported in setcc instructions!");
2451 Value* tmpVal1 = getVal(*$2, $3);
2453 Value* tmpVal2 = getVal(*$2, $5);
2455 $$ = new SetCondInst($1, tmpVal1, tmpVal2);
2457 GEN_ERROR("binary operator returned null!");
2461 std::cerr << "WARNING: Use of eliminated 'not' instruction:"
2462 << " Replacing with 'xor'.\n";
2464 Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
2466 GEN_ERROR("Expected integral type for not instruction!");
2468 $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
2470 GEN_ERROR("Could not create a xor instruction!");
2473 | ShiftOps ResolvedVal ',' ResolvedVal {
2474 if ($4->getType() != Type::UByteTy)
2475 GEN_ERROR("Shift amount must be ubyte!");
2476 if (!$2->getType()->isInteger())
2477 GEN_ERROR("Shift constant expression requires integer operand!");
2478 $$ = new ShiftInst($1, $2, $4);
2481 | CAST ResolvedVal TO Types {
2482 if (!$4->get()->isFirstClassType())
2483 GEN_ERROR("cast instruction to a non-primitive type: '" +
2484 $4->get()->getDescription() + "'!");
2485 $$ = new CastInst($2, *$4);
2489 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2490 if ($2->getType() != Type::BoolTy)
2491 GEN_ERROR("select condition must be boolean!");
2492 if ($4->getType() != $6->getType())
2493 GEN_ERROR("select value types should match!");
2494 $$ = new SelectInst($2, $4, $6);
2497 | VAARG ResolvedVal ',' Types {
2499 $$ = new VAArgInst($2, *$4);
2503 | VAARG_old ResolvedVal ',' Types {
2504 ObsoleteVarArgs = true;
2505 const Type* ArgTy = $2->getType();
2506 Function* NF = CurModule.CurrentModule->
2507 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0);
2510 //foo = alloca 1 of t
2514 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
2515 CurBB->getInstList().push_back(foo);
2516 CallInst* bar = new CallInst(NF, $2);
2517 CurBB->getInstList().push_back(bar);
2518 CurBB->getInstList().push_back(new StoreInst(bar, foo));
2519 $$ = new VAArgInst(foo, *$4);
2523 | VANEXT_old ResolvedVal ',' Types {
2524 ObsoleteVarArgs = true;
2525 const Type* ArgTy = $2->getType();
2526 Function* NF = CurModule.CurrentModule->
2527 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0);
2529 //b = vanext a, t ->
2530 //foo = alloca 1 of t
2533 //tmp = vaarg foo, t
2535 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
2536 CurBB->getInstList().push_back(foo);
2537 CallInst* bar = new CallInst(NF, $2);
2538 CurBB->getInstList().push_back(bar);
2539 CurBB->getInstList().push_back(new StoreInst(bar, foo));
2540 Instruction* tmp = new VAArgInst(foo, *$4);
2541 CurBB->getInstList().push_back(tmp);
2542 $$ = new LoadInst(foo);
2546 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2547 if (!ExtractElementInst::isValidOperands($2, $4))
2548 GEN_ERROR("Invalid extractelement operands!");
2549 $$ = new ExtractElementInst($2, $4);
2552 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2553 if (!InsertElementInst::isValidOperands($2, $4, $6))
2554 GEN_ERROR("Invalid insertelement operands!");
2555 $$ = new InsertElementInst($2, $4, $6);
2558 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2559 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
2560 GEN_ERROR("Invalid shufflevector operands!");
2561 $$ = new ShuffleVectorInst($2, $4, $6);
2565 const Type *Ty = $2->front().first->getType();
2566 if (!Ty->isFirstClassType())
2567 GEN_ERROR("PHI node operands must be of first class type!");
2568 $$ = new PHINode(Ty);
2569 ((PHINode*)$$)->reserveOperandSpace($2->size());
2570 while ($2->begin() != $2->end()) {
2571 if ($2->front().first->getType() != Ty)
2572 GEN_ERROR("All elements of a PHI node must be of the same type!");
2573 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2576 delete $2; // Free the list...
2579 | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')' {
2580 const PointerType *PFTy;
2581 const FunctionType *Ty;
2583 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2584 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2585 // Pull out the types of all of the arguments...
2586 std::vector<const Type*> ParamTypes;
2588 for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
2590 ParamTypes.push_back((*I)->getType());
2593 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2594 if (isVarArg) ParamTypes.pop_back();
2596 if (!(*$3)->isFirstClassType() && *$3 != Type::VoidTy)
2597 GEN_ERROR("LLVM functions cannot return aggregate types!");
2599 Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
2600 PFTy = PointerType::get(Ty);
2603 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2606 // Create the call node...
2607 if (!$6) { // Has no arguments?
2608 // Make sure no arguments is a good thing!
2609 if (Ty->getNumParams() != 0)
2610 GEN_ERROR("No arguments passed to a function that "
2611 "expects arguments!");
2613 $$ = new CallInst(V, std::vector<Value*>());
2614 } else { // Has arguments?
2615 // Loop through FunctionType's arguments and ensure they are specified
2618 FunctionType::param_iterator I = Ty->param_begin();
2619 FunctionType::param_iterator E = Ty->param_end();
2620 std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
2622 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2623 if ((*ArgI)->getType() != *I)
2624 GEN_ERROR("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2625 (*I)->getDescription() + "'!");
2627 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2628 GEN_ERROR("Invalid number of parameters detected!");
2630 $$ = new CallInst(V, *$6);
2632 cast<CallInst>($$)->setTailCall($1);
2633 cast<CallInst>($$)->setCallingConv($2);
2644 // IndexList - List of indices for GEP based instructions...
2645 IndexList : ',' ValueRefList {
2649 $$ = new std::vector<Value*>();
2653 OptVolatile : VOLATILE {
2664 MemoryInst : MALLOC Types OptCAlign {
2665 $$ = new MallocInst(*$2, 0, $3);
2669 | MALLOC Types ',' UINT ValueRef OptCAlign {
2670 Value* tmpVal = getVal($4, $5);
2672 $$ = new MallocInst(*$2, tmpVal, $6);
2675 | ALLOCA Types OptCAlign {
2676 $$ = new AllocaInst(*$2, 0, $3);
2680 | ALLOCA Types ',' UINT ValueRef OptCAlign {
2681 Value* tmpVal = getVal($4, $5);
2683 $$ = new AllocaInst(*$2, tmpVal, $6);
2686 | FREE ResolvedVal {
2687 if (!isa<PointerType>($2->getType()))
2688 GEN_ERROR("Trying to free nonpointer type " +
2689 $2->getType()->getDescription() + "!");
2690 $$ = new FreeInst($2);
2694 | OptVolatile LOAD Types ValueRef {
2695 if (!isa<PointerType>($3->get()))
2696 GEN_ERROR("Can't load from nonpointer type: " +
2697 (*$3)->getDescription());
2698 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
2699 GEN_ERROR("Can't load from pointer of non-first-class type: " +
2700 (*$3)->getDescription());
2701 Value* tmpVal = getVal(*$3, $4);
2703 $$ = new LoadInst(tmpVal, "", $1);
2706 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2707 const PointerType *PT = dyn_cast<PointerType>($5->get());
2709 GEN_ERROR("Can't store to a nonpointer type: " +
2710 (*$5)->getDescription());
2711 const Type *ElTy = PT->getElementType();
2712 if (ElTy != $3->getType())
2713 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
2714 "' into space of type '" + ElTy->getDescription() + "'!");
2716 Value* tmpVal = getVal(*$5, $6);
2718 $$ = new StoreInst($3, tmpVal, $1);
2721 | GETELEMENTPTR Types ValueRef IndexList {
2722 if (!isa<PointerType>($2->get()))
2723 GEN_ERROR("getelementptr insn requires pointer operand!");
2725 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
2726 // indices to uint struct indices for compatibility.
2727 generic_gep_type_iterator<std::vector<Value*>::iterator>
2728 GTI = gep_type_begin($2->get(), $4->begin(), $4->end()),
2729 GTE = gep_type_end($2->get(), $4->begin(), $4->end());
2730 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
2731 if (isa<StructType>(*GTI)) // Only change struct indices
2732 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
2733 if (CUI->getType() == Type::UByteTy)
2734 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
2736 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2737 GEN_ERROR("Invalid getelementptr indices for type '" +
2738 (*$2)->getDescription()+ "'!");
2739 Value* tmpVal = getVal(*$2, $3);
2741 $$ = new GetElementPtrInst(tmpVal, *$4);
2749 void llvm::GenerateError(const std::string &message, int LineNo) {
2750 if (LineNo == -1) LineNo = llvmAsmlineno;
2751 // TODO: column number in exception
2753 TheParseError->setError(CurFilename, message, LineNo);
2757 int yyerror(const char *ErrorMsg) {
2759 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2760 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2761 std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2762 if (yychar == YYEMPTY || yychar == 0)
2763 errMsg += "end-of-file.";
2765 errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2766 GenerateError(errMsg);