1 //===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/ValueSymbolTable.h"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/Support/MathExtras.h"
30 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
31 // relating to upreferences in the input stream.
33 //#define DEBUG_UPREFS 1
35 #define UR_OUT(X) std::cerr << X
40 #define YYERROR_VERBOSE 1
41 #define YYINCLUDED_STDLIB_H
47 int yyerror(const char*);
48 static void warning(const std::string& WarningMsg);
52 std::istream* LexInput;
53 static std::string CurFilename;
55 // This bool controls whether attributes are ever added to function declarations
56 // definitions and calls.
57 static bool AddAttributes = false;
59 static Module *ParserResult;
60 static bool ObsoleteVarArgs;
61 static bool NewVarArgs;
62 static BasicBlock *CurBB;
63 static GlobalVariable *CurGV;
64 static unsigned lastCallingConv;
66 // This contains info used when building the body of a function. It is
67 // destroyed when the function is completed.
69 typedef std::vector<Value *> ValueList; // Numbered defs
71 typedef std::pair<std::string,TypeInfo> RenameMapKey;
72 typedef std::map<RenameMapKey,std::string> RenameMapType;
75 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
76 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
78 static struct PerModuleInfo {
79 Module *CurrentModule;
80 std::map<const Type *, ValueList> Values; // Module level numbered definitions
81 std::map<const Type *,ValueList> LateResolveValues;
82 std::vector<PATypeHolder> Types;
83 std::vector<Signedness> TypeSigns;
84 std::map<std::string,Signedness> NamedTypeSigns;
85 std::map<std::string,Signedness> NamedValueSigns;
86 std::map<ValID, PATypeHolder> LateResolveTypes;
87 static Module::Endianness Endian;
88 static Module::PointerSize PointerSize;
89 RenameMapType RenameMap;
91 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
92 /// how they were referenced and on which line of the input they came from so
93 /// that we can resolve them later and print error messages as appropriate.
94 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
96 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
97 // references to global values. Global values may be referenced before they
98 // are defined, and if so, the temporary object that they represent is held
99 // here. This is used for forward references of GlobalValues.
101 typedef std::map<std::pair<const PointerType *, ValID>, GlobalValue*>
103 GlobalRefsType GlobalRefs;
106 // If we could not resolve some functions at function compilation time
107 // (calls to functions before they are defined), resolve them now... Types
108 // are resolved when the constant pool has been completely parsed.
110 ResolveDefinitions(LateResolveValues);
112 // Check to make sure that all global value forward references have been
115 if (!GlobalRefs.empty()) {
116 std::string UndefinedReferences = "Unresolved global references exist:\n";
118 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
120 UndefinedReferences += " " + I->first.first->getDescription() + " " +
121 I->first.second.getName() + "\n";
123 error(UndefinedReferences);
127 if (CurrentModule->getDataLayout().empty()) {
128 std::string dataLayout;
129 if (Endian != Module::AnyEndianness)
130 dataLayout.append(Endian == Module::BigEndian ? "E" : "e");
131 if (PointerSize != Module::AnyPointerSize) {
132 if (!dataLayout.empty())
134 dataLayout.append(PointerSize == Module::Pointer64 ?
135 "p:64:64" : "p:32:32");
137 CurrentModule->setDataLayout(dataLayout);
140 Values.clear(); // Clear out function local definitions
143 NamedTypeSigns.clear();
144 NamedValueSigns.clear();
148 // GetForwardRefForGlobal - Check to see if there is a forward reference
149 // for this global. If so, remove it from the GlobalRefs map and return it.
150 // If not, just return null.
151 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
152 // Check to see if there is a forward reference to this global variable...
153 // if there is, eliminate it and patch the reference to use the new def'n.
154 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
155 GlobalValue *Ret = 0;
156 if (I != GlobalRefs.end()) {
162 void setEndianness(Module::Endianness E) { Endian = E; }
163 void setPointerSize(Module::PointerSize sz) { PointerSize = sz; }
166 Module::Endianness PerModuleInfo::Endian = Module::AnyEndianness;
167 Module::PointerSize PerModuleInfo::PointerSize = Module::AnyPointerSize;
169 static struct PerFunctionInfo {
170 Function *CurrentFunction; // Pointer to current function being created
172 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
173 std::map<const Type*, ValueList> LateResolveValues;
174 bool isDeclare; // Is this function a forward declararation?
175 GlobalValue::LinkageTypes Linkage;// Linkage for forward declaration.
177 /// BBForwardRefs - When we see forward references to basic blocks, keep
178 /// track of them here.
179 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
180 std::vector<BasicBlock*> NumberedBlocks;
181 RenameMapType RenameMap;
184 inline PerFunctionInfo() {
187 Linkage = GlobalValue::ExternalLinkage;
190 inline void FunctionStart(Function *M) {
195 void FunctionDone() {
196 NumberedBlocks.clear();
198 // Any forward referenced blocks left?
199 if (!BBForwardRefs.empty()) {
200 error("Undefined reference to label " +
201 BBForwardRefs.begin()->first->getName());
205 // Resolve all forward references now.
206 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
208 Values.clear(); // Clear out function local definitions
212 Linkage = GlobalValue::ExternalLinkage;
214 } CurFun; // Info for the current function...
216 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
218 /// This function is just a utility to make a Key value for the rename map.
219 /// The Key is a combination of the name, type, Signedness of the original
220 /// value (global/function). This just constructs the key and ensures that
221 /// named Signedness values are resolved to the actual Signedness.
222 /// @brief Make a key for the RenameMaps
223 static RenameMapKey makeRenameMapKey(const std::string &Name, const Type* Ty,
224 const Signedness &Sign) {
228 // Don't allow Named Signedness nodes because they won't match. The actual
229 // Signedness must be looked up in the NamedTypeSigns map.
230 TI.S.copy(CurModule.NamedTypeSigns[Sign.getName()]);
233 return std::make_pair(Name, TI);
237 //===----------------------------------------------------------------------===//
238 // Code to handle definitions of all the types
239 //===----------------------------------------------------------------------===//
241 static int InsertValue(Value *V,
242 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
243 if (V->hasName()) return -1; // Is this a numbered definition?
245 // Yes, insert the value into the value table...
246 ValueList &List = ValueTab[V->getType()];
248 return List.size()-1;
251 static const Type *getType(const ValID &D, bool DoNotImprovise = false) {
253 case ValID::NumberVal: // Is it a numbered definition?
254 // Module constants occupy the lowest numbered slots...
255 if ((unsigned)D.Num < CurModule.Types.size()) {
256 return CurModule.Types[(unsigned)D.Num];
259 case ValID::NameVal: // Is it a named definition?
260 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
265 error("Internal parser error: Invalid symbol type reference");
269 // If we reached here, we referenced either a symbol that we don't know about
270 // or an id number that hasn't been read yet. We may be referencing something
271 // forward, so just create an entry to be resolved later and get to it...
273 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
275 if (inFunctionScope()) {
276 if (D.Type == ValID::NameVal) {
277 error("Reference to an undefined type: '" + D.getName() + "'");
280 error("Reference to an undefined type: #" + itostr(D.Num));
285 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
286 if (I != CurModule.LateResolveTypes.end())
289 Type *Typ = OpaqueType::get();
290 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
294 /// This is like the getType method except that instead of looking up the type
295 /// for a given ID, it looks up that type's sign.
296 /// @brief Get the signedness of a referenced type
297 static Signedness getTypeSign(const ValID &D) {
299 case ValID::NumberVal: // Is it a numbered definition?
300 // Module constants occupy the lowest numbered slots...
301 if ((unsigned)D.Num < CurModule.TypeSigns.size()) {
302 return CurModule.TypeSigns[(unsigned)D.Num];
305 case ValID::NameVal: { // Is it a named definition?
306 std::map<std::string,Signedness>::const_iterator I =
307 CurModule.NamedTypeSigns.find(D.Name);
308 if (I != CurModule.NamedTypeSigns.end())
310 // Perhaps its a named forward .. just cache the name
318 // If we don't find it, its signless
324 /// This function is analagous to getElementType in LLVM. It provides the same
325 /// function except that it looks up the Signedness instead of the type. This is
326 /// used when processing GEP instructions that need to extract the type of an
327 /// indexed struct/array/ptr member.
328 /// @brief Look up an element's sign.
329 static Signedness getElementSign(const ValueInfo& VI,
330 const std::vector<Value*> &Indices) {
331 const Type *Ptr = VI.V->getType();
332 assert(isa<PointerType>(Ptr) && "Need pointer type");
336 while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
337 if (CurIdx == Indices.size())
340 Value *Index = Indices[CurIdx++];
341 assert(!isa<PointerType>(CT) || CurIdx == 1 && "Invalid type");
342 Ptr = CT->getTypeAtIndex(Index);
343 if (const Type* Ty = Ptr->getForwardedType())
345 assert(S.isComposite() && "Bad Signedness type");
346 if (isa<StructType>(CT)) {
347 S = S.get(cast<ConstantInt>(Index)->getZExtValue());
352 S = CurModule.NamedTypeSigns[S.getName()];
355 Result.makeComposite(S);
359 /// This function just translates a ConstantInfo into a ValueInfo and calls
360 /// getElementSign(ValueInfo,...). Its just a convenience.
361 /// @brief ConstantInfo version of getElementSign.
362 static Signedness getElementSign(const ConstInfo& CI,
363 const std::vector<Constant*> &Indices) {
367 std::vector<Value*> Idx;
368 for (unsigned i = 0; i < Indices.size(); ++i)
369 Idx.push_back(Indices[i]);
370 Signedness result = getElementSign(VI, Idx);
375 // getExistingValue - Look up the value specified by the provided type and
376 // the provided ValID. If the value exists and has already been defined, return
377 // it. Otherwise return null.
379 static Value *getExistingValue(const Type *Ty, const ValID &D) {
380 if (isa<FunctionType>(Ty)) {
381 error("Functions are not values and must be referenced as pointers");
385 case ValID::NumberVal: { // Is it a numbered definition?
386 unsigned Num = (unsigned)D.Num;
388 // Module constants occupy the lowest numbered slots...
389 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
390 if (VI != CurModule.Values.end()) {
391 if (Num < VI->second.size())
392 return VI->second[Num];
393 Num -= VI->second.size();
396 // Make sure that our type is within bounds
397 VI = CurFun.Values.find(Ty);
398 if (VI == CurFun.Values.end()) return 0;
400 // Check that the number is within bounds...
401 if (VI->second.size() <= Num) return 0;
403 return VI->second[Num];
406 case ValID::NameVal: { // Is it a named definition?
407 // Get the name out of the ID
408 RenameMapKey Key = makeRenameMapKey(D.Name, Ty, D.S);
410 if (inFunctionScope()) {
411 // See if the name was renamed
412 RenameMapType::const_iterator I = CurFun.RenameMap.find(Key);
413 std::string LookupName;
414 if (I != CurFun.RenameMap.end())
415 LookupName = I->second;
418 ValueSymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
419 V = SymTab.lookup(LookupName);
420 if (V && V->getType() != Ty)
424 RenameMapType::const_iterator I = CurModule.RenameMap.find(Key);
425 std::string LookupName;
426 if (I != CurModule.RenameMap.end())
427 LookupName = I->second;
430 V = CurModule.CurrentModule->getValueSymbolTable().lookup(LookupName);
431 if (V && V->getType() != Ty)
437 D.destroy(); // Free old strdup'd memory...
441 // Check to make sure that "Ty" is an integral type, and that our
442 // value will fit into the specified type...
443 case ValID::ConstSIntVal: // Is it a constant pool reference??
444 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
445 error("Signed integral constant '" + itostr(D.ConstPool64) +
446 "' is invalid for type '" + Ty->getDescription() + "'");
448 return ConstantInt::get(Ty, D.ConstPool64);
450 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
451 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
452 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64))
453 error("Integral constant '" + utostr(D.UConstPool64) +
454 "' is invalid or out of range");
455 else // This is really a signed reference. Transmogrify.
456 return ConstantInt::get(Ty, D.ConstPool64);
458 return ConstantInt::get(Ty, D.UConstPool64);
460 case ValID::ConstFPVal: // Is it a floating point const pool reference?
461 if (!ConstantFP::isValueValidForType(Ty, *D.ConstPoolFP))
462 error("FP constant invalid for type");
463 // Lexer has no type info, so builds all FP constants as double.
465 if (Ty==Type::FloatTy)
466 D.ConstPoolFP->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
467 return ConstantFP::get(Ty, *D.ConstPoolFP);
469 case ValID::ConstNullVal: // Is it a null value?
470 if (!isa<PointerType>(Ty))
471 error("Cannot create a a non pointer null");
472 return ConstantPointerNull::get(cast<PointerType>(Ty));
474 case ValID::ConstUndefVal: // Is it an undef value?
475 return UndefValue::get(Ty);
477 case ValID::ConstZeroVal: // Is it a zero value?
478 return Constant::getNullValue(Ty);
480 case ValID::ConstantVal: // Fully resolved constant?
481 if (D.ConstantValue->getType() != Ty)
482 error("Constant expression type different from required type");
483 return D.ConstantValue;
485 case ValID::InlineAsmVal: { // Inline asm expression
486 const PointerType *PTy = dyn_cast<PointerType>(Ty);
487 const FunctionType *FTy =
488 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
489 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints))
490 error("Invalid type for asm constraint string");
491 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
492 D.IAD->HasSideEffects);
493 D.destroy(); // Free InlineAsmDescriptor.
497 assert(0 && "Unhandled case");
501 assert(0 && "Unhandled case");
505 // getVal - This function is identical to getExistingValue, except that if a
506 // value is not already defined, it "improvises" by creating a placeholder var
507 // that looks and acts just like the requested variable. When the value is
508 // defined later, all uses of the placeholder variable are replaced with the
511 static Value *getVal(const Type *Ty, const ValID &ID) {
512 if (Ty == Type::LabelTy)
513 error("Cannot use a basic block here");
515 // See if the value has already been defined.
516 Value *V = getExistingValue(Ty, ID);
519 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty))
520 error("Invalid use of a composite type");
522 // If we reached here, we referenced either a symbol that we don't know about
523 // or an id number that hasn't been read yet. We may be referencing something
524 // forward, so just create an entry to be resolved later and get to it...
525 V = new Argument(Ty);
527 // Remember where this forward reference came from. FIXME, shouldn't we try
528 // to recycle these things??
529 CurModule.PlaceHolderInfo.insert(
530 std::make_pair(V, std::make_pair(ID, Upgradelineno)));
532 if (inFunctionScope())
533 InsertValue(V, CurFun.LateResolveValues);
535 InsertValue(V, CurModule.LateResolveValues);
539 /// @brief This just makes any name given to it unique, up to MAX_UINT times.
540 static std::string makeNameUnique(const std::string& Name) {
541 static unsigned UniqueNameCounter = 1;
542 std::string Result(Name);
543 Result += ".upgrd." + llvm::utostr(UniqueNameCounter++);
547 /// getBBVal - This is used for two purposes:
548 /// * If isDefinition is true, a new basic block with the specified ID is being
550 /// * If isDefinition is true, this is a reference to a basic block, which may
551 /// or may not be a forward reference.
553 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
554 assert(inFunctionScope() && "Can't get basic block at global scope");
560 error("Illegal label reference " + ID.getName());
562 case ValID::NumberVal: // Is it a numbered definition?
563 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
564 CurFun.NumberedBlocks.resize(ID.Num+1);
565 BB = CurFun.NumberedBlocks[ID.Num];
567 case ValID::NameVal: // Is it a named definition?
569 if (Value *N = CurFun.CurrentFunction->getValueSymbolTable().lookup(Name)) {
570 if (N->getType() != Type::LabelTy) {
571 // Register names didn't use to conflict with basic block names
572 // because of type planes. Now they all have to be unique. So, we just
573 // rename the register and treat this name as if no basic block
575 RenameMapKey Key = makeRenameMapKey(ID.Name, N->getType(), ID.S);
576 N->setName(makeNameUnique(N->getName()));
577 CurModule.RenameMap[Key] = N->getName();
580 BB = cast<BasicBlock>(N);
586 // See if the block has already been defined.
588 // If this is the definition of the block, make sure the existing value was
589 // just a forward reference. If it was a forward reference, there will be
590 // an entry for it in the PlaceHolderInfo map.
591 if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
592 // The existing value was a definition, not a forward reference.
593 error("Redefinition of label " + ID.getName());
595 ID.destroy(); // Free strdup'd memory.
599 // Otherwise this block has not been seen before.
600 BB = new BasicBlock("", CurFun.CurrentFunction);
601 if (ID.Type == ValID::NameVal) {
602 BB->setName(ID.Name);
604 CurFun.NumberedBlocks[ID.Num] = BB;
607 // If this is not a definition, keep track of it so we can use it as a forward
610 // Remember where this forward reference came from.
611 CurFun.BBForwardRefs[BB] = std::make_pair(ID, Upgradelineno);
613 // The forward declaration could have been inserted anywhere in the
614 // function: insert it into the correct place now.
615 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
616 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
623 //===----------------------------------------------------------------------===//
624 // Code to handle forward references in instructions
625 //===----------------------------------------------------------------------===//
627 // This code handles the late binding needed with statements that reference
628 // values not defined yet... for example, a forward branch, or the PHI node for
631 // This keeps a table (CurFun.LateResolveValues) of all such forward references
632 // and back patchs after we are done.
635 // ResolveDefinitions - If we could not resolve some defs at parsing
636 // time (forward branches, phi functions for loops, etc...) resolve the
640 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
641 std::map<const Type*,ValueList> *FutureLateResolvers) {
643 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
644 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
645 E = LateResolvers.end(); LRI != E; ++LRI) {
646 const Type* Ty = LRI->first;
647 ValueList &List = LRI->second;
648 while (!List.empty()) {
649 Value *V = List.back();
652 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
653 CurModule.PlaceHolderInfo.find(V);
654 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error");
656 ValID &DID = PHI->second.first;
658 Value *TheRealValue = getExistingValue(Ty, DID);
660 V->replaceAllUsesWith(TheRealValue);
662 CurModule.PlaceHolderInfo.erase(PHI);
663 } else if (FutureLateResolvers) {
664 // Functions have their unresolved items forwarded to the module late
666 InsertValue(V, *FutureLateResolvers);
668 if (DID.Type == ValID::NameVal) {
669 error("Reference to an invalid definition: '" + DID.getName() +
670 "' of type '" + V->getType()->getDescription() + "'",
674 error("Reference to an invalid definition: #" +
675 itostr(DID.Num) + " of type '" +
676 V->getType()->getDescription() + "'", PHI->second.second);
683 LateResolvers.clear();
686 /// This function is used for type resolution and upref handling. When a type
687 /// becomes concrete, this function is called to adjust the signedness for the
689 static void ResolveTypeSign(const Type* oldTy, const Signedness &Sign) {
690 std::string TyName = CurModule.CurrentModule->getTypeName(oldTy);
692 CurModule.NamedTypeSigns[TyName] = Sign;
695 /// ResolveTypeTo - A brand new type was just declared. This means that (if
696 /// name is not null) things referencing Name can be resolved. Otherwise,
697 /// things refering to the number can be resolved. Do this now.
698 static void ResolveTypeTo(char *Name, const Type *ToTy, const Signedness& Sign){
701 D = ValID::create(Name);
703 D = ValID::create((int)CurModule.Types.size());
707 CurModule.NamedTypeSigns[Name] = Sign;
709 std::map<ValID, PATypeHolder>::iterator I =
710 CurModule.LateResolveTypes.find(D);
711 if (I != CurModule.LateResolveTypes.end()) {
712 const Type *OldTy = I->second.get();
713 ((DerivedType*)OldTy)->refineAbstractTypeTo(ToTy);
714 CurModule.LateResolveTypes.erase(I);
718 /// This is the implementation portion of TypeHasInteger. It traverses the
719 /// type given, avoiding recursive types, and returns true as soon as it finds
720 /// an integer type. If no integer type is found, it returns false.
721 static bool TypeHasIntegerI(const Type *Ty, std::vector<const Type*> Stack) {
722 // Handle some easy cases
723 if (Ty->isPrimitiveType() || (Ty->getTypeID() == Type::OpaqueTyID))
727 if (const SequentialType *STy = dyn_cast<SequentialType>(Ty))
728 return STy->getElementType()->isInteger();
730 // Avoid type structure recursion
731 for (std::vector<const Type*>::iterator I = Stack.begin(), E = Stack.end();
736 // Push us on the type stack
739 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
740 if (TypeHasIntegerI(FTy->getReturnType(), Stack))
742 FunctionType::param_iterator I = FTy->param_begin();
743 FunctionType::param_iterator E = FTy->param_end();
745 if (TypeHasIntegerI(*I, Stack))
748 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
749 StructType::element_iterator I = STy->element_begin();
750 StructType::element_iterator E = STy->element_end();
751 for (; I != E; ++I) {
752 if (TypeHasIntegerI(*I, Stack))
757 // There shouldn't be anything else, but its definitely not integer
758 assert(0 && "What type is this?");
762 /// This is the interface to TypeHasIntegerI. It just provides the type stack,
763 /// to avoid recursion, and then calls TypeHasIntegerI.
764 static inline bool TypeHasInteger(const Type *Ty) {
765 std::vector<const Type*> TyStack;
766 return TypeHasIntegerI(Ty, TyStack);
769 // setValueName - Set the specified value to the name given. The name may be
770 // null potentially, in which case this is a noop. The string passed in is
771 // assumed to be a malloc'd string buffer, and is free'd by this function.
773 static void setValueName(const ValueInfo &V, char *NameStr) {
775 std::string Name(NameStr); // Copy string
776 free(NameStr); // Free old string
778 if (V.V->getType() == Type::VoidTy) {
779 error("Can't assign name '" + Name + "' to value with void type");
783 assert(inFunctionScope() && "Must be in function scope");
785 // Search the function's symbol table for an existing value of this name
786 ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
787 Value* Existing = ST.lookup(Name);
789 // An existing value of the same name was found. This might have happened
790 // because of the integer type planes collapsing in LLVM 2.0.
791 if (Existing->getType() == V.V->getType() &&
792 !TypeHasInteger(Existing->getType())) {
793 // If the type does not contain any integers in them then this can't be
794 // a type plane collapsing issue. It truly is a redefinition and we
795 // should error out as the assembly is invalid.
796 error("Redefinition of value named '" + Name + "' of type '" +
797 V.V->getType()->getDescription() + "'");
800 // In LLVM 2.0 we don't allow names to be re-used for any values in a
801 // function, regardless of Type. Previously re-use of names was okay as
802 // long as they were distinct types. With type planes collapsing because
803 // of the signedness change and because of PR411, this can no longer be
804 // supported. We must search the entire symbol table for a conflicting
805 // name and make the name unique. No warning is needed as this can't
807 std::string NewName = makeNameUnique(Name);
808 // We're changing the name but it will probably be used by other
809 // instructions as operands later on. Consequently we have to retain
810 // a mapping of the renaming that we're doing.
811 RenameMapKey Key = makeRenameMapKey(Name, V.V->getType(), V.S);
812 CurFun.RenameMap[Key] = NewName;
821 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
822 /// this is a declaration, otherwise it is a definition.
823 static GlobalVariable *
824 ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
825 bool isConstantGlobal, const Type *Ty,
826 Constant *Initializer,
827 const Signedness &Sign) {
828 if (isa<FunctionType>(Ty))
829 error("Cannot declare global vars of function type");
831 const PointerType *PTy = PointerType::getUnqual(Ty);
835 Name = NameStr; // Copy string
836 free(NameStr); // Free old string
839 // See if this global value was forward referenced. If so, recycle the
843 ID = ValID::create((char*)Name.c_str());
845 ID = ValID::create((int)CurModule.Values[PTy].size());
847 ID.S.makeComposite(Sign);
849 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
850 // Move the global to the end of the list, from whereever it was
851 // previously inserted.
852 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
853 CurModule.CurrentModule->getGlobalList().remove(GV);
854 CurModule.CurrentModule->getGlobalList().push_back(GV);
855 GV->setInitializer(Initializer);
856 GV->setLinkage(Linkage);
857 GV->setConstant(isConstantGlobal);
858 InsertValue(GV, CurModule.Values);
862 // If this global has a name, check to see if there is already a definition
863 // of this global in the module and emit warnings if there are conflicts.
865 // The global has a name. See if there's an existing one of the same name.
866 if (CurModule.CurrentModule->getNamedGlobal(Name) ||
867 CurModule.CurrentModule->getFunction(Name)) {
868 // We found an existing global of the same name. This isn't allowed
869 // in LLVM 2.0. Consequently, we must alter the name of the global so it
870 // can at least compile. This can happen because of type planes
871 // There is alread a global of the same name which means there is a
872 // conflict. Let's see what we can do about it.
873 std::string NewName(makeNameUnique(Name));
874 if (Linkage != GlobalValue::InternalLinkage) {
875 // The linkage of this gval is external so we can't reliably rename
876 // it because it could potentially create a linking problem.
877 // However, we can't leave the name conflict in the output either or
878 // it won't assemble with LLVM 2.0. So, all we can do is rename
879 // this one to something unique and emit a warning about the problem.
880 warning("Renaming global variable '" + Name + "' to '" + NewName +
881 "' may cause linkage errors");
884 // Put the renaming in the global rename map
886 makeRenameMapKey(Name, PointerType::getUnqual(Ty), ID.S);
887 CurModule.RenameMap[Key] = NewName;
894 // Otherwise there is no existing GV to use, create one now.
896 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
897 CurModule.CurrentModule);
898 InsertValue(GV, CurModule.Values);
899 // Remember the sign of this global.
900 CurModule.NamedValueSigns[Name] = ID.S;
904 // setTypeName - Set the specified type to the name given. The name may be
905 // null potentially, in which case this is a noop. The string passed in is
906 // assumed to be a malloc'd string buffer, and is freed by this function.
908 // This function returns true if the type has already been defined, but is
909 // allowed to be redefined in the specified context. If the name is a new name
910 // for the type plane, it is inserted and false is returned.
911 static bool setTypeName(const PATypeInfo& TI, char *NameStr) {
912 assert(!inFunctionScope() && "Can't give types function-local names");
913 if (NameStr == 0) return false;
915 std::string Name(NameStr); // Copy string
916 free(NameStr); // Free old string
918 const Type* Ty = TI.PAT->get();
920 // We don't allow assigning names to void type
921 if (Ty == Type::VoidTy) {
922 error("Can't assign name '" + Name + "' to the void type");
926 // Set the type name, checking for conflicts as we do so.
927 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, Ty);
929 // Save the sign information for later use
930 CurModule.NamedTypeSigns[Name] = TI.S;
932 if (AlreadyExists) { // Inserting a name that is already defined???
933 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
934 assert(Existing && "Conflict but no matching type?");
936 // There is only one case where this is allowed: when we are refining an
937 // opaque type. In this case, Existing will be an opaque type.
938 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
939 // We ARE replacing an opaque type!
940 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(Ty);
944 // Otherwise, this is an attempt to redefine a type. That's okay if
945 // the redefinition is identical to the original. This will be so if
946 // Existing and T point to the same Type object. In this one case we
947 // allow the equivalent redefinition.
948 if (Existing == Ty) return true; // Yes, it's equal.
950 // Any other kind of (non-equivalent) redefinition is an error.
951 error("Redefinition of type named '" + Name + "' in the '" +
952 Ty->getDescription() + "' type plane");
958 //===----------------------------------------------------------------------===//
959 // Code for handling upreferences in type names...
962 // TypeContains - Returns true if Ty directly contains E in it.
964 static bool TypeContains(const Type *Ty, const Type *E) {
965 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
966 E) != Ty->subtype_end();
971 // NestingLevel - The number of nesting levels that need to be popped before
972 // this type is resolved.
973 unsigned NestingLevel;
975 // LastContainedTy - This is the type at the current binding level for the
976 // type. Every time we reduce the nesting level, this gets updated.
977 const Type *LastContainedTy;
979 // UpRefTy - This is the actual opaque type that the upreference is
983 UpRefRecord(unsigned NL, OpaqueType *URTy)
984 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) { }
988 // UpRefs - A list of the outstanding upreferences that need to be resolved.
989 static std::vector<UpRefRecord> UpRefs;
991 /// HandleUpRefs - Every time we finish a new layer of types, this function is
992 /// called. It loops through the UpRefs vector, which is a list of the
993 /// currently active types. For each type, if the up reference is contained in
994 /// the newly completed type, we decrement the level count. When the level
995 /// count reaches zero, the upreferenced type is the type that is passed in:
996 /// thus we can complete the cycle.
998 static PATypeHolder HandleUpRefs(const Type *ty, const Signedness& Sign) {
999 // If Ty isn't abstract, or if there are no up-references in it, then there is
1000 // nothing to resolve here.
1001 if (!ty->isAbstract() || UpRefs.empty()) return ty;
1003 PATypeHolder Ty(ty);
1004 UR_OUT("Type '" << Ty->getDescription() <<
1005 "' newly formed. Resolving upreferences.\n" <<
1006 UpRefs.size() << " upreferences active!\n");
1008 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1009 // to zero), we resolve them all together before we resolve them to Ty. At
1010 // the end of the loop, if there is anything to resolve to Ty, it will be in
1012 OpaqueType *TypeToResolve = 0;
1015 for (; i != UpRefs.size(); ++i) {
1016 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1017 << UpRefs[i].UpRefTy->getDescription() << ") = "
1018 << (TypeContains(Ty, UpRefs[i].UpRefTy) ? "true" : "false") << "\n");
1019 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
1020 // Decrement level of upreference
1021 unsigned Level = --UpRefs[i].NestingLevel;
1022 UpRefs[i].LastContainedTy = Ty;
1023 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
1024 if (Level == 0) { // Upreference should be resolved!
1025 if (!TypeToResolve) {
1026 TypeToResolve = UpRefs[i].UpRefTy;
1028 UR_OUT(" * Resolving upreference for "
1029 << UpRefs[i].UpRefTy->getDescription() << "\n";
1030 std::string OldName = UpRefs[i].UpRefTy->getDescription());
1031 ResolveTypeSign(UpRefs[i].UpRefTy, Sign);
1032 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1033 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
1034 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
1036 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
1037 --i; // Do not skip the next element...
1042 if (TypeToResolve) {
1043 UR_OUT(" * Resolving upreference for "
1044 << UpRefs[i].UpRefTy->getDescription() << "\n";
1045 std::string OldName = TypeToResolve->getDescription());
1046 ResolveTypeSign(TypeToResolve, Sign);
1047 TypeToResolve->refineAbstractTypeTo(Ty);
1053 bool Signedness::operator<(const Signedness &that) const {
1056 return *(this->name) < *(that.name);
1058 return CurModule.NamedTypeSigns[*name] < that;
1059 } else if (that.isNamed()) {
1060 return *this < CurModule.NamedTypeSigns[*that.name];
1063 if (isComposite() && that.isComposite()) {
1064 if (sv->size() == that.sv->size()) {
1065 SignVector::const_iterator thisI = sv->begin(), thisE = sv->end();
1066 SignVector::const_iterator thatI = that.sv->begin(),
1067 thatE = that.sv->end();
1068 for (; thisI != thisE; ++thisI, ++thatI) {
1069 if (*thisI < *thatI)
1071 else if (!(*thisI == *thatI))
1076 return sv->size() < that.sv->size();
1078 return kind < that.kind;
1081 bool Signedness::operator==(const Signedness &that) const {
1084 return *(this->name) == *(that.name);
1086 return CurModule.NamedTypeSigns[*(this->name)] == that;
1087 else if (that.isNamed())
1088 return *this == CurModule.NamedTypeSigns[*(that.name)];
1089 if (isComposite() && that.isComposite()) {
1090 if (sv->size() == that.sv->size()) {
1091 SignVector::const_iterator thisI = sv->begin(), thisE = sv->end();
1092 SignVector::const_iterator thatI = that.sv->begin(),
1093 thatE = that.sv->end();
1094 for (; thisI != thisE; ++thisI, ++thatI) {
1095 if (!(*thisI == *thatI))
1102 return kind == that.kind;
1105 void Signedness::copy(const Signedness &that) {
1106 if (that.isNamed()) {
1108 name = new std::string(*that.name);
1109 } else if (that.isComposite()) {
1111 sv = new SignVector();
1119 void Signedness::destroy() {
1122 } else if (isComposite()) {
1128 void Signedness::dump() const {
1129 if (isComposite()) {
1130 if (sv->size() == 1) {
1135 for (unsigned i = 0; i < sv->size(); ++i) {
1142 } else if (isNamed()) {
1144 } else if (isSigned()) {
1146 } else if (isUnsigned()) {
1153 static inline Instruction::TermOps
1154 getTermOp(TermOps op) {
1156 default : assert(0 && "Invalid OldTermOp");
1157 case RetOp : return Instruction::Ret;
1158 case BrOp : return Instruction::Br;
1159 case SwitchOp : return Instruction::Switch;
1160 case InvokeOp : return Instruction::Invoke;
1161 case UnwindOp : return Instruction::Unwind;
1162 case UnreachableOp: return Instruction::Unreachable;
1166 static inline Instruction::BinaryOps
1167 getBinaryOp(BinaryOps op, const Type *Ty, const Signedness& Sign) {
1169 default : assert(0 && "Invalid OldBinaryOps");
1175 case SetGT : assert(0 && "Should use getCompareOp");
1176 case AddOp : return Instruction::Add;
1177 case SubOp : return Instruction::Sub;
1178 case MulOp : return Instruction::Mul;
1180 // This is an obsolete instruction so we must upgrade it based on the
1181 // types of its operands.
1182 bool isFP = Ty->isFloatingPoint();
1183 if (const VectorType* PTy = dyn_cast<VectorType>(Ty))
1184 // If its a vector type we want to use the element type
1185 isFP = PTy->getElementType()->isFloatingPoint();
1187 return Instruction::FDiv;
1188 else if (Sign.isSigned())
1189 return Instruction::SDiv;
1190 return Instruction::UDiv;
1192 case UDivOp : return Instruction::UDiv;
1193 case SDivOp : return Instruction::SDiv;
1194 case FDivOp : return Instruction::FDiv;
1196 // This is an obsolete instruction so we must upgrade it based on the
1197 // types of its operands.
1198 bool isFP = Ty->isFloatingPoint();
1199 if (const VectorType* PTy = dyn_cast<VectorType>(Ty))
1200 // If its a vector type we want to use the element type
1201 isFP = PTy->getElementType()->isFloatingPoint();
1202 // Select correct opcode
1204 return Instruction::FRem;
1205 else if (Sign.isSigned())
1206 return Instruction::SRem;
1207 return Instruction::URem;
1209 case URemOp : return Instruction::URem;
1210 case SRemOp : return Instruction::SRem;
1211 case FRemOp : return Instruction::FRem;
1212 case LShrOp : return Instruction::LShr;
1213 case AShrOp : return Instruction::AShr;
1214 case ShlOp : return Instruction::Shl;
1216 if (Sign.isSigned())
1217 return Instruction::AShr;
1218 return Instruction::LShr;
1219 case AndOp : return Instruction::And;
1220 case OrOp : return Instruction::Or;
1221 case XorOp : return Instruction::Xor;
1225 static inline Instruction::OtherOps
1226 getCompareOp(BinaryOps op, unsigned short &predicate, const Type* &Ty,
1227 const Signedness &Sign) {
1228 bool isSigned = Sign.isSigned();
1229 bool isFP = Ty->isFloatingPoint();
1231 default : assert(0 && "Invalid OldSetCC");
1234 predicate = FCmpInst::FCMP_OEQ;
1235 return Instruction::FCmp;
1237 predicate = ICmpInst::ICMP_EQ;
1238 return Instruction::ICmp;
1242 predicate = FCmpInst::FCMP_UNE;
1243 return Instruction::FCmp;
1245 predicate = ICmpInst::ICMP_NE;
1246 return Instruction::ICmp;
1250 predicate = FCmpInst::FCMP_OLE;
1251 return Instruction::FCmp;
1254 predicate = ICmpInst::ICMP_SLE;
1256 predicate = ICmpInst::ICMP_ULE;
1257 return Instruction::ICmp;
1261 predicate = FCmpInst::FCMP_OGE;
1262 return Instruction::FCmp;
1265 predicate = ICmpInst::ICMP_SGE;
1267 predicate = ICmpInst::ICMP_UGE;
1268 return Instruction::ICmp;
1272 predicate = FCmpInst::FCMP_OLT;
1273 return Instruction::FCmp;
1276 predicate = ICmpInst::ICMP_SLT;
1278 predicate = ICmpInst::ICMP_ULT;
1279 return Instruction::ICmp;
1283 predicate = FCmpInst::FCMP_OGT;
1284 return Instruction::FCmp;
1287 predicate = ICmpInst::ICMP_SGT;
1289 predicate = ICmpInst::ICMP_UGT;
1290 return Instruction::ICmp;
1295 static inline Instruction::MemoryOps getMemoryOp(MemoryOps op) {
1297 default : assert(0 && "Invalid OldMemoryOps");
1298 case MallocOp : return Instruction::Malloc;
1299 case FreeOp : return Instruction::Free;
1300 case AllocaOp : return Instruction::Alloca;
1301 case LoadOp : return Instruction::Load;
1302 case StoreOp : return Instruction::Store;
1303 case GetElementPtrOp : return Instruction::GetElementPtr;
1307 static inline Instruction::OtherOps
1308 getOtherOp(OtherOps op, const Signedness &Sign) {
1310 default : assert(0 && "Invalid OldOtherOps");
1311 case PHIOp : return Instruction::PHI;
1312 case CallOp : return Instruction::Call;
1313 case SelectOp : return Instruction::Select;
1314 case UserOp1 : return Instruction::UserOp1;
1315 case UserOp2 : return Instruction::UserOp2;
1316 case VAArg : return Instruction::VAArg;
1317 case ExtractElementOp : return Instruction::ExtractElement;
1318 case InsertElementOp : return Instruction::InsertElement;
1319 case ShuffleVectorOp : return Instruction::ShuffleVector;
1320 case ICmpOp : return Instruction::ICmp;
1321 case FCmpOp : return Instruction::FCmp;
1325 static inline Value*
1326 getCast(CastOps op, Value *Src, const Signedness &SrcSign, const Type *DstTy,
1327 const Signedness &DstSign, bool ForceInstruction = false) {
1328 Instruction::CastOps Opcode;
1329 const Type* SrcTy = Src->getType();
1331 if (SrcTy->isFloatingPoint() && isa<PointerType>(DstTy)) {
1332 // fp -> ptr cast is no longer supported but we must upgrade this
1333 // by doing a double cast: fp -> int -> ptr
1334 SrcTy = Type::Int64Ty;
1335 Opcode = Instruction::IntToPtr;
1336 if (isa<Constant>(Src)) {
1337 Src = ConstantExpr::getCast(Instruction::FPToUI,
1338 cast<Constant>(Src), SrcTy);
1340 std::string NewName(makeNameUnique(Src->getName()));
1341 Src = new FPToUIInst(Src, SrcTy, NewName, CurBB);
1343 } else if (isa<IntegerType>(DstTy) &&
1344 cast<IntegerType>(DstTy)->getBitWidth() == 1) {
1345 // cast type %x to bool was previously defined as setne type %x, null
1346 // The cast semantic is now to truncate, not compare so we must retain
1347 // the original intent by replacing the cast with a setne
1348 Constant* Null = Constant::getNullValue(SrcTy);
1349 Instruction::OtherOps Opcode = Instruction::ICmp;
1350 unsigned short predicate = ICmpInst::ICMP_NE;
1351 if (SrcTy->isFloatingPoint()) {
1352 Opcode = Instruction::FCmp;
1353 predicate = FCmpInst::FCMP_ONE;
1354 } else if (!SrcTy->isInteger() && !isa<PointerType>(SrcTy)) {
1355 error("Invalid cast to bool");
1357 if (isa<Constant>(Src) && !ForceInstruction)
1358 return ConstantExpr::getCompare(predicate, cast<Constant>(Src), Null);
1360 return CmpInst::create(Opcode, predicate, Src, Null);
1362 // Determine the opcode to use by calling CastInst::getCastOpcode
1364 CastInst::getCastOpcode(Src, SrcSign.isSigned(), DstTy,
1365 DstSign.isSigned());
1367 } else switch (op) {
1368 default: assert(0 && "Invalid cast token");
1369 case TruncOp: Opcode = Instruction::Trunc; break;
1370 case ZExtOp: Opcode = Instruction::ZExt; break;
1371 case SExtOp: Opcode = Instruction::SExt; break;
1372 case FPTruncOp: Opcode = Instruction::FPTrunc; break;
1373 case FPExtOp: Opcode = Instruction::FPExt; break;
1374 case FPToUIOp: Opcode = Instruction::FPToUI; break;
1375 case FPToSIOp: Opcode = Instruction::FPToSI; break;
1376 case UIToFPOp: Opcode = Instruction::UIToFP; break;
1377 case SIToFPOp: Opcode = Instruction::SIToFP; break;
1378 case PtrToIntOp: Opcode = Instruction::PtrToInt; break;
1379 case IntToPtrOp: Opcode = Instruction::IntToPtr; break;
1380 case BitCastOp: Opcode = Instruction::BitCast; break;
1383 if (isa<Constant>(Src) && !ForceInstruction)
1384 return ConstantExpr::getCast(Opcode, cast<Constant>(Src), DstTy);
1385 return CastInst::create(Opcode, Src, DstTy);
1388 static Instruction *
1389 upgradeIntrinsicCall(const Type* RetTy, const ValID &ID,
1390 std::vector<Value*>& Args) {
1392 std::string Name = ID.Type == ValID::NameVal ? ID.Name : "";
1393 if (Name.length() <= 5 || Name[0] != 'l' || Name[1] != 'l' ||
1394 Name[2] != 'v' || Name[3] != 'm' || Name[4] != '.')
1399 if (Name == "llvm.isunordered.f32" || Name == "llvm.isunordered.f64") {
1400 if (Args.size() != 2)
1401 error("Invalid prototype for " + Name);
1402 return new FCmpInst(FCmpInst::FCMP_UNO, Args[0], Args[1]);
1407 const Type* PtrTy = PointerType::getUnqual(Type::Int8Ty);
1408 std::vector<const Type*> Params;
1409 if (Name == "llvm.va_start" || Name == "llvm.va_end") {
1410 if (Args.size() != 1)
1411 error("Invalid prototype for " + Name + " prototype");
1412 Params.push_back(PtrTy);
1413 const FunctionType *FTy =
1414 FunctionType::get(Type::VoidTy, Params, false);
1415 const PointerType *PFTy = PointerType::getUnqual(FTy);
1416 Value* Func = getVal(PFTy, ID);
1417 Args[0] = new BitCastInst(Args[0], PtrTy, makeNameUnique("va"), CurBB);
1418 return new CallInst(Func, Args.begin(), Args.end());
1419 } else if (Name == "llvm.va_copy") {
1420 if (Args.size() != 2)
1421 error("Invalid prototype for " + Name + " prototype");
1422 Params.push_back(PtrTy);
1423 Params.push_back(PtrTy);
1424 const FunctionType *FTy =
1425 FunctionType::get(Type::VoidTy, Params, false);
1426 const PointerType *PFTy = PointerType::getUnqual(FTy);
1427 Value* Func = getVal(PFTy, ID);
1428 std::string InstName0(makeNameUnique("va0"));
1429 std::string InstName1(makeNameUnique("va1"));
1430 Args[0] = new BitCastInst(Args[0], PtrTy, InstName0, CurBB);
1431 Args[1] = new BitCastInst(Args[1], PtrTy, InstName1, CurBB);
1432 return new CallInst(Func, Args.begin(), Args.end());
1439 const Type* upgradeGEPCEIndices(const Type* PTy,
1440 std::vector<ValueInfo> *Indices,
1441 std::vector<Constant*> &Result) {
1442 const Type *Ty = PTy;
1444 for (unsigned i = 0, e = Indices->size(); i != e ; ++i) {
1445 Constant *Index = cast<Constant>((*Indices)[i].V);
1447 if (ConstantInt *CI = dyn_cast<ConstantInt>(Index)) {
1448 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte
1449 // struct indices to i32 struct indices with ZExt for compatibility.
1450 if (CI->getBitWidth() < 32)
1451 Index = ConstantExpr::getCast(Instruction::ZExt, CI, Type::Int32Ty);
1454 if (isa<SequentialType>(Ty)) {
1455 // Make sure that unsigned SequentialType indices are zext'd to
1456 // 64-bits if they were smaller than that because LLVM 2.0 will sext
1457 // all indices for SequentialType elements. We must retain the same
1458 // semantic (zext) for unsigned types.
1459 if (const IntegerType *Ity = dyn_cast<IntegerType>(Index->getType())) {
1460 if (Ity->getBitWidth() < 64 && (*Indices)[i].S.isUnsigned()) {
1461 Index = ConstantExpr::getCast(Instruction::ZExt, Index,Type::Int64Ty);
1465 Result.push_back(Index);
1466 Ty = GetElementPtrInst::getIndexedType(PTy, Result.begin(),
1469 error("Index list invalid for constant getelementptr");
1474 const Type* upgradeGEPInstIndices(const Type* PTy,
1475 std::vector<ValueInfo> *Indices,
1476 std::vector<Value*> &Result) {
1477 const Type *Ty = PTy;
1479 for (unsigned i = 0, e = Indices->size(); i != e ; ++i) {
1480 Value *Index = (*Indices)[i].V;
1482 if (ConstantInt *CI = dyn_cast<ConstantInt>(Index)) {
1483 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte
1484 // struct indices to i32 struct indices with ZExt for compatibility.
1485 if (CI->getBitWidth() < 32)
1486 Index = ConstantExpr::getCast(Instruction::ZExt, CI, Type::Int32Ty);
1490 if (isa<StructType>(Ty)) { // Only change struct indices
1491 if (!isa<Constant>(Index)) {
1492 error("Invalid non-constant structure index");
1496 // Make sure that unsigned SequentialType indices are zext'd to
1497 // 64-bits if they were smaller than that because LLVM 2.0 will sext
1498 // all indices for SequentialType elements. We must retain the same
1499 // semantic (zext) for unsigned types.
1500 if (const IntegerType *Ity = dyn_cast<IntegerType>(Index->getType())) {
1501 if (Ity->getBitWidth() < 64 && (*Indices)[i].S.isUnsigned()) {
1502 if (isa<Constant>(Index))
1503 Index = ConstantExpr::getCast(Instruction::ZExt,
1504 cast<Constant>(Index), Type::Int64Ty);
1506 Index = CastInst::create(Instruction::ZExt, Index, Type::Int64Ty,
1507 makeNameUnique("gep"), CurBB);
1511 Result.push_back(Index);
1512 Ty = GetElementPtrInst::getIndexedType(PTy, Result.begin(),
1515 error("Index list invalid for constant getelementptr");
1520 unsigned upgradeCallingConv(unsigned CC) {
1522 case OldCallingConv::C : return CallingConv::C;
1523 case OldCallingConv::CSRet : return CallingConv::C;
1524 case OldCallingConv::Fast : return CallingConv::Fast;
1525 case OldCallingConv::Cold : return CallingConv::Cold;
1526 case OldCallingConv::X86_StdCall : return CallingConv::X86_StdCall;
1527 case OldCallingConv::X86_FastCall: return CallingConv::X86_FastCall;
1533 Module* UpgradeAssembly(const std::string &infile, std::istream& in,
1534 bool debug, bool addAttrs)
1537 CurFilename = infile;
1540 AddAttributes = addAttrs;
1541 ObsoleteVarArgs = false;
1544 CurModule.CurrentModule = new Module(CurFilename);
1546 // Check to make sure the parser succeeded
1549 delete ParserResult;
1550 std::cerr << "llvm-upgrade: parse failed.\n";
1554 // Check to make sure that parsing produced a result
1555 if (!ParserResult) {
1556 std::cerr << "llvm-upgrade: no parse result.\n";
1560 // Reset ParserResult variable while saving its value for the result.
1561 Module *Result = ParserResult;
1564 //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
1567 if ((F = Result->getFunction("llvm.va_start"))
1568 && F->getFunctionType()->getNumParams() == 0)
1569 ObsoleteVarArgs = true;
1570 if((F = Result->getFunction("llvm.va_copy"))
1571 && F->getFunctionType()->getNumParams() == 1)
1572 ObsoleteVarArgs = true;
1575 if (ObsoleteVarArgs && NewVarArgs) {
1576 error("This file is corrupt: it uses both new and old style varargs");
1580 if(ObsoleteVarArgs) {
1581 if(Function* F = Result->getFunction("llvm.va_start")) {
1582 if (F->arg_size() != 0) {
1583 error("Obsolete va_start takes 0 argument");
1589 //bar = alloca typeof(foo)
1593 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1594 const Type* ArgTy = F->getFunctionType()->getReturnType();
1595 const Type* ArgTyPtr = PointerType::getUnqual(ArgTy);
1596 Function* NF = cast<Function>(Result->getOrInsertFunction(
1597 "llvm.va_start", RetTy, ArgTyPtr, (Type *)0));
1599 while (!F->use_empty()) {
1600 CallInst* CI = cast<CallInst>(F->use_back());
1601 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
1602 new CallInst(NF, bar, "", CI);
1603 Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
1604 CI->replaceAllUsesWith(foo);
1605 CI->getParent()->getInstList().erase(CI);
1607 Result->getFunctionList().erase(F);
1610 if(Function* F = Result->getFunction("llvm.va_end")) {
1611 if(F->arg_size() != 1) {
1612 error("Obsolete va_end takes 1 argument");
1618 //bar = alloca 1 of typeof(foo)
1620 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1621 const Type* ArgTy = F->getFunctionType()->getParamType(0);
1622 const Type* ArgTyPtr = PointerType::getUnqual(ArgTy);
1623 Function* NF = cast<Function>(Result->getOrInsertFunction(
1624 "llvm.va_end", RetTy, ArgTyPtr, (Type *)0));
1626 while (!F->use_empty()) {
1627 CallInst* CI = cast<CallInst>(F->use_back());
1628 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
1629 new StoreInst(CI->getOperand(1), bar, CI);
1630 new CallInst(NF, bar, "", CI);
1631 CI->getParent()->getInstList().erase(CI);
1633 Result->getFunctionList().erase(F);
1636 if(Function* F = Result->getFunction("llvm.va_copy")) {
1637 if(F->arg_size() != 1) {
1638 error("Obsolete va_copy takes 1 argument");
1643 //a = alloca 1 of typeof(foo)
1644 //b = alloca 1 of typeof(foo)
1649 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1650 const Type* ArgTy = F->getFunctionType()->getReturnType();
1651 const Type* ArgTyPtr = PointerType::getUnqual(ArgTy);
1652 Function* NF = cast<Function>(Result->getOrInsertFunction(
1653 "llvm.va_copy", RetTy, ArgTyPtr, ArgTyPtr, (Type *)0));
1655 while (!F->use_empty()) {
1656 CallInst* CI = cast<CallInst>(F->use_back());
1658 new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI),
1659 new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI)
1661 new StoreInst(CI->getOperand(1), Args[1], CI);
1662 new CallInst(NF, Args, Args + 2, "", CI);
1663 Value* foo = new LoadInst(Args[0], "vacopy.fix.3", CI);
1664 CI->replaceAllUsesWith(foo);
1665 CI->getParent()->getInstList().erase(CI);
1667 Result->getFunctionList().erase(F);
1674 } // end llvm namespace
1676 using namespace llvm;
1681 llvm::Module *ModuleVal;
1682 llvm::Function *FunctionVal;
1683 std::pair<llvm::PATypeInfo, char*> *ArgVal;
1684 llvm::BasicBlock *BasicBlockVal;
1685 llvm::TermInstInfo TermInstVal;
1686 llvm::InstrInfo InstVal;
1687 llvm::ConstInfo ConstVal;
1688 llvm::ValueInfo ValueVal;
1689 llvm::PATypeInfo TypeVal;
1690 llvm::TypeInfo PrimType;
1691 llvm::PHIListInfo PHIList;
1692 std::list<llvm::PATypeInfo> *TypeList;
1693 std::vector<llvm::ValueInfo> *ValueList;
1694 std::vector<llvm::ConstInfo> *ConstVector;
1697 std::vector<std::pair<llvm::PATypeInfo,char*> > *ArgList;
1698 // Represent the RHS of PHI node
1699 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
1701 llvm::GlobalValue::LinkageTypes Linkage;
1706 llvm::APFloat *FPVal;
1709 char *StrVal; // This memory is strdup'd!
1710 llvm::ValID ValIDVal; // strdup'd memory maybe!
1712 llvm::BinaryOps BinaryOpVal;
1713 llvm::TermOps TermOpVal;
1714 llvm::MemoryOps MemOpVal;
1715 llvm::OtherOps OtherOpVal;
1716 llvm::CastOps CastOpVal;
1717 llvm::ICmpInst::Predicate IPred;
1718 llvm::FCmpInst::Predicate FPred;
1719 llvm::Module::Endianness Endianness;
1722 %type <ModuleVal> Module FunctionList
1723 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1724 %type <BasicBlockVal> BasicBlock InstructionList
1725 %type <TermInstVal> BBTerminatorInst
1726 %type <InstVal> Inst InstVal MemoryInst
1727 %type <ConstVal> ConstVal ConstExpr
1728 %type <ConstVector> ConstVector
1729 %type <ArgList> ArgList ArgListH
1730 %type <ArgVal> ArgVal
1731 %type <PHIList> PHIList
1732 %type <ValueList> ValueRefList ValueRefListE // For call param lists
1733 %type <ValueList> IndexList // For GEP derived indices
1734 %type <TypeList> TypeListI ArgTypeListI
1735 %type <JumpTable> JumpTable
1736 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1737 %type <BoolVal> OptVolatile // 'volatile' or not
1738 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1739 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
1740 %type <Linkage> OptLinkage FnDeclareLinkage
1741 %type <Endianness> BigOrLittle
1743 // ValueRef - Unresolved reference to a definition or BB
1744 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1745 %type <ValueVal> ResolvedVal // <type> <valref> pair
1747 // Tokens and types for handling constant integer values
1749 // ESINT64VAL - A negative number within long long range
1750 %token <SInt64Val> ESINT64VAL
1752 // EUINT64VAL - A positive number within uns. long long range
1753 %token <UInt64Val> EUINT64VAL
1754 %type <SInt64Val> EINT64VAL
1756 %token <SIntVal> SINTVAL // Signed 32 bit ints...
1757 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
1758 %type <SIntVal> INTVAL
1759 %token <FPVal> FPVAL // Float or Double constant
1761 // Built in types...
1762 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
1763 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
1764 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
1765 %token <PrimType> FLOAT DOUBLE TYPE LABEL
1767 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
1768 %type <StrVal> Name OptName OptAssign
1769 %type <UIntVal> OptAlign OptCAlign
1770 %type <StrVal> OptSection SectionString
1772 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1773 %token DECLARE GLOBAL CONSTANT SECTION VOLATILE
1774 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
1775 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
1776 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
1777 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1778 %token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
1779 %token X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1781 %type <UIntVal> OptCallingConv
1783 // Basic Block Terminating Operators
1784 %token <TermOpVal> RET BR SWITCH INVOKE UNREACHABLE
1785 %token UNWIND EXCEPT
1788 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
1789 %type <BinaryOpVal> ShiftOps
1790 %token <BinaryOpVal> ADD SUB MUL DIV UDIV SDIV FDIV REM UREM SREM FREM
1791 %token <BinaryOpVal> AND OR XOR SHL SHR ASHR LSHR
1792 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comparators
1793 %token <OtherOpVal> ICMP FCMP
1795 // Memory Instructions
1796 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1799 %token <OtherOpVal> PHI_TOK SELECT VAARG
1800 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1801 %token VAARG_old VANEXT_old //OBSOLETE
1803 // Support for ICmp/FCmp Predicates, which is 1.9++ but not 2.0
1804 %type <IPred> IPredicates
1805 %type <FPred> FPredicates
1806 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1807 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1809 %token <CastOpVal> CAST TRUNC ZEXT SEXT FPTRUNC FPEXT FPTOUI FPTOSI
1810 %token <CastOpVal> UITOFP SITOFP PTRTOINT INTTOPTR BITCAST
1811 %type <CastOpVal> CastOps
1817 // Handle constant integer size restriction and conversion...
1822 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
1823 error("Value too large for type");
1829 : ESINT64VAL // These have same type and can't cause problems...
1831 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
1832 error("Value too large for type");
1836 // Operations that are notably excluded from this list include:
1837 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1840 : ADD | SUB | MUL | DIV | UDIV | SDIV | FDIV | REM | UREM | SREM | FREM
1848 : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
1852 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1853 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1854 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1855 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1856 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1860 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1861 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1862 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1863 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1864 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1865 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1866 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1867 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1868 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1871 : SHL | SHR | ASHR | LSHR
1875 : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | FPTOUI | FPTOSI
1876 | UITOFP | SITOFP | PTRTOINT | INTTOPTR | BITCAST | CAST
1879 // These are some types that allow classification if we only want a particular
1880 // thing... for example, only a signed, unsigned, or integral type.
1882 : LONG | INT | SHORT | SBYTE
1886 : ULONG | UINT | USHORT | UBYTE
1890 : SIntType | UIntType
1897 // OptAssign - Value producing statements have an optional assignment component
1907 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1908 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1909 | WEAK { $$ = GlobalValue::WeakLinkage; }
1910 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1911 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1912 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1913 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1914 | /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1918 : /*empty*/ { $$ = lastCallingConv = OldCallingConv::C; }
1919 | CCC_TOK { $$ = lastCallingConv = OldCallingConv::C; }
1920 | CSRETCC_TOK { $$ = lastCallingConv = OldCallingConv::CSRet; }
1921 | FASTCC_TOK { $$ = lastCallingConv = OldCallingConv::Fast; }
1922 | COLDCC_TOK { $$ = lastCallingConv = OldCallingConv::Cold; }
1923 | X86_STDCALLCC_TOK { $$ = lastCallingConv = OldCallingConv::X86_StdCall; }
1924 | X86_FASTCALLCC_TOK { $$ = lastCallingConv = OldCallingConv::X86_FastCall; }
1925 | CC_TOK EUINT64VAL {
1926 if ((unsigned)$2 != $2)
1927 error("Calling conv too large");
1928 $$ = lastCallingConv = $2;
1932 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1933 // a comma before it.
1935 : /*empty*/ { $$ = 0; }
1936 | ALIGN EUINT64VAL {
1938 if ($$ != 0 && !isPowerOf2_32($$))
1939 error("Alignment must be a power of two");
1944 : /*empty*/ { $$ = 0; }
1945 | ',' ALIGN EUINT64VAL {
1947 if ($$ != 0 && !isPowerOf2_32($$))
1948 error("Alignment must be a power of two");
1953 : SECTION STRINGCONSTANT {
1954 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1955 if ($2[i] == '"' || $2[i] == '\\')
1956 error("Invalid character in section name");
1962 : /*empty*/ { $$ = 0; }
1963 | SectionString { $$ = $1; }
1966 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1967 // is set to be the global we are processing.
1971 | ',' GlobalVarAttribute GlobalVarAttributes {}
1976 CurGV->setSection($1);
1979 | ALIGN EUINT64VAL {
1980 if ($2 != 0 && !isPowerOf2_32($2))
1981 error("Alignment must be a power of two");
1982 CurGV->setAlignment($2);
1987 //===----------------------------------------------------------------------===//
1988 // Types includes all predefined types... except void, because it can only be
1989 // used in specific contexts (function returning void for example). To have
1990 // access to it, a user must explicitly use TypesV.
1993 // TypesV includes all of 'Types', but it also includes the void type.
1997 $$.PAT = new PATypeHolder($1.T);
1998 $$.S.makeSignless();
2005 $$.PAT = new PATypeHolder($1.T);
2006 $$.S.makeSignless();
2012 if (!UpRefs.empty())
2013 error("Invalid upreference in type: " + (*$1.PAT)->getDescription());
2019 : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT
2020 | LONG | ULONG | FLOAT | DOUBLE | LABEL
2023 // Derived types are added later...
2026 $$.PAT = new PATypeHolder($1.T);
2030 $$.PAT = new PATypeHolder(OpaqueType::get());
2031 $$.S.makeSignless();
2033 | SymbolicValueRef { // Named types are also simple types...
2034 $$.S.copy(getTypeSign($1));
2035 const Type* tmp = getType($1);
2036 $$.PAT = new PATypeHolder(tmp);
2038 | '\\' EUINT64VAL { // Type UpReference
2039 if ($2 > (uint64_t)~0U)
2040 error("Value out of range");
2041 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
2042 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
2043 $$.PAT = new PATypeHolder(OT);
2044 $$.S.makeSignless();
2045 UR_OUT("New Upreference!\n");
2047 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
2048 $$.S.makeComposite($1.S);
2049 std::vector<const Type*> Params;
2050 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
2051 E = $3->end(); I != E; ++I) {
2052 Params.push_back(I->PAT->get());
2055 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
2056 if (isVarArg) Params.pop_back();
2059 if (lastCallingConv == OldCallingConv::CSRet) {
2060 ParamAttrsWithIndex PAWI =
2061 ParamAttrsWithIndex::get(1, ParamAttr::StructRet);
2062 PAL = PAListPtr::get(&PAWI, 1);
2065 const FunctionType *FTy =
2066 FunctionType::get($1.PAT->get(), Params, isVarArg);
2068 $$.PAT = new PATypeHolder( HandleUpRefs(FTy, $$.S) );
2069 delete $1.PAT; // Delete the return type handle
2070 delete $3; // Delete the argument list
2072 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
2073 $$.S.makeComposite($4.S);
2074 $$.PAT = new PATypeHolder(HandleUpRefs(ArrayType::get($4.PAT->get(),
2075 (unsigned)$2), $$.S));
2078 | '<' EUINT64VAL 'x' UpRTypes '>' { // Vector type?
2079 const llvm::Type* ElemTy = $4.PAT->get();
2080 if ((unsigned)$2 != $2)
2081 error("Unsigned result not equal to signed result");
2082 if (!(ElemTy->isInteger() || ElemTy->isFloatingPoint()))
2083 error("Elements of a VectorType must be integer or floating point");
2084 if (!isPowerOf2_32($2))
2085 error("VectorType length should be a power of 2");
2086 $$.S.makeComposite($4.S);
2087 $$.PAT = new PATypeHolder(HandleUpRefs(VectorType::get(ElemTy,
2088 (unsigned)$2), $$.S));
2091 | '{' TypeListI '}' { // Structure type?
2092 std::vector<const Type*> Elements;
2093 $$.S.makeComposite();
2094 for (std::list<llvm::PATypeInfo>::iterator I = $2->begin(),
2095 E = $2->end(); I != E; ++I) {
2096 Elements.push_back(I->PAT->get());
2099 $$.PAT = new PATypeHolder(HandleUpRefs(StructType::get(Elements), $$.S));
2102 | '{' '}' { // Empty structure type?
2103 $$.PAT = new PATypeHolder(StructType::get(std::vector<const Type*>()));
2104 $$.S.makeComposite();
2106 | '<' '{' TypeListI '}' '>' { // Packed Structure type?
2107 $$.S.makeComposite();
2108 std::vector<const Type*> Elements;
2109 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
2110 E = $3->end(); I != E; ++I) {
2111 Elements.push_back(I->PAT->get());
2115 $$.PAT = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true),
2119 | '<' '{' '}' '>' { // Empty packed structure type?
2120 $$.PAT = new PATypeHolder(StructType::get(std::vector<const Type*>(),true));
2121 $$.S.makeComposite();
2123 | UpRTypes '*' { // Pointer type?
2124 if ($1.PAT->get() == Type::LabelTy)
2125 error("Cannot form a pointer to a basic block");
2126 $$.S.makeComposite($1.S);
2128 PATypeHolder(HandleUpRefs(PointerType::getUnqual($1.PAT->get()),
2134 // TypeList - Used for struct declarations and as a basis for function type
2135 // declaration type lists
2139 $$ = new std::list<PATypeInfo>();
2142 | TypeListI ',' UpRTypes {
2143 ($$=$1)->push_back($3);
2147 // ArgTypeList - List of types for a function type declaration...
2150 | TypeListI ',' DOTDOTDOT {
2152 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2153 VoidTI.S.makeSignless();
2154 ($$=$1)->push_back(VoidTI);
2157 $$ = new std::list<PATypeInfo>();
2159 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2160 VoidTI.S.makeSignless();
2161 $$->push_back(VoidTI);
2164 $$ = new std::list<PATypeInfo>();
2168 // ConstVal - The various declarations that go into the constant pool. This
2169 // production is used ONLY to represent constants that show up AFTER a 'const',
2170 // 'constant' or 'global' token at global scope. Constants that can be inlined
2171 // into other expressions (such as integers and constexprs) are handled by the
2172 // ResolvedVal, ValueRef and ConstValueRef productions.
2175 : Types '[' ConstVector ']' { // Nonempty unsized arr
2176 const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
2178 error("Cannot make array constant with type: '" +
2179 $1.PAT->get()->getDescription() + "'");
2180 const Type *ETy = ATy->getElementType();
2181 int NumElements = ATy->getNumElements();
2183 // Verify that we have the correct size...
2184 if (NumElements != -1 && NumElements != (int)$3->size())
2185 error("Type mismatch: constant sized array initialized with " +
2186 utostr($3->size()) + " arguments, but has size of " +
2187 itostr(NumElements) + "");
2189 // Verify all elements are correct type!
2190 std::vector<Constant*> Elems;
2191 for (unsigned i = 0; i < $3->size(); i++) {
2192 Constant *C = (*$3)[i].C;
2193 const Type* ValTy = C->getType();
2195 error("Element #" + utostr(i) + " is not of type '" +
2196 ETy->getDescription() +"' as required!\nIt is of type '"+
2197 ValTy->getDescription() + "'");
2200 $$.C = ConstantArray::get(ATy, Elems);
2206 const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
2208 error("Cannot make array constant with type: '" +
2209 $1.PAT->get()->getDescription() + "'");
2210 int NumElements = ATy->getNumElements();
2211 if (NumElements != -1 && NumElements != 0)
2212 error("Type mismatch: constant sized array initialized with 0"
2213 " arguments, but has size of " + itostr(NumElements) +"");
2214 $$.C = ConstantArray::get(ATy, std::vector<Constant*>());
2218 | Types 'c' STRINGCONSTANT {
2219 const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
2221 error("Cannot make array constant with type: '" +
2222 $1.PAT->get()->getDescription() + "'");
2223 int NumElements = ATy->getNumElements();
2224 const Type *ETy = dyn_cast<IntegerType>(ATy->getElementType());
2225 if (!ETy || cast<IntegerType>(ETy)->getBitWidth() != 8)
2226 error("String arrays require type i8, not '" + ETy->getDescription() +
2228 char *EndStr = UnEscapeLexed($3, true);
2229 if (NumElements != -1 && NumElements != (EndStr-$3))
2230 error("Can't build string constant of size " +
2231 itostr((int)(EndStr-$3)) + " when array has size " +
2232 itostr(NumElements) + "");
2233 std::vector<Constant*> Vals;
2234 for (char *C = (char *)$3; C != (char *)EndStr; ++C)
2235 Vals.push_back(ConstantInt::get(ETy, *C));
2237 $$.C = ConstantArray::get(ATy, Vals);
2241 | Types '<' ConstVector '>' { // Nonempty unsized arr
2242 const VectorType *PTy = dyn_cast<VectorType>($1.PAT->get());
2244 error("Cannot make packed constant with type: '" +
2245 $1.PAT->get()->getDescription() + "'");
2246 const Type *ETy = PTy->getElementType();
2247 int NumElements = PTy->getNumElements();
2248 // Verify that we have the correct size...
2249 if (NumElements != -1 && NumElements != (int)$3->size())
2250 error("Type mismatch: constant sized packed initialized with " +
2251 utostr($3->size()) + " arguments, but has size of " +
2252 itostr(NumElements) + "");
2253 // Verify all elements are correct type!
2254 std::vector<Constant*> Elems;
2255 for (unsigned i = 0; i < $3->size(); i++) {
2256 Constant *C = (*$3)[i].C;
2257 const Type* ValTy = C->getType();
2259 error("Element #" + utostr(i) + " is not of type '" +
2260 ETy->getDescription() +"' as required!\nIt is of type '"+
2261 ValTy->getDescription() + "'");
2264 $$.C = ConstantVector::get(PTy, Elems);
2269 | Types '{' ConstVector '}' {
2270 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2272 error("Cannot make struct constant with type: '" +
2273 $1.PAT->get()->getDescription() + "'");
2274 if ($3->size() != STy->getNumContainedTypes())
2275 error("Illegal number of initializers for structure type");
2277 // Check to ensure that constants are compatible with the type initializer!
2278 std::vector<Constant*> Fields;
2279 for (unsigned i = 0, e = $3->size(); i != e; ++i) {
2280 Constant *C = (*$3)[i].C;
2281 if (C->getType() != STy->getElementType(i))
2282 error("Expected type '" + STy->getElementType(i)->getDescription() +
2283 "' for element #" + utostr(i) + " of structure initializer");
2284 Fields.push_back(C);
2286 $$.C = ConstantStruct::get(STy, Fields);
2292 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2294 error("Cannot make struct constant with type: '" +
2295 $1.PAT->get()->getDescription() + "'");
2296 if (STy->getNumContainedTypes() != 0)
2297 error("Illegal number of initializers for structure type");
2298 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2302 | Types '<' '{' ConstVector '}' '>' {
2303 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2305 error("Cannot make packed struct constant with type: '" +
2306 $1.PAT->get()->getDescription() + "'");
2307 if ($4->size() != STy->getNumContainedTypes())
2308 error("Illegal number of initializers for packed structure type");
2310 // Check to ensure that constants are compatible with the type initializer!
2311 std::vector<Constant*> Fields;
2312 for (unsigned i = 0, e = $4->size(); i != e; ++i) {
2313 Constant *C = (*$4)[i].C;
2314 if (C->getType() != STy->getElementType(i))
2315 error("Expected type '" + STy->getElementType(i)->getDescription() +
2316 "' for element #" + utostr(i) + " of packed struct initializer");
2317 Fields.push_back(C);
2319 $$.C = ConstantStruct::get(STy, Fields);
2324 | Types '<' '{' '}' '>' {
2325 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2327 error("Cannot make packed struct constant with type: '" +
2328 $1.PAT->get()->getDescription() + "'");
2329 if (STy->getNumContainedTypes() != 0)
2330 error("Illegal number of initializers for packed structure type");
2331 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2336 const PointerType *PTy = dyn_cast<PointerType>($1.PAT->get());
2338 error("Cannot make null pointer constant with type: '" +
2339 $1.PAT->get()->getDescription() + "'");
2340 $$.C = ConstantPointerNull::get(PTy);
2345 $$.C = UndefValue::get($1.PAT->get());
2349 | Types SymbolicValueRef {
2350 const PointerType *Ty = dyn_cast<PointerType>($1.PAT->get());
2352 error("Global const reference must be a pointer type, not" +
2353 $1.PAT->get()->getDescription());
2355 // ConstExprs can exist in the body of a function, thus creating
2356 // GlobalValues whenever they refer to a variable. Because we are in
2357 // the context of a function, getExistingValue will search the functions
2358 // symbol table instead of the module symbol table for the global symbol,
2359 // which throws things all off. To get around this, we just tell
2360 // getExistingValue that we are at global scope here.
2362 Function *SavedCurFn = CurFun.CurrentFunction;
2363 CurFun.CurrentFunction = 0;
2365 Value *V = getExistingValue(Ty, $2);
2366 CurFun.CurrentFunction = SavedCurFn;
2368 // If this is an initializer for a constant pointer, which is referencing a
2369 // (currently) undefined variable, create a stub now that shall be replaced
2370 // in the future with the right type of variable.
2373 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers");
2374 const PointerType *PT = cast<PointerType>(Ty);
2376 // First check to see if the forward references value is already created!
2377 PerModuleInfo::GlobalRefsType::iterator I =
2378 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
2380 if (I != CurModule.GlobalRefs.end()) {
2381 V = I->second; // Placeholder already exists, use it...
2385 if ($2.Type == ValID::NameVal) Name = $2.Name;
2387 // Create the forward referenced global.
2389 if (const FunctionType *FTy =
2390 dyn_cast<FunctionType>(PT->getElementType())) {
2391 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
2392 CurModule.CurrentModule);
2394 GV = new GlobalVariable(PT->getElementType(), false,
2395 GlobalValue::ExternalLinkage, 0,
2396 Name, CurModule.CurrentModule);
2399 // Keep track of the fact that we have a forward ref to recycle it
2400 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
2404 $$.C = cast<GlobalValue>(V);
2406 delete $1.PAT; // Free the type handle
2409 if ($1.PAT->get() != $2.C->getType())
2410 error("Mismatched types for constant expression");
2415 | Types ZEROINITIALIZER {
2416 const Type *Ty = $1.PAT->get();
2417 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
2418 error("Cannot create a null initialized value of this type");
2419 $$.C = Constant::getNullValue(Ty);
2423 | SIntType EINT64VAL { // integral constants
2424 const Type *Ty = $1.T;
2425 if (!ConstantInt::isValueValidForType(Ty, $2))
2426 error("Constant value doesn't fit in type");
2427 $$.C = ConstantInt::get(Ty, $2);
2430 | UIntType EUINT64VAL { // integral constants
2431 const Type *Ty = $1.T;
2432 if (!ConstantInt::isValueValidForType(Ty, $2))
2433 error("Constant value doesn't fit in type");
2434 $$.C = ConstantInt::get(Ty, $2);
2435 $$.S.makeUnsigned();
2437 | BOOL TRUETOK { // Boolean constants
2438 $$.C = ConstantInt::get(Type::Int1Ty, true);
2439 $$.S.makeUnsigned();
2441 | BOOL FALSETOK { // Boolean constants
2442 $$.C = ConstantInt::get(Type::Int1Ty, false);
2443 $$.S.makeUnsigned();
2445 | FPType FPVAL { // Float & Double constants
2446 if (!ConstantFP::isValueValidForType($1.T, *$2))
2447 error("Floating point constant invalid for type");
2448 // Lexer has no type info, so builds all FP constants as double.
2450 if ($1.T==Type::FloatTy)
2451 $2->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
2452 $$.C = ConstantFP::get($1.T, *$2);
2454 $$.S.makeSignless();
2459 : CastOps '(' ConstVal TO Types ')' {
2460 const Type* SrcTy = $3.C->getType();
2461 const Type* DstTy = $5.PAT->get();
2462 Signedness SrcSign($3.S);
2463 Signedness DstSign($5.S);
2464 if (!SrcTy->isFirstClassType())
2465 error("cast constant expression from a non-primitive type: '" +
2466 SrcTy->getDescription() + "'");
2467 if (!DstTy->isFirstClassType())
2468 error("cast constant expression to a non-primitive type: '" +
2469 DstTy->getDescription() + "'");
2470 $$.C = cast<Constant>(getCast($1, $3.C, SrcSign, DstTy, DstSign));
2474 | GETELEMENTPTR '(' ConstVal IndexList ')' {
2475 const Type *Ty = $3.C->getType();
2476 if (!isa<PointerType>(Ty))
2477 error("GetElementPtr requires a pointer operand");
2479 std::vector<Constant*> CIndices;
2480 upgradeGEPCEIndices($3.C->getType(), $4, CIndices);
2483 $$.C = ConstantExpr::getGetElementPtr($3.C, &CIndices[0], CIndices.size());
2484 $$.S.copy(getElementSign($3, CIndices));
2486 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2487 if (!$3.C->getType()->isInteger() ||
2488 cast<IntegerType>($3.C->getType())->getBitWidth() != 1)
2489 error("Select condition must be bool type");
2490 if ($5.C->getType() != $7.C->getType())
2491 error("Select operand types must match");
2492 $$.C = ConstantExpr::getSelect($3.C, $5.C, $7.C);
2495 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
2496 const Type *Ty = $3.C->getType();
2497 if (Ty != $5.C->getType())
2498 error("Binary operator types must match");
2499 // First, make sure we're dealing with the right opcode by upgrading from
2500 // obsolete versions.
2501 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2503 // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
2504 // To retain backward compatibility with these early compilers, we emit a
2505 // cast to the appropriate integer type automatically if we are in the
2506 // broken case. See PR424 for more information.
2507 if (!isa<PointerType>(Ty)) {
2508 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2510 const Type *IntPtrTy = 0;
2511 switch (CurModule.CurrentModule->getPointerSize()) {
2512 case Module::Pointer32: IntPtrTy = Type::Int32Ty; break;
2513 case Module::Pointer64: IntPtrTy = Type::Int64Ty; break;
2514 default: error("invalid pointer binary constant expr");
2516 $$.C = ConstantExpr::get(Opcode,
2517 ConstantExpr::getCast(Instruction::PtrToInt, $3.C, IntPtrTy),
2518 ConstantExpr::getCast(Instruction::PtrToInt, $5.C, IntPtrTy));
2519 $$.C = ConstantExpr::getCast(Instruction::IntToPtr, $$.C, Ty);
2523 | LogicalOps '(' ConstVal ',' ConstVal ')' {
2524 const Type* Ty = $3.C->getType();
2525 if (Ty != $5.C->getType())
2526 error("Logical operator types must match");
2527 if (!Ty->isInteger()) {
2528 if (!isa<VectorType>(Ty) ||
2529 !cast<VectorType>(Ty)->getElementType()->isInteger())
2530 error("Logical operator requires integer operands");
2532 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2533 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2536 | SetCondOps '(' ConstVal ',' ConstVal ')' {
2537 const Type* Ty = $3.C->getType();
2538 if (Ty != $5.C->getType())
2539 error("setcc operand types must match");
2540 unsigned short pred;
2541 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $3.S);
2542 $$.C = ConstantExpr::getCompare(Opcode, $3.C, $5.C);
2543 $$.S.makeUnsigned();
2545 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
2546 if ($4.C->getType() != $6.C->getType())
2547 error("icmp operand types must match");
2548 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2549 $$.S.makeUnsigned();
2551 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
2552 if ($4.C->getType() != $6.C->getType())
2553 error("fcmp operand types must match");
2554 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2555 $$.S.makeUnsigned();
2557 | ShiftOps '(' ConstVal ',' ConstVal ')' {
2558 if (!$5.C->getType()->isInteger() ||
2559 cast<IntegerType>($5.C->getType())->getBitWidth() != 8)
2560 error("Shift count for shift constant must be unsigned byte");
2561 const Type* Ty = $3.C->getType();
2562 if (!$3.C->getType()->isInteger())
2563 error("Shift constant expression requires integer operand");
2564 Constant *ShiftAmt = ConstantExpr::getZExt($5.C, Ty);
2565 $$.C = ConstantExpr::get(getBinaryOp($1, Ty, $3.S), $3.C, ShiftAmt);
2568 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
2569 if (!ExtractElementInst::isValidOperands($3.C, $5.C))
2570 error("Invalid extractelement operands");
2571 $$.C = ConstantExpr::getExtractElement($3.C, $5.C);
2572 $$.S.copy($3.S.get(0));
2574 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2575 if (!InsertElementInst::isValidOperands($3.C, $5.C, $7.C))
2576 error("Invalid insertelement operands");
2577 $$.C = ConstantExpr::getInsertElement($3.C, $5.C, $7.C);
2580 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2581 if (!ShuffleVectorInst::isValidOperands($3.C, $5.C, $7.C))
2582 error("Invalid shufflevector operands");
2583 $$.C = ConstantExpr::getShuffleVector($3.C, $5.C, $7.C);
2589 // ConstVector - A list of comma separated constants.
2591 : ConstVector ',' ConstVal { ($$ = $1)->push_back($3); }
2593 $$ = new std::vector<ConstInfo>();
2599 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
2601 : GLOBAL { $$ = false; }
2602 | CONSTANT { $$ = true; }
2606 //===----------------------------------------------------------------------===//
2607 // Rules to match Modules
2608 //===----------------------------------------------------------------------===//
2610 // Module rule: Capture the result of parsing the whole file into a result
2615 $$ = ParserResult = $1;
2616 CurModule.ModuleDone();
2620 // FunctionList - A list of functions, preceeded by a constant pool.
2623 : FunctionList Function { $$ = $1; CurFun.FunctionDone(); }
2624 | FunctionList FunctionProto { $$ = $1; }
2625 | FunctionList MODULE ASM_TOK AsmBlock { $$ = $1; }
2626 | FunctionList IMPLEMENTATION { $$ = $1; }
2628 $$ = CurModule.CurrentModule;
2629 // Emit an error if there are any unresolved types left.
2630 if (!CurModule.LateResolveTypes.empty()) {
2631 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
2632 if (DID.Type == ValID::NameVal) {
2633 error("Reference to an undefined type: '"+DID.getName() + "'");
2635 error("Reference to an undefined type: #" + itostr(DID.Num));
2641 // ConstPool - Constants with optional names assigned to them.
2643 : ConstPool OptAssign TYPE TypesV {
2644 // Eagerly resolve types. This is not an optimization, this is a
2645 // requirement that is due to the fact that we could have this:
2647 // %list = type { %list * }
2648 // %list = type { %list * } ; repeated type decl
2650 // If types are not resolved eagerly, then the two types will not be
2651 // determined to be the same type!
2653 ResolveTypeTo($2, $4.PAT->get(), $4.S);
2655 if (!setTypeName($4, $2) && !$2) {
2656 // If this is a numbered type that is not a redefinition, add it to the
2658 CurModule.Types.push_back($4.PAT->get());
2659 CurModule.TypeSigns.push_back($4.S);
2663 | ConstPool FunctionProto { // Function prototypes can be in const pool
2665 | ConstPool MODULE ASM_TOK AsmBlock { // Asm blocks can be in the const pool
2667 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
2669 error("Global value initializer is not a constant");
2670 CurGV = ParseGlobalVariable($2, $3, $4, $5.C->getType(), $5.C, $5.S);
2671 } GlobalVarAttributes {
2674 | ConstPool OptAssign EXTERNAL GlobalType Types {
2675 const Type *Ty = $5.PAT->get();
2676 CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, Ty, 0,
2679 } GlobalVarAttributes {
2682 | ConstPool OptAssign DLLIMPORT GlobalType Types {
2683 const Type *Ty = $5.PAT->get();
2684 CurGV = ParseGlobalVariable($2, GlobalValue::DLLImportLinkage, $4, Ty, 0,
2687 } GlobalVarAttributes {
2690 | ConstPool OptAssign EXTERN_WEAK GlobalType Types {
2691 const Type *Ty = $5.PAT->get();
2693 ParseGlobalVariable($2, GlobalValue::ExternalWeakLinkage, $4, Ty, 0,
2696 } GlobalVarAttributes {
2699 | ConstPool TARGET TargetDefinition {
2701 | ConstPool DEPLIBS '=' LibrariesDefinition {
2703 | /* empty: end of list */ {
2709 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2710 char *EndStr = UnEscapeLexed($1, true);
2711 std::string NewAsm($1, EndStr);
2714 if (AsmSoFar.empty())
2715 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
2717 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
2722 : BIG { $$ = Module::BigEndian; }
2723 | LITTLE { $$ = Module::LittleEndian; }
2727 : ENDIAN '=' BigOrLittle {
2728 CurModule.setEndianness($3);
2730 | POINTERSIZE '=' EUINT64VAL {
2732 CurModule.setPointerSize(Module::Pointer32);
2734 CurModule.setPointerSize(Module::Pointer64);
2736 error("Invalid pointer size: '" + utostr($3) + "'");
2738 | TRIPLE '=' STRINGCONSTANT {
2739 CurModule.CurrentModule->setTargetTriple($3);
2742 | DATALAYOUT '=' STRINGCONSTANT {
2743 CurModule.CurrentModule->setDataLayout($3);
2753 : LibList ',' STRINGCONSTANT {
2754 CurModule.CurrentModule->addLibrary($3);
2758 CurModule.CurrentModule->addLibrary($1);
2761 | /* empty: end of list */ { }
2764 //===----------------------------------------------------------------------===//
2765 // Rules to match Function Headers
2766 //===----------------------------------------------------------------------===//
2769 : VAR_ID | STRINGCONSTANT
2774 | /*empty*/ { $$ = 0; }
2779 if ($1.PAT->get() == Type::VoidTy)
2780 error("void typed arguments are invalid");
2781 $$ = new std::pair<PATypeInfo, char*>($1, $2);
2786 : ArgListH ',' ArgVal {
2792 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2799 : ArgListH { $$ = $1; }
2800 | ArgListH ',' DOTDOTDOT {
2803 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2804 VoidTI.S.makeSignless();
2805 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2808 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2810 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2811 VoidTI.S.makeSignless();
2812 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2814 | /* empty */ { $$ = 0; }
2818 : OptCallingConv TypesV Name '(' ArgList ')' OptSection OptAlign {
2820 std::string FunctionName($3);
2821 free($3); // Free strdup'd memory!
2823 const Type* RetTy = $2.PAT->get();
2825 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
2826 error("LLVM functions cannot return aggregate types");
2829 FTySign.makeComposite($2.S);
2830 std::vector<const Type*> ParamTyList;
2832 // In LLVM 2.0 the signatures of three varargs intrinsics changed to take
2833 // i8*. We check here for those names and override the parameter list
2834 // types to ensure the prototype is correct.
2835 if (FunctionName == "llvm.va_start" || FunctionName == "llvm.va_end") {
2836 ParamTyList.push_back(PointerType::getUnqual(Type::Int8Ty));
2837 } else if (FunctionName == "llvm.va_copy") {
2838 ParamTyList.push_back(PointerType::getUnqual(Type::Int8Ty));
2839 ParamTyList.push_back(PointerType::getUnqual(Type::Int8Ty));
2840 } else if ($5) { // If there are arguments...
2841 for (std::vector<std::pair<PATypeInfo,char*> >::iterator
2842 I = $5->begin(), E = $5->end(); I != E; ++I) {
2843 const Type *Ty = I->first.PAT->get();
2844 ParamTyList.push_back(Ty);
2845 FTySign.add(I->first.S);
2849 bool isVarArg = ParamTyList.size() && ParamTyList.back() == Type::VoidTy;
2851 ParamTyList.pop_back();
2853 const FunctionType *FT = FunctionType::get(RetTy, ParamTyList, isVarArg);
2854 const PointerType *PFT = PointerType::getUnqual(FT);
2858 if (!FunctionName.empty()) {
2859 ID = ValID::create((char*)FunctionName.c_str());
2861 ID = ValID::create((int)CurModule.Values[PFT].size());
2863 ID.S.makeComposite(FTySign);
2866 Module* M = CurModule.CurrentModule;
2868 // See if this function was forward referenced. If so, recycle the object.
2869 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2870 // Move the function to the end of the list, from whereever it was
2871 // previously inserted.
2872 Fn = cast<Function>(FWRef);
2873 M->getFunctionList().remove(Fn);
2874 M->getFunctionList().push_back(Fn);
2875 } else if (!FunctionName.empty()) {
2876 GlobalValue *Conflict = M->getFunction(FunctionName);
2878 Conflict = M->getNamedGlobal(FunctionName);
2879 if (Conflict && PFT == Conflict->getType()) {
2880 if (!CurFun.isDeclare && !Conflict->isDeclaration()) {
2881 // We have two function definitions that conflict, same type, same
2882 // name. We should really check to make sure that this is the result
2883 // of integer type planes collapsing and generate an error if it is
2884 // not, but we'll just rename on the assumption that it is. However,
2885 // let's do it intelligently and rename the internal linkage one
2887 std::string NewName(makeNameUnique(FunctionName));
2888 if (Conflict->hasInternalLinkage()) {
2889 Conflict->setName(NewName);
2891 makeRenameMapKey(FunctionName, Conflict->getType(), ID.S);
2892 CurModule.RenameMap[Key] = NewName;
2893 Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2894 InsertValue(Fn, CurModule.Values);
2896 Fn = new Function(FT, CurFun.Linkage, NewName, M);
2897 InsertValue(Fn, CurModule.Values);
2899 makeRenameMapKey(FunctionName, PFT, ID.S);
2900 CurModule.RenameMap[Key] = NewName;
2903 // If they are not both definitions, then just use the function we
2904 // found since the types are the same.
2905 Fn = cast<Function>(Conflict);
2907 // Make sure to strip off any argument names so we can't get
2909 if (Fn->isDeclaration())
2910 for (Function::arg_iterator AI = Fn->arg_begin(),
2911 AE = Fn->arg_end(); AI != AE; ++AI)
2914 } else if (Conflict) {
2915 // We have two globals with the same name and different types.
2916 // Previously, this was permitted because the symbol table had
2917 // "type planes" and names only needed to be distinct within a
2918 // type plane. After PR411 was fixed, this is no loner the case.
2919 // To resolve this we must rename one of the two.
2920 if (Conflict->hasInternalLinkage()) {
2921 // We can safely rename the Conflict.
2923 makeRenameMapKey(Conflict->getName(), Conflict->getType(),
2924 CurModule.NamedValueSigns[Conflict->getName()]);
2925 Conflict->setName(makeNameUnique(Conflict->getName()));
2926 CurModule.RenameMap[Key] = Conflict->getName();
2927 Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2928 InsertValue(Fn, CurModule.Values);
2930 // We can't quietly rename either of these things, but we must
2931 // rename one of them. Only if the function's linkage is internal can
2932 // we forgo a warning message about the renamed function.
2933 std::string NewName = makeNameUnique(FunctionName);
2934 if (CurFun.Linkage != GlobalValue::InternalLinkage) {
2935 warning("Renaming function '" + FunctionName + "' as '" + NewName +
2936 "' may cause linkage errors");
2938 // Elect to rename the thing we're now defining.
2939 Fn = new Function(FT, CurFun.Linkage, NewName, M);
2940 InsertValue(Fn, CurModule.Values);
2941 RenameMapKey Key = makeRenameMapKey(FunctionName, PFT, ID.S);
2942 CurModule.RenameMap[Key] = NewName;
2945 // There's no conflict, just define the function
2946 Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2947 InsertValue(Fn, CurModule.Values);
2950 // There's no conflict, just define the function
2951 Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2952 InsertValue(Fn, CurModule.Values);
2956 CurFun.FunctionStart(Fn);
2958 if (CurFun.isDeclare) {
2959 // If we have declaration, always overwrite linkage. This will allow us
2960 // to correctly handle cases, when pointer to function is passed as
2961 // argument to another function.
2962 Fn->setLinkage(CurFun.Linkage);
2964 Fn->setCallingConv(upgradeCallingConv($1));
2965 Fn->setAlignment($8);
2971 // Convert the CSRet calling convention into the corresponding parameter
2973 if ($1 == OldCallingConv::CSRet) {
2974 ParamAttrsWithIndex PAWI =
2975 ParamAttrsWithIndex::get(1, ParamAttr::StructRet); // first arg
2976 Fn->setParamAttrs(PAListPtr::get(&PAWI, 1));
2979 // Add all of the arguments we parsed to the function...
2980 if ($5) { // Is null if empty...
2981 if (isVarArg) { // Nuke the last entry
2982 assert($5->back().first.PAT->get() == Type::VoidTy &&
2983 $5->back().second == 0 && "Not a varargs marker");
2984 delete $5->back().first.PAT;
2985 $5->pop_back(); // Delete the last entry
2987 Function::arg_iterator ArgIt = Fn->arg_begin();
2988 Function::arg_iterator ArgEnd = Fn->arg_end();
2989 std::vector<std::pair<PATypeInfo,char*> >::iterator I = $5->begin();
2990 std::vector<std::pair<PATypeInfo,char*> >::iterator E = $5->end();
2991 for ( ; I != E && ArgIt != ArgEnd; ++I, ++ArgIt) {
2992 delete I->first.PAT; // Delete the typeholder...
2993 ValueInfo VI; VI.V = ArgIt; VI.S.copy(I->first.S);
2994 setValueName(VI, I->second); // Insert arg into symtab...
2997 delete $5; // We're now done with the argument list
2999 lastCallingConv = OldCallingConv::C;
3004 : BEGINTOK | '{' // Allow BEGIN or '{' to start a function
3008 : OptLinkage { CurFun.Linkage = $1; } FunctionHeaderH BEGIN {
3009 $$ = CurFun.CurrentFunction;
3011 // Make sure that we keep track of the linkage type even if there was a
3012 // previous "declare".
3018 : ENDTOK | '}' // Allow end of '}' to end a function
3022 : BasicBlockList END {
3027 : /*default*/ { $$ = GlobalValue::ExternalLinkage; }
3028 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
3029 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
3033 : DECLARE { CurFun.isDeclare = true; }
3034 FnDeclareLinkage { CurFun.Linkage = $3; } FunctionHeaderH {
3035 $$ = CurFun.CurrentFunction;
3036 CurFun.FunctionDone();
3041 //===----------------------------------------------------------------------===//
3042 // Rules to match Basic Blocks
3043 //===----------------------------------------------------------------------===//
3046 : /* empty */ { $$ = false; }
3047 | SIDEEFFECT { $$ = true; }
3051 // A reference to a direct constant
3052 : ESINT64VAL { $$ = ValID::create($1); }
3053 | EUINT64VAL { $$ = ValID::create($1); }
3054 | FPVAL { $$ = ValID::create($1); }
3056 $$ = ValID::create(ConstantInt::get(Type::Int1Ty, true));
3057 $$.S.makeUnsigned();
3060 $$ = ValID::create(ConstantInt::get(Type::Int1Ty, false));
3061 $$.S.makeUnsigned();
3063 | NULL_TOK { $$ = ValID::createNull(); }
3064 | UNDEF { $$ = ValID::createUndef(); }
3065 | ZEROINITIALIZER { $$ = ValID::createZeroInit(); }
3066 | '<' ConstVector '>' { // Nonempty unsized packed vector
3067 const Type *ETy = (*$2)[0].C->getType();
3068 int NumElements = $2->size();
3069 VectorType* pt = VectorType::get(ETy, NumElements);
3070 $$.S.makeComposite((*$2)[0].S);
3071 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(pt, $$.S));
3073 // Verify all elements are correct type!
3074 std::vector<Constant*> Elems;
3075 for (unsigned i = 0; i < $2->size(); i++) {
3076 Constant *C = (*$2)[i].C;
3077 const Type *CTy = C->getType();
3079 error("Element #" + utostr(i) + " is not of type '" +
3080 ETy->getDescription() +"' as required!\nIt is of type '" +
3081 CTy->getDescription() + "'");
3084 $$ = ValID::create(ConstantVector::get(pt, Elems));
3085 delete PTy; delete $2;
3088 $$ = ValID::create($1.C);
3091 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
3092 char *End = UnEscapeLexed($3, true);
3093 std::string AsmStr = std::string($3, End);
3094 End = UnEscapeLexed($5, true);
3095 std::string Constraints = std::string($5, End);
3096 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
3102 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
3106 : INTVAL { $$ = ValID::create($1); $$.S.makeSignless(); }
3107 | Name { $$ = ValID::create($1); $$.S.makeSignless(); }
3110 // ValueRef - A reference to a definition... either constant or symbolic
3112 : SymbolicValueRef | ConstValueRef
3116 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
3117 // type immediately preceeds the value reference, and allows complex constant
3118 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
3121 const Type *Ty = $1.PAT->get();
3123 $$.V = getVal(Ty, $2);
3130 : BasicBlockList BasicBlock {
3133 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
3138 // Basic blocks are terminated by branching instructions:
3139 // br, br/cc, switch, ret
3142 : InstructionList OptAssign BBTerminatorInst {
3143 ValueInfo VI; VI.V = $3.TI; VI.S.copy($3.S);
3144 setValueName(VI, $2);
3146 $1->getInstList().push_back($3.TI);
3153 : InstructionList Inst {
3155 $1->getInstList().push_back($2.I);
3159 $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++),true);
3160 // Make sure to move the basic block to the correct location in the
3161 // function, instead of leaving it inserted wherever it was first
3163 Function::BasicBlockListType &BBL =
3164 CurFun.CurrentFunction->getBasicBlockList();
3165 BBL.splice(BBL.end(), BBL, $$);
3168 $$ = CurBB = getBBVal(ValID::create($1), true);
3169 // Make sure to move the basic block to the correct location in the
3170 // function, instead of leaving it inserted wherever it was first
3172 Function::BasicBlockListType &BBL =
3173 CurFun.CurrentFunction->getBasicBlockList();
3174 BBL.splice(BBL.end(), BBL, $$);
3178 Unwind : UNWIND | EXCEPT;
3181 : RET ResolvedVal { // Return with a result...
3182 $$.TI = new ReturnInst($2.V);
3183 $$.S.makeSignless();
3185 | RET VOID { // Return with no result...
3186 $$.TI = new ReturnInst();
3187 $$.S.makeSignless();
3189 | BR LABEL ValueRef { // Unconditional Branch...
3190 BasicBlock* tmpBB = getBBVal($3);
3191 $$.TI = new BranchInst(tmpBB);
3192 $$.S.makeSignless();
3193 } // Conditional Branch...
3194 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
3195 $6.S.makeSignless();
3196 $9.S.makeSignless();
3197 BasicBlock* tmpBBA = getBBVal($6);
3198 BasicBlock* tmpBBB = getBBVal($9);
3199 $3.S.makeUnsigned();
3200 Value* tmpVal = getVal(Type::Int1Ty, $3);
3201 $$.TI = new BranchInst(tmpBBA, tmpBBB, tmpVal);
3202 $$.S.makeSignless();
3204 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
3206 Value* tmpVal = getVal($2.T, $3);
3207 $6.S.makeSignless();
3208 BasicBlock* tmpBB = getBBVal($6);
3209 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
3211 $$.S.makeSignless();
3212 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
3214 for (; I != E; ++I) {
3215 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
3216 S->addCase(CI, I->second);
3218 error("Switch case is constant, but not a simple integer");
3222 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
3224 Value* tmpVal = getVal($2.T, $3);
3225 $6.S.makeSignless();
3226 BasicBlock* tmpBB = getBBVal($6);
3227 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
3229 $$.S.makeSignless();
3231 | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
3232 TO LABEL ValueRef Unwind LABEL ValueRef {
3233 const PointerType *PFTy;
3234 const FunctionType *Ty;
3237 if (!(PFTy = dyn_cast<PointerType>($3.PAT->get())) ||
3238 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3239 // Pull out the types of all of the arguments...
3240 std::vector<const Type*> ParamTypes;
3241 FTySign.makeComposite($3.S);
3243 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
3245 ParamTypes.push_back((*I).V->getType());
3249 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
3250 if (isVarArg) ParamTypes.pop_back();
3251 Ty = FunctionType::get($3.PAT->get(), ParamTypes, isVarArg);
3252 PFTy = PointerType::getUnqual(Ty);
3256 // Get the signedness of the result type. $3 is the pointer to the
3257 // function type so we get the 0th element to extract the function type,
3258 // and then the 0th element again to get the result type.
3259 $$.S.copy($3.S.get(0).get(0));
3262 $4.S.makeComposite(FTySign);
3263 Value *V = getVal(PFTy, $4); // Get the function we're calling...
3264 BasicBlock *Normal = getBBVal($10);
3265 BasicBlock *Except = getBBVal($13);
3267 // Create the call node...
3268 if (!$6) { // Has no arguments?
3269 std::vector<Value*> Args;
3270 $$.TI = new InvokeInst(V, Normal, Except, Args.begin(), Args.end());
3271 } else { // Has arguments?
3272 // Loop through FunctionType's arguments and ensure they are specified
3275 FunctionType::param_iterator I = Ty->param_begin();
3276 FunctionType::param_iterator E = Ty->param_end();
3277 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
3279 std::vector<Value*> Args;
3280 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
3281 if ((*ArgI).V->getType() != *I)
3282 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
3283 (*I)->getDescription() + "'");
3284 Args.push_back((*ArgI).V);
3287 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
3288 error("Invalid number of parameters detected");
3290 $$.TI = new InvokeInst(V, Normal, Except, Args.begin(), Args.end());
3292 cast<InvokeInst>($$.TI)->setCallingConv(upgradeCallingConv($2));
3293 if ($2 == OldCallingConv::CSRet) {
3294 ParamAttrsWithIndex PAWI =
3295 ParamAttrsWithIndex::get(1, ParamAttr::StructRet); // first arg
3296 cast<InvokeInst>($$.TI)->setParamAttrs(PAListPtr::get(&PAWI, 1));
3300 lastCallingConv = OldCallingConv::C;
3303 $$.TI = new UnwindInst();
3304 $$.S.makeSignless();
3307 $$.TI = new UnreachableInst();
3308 $$.S.makeSignless();
3313 : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
3316 Constant *V = cast<Constant>(getExistingValue($2.T, $3));
3319 error("May only switch on a constant pool value");
3321 $6.S.makeSignless();
3322 BasicBlock* tmpBB = getBBVal($6);
3323 $$->push_back(std::make_pair(V, tmpBB));
3325 | IntType ConstValueRef ',' LABEL ValueRef {
3326 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
3328 Constant *V = cast<Constant>(getExistingValue($1.T, $2));
3331 error("May only switch on a constant pool value");
3333 $5.S.makeSignless();
3334 BasicBlock* tmpBB = getBBVal($5);
3335 $$->push_back(std::make_pair(V, tmpBB));
3340 : OptAssign InstVal {
3343 if (BitCastInst *BCI = dyn_cast<BitCastInst>($2.I))
3344 if (BCI->getSrcTy() == BCI->getDestTy() &&
3345 BCI->getOperand(0)->getName() == $1)
3346 // This is a useless bit cast causing a name redefinition. It is
3347 // a bit cast from a type to the same type of an operand with the
3348 // same name as the name we would give this instruction. Since this
3349 // instruction results in no code generation, it is safe to omit
3350 // the instruction. This situation can occur because of collapsed
3351 // type planes. For example:
3352 // %X = add int %Y, %Z
3353 // %X = cast int %Y to uint
3354 // After upgrade, this looks like:
3355 // %X = add i32 %Y, %Z
3356 // %X = bitcast i32 to i32
3357 // The bitcast is clearly useless so we omit it.
3361 $$.S.makeSignless();
3363 ValueInfo VI; VI.V = $2.I; VI.S.copy($2.S);
3364 setValueName(VI, $1);
3370 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
3371 $$.P = new std::list<std::pair<Value*, BasicBlock*> >();
3374 Value* tmpVal = getVal($1.PAT->get(), $3);
3375 $5.S.makeSignless();
3376 BasicBlock* tmpBB = getBBVal($5);
3377 $$.P->push_back(std::make_pair(tmpVal, tmpBB));
3380 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
3383 Value* tmpVal = getVal($1.P->front().first->getType(), $4);
3384 $6.S.makeSignless();
3385 BasicBlock* tmpBB = getBBVal($6);
3386 $1.P->push_back(std::make_pair(tmpVal, tmpBB));
3390 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
3391 $$ = new std::vector<ValueInfo>();
3394 | ValueRefList ',' ResolvedVal {
3399 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
3402 | /*empty*/ { $$ = 0; }
3415 : ArithmeticOps Types ValueRef ',' ValueRef {
3418 const Type* Ty = $2.PAT->get();
3419 if (!Ty->isInteger() && !Ty->isFloatingPoint() && !isa<VectorType>(Ty))
3420 error("Arithmetic operator requires integer, FP, or packed operands");
3421 if (isa<VectorType>(Ty) &&
3422 ($1 == URemOp || $1 == SRemOp || $1 == FRemOp || $1 == RemOp))
3423 error("Remainder not supported on vector types");
3424 // Upgrade the opcode from obsolete versions before we do anything with it.
3425 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3426 Value* val1 = getVal(Ty, $3);
3427 Value* val2 = getVal(Ty, $5);
3428 $$.I = BinaryOperator::create(Opcode, val1, val2);
3430 error("binary operator returned null");
3434 | LogicalOps Types ValueRef ',' ValueRef {
3437 const Type *Ty = $2.PAT->get();
3438 if (!Ty->isInteger()) {
3439 if (!isa<VectorType>(Ty) ||
3440 !cast<VectorType>(Ty)->getElementType()->isInteger())
3441 error("Logical operator requires integral operands");
3443 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3444 Value* tmpVal1 = getVal(Ty, $3);
3445 Value* tmpVal2 = getVal(Ty, $5);
3446 $$.I = BinaryOperator::create(Opcode, tmpVal1, tmpVal2);
3448 error("binary operator returned null");
3452 | SetCondOps Types ValueRef ',' ValueRef {
3455 const Type* Ty = $2.PAT->get();
3456 if(isa<VectorType>(Ty))
3457 error("VectorTypes currently not supported in setcc instructions");
3458 unsigned short pred;
3459 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $2.S);
3460 Value* tmpVal1 = getVal(Ty, $3);
3461 Value* tmpVal2 = getVal(Ty, $5);
3462 $$.I = CmpInst::create(Opcode, pred, tmpVal1, tmpVal2);
3464 error("binary operator returned null");
3465 $$.S.makeUnsigned();
3468 | ICMP IPredicates Types ValueRef ',' ValueRef {
3471 const Type *Ty = $3.PAT->get();
3472 if (isa<VectorType>(Ty))
3473 error("VectorTypes currently not supported in icmp instructions");
3474 else if (!Ty->isInteger() && !isa<PointerType>(Ty))
3475 error("icmp requires integer or pointer typed operands");
3476 Value* tmpVal1 = getVal(Ty, $4);
3477 Value* tmpVal2 = getVal(Ty, $6);
3478 $$.I = new ICmpInst($2, tmpVal1, tmpVal2);
3479 $$.S.makeUnsigned();
3482 | FCMP FPredicates Types ValueRef ',' ValueRef {
3485 const Type *Ty = $3.PAT->get();
3486 if (isa<VectorType>(Ty))
3487 error("VectorTypes currently not supported in fcmp instructions");
3488 else if (!Ty->isFloatingPoint())
3489 error("fcmp instruction requires floating point operands");
3490 Value* tmpVal1 = getVal(Ty, $4);
3491 Value* tmpVal2 = getVal(Ty, $6);
3492 $$.I = new FCmpInst($2, tmpVal1, tmpVal2);
3493 $$.S.makeUnsigned();
3497 warning("Use of obsolete 'not' instruction: Replacing with 'xor");
3498 const Type *Ty = $2.V->getType();
3499 Value *Ones = ConstantInt::getAllOnesValue(Ty);
3501 error("Expected integral type for not instruction");
3502 $$.I = BinaryOperator::create(Instruction::Xor, $2.V, Ones);
3504 error("Could not create a xor instruction");
3507 | ShiftOps ResolvedVal ',' ResolvedVal {
3508 if (!$4.V->getType()->isInteger() ||
3509 cast<IntegerType>($4.V->getType())->getBitWidth() != 8)
3510 error("Shift amount must be int8");
3511 const Type* Ty = $2.V->getType();
3512 if (!Ty->isInteger())
3513 error("Shift constant expression requires integer operand");
3514 Value* ShiftAmt = 0;
3515 if (cast<IntegerType>(Ty)->getBitWidth() > Type::Int8Ty->getBitWidth())
3516 if (Constant *C = dyn_cast<Constant>($4.V))
3517 ShiftAmt = ConstantExpr::getZExt(C, Ty);
3519 ShiftAmt = new ZExtInst($4.V, Ty, makeNameUnique("shift"), CurBB);
3522 $$.I = BinaryOperator::create(getBinaryOp($1, Ty, $2.S), $2.V, ShiftAmt);
3525 | CastOps ResolvedVal TO Types {
3526 const Type *DstTy = $4.PAT->get();
3527 if (!DstTy->isFirstClassType())
3528 error("cast instruction to a non-primitive type: '" +
3529 DstTy->getDescription() + "'");
3530 $$.I = cast<Instruction>(getCast($1, $2.V, $2.S, DstTy, $4.S, true));
3534 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3535 if (!$2.V->getType()->isInteger() ||
3536 cast<IntegerType>($2.V->getType())->getBitWidth() != 1)
3537 error("select condition must be bool");
3538 if ($4.V->getType() != $6.V->getType())
3539 error("select value types should match");
3540 $$.I = new SelectInst($2.V, $4.V, $6.V);
3543 | VAARG ResolvedVal ',' Types {
3544 const Type *Ty = $4.PAT->get();
3546 $$.I = new VAArgInst($2.V, Ty);
3550 | VAARG_old ResolvedVal ',' Types {
3551 const Type* ArgTy = $2.V->getType();
3552 const Type* DstTy = $4.PAT->get();
3553 ObsoleteVarArgs = true;
3554 Function* NF = cast<Function>(CurModule.CurrentModule->
3555 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3558 //foo = alloca 1 of t
3562 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
3563 CurBB->getInstList().push_back(foo);
3564 CallInst* bar = new CallInst(NF, $2.V);
3565 CurBB->getInstList().push_back(bar);
3566 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3567 $$.I = new VAArgInst(foo, DstTy);
3571 | VANEXT_old ResolvedVal ',' Types {
3572 const Type* ArgTy = $2.V->getType();
3573 const Type* DstTy = $4.PAT->get();
3574 ObsoleteVarArgs = true;
3575 Function* NF = cast<Function>(CurModule.CurrentModule->
3576 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3578 //b = vanext a, t ->
3579 //foo = alloca 1 of t
3582 //tmp = vaarg foo, t
3584 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
3585 CurBB->getInstList().push_back(foo);
3586 CallInst* bar = new CallInst(NF, $2.V);
3587 CurBB->getInstList().push_back(bar);
3588 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3589 Instruction* tmp = new VAArgInst(foo, DstTy);
3590 CurBB->getInstList().push_back(tmp);
3591 $$.I = new LoadInst(foo);
3595 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
3596 if (!ExtractElementInst::isValidOperands($2.V, $4.V))
3597 error("Invalid extractelement operands");
3598 $$.I = new ExtractElementInst($2.V, $4.V);
3599 $$.S.copy($2.S.get(0));
3601 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3602 if (!InsertElementInst::isValidOperands($2.V, $4.V, $6.V))
3603 error("Invalid insertelement operands");
3604 $$.I = new InsertElementInst($2.V, $4.V, $6.V);
3607 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3608 if (!ShuffleVectorInst::isValidOperands($2.V, $4.V, $6.V))
3609 error("Invalid shufflevector operands");
3610 $$.I = new ShuffleVectorInst($2.V, $4.V, $6.V);
3614 const Type *Ty = $2.P->front().first->getType();
3615 if (!Ty->isFirstClassType())
3616 error("PHI node operands must be of first class type");
3617 PHINode *PHI = new PHINode(Ty);
3618 PHI->reserveOperandSpace($2.P->size());
3619 while ($2.P->begin() != $2.P->end()) {
3620 if ($2.P->front().first->getType() != Ty)
3621 error("All elements of a PHI node must be of the same type");
3622 PHI->addIncoming($2.P->front().first, $2.P->front().second);
3627 delete $2.P; // Free the list...
3629 | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')' {
3630 // Handle the short call syntax
3631 const PointerType *PFTy;
3632 const FunctionType *FTy;
3634 if (!(PFTy = dyn_cast<PointerType>($3.PAT->get())) ||
3635 !(FTy = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3636 // Pull out the types of all of the arguments...
3637 std::vector<const Type*> ParamTypes;
3638 FTySign.makeComposite($3.S);
3640 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
3642 ParamTypes.push_back((*I).V->getType());
3647 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
3648 if (isVarArg) ParamTypes.pop_back();
3650 const Type *RetTy = $3.PAT->get();
3651 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
3652 error("Functions cannot return aggregate types");
3654 FTy = FunctionType::get(RetTy, ParamTypes, isVarArg);
3655 PFTy = PointerType::getUnqual(FTy);
3659 // Get the signedness of the result type. $3 is the pointer to the
3660 // function type so we get the 0th element to extract the function type,
3661 // and then the 0th element again to get the result type.
3662 $$.S.copy($3.S.get(0).get(0));
3664 $4.S.makeComposite(FTySign);
3666 // First upgrade any intrinsic calls.
3667 std::vector<Value*> Args;
3669 for (unsigned i = 0, e = $6->size(); i < e; ++i)
3670 Args.push_back((*$6)[i].V);
3671 Instruction *Inst = upgradeIntrinsicCall(FTy->getReturnType(), $4, Args);
3673 // If we got an upgraded intrinsic
3677 // Get the function we're calling
3678 Value *V = getVal(PFTy, $4);
3680 // Check the argument values match
3681 if (!$6) { // Has no arguments?
3682 // Make sure no arguments is a good thing!
3683 if (FTy->getNumParams() != 0)
3684 error("No arguments passed to a function that expects arguments");
3685 } else { // Has arguments?
3686 // Loop through FunctionType's arguments and ensure they are specified
3689 FunctionType::param_iterator I = FTy->param_begin();
3690 FunctionType::param_iterator E = FTy->param_end();
3691 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
3693 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
3694 if ((*ArgI).V->getType() != *I)
3695 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
3696 (*I)->getDescription() + "'");
3698 if (I != E || (ArgI != ArgE && !FTy->isVarArg()))
3699 error("Invalid number of parameters detected");
3702 // Create the call instruction
3703 CallInst *CI = new CallInst(V, Args.begin(), Args.end());
3704 CI->setTailCall($1);
3705 CI->setCallingConv(upgradeCallingConv($2));
3709 // Deal with CSRetCC
3710 if ($2 == OldCallingConv::CSRet) {
3711 ParamAttrsWithIndex PAWI =
3712 ParamAttrsWithIndex::get(1, ParamAttr::StructRet); // first arg
3713 cast<CallInst>($$.I)->setParamAttrs(PAListPtr::get(&PAWI, 1));
3717 lastCallingConv = OldCallingConv::C;
3725 // IndexList - List of indices for GEP based instructions...
3727 : ',' ValueRefList { $$ = $2; }
3728 | /* empty */ { $$ = new std::vector<ValueInfo>(); }
3732 : VOLATILE { $$ = true; }
3733 | /* empty */ { $$ = false; }
3737 : MALLOC Types OptCAlign {
3738 const Type *Ty = $2.PAT->get();
3739 $$.S.makeComposite($2.S);
3740 $$.I = new MallocInst(Ty, 0, $3);
3743 | MALLOC Types ',' UINT ValueRef OptCAlign {
3744 const Type *Ty = $2.PAT->get();
3745 $5.S.makeUnsigned();
3746 $$.S.makeComposite($2.S);
3747 $$.I = new MallocInst(Ty, getVal($4.T, $5), $6);
3750 | ALLOCA Types OptCAlign {
3751 const Type *Ty = $2.PAT->get();
3752 $$.S.makeComposite($2.S);
3753 $$.I = new AllocaInst(Ty, 0, $3);
3756 | ALLOCA Types ',' UINT ValueRef OptCAlign {
3757 const Type *Ty = $2.PAT->get();
3758 $5.S.makeUnsigned();
3759 $$.S.makeComposite($4.S);
3760 $$.I = new AllocaInst(Ty, getVal($4.T, $5), $6);
3763 | FREE ResolvedVal {
3764 const Type *PTy = $2.V->getType();
3765 if (!isa<PointerType>(PTy))
3766 error("Trying to free nonpointer type '" + PTy->getDescription() + "'");
3767 $$.I = new FreeInst($2.V);
3768 $$.S.makeSignless();
3770 | OptVolatile LOAD Types ValueRef {
3771 const Type* Ty = $3.PAT->get();
3773 if (!isa<PointerType>(Ty))
3774 error("Can't load from nonpointer type: " + Ty->getDescription());
3775 if (!cast<PointerType>(Ty)->getElementType()->isFirstClassType())
3776 error("Can't load from pointer of non-first-class type: " +
3777 Ty->getDescription());
3778 Value* tmpVal = getVal(Ty, $4);
3779 $$.I = new LoadInst(tmpVal, "", $1);
3780 $$.S.copy($3.S.get(0));
3783 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
3785 const PointerType *PTy = dyn_cast<PointerType>($5.PAT->get());
3787 error("Can't store to a nonpointer type: " +
3788 $5.PAT->get()->getDescription());
3789 const Type *ElTy = PTy->getElementType();
3790 Value *StoreVal = $3.V;
3791 Value* tmpVal = getVal(PTy, $6);
3792 if (ElTy != $3.V->getType()) {
3793 PTy = PointerType::getUnqual(StoreVal->getType());
3794 if (Constant *C = dyn_cast<Constant>(tmpVal))
3795 tmpVal = ConstantExpr::getBitCast(C, PTy);
3797 tmpVal = new BitCastInst(tmpVal, PTy, "upgrd.cast", CurBB);
3799 $$.I = new StoreInst(StoreVal, tmpVal, $1);
3800 $$.S.makeSignless();
3803 | GETELEMENTPTR Types ValueRef IndexList {
3805 const Type* Ty = $2.PAT->get();
3806 if (!isa<PointerType>(Ty))
3807 error("getelementptr insn requires pointer operand");
3809 std::vector<Value*> VIndices;
3810 upgradeGEPInstIndices(Ty, $4, VIndices);
3812 Value* tmpVal = getVal(Ty, $3);
3813 $$.I = new GetElementPtrInst(tmpVal, VIndices.begin(), VIndices.end());
3814 ValueInfo VI; VI.V = tmpVal; VI.S.copy($2.S);
3815 $$.S.copy(getElementSign(VI, VIndices));
3823 int yyerror(const char *ErrorMsg) {
3825 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3826 + ":" + llvm::utostr((unsigned) Upgradelineno) + ": ";
3827 std::string errMsg = where + "error: " + std::string(ErrorMsg);
3828 if (yychar != YYEMPTY && yychar != 0)
3829 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3831 std::cerr << "llvm-upgrade: " << errMsg << '\n';
3832 std::cout << "llvm-upgrade: parse failed.\n";
3836 void warning(const std::string& ErrorMsg) {
3838 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3839 + ":" + llvm::utostr((unsigned) Upgradelineno) + ": ";
3840 std::string errMsg = where + "warning: " + std::string(ErrorMsg);
3841 if (yychar != YYEMPTY && yychar != 0)
3842 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3844 std::cerr << "llvm-upgrade: " << errMsg << '\n';
3847 void error(const std::string& ErrorMsg, int LineNo) {
3848 if (LineNo == -1) LineNo = Upgradelineno;
3849 Upgradelineno = LineNo;
3850 yyerror(ErrorMsg.c_str());