1 //===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the bison parser for LLVM assembly languages files.
12 //===----------------------------------------------------------------------===//
15 #include "UpgradeInternals.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/InlineAsm.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/SymbolTable.h"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/Support/MathExtras.h"
29 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
30 // relating to upreferences in the input stream.
32 //#define DEBUG_UPREFS 1
34 #define UR_OUT(X) std::cerr << X
39 #define YYERROR_VERBOSE 1
40 #define YYINCLUDED_STDLIB_H
46 int yyerror(const char*);
47 static void warning(const std::string& WarningMsg);
51 std::istream* LexInput;
52 static std::string CurFilename;
54 // This bool controls whether attributes are ever added to function declarations
55 // definitions and calls.
56 static bool AddAttributes = false;
58 static Module *ParserResult;
59 static bool ObsoleteVarArgs;
60 static bool NewVarArgs;
61 static BasicBlock *CurBB;
62 static GlobalVariable *CurGV;
64 // This contains info used when building the body of a function. It is
65 // destroyed when the function is completed.
67 typedef std::vector<Value *> ValueList; // Numbered defs
69 typedef std::pair<std::string,const Type*> RenameMapKey;
70 typedef std::map<RenameMapKey,std::string> RenameMapType;
73 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
74 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
76 static struct PerModuleInfo {
77 Module *CurrentModule;
78 std::map<const Type *, ValueList> Values; // Module level numbered definitions
79 std::map<const Type *,ValueList> LateResolveValues;
80 std::vector<PATypeHolder> Types;
81 std::map<ValID, PATypeHolder> LateResolveTypes;
82 static Module::Endianness Endian;
83 static Module::PointerSize PointerSize;
84 RenameMapType RenameMap;
86 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
87 /// how they were referenced and on which line of the input they came from so
88 /// that we can resolve them later and print error messages as appropriate.
89 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
91 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
92 // references to global values. Global values may be referenced before they
93 // are defined, and if so, the temporary object that they represent is held
94 // here. This is used for forward references of GlobalValues.
96 typedef std::map<std::pair<const PointerType *, ValID>, GlobalValue*>
98 GlobalRefsType GlobalRefs;
101 // If we could not resolve some functions at function compilation time
102 // (calls to functions before they are defined), resolve them now... Types
103 // are resolved when the constant pool has been completely parsed.
105 ResolveDefinitions(LateResolveValues);
107 // Check to make sure that all global value forward references have been
110 if (!GlobalRefs.empty()) {
111 std::string UndefinedReferences = "Unresolved global references exist:\n";
113 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
115 UndefinedReferences += " " + I->first.first->getDescription() + " " +
116 I->first.second.getName() + "\n";
118 error(UndefinedReferences);
122 if (CurrentModule->getDataLayout().empty()) {
123 std::string dataLayout;
124 if (Endian != Module::AnyEndianness)
125 dataLayout.append(Endian == Module::BigEndian ? "E" : "e");
126 if (PointerSize != Module::AnyPointerSize) {
127 if (!dataLayout.empty())
129 dataLayout.append(PointerSize == Module::Pointer64 ?
130 "p:64:64" : "p:32:32");
132 CurrentModule->setDataLayout(dataLayout);
135 Values.clear(); // Clear out function local definitions
140 // GetForwardRefForGlobal - Check to see if there is a forward reference
141 // for this global. If so, remove it from the GlobalRefs map and return it.
142 // If not, just return null.
143 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
144 // Check to see if there is a forward reference to this global variable...
145 // if there is, eliminate it and patch the reference to use the new def'n.
146 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
147 GlobalValue *Ret = 0;
148 if (I != GlobalRefs.end()) {
154 void setEndianness(Module::Endianness E) { Endian = E; }
155 void setPointerSize(Module::PointerSize sz) { PointerSize = sz; }
158 Module::Endianness PerModuleInfo::Endian = Module::AnyEndianness;
159 Module::PointerSize PerModuleInfo::PointerSize = Module::AnyPointerSize;
161 static struct PerFunctionInfo {
162 Function *CurrentFunction; // Pointer to current function being created
164 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
165 std::map<const Type*, ValueList> LateResolveValues;
166 bool isDeclare; // Is this function a forward declararation?
167 GlobalValue::LinkageTypes Linkage;// Linkage for forward declaration.
169 /// BBForwardRefs - When we see forward references to basic blocks, keep
170 /// track of them here.
171 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
172 std::vector<BasicBlock*> NumberedBlocks;
173 RenameMapType RenameMap;
176 inline PerFunctionInfo() {
179 Linkage = GlobalValue::ExternalLinkage;
182 inline void FunctionStart(Function *M) {
187 void FunctionDone() {
188 NumberedBlocks.clear();
190 // Any forward referenced blocks left?
191 if (!BBForwardRefs.empty()) {
192 error("Undefined reference to label " +
193 BBForwardRefs.begin()->first->getName());
197 // Resolve all forward references now.
198 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
200 Values.clear(); // Clear out function local definitions
204 Linkage = GlobalValue::ExternalLinkage;
206 } CurFun; // Info for the current function...
208 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
211 //===----------------------------------------------------------------------===//
212 // Code to handle definitions of all the types
213 //===----------------------------------------------------------------------===//
215 static int InsertValue(Value *V,
216 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
217 if (V->hasName()) return -1; // Is this a numbered definition?
219 // Yes, insert the value into the value table...
220 ValueList &List = ValueTab[V->getType()];
222 return List.size()-1;
225 static const Type *getType(const ValID &D, bool DoNotImprovise = false) {
227 case ValID::NumberVal: // Is it a numbered definition?
228 // Module constants occupy the lowest numbered slots...
229 if ((unsigned)D.Num < CurModule.Types.size()) {
230 return CurModule.Types[(unsigned)D.Num];
233 case ValID::NameVal: // Is it a named definition?
234 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
235 D.destroy(); // Free old strdup'd memory...
240 error("Internal parser error: Invalid symbol type reference");
244 // If we reached here, we referenced either a symbol that we don't know about
245 // or an id number that hasn't been read yet. We may be referencing something
246 // forward, so just create an entry to be resolved later and get to it...
248 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
251 if (inFunctionScope()) {
252 if (D.Type == ValID::NameVal) {
253 error("Reference to an undefined type: '" + D.getName() + "'");
256 error("Reference to an undefined type: #" + itostr(D.Num));
261 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
262 if (I != CurModule.LateResolveTypes.end())
265 Type *Typ = OpaqueType::get();
266 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
270 // getExistingValue - Look up the value specified by the provided type and
271 // the provided ValID. If the value exists and has already been defined, return
272 // it. Otherwise return null.
274 static Value *getExistingValue(const Type *Ty, const ValID &D) {
275 if (isa<FunctionType>(Ty)) {
276 error("Functions are not values and must be referenced as pointers");
280 case ValID::NumberVal: { // Is it a numbered definition?
281 unsigned Num = (unsigned)D.Num;
283 // Module constants occupy the lowest numbered slots...
284 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
285 if (VI != CurModule.Values.end()) {
286 if (Num < VI->second.size())
287 return VI->second[Num];
288 Num -= VI->second.size();
291 // Make sure that our type is within bounds
292 VI = CurFun.Values.find(Ty);
293 if (VI == CurFun.Values.end()) return 0;
295 // Check that the number is within bounds...
296 if (VI->second.size() <= Num) return 0;
298 return VI->second[Num];
301 case ValID::NameVal: { // Is it a named definition?
302 // Get the name out of the ID
303 std::string Name(D.Name);
305 RenameMapKey Key = std::make_pair(Name, Ty);
306 if (inFunctionScope()) {
307 // See if the name was renamed
308 RenameMapType::const_iterator I = CurFun.RenameMap.find(Key);
309 std::string LookupName;
310 if (I != CurFun.RenameMap.end())
311 LookupName = I->second;
314 SymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
315 V = SymTab.lookup(Ty, LookupName);
318 RenameMapType::const_iterator I = CurModule.RenameMap.find(Key);
319 std::string LookupName;
320 if (I != CurModule.RenameMap.end())
321 LookupName = I->second;
324 V = CurModule.CurrentModule->getValueSymbolTable().lookup(Ty, LookupName);
329 D.destroy(); // Free old strdup'd memory...
333 // Check to make sure that "Ty" is an integral type, and that our
334 // value will fit into the specified type...
335 case ValID::ConstSIntVal: // Is it a constant pool reference??
336 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
337 error("Signed integral constant '" + itostr(D.ConstPool64) +
338 "' is invalid for type '" + Ty->getDescription() + "'");
340 return ConstantInt::get(Ty, D.ConstPool64);
342 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
343 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
344 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64))
345 error("Integral constant '" + utostr(D.UConstPool64) +
346 "' is invalid or out of range");
347 else // This is really a signed reference. Transmogrify.
348 return ConstantInt::get(Ty, D.ConstPool64);
350 return ConstantInt::get(Ty, D.UConstPool64);
352 case ValID::ConstFPVal: // Is it a floating point const pool reference?
353 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
354 error("FP constant invalid for type");
355 return ConstantFP::get(Ty, D.ConstPoolFP);
357 case ValID::ConstNullVal: // Is it a null value?
358 if (!isa<PointerType>(Ty))
359 error("Cannot create a a non pointer null");
360 return ConstantPointerNull::get(cast<PointerType>(Ty));
362 case ValID::ConstUndefVal: // Is it an undef value?
363 return UndefValue::get(Ty);
365 case ValID::ConstZeroVal: // Is it a zero value?
366 return Constant::getNullValue(Ty);
368 case ValID::ConstantVal: // Fully resolved constant?
369 if (D.ConstantValue->getType() != Ty)
370 error("Constant expression type different from required type");
371 return D.ConstantValue;
373 case ValID::InlineAsmVal: { // Inline asm expression
374 const PointerType *PTy = dyn_cast<PointerType>(Ty);
375 const FunctionType *FTy =
376 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
377 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints))
378 error("Invalid type for asm constraint string");
379 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
380 D.IAD->HasSideEffects);
381 D.destroy(); // Free InlineAsmDescriptor.
385 assert(0 && "Unhandled case");
389 assert(0 && "Unhandled case");
393 // getVal - This function is identical to getExistingValue, except that if a
394 // value is not already defined, it "improvises" by creating a placeholder var
395 // that looks and acts just like the requested variable. When the value is
396 // defined later, all uses of the placeholder variable are replaced with the
399 static Value *getVal(const Type *Ty, const ValID &ID) {
400 if (Ty == Type::LabelTy)
401 error("Cannot use a basic block here");
403 // See if the value has already been defined.
404 Value *V = getExistingValue(Ty, ID);
407 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty))
408 error("Invalid use of a composite type");
410 // If we reached here, we referenced either a symbol that we don't know about
411 // or an id number that hasn't been read yet. We may be referencing something
412 // forward, so just create an entry to be resolved later and get to it...
413 V = new Argument(Ty);
415 // Remember where this forward reference came from. FIXME, shouldn't we try
416 // to recycle these things??
417 CurModule.PlaceHolderInfo.insert(
418 std::make_pair(V, std::make_pair(ID, Upgradelineno-1)));
420 if (inFunctionScope())
421 InsertValue(V, CurFun.LateResolveValues);
423 InsertValue(V, CurModule.LateResolveValues);
427 /// getBBVal - This is used for two purposes:
428 /// * If isDefinition is true, a new basic block with the specified ID is being
430 /// * If isDefinition is true, this is a reference to a basic block, which may
431 /// or may not be a forward reference.
433 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
434 assert(inFunctionScope() && "Can't get basic block at global scope");
440 error("Illegal label reference " + ID.getName());
442 case ValID::NumberVal: // Is it a numbered definition?
443 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
444 CurFun.NumberedBlocks.resize(ID.Num+1);
445 BB = CurFun.NumberedBlocks[ID.Num];
447 case ValID::NameVal: // Is it a named definition?
449 if (Value *N = CurFun.CurrentFunction->
450 getValueSymbolTable().lookup(Type::LabelTy, Name)) {
451 if (N->getType() != Type::LabelTy)
452 error("Name '" + Name + "' does not refer to a BasicBlock");
453 BB = cast<BasicBlock>(N);
458 // See if the block has already been defined.
460 // If this is the definition of the block, make sure the existing value was
461 // just a forward reference. If it was a forward reference, there will be
462 // an entry for it in the PlaceHolderInfo map.
463 if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
464 // The existing value was a definition, not a forward reference.
465 error("Redefinition of label " + ID.getName());
467 ID.destroy(); // Free strdup'd memory.
471 // Otherwise this block has not been seen before.
472 BB = new BasicBlock("", CurFun.CurrentFunction);
473 if (ID.Type == ValID::NameVal) {
474 BB->setName(ID.Name);
476 CurFun.NumberedBlocks[ID.Num] = BB;
479 // If this is not a definition, keep track of it so we can use it as a forward
482 // Remember where this forward reference came from.
483 CurFun.BBForwardRefs[BB] = std::make_pair(ID, Upgradelineno);
485 // The forward declaration could have been inserted anywhere in the
486 // function: insert it into the correct place now.
487 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
488 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
495 //===----------------------------------------------------------------------===//
496 // Code to handle forward references in instructions
497 //===----------------------------------------------------------------------===//
499 // This code handles the late binding needed with statements that reference
500 // values not defined yet... for example, a forward branch, or the PHI node for
503 // This keeps a table (CurFun.LateResolveValues) of all such forward references
504 // and back patchs after we are done.
507 // ResolveDefinitions - If we could not resolve some defs at parsing
508 // time (forward branches, phi functions for loops, etc...) resolve the
512 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
513 std::map<const Type*,ValueList> *FutureLateResolvers) {
514 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
515 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
516 E = LateResolvers.end(); LRI != E; ++LRI) {
517 ValueList &List = LRI->second;
518 while (!List.empty()) {
519 Value *V = List.back();
522 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
523 CurModule.PlaceHolderInfo.find(V);
524 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error");
526 ValID &DID = PHI->second.first;
528 Value *TheRealValue = getExistingValue(LRI->first, DID);
530 V->replaceAllUsesWith(TheRealValue);
532 CurModule.PlaceHolderInfo.erase(PHI);
533 } else if (FutureLateResolvers) {
534 // Functions have their unresolved items forwarded to the module late
536 InsertValue(V, *FutureLateResolvers);
538 if (DID.Type == ValID::NameVal) {
539 error("Reference to an invalid definition: '" +DID.getName()+
540 "' of type '" + V->getType()->getDescription() + "'",
544 error("Reference to an invalid definition: #" +
545 itostr(DID.Num) + " of type '" +
546 V->getType()->getDescription() + "'", PHI->second.second);
553 LateResolvers.clear();
556 // ResolveTypeTo - A brand new type was just declared. This means that (if
557 // name is not null) things referencing Name can be resolved. Otherwise, things
558 // refering to the number can be resolved. Do this now.
560 static void ResolveTypeTo(char *Name, const Type *ToTy) {
562 if (Name) D = ValID::create(Name);
563 else D = ValID::create((int)CurModule.Types.size());
565 std::map<ValID, PATypeHolder>::iterator I =
566 CurModule.LateResolveTypes.find(D);
567 if (I != CurModule.LateResolveTypes.end()) {
568 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
569 CurModule.LateResolveTypes.erase(I);
573 /// @brief This just makes any name given to it unique, up to MAX_UINT times.
574 static std::string makeNameUnique(const std::string& Name) {
575 static unsigned UniqueNameCounter = 1;
576 std::string Result(Name);
577 Result += ".upgrd." + llvm::utostr(UniqueNameCounter++);
581 /// This is the implementation portion of TypeHasInteger. It traverses the
582 /// type given, avoiding recursive types, and returns true as soon as it finds
583 /// an integer type. If no integer type is found, it returns false.
584 static bool TypeHasIntegerI(const Type *Ty, std::vector<const Type*> Stack) {
585 // Handle some easy cases
586 if (Ty->isPrimitiveType() || (Ty->getTypeID() == Type::OpaqueTyID))
590 if (const SequentialType *STy = dyn_cast<SequentialType>(Ty))
591 return STy->getElementType()->isInteger();
593 // Avoid type structure recursion
594 for (std::vector<const Type*>::iterator I = Stack.begin(), E = Stack.end();
599 // Push us on the type stack
602 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
603 if (TypeHasIntegerI(FTy->getReturnType(), Stack))
605 FunctionType::param_iterator I = FTy->param_begin();
606 FunctionType::param_iterator E = FTy->param_end();
608 if (TypeHasIntegerI(*I, Stack))
611 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
612 StructType::element_iterator I = STy->element_begin();
613 StructType::element_iterator E = STy->element_end();
614 for (; I != E; ++I) {
615 if (TypeHasIntegerI(*I, Stack))
620 // There shouldn't be anything else, but its definitely not integer
621 assert(0 && "What type is this?");
625 /// This is the interface to TypeHasIntegerI. It just provides the type stack,
626 /// to avoid recursion, and then calls TypeHasIntegerI.
627 static inline bool TypeHasInteger(const Type *Ty) {
628 std::vector<const Type*> TyStack;
629 return TypeHasIntegerI(Ty, TyStack);
632 // setValueName - Set the specified value to the name given. The name may be
633 // null potentially, in which case this is a noop. The string passed in is
634 // assumed to be a malloc'd string buffer, and is free'd by this function.
636 static void setValueName(Value *V, char *NameStr) {
638 std::string Name(NameStr); // Copy string
639 free(NameStr); // Free old string
641 if (V->getType() == Type::VoidTy) {
642 error("Can't assign name '" + Name + "' to value with void type");
646 assert(inFunctionScope() && "Must be in function scope");
648 // Search the function's symbol table for an existing value of this name
650 SymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
651 SymbolTable::plane_const_iterator PI = ST.plane_begin(), PE =ST.plane_end();
652 for ( ; PI != PE; ++PI) {
653 SymbolTable::value_const_iterator VI = PI->second.find(Name);
654 if (VI != PI->second.end()) {
655 Existing = VI->second;
660 // An existing value of the same name was found. This might have happened
661 // because of the integer type planes collapsing in LLVM 2.0.
662 if (Existing->getType() == V->getType() &&
663 !TypeHasInteger(Existing->getType())) {
664 // If the type does not contain any integers in them then this can't be
665 // a type plane collapsing issue. It truly is a redefinition and we
666 // should error out as the assembly is invalid.
667 error("Redefinition of value named '" + Name + "' of type '" +
668 V->getType()->getDescription() + "'");
671 // In LLVM 2.0 we don't allow names to be re-used for any values in a
672 // function, regardless of Type. Previously re-use of names was okay as
673 // long as they were distinct types. With type planes collapsing because
674 // of the signedness change and because of PR411, this can no longer be
675 // supported. We must search the entire symbol table for a conflicting
676 // name and make the name unique. No warning is needed as this can't
678 std::string NewName = makeNameUnique(Name);
679 // We're changing the name but it will probably be used by other
680 // instructions as operands later on. Consequently we have to retain
681 // a mapping of the renaming that we're doing.
682 RenameMapKey Key = std::make_pair(Name,V->getType());
683 CurFun.RenameMap[Key] = NewName;
692 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
693 /// this is a declaration, otherwise it is a definition.
694 static GlobalVariable *
695 ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
696 bool isConstantGlobal, const Type *Ty,
697 Constant *Initializer) {
698 if (isa<FunctionType>(Ty))
699 error("Cannot declare global vars of function type");
701 const PointerType *PTy = PointerType::get(Ty);
705 Name = NameStr; // Copy string
706 free(NameStr); // Free old string
709 // See if this global value was forward referenced. If so, recycle the
713 ID = ValID::create((char*)Name.c_str());
715 ID = ValID::create((int)CurModule.Values[PTy].size());
718 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
719 // Move the global to the end of the list, from whereever it was
720 // previously inserted.
721 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
722 CurModule.CurrentModule->getGlobalList().remove(GV);
723 CurModule.CurrentModule->getGlobalList().push_back(GV);
724 GV->setInitializer(Initializer);
725 GV->setLinkage(Linkage);
726 GV->setConstant(isConstantGlobal);
727 InsertValue(GV, CurModule.Values);
731 // If this global has a name, check to see if there is already a definition
732 // of this global in the module and emit warnings if there are conflicts.
734 // The global has a name. See if there's an existing one of the same name.
735 if (CurModule.CurrentModule->getNamedGlobal(Name)) {
736 // We found an existing global ov the same name. This isn't allowed
737 // in LLVM 2.0. Consequently, we must alter the name of the global so it
738 // can at least compile. This can happen because of type planes
739 // There is alread a global of the same name which means there is a
740 // conflict. Let's see what we can do about it.
741 std::string NewName(makeNameUnique(Name));
742 if (Linkage == GlobalValue::InternalLinkage) {
743 // The linkage type is internal so just warn about the rename without
744 // invoking "scarey language" about linkage failures. GVars with
745 // InternalLinkage can be renamed at will.
746 warning("Global variable '" + Name + "' was renamed to '"+
749 // The linkage of this gval is external so we can't reliably rename
750 // it because it could potentially create a linking problem.
751 // However, we can't leave the name conflict in the output either or
752 // it won't assemble with LLVM 2.0. So, all we can do is rename
753 // this one to something unique and emit a warning about the problem.
754 warning("Renaming global variable '" + Name + "' to '" + NewName +
755 "' may cause linkage errors");
758 // Put the renaming in the global rename map
759 RenameMapKey Key = std::make_pair(Name,PointerType::get(Ty));
760 CurModule.RenameMap[Key] = NewName;
767 // Otherwise there is no existing GV to use, create one now.
769 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
770 CurModule.CurrentModule);
771 InsertValue(GV, CurModule.Values);
775 // setTypeName - Set the specified type to the name given. The name may be
776 // null potentially, in which case this is a noop. The string passed in is
777 // assumed to be a malloc'd string buffer, and is freed by this function.
779 // This function returns true if the type has already been defined, but is
780 // allowed to be redefined in the specified context. If the name is a new name
781 // for the type plane, it is inserted and false is returned.
782 static bool setTypeName(const Type *T, char *NameStr) {
783 assert(!inFunctionScope() && "Can't give types function-local names");
784 if (NameStr == 0) return false;
786 std::string Name(NameStr); // Copy string
787 free(NameStr); // Free old string
789 // We don't allow assigning names to void type
790 if (T == Type::VoidTy) {
791 error("Can't assign name '" + Name + "' to the void type");
795 // Set the type name, checking for conflicts as we do so.
796 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
798 if (AlreadyExists) { // Inserting a name that is already defined???
799 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
800 assert(Existing && "Conflict but no matching type?");
802 // There is only one case where this is allowed: when we are refining an
803 // opaque type. In this case, Existing will be an opaque type.
804 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
805 // We ARE replacing an opaque type!
806 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
810 // Otherwise, this is an attempt to redefine a type. That's okay if
811 // the redefinition is identical to the original. This will be so if
812 // Existing and T point to the same Type object. In this one case we
813 // allow the equivalent redefinition.
814 if (Existing == T) return true; // Yes, it's equal.
816 // Any other kind of (non-equivalent) redefinition is an error.
817 error("Redefinition of type named '" + Name + "' in the '" +
818 T->getDescription() + "' type plane");
824 //===----------------------------------------------------------------------===//
825 // Code for handling upreferences in type names...
828 // TypeContains - Returns true if Ty directly contains E in it.
830 static bool TypeContains(const Type *Ty, const Type *E) {
831 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
832 E) != Ty->subtype_end();
837 // NestingLevel - The number of nesting levels that need to be popped before
838 // this type is resolved.
839 unsigned NestingLevel;
841 // LastContainedTy - This is the type at the current binding level for the
842 // type. Every time we reduce the nesting level, this gets updated.
843 const Type *LastContainedTy;
845 // UpRefTy - This is the actual opaque type that the upreference is
849 UpRefRecord(unsigned NL, OpaqueType *URTy)
850 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
854 // UpRefs - A list of the outstanding upreferences that need to be resolved.
855 static std::vector<UpRefRecord> UpRefs;
857 /// HandleUpRefs - Every time we finish a new layer of types, this function is
858 /// called. It loops through the UpRefs vector, which is a list of the
859 /// currently active types. For each type, if the up reference is contained in
860 /// the newly completed type, we decrement the level count. When the level
861 /// count reaches zero, the upreferenced type is the type that is passed in:
862 /// thus we can complete the cycle.
864 static PATypeHolder HandleUpRefs(const Type *ty) {
865 // If Ty isn't abstract, or if there are no up-references in it, then there is
866 // nothing to resolve here.
867 if (!ty->isAbstract() || UpRefs.empty()) return ty;
870 UR_OUT("Type '" << Ty->getDescription() <<
871 "' newly formed. Resolving upreferences.\n" <<
872 UpRefs.size() << " upreferences active!\n");
874 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
875 // to zero), we resolve them all together before we resolve them to Ty. At
876 // the end of the loop, if there is anything to resolve to Ty, it will be in
878 OpaqueType *TypeToResolve = 0;
880 for (unsigned i = 0; i != UpRefs.size(); ++i) {
881 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
882 << UpRefs[i].second->getDescription() << ") = "
883 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
884 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
885 // Decrement level of upreference
886 unsigned Level = --UpRefs[i].NestingLevel;
887 UpRefs[i].LastContainedTy = Ty;
888 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
889 if (Level == 0) { // Upreference should be resolved!
890 if (!TypeToResolve) {
891 TypeToResolve = UpRefs[i].UpRefTy;
893 UR_OUT(" * Resolving upreference for "
894 << UpRefs[i].second->getDescription() << "\n";
895 std::string OldName = UpRefs[i].UpRefTy->getDescription());
896 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
897 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
898 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
900 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
901 --i; // Do not skip the next element...
907 UR_OUT(" * Resolving upreference for "
908 << UpRefs[i].second->getDescription() << "\n";
909 std::string OldName = TypeToResolve->getDescription());
910 TypeToResolve->refineAbstractTypeTo(Ty);
916 static inline Instruction::TermOps
917 getTermOp(TermOps op) {
919 default : assert(0 && "Invalid OldTermOp");
920 case RetOp : return Instruction::Ret;
921 case BrOp : return Instruction::Br;
922 case SwitchOp : return Instruction::Switch;
923 case InvokeOp : return Instruction::Invoke;
924 case UnwindOp : return Instruction::Unwind;
925 case UnreachableOp: return Instruction::Unreachable;
929 static inline Instruction::BinaryOps
930 getBinaryOp(BinaryOps op, const Type *Ty, Signedness Sign) {
932 default : assert(0 && "Invalid OldBinaryOps");
938 case SetGT : assert(0 && "Should use getCompareOp");
939 case AddOp : return Instruction::Add;
940 case SubOp : return Instruction::Sub;
941 case MulOp : return Instruction::Mul;
943 // This is an obsolete instruction so we must upgrade it based on the
944 // types of its operands.
945 bool isFP = Ty->isFloatingPoint();
946 if (const PackedType* PTy = dyn_cast<PackedType>(Ty))
947 // If its a packed type we want to use the element type
948 isFP = PTy->getElementType()->isFloatingPoint();
950 return Instruction::FDiv;
951 else if (Sign == Signed)
952 return Instruction::SDiv;
953 return Instruction::UDiv;
955 case UDivOp : return Instruction::UDiv;
956 case SDivOp : return Instruction::SDiv;
957 case FDivOp : return Instruction::FDiv;
959 // This is an obsolete instruction so we must upgrade it based on the
960 // types of its operands.
961 bool isFP = Ty->isFloatingPoint();
962 if (const PackedType* PTy = dyn_cast<PackedType>(Ty))
963 // If its a packed type we want to use the element type
964 isFP = PTy->getElementType()->isFloatingPoint();
965 // Select correct opcode
967 return Instruction::FRem;
968 else if (Sign == Signed)
969 return Instruction::SRem;
970 return Instruction::URem;
972 case URemOp : return Instruction::URem;
973 case SRemOp : return Instruction::SRem;
974 case FRemOp : return Instruction::FRem;
975 case AndOp : return Instruction::And;
976 case OrOp : return Instruction::Or;
977 case XorOp : return Instruction::Xor;
981 static inline Instruction::OtherOps
982 getCompareOp(BinaryOps op, unsigned short &predicate, const Type* &Ty,
984 bool isSigned = Sign == Signed;
985 bool isFP = Ty->isFloatingPoint();
987 default : assert(0 && "Invalid OldSetCC");
990 predicate = FCmpInst::FCMP_OEQ;
991 return Instruction::FCmp;
993 predicate = ICmpInst::ICMP_EQ;
994 return Instruction::ICmp;
998 predicate = FCmpInst::FCMP_UNE;
999 return Instruction::FCmp;
1001 predicate = ICmpInst::ICMP_NE;
1002 return Instruction::ICmp;
1006 predicate = FCmpInst::FCMP_OLE;
1007 return Instruction::FCmp;
1010 predicate = ICmpInst::ICMP_SLE;
1012 predicate = ICmpInst::ICMP_ULE;
1013 return Instruction::ICmp;
1017 predicate = FCmpInst::FCMP_OGE;
1018 return Instruction::FCmp;
1021 predicate = ICmpInst::ICMP_SGE;
1023 predicate = ICmpInst::ICMP_UGE;
1024 return Instruction::ICmp;
1028 predicate = FCmpInst::FCMP_OLT;
1029 return Instruction::FCmp;
1032 predicate = ICmpInst::ICMP_SLT;
1034 predicate = ICmpInst::ICMP_ULT;
1035 return Instruction::ICmp;
1039 predicate = FCmpInst::FCMP_OGT;
1040 return Instruction::FCmp;
1043 predicate = ICmpInst::ICMP_SGT;
1045 predicate = ICmpInst::ICMP_UGT;
1046 return Instruction::ICmp;
1051 static inline Instruction::MemoryOps getMemoryOp(MemoryOps op) {
1053 default : assert(0 && "Invalid OldMemoryOps");
1054 case MallocOp : return Instruction::Malloc;
1055 case FreeOp : return Instruction::Free;
1056 case AllocaOp : return Instruction::Alloca;
1057 case LoadOp : return Instruction::Load;
1058 case StoreOp : return Instruction::Store;
1059 case GetElementPtrOp : return Instruction::GetElementPtr;
1063 static inline Instruction::OtherOps
1064 getOtherOp(OtherOps op, Signedness Sign) {
1066 default : assert(0 && "Invalid OldOtherOps");
1067 case PHIOp : return Instruction::PHI;
1068 case CallOp : return Instruction::Call;
1069 case ShlOp : return Instruction::Shl;
1072 return Instruction::AShr;
1073 return Instruction::LShr;
1074 case SelectOp : return Instruction::Select;
1075 case UserOp1 : return Instruction::UserOp1;
1076 case UserOp2 : return Instruction::UserOp2;
1077 case VAArg : return Instruction::VAArg;
1078 case ExtractElementOp : return Instruction::ExtractElement;
1079 case InsertElementOp : return Instruction::InsertElement;
1080 case ShuffleVectorOp : return Instruction::ShuffleVector;
1081 case ICmpOp : return Instruction::ICmp;
1082 case FCmpOp : return Instruction::FCmp;
1083 case LShrOp : return Instruction::LShr;
1084 case AShrOp : return Instruction::AShr;
1088 static inline Value*
1089 getCast(CastOps op, Value *Src, Signedness SrcSign, const Type *DstTy,
1090 Signedness DstSign, bool ForceInstruction = false) {
1091 Instruction::CastOps Opcode;
1092 const Type* SrcTy = Src->getType();
1094 if (SrcTy->isFloatingPoint() && isa<PointerType>(DstTy)) {
1095 // fp -> ptr cast is no longer supported but we must upgrade this
1096 // by doing a double cast: fp -> int -> ptr
1097 SrcTy = Type::Int64Ty;
1098 Opcode = Instruction::IntToPtr;
1099 if (isa<Constant>(Src)) {
1100 Src = ConstantExpr::getCast(Instruction::FPToUI,
1101 cast<Constant>(Src), SrcTy);
1103 std::string NewName(makeNameUnique(Src->getName()));
1104 Src = new FPToUIInst(Src, SrcTy, NewName, CurBB);
1106 } else if (isa<IntegerType>(DstTy) &&
1107 cast<IntegerType>(DstTy)->getBitWidth() == 1) {
1108 // cast type %x to bool was previously defined as setne type %x, null
1109 // The cast semantic is now to truncate, not compare so we must retain
1110 // the original intent by replacing the cast with a setne
1111 Constant* Null = Constant::getNullValue(SrcTy);
1112 Instruction::OtherOps Opcode = Instruction::ICmp;
1113 unsigned short predicate = ICmpInst::ICMP_NE;
1114 if (SrcTy->isFloatingPoint()) {
1115 Opcode = Instruction::FCmp;
1116 predicate = FCmpInst::FCMP_ONE;
1117 } else if (!SrcTy->isInteger() && !isa<PointerType>(SrcTy)) {
1118 error("Invalid cast to bool");
1120 if (isa<Constant>(Src) && !ForceInstruction)
1121 return ConstantExpr::getCompare(predicate, cast<Constant>(Src), Null);
1123 return CmpInst::create(Opcode, predicate, Src, Null);
1125 // Determine the opcode to use by calling CastInst::getCastOpcode
1127 CastInst::getCastOpcode(Src, SrcSign == Signed, DstTy, DstSign == Signed);
1129 } else switch (op) {
1130 default: assert(0 && "Invalid cast token");
1131 case TruncOp: Opcode = Instruction::Trunc; break;
1132 case ZExtOp: Opcode = Instruction::ZExt; break;
1133 case SExtOp: Opcode = Instruction::SExt; break;
1134 case FPTruncOp: Opcode = Instruction::FPTrunc; break;
1135 case FPExtOp: Opcode = Instruction::FPExt; break;
1136 case FPToUIOp: Opcode = Instruction::FPToUI; break;
1137 case FPToSIOp: Opcode = Instruction::FPToSI; break;
1138 case UIToFPOp: Opcode = Instruction::UIToFP; break;
1139 case SIToFPOp: Opcode = Instruction::SIToFP; break;
1140 case PtrToIntOp: Opcode = Instruction::PtrToInt; break;
1141 case IntToPtrOp: Opcode = Instruction::IntToPtr; break;
1142 case BitCastOp: Opcode = Instruction::BitCast; break;
1145 if (isa<Constant>(Src) && !ForceInstruction)
1146 return ConstantExpr::getCast(Opcode, cast<Constant>(Src), DstTy);
1147 return CastInst::create(Opcode, Src, DstTy);
1150 static Instruction *
1151 upgradeIntrinsicCall(const Type* RetTy, const ValID &ID,
1152 std::vector<Value*>& Args) {
1154 std::string Name = ID.Type == ValID::NameVal ? ID.Name : "";
1155 if (Name == "llvm.isunordered.f32" || Name == "llvm.isunordered.f64") {
1156 if (Args.size() != 2)
1157 error("Invalid prototype for " + Name + " prototype");
1158 return new FCmpInst(FCmpInst::FCMP_UNO, Args[0], Args[1]);
1160 static unsigned upgradeCount = 1;
1161 const Type* PtrTy = PointerType::get(Type::Int8Ty);
1162 std::vector<const Type*> Params;
1163 if (Name == "llvm.va_start" || Name == "llvm.va_end") {
1164 if (Args.size() != 1)
1165 error("Invalid prototype for " + Name + " prototype");
1166 Params.push_back(PtrTy);
1167 const FunctionType *FTy = FunctionType::get(Type::VoidTy, Params, false);
1168 const PointerType *PFTy = PointerType::get(FTy);
1169 Value* Func = getVal(PFTy, ID);
1170 std::string InstName("va_upgrade");
1171 InstName += llvm::utostr(upgradeCount++);
1172 Args[0] = new BitCastInst(Args[0], PtrTy, InstName, CurBB);
1173 return new CallInst(Func, Args);
1174 } else if (Name == "llvm.va_copy") {
1175 if (Args.size() != 2)
1176 error("Invalid prototype for " + Name + " prototype");
1177 Params.push_back(PtrTy);
1178 Params.push_back(PtrTy);
1179 const FunctionType *FTy = FunctionType::get(Type::VoidTy, Params, false);
1180 const PointerType *PFTy = PointerType::get(FTy);
1181 Value* Func = getVal(PFTy, ID);
1182 std::string InstName0("va_upgrade");
1183 InstName0 += llvm::utostr(upgradeCount++);
1184 std::string InstName1("va_upgrade");
1185 InstName1 += llvm::utostr(upgradeCount++);
1186 Args[0] = new BitCastInst(Args[0], PtrTy, InstName0, CurBB);
1187 Args[1] = new BitCastInst(Args[1], PtrTy, InstName1, CurBB);
1188 return new CallInst(Func, Args);
1194 const Type* upgradeGEPIndices(const Type* PTy,
1195 std::vector<ValueInfo> *Indices,
1196 std::vector<Value*> &VIndices,
1197 std::vector<Constant*> *CIndices = 0) {
1198 // Traverse the indices with a gep_type_iterator so we can build the list
1199 // of constant and value indices for use later. Also perform upgrades
1201 if (CIndices) CIndices->clear();
1202 for (unsigned i = 0, e = Indices->size(); i != e; ++i)
1203 VIndices.push_back((*Indices)[i].V);
1204 generic_gep_type_iterator<std::vector<Value*>::iterator>
1205 GTI = gep_type_begin(PTy, VIndices.begin(), VIndices.end()),
1206 GTE = gep_type_end(PTy, VIndices.begin(), VIndices.end());
1207 for (unsigned i = 0, e = Indices->size(); i != e && GTI != GTE; ++i, ++GTI) {
1208 Value *Index = VIndices[i];
1209 if (CIndices && !isa<Constant>(Index))
1210 error("Indices to constant getelementptr must be constants");
1211 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte
1212 // struct indices to i32 struct indices with ZExt for compatibility.
1213 else if (isa<StructType>(*GTI)) { // Only change struct indices
1214 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Index))
1215 if (CUI->getType()->getBitWidth() == 8)
1217 ConstantExpr::getCast(Instruction::ZExt, CUI, Type::Int32Ty);
1219 // Make sure that unsigned SequentialType indices are zext'd to
1220 // 64-bits if they were smaller than that because LLVM 2.0 will sext
1221 // all indices for SequentialType elements. We must retain the same
1222 // semantic (zext) for unsigned types.
1223 if (const IntegerType *Ity = dyn_cast<IntegerType>(Index->getType()))
1224 if (Ity->getBitWidth() < 64 && (*Indices)[i].S == Unsigned) {
1226 Index = ConstantExpr::getCast(Instruction::ZExt,
1227 cast<Constant>(Index), Type::Int64Ty);
1229 Index = CastInst::create(Instruction::ZExt, Index, Type::Int64Ty,
1230 makeNameUnique("gep_upgrade"), CurBB);
1231 VIndices[i] = Index;
1234 // Add to the CIndices list, if requested.
1236 CIndices->push_back(cast<Constant>(Index));
1240 GetElementPtrInst::getIndexedType(PTy, VIndices, true);
1242 error("Index list invalid for constant getelementptr");
1246 Module* UpgradeAssembly(const std::string &infile, std::istream& in,
1247 bool debug, bool addAttrs)
1250 CurFilename = infile;
1253 AddAttributes = addAttrs;
1254 ObsoleteVarArgs = false;
1257 CurModule.CurrentModule = new Module(CurFilename);
1259 // Check to make sure the parser succeeded
1262 delete ParserResult;
1263 std::cerr << "llvm-upgrade: parse failed.\n";
1267 // Check to make sure that parsing produced a result
1268 if (!ParserResult) {
1269 std::cerr << "llvm-upgrade: no parse result.\n";
1273 // Reset ParserResult variable while saving its value for the result.
1274 Module *Result = ParserResult;
1277 //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
1280 if ((F = Result->getNamedFunction("llvm.va_start"))
1281 && F->getFunctionType()->getNumParams() == 0)
1282 ObsoleteVarArgs = true;
1283 if((F = Result->getNamedFunction("llvm.va_copy"))
1284 && F->getFunctionType()->getNumParams() == 1)
1285 ObsoleteVarArgs = true;
1288 if (ObsoleteVarArgs && NewVarArgs) {
1289 error("This file is corrupt: it uses both new and old style varargs");
1293 if(ObsoleteVarArgs) {
1294 if(Function* F = Result->getNamedFunction("llvm.va_start")) {
1295 if (F->arg_size() != 0) {
1296 error("Obsolete va_start takes 0 argument");
1302 //bar = alloca typeof(foo)
1306 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1307 const Type* ArgTy = F->getFunctionType()->getReturnType();
1308 const Type* ArgTyPtr = PointerType::get(ArgTy);
1309 Function* NF = cast<Function>(Result->getOrInsertFunction(
1310 "llvm.va_start", RetTy, ArgTyPtr, (Type *)0));
1312 while (!F->use_empty()) {
1313 CallInst* CI = cast<CallInst>(F->use_back());
1314 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
1315 new CallInst(NF, bar, "", CI);
1316 Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
1317 CI->replaceAllUsesWith(foo);
1318 CI->getParent()->getInstList().erase(CI);
1320 Result->getFunctionList().erase(F);
1323 if(Function* F = Result->getNamedFunction("llvm.va_end")) {
1324 if(F->arg_size() != 1) {
1325 error("Obsolete va_end takes 1 argument");
1331 //bar = alloca 1 of typeof(foo)
1333 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1334 const Type* ArgTy = F->getFunctionType()->getParamType(0);
1335 const Type* ArgTyPtr = PointerType::get(ArgTy);
1336 Function* NF = cast<Function>(Result->getOrInsertFunction(
1337 "llvm.va_end", RetTy, ArgTyPtr, (Type *)0));
1339 while (!F->use_empty()) {
1340 CallInst* CI = cast<CallInst>(F->use_back());
1341 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
1342 new StoreInst(CI->getOperand(1), bar, CI);
1343 new CallInst(NF, bar, "", CI);
1344 CI->getParent()->getInstList().erase(CI);
1346 Result->getFunctionList().erase(F);
1349 if(Function* F = Result->getNamedFunction("llvm.va_copy")) {
1350 if(F->arg_size() != 1) {
1351 error("Obsolete va_copy takes 1 argument");
1356 //a = alloca 1 of typeof(foo)
1357 //b = alloca 1 of typeof(foo)
1362 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1363 const Type* ArgTy = F->getFunctionType()->getReturnType();
1364 const Type* ArgTyPtr = PointerType::get(ArgTy);
1365 Function* NF = cast<Function>(Result->getOrInsertFunction(
1366 "llvm.va_copy", RetTy, ArgTyPtr, ArgTyPtr, (Type *)0));
1368 while (!F->use_empty()) {
1369 CallInst* CI = cast<CallInst>(F->use_back());
1370 AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
1371 AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
1372 new StoreInst(CI->getOperand(1), b, CI);
1373 new CallInst(NF, a, b, "", CI);
1374 Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
1375 CI->replaceAllUsesWith(foo);
1376 CI->getParent()->getInstList().erase(CI);
1378 Result->getFunctionList().erase(F);
1385 } // end llvm namespace
1387 using namespace llvm;
1392 llvm::Module *ModuleVal;
1393 llvm::Function *FunctionVal;
1394 std::pair<llvm::PATypeInfo, char*> *ArgVal;
1395 llvm::BasicBlock *BasicBlockVal;
1396 llvm::TerminatorInst *TermInstVal;
1397 llvm::InstrInfo InstVal;
1398 llvm::ConstInfo ConstVal;
1399 llvm::ValueInfo ValueVal;
1400 llvm::PATypeInfo TypeVal;
1401 llvm::TypeInfo PrimType;
1402 llvm::PHIListInfo PHIList;
1403 std::list<llvm::PATypeInfo> *TypeList;
1404 std::vector<llvm::ValueInfo> *ValueList;
1405 std::vector<llvm::ConstInfo> *ConstVector;
1408 std::vector<std::pair<llvm::PATypeInfo,char*> > *ArgList;
1409 // Represent the RHS of PHI node
1410 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
1412 llvm::GlobalValue::LinkageTypes Linkage;
1420 char *StrVal; // This memory is strdup'd!
1421 llvm::ValID ValIDVal; // strdup'd memory maybe!
1423 llvm::BinaryOps BinaryOpVal;
1424 llvm::TermOps TermOpVal;
1425 llvm::MemoryOps MemOpVal;
1426 llvm::OtherOps OtherOpVal;
1427 llvm::CastOps CastOpVal;
1428 llvm::ICmpInst::Predicate IPred;
1429 llvm::FCmpInst::Predicate FPred;
1430 llvm::Module::Endianness Endianness;
1433 %type <ModuleVal> Module FunctionList
1434 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1435 %type <BasicBlockVal> BasicBlock InstructionList
1436 %type <TermInstVal> BBTerminatorInst
1437 %type <InstVal> Inst InstVal MemoryInst
1438 %type <ConstVal> ConstVal ConstExpr
1439 %type <ConstVector> ConstVector
1440 %type <ArgList> ArgList ArgListH
1441 %type <ArgVal> ArgVal
1442 %type <PHIList> PHIList
1443 %type <ValueList> ValueRefList ValueRefListE // For call param lists
1444 %type <ValueList> IndexList // For GEP derived indices
1445 %type <TypeList> TypeListI ArgTypeListI
1446 %type <JumpTable> JumpTable
1447 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1448 %type <BoolVal> OptVolatile // 'volatile' or not
1449 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1450 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
1451 %type <Linkage> OptLinkage
1452 %type <Endianness> BigOrLittle
1454 // ValueRef - Unresolved reference to a definition or BB
1455 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1456 %type <ValueVal> ResolvedVal // <type> <valref> pair
1458 // Tokens and types for handling constant integer values
1460 // ESINT64VAL - A negative number within long long range
1461 %token <SInt64Val> ESINT64VAL
1463 // EUINT64VAL - A positive number within uns. long long range
1464 %token <UInt64Val> EUINT64VAL
1465 %type <SInt64Val> EINT64VAL
1467 %token <SIntVal> SINTVAL // Signed 32 bit ints...
1468 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
1469 %type <SIntVal> INTVAL
1470 %token <FPVal> FPVAL // Float or Double constant
1472 // Built in types...
1473 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
1474 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
1475 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
1476 %token <PrimType> FLOAT DOUBLE TYPE LABEL
1478 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
1479 %type <StrVal> Name OptName OptAssign
1480 %type <UIntVal> OptAlign OptCAlign
1481 %type <StrVal> OptSection SectionString
1483 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1484 %token DECLARE GLOBAL CONSTANT SECTION VOLATILE
1485 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
1486 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
1487 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
1488 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1489 %token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
1490 %token X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1492 %type <UIntVal> OptCallingConv
1494 // Basic Block Terminating Operators
1495 %token <TermOpVal> RET BR SWITCH INVOKE UNREACHABLE
1496 %token UNWIND EXCEPT
1499 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
1500 %token <BinaryOpVal> ADD SUB MUL DIV UDIV SDIV FDIV REM UREM SREM FREM
1501 %token <BinaryOpVal> AND OR XOR
1502 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comparators
1503 %token <OtherOpVal> ICMP FCMP
1505 // Memory Instructions
1506 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1509 %type <OtherOpVal> ShiftOps
1510 %token <OtherOpVal> PHI_TOK SELECT SHL SHR ASHR LSHR VAARG
1511 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1512 %token VAARG_old VANEXT_old //OBSOLETE
1514 // Support for ICmp/FCmp Predicates, which is 1.9++ but not 2.0
1515 %type <IPred> IPredicates
1516 %type <FPred> FPredicates
1517 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1518 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1520 %token <CastOpVal> CAST TRUNC ZEXT SEXT FPTRUNC FPEXT FPTOUI FPTOSI
1521 %token <CastOpVal> UITOFP SITOFP PTRTOINT INTTOPTR BITCAST
1522 %type <CastOpVal> CastOps
1528 // Handle constant integer size restriction and conversion...
1533 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
1534 error("Value too large for type");
1540 : ESINT64VAL // These have same type and can't cause problems...
1542 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
1543 error("Value too large for type");
1547 // Operations that are notably excluded from this list include:
1548 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1551 : ADD | SUB | MUL | DIV | UDIV | SDIV | FDIV | REM | UREM | SREM | FREM
1559 : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
1563 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1564 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1565 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1566 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1567 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1571 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1572 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1573 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1574 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1575 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1576 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1577 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1578 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1579 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1582 : SHL | SHR | ASHR | LSHR
1586 : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | FPTOUI | FPTOSI
1587 | UITOFP | SITOFP | PTRTOINT | INTTOPTR | BITCAST | CAST
1590 // These are some types that allow classification if we only want a particular
1591 // thing... for example, only a signed, unsigned, or integral type.
1593 : LONG | INT | SHORT | SBYTE
1597 : ULONG | UINT | USHORT | UBYTE
1601 : SIntType | UIntType
1608 // OptAssign - Value producing statements have an optional assignment component
1618 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1619 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1620 | WEAK { $$ = GlobalValue::WeakLinkage; }
1621 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1622 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1623 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1624 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1625 | /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1629 : /*empty*/ { $$ = CallingConv::C; }
1630 | CCC_TOK { $$ = CallingConv::C; }
1631 | CSRETCC_TOK { $$ = CallingConv::CSRet; }
1632 | FASTCC_TOK { $$ = CallingConv::Fast; }
1633 | COLDCC_TOK { $$ = CallingConv::Cold; }
1634 | X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; }
1635 | X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; }
1636 | CC_TOK EUINT64VAL {
1637 if ((unsigned)$2 != $2)
1638 error("Calling conv too large");
1643 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1644 // a comma before it.
1646 : /*empty*/ { $$ = 0; }
1647 | ALIGN EUINT64VAL {
1649 if ($$ != 0 && !isPowerOf2_32($$))
1650 error("Alignment must be a power of two");
1655 : /*empty*/ { $$ = 0; }
1656 | ',' ALIGN EUINT64VAL {
1658 if ($$ != 0 && !isPowerOf2_32($$))
1659 error("Alignment must be a power of two");
1664 : SECTION STRINGCONSTANT {
1665 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1666 if ($2[i] == '"' || $2[i] == '\\')
1667 error("Invalid character in section name");
1673 : /*empty*/ { $$ = 0; }
1674 | SectionString { $$ = $1; }
1677 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1678 // is set to be the global we are processing.
1682 | ',' GlobalVarAttribute GlobalVarAttributes {}
1687 CurGV->setSection($1);
1690 | ALIGN EUINT64VAL {
1691 if ($2 != 0 && !isPowerOf2_32($2))
1692 error("Alignment must be a power of two");
1693 CurGV->setAlignment($2);
1698 //===----------------------------------------------------------------------===//
1699 // Types includes all predefined types... except void, because it can only be
1700 // used in specific contexts (function returning void for example). To have
1701 // access to it, a user must explicitly use TypesV.
1704 // TypesV includes all of 'Types', but it also includes the void type.
1708 $$.T = new PATypeHolder($1.T);
1716 $$.T = new PATypeHolder($1.T);
1723 if (!UpRefs.empty())
1724 error("Invalid upreference in type: " + (*$1.T)->getDescription());
1730 : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT
1731 | LONG | ULONG | FLOAT | DOUBLE | LABEL
1734 // Derived types are added later...
1737 $$.T = new PATypeHolder($1.T);
1741 $$.T = new PATypeHolder(OpaqueType::get());
1744 | SymbolicValueRef { // Named types are also simple types...
1745 const Type* tmp = getType($1);
1746 $$.T = new PATypeHolder(tmp);
1747 $$.S = Signless; // FIXME: what if its signed?
1749 | '\\' EUINT64VAL { // Type UpReference
1750 if ($2 > (uint64_t)~0U)
1751 error("Value out of range");
1752 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1753 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1754 $$.T = new PATypeHolder(OT);
1756 UR_OUT("New Upreference!\n");
1758 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
1759 std::vector<const Type*> Params;
1760 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
1761 E = $3->end(); I != E; ++I) {
1762 Params.push_back(I->T->get());
1765 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1766 if (isVarArg) Params.pop_back();
1768 $$.T = new PATypeHolder(HandleUpRefs(
1769 FunctionType::get($1.T->get(),Params,isVarArg)));
1771 delete $1.T; // Delete the return type handle
1772 delete $3; // Delete the argument list
1774 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
1775 $$.T = new PATypeHolder(HandleUpRefs(ArrayType::get($4.T->get(),
1780 | '<' EUINT64VAL 'x' UpRTypes '>' { // Packed array type?
1781 const llvm::Type* ElemTy = $4.T->get();
1782 if ((unsigned)$2 != $2)
1783 error("Unsigned result not equal to signed result");
1784 if (!(ElemTy->isInteger() || ElemTy->isFloatingPoint()))
1785 error("Elements of a PackedType must be integer or floating point");
1786 if (!isPowerOf2_32($2))
1787 error("PackedType length should be a power of 2");
1788 $$.T = new PATypeHolder(HandleUpRefs(PackedType::get(ElemTy,
1793 | '{' TypeListI '}' { // Structure type?
1794 std::vector<const Type*> Elements;
1795 for (std::list<llvm::PATypeInfo>::iterator I = $2->begin(),
1796 E = $2->end(); I != E; ++I)
1797 Elements.push_back(I->T->get());
1798 $$.T = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1802 | '{' '}' { // Empty structure type?
1803 $$.T = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1806 | '<' '{' TypeListI '}' '>' { // Packed Structure type?
1807 std::vector<const Type*> Elements;
1808 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
1809 E = $3->end(); I != E; ++I) {
1810 Elements.push_back(I->T->get());
1813 $$.T = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1817 | '<' '{' '}' '>' { // Empty packed structure type?
1818 $$.T = new PATypeHolder(StructType::get(std::vector<const Type*>(),true));
1821 | UpRTypes '*' { // Pointer type?
1822 if ($1.T->get() == Type::LabelTy)
1823 error("Cannot form a pointer to a basic block");
1824 $$.T = new PATypeHolder(HandleUpRefs(PointerType::get($1.T->get())));
1830 // TypeList - Used for struct declarations and as a basis for function type
1831 // declaration type lists
1835 $$ = new std::list<PATypeInfo>();
1838 | TypeListI ',' UpRTypes {
1839 ($$=$1)->push_back($3);
1843 // ArgTypeList - List of types for a function type declaration...
1846 | TypeListI ',' DOTDOTDOT {
1848 VoidTI.T = new PATypeHolder(Type::VoidTy);
1849 VoidTI.S = Signless;
1850 ($$=$1)->push_back(VoidTI);
1853 $$ = new std::list<PATypeInfo>();
1855 VoidTI.T = new PATypeHolder(Type::VoidTy);
1856 VoidTI.S = Signless;
1857 $$->push_back(VoidTI);
1860 $$ = new std::list<PATypeInfo>();
1864 // ConstVal - The various declarations that go into the constant pool. This
1865 // production is used ONLY to represent constants that show up AFTER a 'const',
1866 // 'constant' or 'global' token at global scope. Constants that can be inlined
1867 // into other expressions (such as integers and constexprs) are handled by the
1868 // ResolvedVal, ValueRef and ConstValueRef productions.
1871 : Types '[' ConstVector ']' { // Nonempty unsized arr
1872 const ArrayType *ATy = dyn_cast<ArrayType>($1.T->get());
1874 error("Cannot make array constant with type: '" +
1875 $1.T->get()->getDescription() + "'");
1876 const Type *ETy = ATy->getElementType();
1877 int NumElements = ATy->getNumElements();
1879 // Verify that we have the correct size...
1880 if (NumElements != -1 && NumElements != (int)$3->size())
1881 error("Type mismatch: constant sized array initialized with " +
1882 utostr($3->size()) + " arguments, but has size of " +
1883 itostr(NumElements) + "");
1885 // Verify all elements are correct type!
1886 std::vector<Constant*> Elems;
1887 for (unsigned i = 0; i < $3->size(); i++) {
1888 Constant *C = (*$3)[i].C;
1889 const Type* ValTy = C->getType();
1891 error("Element #" + utostr(i) + " is not of type '" +
1892 ETy->getDescription() +"' as required!\nIt is of type '"+
1893 ValTy->getDescription() + "'");
1896 $$.C = ConstantArray::get(ATy, Elems);
1902 const ArrayType *ATy = dyn_cast<ArrayType>($1.T->get());
1904 error("Cannot make array constant with type: '" +
1905 $1.T->get()->getDescription() + "'");
1906 int NumElements = ATy->getNumElements();
1907 if (NumElements != -1 && NumElements != 0)
1908 error("Type mismatch: constant sized array initialized with 0"
1909 " arguments, but has size of " + itostr(NumElements) +"");
1910 $$.C = ConstantArray::get(ATy, std::vector<Constant*>());
1914 | Types 'c' STRINGCONSTANT {
1915 const ArrayType *ATy = dyn_cast<ArrayType>($1.T->get());
1917 error("Cannot make array constant with type: '" +
1918 $1.T->get()->getDescription() + "'");
1919 int NumElements = ATy->getNumElements();
1920 const Type *ETy = dyn_cast<IntegerType>(ATy->getElementType());
1921 if (!ETy || cast<IntegerType>(ETy)->getBitWidth() != 8)
1922 error("String arrays require type i8, not '" + ETy->getDescription() +
1924 char *EndStr = UnEscapeLexed($3, true);
1925 if (NumElements != -1 && NumElements != (EndStr-$3))
1926 error("Can't build string constant of size " +
1927 itostr((int)(EndStr-$3)) + " when array has size " +
1928 itostr(NumElements) + "");
1929 std::vector<Constant*> Vals;
1930 for (char *C = (char *)$3; C != (char *)EndStr; ++C)
1931 Vals.push_back(ConstantInt::get(ETy, *C));
1933 $$.C = ConstantArray::get(ATy, Vals);
1937 | Types '<' ConstVector '>' { // Nonempty unsized arr
1938 const PackedType *PTy = dyn_cast<PackedType>($1.T->get());
1940 error("Cannot make packed constant with type: '" +
1941 $1.T->get()->getDescription() + "'");
1942 const Type *ETy = PTy->getElementType();
1943 int NumElements = PTy->getNumElements();
1944 // Verify that we have the correct size...
1945 if (NumElements != -1 && NumElements != (int)$3->size())
1946 error("Type mismatch: constant sized packed initialized with " +
1947 utostr($3->size()) + " arguments, but has size of " +
1948 itostr(NumElements) + "");
1949 // Verify all elements are correct type!
1950 std::vector<Constant*> Elems;
1951 for (unsigned i = 0; i < $3->size(); i++) {
1952 Constant *C = (*$3)[i].C;
1953 const Type* ValTy = C->getType();
1955 error("Element #" + utostr(i) + " is not of type '" +
1956 ETy->getDescription() +"' as required!\nIt is of type '"+
1957 ValTy->getDescription() + "'");
1960 $$.C = ConstantPacked::get(PTy, Elems);
1965 | Types '{' ConstVector '}' {
1966 const StructType *STy = dyn_cast<StructType>($1.T->get());
1968 error("Cannot make struct constant with type: '" +
1969 $1.T->get()->getDescription() + "'");
1970 if ($3->size() != STy->getNumContainedTypes())
1971 error("Illegal number of initializers for structure type");
1973 // Check to ensure that constants are compatible with the type initializer!
1974 std::vector<Constant*> Fields;
1975 for (unsigned i = 0, e = $3->size(); i != e; ++i) {
1976 Constant *C = (*$3)[i].C;
1977 if (C->getType() != STy->getElementType(i))
1978 error("Expected type '" + STy->getElementType(i)->getDescription() +
1979 "' for element #" + utostr(i) + " of structure initializer");
1980 Fields.push_back(C);
1982 $$.C = ConstantStruct::get(STy, Fields);
1988 const StructType *STy = dyn_cast<StructType>($1.T->get());
1990 error("Cannot make struct constant with type: '" +
1991 $1.T->get()->getDescription() + "'");
1992 if (STy->getNumContainedTypes() != 0)
1993 error("Illegal number of initializers for structure type");
1994 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
1998 | Types '<' '{' ConstVector '}' '>' {
1999 const StructType *STy = dyn_cast<StructType>($1.T->get());
2001 error("Cannot make packed struct constant with type: '" +
2002 $1.T->get()->getDescription() + "'");
2003 if ($4->size() != STy->getNumContainedTypes())
2004 error("Illegal number of initializers for packed structure type");
2006 // Check to ensure that constants are compatible with the type initializer!
2007 std::vector<Constant*> Fields;
2008 for (unsigned i = 0, e = $4->size(); i != e; ++i) {
2009 Constant *C = (*$4)[i].C;
2010 if (C->getType() != STy->getElementType(i))
2011 error("Expected type '" + STy->getElementType(i)->getDescription() +
2012 "' for element #" + utostr(i) + " of packed struct initializer");
2013 Fields.push_back(C);
2015 $$.C = ConstantStruct::get(STy, Fields);
2020 | Types '<' '{' '}' '>' {
2021 const StructType *STy = dyn_cast<StructType>($1.T->get());
2023 error("Cannot make packed struct constant with type: '" +
2024 $1.T->get()->getDescription() + "'");
2025 if (STy->getNumContainedTypes() != 0)
2026 error("Illegal number of initializers for packed structure type");
2027 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2032 const PointerType *PTy = dyn_cast<PointerType>($1.T->get());
2034 error("Cannot make null pointer constant with type: '" +
2035 $1.T->get()->getDescription() + "'");
2036 $$.C = ConstantPointerNull::get(PTy);
2041 $$.C = UndefValue::get($1.T->get());
2045 | Types SymbolicValueRef {
2046 const PointerType *Ty = dyn_cast<PointerType>($1.T->get());
2048 error("Global const reference must be a pointer type, not" +
2049 $1.T->get()->getDescription());
2051 // ConstExprs can exist in the body of a function, thus creating
2052 // GlobalValues whenever they refer to a variable. Because we are in
2053 // the context of a function, getExistingValue will search the functions
2054 // symbol table instead of the module symbol table for the global symbol,
2055 // which throws things all off. To get around this, we just tell
2056 // getExistingValue that we are at global scope here.
2058 Function *SavedCurFn = CurFun.CurrentFunction;
2059 CurFun.CurrentFunction = 0;
2060 Value *V = getExistingValue(Ty, $2);
2061 CurFun.CurrentFunction = SavedCurFn;
2063 // If this is an initializer for a constant pointer, which is referencing a
2064 // (currently) undefined variable, create a stub now that shall be replaced
2065 // in the future with the right type of variable.
2068 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers");
2069 const PointerType *PT = cast<PointerType>(Ty);
2071 // First check to see if the forward references value is already created!
2072 PerModuleInfo::GlobalRefsType::iterator I =
2073 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
2075 if (I != CurModule.GlobalRefs.end()) {
2076 V = I->second; // Placeholder already exists, use it...
2080 if ($2.Type == ValID::NameVal) Name = $2.Name;
2082 // Create the forward referenced global.
2084 if (const FunctionType *FTy =
2085 dyn_cast<FunctionType>(PT->getElementType())) {
2086 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
2087 CurModule.CurrentModule);
2089 GV = new GlobalVariable(PT->getElementType(), false,
2090 GlobalValue::ExternalLinkage, 0,
2091 Name, CurModule.CurrentModule);
2094 // Keep track of the fact that we have a forward ref to recycle it
2095 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
2099 $$.C = cast<GlobalValue>(V);
2101 delete $1.T; // Free the type handle
2104 if ($1.T->get() != $2.C->getType())
2105 error("Mismatched types for constant expression");
2110 | Types ZEROINITIALIZER {
2111 const Type *Ty = $1.T->get();
2112 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
2113 error("Cannot create a null initialized value of this type");
2114 $$.C = Constant::getNullValue(Ty);
2118 | SIntType EINT64VAL { // integral constants
2119 const Type *Ty = $1.T;
2120 if (!ConstantInt::isValueValidForType(Ty, $2))
2121 error("Constant value doesn't fit in type");
2122 $$.C = ConstantInt::get(Ty, $2);
2125 | UIntType EUINT64VAL { // integral constants
2126 const Type *Ty = $1.T;
2127 if (!ConstantInt::isValueValidForType(Ty, $2))
2128 error("Constant value doesn't fit in type");
2129 $$.C = ConstantInt::get(Ty, $2);
2132 | BOOL TRUETOK { // Boolean constants
2133 $$.C = ConstantInt::get(Type::Int1Ty, true);
2136 | BOOL FALSETOK { // Boolean constants
2137 $$.C = ConstantInt::get(Type::Int1Ty, false);
2140 | FPType FPVAL { // Float & Double constants
2141 if (!ConstantFP::isValueValidForType($1.T, $2))
2142 error("Floating point constant invalid for type");
2143 $$.C = ConstantFP::get($1.T, $2);
2149 : CastOps '(' ConstVal TO Types ')' {
2150 const Type* SrcTy = $3.C->getType();
2151 const Type* DstTy = $5.T->get();
2152 Signedness SrcSign = $3.S;
2153 Signedness DstSign = $5.S;
2154 if (!SrcTy->isFirstClassType())
2155 error("cast constant expression from a non-primitive type: '" +
2156 SrcTy->getDescription() + "'");
2157 if (!DstTy->isFirstClassType())
2158 error("cast constant expression to a non-primitive type: '" +
2159 DstTy->getDescription() + "'");
2160 $$.C = cast<Constant>(getCast($1, $3.C, SrcSign, DstTy, DstSign));
2164 | GETELEMENTPTR '(' ConstVal IndexList ')' {
2165 const Type *Ty = $3.C->getType();
2166 if (!isa<PointerType>(Ty))
2167 error("GetElementPtr requires a pointer operand");
2169 std::vector<Value*> VIndices;
2170 std::vector<Constant*> CIndices;
2171 upgradeGEPIndices($3.C->getType(), $4, VIndices, &CIndices);
2174 $$.C = ConstantExpr::getGetElementPtr($3.C, CIndices);
2177 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2178 if (!$3.C->getType()->isInteger() ||
2179 cast<IntegerType>($3.C->getType())->getBitWidth() != 1)
2180 error("Select condition must be bool type");
2181 if ($5.C->getType() != $7.C->getType())
2182 error("Select operand types must match");
2183 $$.C = ConstantExpr::getSelect($3.C, $5.C, $7.C);
2186 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
2187 const Type *Ty = $3.C->getType();
2188 if (Ty != $5.C->getType())
2189 error("Binary operator types must match");
2190 // First, make sure we're dealing with the right opcode by upgrading from
2191 // obsolete versions.
2192 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2194 // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
2195 // To retain backward compatibility with these early compilers, we emit a
2196 // cast to the appropriate integer type automatically if we are in the
2197 // broken case. See PR424 for more information.
2198 if (!isa<PointerType>(Ty)) {
2199 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2201 const Type *IntPtrTy = 0;
2202 switch (CurModule.CurrentModule->getPointerSize()) {
2203 case Module::Pointer32: IntPtrTy = Type::Int32Ty; break;
2204 case Module::Pointer64: IntPtrTy = Type::Int64Ty; break;
2205 default: error("invalid pointer binary constant expr");
2207 $$.C = ConstantExpr::get(Opcode,
2208 ConstantExpr::getCast(Instruction::PtrToInt, $3.C, IntPtrTy),
2209 ConstantExpr::getCast(Instruction::PtrToInt, $5.C, IntPtrTy));
2210 $$.C = ConstantExpr::getCast(Instruction::IntToPtr, $$.C, Ty);
2214 | LogicalOps '(' ConstVal ',' ConstVal ')' {
2215 const Type* Ty = $3.C->getType();
2216 if (Ty != $5.C->getType())
2217 error("Logical operator types must match");
2218 if (!Ty->isInteger()) {
2219 if (!isa<PackedType>(Ty) ||
2220 !cast<PackedType>(Ty)->getElementType()->isInteger())
2221 error("Logical operator requires integer operands");
2223 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2224 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2227 | SetCondOps '(' ConstVal ',' ConstVal ')' {
2228 const Type* Ty = $3.C->getType();
2229 if (Ty != $5.C->getType())
2230 error("setcc operand types must match");
2231 unsigned short pred;
2232 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $3.S);
2233 $$.C = ConstantExpr::getCompare(Opcode, $3.C, $5.C);
2236 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
2237 if ($4.C->getType() != $6.C->getType())
2238 error("icmp operand types must match");
2239 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2242 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
2243 if ($4.C->getType() != $6.C->getType())
2244 error("fcmp operand types must match");
2245 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2248 | ShiftOps '(' ConstVal ',' ConstVal ')' {
2249 if (!$5.C->getType()->isInteger() ||
2250 cast<IntegerType>($5.C->getType())->getBitWidth() != 8)
2251 error("Shift count for shift constant must be unsigned byte");
2252 if (!$3.C->getType()->isInteger())
2253 error("Shift constant expression requires integer operand");
2254 $$.C = ConstantExpr::get(getOtherOp($1, $3.S), $3.C, $5.C);
2257 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
2258 if (!ExtractElementInst::isValidOperands($3.C, $5.C))
2259 error("Invalid extractelement operands");
2260 $$.C = ConstantExpr::getExtractElement($3.C, $5.C);
2263 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2264 if (!InsertElementInst::isValidOperands($3.C, $5.C, $7.C))
2265 error("Invalid insertelement operands");
2266 $$.C = ConstantExpr::getInsertElement($3.C, $5.C, $7.C);
2269 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2270 if (!ShuffleVectorInst::isValidOperands($3.C, $5.C, $7.C))
2271 error("Invalid shufflevector operands");
2272 $$.C = ConstantExpr::getShuffleVector($3.C, $5.C, $7.C);
2278 // ConstVector - A list of comma separated constants.
2280 : ConstVector ',' ConstVal { ($$ = $1)->push_back($3); }
2282 $$ = new std::vector<ConstInfo>();
2288 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
2290 : GLOBAL { $$ = false; }
2291 | CONSTANT { $$ = true; }
2295 //===----------------------------------------------------------------------===//
2296 // Rules to match Modules
2297 //===----------------------------------------------------------------------===//
2299 // Module rule: Capture the result of parsing the whole file into a result
2304 $$ = ParserResult = $1;
2305 CurModule.ModuleDone();
2309 // FunctionList - A list of functions, preceeded by a constant pool.
2312 : FunctionList Function { $$ = $1; CurFun.FunctionDone(); }
2313 | FunctionList FunctionProto { $$ = $1; }
2314 | FunctionList MODULE ASM_TOK AsmBlock { $$ = $1; }
2315 | FunctionList IMPLEMENTATION { $$ = $1; }
2317 $$ = CurModule.CurrentModule;
2318 // Emit an error if there are any unresolved types left.
2319 if (!CurModule.LateResolveTypes.empty()) {
2320 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
2321 if (DID.Type == ValID::NameVal) {
2322 error("Reference to an undefined type: '"+DID.getName() + "'");
2324 error("Reference to an undefined type: #" + itostr(DID.Num));
2330 // ConstPool - Constants with optional names assigned to them.
2332 : ConstPool OptAssign TYPE TypesV {
2333 // Eagerly resolve types. This is not an optimization, this is a
2334 // requirement that is due to the fact that we could have this:
2336 // %list = type { %list * }
2337 // %list = type { %list * } ; repeated type decl
2339 // If types are not resolved eagerly, then the two types will not be
2340 // determined to be the same type!
2342 const Type* Ty = $4.T->get();
2343 ResolveTypeTo($2, Ty);
2345 if (!setTypeName(Ty, $2) && !$2) {
2346 // If this is a named type that is not a redefinition, add it to the slot
2348 CurModule.Types.push_back(Ty);
2352 | ConstPool FunctionProto { // Function prototypes can be in const pool
2354 | ConstPool MODULE ASM_TOK AsmBlock { // Asm blocks can be in the const pool
2356 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
2358 error("Global value initializer is not a constant");
2359 CurGV = ParseGlobalVariable($2, $3, $4, $5.C->getType(), $5.C);
2360 } GlobalVarAttributes {
2363 | ConstPool OptAssign EXTERNAL GlobalType Types {
2364 const Type *Ty = $5.T->get();
2365 CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, Ty, 0);
2367 } GlobalVarAttributes {
2370 | ConstPool OptAssign DLLIMPORT GlobalType Types {
2371 const Type *Ty = $5.T->get();
2372 CurGV = ParseGlobalVariable($2, GlobalValue::DLLImportLinkage, $4, Ty, 0);
2374 } GlobalVarAttributes {
2377 | ConstPool OptAssign EXTERN_WEAK GlobalType Types {
2378 const Type *Ty = $5.T->get();
2380 ParseGlobalVariable($2, GlobalValue::ExternalWeakLinkage, $4, Ty, 0);
2382 } GlobalVarAttributes {
2385 | ConstPool TARGET TargetDefinition {
2387 | ConstPool DEPLIBS '=' LibrariesDefinition {
2389 | /* empty: end of list */ {
2395 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2396 char *EndStr = UnEscapeLexed($1, true);
2397 std::string NewAsm($1, EndStr);
2400 if (AsmSoFar.empty())
2401 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
2403 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
2408 : BIG { $$ = Module::BigEndian; }
2409 | LITTLE { $$ = Module::LittleEndian; }
2413 : ENDIAN '=' BigOrLittle {
2414 CurModule.setEndianness($3);
2416 | POINTERSIZE '=' EUINT64VAL {
2418 CurModule.setPointerSize(Module::Pointer32);
2420 CurModule.setPointerSize(Module::Pointer64);
2422 error("Invalid pointer size: '" + utostr($3) + "'");
2424 | TRIPLE '=' STRINGCONSTANT {
2425 CurModule.CurrentModule->setTargetTriple($3);
2428 | DATALAYOUT '=' STRINGCONSTANT {
2429 CurModule.CurrentModule->setDataLayout($3);
2439 : LibList ',' STRINGCONSTANT {
2440 CurModule.CurrentModule->addLibrary($3);
2444 CurModule.CurrentModule->addLibrary($1);
2447 | /* empty: end of list */ { }
2450 //===----------------------------------------------------------------------===//
2451 // Rules to match Function Headers
2452 //===----------------------------------------------------------------------===//
2455 : VAR_ID | STRINGCONSTANT
2460 | /*empty*/ { $$ = 0; }
2465 if ($1.T->get() == Type::VoidTy)
2466 error("void typed arguments are invalid");
2467 $$ = new std::pair<PATypeInfo, char*>($1, $2);
2472 : ArgListH ',' ArgVal {
2478 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2485 : ArgListH { $$ = $1; }
2486 | ArgListH ',' DOTDOTDOT {
2489 VoidTI.T = new PATypeHolder(Type::VoidTy);
2490 VoidTI.S = Signless;
2491 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2494 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2496 VoidTI.T = new PATypeHolder(Type::VoidTy);
2497 VoidTI.S = Signless;
2498 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2500 | /* empty */ { $$ = 0; }
2504 : OptCallingConv TypesV Name '(' ArgList ')' OptSection OptAlign {
2506 std::string FunctionName($3);
2507 free($3); // Free strdup'd memory!
2509 const Type* RetTy = $2.T->get();
2511 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
2512 error("LLVM functions cannot return aggregate types");
2514 std::vector<const Type*> ParamTypeList;
2516 // In LLVM 2.0 the signatures of three varargs intrinsics changed to take
2517 // i8*. We check here for those names and override the parameter list
2518 // types to ensure the prototype is correct.
2519 if (FunctionName == "llvm.va_start" || FunctionName == "llvm.va_end") {
2520 ParamTypeList.push_back(PointerType::get(Type::Int8Ty));
2521 } else if (FunctionName == "llvm.va_copy") {
2522 ParamTypeList.push_back(PointerType::get(Type::Int8Ty));
2523 ParamTypeList.push_back(PointerType::get(Type::Int8Ty));
2524 } else if ($5) { // If there are arguments...
2525 for (std::vector<std::pair<PATypeInfo,char*> >::iterator
2526 I = $5->begin(), E = $5->end(); I != E; ++I) {
2527 const Type *Ty = I->first.T->get();
2528 ParamTypeList.push_back(Ty);
2533 ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2534 if (isVarArg) ParamTypeList.pop_back();
2536 const FunctionType *FT = FunctionType::get(RetTy, ParamTypeList, isVarArg);
2537 const PointerType *PFT = PointerType::get(FT);
2541 if (!FunctionName.empty()) {
2542 ID = ValID::create((char*)FunctionName.c_str());
2544 ID = ValID::create((int)CurModule.Values[PFT].size());
2548 // See if this function was forward referenced. If so, recycle the object.
2549 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2550 // Move the function to the end of the list, from whereever it was
2551 // previously inserted.
2552 Fn = cast<Function>(FWRef);
2553 CurModule.CurrentModule->getFunctionList().remove(Fn);
2554 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2555 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2556 (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
2557 // If this is the case, either we need to be a forward decl, or it needs
2559 if (!CurFun.isDeclare && !Fn->isExternal())
2560 error("Redefinition of function '" + FunctionName + "'");
2562 // Make sure to strip off any argument names so we can't get conflicts.
2563 if (Fn->isExternal())
2564 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2567 } else { // Not already defined?
2568 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
2569 CurModule.CurrentModule);
2571 InsertValue(Fn, CurModule.Values);
2574 CurFun.FunctionStart(Fn);
2576 if (CurFun.isDeclare) {
2577 // If we have declaration, always overwrite linkage. This will allow us
2578 // to correctly handle cases, when pointer to function is passed as
2579 // argument to another function.
2580 Fn->setLinkage(CurFun.Linkage);
2582 Fn->setCallingConv($1);
2583 Fn->setAlignment($8);
2589 // Add all of the arguments we parsed to the function...
2590 if ($5) { // Is null if empty...
2591 if (isVarArg) { // Nuke the last entry
2592 assert($5->back().first.T->get() == Type::VoidTy &&
2593 $5->back().second == 0 && "Not a varargs marker");
2594 delete $5->back().first.T;
2595 $5->pop_back(); // Delete the last entry
2597 Function::arg_iterator ArgIt = Fn->arg_begin();
2598 for (std::vector<std::pair<PATypeInfo,char*> >::iterator
2599 I = $5->begin(), E = $5->end(); I != E; ++I, ++ArgIt) {
2600 delete I->first.T; // Delete the typeholder...
2601 setValueName(ArgIt, I->second); // Insert arg into symtab...
2604 delete $5; // We're now done with the argument list
2610 : BEGINTOK | '{' // Allow BEGIN or '{' to start a function
2614 : OptLinkage FunctionHeaderH BEGIN {
2615 $$ = CurFun.CurrentFunction;
2617 // Make sure that we keep track of the linkage type even if there was a
2618 // previous "declare".
2624 : ENDTOK | '}' // Allow end of '}' to end a function
2628 : BasicBlockList END {
2634 | DLLIMPORT { CurFun.Linkage = GlobalValue::DLLImportLinkage; }
2635 | EXTERN_WEAK { CurFun.Linkage = GlobalValue::ExternalWeakLinkage; }
2639 : DECLARE { CurFun.isDeclare = true; } FnDeclareLinkage FunctionHeaderH {
2640 $$ = CurFun.CurrentFunction;
2641 CurFun.FunctionDone();
2646 //===----------------------------------------------------------------------===//
2647 // Rules to match Basic Blocks
2648 //===----------------------------------------------------------------------===//
2651 : /* empty */ { $$ = false; }
2652 | SIDEEFFECT { $$ = true; }
2656 // A reference to a direct constant
2657 : ESINT64VAL { $$ = ValID::create($1); }
2658 | EUINT64VAL { $$ = ValID::create($1); }
2659 | FPVAL { $$ = ValID::create($1); }
2660 | TRUETOK { $$ = ValID::create(ConstantInt::get(Type::Int1Ty, true)); }
2661 | FALSETOK { $$ = ValID::create(ConstantInt::get(Type::Int1Ty, false)); }
2662 | NULL_TOK { $$ = ValID::createNull(); }
2663 | UNDEF { $$ = ValID::createUndef(); }
2664 | ZEROINITIALIZER { $$ = ValID::createZeroInit(); }
2665 | '<' ConstVector '>' { // Nonempty unsized packed vector
2666 const Type *ETy = (*$2)[0].C->getType();
2667 int NumElements = $2->size();
2668 PackedType* pt = PackedType::get(ETy, NumElements);
2669 PATypeHolder* PTy = new PATypeHolder(
2670 HandleUpRefs(PackedType::get(ETy, NumElements)));
2672 // Verify all elements are correct type!
2673 std::vector<Constant*> Elems;
2674 for (unsigned i = 0; i < $2->size(); i++) {
2675 Constant *C = (*$2)[i].C;
2676 const Type *CTy = C->getType();
2678 error("Element #" + utostr(i) + " is not of type '" +
2679 ETy->getDescription() +"' as required!\nIt is of type '" +
2680 CTy->getDescription() + "'");
2683 $$ = ValID::create(ConstantPacked::get(pt, Elems));
2684 delete PTy; delete $2;
2687 $$ = ValID::create($1.C);
2689 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2690 char *End = UnEscapeLexed($3, true);
2691 std::string AsmStr = std::string($3, End);
2692 End = UnEscapeLexed($5, true);
2693 std::string Constraints = std::string($5, End);
2694 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2700 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2704 : INTVAL { $$ = ValID::create($1); }
2705 | Name { $$ = ValID::create($1); }
2708 // ValueRef - A reference to a definition... either constant or symbolic
2710 : SymbolicValueRef | ConstValueRef
2714 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2715 // type immediately preceeds the value reference, and allows complex constant
2716 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2719 const Type *Ty = $1.T->get();
2721 $$.V = getVal(Ty, $2);
2727 : BasicBlockList BasicBlock {
2730 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2735 // Basic blocks are terminated by branching instructions:
2736 // br, br/cc, switch, ret
2739 : InstructionList OptAssign BBTerminatorInst {
2740 setValueName($3, $2);
2742 $1->getInstList().push_back($3);
2749 : InstructionList Inst {
2751 $1->getInstList().push_back($2.I);
2755 $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
2756 // Make sure to move the basic block to the correct location in the
2757 // function, instead of leaving it inserted wherever it was first
2759 Function::BasicBlockListType &BBL =
2760 CurFun.CurrentFunction->getBasicBlockList();
2761 BBL.splice(BBL.end(), BBL, $$);
2764 $$ = CurBB = getBBVal(ValID::create($1), true);
2765 // Make sure to move the basic block to the correct location in the
2766 // function, instead of leaving it inserted wherever it was first
2768 Function::BasicBlockListType &BBL =
2769 CurFun.CurrentFunction->getBasicBlockList();
2770 BBL.splice(BBL.end(), BBL, $$);
2774 Unwind : UNWIND | EXCEPT;
2777 : RET ResolvedVal { // Return with a result...
2778 $$ = new ReturnInst($2.V);
2780 | RET VOID { // Return with no result...
2781 $$ = new ReturnInst();
2783 | BR LABEL ValueRef { // Unconditional Branch...
2784 BasicBlock* tmpBB = getBBVal($3);
2785 $$ = new BranchInst(tmpBB);
2786 } // Conditional Branch...
2787 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2788 BasicBlock* tmpBBA = getBBVal($6);
2789 BasicBlock* tmpBBB = getBBVal($9);
2790 Value* tmpVal = getVal(Type::Int1Ty, $3);
2791 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2793 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2794 Value* tmpVal = getVal($2.T, $3);
2795 BasicBlock* tmpBB = getBBVal($6);
2796 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2798 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2800 for (; I != E; ++I) {
2801 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2802 S->addCase(CI, I->second);
2804 error("Switch case is constant, but not a simple integer");
2808 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2809 Value* tmpVal = getVal($2.T, $3);
2810 BasicBlock* tmpBB = getBBVal($6);
2811 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2814 | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
2815 TO LABEL ValueRef Unwind LABEL ValueRef {
2816 const PointerType *PFTy;
2817 const FunctionType *Ty;
2819 if (!(PFTy = dyn_cast<PointerType>($3.T->get())) ||
2820 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2821 // Pull out the types of all of the arguments...
2822 std::vector<const Type*> ParamTypes;
2824 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
2826 ParamTypes.push_back((*I).V->getType());
2828 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2829 if (isVarArg) ParamTypes.pop_back();
2830 Ty = FunctionType::get($3.T->get(), ParamTypes, isVarArg);
2831 PFTy = PointerType::get(Ty);
2833 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2834 BasicBlock *Normal = getBBVal($10);
2835 BasicBlock *Except = getBBVal($13);
2837 // Create the call node...
2838 if (!$6) { // Has no arguments?
2839 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
2840 } else { // Has arguments?
2841 // Loop through FunctionType's arguments and ensure they are specified
2844 FunctionType::param_iterator I = Ty->param_begin();
2845 FunctionType::param_iterator E = Ty->param_end();
2846 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
2848 std::vector<Value*> Args;
2849 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2850 if ((*ArgI).V->getType() != *I)
2851 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
2852 (*I)->getDescription() + "'");
2853 Args.push_back((*ArgI).V);
2856 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2857 error("Invalid number of parameters detected");
2859 $$ = new InvokeInst(V, Normal, Except, Args);
2861 cast<InvokeInst>($$)->setCallingConv($2);
2866 $$ = new UnwindInst();
2869 $$ = new UnreachableInst();
2874 : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2876 Constant *V = cast<Constant>(getExistingValue($2.T, $3));
2879 error("May only switch on a constant pool value");
2881 BasicBlock* tmpBB = getBBVal($6);
2882 $$->push_back(std::make_pair(V, tmpBB));
2884 | IntType ConstValueRef ',' LABEL ValueRef {
2885 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2886 Constant *V = cast<Constant>(getExistingValue($1.T, $2));
2889 error("May only switch on a constant pool value");
2891 BasicBlock* tmpBB = getBBVal($5);
2892 $$->push_back(std::make_pair(V, tmpBB));
2897 : OptAssign InstVal {
2900 if (BitCastInst *BCI = dyn_cast<BitCastInst>($2.I))
2901 if (BCI->getSrcTy() == BCI->getDestTy() &&
2902 BCI->getOperand(0)->getName() == $1)
2903 // This is a useless bit cast causing a name redefinition. It is
2904 // a bit cast from a type to the same type of an operand with the
2905 // same name as the name we would give this instruction. Since this
2906 // instruction results in no code generation, it is safe to omit
2907 // the instruction. This situation can occur because of collapsed
2908 // type planes. For example:
2909 // %X = add int %Y, %Z
2910 // %X = cast int %Y to uint
2911 // After upgrade, this looks like:
2912 // %X = add i32 %Y, %Z
2913 // %X = bitcast i32 to i32
2914 // The bitcast is clearly useless so we omit it.
2920 setValueName($2.I, $1);
2926 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2927 $$.P = new std::list<std::pair<Value*, BasicBlock*> >();
2929 Value* tmpVal = getVal($1.T->get(), $3);
2930 BasicBlock* tmpBB = getBBVal($5);
2931 $$.P->push_back(std::make_pair(tmpVal, tmpBB));
2934 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2936 Value* tmpVal = getVal($1.P->front().first->getType(), $4);
2937 BasicBlock* tmpBB = getBBVal($6);
2938 $1.P->push_back(std::make_pair(tmpVal, tmpBB));
2942 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
2943 $$ = new std::vector<ValueInfo>();
2946 | ValueRefList ',' ResolvedVal {
2951 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
2954 | /*empty*/ { $$ = 0; }
2967 : ArithmeticOps Types ValueRef ',' ValueRef {
2968 const Type* Ty = $2.T->get();
2969 if (!Ty->isInteger() && !Ty->isFloatingPoint() && !isa<PackedType>(Ty))
2970 error("Arithmetic operator requires integer, FP, or packed operands");
2971 if (isa<PackedType>(Ty) &&
2972 ($1 == URemOp || $1 == SRemOp || $1 == FRemOp || $1 == RemOp))
2973 error("Remainder not supported on packed types");
2974 // Upgrade the opcode from obsolete versions before we do anything with it.
2975 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
2976 Value* val1 = getVal(Ty, $3);
2977 Value* val2 = getVal(Ty, $5);
2978 $$.I = BinaryOperator::create(Opcode, val1, val2);
2980 error("binary operator returned null");
2984 | LogicalOps Types ValueRef ',' ValueRef {
2985 const Type *Ty = $2.T->get();
2986 if (!Ty->isInteger()) {
2987 if (!isa<PackedType>(Ty) ||
2988 !cast<PackedType>(Ty)->getElementType()->isInteger())
2989 error("Logical operator requires integral operands");
2991 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
2992 Value* tmpVal1 = getVal(Ty, $3);
2993 Value* tmpVal2 = getVal(Ty, $5);
2994 $$.I = BinaryOperator::create(Opcode, tmpVal1, tmpVal2);
2996 error("binary operator returned null");
3000 | SetCondOps Types ValueRef ',' ValueRef {
3001 const Type* Ty = $2.T->get();
3002 if(isa<PackedType>(Ty))
3003 error("PackedTypes currently not supported in setcc instructions");
3004 unsigned short pred;
3005 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $2.S);
3006 Value* tmpVal1 = getVal(Ty, $3);
3007 Value* tmpVal2 = getVal(Ty, $5);
3008 $$.I = CmpInst::create(Opcode, pred, tmpVal1, tmpVal2);
3010 error("binary operator returned null");
3014 | ICMP IPredicates Types ValueRef ',' ValueRef {
3015 const Type *Ty = $3.T->get();
3016 if (isa<PackedType>(Ty))
3017 error("PackedTypes currently not supported in icmp instructions");
3018 else if (!Ty->isInteger() && !isa<PointerType>(Ty))
3019 error("icmp requires integer or pointer typed operands");
3020 Value* tmpVal1 = getVal(Ty, $4);
3021 Value* tmpVal2 = getVal(Ty, $6);
3022 $$.I = new ICmpInst($2, tmpVal1, tmpVal2);
3026 | FCMP FPredicates Types ValueRef ',' ValueRef {
3027 const Type *Ty = $3.T->get();
3028 if (isa<PackedType>(Ty))
3029 error("PackedTypes currently not supported in fcmp instructions");
3030 else if (!Ty->isFloatingPoint())
3031 error("fcmp instruction requires floating point operands");
3032 Value* tmpVal1 = getVal(Ty, $4);
3033 Value* tmpVal2 = getVal(Ty, $6);
3034 $$.I = new FCmpInst($2, tmpVal1, tmpVal2);
3039 warning("Use of obsolete 'not' instruction: Replacing with 'xor");
3040 const Type *Ty = $2.V->getType();
3041 Value *Ones = ConstantInt::getAllOnesValue(Ty);
3043 error("Expected integral type for not instruction");
3044 $$.I = BinaryOperator::create(Instruction::Xor, $2.V, Ones);
3046 error("Could not create a xor instruction");
3049 | ShiftOps ResolvedVal ',' ResolvedVal {
3050 if (!$4.V->getType()->isInteger() ||
3051 cast<IntegerType>($4.V->getType())->getBitWidth() != 8)
3052 error("Shift amount must be int8");
3053 if (!$2.V->getType()->isInteger())
3054 error("Shift constant expression requires integer operand");
3055 $$.I = new ShiftInst(getOtherOp($1, $2.S), $2.V, $4.V);
3058 | CastOps ResolvedVal TO Types {
3059 const Type *DstTy = $4.T->get();
3060 if (!DstTy->isFirstClassType())
3061 error("cast instruction to a non-primitive type: '" +
3062 DstTy->getDescription() + "'");
3063 $$.I = cast<Instruction>(getCast($1, $2.V, $2.S, DstTy, $4.S, true));
3067 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3068 if (!$2.V->getType()->isInteger() ||
3069 cast<IntegerType>($2.V->getType())->getBitWidth() != 1)
3070 error("select condition must be bool");
3071 if ($4.V->getType() != $6.V->getType())
3072 error("select value types should match");
3073 $$.I = new SelectInst($2.V, $4.V, $6.V);
3076 | VAARG ResolvedVal ',' Types {
3077 const Type *Ty = $4.T->get();
3079 $$.I = new VAArgInst($2.V, Ty);
3083 | VAARG_old ResolvedVal ',' Types {
3084 const Type* ArgTy = $2.V->getType();
3085 const Type* DstTy = $4.T->get();
3086 ObsoleteVarArgs = true;
3087 Function* NF = cast<Function>(CurModule.CurrentModule->
3088 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3091 //foo = alloca 1 of t
3095 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
3096 CurBB->getInstList().push_back(foo);
3097 CallInst* bar = new CallInst(NF, $2.V);
3098 CurBB->getInstList().push_back(bar);
3099 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3100 $$.I = new VAArgInst(foo, DstTy);
3104 | VANEXT_old ResolvedVal ',' Types {
3105 const Type* ArgTy = $2.V->getType();
3106 const Type* DstTy = $4.T->get();
3107 ObsoleteVarArgs = true;
3108 Function* NF = cast<Function>(CurModule.CurrentModule->
3109 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3111 //b = vanext a, t ->
3112 //foo = alloca 1 of t
3115 //tmp = vaarg foo, t
3117 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
3118 CurBB->getInstList().push_back(foo);
3119 CallInst* bar = new CallInst(NF, $2.V);
3120 CurBB->getInstList().push_back(bar);
3121 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3122 Instruction* tmp = new VAArgInst(foo, DstTy);
3123 CurBB->getInstList().push_back(tmp);
3124 $$.I = new LoadInst(foo);
3128 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
3129 if (!ExtractElementInst::isValidOperands($2.V, $4.V))
3130 error("Invalid extractelement operands");
3131 $$.I = new ExtractElementInst($2.V, $4.V);
3134 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3135 if (!InsertElementInst::isValidOperands($2.V, $4.V, $6.V))
3136 error("Invalid insertelement operands");
3137 $$.I = new InsertElementInst($2.V, $4.V, $6.V);
3140 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3141 if (!ShuffleVectorInst::isValidOperands($2.V, $4.V, $6.V))
3142 error("Invalid shufflevector operands");
3143 $$.I = new ShuffleVectorInst($2.V, $4.V, $6.V);
3147 const Type *Ty = $2.P->front().first->getType();
3148 if (!Ty->isFirstClassType())
3149 error("PHI node operands must be of first class type");
3150 PHINode *PHI = new PHINode(Ty);
3151 PHI->reserveOperandSpace($2.P->size());
3152 while ($2.P->begin() != $2.P->end()) {
3153 if ($2.P->front().first->getType() != Ty)
3154 error("All elements of a PHI node must be of the same type");
3155 PHI->addIncoming($2.P->front().first, $2.P->front().second);
3160 delete $2.P; // Free the list...
3162 | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')' {
3164 // Handle the short call syntax
3165 const PointerType *PFTy;
3166 const FunctionType *FTy;
3167 if (!(PFTy = dyn_cast<PointerType>($3.T->get())) ||
3168 !(FTy = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3169 // Pull out the types of all of the arguments...
3170 std::vector<const Type*> ParamTypes;
3172 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
3174 ParamTypes.push_back((*I).V->getType());
3177 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
3178 if (isVarArg) ParamTypes.pop_back();
3180 const Type *RetTy = $3.T->get();
3181 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
3182 error("Functions cannot return aggregate types");
3184 FTy = FunctionType::get(RetTy, ParamTypes, isVarArg);
3185 PFTy = PointerType::get(FTy);
3188 // First upgrade any intrinsic calls.
3189 std::vector<Value*> Args;
3191 for (unsigned i = 0, e = $6->size(); i < e; ++i)
3192 Args.push_back((*$6)[i].V);
3193 Instruction *Inst = upgradeIntrinsicCall(FTy, $4, Args);
3195 // If we got an upgraded intrinsic
3200 // Get the function we're calling
3201 Value *V = getVal(PFTy, $4);
3203 // Check the argument values match
3204 if (!$6) { // Has no arguments?
3205 // Make sure no arguments is a good thing!
3206 if (FTy->getNumParams() != 0)
3207 error("No arguments passed to a function that expects arguments");
3208 } else { // Has arguments?
3209 // Loop through FunctionType's arguments and ensure they are specified
3212 FunctionType::param_iterator I = FTy->param_begin();
3213 FunctionType::param_iterator E = FTy->param_end();
3214 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
3216 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
3217 if ((*ArgI).V->getType() != *I)
3218 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
3219 (*I)->getDescription() + "'");
3221 if (I != E || (ArgI != ArgE && !FTy->isVarArg()))
3222 error("Invalid number of parameters detected");
3225 // Create the call instruction
3226 CallInst *CI = new CallInst(V, Args);
3227 CI->setTailCall($1);
3228 CI->setCallingConv($2);
3241 // IndexList - List of indices for GEP based instructions...
3243 : ',' ValueRefList { $$ = $2; }
3244 | /* empty */ { $$ = new std::vector<ValueInfo>(); }
3248 : VOLATILE { $$ = true; }
3249 | /* empty */ { $$ = false; }
3253 : MALLOC Types OptCAlign {
3254 const Type *Ty = $2.T->get();
3256 $$.I = new MallocInst(Ty, 0, $3);
3259 | MALLOC Types ',' UINT ValueRef OptCAlign {
3260 const Type *Ty = $2.T->get();
3262 $$.I = new MallocInst(Ty, getVal($4.T, $5), $6);
3265 | ALLOCA Types OptCAlign {
3266 const Type *Ty = $2.T->get();
3268 $$.I = new AllocaInst(Ty, 0, $3);
3271 | ALLOCA Types ',' UINT ValueRef OptCAlign {
3272 const Type *Ty = $2.T->get();
3274 $$.I = new AllocaInst(Ty, getVal($4.T, $5), $6);
3277 | FREE ResolvedVal {
3278 const Type *PTy = $2.V->getType();
3279 if (!isa<PointerType>(PTy))
3280 error("Trying to free nonpointer type '" + PTy->getDescription() + "'");
3281 $$.I = new FreeInst($2.V);
3284 | OptVolatile LOAD Types ValueRef {
3285 const Type* Ty = $3.T->get();
3287 if (!isa<PointerType>(Ty))
3288 error("Can't load from nonpointer type: " + Ty->getDescription());
3289 if (!cast<PointerType>(Ty)->getElementType()->isFirstClassType())
3290 error("Can't load from pointer of non-first-class type: " +
3291 Ty->getDescription());
3292 Value* tmpVal = getVal(Ty, $4);
3293 $$.I = new LoadInst(tmpVal, "", $1);
3296 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
3297 const PointerType *PTy = dyn_cast<PointerType>($5.T->get());
3299 error("Can't store to a nonpointer type: " +
3300 $5.T->get()->getDescription());
3301 const Type *ElTy = PTy->getElementType();
3302 if (ElTy != $3.V->getType())
3303 error("Can't store '" + $3.V->getType()->getDescription() +
3304 "' into space of type '" + ElTy->getDescription() + "'");
3305 Value* tmpVal = getVal(PTy, $6);
3306 $$.I = new StoreInst($3.V, tmpVal, $1);
3310 | GETELEMENTPTR Types ValueRef IndexList {
3311 const Type* Ty = $2.T->get();
3312 if (!isa<PointerType>(Ty))
3313 error("getelementptr insn requires pointer operand");
3315 std::vector<Value*> VIndices;
3316 upgradeGEPIndices(Ty, $4, VIndices);
3318 Value* tmpVal = getVal(Ty, $3);
3319 $$.I = new GetElementPtrInst(tmpVal, VIndices);
3328 int yyerror(const char *ErrorMsg) {
3330 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3331 + ":" + llvm::utostr((unsigned) Upgradelineno-1) + ": ";
3332 std::string errMsg = where + "error: " + std::string(ErrorMsg);
3333 if (yychar != YYEMPTY && yychar != 0)
3334 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3336 std::cerr << "llvm-upgrade: " << errMsg << '\n';
3337 std::cout << "llvm-upgrade: parse failed.\n";
3341 void warning(const std::string& ErrorMsg) {
3343 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3344 + ":" + llvm::utostr((unsigned) Upgradelineno-1) + ": ";
3345 std::string errMsg = where + "warning: " + std::string(ErrorMsg);
3346 if (yychar != YYEMPTY && yychar != 0)
3347 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3349 std::cerr << "llvm-upgrade: " << errMsg << '\n';
3352 void error(const std::string& ErrorMsg, int LineNo) {
3353 if (LineNo == -1) LineNo = Upgradelineno;
3354 Upgradelineno = LineNo;
3355 yyerror(ErrorMsg.c_str());