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 "UpgradeInternals.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/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/Support/MathExtras.h"
29 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
30 // relating to upreferences in the input stream.
32 //#define DEBUG_UPREFS 1
34 #define UR_OUT(X) std::cerr << X
39 #define YYERROR_VERBOSE 1
40 #define YYINCLUDED_STDLIB_H
46 int yyerror(const char*);
47 static void warning(const std::string& WarningMsg);
51 std::istream* LexInput;
52 static std::string CurFilename;
54 // This bool controls whether attributes are ever added to function declarations
55 // definitions and calls.
56 static bool AddAttributes = false;
58 static Module *ParserResult;
59 static bool ObsoleteVarArgs;
60 static bool NewVarArgs;
61 static BasicBlock *CurBB;
62 static GlobalVariable *CurGV;
64 // This contains info used when building the body of a function. It is
65 // destroyed when the function is completed.
67 typedef std::vector<Value *> ValueList; // Numbered defs
69 typedef std::pair<std::string,const Type*> RenameMapKey;
70 typedef std::map<RenameMapKey,std::string> RenameMapType;
73 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
74 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
76 static struct PerModuleInfo {
77 Module *CurrentModule;
78 std::map<const Type *, ValueList> Values; // Module level numbered definitions
79 std::map<const Type *,ValueList> LateResolveValues;
80 std::vector<PATypeHolder> Types;
81 std::map<ValID, PATypeHolder> LateResolveTypes;
82 static Module::Endianness Endian;
83 static Module::PointerSize PointerSize;
84 RenameMapType RenameMap;
86 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
87 /// how they were referenced and on which line of the input they came from so
88 /// that we can resolve them later and print error messages as appropriate.
89 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
91 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
92 // references to global values. Global values may be referenced before they
93 // are defined, and if so, the temporary object that they represent is held
94 // here. This is used for forward references of GlobalValues.
96 typedef std::map<std::pair<const PointerType *, ValID>, GlobalValue*>
98 GlobalRefsType GlobalRefs;
101 // If we could not resolve some functions at function compilation time
102 // (calls to functions before they are defined), resolve them now... Types
103 // are resolved when the constant pool has been completely parsed.
105 ResolveDefinitions(LateResolveValues);
107 // Check to make sure that all global value forward references have been
110 if (!GlobalRefs.empty()) {
111 std::string UndefinedReferences = "Unresolved global references exist:\n";
113 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
115 UndefinedReferences += " " + I->first.first->getDescription() + " " +
116 I->first.second.getName() + "\n";
118 error(UndefinedReferences);
122 if (CurrentModule->getDataLayout().empty()) {
123 std::string dataLayout;
124 if (Endian != Module::AnyEndianness)
125 dataLayout.append(Endian == Module::BigEndian ? "E" : "e");
126 if (PointerSize != Module::AnyPointerSize) {
127 if (!dataLayout.empty())
129 dataLayout.append(PointerSize == Module::Pointer64 ?
130 "p:64:64" : "p:32:32");
132 CurrentModule->setDataLayout(dataLayout);
135 Values.clear(); // Clear out function local definitions
140 // GetForwardRefForGlobal - Check to see if there is a forward reference
141 // for this global. If so, remove it from the GlobalRefs map and return it.
142 // If not, just return null.
143 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
144 // Check to see if there is a forward reference to this global variable...
145 // if there is, eliminate it and patch the reference to use the new def'n.
146 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
147 GlobalValue *Ret = 0;
148 if (I != GlobalRefs.end()) {
154 void setEndianness(Module::Endianness E) { Endian = E; }
155 void setPointerSize(Module::PointerSize sz) { PointerSize = sz; }
158 Module::Endianness PerModuleInfo::Endian = Module::AnyEndianness;
159 Module::PointerSize PerModuleInfo::PointerSize = Module::AnyPointerSize;
161 static struct PerFunctionInfo {
162 Function *CurrentFunction; // Pointer to current function being created
164 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
165 std::map<const Type*, ValueList> LateResolveValues;
166 bool isDeclare; // Is this function a forward declararation?
167 GlobalValue::LinkageTypes Linkage;// Linkage for forward declaration.
169 /// BBForwardRefs - When we see forward references to basic blocks, keep
170 /// track of them here.
171 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
172 std::vector<BasicBlock*> NumberedBlocks;
173 RenameMapType RenameMap;
176 inline PerFunctionInfo() {
179 Linkage = GlobalValue::ExternalLinkage;
182 inline void FunctionStart(Function *M) {
187 void FunctionDone() {
188 NumberedBlocks.clear();
190 // Any forward referenced blocks left?
191 if (!BBForwardRefs.empty()) {
192 error("Undefined reference to label " +
193 BBForwardRefs.begin()->first->getName());
197 // Resolve all forward references now.
198 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
200 Values.clear(); // Clear out function local definitions
204 Linkage = GlobalValue::ExternalLinkage;
206 } CurFun; // Info for the current function...
208 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
211 //===----------------------------------------------------------------------===//
212 // Code to handle definitions of all the types
213 //===----------------------------------------------------------------------===//
215 static int InsertValue(Value *V,
216 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
217 if (V->hasName()) return -1; // Is this a numbered definition?
219 // Yes, insert the value into the value table...
220 ValueList &List = ValueTab[V->getType()];
222 return List.size()-1;
225 static const Type *getType(const ValID &D, bool DoNotImprovise = false) {
227 case ValID::NumberVal: // Is it a numbered definition?
228 // Module constants occupy the lowest numbered slots...
229 if ((unsigned)D.Num < CurModule.Types.size()) {
230 return CurModule.Types[(unsigned)D.Num];
233 case ValID::NameVal: // Is it a named definition?
234 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
235 D.destroy(); // Free old strdup'd memory...
240 error("Internal parser error: Invalid symbol type reference");
244 // If we reached here, we referenced either a symbol that we don't know about
245 // or an id number that hasn't been read yet. We may be referencing something
246 // forward, so just create an entry to be resolved later and get to it...
248 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
251 if (inFunctionScope()) {
252 if (D.Type == ValID::NameVal) {
253 error("Reference to an undefined type: '" + D.getName() + "'");
256 error("Reference to an undefined type: #" + itostr(D.Num));
261 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
262 if (I != CurModule.LateResolveTypes.end())
265 Type *Typ = OpaqueType::get();
266 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
270 // getExistingValue - Look up the value specified by the provided type and
271 // the provided ValID. If the value exists and has already been defined, return
272 // it. Otherwise return null.
274 static Value *getExistingValue(const Type *Ty, const ValID &D) {
275 if (isa<FunctionType>(Ty)) {
276 error("Functions are not values and must be referenced as pointers");
280 case ValID::NumberVal: { // Is it a numbered definition?
281 unsigned Num = (unsigned)D.Num;
283 // Module constants occupy the lowest numbered slots...
284 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
285 if (VI != CurModule.Values.end()) {
286 if (Num < VI->second.size())
287 return VI->second[Num];
288 Num -= VI->second.size();
291 // Make sure that our type is within bounds
292 VI = CurFun.Values.find(Ty);
293 if (VI == CurFun.Values.end()) return 0;
295 // Check that the number is within bounds...
296 if (VI->second.size() <= Num) return 0;
298 return VI->second[Num];
301 case ValID::NameVal: { // Is it a named definition?
302 // Get the name out of the ID
303 std::string Name(D.Name);
305 RenameMapKey Key = std::make_pair(Name, Ty);
306 if (inFunctionScope()) {
307 // See if the name was renamed
308 RenameMapType::const_iterator I = CurFun.RenameMap.find(Key);
309 std::string LookupName;
310 if (I != CurFun.RenameMap.end())
311 LookupName = I->second;
314 SymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
315 V = SymTab.lookup(Ty, LookupName);
318 RenameMapType::const_iterator I = CurModule.RenameMap.find(Key);
319 std::string LookupName;
320 if (I != CurModule.RenameMap.end())
321 LookupName = I->second;
324 V = CurModule.CurrentModule->getValueSymbolTable().lookup(Ty, LookupName);
329 D.destroy(); // Free old strdup'd memory...
333 // Check to make sure that "Ty" is an integral type, and that our
334 // value will fit into the specified type...
335 case ValID::ConstSIntVal: // Is it a constant pool reference??
336 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
337 error("Signed integral constant '" + itostr(D.ConstPool64) +
338 "' is invalid for type '" + Ty->getDescription() + "'");
340 return ConstantInt::get(Ty, D.ConstPool64);
342 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
343 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
344 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64))
345 error("Integral constant '" + utostr(D.UConstPool64) +
346 "' is invalid or out of range");
347 else // This is really a signed reference. Transmogrify.
348 return ConstantInt::get(Ty, D.ConstPool64);
350 return ConstantInt::get(Ty, D.UConstPool64);
352 case ValID::ConstFPVal: // Is it a floating point const pool reference?
353 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
354 error("FP constant invalid for type");
355 return ConstantFP::get(Ty, D.ConstPoolFP);
357 case ValID::ConstNullVal: // Is it a null value?
358 if (!isa<PointerType>(Ty))
359 error("Cannot create a a non pointer null");
360 return ConstantPointerNull::get(cast<PointerType>(Ty));
362 case ValID::ConstUndefVal: // Is it an undef value?
363 return UndefValue::get(Ty);
365 case ValID::ConstZeroVal: // Is it a zero value?
366 return Constant::getNullValue(Ty);
368 case ValID::ConstantVal: // Fully resolved constant?
369 if (D.ConstantValue->getType() != Ty)
370 error("Constant expression type different from required type");
371 return D.ConstantValue;
373 case ValID::InlineAsmVal: { // Inline asm expression
374 const PointerType *PTy = dyn_cast<PointerType>(Ty);
375 const FunctionType *FTy =
376 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
377 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints))
378 error("Invalid type for asm constraint string");
379 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
380 D.IAD->HasSideEffects);
381 D.destroy(); // Free InlineAsmDescriptor.
385 assert(0 && "Unhandled case");
389 assert(0 && "Unhandled case");
393 // getVal - This function is identical to getExistingValue, except that if a
394 // value is not already defined, it "improvises" by creating a placeholder var
395 // that looks and acts just like the requested variable. When the value is
396 // defined later, all uses of the placeholder variable are replaced with the
399 static Value *getVal(const Type *Ty, const ValID &ID) {
400 if (Ty == Type::LabelTy)
401 error("Cannot use a basic block here");
403 // See if the value has already been defined.
404 Value *V = getExistingValue(Ty, ID);
407 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty))
408 error("Invalid use of a composite type");
410 // If we reached here, we referenced either a symbol that we don't know about
411 // or an id number that hasn't been read yet. We may be referencing something
412 // forward, so just create an entry to be resolved later and get to it...
413 V = new Argument(Ty);
415 // Remember where this forward reference came from. FIXME, shouldn't we try
416 // to recycle these things??
417 CurModule.PlaceHolderInfo.insert(
418 std::make_pair(V, std::make_pair(ID, Upgradelineno-1)));
420 if (inFunctionScope())
421 InsertValue(V, CurFun.LateResolveValues);
423 InsertValue(V, CurModule.LateResolveValues);
427 /// getBBVal - This is used for two purposes:
428 /// * If isDefinition is true, a new basic block with the specified ID is being
430 /// * If isDefinition is true, this is a reference to a basic block, which may
431 /// or may not be a forward reference.
433 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
434 assert(inFunctionScope() && "Can't get basic block at global scope");
440 error("Illegal label reference " + ID.getName());
442 case ValID::NumberVal: // Is it a numbered definition?
443 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
444 CurFun.NumberedBlocks.resize(ID.Num+1);
445 BB = CurFun.NumberedBlocks[ID.Num];
447 case ValID::NameVal: // Is it a named definition?
449 if (Value *N = CurFun.CurrentFunction->
450 getValueSymbolTable().lookup(Type::LabelTy, Name)) {
451 if (N->getType() != Type::LabelTy)
452 error("Name '" + Name + "' does not refer to a BasicBlock");
453 BB = cast<BasicBlock>(N);
458 // See if the block has already been defined.
460 // If this is the definition of the block, make sure the existing value was
461 // just a forward reference. If it was a forward reference, there will be
462 // an entry for it in the PlaceHolderInfo map.
463 if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
464 // The existing value was a definition, not a forward reference.
465 error("Redefinition of label " + ID.getName());
467 ID.destroy(); // Free strdup'd memory.
471 // Otherwise this block has not been seen before.
472 BB = new BasicBlock("", CurFun.CurrentFunction);
473 if (ID.Type == ValID::NameVal) {
474 BB->setName(ID.Name);
476 CurFun.NumberedBlocks[ID.Num] = BB;
479 // If this is not a definition, keep track of it so we can use it as a forward
482 // Remember where this forward reference came from.
483 CurFun.BBForwardRefs[BB] = std::make_pair(ID, Upgradelineno);
485 // The forward declaration could have been inserted anywhere in the
486 // function: insert it into the correct place now.
487 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
488 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
495 //===----------------------------------------------------------------------===//
496 // Code to handle forward references in instructions
497 //===----------------------------------------------------------------------===//
499 // This code handles the late binding needed with statements that reference
500 // values not defined yet... for example, a forward branch, or the PHI node for
503 // This keeps a table (CurFun.LateResolveValues) of all such forward references
504 // and back patchs after we are done.
507 // ResolveDefinitions - If we could not resolve some defs at parsing
508 // time (forward branches, phi functions for loops, etc...) resolve the
512 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
513 std::map<const Type*,ValueList> *FutureLateResolvers) {
514 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
515 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
516 E = LateResolvers.end(); LRI != E; ++LRI) {
517 ValueList &List = LRI->second;
518 while (!List.empty()) {
519 Value *V = List.back();
522 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
523 CurModule.PlaceHolderInfo.find(V);
524 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error");
526 ValID &DID = PHI->second.first;
528 Value *TheRealValue = getExistingValue(LRI->first, DID);
530 V->replaceAllUsesWith(TheRealValue);
532 CurModule.PlaceHolderInfo.erase(PHI);
533 } else if (FutureLateResolvers) {
534 // Functions have their unresolved items forwarded to the module late
536 InsertValue(V, *FutureLateResolvers);
538 if (DID.Type == ValID::NameVal) {
539 error("Reference to an invalid definition: '" +DID.getName()+
540 "' of type '" + V->getType()->getDescription() + "'",
544 error("Reference to an invalid definition: #" +
545 itostr(DID.Num) + " of type '" +
546 V->getType()->getDescription() + "'", PHI->second.second);
553 LateResolvers.clear();
556 // ResolveTypeTo - A brand new type was just declared. This means that (if
557 // name is not null) things referencing Name can be resolved. Otherwise, things
558 // refering to the number can be resolved. Do this now.
560 static void ResolveTypeTo(char *Name, const Type *ToTy) {
562 if (Name) D = ValID::create(Name);
563 else D = ValID::create((int)CurModule.Types.size());
565 std::map<ValID, PATypeHolder>::iterator I =
566 CurModule.LateResolveTypes.find(D);
567 if (I != CurModule.LateResolveTypes.end()) {
568 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
569 CurModule.LateResolveTypes.erase(I);
573 static std::string makeNameUnique(const std::string& Name) {
574 static unsigned UniqueNameCounter = 1;
575 std::string Result(Name);
576 Result += ".upgrd." + llvm::utostr(UniqueNameCounter++);
580 // setValueName - Set the specified value to the name given. The name may be
581 // null potentially, in which case this is a noop. The string passed in is
582 // assumed to be a malloc'd string buffer, and is free'd by this function.
584 static void setValueName(Value *V, char *NameStr) {
586 std::string Name(NameStr); // Copy string
587 free(NameStr); // Free old string
589 if (V->getType() == Type::VoidTy) {
590 error("Can't assign name '" + Name + "' to value with void type");
594 assert(inFunctionScope() && "Must be in function scope");
596 // Search the function's symbol table for an existing value of this name
598 SymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
599 SymbolTable::plane_const_iterator PI = ST.plane_begin(), PE =ST.plane_end();
600 for ( ; PI != PE; ++PI) {
601 SymbolTable::value_const_iterator VI = PI->second.find(Name);
602 if (VI != PI->second.end()) {
603 Existing = VI->second;
608 if (Existing->getType() == V->getType()) {
609 // The type of the Existing value and the new one are the same. This
610 // is probably a type plane collapsing error. If the types involved
611 // are both integer, just rename it. Otherwise it
612 // is a redefinition error.
613 if (!Existing->getType()->isInteger()) {
614 error("Redefinition of value named '" + Name + "' in the '" +
615 V->getType()->getDescription() + "' type plane");
619 // In LLVM 2.0 we don't allow names to be re-used for any values in a
620 // function, regardless of Type. Previously re-use of names was okay as
621 // long as they were distinct types. With type planes collapsing because
622 // of the signedness change and because of PR411, this can no longer be
623 // supported. We must search the entire symbol table for a conflicting
624 // name and make the name unique. No warning is needed as this can't
626 std::string NewName = makeNameUnique(Name);
627 // We're changing the name but it will probably be used by other
628 // instructions as operands later on. Consequently we have to retain
629 // a mapping of the renaming that we're doing.
630 RenameMapKey Key = std::make_pair(Name,V->getType());
631 CurFun.RenameMap[Key] = NewName;
640 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
641 /// this is a declaration, otherwise it is a definition.
642 static GlobalVariable *
643 ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
644 bool isConstantGlobal, const Type *Ty,
645 Constant *Initializer) {
646 if (isa<FunctionType>(Ty))
647 error("Cannot declare global vars of function type");
649 const PointerType *PTy = PointerType::get(Ty);
653 Name = NameStr; // Copy string
654 free(NameStr); // Free old string
657 // See if this global value was forward referenced. If so, recycle the
661 ID = ValID::create((char*)Name.c_str());
663 ID = ValID::create((int)CurModule.Values[PTy].size());
666 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
667 // Move the global to the end of the list, from whereever it was
668 // previously inserted.
669 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
670 CurModule.CurrentModule->getGlobalList().remove(GV);
671 CurModule.CurrentModule->getGlobalList().push_back(GV);
672 GV->setInitializer(Initializer);
673 GV->setLinkage(Linkage);
674 GV->setConstant(isConstantGlobal);
675 InsertValue(GV, CurModule.Values);
679 // If this global has a name, check to see if there is already a definition
680 // of this global in the module and emit warnings if there are conflicts.
682 // The global has a name. See if there's an existing one of the same name.
683 if (CurModule.CurrentModule->getNamedGlobal(Name)) {
684 // We found an existing global ov the same name. This isn't allowed
685 // in LLVM 2.0. Consequently, we must alter the name of the global so it
686 // can at least compile. This can happen because of type planes
687 // There is alread a global of the same name which means there is a
688 // conflict. Let's see what we can do about it.
689 std::string NewName(makeNameUnique(Name));
690 if (Linkage == GlobalValue::InternalLinkage) {
691 // The linkage type is internal so just warn about the rename without
692 // invoking "scarey language" about linkage failures. GVars with
693 // InternalLinkage can be renamed at will.
694 warning("Global variable '" + Name + "' was renamed to '"+
697 // The linkage of this gval is external so we can't reliably rename
698 // it because it could potentially create a linking problem.
699 // However, we can't leave the name conflict in the output either or
700 // it won't assemble with LLVM 2.0. So, all we can do is rename
701 // this one to something unique and emit a warning about the problem.
702 warning("Renaming global variable '" + Name + "' to '" + NewName +
703 "' may cause linkage errors");
706 // Put the renaming in the global rename map
707 RenameMapKey Key = std::make_pair(Name,PointerType::get(Ty));
708 CurModule.RenameMap[Key] = NewName;
715 // Otherwise there is no existing GV to use, create one now.
717 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
718 CurModule.CurrentModule);
719 InsertValue(GV, CurModule.Values);
723 // setTypeName - Set the specified type to the name given. The name may be
724 // null potentially, in which case this is a noop. The string passed in is
725 // assumed to be a malloc'd string buffer, and is freed by this function.
727 // This function returns true if the type has already been defined, but is
728 // allowed to be redefined in the specified context. If the name is a new name
729 // for the type plane, it is inserted and false is returned.
730 static bool setTypeName(const Type *T, char *NameStr) {
731 assert(!inFunctionScope() && "Can't give types function-local names");
732 if (NameStr == 0) return false;
734 std::string Name(NameStr); // Copy string
735 free(NameStr); // Free old string
737 // We don't allow assigning names to void type
738 if (T == Type::VoidTy) {
739 error("Can't assign name '" + Name + "' to the void type");
743 // Set the type name, checking for conflicts as we do so.
744 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
746 if (AlreadyExists) { // Inserting a name that is already defined???
747 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
748 assert(Existing && "Conflict but no matching type?");
750 // There is only one case where this is allowed: when we are refining an
751 // opaque type. In this case, Existing will be an opaque type.
752 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
753 // We ARE replacing an opaque type!
754 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
758 // Otherwise, this is an attempt to redefine a type. That's okay if
759 // the redefinition is identical to the original. This will be so if
760 // Existing and T point to the same Type object. In this one case we
761 // allow the equivalent redefinition.
762 if (Existing == T) return true; // Yes, it's equal.
764 // Any other kind of (non-equivalent) redefinition is an error.
765 error("Redefinition of type named '" + Name + "' in the '" +
766 T->getDescription() + "' type plane");
772 //===----------------------------------------------------------------------===//
773 // Code for handling upreferences in type names...
776 // TypeContains - Returns true if Ty directly contains E in it.
778 static bool TypeContains(const Type *Ty, const Type *E) {
779 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
780 E) != Ty->subtype_end();
785 // NestingLevel - The number of nesting levels that need to be popped before
786 // this type is resolved.
787 unsigned NestingLevel;
789 // LastContainedTy - This is the type at the current binding level for the
790 // type. Every time we reduce the nesting level, this gets updated.
791 const Type *LastContainedTy;
793 // UpRefTy - This is the actual opaque type that the upreference is
797 UpRefRecord(unsigned NL, OpaqueType *URTy)
798 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
802 // UpRefs - A list of the outstanding upreferences that need to be resolved.
803 static std::vector<UpRefRecord> UpRefs;
805 /// HandleUpRefs - Every time we finish a new layer of types, this function is
806 /// called. It loops through the UpRefs vector, which is a list of the
807 /// currently active types. For each type, if the up reference is contained in
808 /// the newly completed type, we decrement the level count. When the level
809 /// count reaches zero, the upreferenced type is the type that is passed in:
810 /// thus we can complete the cycle.
812 static PATypeHolder HandleUpRefs(const Type *ty) {
813 // If Ty isn't abstract, or if there are no up-references in it, then there is
814 // nothing to resolve here.
815 if (!ty->isAbstract() || UpRefs.empty()) return ty;
818 UR_OUT("Type '" << Ty->getDescription() <<
819 "' newly formed. Resolving upreferences.\n" <<
820 UpRefs.size() << " upreferences active!\n");
822 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
823 // to zero), we resolve them all together before we resolve them to Ty. At
824 // the end of the loop, if there is anything to resolve to Ty, it will be in
826 OpaqueType *TypeToResolve = 0;
828 for (unsigned i = 0; i != UpRefs.size(); ++i) {
829 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
830 << UpRefs[i].second->getDescription() << ") = "
831 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
832 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
833 // Decrement level of upreference
834 unsigned Level = --UpRefs[i].NestingLevel;
835 UpRefs[i].LastContainedTy = Ty;
836 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
837 if (Level == 0) { // Upreference should be resolved!
838 if (!TypeToResolve) {
839 TypeToResolve = UpRefs[i].UpRefTy;
841 UR_OUT(" * Resolving upreference for "
842 << UpRefs[i].second->getDescription() << "\n";
843 std::string OldName = UpRefs[i].UpRefTy->getDescription());
844 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
845 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
846 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
848 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
849 --i; // Do not skip the next element...
855 UR_OUT(" * Resolving upreference for "
856 << UpRefs[i].second->getDescription() << "\n";
857 std::string OldName = TypeToResolve->getDescription());
858 TypeToResolve->refineAbstractTypeTo(Ty);
864 static inline Instruction::TermOps
865 getTermOp(TermOps op) {
867 default : assert(0 && "Invalid OldTermOp");
868 case RetOp : return Instruction::Ret;
869 case BrOp : return Instruction::Br;
870 case SwitchOp : return Instruction::Switch;
871 case InvokeOp : return Instruction::Invoke;
872 case UnwindOp : return Instruction::Unwind;
873 case UnreachableOp: return Instruction::Unreachable;
877 static inline Instruction::BinaryOps
878 getBinaryOp(BinaryOps op, const Type *Ty, Signedness Sign) {
880 default : assert(0 && "Invalid OldBinaryOps");
886 case SetGT : assert(0 && "Should use getCompareOp");
887 case AddOp : return Instruction::Add;
888 case SubOp : return Instruction::Sub;
889 case MulOp : return Instruction::Mul;
891 // This is an obsolete instruction so we must upgrade it based on the
892 // types of its operands.
893 bool isFP = Ty->isFloatingPoint();
894 if (const PackedType* PTy = dyn_cast<PackedType>(Ty))
895 // If its a packed type we want to use the element type
896 isFP = PTy->getElementType()->isFloatingPoint();
898 return Instruction::FDiv;
899 else if (Sign == Signed)
900 return Instruction::SDiv;
901 return Instruction::UDiv;
903 case UDivOp : return Instruction::UDiv;
904 case SDivOp : return Instruction::SDiv;
905 case FDivOp : return Instruction::FDiv;
907 // This is an obsolete instruction so we must upgrade it based on the
908 // types of its operands.
909 bool isFP = Ty->isFloatingPoint();
910 if (const PackedType* PTy = dyn_cast<PackedType>(Ty))
911 // If its a packed type we want to use the element type
912 isFP = PTy->getElementType()->isFloatingPoint();
913 // Select correct opcode
915 return Instruction::FRem;
916 else if (Sign == Signed)
917 return Instruction::SRem;
918 return Instruction::URem;
920 case URemOp : return Instruction::URem;
921 case SRemOp : return Instruction::SRem;
922 case FRemOp : return Instruction::FRem;
923 case AndOp : return Instruction::And;
924 case OrOp : return Instruction::Or;
925 case XorOp : return Instruction::Xor;
929 static inline Instruction::OtherOps
930 getCompareOp(BinaryOps op, unsigned short &predicate, const Type* &Ty,
932 bool isSigned = Sign == Signed;
933 bool isFP = Ty->isFloatingPoint();
935 default : assert(0 && "Invalid OldSetCC");
938 predicate = FCmpInst::FCMP_OEQ;
939 return Instruction::FCmp;
941 predicate = ICmpInst::ICMP_EQ;
942 return Instruction::ICmp;
946 predicate = FCmpInst::FCMP_UNE;
947 return Instruction::FCmp;
949 predicate = ICmpInst::ICMP_NE;
950 return Instruction::ICmp;
954 predicate = FCmpInst::FCMP_OLE;
955 return Instruction::FCmp;
958 predicate = ICmpInst::ICMP_SLE;
960 predicate = ICmpInst::ICMP_ULE;
961 return Instruction::ICmp;
965 predicate = FCmpInst::FCMP_OGE;
966 return Instruction::FCmp;
969 predicate = ICmpInst::ICMP_SGE;
971 predicate = ICmpInst::ICMP_UGE;
972 return Instruction::ICmp;
976 predicate = FCmpInst::FCMP_OLT;
977 return Instruction::FCmp;
980 predicate = ICmpInst::ICMP_SLT;
982 predicate = ICmpInst::ICMP_ULT;
983 return Instruction::ICmp;
987 predicate = FCmpInst::FCMP_OGT;
988 return Instruction::FCmp;
991 predicate = ICmpInst::ICMP_SGT;
993 predicate = ICmpInst::ICMP_UGT;
994 return Instruction::ICmp;
999 static inline Instruction::MemoryOps getMemoryOp(MemoryOps op) {
1001 default : assert(0 && "Invalid OldMemoryOps");
1002 case MallocOp : return Instruction::Malloc;
1003 case FreeOp : return Instruction::Free;
1004 case AllocaOp : return Instruction::Alloca;
1005 case LoadOp : return Instruction::Load;
1006 case StoreOp : return Instruction::Store;
1007 case GetElementPtrOp : return Instruction::GetElementPtr;
1011 static inline Instruction::OtherOps
1012 getOtherOp(OtherOps op, Signedness Sign) {
1014 default : assert(0 && "Invalid OldOtherOps");
1015 case PHIOp : return Instruction::PHI;
1016 case CallOp : return Instruction::Call;
1017 case ShlOp : return Instruction::Shl;
1020 return Instruction::AShr;
1021 return Instruction::LShr;
1022 case SelectOp : return Instruction::Select;
1023 case UserOp1 : return Instruction::UserOp1;
1024 case UserOp2 : return Instruction::UserOp2;
1025 case VAArg : return Instruction::VAArg;
1026 case ExtractElementOp : return Instruction::ExtractElement;
1027 case InsertElementOp : return Instruction::InsertElement;
1028 case ShuffleVectorOp : return Instruction::ShuffleVector;
1029 case ICmpOp : return Instruction::ICmp;
1030 case FCmpOp : return Instruction::FCmp;
1031 case LShrOp : return Instruction::LShr;
1032 case AShrOp : return Instruction::AShr;
1036 static inline Value*
1037 getCast(CastOps op, Value *Src, Signedness SrcSign, const Type *DstTy,
1038 Signedness DstSign, bool ForceInstruction = false) {
1039 Instruction::CastOps Opcode;
1040 const Type* SrcTy = Src->getType();
1042 if (SrcTy->isFloatingPoint() && isa<PointerType>(DstTy)) {
1043 // fp -> ptr cast is no longer supported but we must upgrade this
1044 // by doing a double cast: fp -> int -> ptr
1045 SrcTy = Type::Int64Ty;
1046 Opcode = Instruction::IntToPtr;
1047 if (isa<Constant>(Src)) {
1048 Src = ConstantExpr::getCast(Instruction::FPToUI,
1049 cast<Constant>(Src), SrcTy);
1051 std::string NewName(makeNameUnique(Src->getName()));
1052 Src = new FPToUIInst(Src, SrcTy, NewName, CurBB);
1054 } else if (isa<IntegerType>(DstTy) &&
1055 cast<IntegerType>(DstTy)->getBitWidth() == 1) {
1056 // cast type %x to bool was previously defined as setne type %x, null
1057 // The cast semantic is now to truncate, not compare so we must retain
1058 // the original intent by replacing the cast with a setne
1059 Constant* Null = Constant::getNullValue(SrcTy);
1060 Instruction::OtherOps Opcode = Instruction::ICmp;
1061 unsigned short predicate = ICmpInst::ICMP_NE;
1062 if (SrcTy->isFloatingPoint()) {
1063 Opcode = Instruction::FCmp;
1064 predicate = FCmpInst::FCMP_ONE;
1065 } else if (!SrcTy->isInteger() && !isa<PointerType>(SrcTy)) {
1066 error("Invalid cast to bool");
1068 if (isa<Constant>(Src) && !ForceInstruction)
1069 return ConstantExpr::getCompare(predicate, cast<Constant>(Src), Null);
1071 return CmpInst::create(Opcode, predicate, Src, Null);
1073 // Determine the opcode to use by calling CastInst::getCastOpcode
1075 CastInst::getCastOpcode(Src, SrcSign == Signed, DstTy, DstSign == Signed);
1077 } else switch (op) {
1078 default: assert(0 && "Invalid cast token");
1079 case TruncOp: Opcode = Instruction::Trunc; break;
1080 case ZExtOp: Opcode = Instruction::ZExt; break;
1081 case SExtOp: Opcode = Instruction::SExt; break;
1082 case FPTruncOp: Opcode = Instruction::FPTrunc; break;
1083 case FPExtOp: Opcode = Instruction::FPExt; break;
1084 case FPToUIOp: Opcode = Instruction::FPToUI; break;
1085 case FPToSIOp: Opcode = Instruction::FPToSI; break;
1086 case UIToFPOp: Opcode = Instruction::UIToFP; break;
1087 case SIToFPOp: Opcode = Instruction::SIToFP; break;
1088 case PtrToIntOp: Opcode = Instruction::PtrToInt; break;
1089 case IntToPtrOp: Opcode = Instruction::IntToPtr; break;
1090 case BitCastOp: Opcode = Instruction::BitCast; break;
1093 if (isa<Constant>(Src) && !ForceInstruction)
1094 return ConstantExpr::getCast(Opcode, cast<Constant>(Src), DstTy);
1095 return CastInst::create(Opcode, Src, DstTy);
1098 static Instruction *
1099 upgradeIntrinsicCall(const Type* RetTy, const ValID &ID,
1100 std::vector<Value*>& Args) {
1102 std::string Name = ID.Type == ValID::NameVal ? ID.Name : "";
1103 if (Name == "llvm.isunordered.f32" || Name == "llvm.isunordered.f64") {
1104 if (Args.size() != 2)
1105 error("Invalid prototype for " + Name + " prototype");
1106 return new FCmpInst(FCmpInst::FCMP_UNO, Args[0], Args[1]);
1108 static unsigned upgradeCount = 1;
1109 const Type* PtrTy = PointerType::get(Type::Int8Ty);
1110 std::vector<const Type*> Params;
1111 if (Name == "llvm.va_start" || Name == "llvm.va_end") {
1112 if (Args.size() != 1)
1113 error("Invalid prototype for " + Name + " prototype");
1114 Params.push_back(PtrTy);
1115 const FunctionType *FTy = FunctionType::get(Type::VoidTy, Params, false);
1116 const PointerType *PFTy = PointerType::get(FTy);
1117 Value* Func = getVal(PFTy, ID);
1118 std::string InstName("va_upgrade");
1119 InstName += llvm::utostr(upgradeCount++);
1120 Args[0] = new BitCastInst(Args[0], PtrTy, InstName, CurBB);
1121 return new CallInst(Func, Args);
1122 } else if (Name == "llvm.va_copy") {
1123 if (Args.size() != 2)
1124 error("Invalid prototype for " + Name + " prototype");
1125 Params.push_back(PtrTy);
1126 Params.push_back(PtrTy);
1127 const FunctionType *FTy = FunctionType::get(Type::VoidTy, Params, false);
1128 const PointerType *PFTy = PointerType::get(FTy);
1129 Value* Func = getVal(PFTy, ID);
1130 std::string InstName0("va_upgrade");
1131 InstName0 += llvm::utostr(upgradeCount++);
1132 std::string InstName1("va_upgrade");
1133 InstName1 += llvm::utostr(upgradeCount++);
1134 Args[0] = new BitCastInst(Args[0], PtrTy, InstName0, CurBB);
1135 Args[1] = new BitCastInst(Args[1], PtrTy, InstName1, CurBB);
1136 return new CallInst(Func, Args);
1142 const Type* upgradeGEPIndices(const Type* PTy,
1143 std::vector<ValueInfo> *Indices,
1144 std::vector<Value*> &VIndices,
1145 std::vector<Constant*> *CIndices = 0) {
1146 // Traverse the indices with a gep_type_iterator so we can build the list
1147 // of constant and value indices for use later. Also perform upgrades
1149 if (CIndices) CIndices->clear();
1150 for (unsigned i = 0, e = Indices->size(); i != e; ++i)
1151 VIndices.push_back((*Indices)[i].V);
1152 generic_gep_type_iterator<std::vector<Value*>::iterator>
1153 GTI = gep_type_begin(PTy, VIndices.begin(), VIndices.end()),
1154 GTE = gep_type_end(PTy, VIndices.begin(), VIndices.end());
1155 for (unsigned i = 0, e = Indices->size(); i != e && GTI != GTE; ++i, ++GTI) {
1156 Value *Index = VIndices[i];
1157 if (CIndices && !isa<Constant>(Index))
1158 error("Indices to constant getelementptr must be constants");
1159 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte
1160 // struct indices to i32 struct indices with ZExt for compatibility.
1161 else if (isa<StructType>(*GTI)) { // Only change struct indices
1162 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Index))
1163 if (CUI->getType()->getBitWidth() == 8)
1165 ConstantExpr::getCast(Instruction::ZExt, CUI, Type::Int32Ty);
1167 // Make sure that unsigned SequentialType indices are zext'd to
1168 // 64-bits if they were smaller than that because LLVM 2.0 will sext
1169 // all indices for SequentialType elements. We must retain the same
1170 // semantic (zext) for unsigned types.
1171 if (const IntegerType *Ity = dyn_cast<IntegerType>(Index->getType()))
1172 if (Ity->getBitWidth() < 64 && (*Indices)[i].S == Unsigned)
1174 Index = ConstantExpr::getCast(Instruction::ZExt,
1175 cast<Constant>(Index), Type::Int64Ty);
1177 Index = CastInst::create(Instruction::ZExt, Index, Type::Int64Ty,
1178 "gep_upgrade", CurBB);
1180 // Add to the CIndices list, if requested.
1182 CIndices->push_back(cast<Constant>(Index));
1186 GetElementPtrInst::getIndexedType(PTy, VIndices, true);
1188 error("Index list invalid for constant getelementptr");
1192 Module* UpgradeAssembly(const std::string &infile, std::istream& in,
1193 bool debug, bool addAttrs)
1196 CurFilename = infile;
1199 AddAttributes = addAttrs;
1200 ObsoleteVarArgs = false;
1203 CurModule.CurrentModule = new Module(CurFilename);
1205 // Check to make sure the parser succeeded
1208 delete ParserResult;
1209 std::cerr << "llvm-upgrade: parse failed.\n";
1213 // Check to make sure that parsing produced a result
1214 if (!ParserResult) {
1215 std::cerr << "llvm-upgrade: no parse result.\n";
1219 // Reset ParserResult variable while saving its value for the result.
1220 Module *Result = ParserResult;
1223 //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
1226 if ((F = Result->getNamedFunction("llvm.va_start"))
1227 && F->getFunctionType()->getNumParams() == 0)
1228 ObsoleteVarArgs = true;
1229 if((F = Result->getNamedFunction("llvm.va_copy"))
1230 && F->getFunctionType()->getNumParams() == 1)
1231 ObsoleteVarArgs = true;
1234 if (ObsoleteVarArgs && NewVarArgs) {
1235 error("This file is corrupt: it uses both new and old style varargs");
1239 if(ObsoleteVarArgs) {
1240 if(Function* F = Result->getNamedFunction("llvm.va_start")) {
1241 if (F->arg_size() != 0) {
1242 error("Obsolete va_start takes 0 argument");
1248 //bar = alloca typeof(foo)
1252 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1253 const Type* ArgTy = F->getFunctionType()->getReturnType();
1254 const Type* ArgTyPtr = PointerType::get(ArgTy);
1255 Function* NF = cast<Function>(Result->getOrInsertFunction(
1256 "llvm.va_start", RetTy, ArgTyPtr, (Type *)0));
1258 while (!F->use_empty()) {
1259 CallInst* CI = cast<CallInst>(F->use_back());
1260 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
1261 new CallInst(NF, bar, "", CI);
1262 Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
1263 CI->replaceAllUsesWith(foo);
1264 CI->getParent()->getInstList().erase(CI);
1266 Result->getFunctionList().erase(F);
1269 if(Function* F = Result->getNamedFunction("llvm.va_end")) {
1270 if(F->arg_size() != 1) {
1271 error("Obsolete va_end takes 1 argument");
1277 //bar = alloca 1 of typeof(foo)
1279 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1280 const Type* ArgTy = F->getFunctionType()->getParamType(0);
1281 const Type* ArgTyPtr = PointerType::get(ArgTy);
1282 Function* NF = cast<Function>(Result->getOrInsertFunction(
1283 "llvm.va_end", RetTy, ArgTyPtr, (Type *)0));
1285 while (!F->use_empty()) {
1286 CallInst* CI = cast<CallInst>(F->use_back());
1287 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
1288 new StoreInst(CI->getOperand(1), bar, CI);
1289 new CallInst(NF, bar, "", CI);
1290 CI->getParent()->getInstList().erase(CI);
1292 Result->getFunctionList().erase(F);
1295 if(Function* F = Result->getNamedFunction("llvm.va_copy")) {
1296 if(F->arg_size() != 1) {
1297 error("Obsolete va_copy takes 1 argument");
1302 //a = alloca 1 of typeof(foo)
1303 //b = alloca 1 of typeof(foo)
1308 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1309 const Type* ArgTy = F->getFunctionType()->getReturnType();
1310 const Type* ArgTyPtr = PointerType::get(ArgTy);
1311 Function* NF = cast<Function>(Result->getOrInsertFunction(
1312 "llvm.va_copy", RetTy, ArgTyPtr, ArgTyPtr, (Type *)0));
1314 while (!F->use_empty()) {
1315 CallInst* CI = cast<CallInst>(F->use_back());
1316 AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
1317 AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
1318 new StoreInst(CI->getOperand(1), b, CI);
1319 new CallInst(NF, a, b, "", CI);
1320 Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
1321 CI->replaceAllUsesWith(foo);
1322 CI->getParent()->getInstList().erase(CI);
1324 Result->getFunctionList().erase(F);
1331 } // end llvm namespace
1333 using namespace llvm;
1338 llvm::Module *ModuleVal;
1339 llvm::Function *FunctionVal;
1340 std::pair<llvm::PATypeInfo, char*> *ArgVal;
1341 llvm::BasicBlock *BasicBlockVal;
1342 llvm::TerminatorInst *TermInstVal;
1343 llvm::InstrInfo InstVal;
1344 llvm::ConstInfo ConstVal;
1345 llvm::ValueInfo ValueVal;
1346 llvm::PATypeInfo TypeVal;
1347 llvm::TypeInfo PrimType;
1348 llvm::PHIListInfo PHIList;
1349 std::list<llvm::PATypeInfo> *TypeList;
1350 std::vector<llvm::ValueInfo> *ValueList;
1351 std::vector<llvm::ConstInfo> *ConstVector;
1354 std::vector<std::pair<llvm::PATypeInfo,char*> > *ArgList;
1355 // Represent the RHS of PHI node
1356 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
1358 llvm::GlobalValue::LinkageTypes Linkage;
1366 char *StrVal; // This memory is strdup'd!
1367 llvm::ValID ValIDVal; // strdup'd memory maybe!
1369 llvm::BinaryOps BinaryOpVal;
1370 llvm::TermOps TermOpVal;
1371 llvm::MemoryOps MemOpVal;
1372 llvm::OtherOps OtherOpVal;
1373 llvm::CastOps CastOpVal;
1374 llvm::ICmpInst::Predicate IPred;
1375 llvm::FCmpInst::Predicate FPred;
1376 llvm::Module::Endianness Endianness;
1379 %type <ModuleVal> Module FunctionList
1380 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1381 %type <BasicBlockVal> BasicBlock InstructionList
1382 %type <TermInstVal> BBTerminatorInst
1383 %type <InstVal> Inst InstVal MemoryInst
1384 %type <ConstVal> ConstVal ConstExpr
1385 %type <ConstVector> ConstVector
1386 %type <ArgList> ArgList ArgListH
1387 %type <ArgVal> ArgVal
1388 %type <PHIList> PHIList
1389 %type <ValueList> ValueRefList ValueRefListE // For call param lists
1390 %type <ValueList> IndexList // For GEP derived indices
1391 %type <TypeList> TypeListI ArgTypeListI
1392 %type <JumpTable> JumpTable
1393 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1394 %type <BoolVal> OptVolatile // 'volatile' or not
1395 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1396 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
1397 %type <Linkage> OptLinkage
1398 %type <Endianness> BigOrLittle
1400 // ValueRef - Unresolved reference to a definition or BB
1401 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1402 %type <ValueVal> ResolvedVal // <type> <valref> pair
1404 // Tokens and types for handling constant integer values
1406 // ESINT64VAL - A negative number within long long range
1407 %token <SInt64Val> ESINT64VAL
1409 // EUINT64VAL - A positive number within uns. long long range
1410 %token <UInt64Val> EUINT64VAL
1411 %type <SInt64Val> EINT64VAL
1413 %token <SIntVal> SINTVAL // Signed 32 bit ints...
1414 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
1415 %type <SIntVal> INTVAL
1416 %token <FPVal> FPVAL // Float or Double constant
1418 // Built in types...
1419 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
1420 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
1421 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
1422 %token <PrimType> FLOAT DOUBLE TYPE LABEL
1424 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
1425 %type <StrVal> Name OptName OptAssign
1426 %type <UIntVal> OptAlign OptCAlign
1427 %type <StrVal> OptSection SectionString
1429 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1430 %token DECLARE GLOBAL CONSTANT SECTION VOLATILE
1431 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
1432 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
1433 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
1434 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1435 %token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
1436 %token X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1438 %type <UIntVal> OptCallingConv
1440 // Basic Block Terminating Operators
1441 %token <TermOpVal> RET BR SWITCH INVOKE UNREACHABLE
1442 %token UNWIND EXCEPT
1445 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
1446 %token <BinaryOpVal> ADD SUB MUL DIV UDIV SDIV FDIV REM UREM SREM FREM
1447 %token <BinaryOpVal> AND OR XOR
1448 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comparators
1449 %token <OtherOpVal> ICMP FCMP
1451 // Memory Instructions
1452 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1455 %type <OtherOpVal> ShiftOps
1456 %token <OtherOpVal> PHI_TOK SELECT SHL SHR ASHR LSHR VAARG
1457 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1458 %token VAARG_old VANEXT_old //OBSOLETE
1460 // Support for ICmp/FCmp Predicates, which is 1.9++ but not 2.0
1461 %type <IPred> IPredicates
1462 %type <FPred> FPredicates
1463 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1464 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1466 %token <CastOpVal> CAST TRUNC ZEXT SEXT FPTRUNC FPEXT FPTOUI FPTOSI
1467 %token <CastOpVal> UITOFP SITOFP PTRTOINT INTTOPTR BITCAST
1468 %type <CastOpVal> CastOps
1474 // Handle constant integer size restriction and conversion...
1479 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
1480 error("Value too large for type");
1486 : ESINT64VAL; // These have same type and can't cause problems...
1488 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
1489 error("Value too large for type");
1493 // Operations that are notably excluded from this list include:
1494 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1497 : ADD | SUB | MUL | DIV | UDIV | SDIV | FDIV | REM | UREM | SREM | FREM
1505 : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
1509 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1510 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1511 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1512 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1513 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1517 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1518 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1519 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1520 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1521 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1522 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1523 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1524 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1525 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1528 : SHL | SHR | ASHR | LSHR
1532 : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | FPTOUI | FPTOSI
1533 | UITOFP | SITOFP | PTRTOINT | INTTOPTR | BITCAST | CAST
1536 // These are some types that allow classification if we only want a particular
1537 // thing... for example, only a signed, unsigned, or integral type.
1539 : LONG | INT | SHORT | SBYTE
1543 : ULONG | UINT | USHORT | UBYTE
1547 : SIntType | UIntType
1554 // OptAssign - Value producing statements have an optional assignment component
1564 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1565 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1566 | WEAK { $$ = GlobalValue::WeakLinkage; }
1567 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1568 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1569 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1570 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1571 | /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1575 : /*empty*/ { $$ = CallingConv::C; }
1576 | CCC_TOK { $$ = CallingConv::C; }
1577 | CSRETCC_TOK { $$ = CallingConv::CSRet; }
1578 | FASTCC_TOK { $$ = CallingConv::Fast; }
1579 | COLDCC_TOK { $$ = CallingConv::Cold; }
1580 | X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; }
1581 | X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; }
1582 | CC_TOK EUINT64VAL {
1583 if ((unsigned)$2 != $2)
1584 error("Calling conv too large");
1589 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1590 // a comma before it.
1592 : /*empty*/ { $$ = 0; }
1593 | ALIGN EUINT64VAL {
1595 if ($$ != 0 && !isPowerOf2_32($$))
1596 error("Alignment must be a power of two");
1601 : /*empty*/ { $$ = 0; }
1602 | ',' ALIGN EUINT64VAL {
1604 if ($$ != 0 && !isPowerOf2_32($$))
1605 error("Alignment must be a power of two");
1610 : SECTION STRINGCONSTANT {
1611 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1612 if ($2[i] == '"' || $2[i] == '\\')
1613 error("Invalid character in section name");
1619 : /*empty*/ { $$ = 0; }
1620 | SectionString { $$ = $1; }
1623 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1624 // is set to be the global we are processing.
1628 | ',' GlobalVarAttribute GlobalVarAttributes {}
1633 CurGV->setSection($1);
1636 | ALIGN EUINT64VAL {
1637 if ($2 != 0 && !isPowerOf2_32($2))
1638 error("Alignment must be a power of two");
1639 CurGV->setAlignment($2);
1644 //===----------------------------------------------------------------------===//
1645 // Types includes all predefined types... except void, because it can only be
1646 // used in specific contexts (function returning void for example). To have
1647 // access to it, a user must explicitly use TypesV.
1650 // TypesV includes all of 'Types', but it also includes the void type.
1654 $$.T = new PATypeHolder($1.T);
1662 $$.T = new PATypeHolder($1.T);
1669 if (!UpRefs.empty())
1670 error("Invalid upreference in type: " + (*$1.T)->getDescription());
1676 : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT
1677 | LONG | ULONG | FLOAT | DOUBLE | LABEL
1680 // Derived types are added later...
1683 $$.T = new PATypeHolder($1.T);
1687 $$.T = new PATypeHolder(OpaqueType::get());
1690 | SymbolicValueRef { // Named types are also simple types...
1691 const Type* tmp = getType($1);
1692 $$.T = new PATypeHolder(tmp);
1693 $$.S = Signless; // FIXME: what if its signed?
1695 | '\\' EUINT64VAL { // Type UpReference
1696 if ($2 > (uint64_t)~0U)
1697 error("Value out of range");
1698 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1699 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1700 $$.T = new PATypeHolder(OT);
1702 UR_OUT("New Upreference!\n");
1704 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
1705 std::vector<const Type*> Params;
1706 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
1707 E = $3->end(); I != E; ++I) {
1708 Params.push_back(I->T->get());
1711 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1712 if (isVarArg) Params.pop_back();
1714 $$.T = new PATypeHolder(HandleUpRefs(
1715 FunctionType::get($1.T->get(),Params,isVarArg)));
1717 delete $1.T; // Delete the return type handle
1718 delete $3; // Delete the argument list
1720 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
1721 $$.T = new PATypeHolder(HandleUpRefs(ArrayType::get($4.T->get(),
1726 | '<' EUINT64VAL 'x' UpRTypes '>' { // Packed array type?
1727 const llvm::Type* ElemTy = $4.T->get();
1728 if ((unsigned)$2 != $2)
1729 error("Unsigned result not equal to signed result");
1730 if (!(ElemTy->isInteger() || ElemTy->isFloatingPoint()))
1731 error("Elements of a PackedType must be integer or floating point");
1732 if (!isPowerOf2_32($2))
1733 error("PackedType length should be a power of 2");
1734 $$.T = new PATypeHolder(HandleUpRefs(PackedType::get(ElemTy,
1739 | '{' TypeListI '}' { // Structure type?
1740 std::vector<const Type*> Elements;
1741 for (std::list<llvm::PATypeInfo>::iterator I = $2->begin(),
1742 E = $2->end(); I != E; ++I)
1743 Elements.push_back(I->T->get());
1744 $$.T = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1748 | '{' '}' { // Empty structure type?
1749 $$.T = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1752 | '<' '{' TypeListI '}' '>' { // Packed Structure type?
1753 std::vector<const Type*> Elements;
1754 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
1755 E = $3->end(); I != E; ++I) {
1756 Elements.push_back(I->T->get());
1759 $$.T = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1763 | '<' '{' '}' '>' { // Empty packed structure type?
1764 $$.T = new PATypeHolder(StructType::get(std::vector<const Type*>(),true));
1767 | UpRTypes '*' { // Pointer type?
1768 if ($1.T->get() == Type::LabelTy)
1769 error("Cannot form a pointer to a basic block");
1770 $$.T = new PATypeHolder(HandleUpRefs(PointerType::get($1.T->get())));
1776 // TypeList - Used for struct declarations and as a basis for function type
1777 // declaration type lists
1781 $$ = new std::list<PATypeInfo>();
1784 | TypeListI ',' UpRTypes {
1785 ($$=$1)->push_back($3);
1789 // ArgTypeList - List of types for a function type declaration...
1792 | TypeListI ',' DOTDOTDOT {
1794 VoidTI.T = new PATypeHolder(Type::VoidTy);
1795 VoidTI.S = Signless;
1796 ($$=$1)->push_back(VoidTI);
1799 $$ = new std::list<PATypeInfo>();
1801 VoidTI.T = new PATypeHolder(Type::VoidTy);
1802 VoidTI.S = Signless;
1803 $$->push_back(VoidTI);
1806 $$ = new std::list<PATypeInfo>();
1810 // ConstVal - The various declarations that go into the constant pool. This
1811 // production is used ONLY to represent constants that show up AFTER a 'const',
1812 // 'constant' or 'global' token at global scope. Constants that can be inlined
1813 // into other expressions (such as integers and constexprs) are handled by the
1814 // ResolvedVal, ValueRef and ConstValueRef productions.
1817 : Types '[' ConstVector ']' { // Nonempty unsized arr
1818 const ArrayType *ATy = dyn_cast<ArrayType>($1.T->get());
1820 error("Cannot make array constant with type: '" +
1821 $1.T->get()->getDescription() + "'");
1822 const Type *ETy = ATy->getElementType();
1823 int NumElements = ATy->getNumElements();
1825 // Verify that we have the correct size...
1826 if (NumElements != -1 && NumElements != (int)$3->size())
1827 error("Type mismatch: constant sized array initialized with " +
1828 utostr($3->size()) + " arguments, but has size of " +
1829 itostr(NumElements) + "");
1831 // Verify all elements are correct type!
1832 std::vector<Constant*> Elems;
1833 for (unsigned i = 0; i < $3->size(); i++) {
1834 Constant *C = (*$3)[i].C;
1835 const Type* ValTy = C->getType();
1837 error("Element #" + utostr(i) + " is not of type '" +
1838 ETy->getDescription() +"' as required!\nIt is of type '"+
1839 ValTy->getDescription() + "'");
1842 $$.C = ConstantArray::get(ATy, Elems);
1848 const ArrayType *ATy = dyn_cast<ArrayType>($1.T->get());
1850 error("Cannot make array constant with type: '" +
1851 $1.T->get()->getDescription() + "'");
1852 int NumElements = ATy->getNumElements();
1853 if (NumElements != -1 && NumElements != 0)
1854 error("Type mismatch: constant sized array initialized with 0"
1855 " arguments, but has size of " + itostr(NumElements) +"");
1856 $$.C = ConstantArray::get(ATy, std::vector<Constant*>());
1860 | Types 'c' STRINGCONSTANT {
1861 const ArrayType *ATy = dyn_cast<ArrayType>($1.T->get());
1863 error("Cannot make array constant with type: '" +
1864 $1.T->get()->getDescription() + "'");
1865 int NumElements = ATy->getNumElements();
1866 const Type *ETy = dyn_cast<IntegerType>(ATy->getElementType());
1867 if (!ETy || cast<IntegerType>(ETy)->getBitWidth() != 8)
1868 error("String arrays require type i8, not '" + ETy->getDescription() +
1870 char *EndStr = UnEscapeLexed($3, true);
1871 if (NumElements != -1 && NumElements != (EndStr-$3))
1872 error("Can't build string constant of size " +
1873 itostr((int)(EndStr-$3)) + " when array has size " +
1874 itostr(NumElements) + "");
1875 std::vector<Constant*> Vals;
1876 for (char *C = (char *)$3; C != (char *)EndStr; ++C)
1877 Vals.push_back(ConstantInt::get(ETy, *C));
1879 $$.C = ConstantArray::get(ATy, Vals);
1883 | Types '<' ConstVector '>' { // Nonempty unsized arr
1884 const PackedType *PTy = dyn_cast<PackedType>($1.T->get());
1886 error("Cannot make packed constant with type: '" +
1887 $1.T->get()->getDescription() + "'");
1888 const Type *ETy = PTy->getElementType();
1889 int NumElements = PTy->getNumElements();
1890 // Verify that we have the correct size...
1891 if (NumElements != -1 && NumElements != (int)$3->size())
1892 error("Type mismatch: constant sized packed initialized with " +
1893 utostr($3->size()) + " arguments, but has size of " +
1894 itostr(NumElements) + "");
1895 // Verify all elements are correct type!
1896 std::vector<Constant*> Elems;
1897 for (unsigned i = 0; i < $3->size(); i++) {
1898 Constant *C = (*$3)[i].C;
1899 const Type* ValTy = C->getType();
1901 error("Element #" + utostr(i) + " is not of type '" +
1902 ETy->getDescription() +"' as required!\nIt is of type '"+
1903 ValTy->getDescription() + "'");
1906 $$.C = ConstantPacked::get(PTy, Elems);
1911 | Types '{' ConstVector '}' {
1912 const StructType *STy = dyn_cast<StructType>($1.T->get());
1914 error("Cannot make struct constant with type: '" +
1915 $1.T->get()->getDescription() + "'");
1916 if ($3->size() != STy->getNumContainedTypes())
1917 error("Illegal number of initializers for structure type");
1919 // Check to ensure that constants are compatible with the type initializer!
1920 std::vector<Constant*> Fields;
1921 for (unsigned i = 0, e = $3->size(); i != e; ++i) {
1922 Constant *C = (*$3)[i].C;
1923 if (C->getType() != STy->getElementType(i))
1924 error("Expected type '" + STy->getElementType(i)->getDescription() +
1925 "' for element #" + utostr(i) + " of structure initializer");
1926 Fields.push_back(C);
1928 $$.C = ConstantStruct::get(STy, Fields);
1934 const StructType *STy = dyn_cast<StructType>($1.T->get());
1936 error("Cannot make struct constant with type: '" +
1937 $1.T->get()->getDescription() + "'");
1938 if (STy->getNumContainedTypes() != 0)
1939 error("Illegal number of initializers for structure type");
1940 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
1944 | Types '<' '{' ConstVector '}' '>' {
1945 const StructType *STy = dyn_cast<StructType>($1.T->get());
1947 error("Cannot make packed struct constant with type: '" +
1948 $1.T->get()->getDescription() + "'");
1949 if ($4->size() != STy->getNumContainedTypes())
1950 error("Illegal number of initializers for packed structure type");
1952 // Check to ensure that constants are compatible with the type initializer!
1953 std::vector<Constant*> Fields;
1954 for (unsigned i = 0, e = $4->size(); i != e; ++i) {
1955 Constant *C = (*$4)[i].C;
1956 if (C->getType() != STy->getElementType(i))
1957 error("Expected type '" + STy->getElementType(i)->getDescription() +
1958 "' for element #" + utostr(i) + " of packed struct initializer");
1959 Fields.push_back(C);
1961 $$.C = ConstantStruct::get(STy, Fields);
1966 | Types '<' '{' '}' '>' {
1967 const StructType *STy = dyn_cast<StructType>($1.T->get());
1969 error("Cannot make packed struct constant with type: '" +
1970 $1.T->get()->getDescription() + "'");
1971 if (STy->getNumContainedTypes() != 0)
1972 error("Illegal number of initializers for packed structure type");
1973 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
1978 const PointerType *PTy = dyn_cast<PointerType>($1.T->get());
1980 error("Cannot make null pointer constant with type: '" +
1981 $1.T->get()->getDescription() + "'");
1982 $$.C = ConstantPointerNull::get(PTy);
1987 $$.C = UndefValue::get($1.T->get());
1991 | Types SymbolicValueRef {
1992 const PointerType *Ty = dyn_cast<PointerType>($1.T->get());
1994 error("Global const reference must be a pointer type, not" +
1995 $1.T->get()->getDescription());
1997 // ConstExprs can exist in the body of a function, thus creating
1998 // GlobalValues whenever they refer to a variable. Because we are in
1999 // the context of a function, getExistingValue will search the functions
2000 // symbol table instead of the module symbol table for the global symbol,
2001 // which throws things all off. To get around this, we just tell
2002 // getExistingValue that we are at global scope here.
2004 Function *SavedCurFn = CurFun.CurrentFunction;
2005 CurFun.CurrentFunction = 0;
2006 Value *V = getExistingValue(Ty, $2);
2007 CurFun.CurrentFunction = SavedCurFn;
2009 // If this is an initializer for a constant pointer, which is referencing a
2010 // (currently) undefined variable, create a stub now that shall be replaced
2011 // in the future with the right type of variable.
2014 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers");
2015 const PointerType *PT = cast<PointerType>(Ty);
2017 // First check to see if the forward references value is already created!
2018 PerModuleInfo::GlobalRefsType::iterator I =
2019 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
2021 if (I != CurModule.GlobalRefs.end()) {
2022 V = I->second; // Placeholder already exists, use it...
2026 if ($2.Type == ValID::NameVal) Name = $2.Name;
2028 // Create the forward referenced global.
2030 if (const FunctionType *FTy =
2031 dyn_cast<FunctionType>(PT->getElementType())) {
2032 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
2033 CurModule.CurrentModule);
2035 GV = new GlobalVariable(PT->getElementType(), false,
2036 GlobalValue::ExternalLinkage, 0,
2037 Name, CurModule.CurrentModule);
2040 // Keep track of the fact that we have a forward ref to recycle it
2041 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
2045 $$.C = cast<GlobalValue>(V);
2047 delete $1.T; // Free the type handle
2050 if ($1.T->get() != $2.C->getType())
2051 error("Mismatched types for constant expression");
2056 | Types ZEROINITIALIZER {
2057 const Type *Ty = $1.T->get();
2058 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
2059 error("Cannot create a null initialized value of this type");
2060 $$.C = Constant::getNullValue(Ty);
2064 | SIntType EINT64VAL { // integral constants
2065 const Type *Ty = $1.T;
2066 if (!ConstantInt::isValueValidForType(Ty, $2))
2067 error("Constant value doesn't fit in type");
2068 $$.C = ConstantInt::get(Ty, $2);
2071 | UIntType EUINT64VAL { // integral constants
2072 const Type *Ty = $1.T;
2073 if (!ConstantInt::isValueValidForType(Ty, $2))
2074 error("Constant value doesn't fit in type");
2075 $$.C = ConstantInt::get(Ty, $2);
2078 | BOOL TRUETOK { // Boolean constants
2079 $$.C = ConstantInt::get(Type::Int1Ty, true);
2082 | BOOL FALSETOK { // Boolean constants
2083 $$.C = ConstantInt::get(Type::Int1Ty, false);
2086 | FPType FPVAL { // Float & Double constants
2087 if (!ConstantFP::isValueValidForType($1.T, $2))
2088 error("Floating point constant invalid for type");
2089 $$.C = ConstantFP::get($1.T, $2);
2095 : CastOps '(' ConstVal TO Types ')' {
2096 const Type* SrcTy = $3.C->getType();
2097 const Type* DstTy = $5.T->get();
2098 Signedness SrcSign = $3.S;
2099 Signedness DstSign = $5.S;
2100 if (!SrcTy->isFirstClassType())
2101 error("cast constant expression from a non-primitive type: '" +
2102 SrcTy->getDescription() + "'");
2103 if (!DstTy->isFirstClassType())
2104 error("cast constant expression to a non-primitive type: '" +
2105 DstTy->getDescription() + "'");
2106 $$.C = cast<Constant>(getCast($1, $3.C, SrcSign, DstTy, DstSign));
2110 | GETELEMENTPTR '(' ConstVal IndexList ')' {
2111 const Type *Ty = $3.C->getType();
2112 if (!isa<PointerType>(Ty))
2113 error("GetElementPtr requires a pointer operand");
2115 std::vector<Value*> VIndices;
2116 std::vector<Constant*> CIndices;
2117 upgradeGEPIndices($3.C->getType(), $4, VIndices, &CIndices);
2120 $$.C = ConstantExpr::getGetElementPtr($3.C, CIndices);
2123 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2124 if (!$3.C->getType()->isInteger() ||
2125 cast<IntegerType>($3.C->getType())->getBitWidth() != 1)
2126 error("Select condition must be bool type");
2127 if ($5.C->getType() != $7.C->getType())
2128 error("Select operand types must match");
2129 $$.C = ConstantExpr::getSelect($3.C, $5.C, $7.C);
2132 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
2133 const Type *Ty = $3.C->getType();
2134 if (Ty != $5.C->getType())
2135 error("Binary operator types must match");
2136 // First, make sure we're dealing with the right opcode by upgrading from
2137 // obsolete versions.
2138 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2140 // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
2141 // To retain backward compatibility with these early compilers, we emit a
2142 // cast to the appropriate integer type automatically if we are in the
2143 // broken case. See PR424 for more information.
2144 if (!isa<PointerType>(Ty)) {
2145 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2147 const Type *IntPtrTy = 0;
2148 switch (CurModule.CurrentModule->getPointerSize()) {
2149 case Module::Pointer32: IntPtrTy = Type::Int32Ty; break;
2150 case Module::Pointer64: IntPtrTy = Type::Int64Ty; break;
2151 default: error("invalid pointer binary constant expr");
2153 $$.C = ConstantExpr::get(Opcode,
2154 ConstantExpr::getCast(Instruction::PtrToInt, $3.C, IntPtrTy),
2155 ConstantExpr::getCast(Instruction::PtrToInt, $5.C, IntPtrTy));
2156 $$.C = ConstantExpr::getCast(Instruction::IntToPtr, $$.C, Ty);
2160 | LogicalOps '(' ConstVal ',' ConstVal ')' {
2161 const Type* Ty = $3.C->getType();
2162 if (Ty != $5.C->getType())
2163 error("Logical operator types must match");
2164 if (!Ty->isInteger()) {
2165 if (!isa<PackedType>(Ty) ||
2166 !cast<PackedType>(Ty)->getElementType()->isInteger())
2167 error("Logical operator requires integer operands");
2169 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2170 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2173 | SetCondOps '(' ConstVal ',' ConstVal ')' {
2174 const Type* Ty = $3.C->getType();
2175 if (Ty != $5.C->getType())
2176 error("setcc operand types must match");
2177 unsigned short pred;
2178 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $3.S);
2179 $$.C = ConstantExpr::getCompare(Opcode, $3.C, $5.C);
2182 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
2183 if ($4.C->getType() != $6.C->getType())
2184 error("icmp operand types must match");
2185 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2188 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
2189 if ($4.C->getType() != $6.C->getType())
2190 error("fcmp operand types must match");
2191 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2194 | ShiftOps '(' ConstVal ',' ConstVal ')' {
2195 if (!$5.C->getType()->isInteger() ||
2196 cast<IntegerType>($5.C->getType())->getBitWidth() != 8)
2197 error("Shift count for shift constant must be unsigned byte");
2198 if (!$3.C->getType()->isInteger())
2199 error("Shift constant expression requires integer operand");
2200 $$.C = ConstantExpr::get(getOtherOp($1, $3.S), $3.C, $5.C);
2203 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
2204 if (!ExtractElementInst::isValidOperands($3.C, $5.C))
2205 error("Invalid extractelement operands");
2206 $$.C = ConstantExpr::getExtractElement($3.C, $5.C);
2209 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2210 if (!InsertElementInst::isValidOperands($3.C, $5.C, $7.C))
2211 error("Invalid insertelement operands");
2212 $$.C = ConstantExpr::getInsertElement($3.C, $5.C, $7.C);
2215 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2216 if (!ShuffleVectorInst::isValidOperands($3.C, $5.C, $7.C))
2217 error("Invalid shufflevector operands");
2218 $$.C = ConstantExpr::getShuffleVector($3.C, $5.C, $7.C);
2224 // ConstVector - A list of comma separated constants.
2226 : ConstVector ',' ConstVal { ($$ = $1)->push_back($3); }
2228 $$ = new std::vector<ConstInfo>();
2234 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
2236 : GLOBAL { $$ = false; }
2237 | CONSTANT { $$ = true; }
2241 //===----------------------------------------------------------------------===//
2242 // Rules to match Modules
2243 //===----------------------------------------------------------------------===//
2245 // Module rule: Capture the result of parsing the whole file into a result
2250 $$ = ParserResult = $1;
2251 CurModule.ModuleDone();
2255 // FunctionList - A list of functions, preceeded by a constant pool.
2258 : FunctionList Function { $$ = $1; CurFun.FunctionDone(); }
2259 | FunctionList FunctionProto { $$ = $1; }
2260 | FunctionList MODULE ASM_TOK AsmBlock { $$ = $1; }
2261 | FunctionList IMPLEMENTATION { $$ = $1; }
2263 $$ = CurModule.CurrentModule;
2264 // Emit an error if there are any unresolved types left.
2265 if (!CurModule.LateResolveTypes.empty()) {
2266 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
2267 if (DID.Type == ValID::NameVal) {
2268 error("Reference to an undefined type: '"+DID.getName() + "'");
2270 error("Reference to an undefined type: #" + itostr(DID.Num));
2276 // ConstPool - Constants with optional names assigned to them.
2278 : ConstPool OptAssign TYPE TypesV {
2279 // Eagerly resolve types. This is not an optimization, this is a
2280 // requirement that is due to the fact that we could have this:
2282 // %list = type { %list * }
2283 // %list = type { %list * } ; repeated type decl
2285 // If types are not resolved eagerly, then the two types will not be
2286 // determined to be the same type!
2288 const Type* Ty = $4.T->get();
2289 ResolveTypeTo($2, Ty);
2291 if (!setTypeName(Ty, $2) && !$2) {
2292 // If this is a named type that is not a redefinition, add it to the slot
2294 CurModule.Types.push_back(Ty);
2298 | ConstPool FunctionProto { // Function prototypes can be in const pool
2300 | ConstPool MODULE ASM_TOK AsmBlock { // Asm blocks can be in the const pool
2302 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
2304 error("Global value initializer is not a constant");
2305 CurGV = ParseGlobalVariable($2, $3, $4, $5.C->getType(), $5.C);
2306 } GlobalVarAttributes {
2309 | ConstPool OptAssign EXTERNAL GlobalType Types {
2310 const Type *Ty = $5.T->get();
2311 CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, Ty, 0);
2313 } GlobalVarAttributes {
2316 | ConstPool OptAssign DLLIMPORT GlobalType Types {
2317 const Type *Ty = $5.T->get();
2318 CurGV = ParseGlobalVariable($2, GlobalValue::DLLImportLinkage, $4, Ty, 0);
2320 } GlobalVarAttributes {
2323 | ConstPool OptAssign EXTERN_WEAK GlobalType Types {
2324 const Type *Ty = $5.T->get();
2326 ParseGlobalVariable($2, GlobalValue::ExternalWeakLinkage, $4, Ty, 0);
2328 } GlobalVarAttributes {
2331 | ConstPool TARGET TargetDefinition {
2333 | ConstPool DEPLIBS '=' LibrariesDefinition {
2335 | /* empty: end of list */ {
2341 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2342 char *EndStr = UnEscapeLexed($1, true);
2343 std::string NewAsm($1, EndStr);
2346 if (AsmSoFar.empty())
2347 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
2349 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
2354 : BIG { $$ = Module::BigEndian; };
2355 | LITTLE { $$ = Module::LittleEndian; }
2359 : ENDIAN '=' BigOrLittle {
2360 CurModule.setEndianness($3);
2362 | POINTERSIZE '=' EUINT64VAL {
2364 CurModule.setPointerSize(Module::Pointer32);
2366 CurModule.setPointerSize(Module::Pointer64);
2368 error("Invalid pointer size: '" + utostr($3) + "'");
2370 | TRIPLE '=' STRINGCONSTANT {
2371 CurModule.CurrentModule->setTargetTriple($3);
2374 | DATALAYOUT '=' STRINGCONSTANT {
2375 CurModule.CurrentModule->setDataLayout($3);
2385 : LibList ',' STRINGCONSTANT {
2386 CurModule.CurrentModule->addLibrary($3);
2390 CurModule.CurrentModule->addLibrary($1);
2393 | /* empty: end of list */ { }
2396 //===----------------------------------------------------------------------===//
2397 // Rules to match Function Headers
2398 //===----------------------------------------------------------------------===//
2401 : VAR_ID | STRINGCONSTANT
2406 | /*empty*/ { $$ = 0; }
2411 if ($1.T->get() == Type::VoidTy)
2412 error("void typed arguments are invalid");
2413 $$ = new std::pair<PATypeInfo, char*>($1, $2);
2418 : ArgListH ',' ArgVal {
2424 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2431 : ArgListH { $$ = $1; }
2432 | ArgListH ',' DOTDOTDOT {
2435 VoidTI.T = new PATypeHolder(Type::VoidTy);
2436 VoidTI.S = Signless;
2437 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2440 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2442 VoidTI.T = new PATypeHolder(Type::VoidTy);
2443 VoidTI.S = Signless;
2444 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2446 | /* empty */ { $$ = 0; }
2450 : OptCallingConv TypesV Name '(' ArgList ')' OptSection OptAlign {
2452 std::string FunctionName($3);
2453 free($3); // Free strdup'd memory!
2455 const Type* RetTy = $2.T->get();
2457 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
2458 error("LLVM functions cannot return aggregate types");
2460 std::vector<const Type*> ParamTypeList;
2462 // In LLVM 2.0 the signatures of three varargs intrinsics changed to take
2463 // i8*. We check here for those names and override the parameter list
2464 // types to ensure the prototype is correct.
2465 if (FunctionName == "llvm.va_start" || FunctionName == "llvm.va_end") {
2466 ParamTypeList.push_back(PointerType::get(Type::Int8Ty));
2467 } else if (FunctionName == "llvm.va_copy") {
2468 ParamTypeList.push_back(PointerType::get(Type::Int8Ty));
2469 ParamTypeList.push_back(PointerType::get(Type::Int8Ty));
2470 } else if ($5) { // If there are arguments...
2471 for (std::vector<std::pair<PATypeInfo,char*> >::iterator
2472 I = $5->begin(), E = $5->end(); I != E; ++I) {
2473 const Type *Ty = I->first.T->get();
2474 ParamTypeList.push_back(Ty);
2479 ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2480 if (isVarArg) ParamTypeList.pop_back();
2482 const FunctionType *FT = FunctionType::get(RetTy, ParamTypeList, isVarArg);
2483 const PointerType *PFT = PointerType::get(FT);
2487 if (!FunctionName.empty()) {
2488 ID = ValID::create((char*)FunctionName.c_str());
2490 ID = ValID::create((int)CurModule.Values[PFT].size());
2494 // See if this function was forward referenced. If so, recycle the object.
2495 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2496 // Move the function to the end of the list, from whereever it was
2497 // previously inserted.
2498 Fn = cast<Function>(FWRef);
2499 CurModule.CurrentModule->getFunctionList().remove(Fn);
2500 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2501 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2502 (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
2503 // If this is the case, either we need to be a forward decl, or it needs
2505 if (!CurFun.isDeclare && !Fn->isExternal())
2506 error("Redefinition of function '" + FunctionName + "'");
2508 // Make sure to strip off any argument names so we can't get conflicts.
2509 if (Fn->isExternal())
2510 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2513 } else { // Not already defined?
2514 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
2515 CurModule.CurrentModule);
2517 InsertValue(Fn, CurModule.Values);
2520 CurFun.FunctionStart(Fn);
2522 if (CurFun.isDeclare) {
2523 // If we have declaration, always overwrite linkage. This will allow us
2524 // to correctly handle cases, when pointer to function is passed as
2525 // argument to another function.
2526 Fn->setLinkage(CurFun.Linkage);
2528 Fn->setCallingConv($1);
2529 Fn->setAlignment($8);
2535 // Add all of the arguments we parsed to the function...
2536 if ($5) { // Is null if empty...
2537 if (isVarArg) { // Nuke the last entry
2538 assert($5->back().first.T->get() == Type::VoidTy &&
2539 $5->back().second == 0 && "Not a varargs marker");
2540 delete $5->back().first.T;
2541 $5->pop_back(); // Delete the last entry
2543 Function::arg_iterator ArgIt = Fn->arg_begin();
2544 for (std::vector<std::pair<PATypeInfo,char*> >::iterator
2545 I = $5->begin(), E = $5->end(); I != E; ++I, ++ArgIt) {
2546 delete I->first.T; // Delete the typeholder...
2547 setValueName(ArgIt, I->second); // Insert arg into symtab...
2550 delete $5; // We're now done with the argument list
2556 : BEGINTOK | '{' // Allow BEGIN or '{' to start a function
2560 : OptLinkage FunctionHeaderH BEGIN {
2561 $$ = CurFun.CurrentFunction;
2563 // Make sure that we keep track of the linkage type even if there was a
2564 // previous "declare".
2570 : ENDTOK | '}' // Allow end of '}' to end a function
2574 : BasicBlockList END {
2580 | DLLIMPORT { CurFun.Linkage = GlobalValue::DLLImportLinkage; }
2581 | EXTERN_WEAK { CurFun.Linkage = GlobalValue::ExternalWeakLinkage; }
2585 : DECLARE { CurFun.isDeclare = true; } FnDeclareLinkage FunctionHeaderH {
2586 $$ = CurFun.CurrentFunction;
2587 CurFun.FunctionDone();
2592 //===----------------------------------------------------------------------===//
2593 // Rules to match Basic Blocks
2594 //===----------------------------------------------------------------------===//
2597 : /* empty */ { $$ = false; }
2598 | SIDEEFFECT { $$ = true; }
2602 // A reference to a direct constant
2603 : ESINT64VAL { $$ = ValID::create($1); }
2604 | EUINT64VAL { $$ = ValID::create($1); }
2605 | FPVAL { $$ = ValID::create($1); }
2606 | TRUETOK { $$ = ValID::create(ConstantInt::get(Type::Int1Ty, true)); }
2607 | FALSETOK { $$ = ValID::create(ConstantInt::get(Type::Int1Ty, false)); }
2608 | NULL_TOK { $$ = ValID::createNull(); }
2609 | UNDEF { $$ = ValID::createUndef(); }
2610 | ZEROINITIALIZER { $$ = ValID::createZeroInit(); }
2611 | '<' ConstVector '>' { // Nonempty unsized packed vector
2612 const Type *ETy = (*$2)[0].C->getType();
2613 int NumElements = $2->size();
2614 PackedType* pt = PackedType::get(ETy, NumElements);
2615 PATypeHolder* PTy = new PATypeHolder(
2616 HandleUpRefs(PackedType::get(ETy, NumElements)));
2618 // Verify all elements are correct type!
2619 std::vector<Constant*> Elems;
2620 for (unsigned i = 0; i < $2->size(); i++) {
2621 Constant *C = (*$2)[i].C;
2622 const Type *CTy = C->getType();
2624 error("Element #" + utostr(i) + " is not of type '" +
2625 ETy->getDescription() +"' as required!\nIt is of type '" +
2626 CTy->getDescription() + "'");
2629 $$ = ValID::create(ConstantPacked::get(pt, Elems));
2630 delete PTy; delete $2;
2633 $$ = ValID::create($1.C);
2635 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2636 char *End = UnEscapeLexed($3, true);
2637 std::string AsmStr = std::string($3, End);
2638 End = UnEscapeLexed($5, true);
2639 std::string Constraints = std::string($5, End);
2640 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2646 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2650 : INTVAL { $$ = ValID::create($1); }
2651 | Name { $$ = ValID::create($1); }
2654 // ValueRef - A reference to a definition... either constant or symbolic
2656 : SymbolicValueRef | ConstValueRef
2660 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2661 // type immediately preceeds the value reference, and allows complex constant
2662 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2665 const Type *Ty = $1.T->get();
2667 $$.V = getVal(Ty, $2);
2673 : BasicBlockList BasicBlock {
2676 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2681 // Basic blocks are terminated by branching instructions:
2682 // br, br/cc, switch, ret
2685 : InstructionList OptAssign BBTerminatorInst {
2686 setValueName($3, $2);
2688 $1->getInstList().push_back($3);
2695 : InstructionList Inst {
2697 $1->getInstList().push_back($2.I);
2701 $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
2702 // Make sure to move the basic block to the correct location in the
2703 // function, instead of leaving it inserted wherever it was first
2705 Function::BasicBlockListType &BBL =
2706 CurFun.CurrentFunction->getBasicBlockList();
2707 BBL.splice(BBL.end(), BBL, $$);
2710 $$ = CurBB = getBBVal(ValID::create($1), true);
2711 // Make sure to move the basic block to the correct location in the
2712 // function, instead of leaving it inserted wherever it was first
2714 Function::BasicBlockListType &BBL =
2715 CurFun.CurrentFunction->getBasicBlockList();
2716 BBL.splice(BBL.end(), BBL, $$);
2720 Unwind : UNWIND | EXCEPT;
2723 : RET ResolvedVal { // Return with a result...
2724 $$ = new ReturnInst($2.V);
2726 | RET VOID { // Return with no result...
2727 $$ = new ReturnInst();
2729 | BR LABEL ValueRef { // Unconditional Branch...
2730 BasicBlock* tmpBB = getBBVal($3);
2731 $$ = new BranchInst(tmpBB);
2732 } // Conditional Branch...
2733 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2734 BasicBlock* tmpBBA = getBBVal($6);
2735 BasicBlock* tmpBBB = getBBVal($9);
2736 Value* tmpVal = getVal(Type::Int1Ty, $3);
2737 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2739 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2740 Value* tmpVal = getVal($2.T, $3);
2741 BasicBlock* tmpBB = getBBVal($6);
2742 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2744 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2746 for (; I != E; ++I) {
2747 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2748 S->addCase(CI, I->second);
2750 error("Switch case is constant, but not a simple integer");
2754 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2755 Value* tmpVal = getVal($2.T, $3);
2756 BasicBlock* tmpBB = getBBVal($6);
2757 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2760 | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
2761 TO LABEL ValueRef Unwind LABEL ValueRef {
2762 const PointerType *PFTy;
2763 const FunctionType *Ty;
2765 if (!(PFTy = dyn_cast<PointerType>($3.T->get())) ||
2766 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2767 // Pull out the types of all of the arguments...
2768 std::vector<const Type*> ParamTypes;
2770 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
2772 ParamTypes.push_back((*I).V->getType());
2774 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2775 if (isVarArg) ParamTypes.pop_back();
2776 Ty = FunctionType::get($3.T->get(), ParamTypes, isVarArg);
2777 PFTy = PointerType::get(Ty);
2779 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2780 BasicBlock *Normal = getBBVal($10);
2781 BasicBlock *Except = getBBVal($13);
2783 // Create the call node...
2784 if (!$6) { // Has no arguments?
2785 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
2786 } else { // Has arguments?
2787 // Loop through FunctionType's arguments and ensure they are specified
2790 FunctionType::param_iterator I = Ty->param_begin();
2791 FunctionType::param_iterator E = Ty->param_end();
2792 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
2794 std::vector<Value*> Args;
2795 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2796 if ((*ArgI).V->getType() != *I)
2797 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
2798 (*I)->getDescription() + "'");
2799 Args.push_back((*ArgI).V);
2802 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2803 error("Invalid number of parameters detected");
2805 $$ = new InvokeInst(V, Normal, Except, Args);
2807 cast<InvokeInst>($$)->setCallingConv($2);
2812 $$ = new UnwindInst();
2815 $$ = new UnreachableInst();
2820 : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2822 Constant *V = cast<Constant>(getExistingValue($2.T, $3));
2825 error("May only switch on a constant pool value");
2827 BasicBlock* tmpBB = getBBVal($6);
2828 $$->push_back(std::make_pair(V, tmpBB));
2830 | IntType ConstValueRef ',' LABEL ValueRef {
2831 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2832 Constant *V = cast<Constant>(getExistingValue($1.T, $2));
2835 error("May only switch on a constant pool value");
2837 BasicBlock* tmpBB = getBBVal($5);
2838 $$->push_back(std::make_pair(V, tmpBB));
2843 : OptAssign InstVal {
2846 if (BitCastInst *BCI = dyn_cast<BitCastInst>($2.I))
2847 if (BCI->getSrcTy() == BCI->getDestTy() &&
2848 BCI->getOperand(0)->getName() == $1)
2849 // This is a useless bit cast causing a name redefinition. It is
2850 // a bit cast from a type to the same type of an operand with the
2851 // same name as the name we would give this instruction. Since this
2852 // instruction results in no code generation, it is safe to omit
2853 // the instruction. This situation can occur because of collapsed
2854 // type planes. For example:
2855 // %X = add int %Y, %Z
2856 // %X = cast int %Y to uint
2857 // After upgrade, this looks like:
2858 // %X = add i32 %Y, %Z
2859 // %X = bitcast i32 to i32
2860 // The bitcast is clearly useless so we omit it.
2866 setValueName($2.I, $1);
2872 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2873 $$.P = new std::list<std::pair<Value*, BasicBlock*> >();
2875 Value* tmpVal = getVal($1.T->get(), $3);
2876 BasicBlock* tmpBB = getBBVal($5);
2877 $$.P->push_back(std::make_pair(tmpVal, tmpBB));
2880 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2882 Value* tmpVal = getVal($1.P->front().first->getType(), $4);
2883 BasicBlock* tmpBB = getBBVal($6);
2884 $1.P->push_back(std::make_pair(tmpVal, tmpBB));
2888 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
2889 $$ = new std::vector<ValueInfo>();
2892 | ValueRefList ',' ResolvedVal {
2897 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
2900 | /*empty*/ { $$ = 0; }
2913 : ArithmeticOps Types ValueRef ',' ValueRef {
2914 const Type* Ty = $2.T->get();
2915 if (!Ty->isInteger() && !Ty->isFloatingPoint() && !isa<PackedType>(Ty))
2916 error("Arithmetic operator requires integer, FP, or packed operands");
2917 if (isa<PackedType>(Ty) &&
2918 ($1 == URemOp || $1 == SRemOp || $1 == FRemOp || $1 == RemOp))
2919 error("Remainder not supported on packed types");
2920 // Upgrade the opcode from obsolete versions before we do anything with it.
2921 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
2922 Value* val1 = getVal(Ty, $3);
2923 Value* val2 = getVal(Ty, $5);
2924 $$.I = BinaryOperator::create(Opcode, val1, val2);
2926 error("binary operator returned null");
2930 | LogicalOps Types ValueRef ',' ValueRef {
2931 const Type *Ty = $2.T->get();
2932 if (!Ty->isInteger()) {
2933 if (!isa<PackedType>(Ty) ||
2934 !cast<PackedType>(Ty)->getElementType()->isInteger())
2935 error("Logical operator requires integral operands");
2937 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
2938 Value* tmpVal1 = getVal(Ty, $3);
2939 Value* tmpVal2 = getVal(Ty, $5);
2940 $$.I = BinaryOperator::create(Opcode, tmpVal1, tmpVal2);
2942 error("binary operator returned null");
2946 | SetCondOps Types ValueRef ',' ValueRef {
2947 const Type* Ty = $2.T->get();
2948 if(isa<PackedType>(Ty))
2949 error("PackedTypes currently not supported in setcc instructions");
2950 unsigned short pred;
2951 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $2.S);
2952 Value* tmpVal1 = getVal(Ty, $3);
2953 Value* tmpVal2 = getVal(Ty, $5);
2954 $$.I = CmpInst::create(Opcode, pred, tmpVal1, tmpVal2);
2956 error("binary operator returned null");
2960 | ICMP IPredicates Types ValueRef ',' ValueRef {
2961 const Type *Ty = $3.T->get();
2962 if (isa<PackedType>(Ty))
2963 error("PackedTypes currently not supported in icmp instructions");
2964 else if (!Ty->isInteger() && !isa<PointerType>(Ty))
2965 error("icmp requires integer or pointer typed operands");
2966 Value* tmpVal1 = getVal(Ty, $4);
2967 Value* tmpVal2 = getVal(Ty, $6);
2968 $$.I = new ICmpInst($2, tmpVal1, tmpVal2);
2972 | FCMP FPredicates Types ValueRef ',' ValueRef {
2973 const Type *Ty = $3.T->get();
2974 if (isa<PackedType>(Ty))
2975 error("PackedTypes currently not supported in fcmp instructions");
2976 else if (!Ty->isFloatingPoint())
2977 error("fcmp instruction requires floating point operands");
2978 Value* tmpVal1 = getVal(Ty, $4);
2979 Value* tmpVal2 = getVal(Ty, $6);
2980 $$.I = new FCmpInst($2, tmpVal1, tmpVal2);
2985 warning("Use of obsolete 'not' instruction: Replacing with 'xor");
2986 const Type *Ty = $2.V->getType();
2987 Value *Ones = ConstantInt::getAllOnesValue(Ty);
2989 error("Expected integral type for not instruction");
2990 $$.I = BinaryOperator::create(Instruction::Xor, $2.V, Ones);
2992 error("Could not create a xor instruction");
2995 | ShiftOps ResolvedVal ',' ResolvedVal {
2996 if (!$4.V->getType()->isInteger() ||
2997 cast<IntegerType>($4.V->getType())->getBitWidth() != 8)
2998 error("Shift amount must be int8");
2999 if (!$2.V->getType()->isInteger())
3000 error("Shift constant expression requires integer operand");
3001 $$.I = new ShiftInst(getOtherOp($1, $2.S), $2.V, $4.V);
3004 | CastOps ResolvedVal TO Types {
3005 const Type *DstTy = $4.T->get();
3006 if (!DstTy->isFirstClassType())
3007 error("cast instruction to a non-primitive type: '" +
3008 DstTy->getDescription() + "'");
3009 $$.I = cast<Instruction>(getCast($1, $2.V, $2.S, DstTy, $4.S, true));
3013 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3014 if (!$2.V->getType()->isInteger() ||
3015 cast<IntegerType>($2.V->getType())->getBitWidth() != 1)
3016 error("select condition must be bool");
3017 if ($4.V->getType() != $6.V->getType())
3018 error("select value types should match");
3019 $$.I = new SelectInst($2.V, $4.V, $6.V);
3022 | VAARG ResolvedVal ',' Types {
3023 const Type *Ty = $4.T->get();
3025 $$.I = new VAArgInst($2.V, Ty);
3029 | VAARG_old ResolvedVal ',' Types {
3030 const Type* ArgTy = $2.V->getType();
3031 const Type* DstTy = $4.T->get();
3032 ObsoleteVarArgs = true;
3033 Function* NF = cast<Function>(CurModule.CurrentModule->
3034 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3037 //foo = alloca 1 of t
3041 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
3042 CurBB->getInstList().push_back(foo);
3043 CallInst* bar = new CallInst(NF, $2.V);
3044 CurBB->getInstList().push_back(bar);
3045 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3046 $$.I = new VAArgInst(foo, DstTy);
3050 | VANEXT_old ResolvedVal ',' Types {
3051 const Type* ArgTy = $2.V->getType();
3052 const Type* DstTy = $4.T->get();
3053 ObsoleteVarArgs = true;
3054 Function* NF = cast<Function>(CurModule.CurrentModule->
3055 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3057 //b = vanext a, t ->
3058 //foo = alloca 1 of t
3061 //tmp = vaarg foo, t
3063 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
3064 CurBB->getInstList().push_back(foo);
3065 CallInst* bar = new CallInst(NF, $2.V);
3066 CurBB->getInstList().push_back(bar);
3067 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3068 Instruction* tmp = new VAArgInst(foo, DstTy);
3069 CurBB->getInstList().push_back(tmp);
3070 $$.I = new LoadInst(foo);
3074 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
3075 if (!ExtractElementInst::isValidOperands($2.V, $4.V))
3076 error("Invalid extractelement operands");
3077 $$.I = new ExtractElementInst($2.V, $4.V);
3080 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3081 if (!InsertElementInst::isValidOperands($2.V, $4.V, $6.V))
3082 error("Invalid insertelement operands");
3083 $$.I = new InsertElementInst($2.V, $4.V, $6.V);
3086 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3087 if (!ShuffleVectorInst::isValidOperands($2.V, $4.V, $6.V))
3088 error("Invalid shufflevector operands");
3089 $$.I = new ShuffleVectorInst($2.V, $4.V, $6.V);
3093 const Type *Ty = $2.P->front().first->getType();
3094 if (!Ty->isFirstClassType())
3095 error("PHI node operands must be of first class type");
3096 PHINode *PHI = new PHINode(Ty);
3097 PHI->reserveOperandSpace($2.P->size());
3098 while ($2.P->begin() != $2.P->end()) {
3099 if ($2.P->front().first->getType() != Ty)
3100 error("All elements of a PHI node must be of the same type");
3101 PHI->addIncoming($2.P->front().first, $2.P->front().second);
3106 delete $2.P; // Free the list...
3108 | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')' {
3110 // Handle the short call syntax
3111 const PointerType *PFTy;
3112 const FunctionType *FTy;
3113 if (!(PFTy = dyn_cast<PointerType>($3.T->get())) ||
3114 !(FTy = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3115 // Pull out the types of all of the arguments...
3116 std::vector<const Type*> ParamTypes;
3118 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
3120 ParamTypes.push_back((*I).V->getType());
3123 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
3124 if (isVarArg) ParamTypes.pop_back();
3126 const Type *RetTy = $3.T->get();
3127 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
3128 error("Functions cannot return aggregate types");
3130 FTy = FunctionType::get(RetTy, ParamTypes, isVarArg);
3131 PFTy = PointerType::get(FTy);
3134 // First upgrade any intrinsic calls.
3135 std::vector<Value*> Args;
3137 for (unsigned i = 0, e = $6->size(); i < e; ++i)
3138 Args.push_back((*$6)[i].V);
3139 Instruction *Inst = upgradeIntrinsicCall(FTy, $4, Args);
3141 // If we got an upgraded intrinsic
3146 // Get the function we're calling
3147 Value *V = getVal(PFTy, $4);
3149 // Check the argument values match
3150 if (!$6) { // Has no arguments?
3151 // Make sure no arguments is a good thing!
3152 if (FTy->getNumParams() != 0)
3153 error("No arguments passed to a function that expects arguments");
3154 } else { // Has arguments?
3155 // Loop through FunctionType's arguments and ensure they are specified
3158 FunctionType::param_iterator I = FTy->param_begin();
3159 FunctionType::param_iterator E = FTy->param_end();
3160 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
3162 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
3163 if ((*ArgI).V->getType() != *I)
3164 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
3165 (*I)->getDescription() + "'");
3167 if (I != E || (ArgI != ArgE && !FTy->isVarArg()))
3168 error("Invalid number of parameters detected");
3171 // Create the call instruction
3172 CallInst *CI = new CallInst(V, Args);
3173 CI->setTailCall($1);
3174 CI->setCallingConv($2);
3187 // IndexList - List of indices for GEP based instructions...
3189 : ',' ValueRefList { $$ = $2; }
3190 | /* empty */ { $$ = new std::vector<ValueInfo>(); }
3194 : VOLATILE { $$ = true; }
3195 | /* empty */ { $$ = false; }
3199 : MALLOC Types OptCAlign {
3200 const Type *Ty = $2.T->get();
3202 $$.I = new MallocInst(Ty, 0, $3);
3205 | MALLOC Types ',' UINT ValueRef OptCAlign {
3206 const Type *Ty = $2.T->get();
3208 $$.I = new MallocInst(Ty, getVal($4.T, $5), $6);
3211 | ALLOCA Types OptCAlign {
3212 const Type *Ty = $2.T->get();
3214 $$.I = new AllocaInst(Ty, 0, $3);
3217 | ALLOCA Types ',' UINT ValueRef OptCAlign {
3218 const Type *Ty = $2.T->get();
3220 $$.I = new AllocaInst(Ty, getVal($4.T, $5), $6);
3223 | FREE ResolvedVal {
3224 const Type *PTy = $2.V->getType();
3225 if (!isa<PointerType>(PTy))
3226 error("Trying to free nonpointer type '" + PTy->getDescription() + "'");
3227 $$.I = new FreeInst($2.V);
3230 | OptVolatile LOAD Types ValueRef {
3231 const Type* Ty = $3.T->get();
3233 if (!isa<PointerType>(Ty))
3234 error("Can't load from nonpointer type: " + Ty->getDescription());
3235 if (!cast<PointerType>(Ty)->getElementType()->isFirstClassType())
3236 error("Can't load from pointer of non-first-class type: " +
3237 Ty->getDescription());
3238 Value* tmpVal = getVal(Ty, $4);
3239 $$.I = new LoadInst(tmpVal, "", $1);
3242 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
3243 const PointerType *PTy = dyn_cast<PointerType>($5.T->get());
3245 error("Can't store to a nonpointer type: " +
3246 $5.T->get()->getDescription());
3247 const Type *ElTy = PTy->getElementType();
3248 if (ElTy != $3.V->getType())
3249 error("Can't store '" + $3.V->getType()->getDescription() +
3250 "' into space of type '" + ElTy->getDescription() + "'");
3251 Value* tmpVal = getVal(PTy, $6);
3252 $$.I = new StoreInst($3.V, tmpVal, $1);
3256 | GETELEMENTPTR Types ValueRef IndexList {
3257 const Type* Ty = $2.T->get();
3258 if (!isa<PointerType>(Ty))
3259 error("getelementptr insn requires pointer operand");
3261 std::vector<Value*> VIndices;
3262 upgradeGEPIndices(Ty, $4, VIndices);
3264 Value* tmpVal = getVal(Ty, $3);
3265 $$.I = new GetElementPtrInst(tmpVal, VIndices);
3274 int yyerror(const char *ErrorMsg) {
3276 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3277 + ":" + llvm::utostr((unsigned) Upgradelineno-1) + ": ";
3278 std::string errMsg = where + "error: " + std::string(ErrorMsg);
3279 if (yychar != YYEMPTY && yychar != 0)
3280 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3282 std::cerr << "llvm-upgrade: " << errMsg << '\n';
3283 std::cout << "llvm-upgrade: parse failed.\n";
3287 void warning(const std::string& ErrorMsg) {
3289 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3290 + ":" + llvm::utostr((unsigned) Upgradelineno-1) + ": ";
3291 std::string errMsg = where + "warning: " + std::string(ErrorMsg);
3292 if (yychar != YYEMPTY && yychar != 0)
3293 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3295 std::cerr << "llvm-upgrade: " << errMsg << '\n';
3298 void error(const std::string& ErrorMsg, int LineNo) {
3299 if (LineNo == -1) LineNo = Upgradelineno;
3300 Upgradelineno = LineNo;
3301 yyerror(ErrorMsg.c_str());