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 (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
311 GenerateError("Signed integral constant '" +
312 itostr(D.ConstPool64) + "' is invalid for type '" +
313 Ty->getDescription() + "'!");
316 return ConstantInt::get(Ty, D.ConstPool64);
318 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
319 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
320 if (!ConstantInt::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 ConstantInt::get(Ty, D.ConstPool64);
328 return ConstantInt::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);
816 /// This function is used to obtain the correct opcode for an instruction when
817 /// an obsolete opcode is encountered. The OI parameter (OpcodeInfo) has both
818 /// an opcode and an "obsolete" flag. These are generated by the lexer and
819 /// the "obsolete" member will be true when the lexer encounters the token for
820 /// an obsolete opcode. For example, "div" was replaced by [usf]div but we need
821 /// to maintain backwards compatibility for asm files that still have the "div"
822 /// instruction. This function handles converting div -> [usf]div appropriately.
823 /// @brief Convert obsolete opcodes to new values
825 sanitizeOpCode(OpcodeInfo<Instruction::BinaryOps> &OI, const PATypeHolder& PATy)
827 // If its not obsolete, don't do anything
831 // If its a packed type we want to use the element type
832 const Type* Ty = PATy;
833 if (const PackedType* PTy = dyn_cast<PackedType>(Ty))
834 Ty = PTy->getElementType();
836 // Depending on the opcode ..
839 GenerateError("Invalid obsolete opCode (check Lexer.l)");
841 case Instruction::UDiv:
842 // Handle cases where the opcode needs to change
843 if (Ty->isFloatingPoint())
844 OI.opcode = Instruction::FDiv;
845 else if (Ty->isSigned())
846 OI.opcode = Instruction::SDiv;
848 case Instruction::URem:
849 if (Ty->isFloatingPoint())
850 OI.opcode = Instruction::FRem;
851 else if (Ty->isSigned())
852 OI.opcode = Instruction::SRem;
855 // Its not obsolete any more, we fixed it.
859 // common code from the two 'RunVMAsmParser' functions
860 static Module* RunParser(Module * M) {
862 llvmAsmlineno = 1; // Reset the current line number...
863 ObsoleteVarArgs = false;
865 CurModule.CurrentModule = M;
867 // Check to make sure the parser succeeded
874 // Check to make sure that parsing produced a result
878 // Reset ParserResult variable while saving its value for the result.
879 Module *Result = ParserResult;
882 //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
885 if ((F = Result->getNamedFunction("llvm.va_start"))
886 && F->getFunctionType()->getNumParams() == 0)
887 ObsoleteVarArgs = true;
888 if((F = Result->getNamedFunction("llvm.va_copy"))
889 && F->getFunctionType()->getNumParams() == 1)
890 ObsoleteVarArgs = true;
893 if (ObsoleteVarArgs && NewVarArgs) {
895 "This file is corrupt: it uses both new and old style varargs");
899 if(ObsoleteVarArgs) {
900 if(Function* F = Result->getNamedFunction("llvm.va_start")) {
901 if (F->arg_size() != 0) {
902 GenerateError("Obsolete va_start takes 0 argument!");
908 //bar = alloca typeof(foo)
912 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
913 const Type* ArgTy = F->getFunctionType()->getReturnType();
914 const Type* ArgTyPtr = PointerType::get(ArgTy);
915 Function* NF = Result->getOrInsertFunction("llvm.va_start",
916 RetTy, ArgTyPtr, (Type *)0);
918 while (!F->use_empty()) {
919 CallInst* CI = cast<CallInst>(F->use_back());
920 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
921 new CallInst(NF, bar, "", CI);
922 Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
923 CI->replaceAllUsesWith(foo);
924 CI->getParent()->getInstList().erase(CI);
926 Result->getFunctionList().erase(F);
929 if(Function* F = Result->getNamedFunction("llvm.va_end")) {
930 if(F->arg_size() != 1) {
931 GenerateError("Obsolete va_end takes 1 argument!");
937 //bar = alloca 1 of typeof(foo)
939 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
940 const Type* ArgTy = F->getFunctionType()->getParamType(0);
941 const Type* ArgTyPtr = PointerType::get(ArgTy);
942 Function* NF = Result->getOrInsertFunction("llvm.va_end",
943 RetTy, ArgTyPtr, (Type *)0);
945 while (!F->use_empty()) {
946 CallInst* CI = cast<CallInst>(F->use_back());
947 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
948 new StoreInst(CI->getOperand(1), bar, CI);
949 new CallInst(NF, bar, "", CI);
950 CI->getParent()->getInstList().erase(CI);
952 Result->getFunctionList().erase(F);
955 if(Function* F = Result->getNamedFunction("llvm.va_copy")) {
956 if(F->arg_size() != 1) {
957 GenerateError("Obsolete va_copy takes 1 argument!");
962 //a = alloca 1 of typeof(foo)
963 //b = alloca 1 of typeof(foo)
968 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
969 const Type* ArgTy = F->getFunctionType()->getReturnType();
970 const Type* ArgTyPtr = PointerType::get(ArgTy);
971 Function* NF = Result->getOrInsertFunction("llvm.va_copy",
972 RetTy, ArgTyPtr, ArgTyPtr,
975 while (!F->use_empty()) {
976 CallInst* CI = cast<CallInst>(F->use_back());
977 AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
978 AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
979 new StoreInst(CI->getOperand(1), b, CI);
980 new CallInst(NF, a, b, "", CI);
981 Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
982 CI->replaceAllUsesWith(foo);
983 CI->getParent()->getInstList().erase(CI);
985 Result->getFunctionList().erase(F);
992 //===----------------------------------------------------------------------===//
993 // RunVMAsmParser - Define an interface to this parser
994 //===----------------------------------------------------------------------===//
996 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
999 CurFilename = Filename;
1000 return RunParser(new Module(CurFilename));
1003 Module *llvm::RunVMAsmParser(const char * AsmString, Module * M) {
1004 set_scan_string(AsmString);
1006 CurFilename = "from_memory";
1008 return RunParser(new Module (CurFilename));
1010 return RunParser(M);
1017 llvm::Module *ModuleVal;
1018 llvm::Function *FunctionVal;
1019 std::pair<llvm::PATypeHolder*, char*> *ArgVal;
1020 llvm::BasicBlock *BasicBlockVal;
1021 llvm::TerminatorInst *TermInstVal;
1022 llvm::Instruction *InstVal;
1023 llvm::Constant *ConstVal;
1025 const llvm::Type *PrimType;
1026 llvm::PATypeHolder *TypeVal;
1027 llvm::Value *ValueVal;
1029 std::vector<std::pair<llvm::PATypeHolder*,char*> > *ArgList;
1030 std::vector<llvm::Value*> *ValueList;
1031 std::list<llvm::PATypeHolder> *TypeList;
1032 // Represent the RHS of PHI node
1033 std::list<std::pair<llvm::Value*,
1034 llvm::BasicBlock*> > *PHIList;
1035 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
1036 std::vector<llvm::Constant*> *ConstVector;
1038 llvm::GlobalValue::LinkageTypes Linkage;
1046 char *StrVal; // This memory is strdup'd!
1047 llvm::ValID ValIDVal; // strdup'd memory maybe!
1049 BinaryOpInfo BinaryOpVal;
1050 TermOpInfo TermOpVal;
1052 OtherOpInfo OtherOpVal;
1053 llvm::Module::Endianness Endianness;
1056 %type <ModuleVal> Module FunctionList
1057 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1058 %type <BasicBlockVal> BasicBlock InstructionList
1059 %type <TermInstVal> BBTerminatorInst
1060 %type <InstVal> Inst InstVal MemoryInst
1061 %type <ConstVal> ConstVal ConstExpr
1062 %type <ConstVector> ConstVector
1063 %type <ArgList> ArgList ArgListH
1064 %type <ArgVal> ArgVal
1065 %type <PHIList> PHIList
1066 %type <ValueList> ValueRefList ValueRefListE // For call param lists
1067 %type <ValueList> IndexList // For GEP derived indices
1068 %type <TypeList> TypeListI ArgTypeListI
1069 %type <JumpTable> JumpTable
1070 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1071 %type <BoolVal> OptVolatile // 'volatile' or not
1072 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1073 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
1074 %type <Linkage> OptLinkage
1075 %type <Endianness> BigOrLittle
1077 // ValueRef - Unresolved reference to a definition or BB
1078 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1079 %type <ValueVal> ResolvedVal // <type> <valref> pair
1080 // Tokens and types for handling constant integer values
1082 // ESINT64VAL - A negative number within long long range
1083 %token <SInt64Val> ESINT64VAL
1085 // EUINT64VAL - A positive number within uns. long long range
1086 %token <UInt64Val> EUINT64VAL
1087 %type <SInt64Val> EINT64VAL
1089 %token <SIntVal> SINTVAL // Signed 32 bit ints...
1090 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
1091 %type <SIntVal> INTVAL
1092 %token <FPVal> FPVAL // Float or Double constant
1094 // Built in types...
1095 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
1096 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
1097 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
1098 %token <PrimType> FLOAT DOUBLE TYPE LABEL
1100 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
1101 %type <StrVal> Name OptName OptAssign
1102 %type <UIntVal> OptAlign OptCAlign
1103 %type <StrVal> OptSection SectionString
1105 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1106 %token DECLARE GLOBAL CONSTANT SECTION VOLATILE
1107 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
1108 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
1109 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
1110 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1111 %token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
1112 %token X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1114 %type <UIntVal> OptCallingConv
1116 // Basic Block Terminating Operators
1117 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1120 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
1121 %token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1122 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comparators
1124 // Memory Instructions
1125 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1128 %type <OtherOpVal> ShiftOps
1129 %token <OtherOpVal> PHI_TOK CAST SELECT SHL SHR VAARG
1130 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1131 %token VAARG_old VANEXT_old //OBSOLETE
1137 // Handle constant integer size restriction and conversion...
1141 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
1142 GEN_ERROR("Value too large for type!");
1148 EINT64VAL : ESINT64VAL; // These have same type and can't cause problems...
1149 EINT64VAL : EUINT64VAL {
1150 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
1151 GEN_ERROR("Value too large for type!");
1156 // Operations that are notably excluded from this list include:
1157 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1159 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1160 LogicalOps : AND | OR | XOR;
1161 SetCondOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
1163 ShiftOps : SHL | SHR;
1165 // These are some types that allow classification if we only want a particular
1166 // thing... for example, only a signed, unsigned, or integral type.
1167 SIntType : LONG | INT | SHORT | SBYTE;
1168 UIntType : ULONG | UINT | USHORT | UBYTE;
1169 IntType : SIntType | UIntType;
1170 FPType : FLOAT | DOUBLE;
1172 // OptAssign - Value producing statements have an optional assignment component
1173 OptAssign : Name '=' {
1182 OptLinkage : INTERNAL { $$ = GlobalValue::InternalLinkage; } |
1183 LINKONCE { $$ = GlobalValue::LinkOnceLinkage; } |
1184 WEAK { $$ = GlobalValue::WeakLinkage; } |
1185 APPENDING { $$ = GlobalValue::AppendingLinkage; } |
1186 DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; } |
1187 DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; } |
1188 EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; } |
1189 /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
1191 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1192 CCC_TOK { $$ = CallingConv::C; } |
1193 CSRETCC_TOK { $$ = CallingConv::CSRet; } |
1194 FASTCC_TOK { $$ = CallingConv::Fast; } |
1195 COLDCC_TOK { $$ = CallingConv::Cold; } |
1196 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1197 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1199 if ((unsigned)$2 != $2)
1200 GEN_ERROR("Calling conv too large!");
1205 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1206 // a comma before it.
1207 OptAlign : /*empty*/ { $$ = 0; } |
1210 if ($$ != 0 && !isPowerOf2_32($$))
1211 GEN_ERROR("Alignment must be a power of two!");
1214 OptCAlign : /*empty*/ { $$ = 0; } |
1215 ',' ALIGN EUINT64VAL {
1217 if ($$ != 0 && !isPowerOf2_32($$))
1218 GEN_ERROR("Alignment must be a power of two!");
1223 SectionString : SECTION STRINGCONSTANT {
1224 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1225 if ($2[i] == '"' || $2[i] == '\\')
1226 GEN_ERROR("Invalid character in section name!");
1231 OptSection : /*empty*/ { $$ = 0; } |
1232 SectionString { $$ = $1; };
1234 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1235 // is set to be the global we are processing.
1237 GlobalVarAttributes : /* empty */ {} |
1238 ',' GlobalVarAttribute GlobalVarAttributes {};
1239 GlobalVarAttribute : SectionString {
1240 CurGV->setSection($1);
1244 | ALIGN EUINT64VAL {
1245 if ($2 != 0 && !isPowerOf2_32($2))
1246 GEN_ERROR("Alignment must be a power of two!");
1247 CurGV->setAlignment($2);
1251 //===----------------------------------------------------------------------===//
1252 // Types includes all predefined types... except void, because it can only be
1253 // used in specific contexts (function returning void for example). To have
1254 // access to it, a user must explicitly use TypesV.
1257 // TypesV includes all of 'Types', but it also includes the void type.
1258 TypesV : Types | VOID { $$ = new PATypeHolder($1); };
1259 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
1262 if (!UpRefs.empty())
1263 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1269 // Derived types are added later...
1271 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT ;
1272 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL;
1274 $$ = new PATypeHolder(OpaqueType::get());
1278 $$ = new PATypeHolder($1);
1281 UpRTypes : SymbolicValueRef { // Named types are also simple types...
1282 const Type* tmp = getTypeVal($1);
1284 $$ = new PATypeHolder(tmp);
1287 // Include derived types in the Types production.
1289 UpRTypes : '\\' EUINT64VAL { // Type UpReference
1290 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range!");
1291 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1292 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1293 $$ = new PATypeHolder(OT);
1294 UR_OUT("New Upreference!\n");
1297 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
1298 std::vector<const Type*> Params;
1299 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1300 E = $3->end(); I != E; ++I)
1301 Params.push_back(*I);
1302 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1303 if (isVarArg) Params.pop_back();
1305 $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
1306 delete $3; // Delete the argument list
1307 delete $1; // Delete the return type handle
1310 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
1311 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1315 | '<' EUINT64VAL 'x' UpRTypes '>' { // Packed array type?
1316 const llvm::Type* ElemTy = $4->get();
1317 if ((unsigned)$2 != $2)
1318 GEN_ERROR("Unsigned result not equal to signed result");
1319 if (!ElemTy->isPrimitiveType())
1320 GEN_ERROR("Elemental type of a PackedType must be primitive");
1321 if (!isPowerOf2_32($2))
1322 GEN_ERROR("Vector length should be a power of 2!");
1323 $$ = new PATypeHolder(HandleUpRefs(PackedType::get(*$4, (unsigned)$2)));
1327 | '{' TypeListI '}' { // Structure type?
1328 std::vector<const Type*> Elements;
1329 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1330 E = $2->end(); I != E; ++I)
1331 Elements.push_back(*I);
1333 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1337 | '{' '}' { // Empty structure type?
1338 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1341 | UpRTypes '*' { // Pointer type?
1342 if (*$1 == Type::LabelTy)
1343 GEN_ERROR("Cannot form a pointer to a basic block");
1344 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1349 // TypeList - Used for struct declarations and as a basis for function type
1350 // declaration type lists
1352 TypeListI : UpRTypes {
1353 $$ = new std::list<PATypeHolder>();
1354 $$->push_back(*$1); delete $1;
1357 | TypeListI ',' UpRTypes {
1358 ($$=$1)->push_back(*$3); delete $3;
1362 // ArgTypeList - List of types for a function type declaration...
1363 ArgTypeListI : TypeListI
1364 | TypeListI ',' DOTDOTDOT {
1365 ($$=$1)->push_back(Type::VoidTy);
1369 ($$ = new std::list<PATypeHolder>())->push_back(Type::VoidTy);
1373 $$ = new std::list<PATypeHolder>();
1377 // ConstVal - The various declarations that go into the constant pool. This
1378 // production is used ONLY to represent constants that show up AFTER a 'const',
1379 // 'constant' or 'global' token at global scope. Constants that can be inlined
1380 // into other expressions (such as integers and constexprs) are handled by the
1381 // ResolvedVal, ValueRef and ConstValueRef productions.
1383 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1384 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1386 GEN_ERROR("Cannot make array constant with type: '" +
1387 (*$1)->getDescription() + "'!");
1388 const Type *ETy = ATy->getElementType();
1389 int NumElements = ATy->getNumElements();
1391 // Verify that we have the correct size...
1392 if (NumElements != -1 && NumElements != (int)$3->size())
1393 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1394 utostr($3->size()) + " arguments, but has size of " +
1395 itostr(NumElements) + "!");
1397 // Verify all elements are correct type!
1398 for (unsigned i = 0; i < $3->size(); i++) {
1399 if (ETy != (*$3)[i]->getType())
1400 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1401 ETy->getDescription() +"' as required!\nIt is of type '"+
1402 (*$3)[i]->getType()->getDescription() + "'.");
1405 $$ = ConstantArray::get(ATy, *$3);
1406 delete $1; delete $3;
1410 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1412 GEN_ERROR("Cannot make array constant with type: '" +
1413 (*$1)->getDescription() + "'!");
1415 int NumElements = ATy->getNumElements();
1416 if (NumElements != -1 && NumElements != 0)
1417 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1418 " arguments, but has size of " + itostr(NumElements) +"!");
1419 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1423 | Types 'c' STRINGCONSTANT {
1424 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1426 GEN_ERROR("Cannot make array constant with type: '" +
1427 (*$1)->getDescription() + "'!");
1429 int NumElements = ATy->getNumElements();
1430 const Type *ETy = ATy->getElementType();
1431 char *EndStr = UnEscapeLexed($3, true);
1432 if (NumElements != -1 && NumElements != (EndStr-$3))
1433 GEN_ERROR("Can't build string constant of size " +
1434 itostr((int)(EndStr-$3)) +
1435 " when array has size " + itostr(NumElements) + "!");
1436 std::vector<Constant*> Vals;
1437 if (ETy == Type::SByteTy) {
1438 for (signed char *C = (signed char *)$3; C != (signed char *)EndStr; ++C)
1439 Vals.push_back(ConstantInt::get(ETy, *C));
1440 } else if (ETy == Type::UByteTy) {
1441 for (unsigned char *C = (unsigned char *)$3;
1442 C != (unsigned char*)EndStr; ++C)
1443 Vals.push_back(ConstantInt::get(ETy, *C));
1446 GEN_ERROR("Cannot build string arrays of non byte sized elements!");
1449 $$ = ConstantArray::get(ATy, Vals);
1453 | Types '<' ConstVector '>' { // Nonempty unsized arr
1454 const PackedType *PTy = dyn_cast<PackedType>($1->get());
1456 GEN_ERROR("Cannot make packed constant with type: '" +
1457 (*$1)->getDescription() + "'!");
1458 const Type *ETy = PTy->getElementType();
1459 int NumElements = PTy->getNumElements();
1461 // Verify that we have the correct size...
1462 if (NumElements != -1 && NumElements != (int)$3->size())
1463 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1464 utostr($3->size()) + " arguments, but has size of " +
1465 itostr(NumElements) + "!");
1467 // Verify all elements are correct type!
1468 for (unsigned i = 0; i < $3->size(); i++) {
1469 if (ETy != (*$3)[i]->getType())
1470 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1471 ETy->getDescription() +"' as required!\nIt is of type '"+
1472 (*$3)[i]->getType()->getDescription() + "'.");
1475 $$ = ConstantPacked::get(PTy, *$3);
1476 delete $1; delete $3;
1479 | Types '{' ConstVector '}' {
1480 const StructType *STy = dyn_cast<StructType>($1->get());
1482 GEN_ERROR("Cannot make struct constant with type: '" +
1483 (*$1)->getDescription() + "'!");
1485 if ($3->size() != STy->getNumContainedTypes())
1486 GEN_ERROR("Illegal number of initializers for structure type!");
1488 // Check to ensure that constants are compatible with the type initializer!
1489 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1490 if ((*$3)[i]->getType() != STy->getElementType(i))
1491 GEN_ERROR("Expected type '" +
1492 STy->getElementType(i)->getDescription() +
1493 "' for element #" + utostr(i) +
1494 " of structure initializer!");
1496 $$ = ConstantStruct::get(STy, *$3);
1497 delete $1; delete $3;
1501 const StructType *STy = dyn_cast<StructType>($1->get());
1503 GEN_ERROR("Cannot make struct constant with type: '" +
1504 (*$1)->getDescription() + "'!");
1506 if (STy->getNumContainedTypes() != 0)
1507 GEN_ERROR("Illegal number of initializers for structure type!");
1509 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1514 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1516 GEN_ERROR("Cannot make null pointer constant with type: '" +
1517 (*$1)->getDescription() + "'!");
1519 $$ = ConstantPointerNull::get(PTy);
1524 $$ = UndefValue::get($1->get());
1528 | Types SymbolicValueRef {
1529 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1531 GEN_ERROR("Global const reference must be a pointer type!");
1533 // ConstExprs can exist in the body of a function, thus creating
1534 // GlobalValues whenever they refer to a variable. Because we are in
1535 // the context of a function, getValNonImprovising will search the functions
1536 // symbol table instead of the module symbol table for the global symbol,
1537 // which throws things all off. To get around this, we just tell
1538 // getValNonImprovising that we are at global scope here.
1540 Function *SavedCurFn = CurFun.CurrentFunction;
1541 CurFun.CurrentFunction = 0;
1543 Value *V = getValNonImprovising(Ty, $2);
1546 CurFun.CurrentFunction = SavedCurFn;
1548 // If this is an initializer for a constant pointer, which is referencing a
1549 // (currently) undefined variable, create a stub now that shall be replaced
1550 // in the future with the right type of variable.
1553 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1554 const PointerType *PT = cast<PointerType>(Ty);
1556 // First check to see if the forward references value is already created!
1557 PerModuleInfo::GlobalRefsType::iterator I =
1558 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1560 if (I != CurModule.GlobalRefs.end()) {
1561 V = I->second; // Placeholder already exists, use it...
1565 if ($2.Type == ValID::NameVal) Name = $2.Name;
1567 // Create the forward referenced global.
1569 if (const FunctionType *FTy =
1570 dyn_cast<FunctionType>(PT->getElementType())) {
1571 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1572 CurModule.CurrentModule);
1574 GV = new GlobalVariable(PT->getElementType(), false,
1575 GlobalValue::ExternalLinkage, 0,
1576 Name, CurModule.CurrentModule);
1579 // Keep track of the fact that we have a forward ref to recycle it
1580 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1585 $$ = cast<GlobalValue>(V);
1586 delete $1; // Free the type handle
1590 if ($1->get() != $2->getType())
1591 GEN_ERROR("Mismatched types for constant expression!");
1596 | Types ZEROINITIALIZER {
1597 const Type *Ty = $1->get();
1598 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1599 GEN_ERROR("Cannot create a null initialized value of this type!");
1600 $$ = Constant::getNullValue(Ty);
1605 ConstVal : SIntType EINT64VAL { // integral constants
1606 if (!ConstantInt::isValueValidForType($1, $2))
1607 GEN_ERROR("Constant value doesn't fit in type!");
1608 $$ = ConstantInt::get($1, $2);
1611 | UIntType EUINT64VAL { // integral constants
1612 if (!ConstantInt::isValueValidForType($1, $2))
1613 GEN_ERROR("Constant value doesn't fit in type!");
1614 $$ = ConstantInt::get($1, $2);
1617 | BOOL TRUETOK { // Boolean constants
1618 $$ = ConstantBool::getTrue();
1621 | BOOL FALSETOK { // Boolean constants
1622 $$ = ConstantBool::getFalse();
1625 | FPType FPVAL { // Float & Double constants
1626 if (!ConstantFP::isValueValidForType($1, $2))
1627 GEN_ERROR("Floating point constant invalid for type!!");
1628 $$ = ConstantFP::get($1, $2);
1633 ConstExpr: CAST '(' ConstVal TO Types ')' {
1634 if (!$3->getType()->isFirstClassType())
1635 GEN_ERROR("cast constant expression from a non-primitive type: '" +
1636 $3->getType()->getDescription() + "'!");
1637 if (!$5->get()->isFirstClassType())
1638 GEN_ERROR("cast constant expression to a non-primitive type: '" +
1639 $5->get()->getDescription() + "'!");
1640 $$ = ConstantExpr::getCast($3, $5->get());
1644 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1645 if (!isa<PointerType>($3->getType()))
1646 GEN_ERROR("GetElementPtr requires a pointer operand!");
1648 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
1649 // indices to uint struct indices for compatibility.
1650 generic_gep_type_iterator<std::vector<Value*>::iterator>
1651 GTI = gep_type_begin($3->getType(), $4->begin(), $4->end()),
1652 GTE = gep_type_end($3->getType(), $4->begin(), $4->end());
1653 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
1654 if (isa<StructType>(*GTI)) // Only change struct indices
1655 if (ConstantInt *CUI = dyn_cast<ConstantInt>((*$4)[i]))
1656 if (CUI->getType() == Type::UByteTy)
1657 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
1660 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1662 GEN_ERROR("Index list invalid for constant getelementptr!");
1664 std::vector<Constant*> IdxVec;
1665 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1666 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1667 IdxVec.push_back(C);
1669 GEN_ERROR("Indices to constant getelementptr must be constants!");
1673 $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1676 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1677 if ($3->getType() != Type::BoolTy)
1678 GEN_ERROR("Select condition must be of boolean type!");
1679 if ($5->getType() != $7->getType())
1680 GEN_ERROR("Select operand types must match!");
1681 $$ = ConstantExpr::getSelect($3, $5, $7);
1684 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1685 if ($3->getType() != $5->getType())
1686 GEN_ERROR("Binary operator types must match!");
1687 // First, make sure we're dealing with the right opcode by upgrading from
1688 // obsolete versions.
1689 sanitizeOpCode($1,$3->getType());
1692 // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
1693 // To retain backward compatibility with these early compilers, we emit a
1694 // cast to the appropriate integer type automatically if we are in the
1695 // broken case. See PR424 for more information.
1696 if (!isa<PointerType>($3->getType())) {
1697 $$ = ConstantExpr::get($1.opcode, $3, $5);
1699 const Type *IntPtrTy = 0;
1700 switch (CurModule.CurrentModule->getPointerSize()) {
1701 case Module::Pointer32: IntPtrTy = Type::IntTy; break;
1702 case Module::Pointer64: IntPtrTy = Type::LongTy; break;
1703 default: GEN_ERROR("invalid pointer binary constant expr!");
1705 $$ = ConstantExpr::get($1.opcode, ConstantExpr::getCast($3, IntPtrTy),
1706 ConstantExpr::getCast($5, IntPtrTy));
1707 $$ = ConstantExpr::getCast($$, $3->getType());
1711 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1712 if ($3->getType() != $5->getType())
1713 GEN_ERROR("Logical operator types must match!");
1714 if (!$3->getType()->isIntegral()) {
1715 if (!isa<PackedType>($3->getType()) ||
1716 !cast<PackedType>($3->getType())->getElementType()->isIntegral())
1717 GEN_ERROR("Logical operator requires integral operands!");
1719 $$ = ConstantExpr::get($1.opcode, $3, $5);
1722 | SetCondOps '(' ConstVal ',' ConstVal ')' {
1723 if ($3->getType() != $5->getType())
1724 GEN_ERROR("setcc operand types must match!");
1725 $$ = ConstantExpr::get($1.opcode, $3, $5);
1728 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1729 if ($5->getType() != Type::UByteTy)
1730 GEN_ERROR("Shift count for shift constant must be unsigned byte!");
1731 if (!$3->getType()->isInteger())
1732 GEN_ERROR("Shift constant expression requires integer operand!");
1733 $$ = ConstantExpr::get($1.opcode, $3, $5);
1736 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1737 if (!ExtractElementInst::isValidOperands($3, $5))
1738 GEN_ERROR("Invalid extractelement operands!");
1739 $$ = ConstantExpr::getExtractElement($3, $5);
1742 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1743 if (!InsertElementInst::isValidOperands($3, $5, $7))
1744 GEN_ERROR("Invalid insertelement operands!");
1745 $$ = ConstantExpr::getInsertElement($3, $5, $7);
1748 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1749 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1750 GEN_ERROR("Invalid shufflevector operands!");
1751 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1756 // ConstVector - A list of comma separated constants.
1757 ConstVector : ConstVector ',' ConstVal {
1758 ($$ = $1)->push_back($3);
1762 $$ = new std::vector<Constant*>();
1768 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1769 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1772 //===----------------------------------------------------------------------===//
1773 // Rules to match Modules
1774 //===----------------------------------------------------------------------===//
1776 // Module rule: Capture the result of parsing the whole file into a result
1779 Module : FunctionList {
1780 $$ = ParserResult = $1;
1781 CurModule.ModuleDone();
1785 // FunctionList - A list of functions, preceeded by a constant pool.
1787 FunctionList : FunctionList Function {
1789 CurFun.FunctionDone();
1792 | FunctionList FunctionProto {
1796 | FunctionList MODULE ASM_TOK AsmBlock {
1800 | FunctionList IMPLEMENTATION {
1805 $$ = CurModule.CurrentModule;
1806 // Emit an error if there are any unresolved types left.
1807 if (!CurModule.LateResolveTypes.empty()) {
1808 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
1809 if (DID.Type == ValID::NameVal) {
1810 GEN_ERROR("Reference to an undefined type: '"+DID.getName() + "'");
1812 GEN_ERROR("Reference to an undefined type: #" + itostr(DID.Num));
1818 // ConstPool - Constants with optional names assigned to them.
1819 ConstPool : ConstPool OptAssign TYPE TypesV {
1820 // Eagerly resolve types. This is not an optimization, this is a
1821 // requirement that is due to the fact that we could have this:
1823 // %list = type { %list * }
1824 // %list = type { %list * } ; repeated type decl
1826 // If types are not resolved eagerly, then the two types will not be
1827 // determined to be the same type!
1829 ResolveTypeTo($2, *$4);
1831 if (!setTypeName(*$4, $2) && !$2) {
1833 // If this is a named type that is not a redefinition, add it to the slot
1835 CurModule.Types.push_back(*$4);
1841 | ConstPool FunctionProto { // Function prototypes can be in const pool
1844 | ConstPool MODULE ASM_TOK AsmBlock { // Asm blocks can be in the const pool
1847 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
1849 GEN_ERROR("Global value initializer is not a constant!");
1850 CurGV = ParseGlobalVariable($2, $3, $4, $5->getType(), $5);
1852 } GlobalVarAttributes {
1855 | ConstPool OptAssign EXTERNAL GlobalType Types {
1856 CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, *$5, 0);
1859 } GlobalVarAttributes {
1863 | ConstPool OptAssign DLLIMPORT GlobalType Types {
1864 CurGV = ParseGlobalVariable($2, GlobalValue::DLLImportLinkage, $4, *$5, 0);
1867 } GlobalVarAttributes {
1871 | ConstPool OptAssign EXTERN_WEAK GlobalType Types {
1873 ParseGlobalVariable($2, GlobalValue::ExternalWeakLinkage, $4, *$5, 0);
1876 } GlobalVarAttributes {
1880 | ConstPool TARGET TargetDefinition {
1883 | ConstPool DEPLIBS '=' LibrariesDefinition {
1886 | /* empty: end of list */ {
1890 AsmBlock : STRINGCONSTANT {
1891 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
1892 char *EndStr = UnEscapeLexed($1, true);
1893 std::string NewAsm($1, EndStr);
1896 if (AsmSoFar.empty())
1897 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
1899 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
1903 BigOrLittle : BIG { $$ = Module::BigEndian; };
1904 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1906 TargetDefinition : ENDIAN '=' BigOrLittle {
1907 CurModule.CurrentModule->setEndianness($3);
1910 | POINTERSIZE '=' EUINT64VAL {
1912 CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1914 CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1916 GEN_ERROR("Invalid pointer size: '" + utostr($3) + "'!");
1919 | TRIPLE '=' STRINGCONSTANT {
1920 CurModule.CurrentModule->setTargetTriple($3);
1923 | DATALAYOUT '=' STRINGCONSTANT {
1924 CurModule.CurrentModule->setDataLayout($3);
1928 LibrariesDefinition : '[' LibList ']';
1930 LibList : LibList ',' STRINGCONSTANT {
1931 CurModule.CurrentModule->addLibrary($3);
1936 CurModule.CurrentModule->addLibrary($1);
1940 | /* empty: end of list */ {
1945 //===----------------------------------------------------------------------===//
1946 // Rules to match Function Headers
1947 //===----------------------------------------------------------------------===//
1949 Name : VAR_ID | STRINGCONSTANT;
1950 OptName : Name | /*empty*/ { $$ = 0; };
1952 ArgVal : Types OptName {
1953 if (*$1 == Type::VoidTy)
1954 GEN_ERROR("void typed arguments are invalid!");
1955 $$ = new std::pair<PATypeHolder*, char*>($1, $2);
1959 ArgListH : ArgListH ',' ArgVal {
1966 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1972 ArgList : ArgListH {
1976 | ArgListH ',' DOTDOTDOT {
1978 $$->push_back(std::pair<PATypeHolder*,
1979 char*>(new PATypeHolder(Type::VoidTy), 0));
1983 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1984 $$->push_back(std::make_pair(new PATypeHolder(Type::VoidTy), (char*)0));
1992 FunctionHeaderH : OptCallingConv TypesV Name '(' ArgList ')'
1993 OptSection OptAlign {
1995 std::string FunctionName($3);
1996 free($3); // Free strdup'd memory!
1998 if (!(*$2)->isFirstClassType() && *$2 != Type::VoidTy)
1999 GEN_ERROR("LLVM functions cannot return aggregate types!");
2001 std::vector<const Type*> ParamTypeList;
2002 if ($5) { // If there are arguments...
2003 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
2004 I != $5->end(); ++I)
2005 ParamTypeList.push_back(I->first->get());
2008 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2009 if (isVarArg) ParamTypeList.pop_back();
2011 const FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
2012 const PointerType *PFT = PointerType::get(FT);
2016 if (!FunctionName.empty()) {
2017 ID = ValID::create((char*)FunctionName.c_str());
2019 ID = ValID::create((int)CurModule.Values[PFT].size());
2023 // See if this function was forward referenced. If so, recycle the object.
2024 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2025 // Move the function to the end of the list, from whereever it was
2026 // previously inserted.
2027 Fn = cast<Function>(FWRef);
2028 CurModule.CurrentModule->getFunctionList().remove(Fn);
2029 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2030 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2031 (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
2032 // If this is the case, either we need to be a forward decl, or it needs
2034 if (!CurFun.isDeclare && !Fn->isExternal())
2035 GEN_ERROR("Redefinition of function '" + FunctionName + "'!");
2037 // Make sure to strip off any argument names so we can't get conflicts.
2038 if (Fn->isExternal())
2039 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2042 } else { // Not already defined?
2043 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
2044 CurModule.CurrentModule);
2046 InsertValue(Fn, CurModule.Values);
2049 CurFun.FunctionStart(Fn);
2051 if (CurFun.isDeclare) {
2052 // If we have declaration, always overwrite linkage. This will allow us to
2053 // correctly handle cases, when pointer to function is passed as argument to
2054 // another function.
2055 Fn->setLinkage(CurFun.Linkage);
2057 Fn->setCallingConv($1);
2058 Fn->setAlignment($8);
2064 // Add all of the arguments we parsed to the function...
2065 if ($5) { // Is null if empty...
2066 if (isVarArg) { // Nuke the last entry
2067 assert($5->back().first->get() == Type::VoidTy && $5->back().second == 0&&
2068 "Not a varargs marker!");
2069 delete $5->back().first;
2070 $5->pop_back(); // Delete the last entry
2072 Function::arg_iterator ArgIt = Fn->arg_begin();
2073 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
2074 I != $5->end(); ++I, ++ArgIt) {
2075 delete I->first; // Delete the typeholder...
2077 setValueName(ArgIt, I->second); // Insert arg into symtab...
2082 delete $5; // We're now done with the argument list
2087 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2089 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
2090 $$ = CurFun.CurrentFunction;
2092 // Make sure that we keep track of the linkage type even if there was a
2093 // previous "declare".
2097 END : ENDTOK | '}'; // Allow end of '}' to end a function
2099 Function : BasicBlockList END {
2104 FnDeclareLinkage: /*default*/ |
2105 DLLIMPORT { CurFun.Linkage = GlobalValue::DLLImportLinkage; } |
2106 EXTERN_WEAK { CurFun.Linkage = GlobalValue::DLLImportLinkage; };
2108 FunctionProto : DECLARE { CurFun.isDeclare = true; } FnDeclareLinkage FunctionHeaderH {
2109 $$ = CurFun.CurrentFunction;
2110 CurFun.FunctionDone();
2114 //===----------------------------------------------------------------------===//
2115 // Rules to match Basic Blocks
2116 //===----------------------------------------------------------------------===//
2118 OptSideEffect : /* empty */ {
2127 ConstValueRef : ESINT64VAL { // A reference to a direct constant
2128 $$ = ValID::create($1);
2132 $$ = ValID::create($1);
2135 | FPVAL { // Perhaps it's an FP constant?
2136 $$ = ValID::create($1);
2140 $$ = ValID::create(ConstantBool::getTrue());
2144 $$ = ValID::create(ConstantBool::getFalse());
2148 $$ = ValID::createNull();
2152 $$ = ValID::createUndef();
2155 | ZEROINITIALIZER { // A vector zero constant.
2156 $$ = ValID::createZeroInit();
2159 | '<' ConstVector '>' { // Nonempty unsized packed vector
2160 const Type *ETy = (*$2)[0]->getType();
2161 int NumElements = $2->size();
2163 PackedType* pt = PackedType::get(ETy, NumElements);
2164 PATypeHolder* PTy = new PATypeHolder(
2172 // Verify all elements are correct type!
2173 for (unsigned i = 0; i < $2->size(); i++) {
2174 if (ETy != (*$2)[i]->getType())
2175 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2176 ETy->getDescription() +"' as required!\nIt is of type '" +
2177 (*$2)[i]->getType()->getDescription() + "'.");
2180 $$ = ValID::create(ConstantPacked::get(pt, *$2));
2181 delete PTy; delete $2;
2185 $$ = ValID::create($1);
2188 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2189 char *End = UnEscapeLexed($3, true);
2190 std::string AsmStr = std::string($3, End);
2191 End = UnEscapeLexed($5, true);
2192 std::string Constraints = std::string($5, End);
2193 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2199 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2202 SymbolicValueRef : INTVAL { // Is it an integer reference...?
2203 $$ = ValID::create($1);
2206 | Name { // Is it a named reference...?
2207 $$ = ValID::create($1);
2211 // ValueRef - A reference to a definition... either constant or symbolic
2212 ValueRef : SymbolicValueRef | ConstValueRef;
2215 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2216 // type immediately preceeds the value reference, and allows complex constant
2217 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2218 ResolvedVal : Types ValueRef {
2219 $$ = getVal(*$1, $2); delete $1;
2223 BasicBlockList : BasicBlockList BasicBlock {
2227 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2233 // Basic blocks are terminated by branching instructions:
2234 // br, br/cc, switch, ret
2236 BasicBlock : InstructionList OptAssign BBTerminatorInst {
2237 setValueName($3, $2);
2241 $1->getInstList().push_back($3);
2247 InstructionList : InstructionList Inst {
2248 $1->getInstList().push_back($2);
2253 $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
2256 // Make sure to move the basic block to the correct location in the
2257 // function, instead of leaving it inserted wherever it was first
2259 Function::BasicBlockListType &BBL =
2260 CurFun.CurrentFunction->getBasicBlockList();
2261 BBL.splice(BBL.end(), BBL, $$);
2265 $$ = CurBB = getBBVal(ValID::create($1), true);
2268 // Make sure to move the basic block to the correct location in the
2269 // function, instead of leaving it inserted wherever it was first
2271 Function::BasicBlockListType &BBL =
2272 CurFun.CurrentFunction->getBasicBlockList();
2273 BBL.splice(BBL.end(), BBL, $$);
2277 BBTerminatorInst : RET ResolvedVal { // Return with a result...
2278 $$ = new ReturnInst($2);
2281 | RET VOID { // Return with no result...
2282 $$ = new ReturnInst();
2285 | BR LABEL ValueRef { // Unconditional Branch...
2286 BasicBlock* tmpBB = getBBVal($3);
2288 $$ = new BranchInst(tmpBB);
2289 } // Conditional Branch...
2290 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2291 BasicBlock* tmpBBA = getBBVal($6);
2293 BasicBlock* tmpBBB = getBBVal($9);
2295 Value* tmpVal = getVal(Type::BoolTy, $3);
2297 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2299 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2300 Value* tmpVal = getVal($2, $3);
2302 BasicBlock* tmpBB = getBBVal($6);
2304 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2307 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2309 for (; I != E; ++I) {
2310 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2311 S->addCase(CI, I->second);
2313 GEN_ERROR("Switch case is constant, but not a simple integer!");
2318 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2319 Value* tmpVal = getVal($2, $3);
2321 BasicBlock* tmpBB = getBBVal($6);
2323 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2327 | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
2328 TO LABEL ValueRef UNWIND LABEL ValueRef {
2329 const PointerType *PFTy;
2330 const FunctionType *Ty;
2332 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2333 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2334 // Pull out the types of all of the arguments...
2335 std::vector<const Type*> ParamTypes;
2337 for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
2339 ParamTypes.push_back((*I)->getType());
2342 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2343 if (isVarArg) ParamTypes.pop_back();
2345 Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
2346 PFTy = PointerType::get(Ty);
2349 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2351 BasicBlock *Normal = getBBVal($10);
2353 BasicBlock *Except = getBBVal($13);
2356 // Create the call node...
2357 if (!$6) { // Has no arguments?
2358 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
2359 } else { // Has arguments?
2360 // Loop through FunctionType's arguments and ensure they are specified
2363 FunctionType::param_iterator I = Ty->param_begin();
2364 FunctionType::param_iterator E = Ty->param_end();
2365 std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
2367 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2368 if ((*ArgI)->getType() != *I)
2369 GEN_ERROR("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2370 (*I)->getDescription() + "'!");
2372 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2373 GEN_ERROR("Invalid number of parameters detected!");
2375 $$ = new InvokeInst(V, Normal, Except, *$6);
2377 cast<InvokeInst>($$)->setCallingConv($2);
2384 $$ = new UnwindInst();
2388 $$ = new UnreachableInst();
2394 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2396 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
2399 GEN_ERROR("May only switch on a constant pool value!");
2401 BasicBlock* tmpBB = getBBVal($6);
2403 $$->push_back(std::make_pair(V, tmpBB));
2405 | IntType ConstValueRef ',' LABEL ValueRef {
2406 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2407 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
2411 GEN_ERROR("May only switch on a constant pool value!");
2413 BasicBlock* tmpBB = getBBVal($5);
2415 $$->push_back(std::make_pair(V, tmpBB));
2418 Inst : OptAssign InstVal {
2419 // Is this definition named?? if so, assign the name...
2420 setValueName($2, $1);
2427 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2428 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2429 Value* tmpVal = getVal(*$1, $3);
2431 BasicBlock* tmpBB = getBBVal($5);
2433 $$->push_back(std::make_pair(tmpVal, tmpBB));
2436 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2438 Value* tmpVal = getVal($1->front().first->getType(), $4);
2440 BasicBlock* tmpBB = getBBVal($6);
2442 $1->push_back(std::make_pair(tmpVal, tmpBB));
2446 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
2447 $$ = new std::vector<Value*>();
2450 | ValueRefList ',' ResolvedVal {
2456 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
2457 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
2459 OptTailCall : TAIL CALL {
2468 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2469 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
2470 !isa<PackedType>((*$2).get()))
2472 "Arithmetic operator requires integer, FP, or packed operands!");
2473 if (isa<PackedType>((*$2).get()) &&
2474 ($1.opcode == Instruction::URem ||
2475 $1.opcode == Instruction::SRem ||
2476 $1.opcode == Instruction::FRem))
2477 GEN_ERROR("U/S/FRem not supported on packed types!");
2478 // Upgrade the opcode from obsolete versions before we do anything with it.
2479 sanitizeOpCode($1,*$2);
2481 Value* val1 = getVal(*$2, $3);
2483 Value* val2 = getVal(*$2, $5);
2485 $$ = BinaryOperator::create($1.opcode, val1, val2);
2487 GEN_ERROR("binary operator returned null!");
2490 | LogicalOps Types ValueRef ',' ValueRef {
2491 if (!(*$2)->isIntegral()) {
2492 if (!isa<PackedType>($2->get()) ||
2493 !cast<PackedType>($2->get())->getElementType()->isIntegral())
2494 GEN_ERROR("Logical operator requires integral operands!");
2496 Value* tmpVal1 = getVal(*$2, $3);
2498 Value* tmpVal2 = getVal(*$2, $5);
2500 $$ = BinaryOperator::create($1.opcode, tmpVal1, tmpVal2);
2502 GEN_ERROR("binary operator returned null!");
2505 | SetCondOps Types ValueRef ',' ValueRef {
2506 if(isa<PackedType>((*$2).get())) {
2508 "PackedTypes currently not supported in setcc instructions!");
2510 Value* tmpVal1 = getVal(*$2, $3);
2512 Value* tmpVal2 = getVal(*$2, $5);
2514 $$ = new SetCondInst($1.opcode, tmpVal1, tmpVal2);
2516 GEN_ERROR("binary operator returned null!");
2520 std::cerr << "WARNING: Use of eliminated 'not' instruction:"
2521 << " Replacing with 'xor'.\n";
2523 Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
2525 GEN_ERROR("Expected integral type for not instruction!");
2527 $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
2529 GEN_ERROR("Could not create a xor instruction!");
2532 | ShiftOps ResolvedVal ',' ResolvedVal {
2533 if ($4->getType() != Type::UByteTy)
2534 GEN_ERROR("Shift amount must be ubyte!");
2535 if (!$2->getType()->isInteger())
2536 GEN_ERROR("Shift constant expression requires integer operand!");
2537 $$ = new ShiftInst($1.opcode, $2, $4);
2540 | CAST ResolvedVal TO Types {
2541 if (!$4->get()->isFirstClassType())
2542 GEN_ERROR("cast instruction to a non-primitive type: '" +
2543 $4->get()->getDescription() + "'!");
2544 $$ = new CastInst($2, *$4);
2548 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2549 if ($2->getType() != Type::BoolTy)
2550 GEN_ERROR("select condition must be boolean!");
2551 if ($4->getType() != $6->getType())
2552 GEN_ERROR("select value types should match!");
2553 $$ = new SelectInst($2, $4, $6);
2556 | VAARG ResolvedVal ',' Types {
2558 $$ = new VAArgInst($2, *$4);
2562 | VAARG_old ResolvedVal ',' Types {
2563 ObsoleteVarArgs = true;
2564 const Type* ArgTy = $2->getType();
2565 Function* NF = CurModule.CurrentModule->
2566 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0);
2569 //foo = alloca 1 of t
2573 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
2574 CurBB->getInstList().push_back(foo);
2575 CallInst* bar = new CallInst(NF, $2);
2576 CurBB->getInstList().push_back(bar);
2577 CurBB->getInstList().push_back(new StoreInst(bar, foo));
2578 $$ = new VAArgInst(foo, *$4);
2582 | VANEXT_old ResolvedVal ',' Types {
2583 ObsoleteVarArgs = true;
2584 const Type* ArgTy = $2->getType();
2585 Function* NF = CurModule.CurrentModule->
2586 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0);
2588 //b = vanext a, t ->
2589 //foo = alloca 1 of t
2592 //tmp = vaarg foo, t
2594 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
2595 CurBB->getInstList().push_back(foo);
2596 CallInst* bar = new CallInst(NF, $2);
2597 CurBB->getInstList().push_back(bar);
2598 CurBB->getInstList().push_back(new StoreInst(bar, foo));
2599 Instruction* tmp = new VAArgInst(foo, *$4);
2600 CurBB->getInstList().push_back(tmp);
2601 $$ = new LoadInst(foo);
2605 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2606 if (!ExtractElementInst::isValidOperands($2, $4))
2607 GEN_ERROR("Invalid extractelement operands!");
2608 $$ = new ExtractElementInst($2, $4);
2611 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2612 if (!InsertElementInst::isValidOperands($2, $4, $6))
2613 GEN_ERROR("Invalid insertelement operands!");
2614 $$ = new InsertElementInst($2, $4, $6);
2617 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2618 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
2619 GEN_ERROR("Invalid shufflevector operands!");
2620 $$ = new ShuffleVectorInst($2, $4, $6);
2624 const Type *Ty = $2->front().first->getType();
2625 if (!Ty->isFirstClassType())
2626 GEN_ERROR("PHI node operands must be of first class type!");
2627 $$ = new PHINode(Ty);
2628 ((PHINode*)$$)->reserveOperandSpace($2->size());
2629 while ($2->begin() != $2->end()) {
2630 if ($2->front().first->getType() != Ty)
2631 GEN_ERROR("All elements of a PHI node must be of the same type!");
2632 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2635 delete $2; // Free the list...
2638 | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')' {
2639 const PointerType *PFTy;
2640 const FunctionType *Ty;
2642 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2643 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2644 // Pull out the types of all of the arguments...
2645 std::vector<const Type*> ParamTypes;
2647 for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
2649 ParamTypes.push_back((*I)->getType());
2652 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2653 if (isVarArg) ParamTypes.pop_back();
2655 if (!(*$3)->isFirstClassType() && *$3 != Type::VoidTy)
2656 GEN_ERROR("LLVM functions cannot return aggregate types!");
2658 Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
2659 PFTy = PointerType::get(Ty);
2662 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2665 // Create the call node...
2666 if (!$6) { // Has no arguments?
2667 // Make sure no arguments is a good thing!
2668 if (Ty->getNumParams() != 0)
2669 GEN_ERROR("No arguments passed to a function that "
2670 "expects arguments!");
2672 $$ = new CallInst(V, std::vector<Value*>());
2673 } else { // Has arguments?
2674 // Loop through FunctionType's arguments and ensure they are specified
2677 FunctionType::param_iterator I = Ty->param_begin();
2678 FunctionType::param_iterator E = Ty->param_end();
2679 std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
2681 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2682 if ((*ArgI)->getType() != *I)
2683 GEN_ERROR("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2684 (*I)->getDescription() + "'!");
2686 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2687 GEN_ERROR("Invalid number of parameters detected!");
2689 $$ = new CallInst(V, *$6);
2691 cast<CallInst>($$)->setTailCall($1);
2692 cast<CallInst>($$)->setCallingConv($2);
2703 // IndexList - List of indices for GEP based instructions...
2704 IndexList : ',' ValueRefList {
2708 $$ = new std::vector<Value*>();
2712 OptVolatile : VOLATILE {
2723 MemoryInst : MALLOC Types OptCAlign {
2724 $$ = new MallocInst(*$2, 0, $3);
2728 | MALLOC Types ',' UINT ValueRef OptCAlign {
2729 Value* tmpVal = getVal($4, $5);
2731 $$ = new MallocInst(*$2, tmpVal, $6);
2734 | ALLOCA Types OptCAlign {
2735 $$ = new AllocaInst(*$2, 0, $3);
2739 | ALLOCA Types ',' UINT ValueRef OptCAlign {
2740 Value* tmpVal = getVal($4, $5);
2742 $$ = new AllocaInst(*$2, tmpVal, $6);
2745 | FREE ResolvedVal {
2746 if (!isa<PointerType>($2->getType()))
2747 GEN_ERROR("Trying to free nonpointer type " +
2748 $2->getType()->getDescription() + "!");
2749 $$ = new FreeInst($2);
2753 | OptVolatile LOAD Types ValueRef {
2754 if (!isa<PointerType>($3->get()))
2755 GEN_ERROR("Can't load from nonpointer type: " +
2756 (*$3)->getDescription());
2757 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
2758 GEN_ERROR("Can't load from pointer of non-first-class type: " +
2759 (*$3)->getDescription());
2760 Value* tmpVal = getVal(*$3, $4);
2762 $$ = new LoadInst(tmpVal, "", $1);
2765 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2766 const PointerType *PT = dyn_cast<PointerType>($5->get());
2768 GEN_ERROR("Can't store to a nonpointer type: " +
2769 (*$5)->getDescription());
2770 const Type *ElTy = PT->getElementType();
2771 if (ElTy != $3->getType())
2772 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
2773 "' into space of type '" + ElTy->getDescription() + "'!");
2775 Value* tmpVal = getVal(*$5, $6);
2777 $$ = new StoreInst($3, tmpVal, $1);
2780 | GETELEMENTPTR Types ValueRef IndexList {
2781 if (!isa<PointerType>($2->get()))
2782 GEN_ERROR("getelementptr insn requires pointer operand!");
2784 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
2785 // indices to uint struct indices for compatibility.
2786 generic_gep_type_iterator<std::vector<Value*>::iterator>
2787 GTI = gep_type_begin($2->get(), $4->begin(), $4->end()),
2788 GTE = gep_type_end($2->get(), $4->begin(), $4->end());
2789 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
2790 if (isa<StructType>(*GTI)) // Only change struct indices
2791 if (ConstantInt *CUI = dyn_cast<ConstantInt>((*$4)[i]))
2792 if (CUI->getType() == Type::UByteTy)
2793 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
2795 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2796 GEN_ERROR("Invalid getelementptr indices for type '" +
2797 (*$2)->getDescription()+ "'!");
2798 Value* tmpVal = getVal(*$2, $3);
2800 $$ = new GetElementPtrInst(tmpVal, *$4);
2808 void llvm::GenerateError(const std::string &message, int LineNo) {
2809 if (LineNo == -1) LineNo = llvmAsmlineno;
2810 // TODO: column number in exception
2812 TheParseError->setError(CurFilename, message, LineNo);
2816 int yyerror(const char *ErrorMsg) {
2818 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2819 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2820 std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2821 if (yychar == YYEMPTY || yychar == 0)
2822 errMsg += "end-of-file.";
2824 errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2825 GenerateError(errMsg);