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);
52 SignedType *SignedType::SByteTy = 0;
53 SignedType *SignedType::SShortTy = 0;
54 SignedType *SignedType::SIntTy = 0;
55 SignedType *SignedType::SLongTy = 0;
57 inline bool SignedType::classof(const Type *T) {
58 if (T->getTypeID() != IntegerTyID)
60 return (T == SByteTy || T == SShortTy || T == SIntTy || T == SLongTy );
63 SignedType::SignedType(const IntegerType* ITy)
64 : IntegerType(ITy->getBitWidth()), base_type(ITy)
68 const SignedType *SignedType::get(const IntegerType* ITy) {
69 if (ITy == Type::Int8Ty) {
71 SByteTy = new SignedType(IntegerType::get(8));
73 } else if (ITy == Type::Int16Ty) {
75 SShortTy = new SignedType(IntegerType::get(16));
77 } else if (ITy == Type::Int32Ty) {
79 SIntTy = new SignedType(IntegerType::get(32));
81 } else if (ITy == Type::Int64Ty) {
83 SLongTy = new SignedType(IntegerType::get(64));
86 assert(0 && "Invalid integer type for SignedType::get");
89 static inline Signedness getSign(const Type *&Ty) {
90 if (const SignedType *STy = dyn_cast<SignedType>(Ty)) {
91 Ty = STy->getBaseType();
93 } else if (isa<IntegerType>(Ty))
99 resolveTypeImpl(const Type* Ty, std::vector<const Type*>& TyStack)
101 // Nothing to resolve if it isn't a derived type
102 if (!Ty->isDerivedType())
105 // Prevent infinite recursion for recursive types
106 for (std::vector<const Type*>::const_iterator I = TyStack.begin(),
107 E = TyStack.end(); I != E; ++I)
111 // Okay, haven't seen this derived type yet, push it on the stack.
112 const Type* Result = Ty;
113 TyStack.push_back(Ty);
116 switch (Ty->getTypeID()) {
117 default: assert(0 && "Invalid derived type");
118 case Type::IntegerTyID:
120 case Type::FunctionTyID: {
121 const FunctionType* FTy = cast<FunctionType>(Ty);
122 const Type* RetTy = resolveTypeImpl(FTy->getReturnType(), TyStack);
123 std::vector<const Type*> Types;
124 FunctionType::ParamAttrsList Attrs;
125 Attrs.push_back(FTy->getParamAttrs(0));
126 for (unsigned i = 0; i < FTy->getNumParams(); ++i) {
127 Types.push_back(resolveTypeImpl(FTy->getParamType(i), TyStack));
128 Attrs.push_back(FTy->getParamAttrs(i+1));
130 Result = FunctionType::get(RetTy, Types, FTy->isVarArg(), Attrs);
133 case Type::StructTyID:
134 case Type::PackedStructTyID: {
135 const StructType *STy = cast<StructType>(Ty);
136 std::vector<const Type*> FieldTypes;
137 for (unsigned i = 0; i < STy->getNumElements(); ++i)
138 FieldTypes.push_back(resolveTypeImpl(STy->getElementType(i), TyStack));
139 Result = StructType::get(FieldTypes, STy->isPacked());
142 case Type::ArrayTyID: {
143 const ArrayType *ATy = cast<ArrayType>(Ty);
144 uint64_t NElems = ATy->getNumElements();
145 const Type *ElemTy = resolveTypeImpl(ATy->getElementType(), TyStack);
146 Result = ArrayType::get(ElemTy, NElems);
149 case Type::PointerTyID: {
150 const PointerType *PTy = cast<PointerType>(Ty);
151 const Type *ElemTy = resolveTypeImpl(PTy->getElementType(), TyStack);
152 Result = PointerType::get(ElemTy);
155 case Type::PackedTyID: {
156 const PackedType *PTy = cast<PackedType>(Ty);
157 unsigned NElems = PTy->getNumElements();
158 const Type *ElemTy = resolveTypeImpl(PTy->getElementType(), TyStack);
159 Result = PackedType::get(ElemTy, NElems);
163 // Done with it, pop it off.
168 static inline const Type* resolveType(const Type* Ty) {
171 if (const SignedType* STy = dyn_cast<SignedType>(Ty))
172 return STy->getBaseType();
173 std::vector<const Type*> TyStack;
174 return resolveTypeImpl(Ty, TyStack);
177 std::istream* LexInput;
178 static std::string CurFilename;
180 // This bool controls whether attributes are ever added to function declarations
181 // definitions and calls.
182 static bool AddAttributes = false;
184 static Module *ParserResult;
185 static bool ObsoleteVarArgs;
186 static bool NewVarArgs;
187 static BasicBlock *CurBB;
188 static GlobalVariable *CurGV;
192 // This contains info used when building the body of a function. It is
193 // destroyed when the function is completed.
195 typedef std::vector<Value *> ValueList; // Numbered defs
197 typedef std::pair<std::string,const Type*> RenameMapKey;
198 typedef std::map<RenameMapKey,std::string> RenameMapType;
201 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
202 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
204 static struct PerModuleInfo {
205 Module *CurrentModule;
206 std::map<const Type *, ValueList> Values; // Module level numbered definitions
207 std::map<const Type *,ValueList> LateResolveValues;
208 std::vector<PATypeHolder> Types;
209 std::map<ValID, PATypeHolder> LateResolveTypes;
210 static Module::Endianness Endian;
211 static Module::PointerSize PointerSize;
212 RenameMapType RenameMap;
214 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
215 /// how they were referenced and on which line of the input they came from so
216 /// that we can resolve them later and print error messages as appropriate.
217 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
219 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
220 // references to global values. Global values may be referenced before they
221 // are defined, and if so, the temporary object that they represent is held
222 // here. This is used for forward references of GlobalValues.
224 typedef std::map<std::pair<const PointerType *, ValID>, GlobalValue*>
226 GlobalRefsType GlobalRefs;
229 // If we could not resolve some functions at function compilation time
230 // (calls to functions before they are defined), resolve them now... Types
231 // are resolved when the constant pool has been completely parsed.
233 ResolveDefinitions(LateResolveValues);
235 // Check to make sure that all global value forward references have been
238 if (!GlobalRefs.empty()) {
239 std::string UndefinedReferences = "Unresolved global references exist:\n";
241 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
243 UndefinedReferences += " " + I->first.first->getDescription() + " " +
244 I->first.second.getName() + "\n";
246 error(UndefinedReferences);
250 if (CurrentModule->getDataLayout().empty()) {
251 std::string dataLayout;
252 if (Endian != Module::AnyEndianness)
253 dataLayout.append(Endian == Module::BigEndian ? "E" : "e");
254 if (PointerSize != Module::AnyPointerSize) {
255 if (!dataLayout.empty())
257 dataLayout.append(PointerSize == Module::Pointer64 ?
258 "p:64:64" : "p:32:32");
260 CurrentModule->setDataLayout(dataLayout);
263 Values.clear(); // Clear out function local definitions
268 // GetForwardRefForGlobal - Check to see if there is a forward reference
269 // for this global. If so, remove it from the GlobalRefs map and return it.
270 // If not, just return null.
271 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
272 // Check to see if there is a forward reference to this global variable...
273 // if there is, eliminate it and patch the reference to use the new def'n.
274 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
275 GlobalValue *Ret = 0;
276 if (I != GlobalRefs.end()) {
282 void setEndianness(Module::Endianness E) { Endian = E; }
283 void setPointerSize(Module::PointerSize sz) { PointerSize = sz; }
286 Module::Endianness PerModuleInfo::Endian = Module::AnyEndianness;
287 Module::PointerSize PerModuleInfo::PointerSize = Module::AnyPointerSize;
289 static struct PerFunctionInfo {
290 Function *CurrentFunction; // Pointer to current function being created
292 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
293 std::map<const Type*, ValueList> LateResolveValues;
294 bool isDeclare; // Is this function a forward declararation?
295 GlobalValue::LinkageTypes Linkage;// Linkage for forward declaration.
297 /// BBForwardRefs - When we see forward references to basic blocks, keep
298 /// track of them here.
299 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
300 std::vector<BasicBlock*> NumberedBlocks;
301 RenameMapType RenameMap;
302 std::set<Value*> SignedValues;
305 inline PerFunctionInfo() {
308 Linkage = GlobalValue::ExternalLinkage;
311 inline void FunctionStart(Function *M) {
316 void FunctionDone() {
317 NumberedBlocks.clear();
319 // Any forward referenced blocks left?
320 if (!BBForwardRefs.empty()) {
321 error("Undefined reference to label " +
322 BBForwardRefs.begin()->first->getName());
326 // Resolve all forward references now.
327 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
329 Values.clear(); // Clear out function local definitions
331 SignedValues.clear();
334 Linkage = GlobalValue::ExternalLinkage;
336 } CurFun; // Info for the current function...
338 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
341 //===----------------------------------------------------------------------===//
342 // Code to handle definitions of all the types
343 //===----------------------------------------------------------------------===//
345 static int InsertValue(Value *V,
346 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
347 if (V->hasName()) return -1; // Is this a numbered definition?
349 // Yes, insert the value into the value table...
350 ValueList &List = ValueTab[V->getType()];
352 return List.size()-1;
355 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
357 case ValID::NumberVal: // Is it a numbered definition?
358 // Module constants occupy the lowest numbered slots...
359 if ((unsigned)D.Num < CurModule.Types.size()) {
360 return CurModule.Types[(unsigned)D.Num];
363 case ValID::NameVal: // Is it a named definition?
364 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
365 D.destroy(); // Free old strdup'd memory...
370 error("Internal parser error: Invalid symbol type reference");
374 // If we reached here, we referenced either a symbol that we don't know about
375 // or an id number that hasn't been read yet. We may be referencing something
376 // forward, so just create an entry to be resolved later and get to it...
378 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
381 if (inFunctionScope()) {
382 if (D.Type == ValID::NameVal) {
383 error("Reference to an undefined type: '" + D.getName() + "'");
386 error("Reference to an undefined type: #" + itostr(D.Num));
391 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
392 if (I != CurModule.LateResolveTypes.end())
395 Type *Typ = OpaqueType::get();
396 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
400 // getExistingValue - Look up the value specified by the provided type and
401 // the provided ValID. If the value exists and has already been defined, return
402 // it. Otherwise return null.
404 static Value *getExistingValue(const Type *Ty, const ValID &D) {
405 if (isa<FunctionType>(Ty)) {
406 error("Functions are not values and must be referenced as pointers");
410 case ValID::NumberVal: { // Is it a numbered definition?
411 unsigned Num = (unsigned)D.Num;
413 // Module constants occupy the lowest numbered slots...
414 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
415 if (VI != CurModule.Values.end()) {
416 if (Num < VI->second.size())
417 return VI->second[Num];
418 Num -= VI->second.size();
421 // Make sure that our type is within bounds
422 VI = CurFun.Values.find(Ty);
423 if (VI == CurFun.Values.end()) return 0;
425 // Check that the number is within bounds...
426 if (VI->second.size() <= Num) return 0;
428 return VI->second[Num];
431 case ValID::NameVal: { // Is it a named definition?
432 // Get the name out of the ID
433 std::string Name(D.Name);
435 RenameMapKey Key = std::make_pair(Name, Ty);
436 if (inFunctionScope()) {
437 // See if the name was renamed
438 RenameMapType::const_iterator I = CurFun.RenameMap.find(Key);
439 std::string LookupName;
440 if (I != CurFun.RenameMap.end())
441 LookupName = I->second;
444 SymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
445 V = SymTab.lookup(Ty, LookupName);
448 RenameMapType::const_iterator I = CurModule.RenameMap.find(Key);
449 std::string LookupName;
450 if (I != CurModule.RenameMap.end())
451 LookupName = I->second;
454 V = CurModule.CurrentModule->getValueSymbolTable().lookup(Ty, LookupName);
459 D.destroy(); // Free old strdup'd memory...
463 // Check to make sure that "Ty" is an integral type, and that our
464 // value will fit into the specified type...
465 case ValID::ConstSIntVal: // Is it a constant pool reference??
466 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
467 error("Signed integral constant '" + itostr(D.ConstPool64) +
468 "' is invalid for type '" + Ty->getDescription() + "'");
470 return ConstantInt::get(Ty, D.ConstPool64);
472 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
473 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
474 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64))
475 error("Integral constant '" + utostr(D.UConstPool64) +
476 "' is invalid or out of range");
477 else // This is really a signed reference. Transmogrify.
478 return ConstantInt::get(Ty, D.ConstPool64);
480 return ConstantInt::get(Ty, D.UConstPool64);
482 case ValID::ConstFPVal: // Is it a floating point const pool reference?
483 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
484 error("FP constant invalid for type");
485 return ConstantFP::get(Ty, D.ConstPoolFP);
487 case ValID::ConstNullVal: // Is it a null value?
488 if (!isa<PointerType>(Ty))
489 error("Cannot create a a non pointer null");
490 return ConstantPointerNull::get(cast<PointerType>(Ty));
492 case ValID::ConstUndefVal: // Is it an undef value?
493 return UndefValue::get(Ty);
495 case ValID::ConstZeroVal: // Is it a zero value?
496 return Constant::getNullValue(Ty);
498 case ValID::ConstantVal: // Fully resolved constant?
499 if (D.ConstantValue->getType() != Ty)
500 error("Constant expression type different from required type");
501 return D.ConstantValue;
503 case ValID::InlineAsmVal: { // Inline asm expression
504 const PointerType *PTy = dyn_cast<PointerType>(Ty);
505 const FunctionType *FTy =
506 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
507 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints))
508 error("Invalid type for asm constraint string");
509 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
510 D.IAD->HasSideEffects);
511 D.destroy(); // Free InlineAsmDescriptor.
515 assert(0 && "Unhandled case");
519 assert(0 && "Unhandled case");
523 // getVal - This function is identical to getExistingValue, except that if a
524 // value is not already defined, it "improvises" by creating a placeholder var
525 // that looks and acts just like the requested variable. When the value is
526 // defined later, all uses of the placeholder variable are replaced with the
529 static Value *getVal(const Type *Ty, const ValID &ID) {
530 if (Ty == Type::LabelTy)
531 error("Cannot use a basic block here");
533 // See if the value has already been defined.
534 Value *V = getExistingValue(Ty, ID);
537 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty))
538 error("Invalid use of a composite type");
540 // If we reached here, we referenced either a symbol that we don't know about
541 // or an id number that hasn't been read yet. We may be referencing something
542 // forward, so just create an entry to be resolved later and get to it...
543 assert(!isa<SignedType>(Ty) && "Can't create value with SignedType");
544 V = new Argument(Ty);
546 // Remember where this forward reference came from. FIXME, shouldn't we try
547 // to recycle these things??
548 CurModule.PlaceHolderInfo.insert(
549 std::make_pair(V, std::make_pair(ID, Upgradelineno-1)));
551 if (inFunctionScope())
552 InsertValue(V, CurFun.LateResolveValues);
554 InsertValue(V, CurModule.LateResolveValues);
558 /// getBBVal - This is used for two purposes:
559 /// * If isDefinition is true, a new basic block with the specified ID is being
561 /// * If isDefinition is true, this is a reference to a basic block, which may
562 /// or may not be a forward reference.
564 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
565 assert(inFunctionScope() && "Can't get basic block at global scope");
571 error("Illegal label reference " + ID.getName());
573 case ValID::NumberVal: // Is it a numbered definition?
574 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
575 CurFun.NumberedBlocks.resize(ID.Num+1);
576 BB = CurFun.NumberedBlocks[ID.Num];
578 case ValID::NameVal: // Is it a named definition?
580 if (Value *N = CurFun.CurrentFunction->
581 getValueSymbolTable().lookup(Type::LabelTy, Name)) {
582 if (N->getType() != Type::LabelTy)
583 error("Name '" + Name + "' does not refer to a BasicBlock");
584 BB = cast<BasicBlock>(N);
589 // See if the block has already been defined.
591 // If this is the definition of the block, make sure the existing value was
592 // just a forward reference. If it was a forward reference, there will be
593 // an entry for it in the PlaceHolderInfo map.
594 if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
595 // The existing value was a definition, not a forward reference.
596 error("Redefinition of label " + ID.getName());
598 ID.destroy(); // Free strdup'd memory.
602 // Otherwise this block has not been seen before.
603 BB = new BasicBlock("", CurFun.CurrentFunction);
604 if (ID.Type == ValID::NameVal) {
605 BB->setName(ID.Name);
607 CurFun.NumberedBlocks[ID.Num] = BB;
610 // If this is not a definition, keep track of it so we can use it as a forward
613 // Remember where this forward reference came from.
614 CurFun.BBForwardRefs[BB] = std::make_pair(ID, Upgradelineno);
616 // The forward declaration could have been inserted anywhere in the
617 // function: insert it into the correct place now.
618 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
619 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
626 //===----------------------------------------------------------------------===//
627 // Code to handle forward references in instructions
628 //===----------------------------------------------------------------------===//
630 // This code handles the late binding needed with statements that reference
631 // values not defined yet... for example, a forward branch, or the PHI node for
634 // This keeps a table (CurFun.LateResolveValues) of all such forward references
635 // and back patchs after we are done.
638 // ResolveDefinitions - If we could not resolve some defs at parsing
639 // time (forward branches, phi functions for loops, etc...) resolve the
643 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
644 std::map<const Type*,ValueList> *FutureLateResolvers) {
645 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
646 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
647 E = LateResolvers.end(); LRI != E; ++LRI) {
648 ValueList &List = LRI->second;
649 while (!List.empty()) {
650 Value *V = List.back();
653 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
654 CurModule.PlaceHolderInfo.find(V);
655 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error");
657 ValID &DID = PHI->second.first;
659 Value *TheRealValue = getExistingValue(LRI->first, DID);
661 V->replaceAllUsesWith(TheRealValue);
663 CurModule.PlaceHolderInfo.erase(PHI);
664 } else if (FutureLateResolvers) {
665 // Functions have their unresolved items forwarded to the module late
667 InsertValue(V, *FutureLateResolvers);
669 if (DID.Type == ValID::NameVal) {
670 error("Reference to an invalid definition: '" +DID.getName()+
671 "' of type '" + V->getType()->getDescription() + "'",
675 error("Reference to an invalid definition: #" +
676 itostr(DID.Num) + " of type '" +
677 V->getType()->getDescription() + "'", PHI->second.second);
684 LateResolvers.clear();
687 // ResolveTypeTo - A brand new type was just declared. This means that (if
688 // name is not null) things referencing Name can be resolved. Otherwise, things
689 // refering to the number can be resolved. Do this now.
691 static void ResolveTypeTo(char *Name, const Type *ToTy) {
693 if (Name) D = ValID::create(Name);
694 else D = ValID::create((int)CurModule.Types.size());
696 std::map<ValID, PATypeHolder>::iterator I =
697 CurModule.LateResolveTypes.find(D);
698 if (I != CurModule.LateResolveTypes.end()) {
699 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
700 CurModule.LateResolveTypes.erase(I);
704 static std::string makeNameUnique(const std::string& Name) {
705 static unsigned UniqueNameCounter = 1;
706 std::string Result(Name);
707 Result += ".upgrd." + llvm::utostr(UniqueNameCounter++);
711 // setValueName - Set the specified value to the name given. The name may be
712 // null potentially, in which case this is a noop. The string passed in is
713 // assumed to be a malloc'd string buffer, and is free'd by this function.
715 static void setValueName(Value *V, char *NameStr) {
717 std::string Name(NameStr); // Copy string
718 free(NameStr); // Free old string
720 if (V->getType() == Type::VoidTy) {
721 error("Can't assign name '" + Name + "' to value with void type");
725 assert(!isa<SignedType>(V->getType()) && "Shouldn't have SignedType Value");
726 assert(inFunctionScope() && "Must be in function scope");
728 // Search the function's symbol table for an existing value of this name
730 SymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
731 SymbolTable::plane_const_iterator PI = ST.plane_begin(), PE =ST.plane_end();
732 for ( ; PI != PE; ++PI) {
733 SymbolTable::value_const_iterator VI = PI->second.find(Name);
734 if (VI != PI->second.end()) {
735 Existing = VI->second;
740 if (Existing->getType() == V->getType()) {
741 // The type of the Existing value and the new one are the same. This
742 // is probably a type plane collapsing error. If the types involved
743 // are both integer, just rename it. Otherwise it
744 // is a redefinition error.
745 if (!Existing->getType()->isInteger()) {
746 error("Redefinition of value named '" + Name + "' in the '" +
747 V->getType()->getDescription() + "' type plane");
751 // In LLVM 2.0 we don't allow names to be re-used for any values in a
752 // function, regardless of Type. Previously re-use of names was okay as
753 // long as they were distinct types. With type planes collapsing because
754 // of the signedness change and because of PR411, this can no longer be
755 // supported. We must search the entire symbol table for a conflicting
756 // name and make the name unique. No warning is needed as this can't
758 std::string NewName = makeNameUnique(Name);
759 // We're changing the name but it will probably be used by other
760 // instructions as operands later on. Consequently we have to retain
761 // a mapping of the renaming that we're doing.
762 RenameMapKey Key = std::make_pair(Name,V->getType());
763 CurFun.RenameMap[Key] = NewName;
772 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
773 /// this is a declaration, otherwise it is a definition.
774 static GlobalVariable *
775 ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
776 bool isConstantGlobal, const Type *Ty,
777 Constant *Initializer) {
778 if (isa<FunctionType>(Ty))
779 error("Cannot declare global vars of function type");
781 const PointerType *PTy = PointerType::get(Ty);
785 Name = NameStr; // Copy string
786 free(NameStr); // Free old string
789 // See if this global value was forward referenced. If so, recycle the
793 ID = ValID::create((char*)Name.c_str());
795 ID = ValID::create((int)CurModule.Values[PTy].size());
798 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
799 // Move the global to the end of the list, from whereever it was
800 // previously inserted.
801 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
802 CurModule.CurrentModule->getGlobalList().remove(GV);
803 CurModule.CurrentModule->getGlobalList().push_back(GV);
804 GV->setInitializer(Initializer);
805 GV->setLinkage(Linkage);
806 GV->setConstant(isConstantGlobal);
807 InsertValue(GV, CurModule.Values);
811 // If this global has a name, check to see if there is already a definition
812 // of this global in the module and emit warnings if there are conflicts.
814 // The global has a name. See if there's an existing one of the same name.
815 if (CurModule.CurrentModule->getNamedGlobal(Name)) {
816 // We found an existing global ov the same name. This isn't allowed
817 // in LLVM 2.0. Consequently, we must alter the name of the global so it
818 // can at least compile. This can happen because of type planes
819 // There is alread a global of the same name which means there is a
820 // conflict. Let's see what we can do about it.
821 std::string NewName(makeNameUnique(Name));
822 if (Linkage == GlobalValue::InternalLinkage) {
823 // The linkage type is internal so just warn about the rename without
824 // invoking "scarey language" about linkage failures. GVars with
825 // InternalLinkage can be renamed at will.
826 warning("Global variable '" + Name + "' was renamed to '"+
829 // The linkage of this gval is external so we can't reliably rename
830 // it because it could potentially create a linking problem.
831 // However, we can't leave the name conflict in the output either or
832 // it won't assemble with LLVM 2.0. So, all we can do is rename
833 // this one to something unique and emit a warning about the problem.
834 warning("Renaming global variable '" + Name + "' to '" + NewName +
835 "' may cause linkage errors");
838 // Put the renaming in the global rename map
839 RenameMapKey Key = std::make_pair(Name,PointerType::get(Ty));
840 CurModule.RenameMap[Key] = NewName;
847 // Otherwise there is no existing GV to use, create one now.
849 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
850 CurModule.CurrentModule);
851 InsertValue(GV, CurModule.Values);
855 // setTypeName - Set the specified type to the name given. The name may be
856 // null potentially, in which case this is a noop. The string passed in is
857 // assumed to be a malloc'd string buffer, and is freed by this function.
859 // This function returns true if the type has already been defined, but is
860 // allowed to be redefined in the specified context. If the name is a new name
861 // for the type plane, it is inserted and false is returned.
862 static bool setTypeName(const Type *T, char *NameStr) {
863 assert(!inFunctionScope() && "Can't give types function-local names");
864 if (NameStr == 0) return false;
866 std::string Name(NameStr); // Copy string
867 free(NameStr); // Free old string
869 // We don't allow assigning names to void type
870 if (T == Type::VoidTy) {
871 error("Can't assign name '" + Name + "' to the void type");
875 // Set the type name, checking for conflicts as we do so.
876 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
878 if (AlreadyExists) { // Inserting a name that is already defined???
879 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
880 assert(Existing && "Conflict but no matching type?");
882 // There is only one case where this is allowed: when we are refining an
883 // opaque type. In this case, Existing will be an opaque type.
884 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
885 // We ARE replacing an opaque type!
886 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
890 // Otherwise, this is an attempt to redefine a type. That's okay if
891 // the redefinition is identical to the original. This will be so if
892 // Existing and T point to the same Type object. In this one case we
893 // allow the equivalent redefinition.
894 if (Existing == T) return true; // Yes, it's equal.
896 // Any other kind of (non-equivalent) redefinition is an error.
897 error("Redefinition of type named '" + Name + "' in the '" +
898 T->getDescription() + "' type plane");
904 //===----------------------------------------------------------------------===//
905 // Code for handling upreferences in type names...
908 // TypeContains - Returns true if Ty directly contains E in it.
910 static bool TypeContains(const Type *Ty, const Type *E) {
911 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
912 E) != Ty->subtype_end();
917 // NestingLevel - The number of nesting levels that need to be popped before
918 // this type is resolved.
919 unsigned NestingLevel;
921 // LastContainedTy - This is the type at the current binding level for the
922 // type. Every time we reduce the nesting level, this gets updated.
923 const Type *LastContainedTy;
925 // UpRefTy - This is the actual opaque type that the upreference is
929 UpRefRecord(unsigned NL, OpaqueType *URTy)
930 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
934 // UpRefs - A list of the outstanding upreferences that need to be resolved.
935 static std::vector<UpRefRecord> UpRefs;
937 /// HandleUpRefs - Every time we finish a new layer of types, this function is
938 /// called. It loops through the UpRefs vector, which is a list of the
939 /// currently active types. For each type, if the up reference is contained in
940 /// the newly completed type, we decrement the level count. When the level
941 /// count reaches zero, the upreferenced type is the type that is passed in:
942 /// thus we can complete the cycle.
944 static PATypeHolder HandleUpRefs(const Type *ty) {
945 // If Ty isn't abstract, or if there are no up-references in it, then there is
946 // nothing to resolve here.
947 if (!ty->isAbstract() || UpRefs.empty()) return ty;
950 UR_OUT("Type '" << Ty->getDescription() <<
951 "' newly formed. Resolving upreferences.\n" <<
952 UpRefs.size() << " upreferences active!\n");
954 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
955 // to zero), we resolve them all together before we resolve them to Ty. At
956 // the end of the loop, if there is anything to resolve to Ty, it will be in
958 OpaqueType *TypeToResolve = 0;
960 for (unsigned i = 0; i != UpRefs.size(); ++i) {
961 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
962 << UpRefs[i].second->getDescription() << ") = "
963 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
964 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
965 // Decrement level of upreference
966 unsigned Level = --UpRefs[i].NestingLevel;
967 UpRefs[i].LastContainedTy = Ty;
968 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
969 if (Level == 0) { // Upreference should be resolved!
970 if (!TypeToResolve) {
971 TypeToResolve = UpRefs[i].UpRefTy;
973 UR_OUT(" * Resolving upreference for "
974 << UpRefs[i].second->getDescription() << "\n";
975 std::string OldName = UpRefs[i].UpRefTy->getDescription());
976 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
977 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
978 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
980 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
981 --i; // Do not skip the next element...
987 UR_OUT(" * Resolving upreference for "
988 << UpRefs[i].second->getDescription() << "\n";
989 std::string OldName = TypeToResolve->getDescription());
990 TypeToResolve->refineAbstractTypeTo(Ty);
996 static inline Instruction::TermOps
997 getTermOp(TermOps op) {
999 default : assert(0 && "Invalid OldTermOp");
1000 case RetOp : return Instruction::Ret;
1001 case BrOp : return Instruction::Br;
1002 case SwitchOp : return Instruction::Switch;
1003 case InvokeOp : return Instruction::Invoke;
1004 case UnwindOp : return Instruction::Unwind;
1005 case UnreachableOp: return Instruction::Unreachable;
1009 static inline Instruction::BinaryOps
1010 getBinaryOp(BinaryOps op, const Type *Ty, Signedness Sign) {
1012 default : assert(0 && "Invalid OldBinaryOps");
1018 case SetGT : assert(0 && "Should use getCompareOp");
1019 case AddOp : return Instruction::Add;
1020 case SubOp : return Instruction::Sub;
1021 case MulOp : return Instruction::Mul;
1023 // This is an obsolete instruction so we must upgrade it based on the
1024 // types of its operands.
1025 bool isFP = Ty->isFloatingPoint();
1026 if (const PackedType* PTy = dyn_cast<PackedType>(Ty))
1027 // If its a packed type we want to use the element type
1028 isFP = PTy->getElementType()->isFloatingPoint();
1030 return Instruction::FDiv;
1031 else if (Sign == Signed)
1032 return Instruction::SDiv;
1033 return Instruction::UDiv;
1035 case UDivOp : return Instruction::UDiv;
1036 case SDivOp : return Instruction::SDiv;
1037 case FDivOp : return Instruction::FDiv;
1039 // This is an obsolete instruction so we must upgrade it based on the
1040 // types of its operands.
1041 bool isFP = Ty->isFloatingPoint();
1042 if (const PackedType* PTy = dyn_cast<PackedType>(Ty))
1043 // If its a packed type we want to use the element type
1044 isFP = PTy->getElementType()->isFloatingPoint();
1045 // Select correct opcode
1047 return Instruction::FRem;
1048 else if (Sign == Signed)
1049 return Instruction::SRem;
1050 return Instruction::URem;
1052 case URemOp : return Instruction::URem;
1053 case SRemOp : return Instruction::SRem;
1054 case FRemOp : return Instruction::FRem;
1055 case AndOp : return Instruction::And;
1056 case OrOp : return Instruction::Or;
1057 case XorOp : return Instruction::Xor;
1061 static inline Instruction::OtherOps
1062 getCompareOp(BinaryOps op, unsigned short &predicate, const Type* &Ty,
1064 bool isSigned = Sign == Signed;
1065 bool isFP = Ty->isFloatingPoint();
1067 default : assert(0 && "Invalid OldSetCC");
1070 predicate = FCmpInst::FCMP_OEQ;
1071 return Instruction::FCmp;
1073 predicate = ICmpInst::ICMP_EQ;
1074 return Instruction::ICmp;
1078 predicate = FCmpInst::FCMP_UNE;
1079 return Instruction::FCmp;
1081 predicate = ICmpInst::ICMP_NE;
1082 return Instruction::ICmp;
1086 predicate = FCmpInst::FCMP_OLE;
1087 return Instruction::FCmp;
1090 predicate = ICmpInst::ICMP_SLE;
1092 predicate = ICmpInst::ICMP_ULE;
1093 return Instruction::ICmp;
1097 predicate = FCmpInst::FCMP_OGE;
1098 return Instruction::FCmp;
1101 predicate = ICmpInst::ICMP_SGE;
1103 predicate = ICmpInst::ICMP_UGE;
1104 return Instruction::ICmp;
1108 predicate = FCmpInst::FCMP_OLT;
1109 return Instruction::FCmp;
1112 predicate = ICmpInst::ICMP_SLT;
1114 predicate = ICmpInst::ICMP_ULT;
1115 return Instruction::ICmp;
1119 predicate = FCmpInst::FCMP_OGT;
1120 return Instruction::FCmp;
1123 predicate = ICmpInst::ICMP_SGT;
1125 predicate = ICmpInst::ICMP_UGT;
1126 return Instruction::ICmp;
1131 static inline Instruction::MemoryOps getMemoryOp(MemoryOps op) {
1133 default : assert(0 && "Invalid OldMemoryOps");
1134 case MallocOp : return Instruction::Malloc;
1135 case FreeOp : return Instruction::Free;
1136 case AllocaOp : return Instruction::Alloca;
1137 case LoadOp : return Instruction::Load;
1138 case StoreOp : return Instruction::Store;
1139 case GetElementPtrOp : return Instruction::GetElementPtr;
1143 static inline Instruction::OtherOps
1144 getOtherOp(OtherOps op, Signedness Sign) {
1146 default : assert(0 && "Invalid OldOtherOps");
1147 case PHIOp : return Instruction::PHI;
1148 case CallOp : return Instruction::Call;
1149 case ShlOp : return Instruction::Shl;
1152 return Instruction::AShr;
1153 return Instruction::LShr;
1154 case SelectOp : return Instruction::Select;
1155 case UserOp1 : return Instruction::UserOp1;
1156 case UserOp2 : return Instruction::UserOp2;
1157 case VAArg : return Instruction::VAArg;
1158 case ExtractElementOp : return Instruction::ExtractElement;
1159 case InsertElementOp : return Instruction::InsertElement;
1160 case ShuffleVectorOp : return Instruction::ShuffleVector;
1161 case ICmpOp : return Instruction::ICmp;
1162 case FCmpOp : return Instruction::FCmp;
1163 case LShrOp : return Instruction::LShr;
1164 case AShrOp : return Instruction::AShr;
1168 static inline Value*
1169 getCast(CastOps op, Value *Src, Signedness SrcSign, const Type *DstTy,
1170 Signedness DstSign, bool ForceInstruction = false) {
1171 Instruction::CastOps Opcode;
1172 const Type* SrcTy = Src->getType();
1174 if (SrcTy->isFloatingPoint() && isa<PointerType>(DstTy)) {
1175 // fp -> ptr cast is no longer supported but we must upgrade this
1176 // by doing a double cast: fp -> int -> ptr
1177 SrcTy = Type::Int64Ty;
1178 Opcode = Instruction::IntToPtr;
1179 if (isa<Constant>(Src)) {
1180 Src = ConstantExpr::getCast(Instruction::FPToUI,
1181 cast<Constant>(Src), SrcTy);
1183 std::string NewName(makeNameUnique(Src->getName()));
1184 Src = new FPToUIInst(Src, SrcTy, NewName, CurBB);
1186 } else if (isa<IntegerType>(DstTy) &&
1187 cast<IntegerType>(DstTy)->getBitWidth() == 1) {
1188 // cast type %x to bool was previously defined as setne type %x, null
1189 // The cast semantic is now to truncate, not compare so we must retain
1190 // the original intent by replacing the cast with a setne
1191 Constant* Null = Constant::getNullValue(SrcTy);
1192 Instruction::OtherOps Opcode = Instruction::ICmp;
1193 unsigned short predicate = ICmpInst::ICMP_NE;
1194 if (SrcTy->isFloatingPoint()) {
1195 Opcode = Instruction::FCmp;
1196 predicate = FCmpInst::FCMP_ONE;
1197 } else if (!SrcTy->isInteger() && !isa<PointerType>(SrcTy)) {
1198 error("Invalid cast to bool");
1200 if (isa<Constant>(Src) && !ForceInstruction)
1201 return ConstantExpr::getCompare(predicate, cast<Constant>(Src), Null);
1203 return CmpInst::create(Opcode, predicate, Src, Null);
1205 // Determine the opcode to use by calling CastInst::getCastOpcode
1207 CastInst::getCastOpcode(Src, SrcSign == Signed, DstTy, DstSign == Signed);
1209 } else switch (op) {
1210 default: assert(0 && "Invalid cast token");
1211 case TruncOp: Opcode = Instruction::Trunc; break;
1212 case ZExtOp: Opcode = Instruction::ZExt; break;
1213 case SExtOp: Opcode = Instruction::SExt; break;
1214 case FPTruncOp: Opcode = Instruction::FPTrunc; break;
1215 case FPExtOp: Opcode = Instruction::FPExt; break;
1216 case FPToUIOp: Opcode = Instruction::FPToUI; break;
1217 case FPToSIOp: Opcode = Instruction::FPToSI; break;
1218 case UIToFPOp: Opcode = Instruction::UIToFP; break;
1219 case SIToFPOp: Opcode = Instruction::SIToFP; break;
1220 case PtrToIntOp: Opcode = Instruction::PtrToInt; break;
1221 case IntToPtrOp: Opcode = Instruction::IntToPtr; break;
1222 case BitCastOp: Opcode = Instruction::BitCast; break;
1225 if (isa<Constant>(Src) && !ForceInstruction)
1226 return ConstantExpr::getCast(Opcode, cast<Constant>(Src), DstTy);
1227 return CastInst::create(Opcode, Src, DstTy);
1230 static Instruction *
1231 upgradeIntrinsicCall(const Type* RetTy, const ValID &ID,
1232 std::vector<Value*>& Args) {
1234 std::string Name = ID.Type == ValID::NameVal ? ID.Name : "";
1235 if (Name == "llvm.isunordered.f32" || Name == "llvm.isunordered.f64") {
1236 if (Args.size() != 2)
1237 error("Invalid prototype for " + Name + " prototype");
1238 return new FCmpInst(FCmpInst::FCMP_UNO, Args[0], Args[1]);
1240 static unsigned upgradeCount = 1;
1241 const Type* PtrTy = PointerType::get(Type::Int8Ty);
1242 std::vector<const Type*> Params;
1243 if (Name == "llvm.va_start" || Name == "llvm.va_end") {
1244 if (Args.size() != 1)
1245 error("Invalid prototype for " + Name + " prototype");
1246 Params.push_back(PtrTy);
1247 const FunctionType *FTy = FunctionType::get(Type::VoidTy, Params, false);
1248 const PointerType *PFTy = PointerType::get(FTy);
1249 Value* Func = getVal(PFTy, ID);
1250 std::string InstName("va_upgrade");
1251 InstName += llvm::utostr(upgradeCount++);
1252 Args[0] = new BitCastInst(Args[0], PtrTy, InstName, CurBB);
1253 return new CallInst(Func, Args);
1254 } else if (Name == "llvm.va_copy") {
1255 if (Args.size() != 2)
1256 error("Invalid prototype for " + Name + " prototype");
1257 Params.push_back(PtrTy);
1258 Params.push_back(PtrTy);
1259 const FunctionType *FTy = FunctionType::get(Type::VoidTy, Params, false);
1260 const PointerType *PFTy = PointerType::get(FTy);
1261 Value* Func = getVal(PFTy, ID);
1262 std::string InstName0("va_upgrade");
1263 InstName0 += llvm::utostr(upgradeCount++);
1264 std::string InstName1("va_upgrade");
1265 InstName1 += llvm::utostr(upgradeCount++);
1266 Args[0] = new BitCastInst(Args[0], PtrTy, InstName0, CurBB);
1267 Args[1] = new BitCastInst(Args[1], PtrTy, InstName1, CurBB);
1268 return new CallInst(Func, Args);
1274 const Type* upgradeGEPIndices(const Type* PTy,
1275 std::vector<ValueInfo> *Indices,
1276 std::vector<Value*> &VIndices,
1277 std::vector<Constant*> *CIndices = 0) {
1278 // Traverse the indices with a gep_type_iterator so we can build the list
1279 // of constant and value indices for use later. Also perform upgrades
1281 if (CIndices) CIndices->clear();
1282 for (unsigned i = 0, e = Indices->size(); i != e; ++i)
1283 VIndices.push_back((*Indices)[i].V);
1284 generic_gep_type_iterator<std::vector<Value*>::iterator>
1285 GTI = gep_type_begin(PTy, VIndices.begin(), VIndices.end()),
1286 GTE = gep_type_end(PTy, VIndices.begin(), VIndices.end());
1287 for (unsigned i = 0, e = Indices->size(); i != e && GTI != GTE; ++i, ++GTI) {
1288 Value *Index = VIndices[i];
1289 if (CIndices && !isa<Constant>(Index))
1290 error("Indices to constant getelementptr must be constants");
1291 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte
1292 // struct indices to i32 struct indices with ZExt for compatibility.
1293 else if (isa<StructType>(*GTI)) { // Only change struct indices
1294 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Index))
1295 if (CUI->getType()->getBitWidth() == 8)
1297 ConstantExpr::getCast(Instruction::ZExt, CUI, Type::Int32Ty);
1299 // Make sure that unsigned SequentialType indices are zext'd to
1300 // 64-bits if they were smaller than that because LLVM 2.0 will sext
1301 // all indices for SequentialType elements. We must retain the same
1302 // semantic (zext) for unsigned types.
1303 if (const IntegerType *Ity = dyn_cast<IntegerType>(Index->getType()))
1304 if (Ity->getBitWidth() < 64 && (*Indices)[i].S == Unsigned)
1306 Index = ConstantExpr::getCast(Instruction::ZExt,
1307 cast<Constant>(Index), Type::Int64Ty);
1309 Index = CastInst::create(Instruction::ZExt, Index, Type::Int64Ty,
1310 "gep_upgrade", CurBB);
1312 // Add to the CIndices list, if requested.
1314 CIndices->push_back(cast<Constant>(Index));
1318 GetElementPtrInst::getIndexedType(PTy, VIndices, true);
1320 error("Index list invalid for constant getelementptr");
1324 Module* UpgradeAssembly(const std::string &infile, std::istream& in,
1325 bool debug, bool addAttrs)
1328 CurFilename = infile;
1331 AddAttributes = addAttrs;
1332 ObsoleteVarArgs = false;
1335 CurModule.CurrentModule = new Module(CurFilename);
1337 // Check to make sure the parser succeeded
1340 delete ParserResult;
1341 std::cerr << "llvm-upgrade: parse failed.\n";
1345 // Check to make sure that parsing produced a result
1346 if (!ParserResult) {
1347 std::cerr << "llvm-upgrade: no parse result.\n";
1351 // Reset ParserResult variable while saving its value for the result.
1352 Module *Result = ParserResult;
1355 //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
1358 if ((F = Result->getNamedFunction("llvm.va_start"))
1359 && F->getFunctionType()->getNumParams() == 0)
1360 ObsoleteVarArgs = true;
1361 if((F = Result->getNamedFunction("llvm.va_copy"))
1362 && F->getFunctionType()->getNumParams() == 1)
1363 ObsoleteVarArgs = true;
1366 if (ObsoleteVarArgs && NewVarArgs) {
1367 error("This file is corrupt: it uses both new and old style varargs");
1371 if(ObsoleteVarArgs) {
1372 if(Function* F = Result->getNamedFunction("llvm.va_start")) {
1373 if (F->arg_size() != 0) {
1374 error("Obsolete va_start takes 0 argument");
1380 //bar = alloca typeof(foo)
1384 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1385 const Type* ArgTy = F->getFunctionType()->getReturnType();
1386 const Type* ArgTyPtr = PointerType::get(ArgTy);
1387 Function* NF = cast<Function>(Result->getOrInsertFunction(
1388 "llvm.va_start", RetTy, ArgTyPtr, (Type *)0));
1390 while (!F->use_empty()) {
1391 CallInst* CI = cast<CallInst>(F->use_back());
1392 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
1393 new CallInst(NF, bar, "", CI);
1394 Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
1395 CI->replaceAllUsesWith(foo);
1396 CI->getParent()->getInstList().erase(CI);
1398 Result->getFunctionList().erase(F);
1401 if(Function* F = Result->getNamedFunction("llvm.va_end")) {
1402 if(F->arg_size() != 1) {
1403 error("Obsolete va_end takes 1 argument");
1409 //bar = alloca 1 of typeof(foo)
1411 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1412 const Type* ArgTy = F->getFunctionType()->getParamType(0);
1413 const Type* ArgTyPtr = PointerType::get(ArgTy);
1414 Function* NF = cast<Function>(Result->getOrInsertFunction(
1415 "llvm.va_end", RetTy, ArgTyPtr, (Type *)0));
1417 while (!F->use_empty()) {
1418 CallInst* CI = cast<CallInst>(F->use_back());
1419 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
1420 new StoreInst(CI->getOperand(1), bar, CI);
1421 new CallInst(NF, bar, "", CI);
1422 CI->getParent()->getInstList().erase(CI);
1424 Result->getFunctionList().erase(F);
1427 if(Function* F = Result->getNamedFunction("llvm.va_copy")) {
1428 if(F->arg_size() != 1) {
1429 error("Obsolete va_copy takes 1 argument");
1434 //a = alloca 1 of typeof(foo)
1435 //b = alloca 1 of typeof(foo)
1440 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1441 const Type* ArgTy = F->getFunctionType()->getReturnType();
1442 const Type* ArgTyPtr = PointerType::get(ArgTy);
1443 Function* NF = cast<Function>(Result->getOrInsertFunction(
1444 "llvm.va_copy", RetTy, ArgTyPtr, ArgTyPtr, (Type *)0));
1446 while (!F->use_empty()) {
1447 CallInst* CI = cast<CallInst>(F->use_back());
1448 AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
1449 AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
1450 new StoreInst(CI->getOperand(1), b, CI);
1451 new CallInst(NF, a, b, "", CI);
1452 Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
1453 CI->replaceAllUsesWith(foo);
1454 CI->getParent()->getInstList().erase(CI);
1456 Result->getFunctionList().erase(F);
1463 } // end llvm namespace
1465 using namespace llvm;
1470 llvm::Module *ModuleVal;
1471 llvm::Function *FunctionVal;
1472 std::pair<llvm::PATypeInfo, char*> *ArgVal;
1473 llvm::BasicBlock *BasicBlockVal;
1474 llvm::TerminatorInst *TermInstVal;
1475 llvm::InstrInfo InstVal;
1476 llvm::ConstInfo ConstVal;
1477 llvm::ValueInfo ValueVal;
1478 llvm::PATypeInfo TypeVal;
1479 llvm::TypeInfo PrimType;
1480 llvm::PHIListInfo PHIList;
1481 std::list<llvm::PATypeInfo> *TypeList;
1482 std::vector<llvm::ValueInfo> *ValueList;
1483 std::vector<llvm::ConstInfo> *ConstVector;
1486 std::vector<std::pair<llvm::PATypeInfo,char*> > *ArgList;
1487 // Represent the RHS of PHI node
1488 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
1490 llvm::GlobalValue::LinkageTypes Linkage;
1498 char *StrVal; // This memory is strdup'd!
1499 llvm::ValID ValIDVal; // strdup'd memory maybe!
1501 llvm::BinaryOps BinaryOpVal;
1502 llvm::TermOps TermOpVal;
1503 llvm::MemoryOps MemOpVal;
1504 llvm::OtherOps OtherOpVal;
1505 llvm::CastOps CastOpVal;
1506 llvm::ICmpInst::Predicate IPred;
1507 llvm::FCmpInst::Predicate FPred;
1508 llvm::Module::Endianness Endianness;
1511 %type <ModuleVal> Module FunctionList
1512 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1513 %type <BasicBlockVal> BasicBlock InstructionList
1514 %type <TermInstVal> BBTerminatorInst
1515 %type <InstVal> Inst InstVal MemoryInst
1516 %type <ConstVal> ConstVal ConstExpr
1517 %type <ConstVector> ConstVector
1518 %type <ArgList> ArgList ArgListH
1519 %type <ArgVal> ArgVal
1520 %type <PHIList> PHIList
1521 %type <ValueList> ValueRefList ValueRefListE // For call param lists
1522 %type <ValueList> IndexList // For GEP derived indices
1523 %type <TypeList> TypeListI ArgTypeListI
1524 %type <JumpTable> JumpTable
1525 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1526 %type <BoolVal> OptVolatile // 'volatile' or not
1527 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1528 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
1529 %type <Linkage> OptLinkage
1530 %type <Endianness> BigOrLittle
1532 // ValueRef - Unresolved reference to a definition or BB
1533 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1534 %type <ValueVal> ResolvedVal // <type> <valref> pair
1535 // Tokens and types for handling constant integer values
1537 // ESINT64VAL - A negative number within long long range
1538 %token <SInt64Val> ESINT64VAL
1540 // EUINT64VAL - A positive number within uns. long long range
1541 %token <UInt64Val> EUINT64VAL
1542 %type <SInt64Val> EINT64VAL
1544 %token <SIntVal> SINTVAL // Signed 32 bit ints...
1545 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
1546 %type <SIntVal> INTVAL
1547 %token <FPVal> FPVAL // Float or Double constant
1549 // Built in types...
1550 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
1551 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
1552 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
1553 %token <PrimType> FLOAT DOUBLE TYPE LABEL
1555 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
1556 %type <StrVal> Name OptName OptAssign
1557 %type <UIntVal> OptAlign OptCAlign
1558 %type <StrVal> OptSection SectionString
1560 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1561 %token DECLARE GLOBAL CONSTANT SECTION VOLATILE
1562 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
1563 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
1564 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
1565 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1566 %token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
1567 %token X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1569 %type <UIntVal> OptCallingConv
1571 // Basic Block Terminating Operators
1572 %token <TermOpVal> RET BR SWITCH INVOKE UNREACHABLE
1573 %token UNWIND EXCEPT
1576 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
1577 %token <BinaryOpVal> ADD SUB MUL DIV UDIV SDIV FDIV REM UREM SREM FREM
1578 %token <BinaryOpVal> AND OR XOR
1579 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comparators
1580 %token <OtherOpVal> ICMP FCMP
1582 // Memory Instructions
1583 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1586 %type <OtherOpVal> ShiftOps
1587 %token <OtherOpVal> PHI_TOK SELECT SHL SHR ASHR LSHR VAARG
1588 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1589 %token VAARG_old VANEXT_old //OBSOLETE
1591 %type <IPred> IPredicates
1592 %type <FPred> FPredicates
1593 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1594 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1596 %token <CastOpVal> CAST TRUNC ZEXT SEXT FPTRUNC FPEXT FPTOUI FPTOSI
1597 %token <CastOpVal> UITOFP SITOFP PTRTOINT INTTOPTR BITCAST
1598 %type <CastOpVal> CastOps
1604 // Handle constant integer size restriction and conversion...
1609 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
1610 error("Value too large for type");
1616 : ESINT64VAL; // These have same type and can't cause problems...
1618 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
1619 error("Value too large for type");
1623 // Operations that are notably excluded from this list include:
1624 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1627 : ADD | SUB | MUL | DIV | UDIV | SDIV | FDIV | REM | UREM | SREM | FREM
1635 : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
1639 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1640 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1641 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1642 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1643 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1647 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1648 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1649 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1650 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1651 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1652 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1653 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1654 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1655 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1658 : SHL | SHR | ASHR | LSHR
1662 : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | FPTOUI | FPTOSI
1663 | UITOFP | SITOFP | PTRTOINT | INTTOPTR | BITCAST | CAST
1666 // These are some types that allow classification if we only want a particular
1667 // thing... for example, only a signed, unsigned, or integral type.
1669 : LONG | INT | SHORT | SBYTE
1673 : ULONG | UINT | USHORT | UBYTE
1677 : SIntType | UIntType
1684 // OptAssign - Value producing statements have an optional assignment component
1694 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1695 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1696 | WEAK { $$ = GlobalValue::WeakLinkage; }
1697 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1698 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1699 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1700 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1701 | /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1705 : /*empty*/ { $$ = CallingConv::C; }
1706 | CCC_TOK { $$ = CallingConv::C; }
1707 | CSRETCC_TOK { $$ = CallingConv::CSRet; }
1708 | FASTCC_TOK { $$ = CallingConv::Fast; }
1709 | COLDCC_TOK { $$ = CallingConv::Cold; }
1710 | X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; }
1711 | X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; }
1712 | CC_TOK EUINT64VAL {
1713 if ((unsigned)$2 != $2)
1714 error("Calling conv too large");
1719 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1720 // a comma before it.
1722 : /*empty*/ { $$ = 0; }
1723 | ALIGN EUINT64VAL {
1725 if ($$ != 0 && !isPowerOf2_32($$))
1726 error("Alignment must be a power of two");
1731 : /*empty*/ { $$ = 0; }
1732 | ',' ALIGN EUINT64VAL {
1734 if ($$ != 0 && !isPowerOf2_32($$))
1735 error("Alignment must be a power of two");
1740 : SECTION STRINGCONSTANT {
1741 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1742 if ($2[i] == '"' || $2[i] == '\\')
1743 error("Invalid character in section name");
1749 : /*empty*/ { $$ = 0; }
1750 | SectionString { $$ = $1; }
1753 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1754 // is set to be the global we are processing.
1758 | ',' GlobalVarAttribute GlobalVarAttributes {}
1763 CurGV->setSection($1);
1766 | ALIGN EUINT64VAL {
1767 if ($2 != 0 && !isPowerOf2_32($2))
1768 error("Alignment must be a power of two");
1769 CurGV->setAlignment($2);
1774 //===----------------------------------------------------------------------===//
1775 // Types includes all predefined types... except void, because it can only be
1776 // used in specific contexts (function returning void for example). To have
1777 // access to it, a user must explicitly use TypesV.
1780 // TypesV includes all of 'Types', but it also includes the void type.
1784 $$.T = new PATypeHolder($1.T);
1792 $$.T = new PATypeHolder($1.T);
1799 if (!UpRefs.empty())
1800 error("Invalid upreference in type: " + (*$1.T)->getDescription());
1806 : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT
1807 | LONG | ULONG | FLOAT | DOUBLE | LABEL
1810 // Derived types are added later...
1813 $$.T = new PATypeHolder($1.T);
1817 $$.T = new PATypeHolder(OpaqueType::get());
1820 | SymbolicValueRef { // Named types are also simple types...
1821 const Type* tmp = getTypeVal($1);
1822 $$.T = new PATypeHolder(tmp);
1823 $$.S = Signless; // FIXME: what if its signed?
1825 | '\\' EUINT64VAL { // Type UpReference
1826 if ($2 > (uint64_t)~0U)
1827 error("Value out of range");
1828 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1829 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1830 $$.T = new PATypeHolder(OT);
1832 UR_OUT("New Upreference!\n");
1834 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
1835 std::vector<const Type*> Params;
1836 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
1837 E = $3->end(); I != E; ++I) {
1838 Params.push_back(I->T->get());
1841 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1842 if (isVarArg) Params.pop_back();
1844 $$.T = new PATypeHolder(HandleUpRefs(
1845 FunctionType::get($1.T->get(),Params,isVarArg)));
1847 delete $1.T; // Delete the return type handle
1848 delete $3; // Delete the argument list
1850 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
1851 $$.T = new PATypeHolder(HandleUpRefs(ArrayType::get($4.T->get(),
1856 | '<' EUINT64VAL 'x' UpRTypes '>' { // Packed array type?
1857 const llvm::Type* ElemTy = $4.T->get();
1858 if ((unsigned)$2 != $2)
1859 error("Unsigned result not equal to signed result");
1860 if (!(ElemTy->isInteger() || ElemTy->isFloatingPoint()))
1861 error("Elements of a PackedType must be integer or floating point");
1862 if (!isPowerOf2_32($2))
1863 error("PackedType length should be a power of 2");
1864 $$.T = new PATypeHolder(HandleUpRefs(PackedType::get(ElemTy,
1869 | '{' TypeListI '}' { // Structure type?
1870 std::vector<const Type*> Elements;
1871 for (std::list<llvm::PATypeInfo>::iterator I = $2->begin(),
1872 E = $2->end(); I != E; ++I)
1873 Elements.push_back(I->T->get());
1874 $$.T = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1878 | '{' '}' { // Empty structure type?
1879 $$.T = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1882 | '<' '{' TypeListI '}' '>' { // Packed Structure type?
1883 std::vector<const Type*> Elements;
1884 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
1885 E = $3->end(); I != E; ++I) {
1886 Elements.push_back(I->T->get());
1889 $$.T = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1893 | '<' '{' '}' '>' { // Empty packed structure type?
1894 $$.T = new PATypeHolder(StructType::get(std::vector<const Type*>(),true));
1897 | UpRTypes '*' { // Pointer type?
1898 if ($1.T->get() == Type::LabelTy)
1899 error("Cannot form a pointer to a basic block");
1900 $$.T = new PATypeHolder(HandleUpRefs(PointerType::get($1.T->get())));
1906 // TypeList - Used for struct declarations and as a basis for function type
1907 // declaration type lists
1911 $$ = new std::list<PATypeInfo>();
1914 | TypeListI ',' UpRTypes {
1915 ($$=$1)->push_back($3);
1919 // ArgTypeList - List of types for a function type declaration...
1922 | TypeListI ',' DOTDOTDOT {
1924 VoidTI.T = new PATypeHolder(Type::VoidTy);
1925 VoidTI.S = Signless;
1926 ($$=$1)->push_back(VoidTI);
1929 $$ = new std::list<PATypeInfo>();
1931 VoidTI.T = new PATypeHolder(Type::VoidTy);
1932 VoidTI.S = Signless;
1933 $$->push_back(VoidTI);
1936 $$ = new std::list<PATypeInfo>();
1940 // ConstVal - The various declarations that go into the constant pool. This
1941 // production is used ONLY to represent constants that show up AFTER a 'const',
1942 // 'constant' or 'global' token at global scope. Constants that can be inlined
1943 // into other expressions (such as integers and constexprs) are handled by the
1944 // ResolvedVal, ValueRef and ConstValueRef productions.
1947 : Types '[' ConstVector ']' { // Nonempty unsized arr
1948 const ArrayType *ATy = dyn_cast<ArrayType>($1.T->get());
1950 error("Cannot make array constant with type: '" +
1951 $1.T->get()->getDescription() + "'");
1952 const Type *ETy = ATy->getElementType();
1953 int NumElements = ATy->getNumElements();
1955 // Verify that we have the correct size...
1956 if (NumElements != -1 && NumElements != (int)$3->size())
1957 error("Type mismatch: constant sized array initialized with " +
1958 utostr($3->size()) + " arguments, but has size of " +
1959 itostr(NumElements) + "");
1961 // Verify all elements are correct type!
1962 std::vector<Constant*> Elems;
1963 for (unsigned i = 0; i < $3->size(); i++) {
1964 Constant *C = (*$3)[i].C;
1965 const Type* ValTy = C->getType();
1967 error("Element #" + utostr(i) + " is not of type '" +
1968 ETy->getDescription() +"' as required!\nIt is of type '"+
1969 ValTy->getDescription() + "'");
1972 $$.C = ConstantArray::get(ATy, Elems);
1978 const ArrayType *ATy = dyn_cast<ArrayType>($1.T->get());
1980 error("Cannot make array constant with type: '" +
1981 $1.T->get()->getDescription() + "'");
1982 int NumElements = ATy->getNumElements();
1983 if (NumElements != -1 && NumElements != 0)
1984 error("Type mismatch: constant sized array initialized with 0"
1985 " arguments, but has size of " + itostr(NumElements) +"");
1986 $$.C = ConstantArray::get(ATy, std::vector<Constant*>());
1990 | Types 'c' STRINGCONSTANT {
1991 const ArrayType *ATy = dyn_cast<ArrayType>($1.T->get());
1993 error("Cannot make array constant with type: '" +
1994 $1.T->get()->getDescription() + "'");
1995 int NumElements = ATy->getNumElements();
1996 const Type *ETy = dyn_cast<IntegerType>(ATy->getElementType());
1997 if (!ETy || cast<IntegerType>(ETy)->getBitWidth() != 8)
1998 error("String arrays require type i8, not '" + ETy->getDescription() +
2000 char *EndStr = UnEscapeLexed($3, true);
2001 if (NumElements != -1 && NumElements != (EndStr-$3))
2002 error("Can't build string constant of size " +
2003 itostr((int)(EndStr-$3)) + " when array has size " +
2004 itostr(NumElements) + "");
2005 std::vector<Constant*> Vals;
2006 for (char *C = (char *)$3; C != (char *)EndStr; ++C)
2007 Vals.push_back(ConstantInt::get(ETy, *C));
2009 $$.C = ConstantArray::get(ATy, Vals);
2013 | Types '<' ConstVector '>' { // Nonempty unsized arr
2014 const PackedType *PTy = dyn_cast<PackedType>($1.T->get());
2016 error("Cannot make packed constant with type: '" +
2017 $1.T->get()->getDescription() + "'");
2018 const Type *ETy = PTy->getElementType();
2019 int NumElements = PTy->getNumElements();
2020 // Verify that we have the correct size...
2021 if (NumElements != -1 && NumElements != (int)$3->size())
2022 error("Type mismatch: constant sized packed initialized with " +
2023 utostr($3->size()) + " arguments, but has size of " +
2024 itostr(NumElements) + "");
2025 // Verify all elements are correct type!
2026 std::vector<Constant*> Elems;
2027 for (unsigned i = 0; i < $3->size(); i++) {
2028 Constant *C = (*$3)[i].C;
2029 const Type* ValTy = C->getType();
2031 error("Element #" + utostr(i) + " is not of type '" +
2032 ETy->getDescription() +"' as required!\nIt is of type '"+
2033 ValTy->getDescription() + "'");
2036 $$.C = ConstantPacked::get(PTy, Elems);
2041 | Types '{' ConstVector '}' {
2042 const StructType *STy = dyn_cast<StructType>($1.T->get());
2044 error("Cannot make struct constant with type: '" +
2045 $1.T->get()->getDescription() + "'");
2046 if ($3->size() != STy->getNumContainedTypes())
2047 error("Illegal number of initializers for structure type");
2049 // Check to ensure that constants are compatible with the type initializer!
2050 std::vector<Constant*> Fields;
2051 for (unsigned i = 0, e = $3->size(); i != e; ++i) {
2052 Constant *C = (*$3)[i].C;
2053 if (C->getType() != STy->getElementType(i))
2054 error("Expected type '" + STy->getElementType(i)->getDescription() +
2055 "' for element #" + utostr(i) + " of structure initializer");
2056 Fields.push_back(C);
2058 $$.C = ConstantStruct::get(STy, Fields);
2064 const StructType *STy = dyn_cast<StructType>($1.T->get());
2066 error("Cannot make struct constant with type: '" +
2067 $1.T->get()->getDescription() + "'");
2068 if (STy->getNumContainedTypes() != 0)
2069 error("Illegal number of initializers for structure type");
2070 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2074 | Types '<' '{' ConstVector '}' '>' {
2075 const StructType *STy = dyn_cast<StructType>($1.T->get());
2077 error("Cannot make packed struct constant with type: '" +
2078 $1.T->get()->getDescription() + "'");
2079 if ($4->size() != STy->getNumContainedTypes())
2080 error("Illegal number of initializers for packed structure type");
2082 // Check to ensure that constants are compatible with the type initializer!
2083 std::vector<Constant*> Fields;
2084 for (unsigned i = 0, e = $4->size(); i != e; ++i) {
2085 Constant *C = (*$4)[i].C;
2086 if (C->getType() != STy->getElementType(i))
2087 error("Expected type '" + STy->getElementType(i)->getDescription() +
2088 "' for element #" + utostr(i) + " of packed struct initializer");
2089 Fields.push_back(C);
2091 $$.C = ConstantStruct::get(STy, Fields);
2096 | Types '<' '{' '}' '>' {
2097 const StructType *STy = dyn_cast<StructType>($1.T->get());
2099 error("Cannot make packed struct constant with type: '" +
2100 $1.T->get()->getDescription() + "'");
2101 if (STy->getNumContainedTypes() != 0)
2102 error("Illegal number of initializers for packed structure type");
2103 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2108 const PointerType *PTy = dyn_cast<PointerType>($1.T->get());
2110 error("Cannot make null pointer constant with type: '" +
2111 $1.T->get()->getDescription() + "'");
2112 $$.C = ConstantPointerNull::get(PTy);
2117 $$.C = UndefValue::get($1.T->get());
2121 | Types SymbolicValueRef {
2122 const PointerType *Ty = dyn_cast<PointerType>($1.T->get());
2124 error("Global const reference must be a pointer type, not" +
2125 $1.T->get()->getDescription());
2127 // ConstExprs can exist in the body of a function, thus creating
2128 // GlobalValues whenever they refer to a variable. Because we are in
2129 // the context of a function, getExistingValue will search the functions
2130 // symbol table instead of the module symbol table for the global symbol,
2131 // which throws things all off. To get around this, we just tell
2132 // getExistingValue that we are at global scope here.
2134 Function *SavedCurFn = CurFun.CurrentFunction;
2135 CurFun.CurrentFunction = 0;
2136 Value *V = getExistingValue(Ty, $2);
2137 CurFun.CurrentFunction = SavedCurFn;
2139 // If this is an initializer for a constant pointer, which is referencing a
2140 // (currently) undefined variable, create a stub now that shall be replaced
2141 // in the future with the right type of variable.
2144 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers");
2145 const PointerType *PT = cast<PointerType>(Ty);
2147 // First check to see if the forward references value is already created!
2148 PerModuleInfo::GlobalRefsType::iterator I =
2149 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
2151 if (I != CurModule.GlobalRefs.end()) {
2152 V = I->second; // Placeholder already exists, use it...
2156 if ($2.Type == ValID::NameVal) Name = $2.Name;
2158 // Create the forward referenced global.
2160 if (const FunctionType *FTy =
2161 dyn_cast<FunctionType>(PT->getElementType())) {
2162 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
2163 CurModule.CurrentModule);
2165 GV = new GlobalVariable(PT->getElementType(), false,
2166 GlobalValue::ExternalLinkage, 0,
2167 Name, CurModule.CurrentModule);
2170 // Keep track of the fact that we have a forward ref to recycle it
2171 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
2175 $$.C = cast<GlobalValue>(V);
2177 delete $1.T; // Free the type handle
2180 if ($1.T->get() != $2.C->getType())
2181 error("Mismatched types for constant expression");
2186 | Types ZEROINITIALIZER {
2187 const Type *Ty = $1.T->get();
2188 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
2189 error("Cannot create a null initialized value of this type");
2190 $$.C = Constant::getNullValue(Ty);
2194 | SIntType EINT64VAL { // integral constants
2195 const Type *Ty = $1.T;
2196 if (!ConstantInt::isValueValidForType(Ty, $2))
2197 error("Constant value doesn't fit in type");
2198 $$.C = ConstantInt::get(Ty, $2);
2201 | UIntType EUINT64VAL { // integral constants
2202 const Type *Ty = $1.T;
2203 if (!ConstantInt::isValueValidForType(Ty, $2))
2204 error("Constant value doesn't fit in type");
2205 $$.C = ConstantInt::get(Ty, $2);
2208 | BOOL TRUETOK { // Boolean constants
2209 $$.C = ConstantInt::get(Type::Int1Ty, true);
2212 | BOOL FALSETOK { // Boolean constants
2213 $$.C = ConstantInt::get(Type::Int1Ty, false);
2216 | FPType FPVAL { // Float & Double constants
2217 if (!ConstantFP::isValueValidForType($1.T, $2))
2218 error("Floating point constant invalid for type");
2219 $$.C = ConstantFP::get($1.T, $2);
2225 : CastOps '(' ConstVal TO Types ')' {
2226 const Type* SrcTy = $3.C->getType();
2227 const Type* DstTy = $5.T->get();
2228 Signedness SrcSign = $3.S;
2229 Signedness DstSign = $5.S;
2230 if (!SrcTy->isFirstClassType())
2231 error("cast constant expression from a non-primitive type: '" +
2232 SrcTy->getDescription() + "'");
2233 if (!DstTy->isFirstClassType())
2234 error("cast constant expression to a non-primitive type: '" +
2235 DstTy->getDescription() + "'");
2236 $$.C = cast<Constant>(getCast($1, $3.C, SrcSign, DstTy, DstSign));
2240 | GETELEMENTPTR '(' ConstVal IndexList ')' {
2241 const Type *Ty = $3.C->getType();
2242 if (!isa<PointerType>(Ty))
2243 error("GetElementPtr requires a pointer operand");
2245 std::vector<Value*> VIndices;
2246 std::vector<Constant*> CIndices;
2247 upgradeGEPIndices($3.C->getType(), $4, VIndices, &CIndices);
2250 $$.C = ConstantExpr::getGetElementPtr($3.C, CIndices);
2253 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2254 if (!$3.C->getType()->isInteger() ||
2255 cast<IntegerType>($3.C->getType())->getBitWidth() != 1)
2256 error("Select condition must be bool type");
2257 if ($5.C->getType() != $7.C->getType())
2258 error("Select operand types must match");
2259 $$.C = ConstantExpr::getSelect($3.C, $5.C, $7.C);
2262 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
2263 const Type *Ty = $3.C->getType();
2264 if (Ty != $5.C->getType())
2265 error("Binary operator types must match");
2266 // First, make sure we're dealing with the right opcode by upgrading from
2267 // obsolete versions.
2268 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2270 // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
2271 // To retain backward compatibility with these early compilers, we emit a
2272 // cast to the appropriate integer type automatically if we are in the
2273 // broken case. See PR424 for more information.
2274 if (!isa<PointerType>(Ty)) {
2275 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2277 const Type *IntPtrTy = 0;
2278 switch (CurModule.CurrentModule->getPointerSize()) {
2279 case Module::Pointer32: IntPtrTy = Type::Int32Ty; break;
2280 case Module::Pointer64: IntPtrTy = Type::Int64Ty; break;
2281 default: error("invalid pointer binary constant expr");
2283 $$.C = ConstantExpr::get(Opcode,
2284 ConstantExpr::getCast(Instruction::PtrToInt, $3.C, IntPtrTy),
2285 ConstantExpr::getCast(Instruction::PtrToInt, $5.C, IntPtrTy));
2286 $$.C = ConstantExpr::getCast(Instruction::IntToPtr, $$.C, Ty);
2290 | LogicalOps '(' ConstVal ',' ConstVal ')' {
2291 const Type* Ty = $3.C->getType();
2292 if (Ty != $5.C->getType())
2293 error("Logical operator types must match");
2294 if (!Ty->isInteger()) {
2295 if (!isa<PackedType>(Ty) ||
2296 !cast<PackedType>(Ty)->getElementType()->isInteger())
2297 error("Logical operator requires integer operands");
2299 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2300 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2303 | SetCondOps '(' ConstVal ',' ConstVal ')' {
2304 const Type* Ty = $3.C->getType();
2305 if (Ty != $5.C->getType())
2306 error("setcc operand types must match");
2307 unsigned short pred;
2308 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $3.S);
2309 $$.C = ConstantExpr::getCompare(Opcode, $3.C, $5.C);
2312 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
2313 if ($4.C->getType() != $6.C->getType())
2314 error("icmp operand types must match");
2315 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2318 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
2319 if ($4.C->getType() != $6.C->getType())
2320 error("fcmp operand types must match");
2321 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2324 | ShiftOps '(' ConstVal ',' ConstVal ')' {
2325 if (!$5.C->getType()->isInteger() ||
2326 cast<IntegerType>($5.C->getType())->getBitWidth() != 8)
2327 error("Shift count for shift constant must be unsigned byte");
2328 if (!$3.C->getType()->isInteger())
2329 error("Shift constant expression requires integer operand");
2330 $$.C = ConstantExpr::get(getOtherOp($1, $3.S), $3.C, $5.C);
2333 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
2334 if (!ExtractElementInst::isValidOperands($3.C, $5.C))
2335 error("Invalid extractelement operands");
2336 $$.C = ConstantExpr::getExtractElement($3.C, $5.C);
2339 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2340 if (!InsertElementInst::isValidOperands($3.C, $5.C, $7.C))
2341 error("Invalid insertelement operands");
2342 $$.C = ConstantExpr::getInsertElement($3.C, $5.C, $7.C);
2345 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2346 if (!ShuffleVectorInst::isValidOperands($3.C, $5.C, $7.C))
2347 error("Invalid shufflevector operands");
2348 $$.C = ConstantExpr::getShuffleVector($3.C, $5.C, $7.C);
2354 // ConstVector - A list of comma separated constants.
2356 : ConstVector ',' ConstVal { ($$ = $1)->push_back($3); }
2358 $$ = new std::vector<ConstInfo>();
2364 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
2366 : GLOBAL { $$ = false; }
2367 | CONSTANT { $$ = true; }
2371 //===----------------------------------------------------------------------===//
2372 // Rules to match Modules
2373 //===----------------------------------------------------------------------===//
2375 // Module rule: Capture the result of parsing the whole file into a result
2380 $$ = ParserResult = $1;
2381 CurModule.ModuleDone();
2385 // FunctionList - A list of functions, preceeded by a constant pool.
2388 : FunctionList Function { $$ = $1; CurFun.FunctionDone(); }
2389 | FunctionList FunctionProto { $$ = $1; }
2390 | FunctionList MODULE ASM_TOK AsmBlock { $$ = $1; }
2391 | FunctionList IMPLEMENTATION { $$ = $1; }
2393 $$ = CurModule.CurrentModule;
2394 // Emit an error if there are any unresolved types left.
2395 if (!CurModule.LateResolveTypes.empty()) {
2396 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
2397 if (DID.Type == ValID::NameVal) {
2398 error("Reference to an undefined type: '"+DID.getName() + "'");
2400 error("Reference to an undefined type: #" + itostr(DID.Num));
2406 // ConstPool - Constants with optional names assigned to them.
2408 : ConstPool OptAssign TYPE TypesV {
2409 // Eagerly resolve types. This is not an optimization, this is a
2410 // requirement that is due to the fact that we could have this:
2412 // %list = type { %list * }
2413 // %list = type { %list * } ; repeated type decl
2415 // If types are not resolved eagerly, then the two types will not be
2416 // determined to be the same type!
2418 const Type* Ty = $4.T->get();
2419 ResolveTypeTo($2, Ty);
2421 if (!setTypeName(Ty, $2) && !$2) {
2422 // If this is a named type that is not a redefinition, add it to the slot
2424 CurModule.Types.push_back(Ty);
2428 | ConstPool FunctionProto { // Function prototypes can be in const pool
2430 | ConstPool MODULE ASM_TOK AsmBlock { // Asm blocks can be in the const pool
2432 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
2434 error("Global value initializer is not a constant");
2435 CurGV = ParseGlobalVariable($2, $3, $4, $5.C->getType(), $5.C);
2436 } GlobalVarAttributes {
2439 | ConstPool OptAssign EXTERNAL GlobalType Types {
2440 const Type *Ty = $5.T->get();
2441 CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, Ty, 0);
2443 } GlobalVarAttributes {
2446 | ConstPool OptAssign DLLIMPORT GlobalType Types {
2447 const Type *Ty = $5.T->get();
2448 CurGV = ParseGlobalVariable($2, GlobalValue::DLLImportLinkage, $4, Ty, 0);
2450 } GlobalVarAttributes {
2453 | ConstPool OptAssign EXTERN_WEAK GlobalType Types {
2454 const Type *Ty = $5.T->get();
2456 ParseGlobalVariable($2, GlobalValue::ExternalWeakLinkage, $4, Ty, 0);
2458 } GlobalVarAttributes {
2461 | ConstPool TARGET TargetDefinition {
2463 | ConstPool DEPLIBS '=' LibrariesDefinition {
2465 | /* empty: end of list */ {
2471 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2472 char *EndStr = UnEscapeLexed($1, true);
2473 std::string NewAsm($1, EndStr);
2476 if (AsmSoFar.empty())
2477 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
2479 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
2484 : BIG { $$ = Module::BigEndian; };
2485 | LITTLE { $$ = Module::LittleEndian; }
2489 : ENDIAN '=' BigOrLittle {
2490 CurModule.setEndianness($3);
2492 | POINTERSIZE '=' EUINT64VAL {
2494 CurModule.setPointerSize(Module::Pointer32);
2496 CurModule.setPointerSize(Module::Pointer64);
2498 error("Invalid pointer size: '" + utostr($3) + "'");
2500 | TRIPLE '=' STRINGCONSTANT {
2501 CurModule.CurrentModule->setTargetTriple($3);
2504 | DATALAYOUT '=' STRINGCONSTANT {
2505 CurModule.CurrentModule->setDataLayout($3);
2515 : LibList ',' STRINGCONSTANT {
2516 CurModule.CurrentModule->addLibrary($3);
2520 CurModule.CurrentModule->addLibrary($1);
2523 | /* empty: end of list */ { }
2526 //===----------------------------------------------------------------------===//
2527 // Rules to match Function Headers
2528 //===----------------------------------------------------------------------===//
2531 : VAR_ID | STRINGCONSTANT
2536 | /*empty*/ { $$ = 0; }
2541 if ($1.T->get() == Type::VoidTy)
2542 error("void typed arguments are invalid");
2543 $$ = new std::pair<PATypeInfo, char*>($1, $2);
2548 : ArgListH ',' ArgVal {
2554 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2561 : ArgListH { $$ = $1; }
2562 | ArgListH ',' DOTDOTDOT {
2565 VoidTI.T = new PATypeHolder(Type::VoidTy);
2566 VoidTI.S = Signless;
2567 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2570 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2572 VoidTI.T = new PATypeHolder(Type::VoidTy);
2573 VoidTI.S = Signless;
2574 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2576 | /* empty */ { $$ = 0; }
2580 : OptCallingConv TypesV Name '(' ArgList ')' OptSection OptAlign {
2582 std::string FunctionName($3);
2583 free($3); // Free strdup'd memory!
2585 const Type* RetTy = $2.T->get();
2587 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
2588 error("LLVM functions cannot return aggregate types");
2590 std::vector<const Type*> ParamTypeList;
2592 // In LLVM 2.0 the signatures of three varargs intrinsics changed to take
2593 // i8*. We check here for those names and override the parameter list
2594 // types to ensure the prototype is correct.
2595 if (FunctionName == "llvm.va_start" || FunctionName == "llvm.va_end") {
2596 ParamTypeList.push_back(PointerType::get(Type::Int8Ty));
2597 } else if (FunctionName == "llvm.va_copy") {
2598 ParamTypeList.push_back(PointerType::get(Type::Int8Ty));
2599 ParamTypeList.push_back(PointerType::get(Type::Int8Ty));
2600 } else if ($5) { // If there are arguments...
2601 for (std::vector<std::pair<PATypeInfo,char*> >::iterator
2602 I = $5->begin(), E = $5->end(); I != E; ++I) {
2603 const Type *Ty = I->first.T->get();
2604 ParamTypeList.push_back(Ty);
2609 ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2610 if (isVarArg) ParamTypeList.pop_back();
2612 const FunctionType *FT = FunctionType::get(RetTy, ParamTypeList, isVarArg);
2613 const PointerType *PFT = PointerType::get(FT);
2617 if (!FunctionName.empty()) {
2618 ID = ValID::create((char*)FunctionName.c_str());
2620 ID = ValID::create((int)CurModule.Values[PFT].size());
2624 // See if this function was forward referenced. If so, recycle the object.
2625 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2626 // Move the function to the end of the list, from whereever it was
2627 // previously inserted.
2628 Fn = cast<Function>(FWRef);
2629 CurModule.CurrentModule->getFunctionList().remove(Fn);
2630 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2631 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2632 (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
2633 // If this is the case, either we need to be a forward decl, or it needs
2635 if (!CurFun.isDeclare && !Fn->isExternal())
2636 error("Redefinition of function '" + FunctionName + "'");
2638 // Make sure to strip off any argument names so we can't get conflicts.
2639 if (Fn->isExternal())
2640 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2643 } else { // Not already defined?
2644 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
2645 CurModule.CurrentModule);
2647 InsertValue(Fn, CurModule.Values);
2650 CurFun.FunctionStart(Fn);
2652 if (CurFun.isDeclare) {
2653 // If we have declaration, always overwrite linkage. This will allow us
2654 // to correctly handle cases, when pointer to function is passed as
2655 // argument to another function.
2656 Fn->setLinkage(CurFun.Linkage);
2658 Fn->setCallingConv($1);
2659 Fn->setAlignment($8);
2665 // Add all of the arguments we parsed to the function...
2666 if ($5) { // Is null if empty...
2667 if (isVarArg) { // Nuke the last entry
2668 assert($5->back().first.T->get() == Type::VoidTy &&
2669 $5->back().second == 0 && "Not a varargs marker");
2670 delete $5->back().first.T;
2671 $5->pop_back(); // Delete the last entry
2673 Function::arg_iterator ArgIt = Fn->arg_begin();
2674 for (std::vector<std::pair<PATypeInfo,char*> >::iterator
2675 I = $5->begin(), E = $5->end(); I != E; ++I, ++ArgIt) {
2676 delete I->first.T; // Delete the typeholder...
2677 setValueName(ArgIt, I->second); // Insert arg into symtab...
2680 delete $5; // We're now done with the argument list
2686 : BEGINTOK | '{' // Allow BEGIN or '{' to start a function
2690 : OptLinkage FunctionHeaderH BEGIN {
2691 $$ = CurFun.CurrentFunction;
2693 // Make sure that we keep track of the linkage type even if there was a
2694 // previous "declare".
2700 : ENDTOK | '}' // Allow end of '}' to end a function
2704 : BasicBlockList END {
2710 | DLLIMPORT { CurFun.Linkage = GlobalValue::DLLImportLinkage; }
2711 | EXTERN_WEAK { CurFun.Linkage = GlobalValue::ExternalWeakLinkage; }
2715 : DECLARE { CurFun.isDeclare = true; } FnDeclareLinkage FunctionHeaderH {
2716 $$ = CurFun.CurrentFunction;
2717 CurFun.FunctionDone();
2722 //===----------------------------------------------------------------------===//
2723 // Rules to match Basic Blocks
2724 //===----------------------------------------------------------------------===//
2727 : /* empty */ { $$ = false; }
2728 | SIDEEFFECT { $$ = true; }
2732 // A reference to a direct constant
2733 : ESINT64VAL { $$ = ValID::create($1); }
2734 | EUINT64VAL { $$ = ValID::create($1); }
2735 | FPVAL { $$ = ValID::create($1); }
2736 | TRUETOK { $$ = ValID::create(ConstantInt::get(Type::Int1Ty, true)); }
2737 | FALSETOK { $$ = ValID::create(ConstantInt::get(Type::Int1Ty, false)); }
2738 | NULL_TOK { $$ = ValID::createNull(); }
2739 | UNDEF { $$ = ValID::createUndef(); }
2740 | ZEROINITIALIZER { $$ = ValID::createZeroInit(); }
2741 | '<' ConstVector '>' { // Nonempty unsized packed vector
2742 const Type *ETy = (*$2)[0].C->getType();
2743 int NumElements = $2->size();
2744 PackedType* pt = PackedType::get(ETy, NumElements);
2745 PATypeHolder* PTy = new PATypeHolder(
2746 HandleUpRefs(PackedType::get(ETy, NumElements)));
2748 // Verify all elements are correct type!
2749 std::vector<Constant*> Elems;
2750 for (unsigned i = 0; i < $2->size(); i++) {
2751 Constant *C = (*$2)[i].C;
2752 const Type *CTy = C->getType();
2754 error("Element #" + utostr(i) + " is not of type '" +
2755 ETy->getDescription() +"' as required!\nIt is of type '" +
2756 CTy->getDescription() + "'");
2759 $$ = ValID::create(ConstantPacked::get(pt, Elems));
2760 delete PTy; delete $2;
2763 $$ = ValID::create($1.C);
2765 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2766 char *End = UnEscapeLexed($3, true);
2767 std::string AsmStr = std::string($3, End);
2768 End = UnEscapeLexed($5, true);
2769 std::string Constraints = std::string($5, End);
2770 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2776 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2780 : INTVAL { $$ = ValID::create($1); }
2781 | Name { $$ = ValID::create($1); }
2784 // ValueRef - A reference to a definition... either constant or symbolic
2786 : SymbolicValueRef | ConstValueRef
2790 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2791 // type immediately preceeds the value reference, and allows complex constant
2792 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2795 const Type *Ty = $1.T->get();
2797 $$.V = getVal(Ty, $2);
2803 : BasicBlockList BasicBlock {
2806 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2811 // Basic blocks are terminated by branching instructions:
2812 // br, br/cc, switch, ret
2815 : InstructionList OptAssign BBTerminatorInst {
2816 setValueName($3, $2);
2818 $1->getInstList().push_back($3);
2825 : InstructionList Inst {
2827 $1->getInstList().push_back($2.I);
2831 $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
2832 // Make sure to move the basic block to the correct location in the
2833 // function, instead of leaving it inserted wherever it was first
2835 Function::BasicBlockListType &BBL =
2836 CurFun.CurrentFunction->getBasicBlockList();
2837 BBL.splice(BBL.end(), BBL, $$);
2840 $$ = CurBB = getBBVal(ValID::create($1), true);
2841 // Make sure to move the basic block to the correct location in the
2842 // function, instead of leaving it inserted wherever it was first
2844 Function::BasicBlockListType &BBL =
2845 CurFun.CurrentFunction->getBasicBlockList();
2846 BBL.splice(BBL.end(), BBL, $$);
2850 Unwind : UNWIND | EXCEPT;
2853 : RET ResolvedVal { // Return with a result...
2854 $$ = new ReturnInst($2.V);
2856 | RET VOID { // Return with no result...
2857 $$ = new ReturnInst();
2859 | BR LABEL ValueRef { // Unconditional Branch...
2860 BasicBlock* tmpBB = getBBVal($3);
2861 $$ = new BranchInst(tmpBB);
2862 } // Conditional Branch...
2863 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2864 BasicBlock* tmpBBA = getBBVal($6);
2865 BasicBlock* tmpBBB = getBBVal($9);
2866 Value* tmpVal = getVal(Type::Int1Ty, $3);
2867 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2869 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2870 Value* tmpVal = getVal($2.T, $3);
2871 BasicBlock* tmpBB = getBBVal($6);
2872 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2874 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2876 for (; I != E; ++I) {
2877 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2878 S->addCase(CI, I->second);
2880 error("Switch case is constant, but not a simple integer");
2884 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2885 Value* tmpVal = getVal($2.T, $3);
2886 BasicBlock* tmpBB = getBBVal($6);
2887 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2890 | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
2891 TO LABEL ValueRef Unwind LABEL ValueRef {
2892 const PointerType *PFTy;
2893 const FunctionType *Ty;
2895 if (!(PFTy = dyn_cast<PointerType>($3.T->get())) ||
2896 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2897 // Pull out the types of all of the arguments...
2898 std::vector<const Type*> ParamTypes;
2900 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
2902 ParamTypes.push_back((*I).V->getType());
2904 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2905 if (isVarArg) ParamTypes.pop_back();
2906 Ty = FunctionType::get($3.T->get(), ParamTypes, isVarArg);
2907 PFTy = PointerType::get(Ty);
2909 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2910 BasicBlock *Normal = getBBVal($10);
2911 BasicBlock *Except = getBBVal($13);
2913 // Create the call node...
2914 if (!$6) { // Has no arguments?
2915 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
2916 } else { // Has arguments?
2917 // Loop through FunctionType's arguments and ensure they are specified
2920 FunctionType::param_iterator I = Ty->param_begin();
2921 FunctionType::param_iterator E = Ty->param_end();
2922 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
2924 std::vector<Value*> Args;
2925 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2926 if ((*ArgI).V->getType() != *I)
2927 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
2928 (*I)->getDescription() + "'");
2929 Args.push_back((*ArgI).V);
2932 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2933 error("Invalid number of parameters detected");
2935 $$ = new InvokeInst(V, Normal, Except, Args);
2937 cast<InvokeInst>($$)->setCallingConv($2);
2942 $$ = new UnwindInst();
2945 $$ = new UnreachableInst();
2950 : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2952 Constant *V = cast<Constant>(getExistingValue($2.T, $3));
2955 error("May only switch on a constant pool value");
2957 BasicBlock* tmpBB = getBBVal($6);
2958 $$->push_back(std::make_pair(V, tmpBB));
2960 | IntType ConstValueRef ',' LABEL ValueRef {
2961 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2962 Constant *V = cast<Constant>(getExistingValue($1.T, $2));
2965 error("May only switch on a constant pool value");
2967 BasicBlock* tmpBB = getBBVal($5);
2968 $$->push_back(std::make_pair(V, tmpBB));
2973 : OptAssign InstVal {
2976 if (BitCastInst *BCI = dyn_cast<BitCastInst>($2.I))
2977 if (BCI->getSrcTy() == BCI->getDestTy() &&
2978 BCI->getOperand(0)->getName() == $1)
2979 // This is a useless bit cast causing a name redefinition. It is
2980 // a bit cast from a type to the same type of an operand with the
2981 // same name as the name we would give this instruction. Since this
2982 // instruction results in no code generation, it is safe to omit
2983 // the instruction. This situation can occur because of collapsed
2984 // type planes. For example:
2985 // %X = add int %Y, %Z
2986 // %X = cast int %Y to uint
2987 // After upgrade, this looks like:
2988 // %X = add i32 %Y, %Z
2989 // %X = bitcast i32 to i32
2990 // The bitcast is clearly useless so we omit it.
2996 setValueName($2.I, $1);
3002 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
3003 $$.P = new std::list<std::pair<Value*, BasicBlock*> >();
3005 Value* tmpVal = getVal($1.T->get(), $3);
3006 BasicBlock* tmpBB = getBBVal($5);
3007 $$.P->push_back(std::make_pair(tmpVal, tmpBB));
3010 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
3012 Value* tmpVal = getVal($1.P->front().first->getType(), $4);
3013 BasicBlock* tmpBB = getBBVal($6);
3014 $1.P->push_back(std::make_pair(tmpVal, tmpBB));
3018 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
3019 $$ = new std::vector<ValueInfo>();
3022 | ValueRefList ',' ResolvedVal {
3027 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
3030 | /*empty*/ { $$ = 0; }
3043 : ArithmeticOps Types ValueRef ',' ValueRef {
3044 const Type* Ty = $2.T->get();
3045 if (!Ty->isInteger() && !Ty->isFloatingPoint() && !isa<PackedType>(Ty))
3046 error("Arithmetic operator requires integer, FP, or packed operands");
3047 if (isa<PackedType>(Ty) &&
3048 ($1 == URemOp || $1 == SRemOp || $1 == FRemOp || $1 == RemOp))
3049 error("Remainder not supported on packed types");
3050 // Upgrade the opcode from obsolete versions before we do anything with it.
3051 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3052 Value* val1 = getVal(Ty, $3);
3053 Value* val2 = getVal(Ty, $5);
3054 $$.I = BinaryOperator::create(Opcode, val1, val2);
3056 error("binary operator returned null");
3060 | LogicalOps Types ValueRef ',' ValueRef {
3061 const Type *Ty = $2.T->get();
3062 if (!Ty->isInteger()) {
3063 if (!isa<PackedType>(Ty) ||
3064 !cast<PackedType>(Ty)->getElementType()->isInteger())
3065 error("Logical operator requires integral operands");
3067 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3068 Value* tmpVal1 = getVal(Ty, $3);
3069 Value* tmpVal2 = getVal(Ty, $5);
3070 $$.I = BinaryOperator::create(Opcode, tmpVal1, tmpVal2);
3072 error("binary operator returned null");
3076 | SetCondOps Types ValueRef ',' ValueRef {
3077 const Type* Ty = $2.T->get();
3078 if(isa<PackedType>(Ty))
3079 error("PackedTypes currently not supported in setcc instructions");
3080 unsigned short pred;
3081 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $2.S);
3082 Value* tmpVal1 = getVal(Ty, $3);
3083 Value* tmpVal2 = getVal(Ty, $5);
3084 $$.I = CmpInst::create(Opcode, pred, tmpVal1, tmpVal2);
3086 error("binary operator returned null");
3090 | ICMP IPredicates Types ValueRef ',' ValueRef {
3091 const Type *Ty = $3.T->get();
3092 if (isa<PackedType>(Ty))
3093 error("PackedTypes currently not supported in icmp instructions");
3094 else if (!Ty->isInteger() && !isa<PointerType>(Ty))
3095 error("icmp requires integer or pointer typed operands");
3096 Value* tmpVal1 = getVal(Ty, $4);
3097 Value* tmpVal2 = getVal(Ty, $6);
3098 $$.I = new ICmpInst($2, tmpVal1, tmpVal2);
3102 | FCMP FPredicates Types ValueRef ',' ValueRef {
3103 const Type *Ty = $3.T->get();
3104 if (isa<PackedType>(Ty))
3105 error("PackedTypes currently not supported in fcmp instructions");
3106 else if (!Ty->isFloatingPoint())
3107 error("fcmp instruction requires floating point operands");
3108 Value* tmpVal1 = getVal(Ty, $4);
3109 Value* tmpVal2 = getVal(Ty, $6);
3110 $$.I = new FCmpInst($2, tmpVal1, tmpVal2);
3115 warning("Use of obsolete 'not' instruction: Replacing with 'xor");
3116 const Type *Ty = $2.V->getType();
3117 Value *Ones = ConstantInt::getAllOnesValue(Ty);
3119 error("Expected integral type for not instruction");
3120 $$.I = BinaryOperator::create(Instruction::Xor, $2.V, Ones);
3122 error("Could not create a xor instruction");
3125 | ShiftOps ResolvedVal ',' ResolvedVal {
3126 if (!$4.V->getType()->isInteger() ||
3127 cast<IntegerType>($4.V->getType())->getBitWidth() != 8)
3128 error("Shift amount must be int8");
3129 if (!$2.V->getType()->isInteger())
3130 error("Shift constant expression requires integer operand");
3131 $$.I = new ShiftInst(getOtherOp($1, $2.S), $2.V, $4.V);
3134 | CastOps ResolvedVal TO Types {
3135 const Type *DstTy = $4.T->get();
3136 if (!DstTy->isFirstClassType())
3137 error("cast instruction to a non-primitive type: '" +
3138 DstTy->getDescription() + "'");
3139 $$.I = cast<Instruction>(getCast($1, $2.V, $2.S, DstTy, $4.S, true));
3143 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3144 if (!$2.V->getType()->isInteger() ||
3145 cast<IntegerType>($2.V->getType())->getBitWidth() != 1)
3146 error("select condition must be bool");
3147 if ($4.V->getType() != $6.V->getType())
3148 error("select value types should match");
3149 $$.I = new SelectInst($2.V, $4.V, $6.V);
3152 | VAARG ResolvedVal ',' Types {
3153 const Type *Ty = $4.T->get();
3155 $$.I = new VAArgInst($2.V, Ty);
3159 | VAARG_old ResolvedVal ',' Types {
3160 const Type* ArgTy = $2.V->getType();
3161 const Type* DstTy = $4.T->get();
3162 ObsoleteVarArgs = true;
3163 Function* NF = cast<Function>(CurModule.CurrentModule->
3164 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3167 //foo = alloca 1 of t
3171 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
3172 CurBB->getInstList().push_back(foo);
3173 CallInst* bar = new CallInst(NF, $2.V);
3174 CurBB->getInstList().push_back(bar);
3175 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3176 $$.I = new VAArgInst(foo, DstTy);
3180 | VANEXT_old ResolvedVal ',' Types {
3181 const Type* ArgTy = $2.V->getType();
3182 const Type* DstTy = $4.T->get();
3183 ObsoleteVarArgs = true;
3184 Function* NF = cast<Function>(CurModule.CurrentModule->
3185 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3187 //b = vanext a, t ->
3188 //foo = alloca 1 of t
3191 //tmp = vaarg foo, t
3193 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
3194 CurBB->getInstList().push_back(foo);
3195 CallInst* bar = new CallInst(NF, $2.V);
3196 CurBB->getInstList().push_back(bar);
3197 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3198 Instruction* tmp = new VAArgInst(foo, DstTy);
3199 CurBB->getInstList().push_back(tmp);
3200 $$.I = new LoadInst(foo);
3204 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
3205 if (!ExtractElementInst::isValidOperands($2.V, $4.V))
3206 error("Invalid extractelement operands");
3207 $$.I = new ExtractElementInst($2.V, $4.V);
3210 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3211 if (!InsertElementInst::isValidOperands($2.V, $4.V, $6.V))
3212 error("Invalid insertelement operands");
3213 $$.I = new InsertElementInst($2.V, $4.V, $6.V);
3216 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3217 if (!ShuffleVectorInst::isValidOperands($2.V, $4.V, $6.V))
3218 error("Invalid shufflevector operands");
3219 $$.I = new ShuffleVectorInst($2.V, $4.V, $6.V);
3223 const Type *Ty = $2.P->front().first->getType();
3224 if (!Ty->isFirstClassType())
3225 error("PHI node operands must be of first class type");
3226 PHINode *PHI = new PHINode(Ty);
3227 PHI->reserveOperandSpace($2.P->size());
3228 while ($2.P->begin() != $2.P->end()) {
3229 if ($2.P->front().first->getType() != Ty)
3230 error("All elements of a PHI node must be of the same type");
3231 PHI->addIncoming($2.P->front().first, $2.P->front().second);
3236 delete $2.P; // Free the list...
3238 | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')' {
3240 // Handle the short call syntax
3241 const PointerType *PFTy;
3242 const FunctionType *FTy;
3243 if (!(PFTy = dyn_cast<PointerType>($3.T->get())) ||
3244 !(FTy = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3245 // Pull out the types of all of the arguments...
3246 std::vector<const Type*> ParamTypes;
3248 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
3250 ParamTypes.push_back((*I).V->getType());
3253 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
3254 if (isVarArg) ParamTypes.pop_back();
3256 const Type *RetTy = $3.T->get();
3257 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
3258 error("Functions cannot return aggregate types");
3260 FTy = FunctionType::get(RetTy, ParamTypes, isVarArg);
3261 PFTy = PointerType::get(FTy);
3264 // First upgrade any intrinsic calls.
3265 std::vector<Value*> Args;
3267 for (unsigned i = 0, e = $6->size(); i < e; ++i)
3268 Args.push_back((*$6)[i].V);
3269 Instruction *Inst = upgradeIntrinsicCall(FTy, $4, Args);
3271 // If we got an upgraded intrinsic
3276 // Get the function we're calling
3277 Value *V = getVal(PFTy, $4);
3279 // Check the argument values match
3280 if (!$6) { // Has no arguments?
3281 // Make sure no arguments is a good thing!
3282 if (FTy->getNumParams() != 0)
3283 error("No arguments passed to a function that expects arguments");
3284 } else { // Has arguments?
3285 // Loop through FunctionType's arguments and ensure they are specified
3288 FunctionType::param_iterator I = FTy->param_begin();
3289 FunctionType::param_iterator E = FTy->param_end();
3290 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
3292 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
3293 if ((*ArgI).V->getType() != *I)
3294 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
3295 (*I)->getDescription() + "'");
3297 if (I != E || (ArgI != ArgE && !FTy->isVarArg()))
3298 error("Invalid number of parameters detected");
3301 // Create the call instruction
3302 CallInst *CI = new CallInst(V, Args);
3303 CI->setTailCall($1);
3304 CI->setCallingConv($2);
3317 // IndexList - List of indices for GEP based instructions...
3319 : ',' ValueRefList { $$ = $2; }
3320 | /* empty */ { $$ = new std::vector<ValueInfo>(); }
3324 : VOLATILE { $$ = true; }
3325 | /* empty */ { $$ = false; }
3329 : MALLOC Types OptCAlign {
3330 const Type *Ty = $2.T->get();
3332 $$.I = new MallocInst(Ty, 0, $3);
3335 | MALLOC Types ',' UINT ValueRef OptCAlign {
3336 const Type *Ty = $2.T->get();
3338 $$.I = new MallocInst(Ty, getVal($4.T, $5), $6);
3341 | ALLOCA Types OptCAlign {
3342 const Type *Ty = $2.T->get();
3344 $$.I = new AllocaInst(Ty, 0, $3);
3347 | ALLOCA Types ',' UINT ValueRef OptCAlign {
3348 const Type *Ty = $2.T->get();
3350 $$.I = new AllocaInst(Ty, getVal($4.T, $5), $6);
3353 | FREE ResolvedVal {
3354 const Type *PTy = $2.V->getType();
3355 if (!isa<PointerType>(PTy))
3356 error("Trying to free nonpointer type '" + PTy->getDescription() + "'");
3357 $$.I = new FreeInst($2.V);
3360 | OptVolatile LOAD Types ValueRef {
3361 const Type* Ty = $3.T->get();
3363 if (!isa<PointerType>(Ty))
3364 error("Can't load from nonpointer type: " + Ty->getDescription());
3365 if (!cast<PointerType>(Ty)->getElementType()->isFirstClassType())
3366 error("Can't load from pointer of non-first-class type: " +
3367 Ty->getDescription());
3368 Value* tmpVal = getVal(Ty, $4);
3369 $$.I = new LoadInst(tmpVal, "", $1);
3372 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
3373 const PointerType *PTy = dyn_cast<PointerType>($5.T->get());
3375 error("Can't store to a nonpointer type: " +
3376 $5.T->get()->getDescription());
3377 const Type *ElTy = PTy->getElementType();
3378 if (ElTy != $3.V->getType())
3379 error("Can't store '" + $3.V->getType()->getDescription() +
3380 "' into space of type '" + ElTy->getDescription() + "'");
3381 Value* tmpVal = getVal(PTy, $6);
3382 $$.I = new StoreInst($3.V, tmpVal, $1);
3386 | GETELEMENTPTR Types ValueRef IndexList {
3387 const Type* Ty = $2.T->get();
3388 if (!isa<PointerType>(Ty))
3389 error("getelementptr insn requires pointer operand");
3391 std::vector<Value*> VIndices;
3392 upgradeGEPIndices(Ty, $4, VIndices);
3394 Value* tmpVal = getVal(Ty, $3);
3395 $$.I = new GetElementPtrInst(tmpVal, VIndices);
3404 int yyerror(const char *ErrorMsg) {
3406 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3407 + ":" + llvm::utostr((unsigned) Upgradelineno-1) + ": ";
3408 std::string errMsg = where + "error: " + std::string(ErrorMsg);
3409 if (yychar != YYEMPTY && yychar != 0)
3410 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3412 std::cerr << "llvm-upgrade: " << errMsg << '\n';
3413 std::cout << "llvm-upgrade: parse failed.\n";
3417 void warning(const std::string& ErrorMsg) {
3419 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3420 + ":" + llvm::utostr((unsigned) Upgradelineno-1) + ": ";
3421 std::string errMsg = where + "warning: " + std::string(ErrorMsg);
3422 if (yychar != YYEMPTY && yychar != 0)
3423 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3425 std::cerr << "llvm-upgrade: " << errMsg << '\n';
3428 void error(const std::string& ErrorMsg, int LineNo) {
3429 if (LineNo == -1) LineNo = Upgradelineno;
3430 Upgradelineno = LineNo;
3431 yyerror(ErrorMsg.c_str());