1 //===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the bison parser for LLVM assembly languages files.
12 //===----------------------------------------------------------------------===//
15 #include "UpgradeInternals.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/InlineAsm.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/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;
65 // This contains info used when building the body of a function. It is
66 // destroyed when the function is completed.
68 typedef std::vector<Value *> ValueList; // Numbered defs
70 typedef std::pair<std::string,const Type*> RenameMapKey;
71 typedef std::map<RenameMapKey,std::string> RenameMapType;
74 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
75 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
77 static struct PerModuleInfo {
78 Module *CurrentModule;
79 std::map<const Type *, ValueList> Values; // Module level numbered definitions
80 std::map<const Type *,ValueList> LateResolveValues;
81 std::vector<PATypeHolder> Types;
82 std::map<ValID, PATypeHolder> LateResolveTypes;
83 static Module::Endianness Endian;
84 static Module::PointerSize PointerSize;
85 RenameMapType RenameMap;
87 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
88 /// how they were referenced and on which line of the input they came from so
89 /// that we can resolve them later and print error messages as appropriate.
90 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
92 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
93 // references to global values. Global values may be referenced before they
94 // are defined, and if so, the temporary object that they represent is held
95 // here. This is used for forward references of GlobalValues.
97 typedef std::map<std::pair<const PointerType *, ValID>, GlobalValue*>
99 GlobalRefsType GlobalRefs;
102 // If we could not resolve some functions at function compilation time
103 // (calls to functions before they are defined), resolve them now... Types
104 // are resolved when the constant pool has been completely parsed.
106 ResolveDefinitions(LateResolveValues);
108 // Check to make sure that all global value forward references have been
111 if (!GlobalRefs.empty()) {
112 std::string UndefinedReferences = "Unresolved global references exist:\n";
114 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
116 UndefinedReferences += " " + I->first.first->getDescription() + " " +
117 I->first.second.getName() + "\n";
119 error(UndefinedReferences);
123 if (CurrentModule->getDataLayout().empty()) {
124 std::string dataLayout;
125 if (Endian != Module::AnyEndianness)
126 dataLayout.append(Endian == Module::BigEndian ? "E" : "e");
127 if (PointerSize != Module::AnyPointerSize) {
128 if (!dataLayout.empty())
130 dataLayout.append(PointerSize == Module::Pointer64 ?
131 "p:64:64" : "p:32:32");
133 CurrentModule->setDataLayout(dataLayout);
136 Values.clear(); // Clear out function local definitions
141 // GetForwardRefForGlobal - Check to see if there is a forward reference
142 // for this global. If so, remove it from the GlobalRefs map and return it.
143 // If not, just return null.
144 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
145 // Check to see if there is a forward reference to this global variable...
146 // if there is, eliminate it and patch the reference to use the new def'n.
147 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
148 GlobalValue *Ret = 0;
149 if (I != GlobalRefs.end()) {
155 void setEndianness(Module::Endianness E) { Endian = E; }
156 void setPointerSize(Module::PointerSize sz) { PointerSize = sz; }
159 Module::Endianness PerModuleInfo::Endian = Module::AnyEndianness;
160 Module::PointerSize PerModuleInfo::PointerSize = Module::AnyPointerSize;
162 static struct PerFunctionInfo {
163 Function *CurrentFunction; // Pointer to current function being created
165 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
166 std::map<const Type*, ValueList> LateResolveValues;
167 bool isDeclare; // Is this function a forward declararation?
168 GlobalValue::LinkageTypes Linkage;// Linkage for forward declaration.
170 /// BBForwardRefs - When we see forward references to basic blocks, keep
171 /// track of them here.
172 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
173 std::vector<BasicBlock*> NumberedBlocks;
174 RenameMapType RenameMap;
177 inline PerFunctionInfo() {
180 Linkage = GlobalValue::ExternalLinkage;
183 inline void FunctionStart(Function *M) {
188 void FunctionDone() {
189 NumberedBlocks.clear();
191 // Any forward referenced blocks left?
192 if (!BBForwardRefs.empty()) {
193 error("Undefined reference to label " +
194 BBForwardRefs.begin()->first->getName());
198 // Resolve all forward references now.
199 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
201 Values.clear(); // Clear out function local definitions
205 Linkage = GlobalValue::ExternalLinkage;
207 } CurFun; // Info for the current function...
209 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
212 //===----------------------------------------------------------------------===//
213 // Code to handle definitions of all the types
214 //===----------------------------------------------------------------------===//
216 static int InsertValue(Value *V,
217 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
218 if (V->hasName()) return -1; // Is this a numbered definition?
220 // Yes, insert the value into the value table...
221 ValueList &List = ValueTab[V->getType()];
223 return List.size()-1;
226 static const Type *getType(const ValID &D, bool DoNotImprovise = false) {
228 case ValID::NumberVal: // Is it a numbered definition?
229 // Module constants occupy the lowest numbered slots...
230 if ((unsigned)D.Num < CurModule.Types.size()) {
231 return CurModule.Types[(unsigned)D.Num];
234 case ValID::NameVal: // Is it a named definition?
235 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
236 D.destroy(); // Free old strdup'd memory...
241 error("Internal parser error: Invalid symbol type reference");
245 // If we reached here, we referenced either a symbol that we don't know about
246 // or an id number that hasn't been read yet. We may be referencing something
247 // forward, so just create an entry to be resolved later and get to it...
249 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
252 if (inFunctionScope()) {
253 if (D.Type == ValID::NameVal) {
254 error("Reference to an undefined type: '" + D.getName() + "'");
257 error("Reference to an undefined type: #" + itostr(D.Num));
262 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
263 if (I != CurModule.LateResolveTypes.end())
266 Type *Typ = OpaqueType::get();
267 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
271 /// This function determines if two function types differ only in their use of
272 /// the sret parameter attribute in the first argument. If they are identical
273 /// in all other respects, it returns true. Otherwise, it returns false.
274 bool FuncTysDifferOnlyBySRet(const FunctionType *F1,
275 const FunctionType *F2) {
276 if (F1->getReturnType() != F2->getReturnType() ||
277 F1->getNumParams() != F2->getNumParams() ||
278 F1->getParamAttrs(0) != F2->getParamAttrs(0))
280 unsigned SRetMask = ~unsigned(FunctionType::StructRetAttribute);
281 for (unsigned i = 0; i < F1->getNumParams(); ++i) {
282 if (F1->getParamType(i) != F2->getParamType(i) ||
283 unsigned(F1->getParamAttrs(i+1)) & SRetMask !=
284 unsigned(F2->getParamAttrs(i+1)) & SRetMask)
290 // The upgrade of csretcc to sret param attribute may have caused a function
291 // to not be found because the param attribute changed the type of the called
292 // function. This helper function, used in getExistingValue, detects that
293 // situation and returns V if it occurs and 0 otherwise.
294 static Value* handleSRetFuncTypeMerge(Value *V, const Type* Ty) {
295 // Handle degenerate cases
298 if (V->getType() == Ty)
302 const PointerType *PF1 = dyn_cast<PointerType>(Ty);
303 const PointerType *PF2 = dyn_cast<PointerType>(V->getType());
305 const FunctionType *FT1 =
306 dyn_cast<FunctionType>(PF1->getElementType());
307 const FunctionType *FT2 =
308 dyn_cast<FunctionType>(PF2->getElementType());
309 if (FT1 && FT2 && FuncTysDifferOnlyBySRet(FT1, FT2))
310 if (FT2->paramHasAttr(1, FunctionType::StructRetAttribute))
312 else if (Constant *C = dyn_cast<Constant>(V))
313 Result = ConstantExpr::getBitCast(C, PF1);
315 Result = new BitCastInst(V, PF1, "upgrd.cast", CurBB);
320 // getExistingValue - Look up the value specified by the provided type and
321 // the provided ValID. If the value exists and has already been defined, return
322 // it. Otherwise return null.
324 static Value *getExistingValue(const Type *Ty, const ValID &D) {
325 if (isa<FunctionType>(Ty)) {
326 error("Functions are not values and must be referenced as pointers");
330 case ValID::NumberVal: { // Is it a numbered definition?
331 unsigned Num = (unsigned)D.Num;
333 // Module constants occupy the lowest numbered slots...
334 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
335 if (VI != CurModule.Values.end()) {
336 if (Num < VI->second.size())
337 return VI->second[Num];
338 Num -= VI->second.size();
341 // Make sure that our type is within bounds
342 VI = CurFun.Values.find(Ty);
343 if (VI == CurFun.Values.end()) return 0;
345 // Check that the number is within bounds...
346 if (VI->second.size() <= Num) return 0;
348 return VI->second[Num];
351 case ValID::NameVal: { // Is it a named definition?
352 // Get the name out of the ID
353 std::string Name(D.Name);
355 RenameMapKey Key = std::make_pair(Name, Ty);
356 if (inFunctionScope()) {
357 // See if the name was renamed
358 RenameMapType::const_iterator I = CurFun.RenameMap.find(Key);
359 std::string LookupName;
360 if (I != CurFun.RenameMap.end())
361 LookupName = I->second;
364 ValueSymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
365 V = SymTab.lookup(LookupName);
366 V = handleSRetFuncTypeMerge(V, Ty);
369 RenameMapType::const_iterator I = CurModule.RenameMap.find(Key);
370 std::string LookupName;
371 if (I != CurModule.RenameMap.end())
372 LookupName = I->second;
375 V = CurModule.CurrentModule->getValueSymbolTable().lookup(LookupName);
376 V = handleSRetFuncTypeMerge(V, Ty);
381 D.destroy(); // Free old strdup'd memory...
385 // Check to make sure that "Ty" is an integral type, and that our
386 // value will fit into the specified type...
387 case ValID::ConstSIntVal: // Is it a constant pool reference??
388 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
389 error("Signed integral constant '" + itostr(D.ConstPool64) +
390 "' is invalid for type '" + Ty->getDescription() + "'");
392 return ConstantInt::get(Ty, D.ConstPool64);
394 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
395 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
396 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64))
397 error("Integral constant '" + utostr(D.UConstPool64) +
398 "' is invalid or out of range");
399 else // This is really a signed reference. Transmogrify.
400 return ConstantInt::get(Ty, D.ConstPool64);
402 return ConstantInt::get(Ty, D.UConstPool64);
404 case ValID::ConstFPVal: // Is it a floating point const pool reference?
405 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
406 error("FP constant invalid for type");
407 return ConstantFP::get(Ty, D.ConstPoolFP);
409 case ValID::ConstNullVal: // Is it a null value?
410 if (!isa<PointerType>(Ty))
411 error("Cannot create a a non pointer null");
412 return ConstantPointerNull::get(cast<PointerType>(Ty));
414 case ValID::ConstUndefVal: // Is it an undef value?
415 return UndefValue::get(Ty);
417 case ValID::ConstZeroVal: // Is it a zero value?
418 return Constant::getNullValue(Ty);
420 case ValID::ConstantVal: // Fully resolved constant?
421 if (D.ConstantValue->getType() != Ty)
422 error("Constant expression type different from required type");
423 return D.ConstantValue;
425 case ValID::InlineAsmVal: { // Inline asm expression
426 const PointerType *PTy = dyn_cast<PointerType>(Ty);
427 const FunctionType *FTy =
428 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
429 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints))
430 error("Invalid type for asm constraint string");
431 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
432 D.IAD->HasSideEffects);
433 D.destroy(); // Free InlineAsmDescriptor.
437 assert(0 && "Unhandled case");
441 assert(0 && "Unhandled case");
445 // getVal - This function is identical to getExistingValue, except that if a
446 // value is not already defined, it "improvises" by creating a placeholder var
447 // that looks and acts just like the requested variable. When the value is
448 // defined later, all uses of the placeholder variable are replaced with the
451 static Value *getVal(const Type *Ty, const ValID &ID) {
452 if (Ty == Type::LabelTy)
453 error("Cannot use a basic block here");
455 // See if the value has already been defined.
456 Value *V = getExistingValue(Ty, ID);
459 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty))
460 error("Invalid use of a composite type");
462 // If we reached here, we referenced either a symbol that we don't know about
463 // or an id number that hasn't been read yet. We may be referencing something
464 // forward, so just create an entry to be resolved later and get to it...
465 V = new Argument(Ty);
467 // Remember where this forward reference came from. FIXME, shouldn't we try
468 // to recycle these things??
469 CurModule.PlaceHolderInfo.insert(
470 std::make_pair(V, std::make_pair(ID, Upgradelineno)));
472 if (inFunctionScope())
473 InsertValue(V, CurFun.LateResolveValues);
475 InsertValue(V, CurModule.LateResolveValues);
479 /// @brief This just makes any name given to it unique, up to MAX_UINT times.
480 static std::string makeNameUnique(const std::string& Name) {
481 static unsigned UniqueNameCounter = 1;
482 std::string Result(Name);
483 Result += ".upgrd." + llvm::utostr(UniqueNameCounter++);
487 /// getBBVal - This is used for two purposes:
488 /// * If isDefinition is true, a new basic block with the specified ID is being
490 /// * If isDefinition is true, this is a reference to a basic block, which may
491 /// or may not be a forward reference.
493 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
494 assert(inFunctionScope() && "Can't get basic block at global scope");
500 error("Illegal label reference " + ID.getName());
502 case ValID::NumberVal: // Is it a numbered definition?
503 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
504 CurFun.NumberedBlocks.resize(ID.Num+1);
505 BB = CurFun.NumberedBlocks[ID.Num];
507 case ValID::NameVal: // Is it a named definition?
509 if (Value *N = CurFun.CurrentFunction->
510 getValueSymbolTable().lookup(Name)) {
511 if (N->getType() != Type::LabelTy) {
512 // Register names didn't use to conflict with basic block names
513 // because of type planes. Now they all have to be unique. So, we just
514 // rename the register and treat this name as if no basic block
516 RenameMapKey Key = std::make_pair(N->getName(),N->getType());
517 N->setName(makeNameUnique(N->getName()));
518 CurModule.RenameMap[Key] = N->getName();
521 BB = cast<BasicBlock>(N);
527 // See if the block has already been defined.
529 // If this is the definition of the block, make sure the existing value was
530 // just a forward reference. If it was a forward reference, there will be
531 // an entry for it in the PlaceHolderInfo map.
532 if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
533 // The existing value was a definition, not a forward reference.
534 error("Redefinition of label " + ID.getName());
536 ID.destroy(); // Free strdup'd memory.
540 // Otherwise this block has not been seen before.
541 BB = new BasicBlock("", CurFun.CurrentFunction);
542 if (ID.Type == ValID::NameVal) {
543 BB->setName(ID.Name);
545 CurFun.NumberedBlocks[ID.Num] = BB;
548 // If this is not a definition, keep track of it so we can use it as a forward
551 // Remember where this forward reference came from.
552 CurFun.BBForwardRefs[BB] = std::make_pair(ID, Upgradelineno);
554 // The forward declaration could have been inserted anywhere in the
555 // function: insert it into the correct place now.
556 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
557 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
564 //===----------------------------------------------------------------------===//
565 // Code to handle forward references in instructions
566 //===----------------------------------------------------------------------===//
568 // This code handles the late binding needed with statements that reference
569 // values not defined yet... for example, a forward branch, or the PHI node for
572 // This keeps a table (CurFun.LateResolveValues) of all such forward references
573 // and back patchs after we are done.
576 // ResolveDefinitions - If we could not resolve some defs at parsing
577 // time (forward branches, phi functions for loops, etc...) resolve the
581 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
582 std::map<const Type*,ValueList> *FutureLateResolvers) {
584 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
585 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
586 E = LateResolvers.end(); LRI != E; ++LRI) {
587 const Type* Ty = LRI->first;
588 ValueList &List = LRI->second;
589 while (!List.empty()) {
590 Value *V = List.back();
593 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
594 CurModule.PlaceHolderInfo.find(V);
595 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error");
597 ValID &DID = PHI->second.first;
599 Value *TheRealValue = getExistingValue(Ty, DID);
601 V->replaceAllUsesWith(TheRealValue);
603 CurModule.PlaceHolderInfo.erase(PHI);
604 } else if (FutureLateResolvers) {
605 // Functions have their unresolved items forwarded to the module late
607 InsertValue(V, *FutureLateResolvers);
609 if (DID.Type == ValID::NameVal) {
610 error("Reference to an invalid definition: '" + DID.getName() +
611 "' of type '" + V->getType()->getDescription() + "'",
615 error("Reference to an invalid definition: #" +
616 itostr(DID.Num) + " of type '" +
617 V->getType()->getDescription() + "'", PHI->second.second);
624 LateResolvers.clear();
627 // ResolveTypeTo - A brand new type was just declared. This means that (if
628 // name is not null) things referencing Name can be resolved. Otherwise, things
629 // refering to the number can be resolved. Do this now.
631 static void ResolveTypeTo(char *Name, const Type *ToTy) {
633 if (Name) D = ValID::create(Name);
634 else D = ValID::create((int)CurModule.Types.size());
636 std::map<ValID, PATypeHolder>::iterator I =
637 CurModule.LateResolveTypes.find(D);
638 if (I != CurModule.LateResolveTypes.end()) {
639 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
640 CurModule.LateResolveTypes.erase(I);
644 /// This is the implementation portion of TypeHasInteger. It traverses the
645 /// type given, avoiding recursive types, and returns true as soon as it finds
646 /// an integer type. If no integer type is found, it returns false.
647 static bool TypeHasIntegerI(const Type *Ty, std::vector<const Type*> Stack) {
648 // Handle some easy cases
649 if (Ty->isPrimitiveType() || (Ty->getTypeID() == Type::OpaqueTyID))
653 if (const SequentialType *STy = dyn_cast<SequentialType>(Ty))
654 return STy->getElementType()->isInteger();
656 // Avoid type structure recursion
657 for (std::vector<const Type*>::iterator I = Stack.begin(), E = Stack.end();
662 // Push us on the type stack
665 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
666 if (TypeHasIntegerI(FTy->getReturnType(), Stack))
668 FunctionType::param_iterator I = FTy->param_begin();
669 FunctionType::param_iterator E = FTy->param_end();
671 if (TypeHasIntegerI(*I, Stack))
674 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
675 StructType::element_iterator I = STy->element_begin();
676 StructType::element_iterator E = STy->element_end();
677 for (; I != E; ++I) {
678 if (TypeHasIntegerI(*I, Stack))
683 // There shouldn't be anything else, but its definitely not integer
684 assert(0 && "What type is this?");
688 /// This is the interface to TypeHasIntegerI. It just provides the type stack,
689 /// to avoid recursion, and then calls TypeHasIntegerI.
690 static inline bool TypeHasInteger(const Type *Ty) {
691 std::vector<const Type*> TyStack;
692 return TypeHasIntegerI(Ty, TyStack);
695 // setValueName - Set the specified value to the name given. The name may be
696 // null potentially, in which case this is a noop. The string passed in is
697 // assumed to be a malloc'd string buffer, and is free'd by this function.
699 static void setValueName(Value *V, char *NameStr) {
701 std::string Name(NameStr); // Copy string
702 free(NameStr); // Free old string
704 if (V->getType() == Type::VoidTy) {
705 error("Can't assign name '" + Name + "' to value with void type");
709 assert(inFunctionScope() && "Must be in function scope");
711 // Search the function's symbol table for an existing value of this name
712 ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
713 Value* Existing = ST.lookup(Name);
715 // An existing value of the same name was found. This might have happened
716 // because of the integer type planes collapsing in LLVM 2.0.
717 if (Existing->getType() == V->getType() &&
718 !TypeHasInteger(Existing->getType())) {
719 // If the type does not contain any integers in them then this can't be
720 // a type plane collapsing issue. It truly is a redefinition and we
721 // should error out as the assembly is invalid.
722 error("Redefinition of value named '" + Name + "' of type '" +
723 V->getType()->getDescription() + "'");
726 // In LLVM 2.0 we don't allow names to be re-used for any values in a
727 // function, regardless of Type. Previously re-use of names was okay as
728 // long as they were distinct types. With type planes collapsing because
729 // of the signedness change and because of PR411, this can no longer be
730 // supported. We must search the entire symbol table for a conflicting
731 // name and make the name unique. No warning is needed as this can't
733 std::string NewName = makeNameUnique(Name);
734 // We're changing the name but it will probably be used by other
735 // instructions as operands later on. Consequently we have to retain
736 // a mapping of the renaming that we're doing.
737 RenameMapKey Key = std::make_pair(Name,V->getType());
738 CurFun.RenameMap[Key] = NewName;
747 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
748 /// this is a declaration, otherwise it is a definition.
749 static GlobalVariable *
750 ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
751 bool isConstantGlobal, const Type *Ty,
752 Constant *Initializer) {
753 if (isa<FunctionType>(Ty))
754 error("Cannot declare global vars of function type");
756 const PointerType *PTy = PointerType::get(Ty);
760 Name = NameStr; // Copy string
761 free(NameStr); // Free old string
764 // See if this global value was forward referenced. If so, recycle the
768 ID = ValID::create((char*)Name.c_str());
770 ID = ValID::create((int)CurModule.Values[PTy].size());
773 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
774 // Move the global to the end of the list, from whereever it was
775 // previously inserted.
776 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
777 CurModule.CurrentModule->getGlobalList().remove(GV);
778 CurModule.CurrentModule->getGlobalList().push_back(GV);
779 GV->setInitializer(Initializer);
780 GV->setLinkage(Linkage);
781 GV->setConstant(isConstantGlobal);
782 InsertValue(GV, CurModule.Values);
786 // If this global has a name, check to see if there is already a definition
787 // of this global in the module and emit warnings if there are conflicts.
789 // The global has a name. See if there's an existing one of the same name.
790 if (CurModule.CurrentModule->getNamedGlobal(Name)) {
791 // We found an existing global ov the same name. This isn't allowed
792 // in LLVM 2.0. Consequently, we must alter the name of the global so it
793 // can at least compile. This can happen because of type planes
794 // There is alread a global of the same name which means there is a
795 // conflict. Let's see what we can do about it.
796 std::string NewName(makeNameUnique(Name));
797 if (Linkage == GlobalValue::InternalLinkage) {
798 // The linkage type is internal so just warn about the rename without
799 // invoking "scarey language" about linkage failures. GVars with
800 // InternalLinkage can be renamed at will.
801 warning("Global variable '" + Name + "' was renamed to '"+
804 // The linkage of this gval is external so we can't reliably rename
805 // it because it could potentially create a linking problem.
806 // However, we can't leave the name conflict in the output either or
807 // it won't assemble with LLVM 2.0. So, all we can do is rename
808 // this one to something unique and emit a warning about the problem.
809 warning("Renaming global variable '" + Name + "' to '" + NewName +
810 "' may cause linkage errors");
813 // Put the renaming in the global rename map
814 RenameMapKey Key = std::make_pair(Name,PointerType::get(Ty));
815 CurModule.RenameMap[Key] = NewName;
822 // Otherwise there is no existing GV to use, create one now.
824 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
825 CurModule.CurrentModule);
826 InsertValue(GV, CurModule.Values);
830 // setTypeName - Set the specified type to the name given. The name may be
831 // null potentially, in which case this is a noop. The string passed in is
832 // assumed to be a malloc'd string buffer, and is freed by this function.
834 // This function returns true if the type has already been defined, but is
835 // allowed to be redefined in the specified context. If the name is a new name
836 // for the type plane, it is inserted and false is returned.
837 static bool setTypeName(const Type *T, char *NameStr) {
838 assert(!inFunctionScope() && "Can't give types function-local names");
839 if (NameStr == 0) return false;
841 std::string Name(NameStr); // Copy string
842 free(NameStr); // Free old string
844 // We don't allow assigning names to void type
845 if (T == Type::VoidTy) {
846 error("Can't assign name '" + Name + "' to the void type");
850 // Set the type name, checking for conflicts as we do so.
851 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
853 if (AlreadyExists) { // Inserting a name that is already defined???
854 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
855 assert(Existing && "Conflict but no matching type?");
857 // There is only one case where this is allowed: when we are refining an
858 // opaque type. In this case, Existing will be an opaque type.
859 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
860 // We ARE replacing an opaque type!
861 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
865 // Otherwise, this is an attempt to redefine a type. That's okay if
866 // the redefinition is identical to the original. This will be so if
867 // Existing and T point to the same Type object. In this one case we
868 // allow the equivalent redefinition.
869 if (Existing == T) return true; // Yes, it's equal.
871 // Any other kind of (non-equivalent) redefinition is an error.
872 error("Redefinition of type named '" + Name + "' in the '" +
873 T->getDescription() + "' type plane");
879 //===----------------------------------------------------------------------===//
880 // Code for handling upreferences in type names...
883 // TypeContains - Returns true if Ty directly contains E in it.
885 static bool TypeContains(const Type *Ty, const Type *E) {
886 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
887 E) != Ty->subtype_end();
892 // NestingLevel - The number of nesting levels that need to be popped before
893 // this type is resolved.
894 unsigned NestingLevel;
896 // LastContainedTy - This is the type at the current binding level for the
897 // type. Every time we reduce the nesting level, this gets updated.
898 const Type *LastContainedTy;
900 // UpRefTy - This is the actual opaque type that the upreference is
904 UpRefRecord(unsigned NL, OpaqueType *URTy)
905 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
909 // UpRefs - A list of the outstanding upreferences that need to be resolved.
910 static std::vector<UpRefRecord> UpRefs;
912 /// HandleUpRefs - Every time we finish a new layer of types, this function is
913 /// called. It loops through the UpRefs vector, which is a list of the
914 /// currently active types. For each type, if the up reference is contained in
915 /// the newly completed type, we decrement the level count. When the level
916 /// count reaches zero, the upreferenced type is the type that is passed in:
917 /// thus we can complete the cycle.
919 static PATypeHolder HandleUpRefs(const Type *ty) {
920 // If Ty isn't abstract, or if there are no up-references in it, then there is
921 // nothing to resolve here.
922 if (!ty->isAbstract() || UpRefs.empty()) return ty;
925 UR_OUT("Type '" << Ty->getDescription() <<
926 "' newly formed. Resolving upreferences.\n" <<
927 UpRefs.size() << " upreferences active!\n");
929 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
930 // to zero), we resolve them all together before we resolve them to Ty. At
931 // the end of the loop, if there is anything to resolve to Ty, it will be in
933 OpaqueType *TypeToResolve = 0;
935 for (unsigned i = 0; i != UpRefs.size(); ++i) {
936 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
937 << UpRefs[i].second->getDescription() << ") = "
938 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
939 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
940 // Decrement level of upreference
941 unsigned Level = --UpRefs[i].NestingLevel;
942 UpRefs[i].LastContainedTy = Ty;
943 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
944 if (Level == 0) { // Upreference should be resolved!
945 if (!TypeToResolve) {
946 TypeToResolve = UpRefs[i].UpRefTy;
948 UR_OUT(" * Resolving upreference for "
949 << UpRefs[i].second->getDescription() << "\n";
950 std::string OldName = UpRefs[i].UpRefTy->getDescription());
951 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
952 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
953 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
955 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
956 --i; // Do not skip the next element...
962 UR_OUT(" * Resolving upreference for "
963 << UpRefs[i].second->getDescription() << "\n";
964 std::string OldName = TypeToResolve->getDescription());
965 TypeToResolve->refineAbstractTypeTo(Ty);
971 static inline Instruction::TermOps
972 getTermOp(TermOps op) {
974 default : assert(0 && "Invalid OldTermOp");
975 case RetOp : return Instruction::Ret;
976 case BrOp : return Instruction::Br;
977 case SwitchOp : return Instruction::Switch;
978 case InvokeOp : return Instruction::Invoke;
979 case UnwindOp : return Instruction::Unwind;
980 case UnreachableOp: return Instruction::Unreachable;
984 static inline Instruction::BinaryOps
985 getBinaryOp(BinaryOps op, const Type *Ty, Signedness Sign) {
987 default : assert(0 && "Invalid OldBinaryOps");
993 case SetGT : assert(0 && "Should use getCompareOp");
994 case AddOp : return Instruction::Add;
995 case SubOp : return Instruction::Sub;
996 case MulOp : return Instruction::Mul;
998 // This is an obsolete instruction so we must upgrade it based on the
999 // types of its operands.
1000 bool isFP = Ty->isFloatingPoint();
1001 if (const VectorType* PTy = dyn_cast<VectorType>(Ty))
1002 // If its a vector type we want to use the element type
1003 isFP = PTy->getElementType()->isFloatingPoint();
1005 return Instruction::FDiv;
1006 else if (Sign == Signed)
1007 return Instruction::SDiv;
1008 return Instruction::UDiv;
1010 case UDivOp : return Instruction::UDiv;
1011 case SDivOp : return Instruction::SDiv;
1012 case FDivOp : return Instruction::FDiv;
1014 // This is an obsolete instruction so we must upgrade it based on the
1015 // types of its operands.
1016 bool isFP = Ty->isFloatingPoint();
1017 if (const VectorType* PTy = dyn_cast<VectorType>(Ty))
1018 // If its a vector type we want to use the element type
1019 isFP = PTy->getElementType()->isFloatingPoint();
1020 // Select correct opcode
1022 return Instruction::FRem;
1023 else if (Sign == Signed)
1024 return Instruction::SRem;
1025 return Instruction::URem;
1027 case URemOp : return Instruction::URem;
1028 case SRemOp : return Instruction::SRem;
1029 case FRemOp : return Instruction::FRem;
1030 case LShrOp : return Instruction::LShr;
1031 case AShrOp : return Instruction::AShr;
1032 case ShlOp : return Instruction::Shl;
1035 return Instruction::AShr;
1036 return Instruction::LShr;
1037 case AndOp : return Instruction::And;
1038 case OrOp : return Instruction::Or;
1039 case XorOp : return Instruction::Xor;
1043 static inline Instruction::OtherOps
1044 getCompareOp(BinaryOps op, unsigned short &predicate, const Type* &Ty,
1046 bool isSigned = Sign == Signed;
1047 bool isFP = Ty->isFloatingPoint();
1049 default : assert(0 && "Invalid OldSetCC");
1052 predicate = FCmpInst::FCMP_OEQ;
1053 return Instruction::FCmp;
1055 predicate = ICmpInst::ICMP_EQ;
1056 return Instruction::ICmp;
1060 predicate = FCmpInst::FCMP_UNE;
1061 return Instruction::FCmp;
1063 predicate = ICmpInst::ICMP_NE;
1064 return Instruction::ICmp;
1068 predicate = FCmpInst::FCMP_OLE;
1069 return Instruction::FCmp;
1072 predicate = ICmpInst::ICMP_SLE;
1074 predicate = ICmpInst::ICMP_ULE;
1075 return Instruction::ICmp;
1079 predicate = FCmpInst::FCMP_OGE;
1080 return Instruction::FCmp;
1083 predicate = ICmpInst::ICMP_SGE;
1085 predicate = ICmpInst::ICMP_UGE;
1086 return Instruction::ICmp;
1090 predicate = FCmpInst::FCMP_OLT;
1091 return Instruction::FCmp;
1094 predicate = ICmpInst::ICMP_SLT;
1096 predicate = ICmpInst::ICMP_ULT;
1097 return Instruction::ICmp;
1101 predicate = FCmpInst::FCMP_OGT;
1102 return Instruction::FCmp;
1105 predicate = ICmpInst::ICMP_SGT;
1107 predicate = ICmpInst::ICMP_UGT;
1108 return Instruction::ICmp;
1113 static inline Instruction::MemoryOps getMemoryOp(MemoryOps op) {
1115 default : assert(0 && "Invalid OldMemoryOps");
1116 case MallocOp : return Instruction::Malloc;
1117 case FreeOp : return Instruction::Free;
1118 case AllocaOp : return Instruction::Alloca;
1119 case LoadOp : return Instruction::Load;
1120 case StoreOp : return Instruction::Store;
1121 case GetElementPtrOp : return Instruction::GetElementPtr;
1125 static inline Instruction::OtherOps
1126 getOtherOp(OtherOps op, Signedness Sign) {
1128 default : assert(0 && "Invalid OldOtherOps");
1129 case PHIOp : return Instruction::PHI;
1130 case CallOp : return Instruction::Call;
1131 case SelectOp : return Instruction::Select;
1132 case UserOp1 : return Instruction::UserOp1;
1133 case UserOp2 : return Instruction::UserOp2;
1134 case VAArg : return Instruction::VAArg;
1135 case ExtractElementOp : return Instruction::ExtractElement;
1136 case InsertElementOp : return Instruction::InsertElement;
1137 case ShuffleVectorOp : return Instruction::ShuffleVector;
1138 case ICmpOp : return Instruction::ICmp;
1139 case FCmpOp : return Instruction::FCmp;
1143 static inline Value*
1144 getCast(CastOps op, Value *Src, Signedness SrcSign, const Type *DstTy,
1145 Signedness DstSign, bool ForceInstruction = false) {
1146 Instruction::CastOps Opcode;
1147 const Type* SrcTy = Src->getType();
1149 if (SrcTy->isFloatingPoint() && isa<PointerType>(DstTy)) {
1150 // fp -> ptr cast is no longer supported but we must upgrade this
1151 // by doing a double cast: fp -> int -> ptr
1152 SrcTy = Type::Int64Ty;
1153 Opcode = Instruction::IntToPtr;
1154 if (isa<Constant>(Src)) {
1155 Src = ConstantExpr::getCast(Instruction::FPToUI,
1156 cast<Constant>(Src), SrcTy);
1158 std::string NewName(makeNameUnique(Src->getName()));
1159 Src = new FPToUIInst(Src, SrcTy, NewName, CurBB);
1161 } else if (isa<IntegerType>(DstTy) &&
1162 cast<IntegerType>(DstTy)->getBitWidth() == 1) {
1163 // cast type %x to bool was previously defined as setne type %x, null
1164 // The cast semantic is now to truncate, not compare so we must retain
1165 // the original intent by replacing the cast with a setne
1166 Constant* Null = Constant::getNullValue(SrcTy);
1167 Instruction::OtherOps Opcode = Instruction::ICmp;
1168 unsigned short predicate = ICmpInst::ICMP_NE;
1169 if (SrcTy->isFloatingPoint()) {
1170 Opcode = Instruction::FCmp;
1171 predicate = FCmpInst::FCMP_ONE;
1172 } else if (!SrcTy->isInteger() && !isa<PointerType>(SrcTy)) {
1173 error("Invalid cast to bool");
1175 if (isa<Constant>(Src) && !ForceInstruction)
1176 return ConstantExpr::getCompare(predicate, cast<Constant>(Src), Null);
1178 return CmpInst::create(Opcode, predicate, Src, Null);
1180 // Determine the opcode to use by calling CastInst::getCastOpcode
1182 CastInst::getCastOpcode(Src, SrcSign == Signed, DstTy, DstSign == Signed);
1184 } else switch (op) {
1185 default: assert(0 && "Invalid cast token");
1186 case TruncOp: Opcode = Instruction::Trunc; break;
1187 case ZExtOp: Opcode = Instruction::ZExt; break;
1188 case SExtOp: Opcode = Instruction::SExt; break;
1189 case FPTruncOp: Opcode = Instruction::FPTrunc; break;
1190 case FPExtOp: Opcode = Instruction::FPExt; break;
1191 case FPToUIOp: Opcode = Instruction::FPToUI; break;
1192 case FPToSIOp: Opcode = Instruction::FPToSI; break;
1193 case UIToFPOp: Opcode = Instruction::UIToFP; break;
1194 case SIToFPOp: Opcode = Instruction::SIToFP; break;
1195 case PtrToIntOp: Opcode = Instruction::PtrToInt; break;
1196 case IntToPtrOp: Opcode = Instruction::IntToPtr; break;
1197 case BitCastOp: Opcode = Instruction::BitCast; break;
1200 if (isa<Constant>(Src) && !ForceInstruction)
1201 return ConstantExpr::getCast(Opcode, cast<Constant>(Src), DstTy);
1202 return CastInst::create(Opcode, Src, DstTy);
1205 static Instruction *
1206 upgradeIntrinsicCall(const Type* RetTy, const ValID &ID,
1207 std::vector<Value*>& Args) {
1209 std::string Name = ID.Type == ValID::NameVal ? ID.Name : "";
1210 if (Name == "llvm.isunordered.f32" || Name == "llvm.isunordered.f64") {
1211 if (Args.size() != 2)
1212 error("Invalid prototype for " + Name + " prototype");
1213 return new FCmpInst(FCmpInst::FCMP_UNO, Args[0], Args[1]);
1215 const Type* PtrTy = PointerType::get(Type::Int8Ty);
1216 std::vector<const Type*> Params;
1217 if (Name == "llvm.va_start" || Name == "llvm.va_end") {
1218 if (Args.size() != 1)
1219 error("Invalid prototype for " + Name + " prototype");
1220 Params.push_back(PtrTy);
1221 const FunctionType *FTy = FunctionType::get(Type::VoidTy, Params, false);
1222 const PointerType *PFTy = PointerType::get(FTy);
1223 Value* Func = getVal(PFTy, ID);
1224 Args[0] = new BitCastInst(Args[0], PtrTy, makeNameUnique("va"), CurBB);
1225 return new CallInst(Func, &Args[0], Args.size());
1226 } else if (Name == "llvm.va_copy") {
1227 if (Args.size() != 2)
1228 error("Invalid prototype for " + Name + " prototype");
1229 Params.push_back(PtrTy);
1230 Params.push_back(PtrTy);
1231 const FunctionType *FTy = FunctionType::get(Type::VoidTy, Params, false);
1232 const PointerType *PFTy = PointerType::get(FTy);
1233 Value* Func = getVal(PFTy, ID);
1234 std::string InstName0(makeNameUnique("va0"));
1235 std::string InstName1(makeNameUnique("va1"));
1236 Args[0] = new BitCastInst(Args[0], PtrTy, InstName0, CurBB);
1237 Args[1] = new BitCastInst(Args[1], PtrTy, InstName1, CurBB);
1238 return new CallInst(Func, &Args[0], Args.size());
1244 const Type* upgradeGEPIndices(const Type* PTy,
1245 std::vector<ValueInfo> *Indices,
1246 std::vector<Value*> &VIndices,
1247 std::vector<Constant*> *CIndices = 0) {
1248 // Traverse the indices with a gep_type_iterator so we can build the list
1249 // of constant and value indices for use later. Also perform upgrades
1251 if (CIndices) CIndices->clear();
1252 for (unsigned i = 0, e = Indices->size(); i != e; ++i)
1253 VIndices.push_back((*Indices)[i].V);
1254 generic_gep_type_iterator<std::vector<Value*>::iterator>
1255 GTI = gep_type_begin(PTy, VIndices.begin(), VIndices.end()),
1256 GTE = gep_type_end(PTy, VIndices.begin(), VIndices.end());
1257 for (unsigned i = 0, e = Indices->size(); i != e && GTI != GTE; ++i, ++GTI) {
1258 Value *Index = VIndices[i];
1259 if (CIndices && !isa<Constant>(Index))
1260 error("Indices to constant getelementptr must be constants");
1261 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte
1262 // struct indices to i32 struct indices with ZExt for compatibility.
1263 else if (isa<StructType>(*GTI)) { // Only change struct indices
1264 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Index))
1265 if (CUI->getType()->getBitWidth() == 8)
1267 ConstantExpr::getCast(Instruction::ZExt, CUI, Type::Int32Ty);
1269 // Make sure that unsigned SequentialType indices are zext'd to
1270 // 64-bits if they were smaller than that because LLVM 2.0 will sext
1271 // all indices for SequentialType elements. We must retain the same
1272 // semantic (zext) for unsigned types.
1273 if (const IntegerType *Ity = dyn_cast<IntegerType>(Index->getType()))
1274 if (Ity->getBitWidth() < 64 && (*Indices)[i].S == Unsigned) {
1276 Index = ConstantExpr::getCast(Instruction::ZExt,
1277 cast<Constant>(Index), Type::Int64Ty);
1279 Index = CastInst::create(Instruction::ZExt, Index, Type::Int64Ty,
1280 makeNameUnique("gep"), CurBB);
1281 VIndices[i] = Index;
1284 // Add to the CIndices list, if requested.
1286 CIndices->push_back(cast<Constant>(Index));
1290 GetElementPtrInst::getIndexedType(PTy, &VIndices[0], VIndices.size(), true);
1292 error("Index list invalid for constant getelementptr");
1296 unsigned upgradeCallingConv(unsigned CC) {
1298 case OldCallingConv::C : return CallingConv::C;
1299 case OldCallingConv::CSRet : return CallingConv::C;
1300 case OldCallingConv::Fast : return CallingConv::Fast;
1301 case OldCallingConv::Cold : return CallingConv::Cold;
1302 case OldCallingConv::X86_StdCall : return CallingConv::X86_StdCall;
1303 case OldCallingConv::X86_FastCall: return CallingConv::X86_FastCall;
1309 Module* UpgradeAssembly(const std::string &infile, std::istream& in,
1310 bool debug, bool addAttrs)
1313 CurFilename = infile;
1316 AddAttributes = addAttrs;
1317 ObsoleteVarArgs = false;
1320 CurModule.CurrentModule = new Module(CurFilename);
1322 // Check to make sure the parser succeeded
1325 delete ParserResult;
1326 std::cerr << "llvm-upgrade: parse failed.\n";
1330 // Check to make sure that parsing produced a result
1331 if (!ParserResult) {
1332 std::cerr << "llvm-upgrade: no parse result.\n";
1336 // Reset ParserResult variable while saving its value for the result.
1337 Module *Result = ParserResult;
1340 //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
1343 if ((F = Result->getFunction("llvm.va_start"))
1344 && F->getFunctionType()->getNumParams() == 0)
1345 ObsoleteVarArgs = true;
1346 if((F = Result->getFunction("llvm.va_copy"))
1347 && F->getFunctionType()->getNumParams() == 1)
1348 ObsoleteVarArgs = true;
1351 if (ObsoleteVarArgs && NewVarArgs) {
1352 error("This file is corrupt: it uses both new and old style varargs");
1356 if(ObsoleteVarArgs) {
1357 if(Function* F = Result->getFunction("llvm.va_start")) {
1358 if (F->arg_size() != 0) {
1359 error("Obsolete va_start takes 0 argument");
1365 //bar = alloca typeof(foo)
1369 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1370 const Type* ArgTy = F->getFunctionType()->getReturnType();
1371 const Type* ArgTyPtr = PointerType::get(ArgTy);
1372 Function* NF = cast<Function>(Result->getOrInsertFunction(
1373 "llvm.va_start", RetTy, ArgTyPtr, (Type *)0));
1375 while (!F->use_empty()) {
1376 CallInst* CI = cast<CallInst>(F->use_back());
1377 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
1378 new CallInst(NF, bar, "", CI);
1379 Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
1380 CI->replaceAllUsesWith(foo);
1381 CI->getParent()->getInstList().erase(CI);
1383 Result->getFunctionList().erase(F);
1386 if(Function* F = Result->getFunction("llvm.va_end")) {
1387 if(F->arg_size() != 1) {
1388 error("Obsolete va_end takes 1 argument");
1394 //bar = alloca 1 of typeof(foo)
1396 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1397 const Type* ArgTy = F->getFunctionType()->getParamType(0);
1398 const Type* ArgTyPtr = PointerType::get(ArgTy);
1399 Function* NF = cast<Function>(Result->getOrInsertFunction(
1400 "llvm.va_end", RetTy, ArgTyPtr, (Type *)0));
1402 while (!F->use_empty()) {
1403 CallInst* CI = cast<CallInst>(F->use_back());
1404 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
1405 new StoreInst(CI->getOperand(1), bar, CI);
1406 new CallInst(NF, bar, "", CI);
1407 CI->getParent()->getInstList().erase(CI);
1409 Result->getFunctionList().erase(F);
1412 if(Function* F = Result->getFunction("llvm.va_copy")) {
1413 if(F->arg_size() != 1) {
1414 error("Obsolete va_copy takes 1 argument");
1419 //a = alloca 1 of typeof(foo)
1420 //b = alloca 1 of typeof(foo)
1425 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1426 const Type* ArgTy = F->getFunctionType()->getReturnType();
1427 const Type* ArgTyPtr = PointerType::get(ArgTy);
1428 Function* NF = cast<Function>(Result->getOrInsertFunction(
1429 "llvm.va_copy", RetTy, ArgTyPtr, ArgTyPtr, (Type *)0));
1431 while (!F->use_empty()) {
1432 CallInst* CI = cast<CallInst>(F->use_back());
1433 AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
1434 AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
1435 new StoreInst(CI->getOperand(1), b, CI);
1436 new CallInst(NF, a, b, "", CI);
1437 Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
1438 CI->replaceAllUsesWith(foo);
1439 CI->getParent()->getInstList().erase(CI);
1441 Result->getFunctionList().erase(F);
1448 } // end llvm namespace
1450 using namespace llvm;
1455 llvm::Module *ModuleVal;
1456 llvm::Function *FunctionVal;
1457 std::pair<llvm::PATypeInfo, char*> *ArgVal;
1458 llvm::BasicBlock *BasicBlockVal;
1459 llvm::TerminatorInst *TermInstVal;
1460 llvm::InstrInfo InstVal;
1461 llvm::ConstInfo ConstVal;
1462 llvm::ValueInfo ValueVal;
1463 llvm::PATypeInfo TypeVal;
1464 llvm::TypeInfo PrimType;
1465 llvm::PHIListInfo PHIList;
1466 std::list<llvm::PATypeInfo> *TypeList;
1467 std::vector<llvm::ValueInfo> *ValueList;
1468 std::vector<llvm::ConstInfo> *ConstVector;
1471 std::vector<std::pair<llvm::PATypeInfo,char*> > *ArgList;
1472 // Represent the RHS of PHI node
1473 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
1475 llvm::GlobalValue::LinkageTypes Linkage;
1483 char *StrVal; // This memory is strdup'd!
1484 llvm::ValID ValIDVal; // strdup'd memory maybe!
1486 llvm::BinaryOps BinaryOpVal;
1487 llvm::TermOps TermOpVal;
1488 llvm::MemoryOps MemOpVal;
1489 llvm::OtherOps OtherOpVal;
1490 llvm::CastOps CastOpVal;
1491 llvm::ICmpInst::Predicate IPred;
1492 llvm::FCmpInst::Predicate FPred;
1493 llvm::Module::Endianness Endianness;
1496 %type <ModuleVal> Module FunctionList
1497 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1498 %type <BasicBlockVal> BasicBlock InstructionList
1499 %type <TermInstVal> BBTerminatorInst
1500 %type <InstVal> Inst InstVal MemoryInst
1501 %type <ConstVal> ConstVal ConstExpr
1502 %type <ConstVector> ConstVector
1503 %type <ArgList> ArgList ArgListH
1504 %type <ArgVal> ArgVal
1505 %type <PHIList> PHIList
1506 %type <ValueList> ValueRefList ValueRefListE // For call param lists
1507 %type <ValueList> IndexList // For GEP derived indices
1508 %type <TypeList> TypeListI ArgTypeListI
1509 %type <JumpTable> JumpTable
1510 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1511 %type <BoolVal> OptVolatile // 'volatile' or not
1512 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1513 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
1514 %type <Linkage> OptLinkage FnDeclareLinkage
1515 %type <Endianness> BigOrLittle
1517 // ValueRef - Unresolved reference to a definition or BB
1518 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1519 %type <ValueVal> ResolvedVal // <type> <valref> pair
1521 // Tokens and types for handling constant integer values
1523 // ESINT64VAL - A negative number within long long range
1524 %token <SInt64Val> ESINT64VAL
1526 // EUINT64VAL - A positive number within uns. long long range
1527 %token <UInt64Val> EUINT64VAL
1528 %type <SInt64Val> EINT64VAL
1530 %token <SIntVal> SINTVAL // Signed 32 bit ints...
1531 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
1532 %type <SIntVal> INTVAL
1533 %token <FPVal> FPVAL // Float or Double constant
1535 // Built in types...
1536 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
1537 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
1538 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
1539 %token <PrimType> FLOAT DOUBLE TYPE LABEL
1541 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
1542 %type <StrVal> Name OptName OptAssign
1543 %type <UIntVal> OptAlign OptCAlign
1544 %type <StrVal> OptSection SectionString
1546 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1547 %token DECLARE GLOBAL CONSTANT SECTION VOLATILE
1548 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
1549 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
1550 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
1551 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1552 %token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
1553 %token X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1555 %type <UIntVal> OptCallingConv
1557 // Basic Block Terminating Operators
1558 %token <TermOpVal> RET BR SWITCH INVOKE UNREACHABLE
1559 %token UNWIND EXCEPT
1562 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
1563 %type <BinaryOpVal> ShiftOps
1564 %token <BinaryOpVal> ADD SUB MUL DIV UDIV SDIV FDIV REM UREM SREM FREM
1565 %token <BinaryOpVal> AND OR XOR SHL SHR ASHR LSHR
1566 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comparators
1567 %token <OtherOpVal> ICMP FCMP
1569 // Memory Instructions
1570 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1573 %token <OtherOpVal> PHI_TOK SELECT VAARG
1574 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1575 %token VAARG_old VANEXT_old //OBSOLETE
1577 // Support for ICmp/FCmp Predicates, which is 1.9++ but not 2.0
1578 %type <IPred> IPredicates
1579 %type <FPred> FPredicates
1580 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1581 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1583 %token <CastOpVal> CAST TRUNC ZEXT SEXT FPTRUNC FPEXT FPTOUI FPTOSI
1584 %token <CastOpVal> UITOFP SITOFP PTRTOINT INTTOPTR BITCAST
1585 %type <CastOpVal> CastOps
1591 // Handle constant integer size restriction and conversion...
1596 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
1597 error("Value too large for type");
1603 : ESINT64VAL // These have same type and can't cause problems...
1605 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
1606 error("Value too large for type");
1610 // Operations that are notably excluded from this list include:
1611 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1614 : ADD | SUB | MUL | DIV | UDIV | SDIV | FDIV | REM | UREM | SREM | FREM
1622 : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
1626 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1627 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1628 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1629 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1630 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1634 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1635 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1636 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1637 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1638 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1639 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1640 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1641 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1642 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1645 : SHL | SHR | ASHR | LSHR
1649 : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | FPTOUI | FPTOSI
1650 | UITOFP | SITOFP | PTRTOINT | INTTOPTR | BITCAST | CAST
1653 // These are some types that allow classification if we only want a particular
1654 // thing... for example, only a signed, unsigned, or integral type.
1656 : LONG | INT | SHORT | SBYTE
1660 : ULONG | UINT | USHORT | UBYTE
1664 : SIntType | UIntType
1671 // OptAssign - Value producing statements have an optional assignment component
1681 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1682 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1683 | WEAK { $$ = GlobalValue::WeakLinkage; }
1684 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1685 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1686 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1687 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1688 | /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1692 : /*empty*/ { $$ = OldCallingConv::C; }
1693 | CCC_TOK { $$ = OldCallingConv::C; }
1694 | CSRETCC_TOK { $$ = OldCallingConv::CSRet; }
1695 | FASTCC_TOK { $$ = OldCallingConv::Fast; }
1696 | COLDCC_TOK { $$ = OldCallingConv::Cold; }
1697 | X86_STDCALLCC_TOK { $$ = OldCallingConv::X86_StdCall; }
1698 | X86_FASTCALLCC_TOK { $$ = OldCallingConv::X86_FastCall; }
1699 | CC_TOK EUINT64VAL {
1700 if ((unsigned)$2 != $2)
1701 error("Calling conv too large");
1706 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1707 // a comma before it.
1709 : /*empty*/ { $$ = 0; }
1710 | ALIGN EUINT64VAL {
1712 if ($$ != 0 && !isPowerOf2_32($$))
1713 error("Alignment must be a power of two");
1718 : /*empty*/ { $$ = 0; }
1719 | ',' ALIGN EUINT64VAL {
1721 if ($$ != 0 && !isPowerOf2_32($$))
1722 error("Alignment must be a power of two");
1727 : SECTION STRINGCONSTANT {
1728 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1729 if ($2[i] == '"' || $2[i] == '\\')
1730 error("Invalid character in section name");
1736 : /*empty*/ { $$ = 0; }
1737 | SectionString { $$ = $1; }
1740 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1741 // is set to be the global we are processing.
1745 | ',' GlobalVarAttribute GlobalVarAttributes {}
1750 CurGV->setSection($1);
1753 | ALIGN EUINT64VAL {
1754 if ($2 != 0 && !isPowerOf2_32($2))
1755 error("Alignment must be a power of two");
1756 CurGV->setAlignment($2);
1761 //===----------------------------------------------------------------------===//
1762 // Types includes all predefined types... except void, because it can only be
1763 // used in specific contexts (function returning void for example). To have
1764 // access to it, a user must explicitly use TypesV.
1767 // TypesV includes all of 'Types', but it also includes the void type.
1771 $$.PAT = new PATypeHolder($1.T);
1779 $$.PAT = new PATypeHolder($1.T);
1786 if (!UpRefs.empty())
1787 error("Invalid upreference in type: " + (*$1.PAT)->getDescription());
1793 : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT
1794 | LONG | ULONG | FLOAT | DOUBLE | LABEL
1797 // Derived types are added later...
1800 $$.PAT = new PATypeHolder($1.T);
1804 $$.PAT = new PATypeHolder(OpaqueType::get());
1807 | SymbolicValueRef { // Named types are also simple types...
1808 const Type* tmp = getType($1);
1809 $$.PAT = new PATypeHolder(tmp);
1810 $$.S = Signless; // FIXME: what if its signed?
1812 | '\\' EUINT64VAL { // Type UpReference
1813 if ($2 > (uint64_t)~0U)
1814 error("Value out of range");
1815 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1816 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1817 $$.PAT = new PATypeHolder(OT);
1819 UR_OUT("New Upreference!\n");
1821 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
1822 std::vector<const Type*> Params;
1823 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
1824 E = $3->end(); I != E; ++I) {
1825 Params.push_back(I->PAT->get());
1827 FunctionType::ParamAttrsList ParamAttrs;
1828 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1829 if (isVarArg) Params.pop_back();
1831 $$.PAT = new PATypeHolder(
1832 HandleUpRefs(FunctionType::get($1.PAT->get(), Params, isVarArg,
1835 delete $1.PAT; // Delete the return type handle
1836 delete $3; // Delete the argument list
1838 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
1839 $$.PAT = new PATypeHolder(HandleUpRefs(ArrayType::get($4.PAT->get(),
1844 | '<' EUINT64VAL 'x' UpRTypes '>' { // Vector type?
1845 const llvm::Type* ElemTy = $4.PAT->get();
1846 if ((unsigned)$2 != $2)
1847 error("Unsigned result not equal to signed result");
1848 if (!(ElemTy->isInteger() || ElemTy->isFloatingPoint()))
1849 error("Elements of a VectorType must be integer or floating point");
1850 if (!isPowerOf2_32($2))
1851 error("VectorType length should be a power of 2");
1852 $$.PAT = new PATypeHolder(HandleUpRefs(VectorType::get(ElemTy,
1857 | '{' TypeListI '}' { // Structure type?
1858 std::vector<const Type*> Elements;
1859 for (std::list<llvm::PATypeInfo>::iterator I = $2->begin(),
1860 E = $2->end(); I != E; ++I)
1861 Elements.push_back(I->PAT->get());
1862 $$.PAT = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1866 | '{' '}' { // Empty structure type?
1867 $$.PAT = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1870 | '<' '{' TypeListI '}' '>' { // Packed Structure type?
1871 std::vector<const Type*> Elements;
1872 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
1873 E = $3->end(); I != E; ++I) {
1874 Elements.push_back(I->PAT->get());
1877 $$.PAT = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1881 | '<' '{' '}' '>' { // Empty packed structure type?
1882 $$.PAT = new PATypeHolder(StructType::get(std::vector<const Type*>(),true));
1885 | UpRTypes '*' { // Pointer type?
1886 if ($1.PAT->get() == Type::LabelTy)
1887 error("Cannot form a pointer to a basic block");
1888 $$.PAT = new PATypeHolder(HandleUpRefs(PointerType::get($1.PAT->get())));
1894 // TypeList - Used for struct declarations and as a basis for function type
1895 // declaration type lists
1899 $$ = new std::list<PATypeInfo>();
1902 | TypeListI ',' UpRTypes {
1903 ($$=$1)->push_back($3);
1907 // ArgTypeList - List of types for a function type declaration...
1910 | TypeListI ',' DOTDOTDOT {
1912 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
1913 VoidTI.S = Signless;
1914 ($$=$1)->push_back(VoidTI);
1917 $$ = new std::list<PATypeInfo>();
1919 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
1920 VoidTI.S = Signless;
1921 $$->push_back(VoidTI);
1924 $$ = new std::list<PATypeInfo>();
1928 // ConstVal - The various declarations that go into the constant pool. This
1929 // production is used ONLY to represent constants that show up AFTER a 'const',
1930 // 'constant' or 'global' token at global scope. Constants that can be inlined
1931 // into other expressions (such as integers and constexprs) are handled by the
1932 // ResolvedVal, ValueRef and ConstValueRef productions.
1935 : Types '[' ConstVector ']' { // Nonempty unsized arr
1936 const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
1938 error("Cannot make array constant with type: '" +
1939 $1.PAT->get()->getDescription() + "'");
1940 const Type *ETy = ATy->getElementType();
1941 int NumElements = ATy->getNumElements();
1943 // Verify that we have the correct size...
1944 if (NumElements != -1 && NumElements != (int)$3->size())
1945 error("Type mismatch: constant sized array initialized with " +
1946 utostr($3->size()) + " arguments, but has size of " +
1947 itostr(NumElements) + "");
1949 // Verify all elements are correct type!
1950 std::vector<Constant*> Elems;
1951 for (unsigned i = 0; i < $3->size(); i++) {
1952 Constant *C = (*$3)[i].C;
1953 const Type* ValTy = C->getType();
1955 error("Element #" + utostr(i) + " is not of type '" +
1956 ETy->getDescription() +"' as required!\nIt is of type '"+
1957 ValTy->getDescription() + "'");
1960 $$.C = ConstantArray::get(ATy, Elems);
1966 const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
1968 error("Cannot make array constant with type: '" +
1969 $1.PAT->get()->getDescription() + "'");
1970 int NumElements = ATy->getNumElements();
1971 if (NumElements != -1 && NumElements != 0)
1972 error("Type mismatch: constant sized array initialized with 0"
1973 " arguments, but has size of " + itostr(NumElements) +"");
1974 $$.C = ConstantArray::get(ATy, std::vector<Constant*>());
1978 | Types 'c' STRINGCONSTANT {
1979 const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
1981 error("Cannot make array constant with type: '" +
1982 $1.PAT->get()->getDescription() + "'");
1983 int NumElements = ATy->getNumElements();
1984 const Type *ETy = dyn_cast<IntegerType>(ATy->getElementType());
1985 if (!ETy || cast<IntegerType>(ETy)->getBitWidth() != 8)
1986 error("String arrays require type i8, not '" + ETy->getDescription() +
1988 char *EndStr = UnEscapeLexed($3, true);
1989 if (NumElements != -1 && NumElements != (EndStr-$3))
1990 error("Can't build string constant of size " +
1991 itostr((int)(EndStr-$3)) + " when array has size " +
1992 itostr(NumElements) + "");
1993 std::vector<Constant*> Vals;
1994 for (char *C = (char *)$3; C != (char *)EndStr; ++C)
1995 Vals.push_back(ConstantInt::get(ETy, *C));
1997 $$.C = ConstantArray::get(ATy, Vals);
2001 | Types '<' ConstVector '>' { // Nonempty unsized arr
2002 const VectorType *PTy = dyn_cast<VectorType>($1.PAT->get());
2004 error("Cannot make packed constant with type: '" +
2005 $1.PAT->get()->getDescription() + "'");
2006 const Type *ETy = PTy->getElementType();
2007 int NumElements = PTy->getNumElements();
2008 // Verify that we have the correct size...
2009 if (NumElements != -1 && NumElements != (int)$3->size())
2010 error("Type mismatch: constant sized packed initialized with " +
2011 utostr($3->size()) + " arguments, but has size of " +
2012 itostr(NumElements) + "");
2013 // Verify all elements are correct type!
2014 std::vector<Constant*> Elems;
2015 for (unsigned i = 0; i < $3->size(); i++) {
2016 Constant *C = (*$3)[i].C;
2017 const Type* ValTy = C->getType();
2019 error("Element #" + utostr(i) + " is not of type '" +
2020 ETy->getDescription() +"' as required!\nIt is of type '"+
2021 ValTy->getDescription() + "'");
2024 $$.C = ConstantVector::get(PTy, Elems);
2029 | Types '{' ConstVector '}' {
2030 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2032 error("Cannot make struct constant with type: '" +
2033 $1.PAT->get()->getDescription() + "'");
2034 if ($3->size() != STy->getNumContainedTypes())
2035 error("Illegal number of initializers for structure type");
2037 // Check to ensure that constants are compatible with the type initializer!
2038 std::vector<Constant*> Fields;
2039 for (unsigned i = 0, e = $3->size(); i != e; ++i) {
2040 Constant *C = (*$3)[i].C;
2041 if (C->getType() != STy->getElementType(i))
2042 error("Expected type '" + STy->getElementType(i)->getDescription() +
2043 "' for element #" + utostr(i) + " of structure initializer");
2044 Fields.push_back(C);
2046 $$.C = ConstantStruct::get(STy, Fields);
2052 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2054 error("Cannot make struct constant with type: '" +
2055 $1.PAT->get()->getDescription() + "'");
2056 if (STy->getNumContainedTypes() != 0)
2057 error("Illegal number of initializers for structure type");
2058 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2062 | Types '<' '{' ConstVector '}' '>' {
2063 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2065 error("Cannot make packed struct constant with type: '" +
2066 $1.PAT->get()->getDescription() + "'");
2067 if ($4->size() != STy->getNumContainedTypes())
2068 error("Illegal number of initializers for packed structure type");
2070 // Check to ensure that constants are compatible with the type initializer!
2071 std::vector<Constant*> Fields;
2072 for (unsigned i = 0, e = $4->size(); i != e; ++i) {
2073 Constant *C = (*$4)[i].C;
2074 if (C->getType() != STy->getElementType(i))
2075 error("Expected type '" + STy->getElementType(i)->getDescription() +
2076 "' for element #" + utostr(i) + " of packed struct initializer");
2077 Fields.push_back(C);
2079 $$.C = ConstantStruct::get(STy, Fields);
2084 | Types '<' '{' '}' '>' {
2085 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2087 error("Cannot make packed struct constant with type: '" +
2088 $1.PAT->get()->getDescription() + "'");
2089 if (STy->getNumContainedTypes() != 0)
2090 error("Illegal number of initializers for packed structure type");
2091 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2096 const PointerType *PTy = dyn_cast<PointerType>($1.PAT->get());
2098 error("Cannot make null pointer constant with type: '" +
2099 $1.PAT->get()->getDescription() + "'");
2100 $$.C = ConstantPointerNull::get(PTy);
2105 $$.C = UndefValue::get($1.PAT->get());
2109 | Types SymbolicValueRef {
2110 const PointerType *Ty = dyn_cast<PointerType>($1.PAT->get());
2112 error("Global const reference must be a pointer type, not" +
2113 $1.PAT->get()->getDescription());
2115 // ConstExprs can exist in the body of a function, thus creating
2116 // GlobalValues whenever they refer to a variable. Because we are in
2117 // the context of a function, getExistingValue will search the functions
2118 // symbol table instead of the module symbol table for the global symbol,
2119 // which throws things all off. To get around this, we just tell
2120 // getExistingValue that we are at global scope here.
2122 Function *SavedCurFn = CurFun.CurrentFunction;
2123 CurFun.CurrentFunction = 0;
2124 Value *V = getExistingValue(Ty, $2);
2125 CurFun.CurrentFunction = SavedCurFn;
2127 // If this is an initializer for a constant pointer, which is referencing a
2128 // (currently) undefined variable, create a stub now that shall be replaced
2129 // in the future with the right type of variable.
2132 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers");
2133 const PointerType *PT = cast<PointerType>(Ty);
2135 // First check to see if the forward references value is already created!
2136 PerModuleInfo::GlobalRefsType::iterator I =
2137 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
2139 if (I != CurModule.GlobalRefs.end()) {
2140 V = I->second; // Placeholder already exists, use it...
2144 if ($2.Type == ValID::NameVal) Name = $2.Name;
2146 // Create the forward referenced global.
2148 if (const FunctionType *FTy =
2149 dyn_cast<FunctionType>(PT->getElementType())) {
2150 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
2151 CurModule.CurrentModule);
2153 GV = new GlobalVariable(PT->getElementType(), false,
2154 GlobalValue::ExternalLinkage, 0,
2155 Name, CurModule.CurrentModule);
2158 // Keep track of the fact that we have a forward ref to recycle it
2159 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
2163 $$.C = cast<GlobalValue>(V);
2165 delete $1.PAT; // Free the type handle
2168 if ($1.PAT->get() != $2.C->getType())
2169 error("Mismatched types for constant expression");
2174 | Types ZEROINITIALIZER {
2175 const Type *Ty = $1.PAT->get();
2176 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
2177 error("Cannot create a null initialized value of this type");
2178 $$.C = Constant::getNullValue(Ty);
2182 | SIntType EINT64VAL { // integral constants
2183 const Type *Ty = $1.T;
2184 if (!ConstantInt::isValueValidForType(Ty, $2))
2185 error("Constant value doesn't fit in type");
2186 $$.C = ConstantInt::get(Ty, $2);
2189 | UIntType EUINT64VAL { // integral constants
2190 const Type *Ty = $1.T;
2191 if (!ConstantInt::isValueValidForType(Ty, $2))
2192 error("Constant value doesn't fit in type");
2193 $$.C = ConstantInt::get(Ty, $2);
2196 | BOOL TRUETOK { // Boolean constants
2197 $$.C = ConstantInt::get(Type::Int1Ty, true);
2200 | BOOL FALSETOK { // Boolean constants
2201 $$.C = ConstantInt::get(Type::Int1Ty, false);
2204 | FPType FPVAL { // Float & Double constants
2205 if (!ConstantFP::isValueValidForType($1.T, $2))
2206 error("Floating point constant invalid for type");
2207 $$.C = ConstantFP::get($1.T, $2);
2213 : CastOps '(' ConstVal TO Types ')' {
2214 const Type* SrcTy = $3.C->getType();
2215 const Type* DstTy = $5.PAT->get();
2216 Signedness SrcSign = $3.S;
2217 Signedness DstSign = $5.S;
2218 if (!SrcTy->isFirstClassType())
2219 error("cast constant expression from a non-primitive type: '" +
2220 SrcTy->getDescription() + "'");
2221 if (!DstTy->isFirstClassType())
2222 error("cast constant expression to a non-primitive type: '" +
2223 DstTy->getDescription() + "'");
2224 $$.C = cast<Constant>(getCast($1, $3.C, SrcSign, DstTy, DstSign));
2228 | GETELEMENTPTR '(' ConstVal IndexList ')' {
2229 const Type *Ty = $3.C->getType();
2230 if (!isa<PointerType>(Ty))
2231 error("GetElementPtr requires a pointer operand");
2233 std::vector<Value*> VIndices;
2234 std::vector<Constant*> CIndices;
2235 upgradeGEPIndices($3.C->getType(), $4, VIndices, &CIndices);
2238 $$.C = ConstantExpr::getGetElementPtr($3.C, CIndices);
2241 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2242 if (!$3.C->getType()->isInteger() ||
2243 cast<IntegerType>($3.C->getType())->getBitWidth() != 1)
2244 error("Select condition must be bool type");
2245 if ($5.C->getType() != $7.C->getType())
2246 error("Select operand types must match");
2247 $$.C = ConstantExpr::getSelect($3.C, $5.C, $7.C);
2250 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
2251 const Type *Ty = $3.C->getType();
2252 if (Ty != $5.C->getType())
2253 error("Binary operator types must match");
2254 // First, make sure we're dealing with the right opcode by upgrading from
2255 // obsolete versions.
2256 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2258 // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
2259 // To retain backward compatibility with these early compilers, we emit a
2260 // cast to the appropriate integer type automatically if we are in the
2261 // broken case. See PR424 for more information.
2262 if (!isa<PointerType>(Ty)) {
2263 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2265 const Type *IntPtrTy = 0;
2266 switch (CurModule.CurrentModule->getPointerSize()) {
2267 case Module::Pointer32: IntPtrTy = Type::Int32Ty; break;
2268 case Module::Pointer64: IntPtrTy = Type::Int64Ty; break;
2269 default: error("invalid pointer binary constant expr");
2271 $$.C = ConstantExpr::get(Opcode,
2272 ConstantExpr::getCast(Instruction::PtrToInt, $3.C, IntPtrTy),
2273 ConstantExpr::getCast(Instruction::PtrToInt, $5.C, IntPtrTy));
2274 $$.C = ConstantExpr::getCast(Instruction::IntToPtr, $$.C, Ty);
2278 | LogicalOps '(' ConstVal ',' ConstVal ')' {
2279 const Type* Ty = $3.C->getType();
2280 if (Ty != $5.C->getType())
2281 error("Logical operator types must match");
2282 if (!Ty->isInteger()) {
2283 if (!isa<VectorType>(Ty) ||
2284 !cast<VectorType>(Ty)->getElementType()->isInteger())
2285 error("Logical operator requires integer operands");
2287 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2288 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2291 | SetCondOps '(' ConstVal ',' ConstVal ')' {
2292 const Type* Ty = $3.C->getType();
2293 if (Ty != $5.C->getType())
2294 error("setcc operand types must match");
2295 unsigned short pred;
2296 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $3.S);
2297 $$.C = ConstantExpr::getCompare(Opcode, $3.C, $5.C);
2300 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
2301 if ($4.C->getType() != $6.C->getType())
2302 error("icmp operand types must match");
2303 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2306 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
2307 if ($4.C->getType() != $6.C->getType())
2308 error("fcmp operand types must match");
2309 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2312 | ShiftOps '(' ConstVal ',' ConstVal ')' {
2313 if (!$5.C->getType()->isInteger() ||
2314 cast<IntegerType>($5.C->getType())->getBitWidth() != 8)
2315 error("Shift count for shift constant must be unsigned byte");
2316 const Type* Ty = $3.C->getType();
2317 if (!$3.C->getType()->isInteger())
2318 error("Shift constant expression requires integer operand");
2319 Constant *ShiftAmt = ConstantExpr::getZExt($5.C, Ty);
2320 $$.C = ConstantExpr::get(getBinaryOp($1, Ty, $3.S), $3.C, ShiftAmt);
2323 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
2324 if (!ExtractElementInst::isValidOperands($3.C, $5.C))
2325 error("Invalid extractelement operands");
2326 $$.C = ConstantExpr::getExtractElement($3.C, $5.C);
2329 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2330 if (!InsertElementInst::isValidOperands($3.C, $5.C, $7.C))
2331 error("Invalid insertelement operands");
2332 $$.C = ConstantExpr::getInsertElement($3.C, $5.C, $7.C);
2335 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2336 if (!ShuffleVectorInst::isValidOperands($3.C, $5.C, $7.C))
2337 error("Invalid shufflevector operands");
2338 $$.C = ConstantExpr::getShuffleVector($3.C, $5.C, $7.C);
2344 // ConstVector - A list of comma separated constants.
2346 : ConstVector ',' ConstVal { ($$ = $1)->push_back($3); }
2348 $$ = new std::vector<ConstInfo>();
2354 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
2356 : GLOBAL { $$ = false; }
2357 | CONSTANT { $$ = true; }
2361 //===----------------------------------------------------------------------===//
2362 // Rules to match Modules
2363 //===----------------------------------------------------------------------===//
2365 // Module rule: Capture the result of parsing the whole file into a result
2370 $$ = ParserResult = $1;
2371 CurModule.ModuleDone();
2375 // FunctionList - A list of functions, preceeded by a constant pool.
2378 : FunctionList Function { $$ = $1; CurFun.FunctionDone(); }
2379 | FunctionList FunctionProto { $$ = $1; }
2380 | FunctionList MODULE ASM_TOK AsmBlock { $$ = $1; }
2381 | FunctionList IMPLEMENTATION { $$ = $1; }
2383 $$ = CurModule.CurrentModule;
2384 // Emit an error if there are any unresolved types left.
2385 if (!CurModule.LateResolveTypes.empty()) {
2386 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
2387 if (DID.Type == ValID::NameVal) {
2388 error("Reference to an undefined type: '"+DID.getName() + "'");
2390 error("Reference to an undefined type: #" + itostr(DID.Num));
2396 // ConstPool - Constants with optional names assigned to them.
2398 : ConstPool OptAssign TYPE TypesV {
2399 // Eagerly resolve types. This is not an optimization, this is a
2400 // requirement that is due to the fact that we could have this:
2402 // %list = type { %list * }
2403 // %list = type { %list * } ; repeated type decl
2405 // If types are not resolved eagerly, then the two types will not be
2406 // determined to be the same type!
2408 const Type* Ty = $4.PAT->get();
2409 ResolveTypeTo($2, Ty);
2411 if (!setTypeName(Ty, $2) && !$2) {
2412 // If this is a named type that is not a redefinition, add it to the slot
2414 CurModule.Types.push_back(Ty);
2418 | ConstPool FunctionProto { // Function prototypes can be in const pool
2420 | ConstPool MODULE ASM_TOK AsmBlock { // Asm blocks can be in the const pool
2422 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
2424 error("Global value initializer is not a constant");
2425 CurGV = ParseGlobalVariable($2, $3, $4, $5.C->getType(), $5.C);
2426 } GlobalVarAttributes {
2429 | ConstPool OptAssign EXTERNAL GlobalType Types {
2430 const Type *Ty = $5.PAT->get();
2431 CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, Ty, 0);
2433 } GlobalVarAttributes {
2436 | ConstPool OptAssign DLLIMPORT GlobalType Types {
2437 const Type *Ty = $5.PAT->get();
2438 CurGV = ParseGlobalVariable($2, GlobalValue::DLLImportLinkage, $4, Ty, 0);
2440 } GlobalVarAttributes {
2443 | ConstPool OptAssign EXTERN_WEAK GlobalType Types {
2444 const Type *Ty = $5.PAT->get();
2446 ParseGlobalVariable($2, GlobalValue::ExternalWeakLinkage, $4, Ty, 0);
2448 } GlobalVarAttributes {
2451 | ConstPool TARGET TargetDefinition {
2453 | ConstPool DEPLIBS '=' LibrariesDefinition {
2455 | /* empty: end of list */ {
2461 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2462 char *EndStr = UnEscapeLexed($1, true);
2463 std::string NewAsm($1, EndStr);
2466 if (AsmSoFar.empty())
2467 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
2469 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
2474 : BIG { $$ = Module::BigEndian; }
2475 | LITTLE { $$ = Module::LittleEndian; }
2479 : ENDIAN '=' BigOrLittle {
2480 CurModule.setEndianness($3);
2482 | POINTERSIZE '=' EUINT64VAL {
2484 CurModule.setPointerSize(Module::Pointer32);
2486 CurModule.setPointerSize(Module::Pointer64);
2488 error("Invalid pointer size: '" + utostr($3) + "'");
2490 | TRIPLE '=' STRINGCONSTANT {
2491 CurModule.CurrentModule->setTargetTriple($3);
2494 | DATALAYOUT '=' STRINGCONSTANT {
2495 CurModule.CurrentModule->setDataLayout($3);
2505 : LibList ',' STRINGCONSTANT {
2506 CurModule.CurrentModule->addLibrary($3);
2510 CurModule.CurrentModule->addLibrary($1);
2513 | /* empty: end of list */ { }
2516 //===----------------------------------------------------------------------===//
2517 // Rules to match Function Headers
2518 //===----------------------------------------------------------------------===//
2521 : VAR_ID | STRINGCONSTANT
2526 | /*empty*/ { $$ = 0; }
2531 if ($1.PAT->get() == Type::VoidTy)
2532 error("void typed arguments are invalid");
2533 $$ = new std::pair<PATypeInfo, char*>($1, $2);
2538 : ArgListH ',' ArgVal {
2544 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2551 : ArgListH { $$ = $1; }
2552 | ArgListH ',' DOTDOTDOT {
2555 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2556 VoidTI.S = Signless;
2557 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2560 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2562 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2563 VoidTI.S = Signless;
2564 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2566 | /* empty */ { $$ = 0; }
2570 : OptCallingConv TypesV Name '(' ArgList ')' OptSection OptAlign {
2572 std::string FunctionName($3);
2573 free($3); // Free strdup'd memory!
2575 const Type* RetTy = $2.PAT->get();
2577 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
2578 error("LLVM functions cannot return aggregate types");
2580 std::vector<const Type*> ParamTyList;
2582 // In LLVM 2.0 the signatures of three varargs intrinsics changed to take
2583 // i8*. We check here for those names and override the parameter list
2584 // types to ensure the prototype is correct.
2585 if (FunctionName == "llvm.va_start" || FunctionName == "llvm.va_end") {
2586 ParamTyList.push_back(PointerType::get(Type::Int8Ty));
2587 } else if (FunctionName == "llvm.va_copy") {
2588 ParamTyList.push_back(PointerType::get(Type::Int8Ty));
2589 ParamTyList.push_back(PointerType::get(Type::Int8Ty));
2590 } else if ($5) { // If there are arguments...
2591 for (std::vector<std::pair<PATypeInfo,char*> >::iterator
2592 I = $5->begin(), E = $5->end(); I != E; ++I) {
2593 const Type *Ty = I->first.PAT->get();
2594 ParamTyList.push_back(Ty);
2598 bool isVarArg = ParamTyList.size() && ParamTyList.back() == Type::VoidTy;
2600 ParamTyList.pop_back();
2602 // Convert the CSRet calling convention into the corresponding parameter
2604 FunctionType::ParamAttrsList ParamAttrs;
2605 if ($1 == OldCallingConv::CSRet) {
2606 ParamAttrs.push_back(FunctionType::NoAttributeSet); // result
2607 ParamAttrs.push_back(FunctionType::StructRetAttribute); // first arg
2610 const FunctionType *FT = FunctionType::get(RetTy, ParamTyList, isVarArg,
2612 const PointerType *PFT = PointerType::get(FT);
2616 if (!FunctionName.empty()) {
2617 ID = ValID::create((char*)FunctionName.c_str());
2619 ID = ValID::create((int)CurModule.Values[PFT].size());
2623 Module* M = CurModule.CurrentModule;
2625 // See if this function was forward referenced. If so, recycle the object.
2626 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2627 // Move the function to the end of the list, from whereever it was
2628 // previously inserted.
2629 Fn = cast<Function>(FWRef);
2630 M->getFunctionList().remove(Fn);
2631 M->getFunctionList().push_back(Fn);
2632 } else if (!FunctionName.empty()) {
2633 GlobalValue *Conflict = M->getFunction(FunctionName);
2635 Conflict = M->getNamedGlobal(FunctionName);
2636 if (Conflict && PFT == Conflict->getType()) {
2637 if (!CurFun.isDeclare && !Conflict->isDeclaration()) {
2638 // We have two function definitions that conflict, same type, same
2639 // name. We should really check to make sure that this is the result
2640 // of integer type planes collapsing and generate an error if it is
2641 // not, but we'll just rename on the assumption that it is. However,
2642 // let's do it intelligently and rename the internal linkage one
2644 std::string NewName(makeNameUnique(FunctionName));
2645 if (Conflict->hasInternalLinkage()) {
2646 Conflict->setName(NewName);
2647 RenameMapKey Key = std::make_pair(FunctionName,Conflict->getType());
2648 CurModule.RenameMap[Key] = NewName;
2649 Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2650 InsertValue(Fn, CurModule.Values);
2652 Fn = new Function(FT, CurFun.Linkage, NewName, M);
2653 InsertValue(Fn, CurModule.Values);
2654 RenameMapKey Key = std::make_pair(FunctionName,PFT);
2655 CurModule.RenameMap[Key] = NewName;
2658 // If they are not both definitions, then just use the function we
2659 // found since the types are the same.
2660 Fn = cast<Function>(Conflict);
2662 // Make sure to strip off any argument names so we can't get
2664 if (Fn->isDeclaration())
2665 for (Function::arg_iterator AI = Fn->arg_begin(),
2666 AE = Fn->arg_end(); AI != AE; ++AI)
2669 } else if (Conflict) {
2670 // We have two globals with the same name and different types.
2671 // Previously, this was permitted because the symbol table had
2672 // "type planes" and names only needed to be distinct within a
2673 // type plane. After PR411 was fixed, this is no loner the case.
2674 // To resolve this we must rename one of the two.
2675 if (Conflict->hasInternalLinkage()) {
2676 // We can safely renamed the Conflict.
2677 Conflict->setName(makeNameUnique(Conflict->getName()));
2678 RenameMapKey Key = std::make_pair(FunctionName,Conflict->getType());
2679 CurModule.RenameMap[Key] = Conflict->getName();
2680 Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2681 InsertValue(Fn, CurModule.Values);
2682 } else if (CurFun.Linkage == GlobalValue::InternalLinkage) {
2683 // We can safely rename the function we're defining
2684 std::string NewName = makeNameUnique(FunctionName);
2685 Fn = new Function(FT, CurFun.Linkage, NewName, M);
2686 InsertValue(Fn, CurModule.Values);
2687 RenameMapKey Key = std::make_pair(FunctionName,PFT);
2688 CurModule.RenameMap[Key] = NewName;
2690 // We can't quietly rename either of these things, but we must
2691 // rename one of them. Generate a warning about the renaming and
2692 // elect to rename the thing we're now defining.
2693 std::string NewName = makeNameUnique(FunctionName);
2694 warning("Renaming function '" + FunctionName + "' as '" + NewName +
2695 "' may cause linkage errors");
2696 Fn = new Function(FT, CurFun.Linkage, NewName, M);
2697 InsertValue(Fn, CurModule.Values);
2698 RenameMapKey Key = std::make_pair(FunctionName,PFT);
2699 CurModule.RenameMap[Key] = NewName;
2702 // There's no conflict, just define the function
2703 Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2704 InsertValue(Fn, CurModule.Values);
2708 CurFun.FunctionStart(Fn);
2710 if (CurFun.isDeclare) {
2711 // If we have declaration, always overwrite linkage. This will allow us
2712 // to correctly handle cases, when pointer to function is passed as
2713 // argument to another function.
2714 Fn->setLinkage(CurFun.Linkage);
2716 Fn->setCallingConv(upgradeCallingConv($1));
2717 Fn->setAlignment($8);
2723 // Add all of the arguments we parsed to the function...
2724 if ($5) { // Is null if empty...
2725 if (isVarArg) { // Nuke the last entry
2726 assert($5->back().first.PAT->get() == Type::VoidTy &&
2727 $5->back().second == 0 && "Not a varargs marker");
2728 delete $5->back().first.PAT;
2729 $5->pop_back(); // Delete the last entry
2731 Function::arg_iterator ArgIt = Fn->arg_begin();
2732 Function::arg_iterator ArgEnd = Fn->arg_end();
2733 std::vector<std::pair<PATypeInfo,char*> >::iterator I = $5->begin();
2734 std::vector<std::pair<PATypeInfo,char*> >::iterator E = $5->end();
2735 for ( ; I != E && ArgIt != ArgEnd; ++I, ++ArgIt) {
2736 delete I->first.PAT; // Delete the typeholder...
2737 setValueName(ArgIt, I->second); // Insert arg into symtab...
2740 delete $5; // We're now done with the argument list
2746 : BEGINTOK | '{' // Allow BEGIN or '{' to start a function
2750 : OptLinkage FunctionHeaderH BEGIN {
2751 $$ = CurFun.CurrentFunction;
2753 // Make sure that we keep track of the linkage type even if there was a
2754 // previous "declare".
2760 : ENDTOK | '}' // Allow end of '}' to end a function
2764 : BasicBlockList END {
2769 : /*default*/ { $$ = GlobalValue::ExternalLinkage; }
2770 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
2771 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
2775 : DECLARE { CurFun.isDeclare = true; }
2776 FnDeclareLinkage { CurFun.Linkage = $3; } FunctionHeaderH {
2777 $$ = CurFun.CurrentFunction;
2778 CurFun.FunctionDone();
2783 //===----------------------------------------------------------------------===//
2784 // Rules to match Basic Blocks
2785 //===----------------------------------------------------------------------===//
2788 : /* empty */ { $$ = false; }
2789 | SIDEEFFECT { $$ = true; }
2793 // A reference to a direct constant
2794 : ESINT64VAL { $$ = ValID::create($1); }
2795 | EUINT64VAL { $$ = ValID::create($1); }
2796 | FPVAL { $$ = ValID::create($1); }
2797 | TRUETOK { $$ = ValID::create(ConstantInt::get(Type::Int1Ty, true)); }
2798 | FALSETOK { $$ = ValID::create(ConstantInt::get(Type::Int1Ty, false)); }
2799 | NULL_TOK { $$ = ValID::createNull(); }
2800 | UNDEF { $$ = ValID::createUndef(); }
2801 | ZEROINITIALIZER { $$ = ValID::createZeroInit(); }
2802 | '<' ConstVector '>' { // Nonempty unsized packed vector
2803 const Type *ETy = (*$2)[0].C->getType();
2804 int NumElements = $2->size();
2805 VectorType* pt = VectorType::get(ETy, NumElements);
2806 PATypeHolder* PTy = new PATypeHolder(
2807 HandleUpRefs(VectorType::get(ETy, NumElements)));
2809 // Verify all elements are correct type!
2810 std::vector<Constant*> Elems;
2811 for (unsigned i = 0; i < $2->size(); i++) {
2812 Constant *C = (*$2)[i].C;
2813 const Type *CTy = C->getType();
2815 error("Element #" + utostr(i) + " is not of type '" +
2816 ETy->getDescription() +"' as required!\nIt is of type '" +
2817 CTy->getDescription() + "'");
2820 $$ = ValID::create(ConstantVector::get(pt, Elems));
2821 delete PTy; delete $2;
2824 $$ = ValID::create($1.C);
2826 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2827 char *End = UnEscapeLexed($3, true);
2828 std::string AsmStr = std::string($3, End);
2829 End = UnEscapeLexed($5, true);
2830 std::string Constraints = std::string($5, End);
2831 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2837 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2841 : INTVAL { $$ = ValID::create($1); }
2842 | Name { $$ = ValID::create($1); }
2845 // ValueRef - A reference to a definition... either constant or symbolic
2847 : SymbolicValueRef | ConstValueRef
2851 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2852 // type immediately preceeds the value reference, and allows complex constant
2853 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2856 const Type *Ty = $1.PAT->get();
2858 $$.V = getVal(Ty, $2);
2864 : BasicBlockList BasicBlock {
2867 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2872 // Basic blocks are terminated by branching instructions:
2873 // br, br/cc, switch, ret
2876 : InstructionList OptAssign BBTerminatorInst {
2877 setValueName($3, $2);
2879 $1->getInstList().push_back($3);
2886 : InstructionList Inst {
2888 $1->getInstList().push_back($2.I);
2892 $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
2893 // Make sure to move the basic block to the correct location in the
2894 // function, instead of leaving it inserted wherever it was first
2896 Function::BasicBlockListType &BBL =
2897 CurFun.CurrentFunction->getBasicBlockList();
2898 BBL.splice(BBL.end(), BBL, $$);
2901 $$ = CurBB = getBBVal(ValID::create($1), true);
2902 // Make sure to move the basic block to the correct location in the
2903 // function, instead of leaving it inserted wherever it was first
2905 Function::BasicBlockListType &BBL =
2906 CurFun.CurrentFunction->getBasicBlockList();
2907 BBL.splice(BBL.end(), BBL, $$);
2911 Unwind : UNWIND | EXCEPT;
2914 : RET ResolvedVal { // Return with a result...
2915 $$ = new ReturnInst($2.V);
2917 | RET VOID { // Return with no result...
2918 $$ = new ReturnInst();
2920 | BR LABEL ValueRef { // Unconditional Branch...
2921 BasicBlock* tmpBB = getBBVal($3);
2922 $$ = new BranchInst(tmpBB);
2923 } // Conditional Branch...
2924 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2925 BasicBlock* tmpBBA = getBBVal($6);
2926 BasicBlock* tmpBBB = getBBVal($9);
2927 Value* tmpVal = getVal(Type::Int1Ty, $3);
2928 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2930 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2931 Value* tmpVal = getVal($2.T, $3);
2932 BasicBlock* tmpBB = getBBVal($6);
2933 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2935 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2937 for (; I != E; ++I) {
2938 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2939 S->addCase(CI, I->second);
2941 error("Switch case is constant, but not a simple integer");
2945 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2946 Value* tmpVal = getVal($2.T, $3);
2947 BasicBlock* tmpBB = getBBVal($6);
2948 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2951 | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
2952 TO LABEL ValueRef Unwind LABEL ValueRef {
2953 const PointerType *PFTy;
2954 const FunctionType *Ty;
2956 if (!(PFTy = dyn_cast<PointerType>($3.PAT->get())) ||
2957 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2958 // Pull out the types of all of the arguments...
2959 std::vector<const Type*> ParamTypes;
2961 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
2963 ParamTypes.push_back((*I).V->getType());
2965 FunctionType::ParamAttrsList ParamAttrs;
2966 if ($2 == OldCallingConv::CSRet) {
2967 ParamAttrs.push_back(FunctionType::NoAttributeSet);
2968 ParamAttrs.push_back(FunctionType::StructRetAttribute);
2970 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2971 if (isVarArg) ParamTypes.pop_back();
2972 Ty = FunctionType::get($3.PAT->get(), ParamTypes, isVarArg, ParamAttrs);
2973 PFTy = PointerType::get(Ty);
2975 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2976 BasicBlock *Normal = getBBVal($10);
2977 BasicBlock *Except = getBBVal($13);
2979 // Create the call node...
2980 if (!$6) { // Has no arguments?
2981 $$ = new InvokeInst(V, Normal, Except, 0, 0);
2982 } else { // Has arguments?
2983 // Loop through FunctionType's arguments and ensure they are specified
2986 FunctionType::param_iterator I = Ty->param_begin();
2987 FunctionType::param_iterator E = Ty->param_end();
2988 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
2990 std::vector<Value*> Args;
2991 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2992 if ((*ArgI).V->getType() != *I)
2993 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
2994 (*I)->getDescription() + "'");
2995 Args.push_back((*ArgI).V);
2998 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2999 error("Invalid number of parameters detected");
3001 $$ = new InvokeInst(V, Normal, Except, &Args[0], Args.size());
3003 cast<InvokeInst>($$)->setCallingConv(upgradeCallingConv($2));
3008 $$ = new UnwindInst();
3011 $$ = new UnreachableInst();
3016 : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
3018 Constant *V = cast<Constant>(getExistingValue($2.T, $3));
3021 error("May only switch on a constant pool value");
3023 BasicBlock* tmpBB = getBBVal($6);
3024 $$->push_back(std::make_pair(V, tmpBB));
3026 | IntType ConstValueRef ',' LABEL ValueRef {
3027 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
3028 Constant *V = cast<Constant>(getExistingValue($1.T, $2));
3031 error("May only switch on a constant pool value");
3033 BasicBlock* tmpBB = getBBVal($5);
3034 $$->push_back(std::make_pair(V, tmpBB));
3039 : OptAssign InstVal {
3042 if (BitCastInst *BCI = dyn_cast<BitCastInst>($2.I))
3043 if (BCI->getSrcTy() == BCI->getDestTy() &&
3044 BCI->getOperand(0)->getName() == $1)
3045 // This is a useless bit cast causing a name redefinition. It is
3046 // a bit cast from a type to the same type of an operand with the
3047 // same name as the name we would give this instruction. Since this
3048 // instruction results in no code generation, it is safe to omit
3049 // the instruction. This situation can occur because of collapsed
3050 // type planes. For example:
3051 // %X = add int %Y, %Z
3052 // %X = cast int %Y to uint
3053 // After upgrade, this looks like:
3054 // %X = add i32 %Y, %Z
3055 // %X = bitcast i32 to i32
3056 // The bitcast is clearly useless so we omit it.
3062 setValueName($2.I, $1);
3068 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
3069 $$.P = new std::list<std::pair<Value*, BasicBlock*> >();
3071 Value* tmpVal = getVal($1.PAT->get(), $3);
3072 BasicBlock* tmpBB = getBBVal($5);
3073 $$.P->push_back(std::make_pair(tmpVal, tmpBB));
3076 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
3078 Value* tmpVal = getVal($1.P->front().first->getType(), $4);
3079 BasicBlock* tmpBB = getBBVal($6);
3080 $1.P->push_back(std::make_pair(tmpVal, tmpBB));
3084 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
3085 $$ = new std::vector<ValueInfo>();
3088 | ValueRefList ',' ResolvedVal {
3093 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
3096 | /*empty*/ { $$ = 0; }
3109 : ArithmeticOps Types ValueRef ',' ValueRef {
3110 const Type* Ty = $2.PAT->get();
3111 if (!Ty->isInteger() && !Ty->isFloatingPoint() && !isa<VectorType>(Ty))
3112 error("Arithmetic operator requires integer, FP, or packed operands");
3113 if (isa<VectorType>(Ty) &&
3114 ($1 == URemOp || $1 == SRemOp || $1 == FRemOp || $1 == RemOp))
3115 error("Remainder not supported on vector types");
3116 // Upgrade the opcode from obsolete versions before we do anything with it.
3117 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3118 Value* val1 = getVal(Ty, $3);
3119 Value* val2 = getVal(Ty, $5);
3120 $$.I = BinaryOperator::create(Opcode, val1, val2);
3122 error("binary operator returned null");
3126 | LogicalOps Types ValueRef ',' ValueRef {
3127 const Type *Ty = $2.PAT->get();
3128 if (!Ty->isInteger()) {
3129 if (!isa<VectorType>(Ty) ||
3130 !cast<VectorType>(Ty)->getElementType()->isInteger())
3131 error("Logical operator requires integral operands");
3133 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3134 Value* tmpVal1 = getVal(Ty, $3);
3135 Value* tmpVal2 = getVal(Ty, $5);
3136 $$.I = BinaryOperator::create(Opcode, tmpVal1, tmpVal2);
3138 error("binary operator returned null");
3142 | SetCondOps Types ValueRef ',' ValueRef {
3143 const Type* Ty = $2.PAT->get();
3144 if(isa<VectorType>(Ty))
3145 error("VectorTypes currently not supported in setcc instructions");
3146 unsigned short pred;
3147 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $2.S);
3148 Value* tmpVal1 = getVal(Ty, $3);
3149 Value* tmpVal2 = getVal(Ty, $5);
3150 $$.I = CmpInst::create(Opcode, pred, tmpVal1, tmpVal2);
3152 error("binary operator returned null");
3156 | ICMP IPredicates Types ValueRef ',' ValueRef {
3157 const Type *Ty = $3.PAT->get();
3158 if (isa<VectorType>(Ty))
3159 error("VectorTypes currently not supported in icmp instructions");
3160 else if (!Ty->isInteger() && !isa<PointerType>(Ty))
3161 error("icmp requires integer or pointer typed operands");
3162 Value* tmpVal1 = getVal(Ty, $4);
3163 Value* tmpVal2 = getVal(Ty, $6);
3164 $$.I = new ICmpInst($2, tmpVal1, tmpVal2);
3168 | FCMP FPredicates Types ValueRef ',' ValueRef {
3169 const Type *Ty = $3.PAT->get();
3170 if (isa<VectorType>(Ty))
3171 error("VectorTypes currently not supported in fcmp instructions");
3172 else if (!Ty->isFloatingPoint())
3173 error("fcmp instruction requires floating point operands");
3174 Value* tmpVal1 = getVal(Ty, $4);
3175 Value* tmpVal2 = getVal(Ty, $6);
3176 $$.I = new FCmpInst($2, tmpVal1, tmpVal2);
3181 warning("Use of obsolete 'not' instruction: Replacing with 'xor");
3182 const Type *Ty = $2.V->getType();
3183 Value *Ones = ConstantInt::getAllOnesValue(Ty);
3185 error("Expected integral type for not instruction");
3186 $$.I = BinaryOperator::create(Instruction::Xor, $2.V, Ones);
3188 error("Could not create a xor instruction");
3191 | ShiftOps ResolvedVal ',' ResolvedVal {
3192 if (!$4.V->getType()->isInteger() ||
3193 cast<IntegerType>($4.V->getType())->getBitWidth() != 8)
3194 error("Shift amount must be int8");
3195 const Type* Ty = $2.V->getType();
3196 if (!Ty->isInteger())
3197 error("Shift constant expression requires integer operand");
3198 Value* ShiftAmt = 0;
3199 if (cast<IntegerType>(Ty)->getBitWidth() > Type::Int8Ty->getBitWidth())
3200 if (Constant *C = dyn_cast<Constant>($4.V))
3201 ShiftAmt = ConstantExpr::getZExt(C, Ty);
3203 ShiftAmt = new ZExtInst($4.V, Ty, makeNameUnique("shift"), CurBB);
3206 $$.I = BinaryOperator::create(getBinaryOp($1, Ty, $2.S), $2.V, ShiftAmt);
3209 | CastOps ResolvedVal TO Types {
3210 const Type *DstTy = $4.PAT->get();
3211 if (!DstTy->isFirstClassType())
3212 error("cast instruction to a non-primitive type: '" +
3213 DstTy->getDescription() + "'");
3214 $$.I = cast<Instruction>(getCast($1, $2.V, $2.S, DstTy, $4.S, true));
3218 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3219 if (!$2.V->getType()->isInteger() ||
3220 cast<IntegerType>($2.V->getType())->getBitWidth() != 1)
3221 error("select condition must be bool");
3222 if ($4.V->getType() != $6.V->getType())
3223 error("select value types should match");
3224 $$.I = new SelectInst($2.V, $4.V, $6.V);
3227 | VAARG ResolvedVal ',' Types {
3228 const Type *Ty = $4.PAT->get();
3230 $$.I = new VAArgInst($2.V, Ty);
3234 | VAARG_old ResolvedVal ',' Types {
3235 const Type* ArgTy = $2.V->getType();
3236 const Type* DstTy = $4.PAT->get();
3237 ObsoleteVarArgs = true;
3238 Function* NF = cast<Function>(CurModule.CurrentModule->
3239 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3242 //foo = alloca 1 of t
3246 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
3247 CurBB->getInstList().push_back(foo);
3248 CallInst* bar = new CallInst(NF, $2.V);
3249 CurBB->getInstList().push_back(bar);
3250 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3251 $$.I = new VAArgInst(foo, DstTy);
3255 | VANEXT_old ResolvedVal ',' Types {
3256 const Type* ArgTy = $2.V->getType();
3257 const Type* DstTy = $4.PAT->get();
3258 ObsoleteVarArgs = true;
3259 Function* NF = cast<Function>(CurModule.CurrentModule->
3260 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3262 //b = vanext a, t ->
3263 //foo = alloca 1 of t
3266 //tmp = vaarg foo, t
3268 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
3269 CurBB->getInstList().push_back(foo);
3270 CallInst* bar = new CallInst(NF, $2.V);
3271 CurBB->getInstList().push_back(bar);
3272 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3273 Instruction* tmp = new VAArgInst(foo, DstTy);
3274 CurBB->getInstList().push_back(tmp);
3275 $$.I = new LoadInst(foo);
3279 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
3280 if (!ExtractElementInst::isValidOperands($2.V, $4.V))
3281 error("Invalid extractelement operands");
3282 $$.I = new ExtractElementInst($2.V, $4.V);
3285 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3286 if (!InsertElementInst::isValidOperands($2.V, $4.V, $6.V))
3287 error("Invalid insertelement operands");
3288 $$.I = new InsertElementInst($2.V, $4.V, $6.V);
3291 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3292 if (!ShuffleVectorInst::isValidOperands($2.V, $4.V, $6.V))
3293 error("Invalid shufflevector operands");
3294 $$.I = new ShuffleVectorInst($2.V, $4.V, $6.V);
3298 const Type *Ty = $2.P->front().first->getType();
3299 if (!Ty->isFirstClassType())
3300 error("PHI node operands must be of first class type");
3301 PHINode *PHI = new PHINode(Ty);
3302 PHI->reserveOperandSpace($2.P->size());
3303 while ($2.P->begin() != $2.P->end()) {
3304 if ($2.P->front().first->getType() != Ty)
3305 error("All elements of a PHI node must be of the same type");
3306 PHI->addIncoming($2.P->front().first, $2.P->front().second);
3311 delete $2.P; // Free the list...
3313 | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')' {
3315 // Handle the short call syntax
3316 const PointerType *PFTy;
3317 const FunctionType *FTy;
3318 if (!(PFTy = dyn_cast<PointerType>($3.PAT->get())) ||
3319 !(FTy = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3320 // Pull out the types of all of the arguments...
3321 std::vector<const Type*> ParamTypes;
3323 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
3325 ParamTypes.push_back((*I).V->getType());
3328 FunctionType::ParamAttrsList ParamAttrs;
3329 if ($2 == OldCallingConv::CSRet) {
3330 ParamAttrs.push_back(FunctionType::NoAttributeSet);
3331 ParamAttrs.push_back(FunctionType::StructRetAttribute);
3333 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
3334 if (isVarArg) ParamTypes.pop_back();
3336 const Type *RetTy = $3.PAT->get();
3337 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
3338 error("Functions cannot return aggregate types");
3340 FTy = FunctionType::get(RetTy, ParamTypes, isVarArg, ParamAttrs);
3341 PFTy = PointerType::get(FTy);
3344 // First upgrade any intrinsic calls.
3345 std::vector<Value*> Args;
3347 for (unsigned i = 0, e = $6->size(); i < e; ++i)
3348 Args.push_back((*$6)[i].V);
3349 Instruction *Inst = upgradeIntrinsicCall(FTy, $4, Args);
3351 // If we got an upgraded intrinsic
3356 // Get the function we're calling
3357 Value *V = getVal(PFTy, $4);
3359 // Check the argument values match
3360 if (!$6) { // Has no arguments?
3361 // Make sure no arguments is a good thing!
3362 if (FTy->getNumParams() != 0)
3363 error("No arguments passed to a function that expects arguments");
3364 } else { // Has arguments?
3365 // Loop through FunctionType's arguments and ensure they are specified
3368 FunctionType::param_iterator I = FTy->param_begin();
3369 FunctionType::param_iterator E = FTy->param_end();
3370 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
3372 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
3373 if ((*ArgI).V->getType() != *I)
3374 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
3375 (*I)->getDescription() + "'");
3377 if (I != E || (ArgI != ArgE && !FTy->isVarArg()))
3378 error("Invalid number of parameters detected");
3381 // Create the call instruction
3382 CallInst *CI = new CallInst(V, &Args[0], Args.size());
3383 CI->setTailCall($1);
3384 CI->setCallingConv(upgradeCallingConv($2));
3397 // IndexList - List of indices for GEP based instructions...
3399 : ',' ValueRefList { $$ = $2; }
3400 | /* empty */ { $$ = new std::vector<ValueInfo>(); }
3404 : VOLATILE { $$ = true; }
3405 | /* empty */ { $$ = false; }
3409 : MALLOC Types OptCAlign {
3410 const Type *Ty = $2.PAT->get();
3412 $$.I = new MallocInst(Ty, 0, $3);
3415 | MALLOC Types ',' UINT ValueRef OptCAlign {
3416 const Type *Ty = $2.PAT->get();
3418 $$.I = new MallocInst(Ty, getVal($4.T, $5), $6);
3421 | ALLOCA Types OptCAlign {
3422 const Type *Ty = $2.PAT->get();
3424 $$.I = new AllocaInst(Ty, 0, $3);
3427 | ALLOCA Types ',' UINT ValueRef OptCAlign {
3428 const Type *Ty = $2.PAT->get();
3430 $$.I = new AllocaInst(Ty, getVal($4.T, $5), $6);
3433 | FREE ResolvedVal {
3434 const Type *PTy = $2.V->getType();
3435 if (!isa<PointerType>(PTy))
3436 error("Trying to free nonpointer type '" + PTy->getDescription() + "'");
3437 $$.I = new FreeInst($2.V);
3440 | OptVolatile LOAD Types ValueRef {
3441 const Type* Ty = $3.PAT->get();
3443 if (!isa<PointerType>(Ty))
3444 error("Can't load from nonpointer type: " + Ty->getDescription());
3445 if (!cast<PointerType>(Ty)->getElementType()->isFirstClassType())
3446 error("Can't load from pointer of non-first-class type: " +
3447 Ty->getDescription());
3448 Value* tmpVal = getVal(Ty, $4);
3449 $$.I = new LoadInst(tmpVal, "", $1);
3452 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
3453 const PointerType *PTy = dyn_cast<PointerType>($5.PAT->get());
3455 error("Can't store to a nonpointer type: " +
3456 $5.PAT->get()->getDescription());
3457 const Type *ElTy = PTy->getElementType();
3458 Value *StoreVal = $3.V;
3459 Value* tmpVal = getVal(PTy, $6);
3460 if (ElTy != $3.V->getType()) {
3461 StoreVal = handleSRetFuncTypeMerge($3.V, ElTy);
3463 error("Can't store '" + $3.V->getType()->getDescription() +
3464 "' into space of type '" + ElTy->getDescription() + "'");
3466 PTy = PointerType::get(StoreVal->getType());
3467 if (Constant *C = dyn_cast<Constant>(tmpVal))
3468 tmpVal = ConstantExpr::getBitCast(C, PTy);
3470 tmpVal = new BitCastInst(tmpVal, PTy, "upgrd.cast", CurBB);
3473 $$.I = new StoreInst(StoreVal, tmpVal, $1);
3477 | GETELEMENTPTR Types ValueRef IndexList {
3478 const Type* Ty = $2.PAT->get();
3479 if (!isa<PointerType>(Ty))
3480 error("getelementptr insn requires pointer operand");
3482 std::vector<Value*> VIndices;
3483 upgradeGEPIndices(Ty, $4, VIndices);
3485 Value* tmpVal = getVal(Ty, $3);
3486 $$.I = new GetElementPtrInst(tmpVal, &VIndices[0], VIndices.size());
3495 int yyerror(const char *ErrorMsg) {
3497 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3498 + ":" + llvm::utostr((unsigned) Upgradelineno) + ": ";
3499 std::string errMsg = where + "error: " + std::string(ErrorMsg);
3500 if (yychar != YYEMPTY && yychar != 0)
3501 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3503 std::cerr << "llvm-upgrade: " << errMsg << '\n';
3504 std::cout << "llvm-upgrade: parse failed.\n";
3508 void warning(const std::string& ErrorMsg) {
3510 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3511 + ":" + llvm::utostr((unsigned) Upgradelineno) + ": ";
3512 std::string errMsg = where + "warning: " + std::string(ErrorMsg);
3513 if (yychar != YYEMPTY && yychar != 0)
3514 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3516 std::cerr << "llvm-upgrade: " << errMsg << '\n';
3519 void error(const std::string& ErrorMsg, int LineNo) {
3520 if (LineNo == -1) LineNo = Upgradelineno;
3521 Upgradelineno = LineNo;
3522 yyerror(ErrorMsg.c_str());