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,TypeInfo> 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)
289 bool TypesDifferOnlyBySRet(Value *V, const Type* Ty) {
290 if (V->getType() == Ty)
292 const PointerType *PF1 = dyn_cast<PointerType>(Ty);
293 const PointerType *PF2 = dyn_cast<PointerType>(V->getType());
295 const FunctionType* FT1 = dyn_cast<FunctionType>(PF1->getElementType());
296 const FunctionType* FT2 = dyn_cast<FunctionType>(PF2->getElementType());
298 return FuncTysDifferOnlyBySRet(FT1, FT2);
303 // The upgrade of csretcc to sret param attribute may have caused a function
304 // to not be found because the param attribute changed the type of the called
305 // function. This helper function, used in getExistingValue, detects that
306 // situation and bitcasts the function to the correct type.
307 static Value* handleSRetFuncTypeMerge(Value *V, const Type* Ty) {
308 // Handle degenerate cases
311 if (V->getType() == Ty)
315 const PointerType *PF1 = dyn_cast<PointerType>(Ty);
316 const PointerType *PF2 = dyn_cast<PointerType>(V->getType());
318 const FunctionType *FT1 = dyn_cast<FunctionType>(PF1->getElementType());
319 const FunctionType *FT2 = dyn_cast<FunctionType>(PF2->getElementType());
320 if (FT1 && FT2 && FuncTysDifferOnlyBySRet(FT1, FT2))
321 if (FT2->paramHasAttr(1, FunctionType::StructRetAttribute))
323 else if (Constant *C = dyn_cast<Constant>(V))
324 Result = ConstantExpr::getBitCast(C, PF1);
326 Result = new BitCastInst(V, PF1, "upgrd.cast", CurBB);
331 // getExistingValue - Look up the value specified by the provided type and
332 // the provided ValID. If the value exists and has already been defined, return
333 // it. Otherwise return null.
335 static Value *getExistingValue(const Type *Ty, const ValID &D) {
336 if (isa<FunctionType>(Ty)) {
337 error("Functions are not values and must be referenced as pointers");
341 case ValID::NumberVal: { // Is it a numbered definition?
342 unsigned Num = (unsigned)D.Num;
344 // Module constants occupy the lowest numbered slots...
345 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
346 if (VI != CurModule.Values.end()) {
347 if (Num < VI->second.size())
348 return VI->second[Num];
349 Num -= VI->second.size();
352 // Make sure that our type is within bounds
353 VI = CurFun.Values.find(Ty);
354 if (VI == CurFun.Values.end()) return 0;
356 // Check that the number is within bounds...
357 if (VI->second.size() <= Num) return 0;
359 return VI->second[Num];
362 case ValID::NameVal: { // Is it a named definition?
363 // Get the name out of the ID
364 std::string Name(D.Name);
366 TypeInfo TI; TI.T = Ty; TI.S = D.S;
367 RenameMapKey Key = std::make_pair(Name, TI);
368 if (inFunctionScope()) {
369 // See if the name was renamed
370 RenameMapType::const_iterator I = CurFun.RenameMap.find(Key);
371 std::string LookupName;
372 if (I != CurFun.RenameMap.end())
373 LookupName = I->second;
376 ValueSymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
377 V = SymTab.lookup(LookupName);
378 V = handleSRetFuncTypeMerge(V, Ty);
379 assert((!V || TypesDifferOnlyBySRet(V, Ty)) && "Found wrong type!");
382 RenameMapType::const_iterator I = CurModule.RenameMap.find(Key);
383 std::string LookupName;
384 if (I != CurModule.RenameMap.end())
385 LookupName = I->second;
388 V = CurModule.CurrentModule->getValueSymbolTable().lookup(LookupName);
389 V = handleSRetFuncTypeMerge(V, Ty);
390 assert((!V || TypesDifferOnlyBySRet(V, Ty)) && "Found wrong type!");
395 D.destroy(); // Free old strdup'd memory...
399 // Check to make sure that "Ty" is an integral type, and that our
400 // value will fit into the specified type...
401 case ValID::ConstSIntVal: // Is it a constant pool reference??
402 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
403 error("Signed integral constant '" + itostr(D.ConstPool64) +
404 "' is invalid for type '" + Ty->getDescription() + "'");
406 return ConstantInt::get(Ty, D.ConstPool64);
408 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
409 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
410 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64))
411 error("Integral constant '" + utostr(D.UConstPool64) +
412 "' is invalid or out of range");
413 else // This is really a signed reference. Transmogrify.
414 return ConstantInt::get(Ty, D.ConstPool64);
416 return ConstantInt::get(Ty, D.UConstPool64);
418 case ValID::ConstFPVal: // Is it a floating point const pool reference?
419 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
420 error("FP constant invalid for type");
421 return ConstantFP::get(Ty, D.ConstPoolFP);
423 case ValID::ConstNullVal: // Is it a null value?
424 if (!isa<PointerType>(Ty))
425 error("Cannot create a a non pointer null");
426 return ConstantPointerNull::get(cast<PointerType>(Ty));
428 case ValID::ConstUndefVal: // Is it an undef value?
429 return UndefValue::get(Ty);
431 case ValID::ConstZeroVal: // Is it a zero value?
432 return Constant::getNullValue(Ty);
434 case ValID::ConstantVal: // Fully resolved constant?
435 if (D.ConstantValue->getType() != Ty)
436 error("Constant expression type different from required type");
437 return D.ConstantValue;
439 case ValID::InlineAsmVal: { // Inline asm expression
440 const PointerType *PTy = dyn_cast<PointerType>(Ty);
441 const FunctionType *FTy =
442 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
443 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints))
444 error("Invalid type for asm constraint string");
445 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
446 D.IAD->HasSideEffects);
447 D.destroy(); // Free InlineAsmDescriptor.
451 assert(0 && "Unhandled case");
455 assert(0 && "Unhandled case");
459 // getVal - This function is identical to getExistingValue, except that if a
460 // value is not already defined, it "improvises" by creating a placeholder var
461 // that looks and acts just like the requested variable. When the value is
462 // defined later, all uses of the placeholder variable are replaced with the
465 static Value *getVal(const Type *Ty, const ValID &ID) {
466 if (Ty == Type::LabelTy)
467 error("Cannot use a basic block here");
469 // See if the value has already been defined.
470 Value *V = getExistingValue(Ty, ID);
473 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty))
474 error("Invalid use of a composite type");
476 // If we reached here, we referenced either a symbol that we don't know about
477 // or an id number that hasn't been read yet. We may be referencing something
478 // forward, so just create an entry to be resolved later and get to it...
479 V = new Argument(Ty);
481 // Remember where this forward reference came from. FIXME, shouldn't we try
482 // to recycle these things??
483 CurModule.PlaceHolderInfo.insert(
484 std::make_pair(V, std::make_pair(ID, Upgradelineno)));
486 if (inFunctionScope())
487 InsertValue(V, CurFun.LateResolveValues);
489 InsertValue(V, CurModule.LateResolveValues);
493 /// @brief This just makes any name given to it unique, up to MAX_UINT times.
494 static std::string makeNameUnique(const std::string& Name) {
495 static unsigned UniqueNameCounter = 1;
496 std::string Result(Name);
497 Result += ".upgrd." + llvm::utostr(UniqueNameCounter++);
501 /// getBBVal - This is used for two purposes:
502 /// * If isDefinition is true, a new basic block with the specified ID is being
504 /// * If isDefinition is true, this is a reference to a basic block, which may
505 /// or may not be a forward reference.
507 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
508 assert(inFunctionScope() && "Can't get basic block at global scope");
514 error("Illegal label reference " + ID.getName());
516 case ValID::NumberVal: // Is it a numbered definition?
517 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
518 CurFun.NumberedBlocks.resize(ID.Num+1);
519 BB = CurFun.NumberedBlocks[ID.Num];
521 case ValID::NameVal: // Is it a named definition?
523 if (Value *N = CurFun.CurrentFunction->
524 getValueSymbolTable().lookup(Name)) {
525 if (N->getType() != Type::LabelTy) {
526 // Register names didn't use to conflict with basic block names
527 // because of type planes. Now they all have to be unique. So, we just
528 // rename the register and treat this name as if no basic block
530 TypeInfo TI; TI.T = N->getType(); TI.S = ID.S;
531 RenameMapKey Key = std::make_pair(N->getName(),TI);
532 N->setName(makeNameUnique(N->getName()));
533 CurModule.RenameMap[Key] = N->getName();
536 BB = cast<BasicBlock>(N);
542 // See if the block has already been defined.
544 // If this is the definition of the block, make sure the existing value was
545 // just a forward reference. If it was a forward reference, there will be
546 // an entry for it in the PlaceHolderInfo map.
547 if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
548 // The existing value was a definition, not a forward reference.
549 error("Redefinition of label " + ID.getName());
551 ID.destroy(); // Free strdup'd memory.
555 // Otherwise this block has not been seen before.
556 BB = new BasicBlock("", CurFun.CurrentFunction);
557 if (ID.Type == ValID::NameVal) {
558 BB->setName(ID.Name);
560 CurFun.NumberedBlocks[ID.Num] = BB;
563 // If this is not a definition, keep track of it so we can use it as a forward
566 // Remember where this forward reference came from.
567 CurFun.BBForwardRefs[BB] = std::make_pair(ID, Upgradelineno);
569 // The forward declaration could have been inserted anywhere in the
570 // function: insert it into the correct place now.
571 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
572 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
579 //===----------------------------------------------------------------------===//
580 // Code to handle forward references in instructions
581 //===----------------------------------------------------------------------===//
583 // This code handles the late binding needed with statements that reference
584 // values not defined yet... for example, a forward branch, or the PHI node for
587 // This keeps a table (CurFun.LateResolveValues) of all such forward references
588 // and back patchs after we are done.
591 // ResolveDefinitions - If we could not resolve some defs at parsing
592 // time (forward branches, phi functions for loops, etc...) resolve the
596 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
597 std::map<const Type*,ValueList> *FutureLateResolvers) {
599 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
600 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
601 E = LateResolvers.end(); LRI != E; ++LRI) {
602 const Type* Ty = LRI->first;
603 ValueList &List = LRI->second;
604 while (!List.empty()) {
605 Value *V = List.back();
608 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
609 CurModule.PlaceHolderInfo.find(V);
610 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error");
612 ValID &DID = PHI->second.first;
614 Value *TheRealValue = getExistingValue(Ty, DID);
616 V->replaceAllUsesWith(TheRealValue);
618 CurModule.PlaceHolderInfo.erase(PHI);
619 } else if (FutureLateResolvers) {
620 // Functions have their unresolved items forwarded to the module late
622 InsertValue(V, *FutureLateResolvers);
624 if (DID.Type == ValID::NameVal) {
625 error("Reference to an invalid definition: '" + DID.getName() +
626 "' of type '" + V->getType()->getDescription() + "'",
630 error("Reference to an invalid definition: #" +
631 itostr(DID.Num) + " of type '" +
632 V->getType()->getDescription() + "'", PHI->second.second);
639 LateResolvers.clear();
642 // ResolveTypeTo - A brand new type was just declared. This means that (if
643 // name is not null) things referencing Name can be resolved. Otherwise, things
644 // refering to the number can be resolved. Do this now.
646 static void ResolveTypeTo(char *Name, const Type *ToTy, Signedness Sign) {
649 D = ValID::create(Name, Sign);
651 D = ValID::create((int)CurModule.Types.size(), Sign);
653 std::map<ValID, PATypeHolder>::iterator I =
654 CurModule.LateResolveTypes.find(D);
655 if (I != CurModule.LateResolveTypes.end()) {
656 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
657 CurModule.LateResolveTypes.erase(I);
661 /// This is the implementation portion of TypeHasInteger. It traverses the
662 /// type given, avoiding recursive types, and returns true as soon as it finds
663 /// an integer type. If no integer type is found, it returns false.
664 static bool TypeHasIntegerI(const Type *Ty, std::vector<const Type*> Stack) {
665 // Handle some easy cases
666 if (Ty->isPrimitiveType() || (Ty->getTypeID() == Type::OpaqueTyID))
670 if (const SequentialType *STy = dyn_cast<SequentialType>(Ty))
671 return STy->getElementType()->isInteger();
673 // Avoid type structure recursion
674 for (std::vector<const Type*>::iterator I = Stack.begin(), E = Stack.end();
679 // Push us on the type stack
682 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
683 if (TypeHasIntegerI(FTy->getReturnType(), Stack))
685 FunctionType::param_iterator I = FTy->param_begin();
686 FunctionType::param_iterator E = FTy->param_end();
688 if (TypeHasIntegerI(*I, Stack))
691 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
692 StructType::element_iterator I = STy->element_begin();
693 StructType::element_iterator E = STy->element_end();
694 for (; I != E; ++I) {
695 if (TypeHasIntegerI(*I, Stack))
700 // There shouldn't be anything else, but its definitely not integer
701 assert(0 && "What type is this?");
705 /// This is the interface to TypeHasIntegerI. It just provides the type stack,
706 /// to avoid recursion, and then calls TypeHasIntegerI.
707 static inline bool TypeHasInteger(const Type *Ty) {
708 std::vector<const Type*> TyStack;
709 return TypeHasIntegerI(Ty, TyStack);
712 // setValueName - Set the specified value to the name given. The name may be
713 // null potentially, in which case this is a noop. The string passed in is
714 // assumed to be a malloc'd string buffer, and is free'd by this function.
716 static void setValueName(const ValueInfo &V, char *NameStr) {
718 std::string Name(NameStr); // Copy string
719 free(NameStr); // Free old string
721 if (V.V->getType() == Type::VoidTy) {
722 error("Can't assign name '" + Name + "' to value with void type");
726 assert(inFunctionScope() && "Must be in function scope");
728 // Search the function's symbol table for an existing value of this name
729 ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
730 Value* Existing = ST.lookup(Name);
732 // An existing value of the same name was found. This might have happened
733 // because of the integer type planes collapsing in LLVM 2.0.
734 if (Existing->getType() == V.V->getType() &&
735 !TypeHasInteger(Existing->getType())) {
736 // If the type does not contain any integers in them then this can't be
737 // a type plane collapsing issue. It truly is a redefinition and we
738 // should error out as the assembly is invalid.
739 error("Redefinition of value named '" + Name + "' of type '" +
740 V.V->getType()->getDescription() + "'");
743 // In LLVM 2.0 we don't allow names to be re-used for any values in a
744 // function, regardless of Type. Previously re-use of names was okay as
745 // long as they were distinct types. With type planes collapsing because
746 // of the signedness change and because of PR411, this can no longer be
747 // supported. We must search the entire symbol table for a conflicting
748 // name and make the name unique. No warning is needed as this can't
750 std::string NewName = makeNameUnique(Name);
751 // We're changing the name but it will probably be used by other
752 // instructions as operands later on. Consequently we have to retain
753 // a mapping of the renaming that we're doing.
755 TI.T = V.V->getType();
757 RenameMapKey Key = std::make_pair(Name,TI);
758 CurFun.RenameMap[Key] = NewName;
767 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
768 /// this is a declaration, otherwise it is a definition.
769 static GlobalVariable *
770 ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
771 bool isConstantGlobal, const Type *Ty,
772 Constant *Initializer,
774 if (isa<FunctionType>(Ty))
775 error("Cannot declare global vars of function type");
777 const PointerType *PTy = PointerType::get(Ty);
781 Name = NameStr; // Copy string
782 free(NameStr); // Free old string
785 // See if this global value was forward referenced. If so, recycle the
789 ID = ValID::create((char*)Name.c_str(), Sign);
791 ID = ValID::create((int)CurModule.Values[PTy].size(), Sign);
794 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
795 // Move the global to the end of the list, from whereever it was
796 // previously inserted.
797 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
798 CurModule.CurrentModule->getGlobalList().remove(GV);
799 CurModule.CurrentModule->getGlobalList().push_back(GV);
800 GV->setInitializer(Initializer);
801 GV->setLinkage(Linkage);
802 GV->setConstant(isConstantGlobal);
803 InsertValue(GV, CurModule.Values);
807 // If this global has a name, check to see if there is already a definition
808 // of this global in the module and emit warnings if there are conflicts.
810 // The global has a name. See if there's an existing one of the same name.
811 if (CurModule.CurrentModule->getNamedGlobal(Name)) {
812 // We found an existing global ov the same name. This isn't allowed
813 // in LLVM 2.0. Consequently, we must alter the name of the global so it
814 // can at least compile. This can happen because of type planes
815 // There is alread a global of the same name which means there is a
816 // conflict. Let's see what we can do about it.
817 std::string NewName(makeNameUnique(Name));
818 if (Linkage == GlobalValue::InternalLinkage) {
819 // The linkage type is internal so just warn about the rename without
820 // invoking "scarey language" about linkage failures. GVars with
821 // InternalLinkage can be renamed at will.
822 warning("Global variable '" + Name + "' was renamed to '"+
825 // The linkage of this gval is external so we can't reliably rename
826 // it because it could potentially create a linking problem.
827 // However, we can't leave the name conflict in the output either or
828 // it won't assemble with LLVM 2.0. So, all we can do is rename
829 // this one to something unique and emit a warning about the problem.
830 warning("Renaming global variable '" + Name + "' to '" + NewName +
831 "' may cause linkage errors");
834 // Put the renaming in the global rename map
835 TypeInfo TI; TI.T = PointerType::get(Ty); TI.S = Signless;
836 RenameMapKey Key = std::make_pair(Name,TI);
837 CurModule.RenameMap[Key] = NewName;
844 // Otherwise there is no existing GV to use, create one now.
846 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
847 CurModule.CurrentModule);
848 InsertValue(GV, CurModule.Values);
852 // setTypeName - Set the specified type to the name given. The name may be
853 // null potentially, in which case this is a noop. The string passed in is
854 // assumed to be a malloc'd string buffer, and is freed by this function.
856 // This function returns true if the type has already been defined, but is
857 // allowed to be redefined in the specified context. If the name is a new name
858 // for the type plane, it is inserted and false is returned.
859 static bool setTypeName(const Type *T, char *NameStr) {
860 assert(!inFunctionScope() && "Can't give types function-local names");
861 if (NameStr == 0) return false;
863 std::string Name(NameStr); // Copy string
864 free(NameStr); // Free old string
866 // We don't allow assigning names to void type
867 if (T == Type::VoidTy) {
868 error("Can't assign name '" + Name + "' to the void type");
872 // Set the type name, checking for conflicts as we do so.
873 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
875 if (AlreadyExists) { // Inserting a name that is already defined???
876 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
877 assert(Existing && "Conflict but no matching type?");
879 // There is only one case where this is allowed: when we are refining an
880 // opaque type. In this case, Existing will be an opaque type.
881 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
882 // We ARE replacing an opaque type!
883 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
887 // Otherwise, this is an attempt to redefine a type. That's okay if
888 // the redefinition is identical to the original. This will be so if
889 // Existing and T point to the same Type object. In this one case we
890 // allow the equivalent redefinition.
891 if (Existing == T) return true; // Yes, it's equal.
893 // Any other kind of (non-equivalent) redefinition is an error.
894 error("Redefinition of type named '" + Name + "' in the '" +
895 T->getDescription() + "' type plane");
901 //===----------------------------------------------------------------------===//
902 // Code for handling upreferences in type names...
905 // TypeContains - Returns true if Ty directly contains E in it.
907 static bool TypeContains(const Type *Ty, const Type *E) {
908 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
909 E) != Ty->subtype_end();
914 // NestingLevel - The number of nesting levels that need to be popped before
915 // this type is resolved.
916 unsigned NestingLevel;
918 // LastContainedTy - This is the type at the current binding level for the
919 // type. Every time we reduce the nesting level, this gets updated.
920 const Type *LastContainedTy;
922 // UpRefTy - This is the actual opaque type that the upreference is
926 UpRefRecord(unsigned NL, OpaqueType *URTy)
927 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
931 // UpRefs - A list of the outstanding upreferences that need to be resolved.
932 static std::vector<UpRefRecord> UpRefs;
934 /// HandleUpRefs - Every time we finish a new layer of types, this function is
935 /// called. It loops through the UpRefs vector, which is a list of the
936 /// currently active types. For each type, if the up reference is contained in
937 /// the newly completed type, we decrement the level count. When the level
938 /// count reaches zero, the upreferenced type is the type that is passed in:
939 /// thus we can complete the cycle.
941 static PATypeHolder HandleUpRefs(const Type *ty) {
942 // If Ty isn't abstract, or if there are no up-references in it, then there is
943 // nothing to resolve here.
944 if (!ty->isAbstract() || UpRefs.empty()) return ty;
947 UR_OUT("Type '" << Ty->getDescription() <<
948 "' newly formed. Resolving upreferences.\n" <<
949 UpRefs.size() << " upreferences active!\n");
951 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
952 // to zero), we resolve them all together before we resolve them to Ty. At
953 // the end of the loop, if there is anything to resolve to Ty, it will be in
955 OpaqueType *TypeToResolve = 0;
957 for (unsigned i = 0; i != UpRefs.size(); ++i) {
958 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
959 << UpRefs[i].second->getDescription() << ") = "
960 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
961 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
962 // Decrement level of upreference
963 unsigned Level = --UpRefs[i].NestingLevel;
964 UpRefs[i].LastContainedTy = Ty;
965 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
966 if (Level == 0) { // Upreference should be resolved!
967 if (!TypeToResolve) {
968 TypeToResolve = UpRefs[i].UpRefTy;
970 UR_OUT(" * Resolving upreference for "
971 << UpRefs[i].second->getDescription() << "\n";
972 std::string OldName = UpRefs[i].UpRefTy->getDescription());
973 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
974 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
975 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
977 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
978 --i; // Do not skip the next element...
984 UR_OUT(" * Resolving upreference for "
985 << UpRefs[i].second->getDescription() << "\n";
986 std::string OldName = TypeToResolve->getDescription());
987 TypeToResolve->refineAbstractTypeTo(Ty);
993 static inline Instruction::TermOps
994 getTermOp(TermOps op) {
996 default : assert(0 && "Invalid OldTermOp");
997 case RetOp : return Instruction::Ret;
998 case BrOp : return Instruction::Br;
999 case SwitchOp : return Instruction::Switch;
1000 case InvokeOp : return Instruction::Invoke;
1001 case UnwindOp : return Instruction::Unwind;
1002 case UnreachableOp: return Instruction::Unreachable;
1006 static inline Instruction::BinaryOps
1007 getBinaryOp(BinaryOps op, const Type *Ty, Signedness Sign) {
1009 default : assert(0 && "Invalid OldBinaryOps");
1015 case SetGT : assert(0 && "Should use getCompareOp");
1016 case AddOp : return Instruction::Add;
1017 case SubOp : return Instruction::Sub;
1018 case MulOp : return Instruction::Mul;
1020 // This is an obsolete instruction so we must upgrade it based on the
1021 // types of its operands.
1022 bool isFP = Ty->isFloatingPoint();
1023 if (const VectorType* PTy = dyn_cast<VectorType>(Ty))
1024 // If its a vector type we want to use the element type
1025 isFP = PTy->getElementType()->isFloatingPoint();
1027 return Instruction::FDiv;
1028 else if (Sign == Signed)
1029 return Instruction::SDiv;
1030 return Instruction::UDiv;
1032 case UDivOp : return Instruction::UDiv;
1033 case SDivOp : return Instruction::SDiv;
1034 case FDivOp : return Instruction::FDiv;
1036 // This is an obsolete instruction so we must upgrade it based on the
1037 // types of its operands.
1038 bool isFP = Ty->isFloatingPoint();
1039 if (const VectorType* PTy = dyn_cast<VectorType>(Ty))
1040 // If its a vector type we want to use the element type
1041 isFP = PTy->getElementType()->isFloatingPoint();
1042 // Select correct opcode
1044 return Instruction::FRem;
1045 else if (Sign == Signed)
1046 return Instruction::SRem;
1047 return Instruction::URem;
1049 case URemOp : return Instruction::URem;
1050 case SRemOp : return Instruction::SRem;
1051 case FRemOp : return Instruction::FRem;
1052 case LShrOp : return Instruction::LShr;
1053 case AShrOp : return Instruction::AShr;
1054 case ShlOp : return Instruction::Shl;
1057 return Instruction::AShr;
1058 return Instruction::LShr;
1059 case AndOp : return Instruction::And;
1060 case OrOp : return Instruction::Or;
1061 case XorOp : return Instruction::Xor;
1065 static inline Instruction::OtherOps
1066 getCompareOp(BinaryOps op, unsigned short &predicate, const Type* &Ty,
1068 bool isSigned = Sign == Signed;
1069 bool isFP = Ty->isFloatingPoint();
1071 default : assert(0 && "Invalid OldSetCC");
1074 predicate = FCmpInst::FCMP_OEQ;
1075 return Instruction::FCmp;
1077 predicate = ICmpInst::ICMP_EQ;
1078 return Instruction::ICmp;
1082 predicate = FCmpInst::FCMP_UNE;
1083 return Instruction::FCmp;
1085 predicate = ICmpInst::ICMP_NE;
1086 return Instruction::ICmp;
1090 predicate = FCmpInst::FCMP_OLE;
1091 return Instruction::FCmp;
1094 predicate = ICmpInst::ICMP_SLE;
1096 predicate = ICmpInst::ICMP_ULE;
1097 return Instruction::ICmp;
1101 predicate = FCmpInst::FCMP_OGE;
1102 return Instruction::FCmp;
1105 predicate = ICmpInst::ICMP_SGE;
1107 predicate = ICmpInst::ICMP_UGE;
1108 return Instruction::ICmp;
1112 predicate = FCmpInst::FCMP_OLT;
1113 return Instruction::FCmp;
1116 predicate = ICmpInst::ICMP_SLT;
1118 predicate = ICmpInst::ICMP_ULT;
1119 return Instruction::ICmp;
1123 predicate = FCmpInst::FCMP_OGT;
1124 return Instruction::FCmp;
1127 predicate = ICmpInst::ICMP_SGT;
1129 predicate = ICmpInst::ICMP_UGT;
1130 return Instruction::ICmp;
1135 static inline Instruction::MemoryOps getMemoryOp(MemoryOps op) {
1137 default : assert(0 && "Invalid OldMemoryOps");
1138 case MallocOp : return Instruction::Malloc;
1139 case FreeOp : return Instruction::Free;
1140 case AllocaOp : return Instruction::Alloca;
1141 case LoadOp : return Instruction::Load;
1142 case StoreOp : return Instruction::Store;
1143 case GetElementPtrOp : return Instruction::GetElementPtr;
1147 static inline Instruction::OtherOps
1148 getOtherOp(OtherOps op, Signedness Sign) {
1150 default : assert(0 && "Invalid OldOtherOps");
1151 case PHIOp : return Instruction::PHI;
1152 case CallOp : return Instruction::Call;
1153 case SelectOp : return Instruction::Select;
1154 case UserOp1 : return Instruction::UserOp1;
1155 case UserOp2 : return Instruction::UserOp2;
1156 case VAArg : return Instruction::VAArg;
1157 case ExtractElementOp : return Instruction::ExtractElement;
1158 case InsertElementOp : return Instruction::InsertElement;
1159 case ShuffleVectorOp : return Instruction::ShuffleVector;
1160 case ICmpOp : return Instruction::ICmp;
1161 case FCmpOp : return Instruction::FCmp;
1165 static inline Value*
1166 getCast(CastOps op, Value *Src, Signedness SrcSign, const Type *DstTy,
1167 Signedness DstSign, bool ForceInstruction = false) {
1168 Instruction::CastOps Opcode;
1169 const Type* SrcTy = Src->getType();
1171 if (SrcTy->isFloatingPoint() && isa<PointerType>(DstTy)) {
1172 // fp -> ptr cast is no longer supported but we must upgrade this
1173 // by doing a double cast: fp -> int -> ptr
1174 SrcTy = Type::Int64Ty;
1175 Opcode = Instruction::IntToPtr;
1176 if (isa<Constant>(Src)) {
1177 Src = ConstantExpr::getCast(Instruction::FPToUI,
1178 cast<Constant>(Src), SrcTy);
1180 std::string NewName(makeNameUnique(Src->getName()));
1181 Src = new FPToUIInst(Src, SrcTy, NewName, CurBB);
1183 } else if (isa<IntegerType>(DstTy) &&
1184 cast<IntegerType>(DstTy)->getBitWidth() == 1) {
1185 // cast type %x to bool was previously defined as setne type %x, null
1186 // The cast semantic is now to truncate, not compare so we must retain
1187 // the original intent by replacing the cast with a setne
1188 Constant* Null = Constant::getNullValue(SrcTy);
1189 Instruction::OtherOps Opcode = Instruction::ICmp;
1190 unsigned short predicate = ICmpInst::ICMP_NE;
1191 if (SrcTy->isFloatingPoint()) {
1192 Opcode = Instruction::FCmp;
1193 predicate = FCmpInst::FCMP_ONE;
1194 } else if (!SrcTy->isInteger() && !isa<PointerType>(SrcTy)) {
1195 error("Invalid cast to bool");
1197 if (isa<Constant>(Src) && !ForceInstruction)
1198 return ConstantExpr::getCompare(predicate, cast<Constant>(Src), Null);
1200 return CmpInst::create(Opcode, predicate, Src, Null);
1202 // Determine the opcode to use by calling CastInst::getCastOpcode
1204 CastInst::getCastOpcode(Src, SrcSign == Signed, DstTy, DstSign == Signed);
1206 } else switch (op) {
1207 default: assert(0 && "Invalid cast token");
1208 case TruncOp: Opcode = Instruction::Trunc; break;
1209 case ZExtOp: Opcode = Instruction::ZExt; break;
1210 case SExtOp: Opcode = Instruction::SExt; break;
1211 case FPTruncOp: Opcode = Instruction::FPTrunc; break;
1212 case FPExtOp: Opcode = Instruction::FPExt; break;
1213 case FPToUIOp: Opcode = Instruction::FPToUI; break;
1214 case FPToSIOp: Opcode = Instruction::FPToSI; break;
1215 case UIToFPOp: Opcode = Instruction::UIToFP; break;
1216 case SIToFPOp: Opcode = Instruction::SIToFP; break;
1217 case PtrToIntOp: Opcode = Instruction::PtrToInt; break;
1218 case IntToPtrOp: Opcode = Instruction::IntToPtr; break;
1219 case BitCastOp: Opcode = Instruction::BitCast; break;
1222 if (isa<Constant>(Src) && !ForceInstruction)
1223 return ConstantExpr::getCast(Opcode, cast<Constant>(Src), DstTy);
1224 return CastInst::create(Opcode, Src, DstTy);
1227 static Instruction *
1228 upgradeIntrinsicCall(const Type* RetTy, const ValID &ID,
1229 std::vector<Value*>& Args) {
1231 std::string Name = ID.Type == ValID::NameVal ? ID.Name : "";
1232 if (Name == "llvm.isunordered.f32" || Name == "llvm.isunordered.f64") {
1233 if (Args.size() != 2)
1234 error("Invalid prototype for " + Name + " prototype");
1235 return new FCmpInst(FCmpInst::FCMP_UNO, Args[0], Args[1]);
1237 const Type* PtrTy = PointerType::get(Type::Int8Ty);
1238 std::vector<const Type*> Params;
1239 if (Name == "llvm.va_start" || Name == "llvm.va_end") {
1240 if (Args.size() != 1)
1241 error("Invalid prototype for " + Name + " prototype");
1242 Params.push_back(PtrTy);
1243 const FunctionType *FTy = FunctionType::get(Type::VoidTy, Params, false);
1244 const PointerType *PFTy = PointerType::get(FTy);
1245 Value* Func = getVal(PFTy, ID);
1246 Args[0] = new BitCastInst(Args[0], PtrTy, makeNameUnique("va"), CurBB);
1247 return new CallInst(Func, &Args[0], Args.size());
1248 } else if (Name == "llvm.va_copy") {
1249 if (Args.size() != 2)
1250 error("Invalid prototype for " + Name + " prototype");
1251 Params.push_back(PtrTy);
1252 Params.push_back(PtrTy);
1253 const FunctionType *FTy = FunctionType::get(Type::VoidTy, Params, false);
1254 const PointerType *PFTy = PointerType::get(FTy);
1255 Value* Func = getVal(PFTy, ID);
1256 std::string InstName0(makeNameUnique("va0"));
1257 std::string InstName1(makeNameUnique("va1"));
1258 Args[0] = new BitCastInst(Args[0], PtrTy, InstName0, CurBB);
1259 Args[1] = new BitCastInst(Args[1], PtrTy, InstName1, CurBB);
1260 return new CallInst(Func, &Args[0], Args.size());
1266 const Type* upgradeGEPIndices(const Type* PTy,
1267 std::vector<ValueInfo> *Indices,
1268 std::vector<Value*> &VIndices,
1269 std::vector<Constant*> *CIndices = 0) {
1270 // Traverse the indices with a gep_type_iterator so we can build the list
1271 // of constant and value indices for use later. Also perform upgrades
1273 if (CIndices) CIndices->clear();
1274 for (unsigned i = 0, e = Indices->size(); i != e; ++i)
1275 VIndices.push_back((*Indices)[i].V);
1276 generic_gep_type_iterator<std::vector<Value*>::iterator>
1277 GTI = gep_type_begin(PTy, VIndices.begin(), VIndices.end()),
1278 GTE = gep_type_end(PTy, VIndices.begin(), VIndices.end());
1279 for (unsigned i = 0, e = Indices->size(); i != e && GTI != GTE; ++i, ++GTI) {
1280 Value *Index = VIndices[i];
1281 if (CIndices && !isa<Constant>(Index))
1282 error("Indices to constant getelementptr must be constants");
1283 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte
1284 // struct indices to i32 struct indices with ZExt for compatibility.
1285 else if (isa<StructType>(*GTI)) { // Only change struct indices
1286 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Index))
1287 if (CUI->getType()->getBitWidth() == 8)
1289 ConstantExpr::getCast(Instruction::ZExt, CUI, Type::Int32Ty);
1291 // Make sure that unsigned SequentialType indices are zext'd to
1292 // 64-bits if they were smaller than that because LLVM 2.0 will sext
1293 // all indices for SequentialType elements. We must retain the same
1294 // semantic (zext) for unsigned types.
1295 if (const IntegerType *Ity = dyn_cast<IntegerType>(Index->getType()))
1296 if (Ity->getBitWidth() < 64 && (*Indices)[i].S == Unsigned) {
1298 Index = ConstantExpr::getCast(Instruction::ZExt,
1299 cast<Constant>(Index), Type::Int64Ty);
1301 Index = CastInst::create(Instruction::ZExt, Index, Type::Int64Ty,
1302 makeNameUnique("gep"), CurBB);
1303 VIndices[i] = Index;
1306 // Add to the CIndices list, if requested.
1308 CIndices->push_back(cast<Constant>(Index));
1312 GetElementPtrInst::getIndexedType(PTy, &VIndices[0], VIndices.size(), true);
1314 error("Index list invalid for constant getelementptr");
1318 unsigned upgradeCallingConv(unsigned CC) {
1320 case OldCallingConv::C : return CallingConv::C;
1321 case OldCallingConv::CSRet : return CallingConv::C;
1322 case OldCallingConv::Fast : return CallingConv::Fast;
1323 case OldCallingConv::Cold : return CallingConv::Cold;
1324 case OldCallingConv::X86_StdCall : return CallingConv::X86_StdCall;
1325 case OldCallingConv::X86_FastCall: return CallingConv::X86_FastCall;
1331 Module* UpgradeAssembly(const std::string &infile, std::istream& in,
1332 bool debug, bool addAttrs)
1335 CurFilename = infile;
1338 AddAttributes = addAttrs;
1339 ObsoleteVarArgs = false;
1342 CurModule.CurrentModule = new Module(CurFilename);
1344 // Check to make sure the parser succeeded
1347 delete ParserResult;
1348 std::cerr << "llvm-upgrade: parse failed.\n";
1352 // Check to make sure that parsing produced a result
1353 if (!ParserResult) {
1354 std::cerr << "llvm-upgrade: no parse result.\n";
1358 // Reset ParserResult variable while saving its value for the result.
1359 Module *Result = ParserResult;
1362 //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
1365 if ((F = Result->getFunction("llvm.va_start"))
1366 && F->getFunctionType()->getNumParams() == 0)
1367 ObsoleteVarArgs = true;
1368 if((F = Result->getFunction("llvm.va_copy"))
1369 && F->getFunctionType()->getNumParams() == 1)
1370 ObsoleteVarArgs = true;
1373 if (ObsoleteVarArgs && NewVarArgs) {
1374 error("This file is corrupt: it uses both new and old style varargs");
1378 if(ObsoleteVarArgs) {
1379 if(Function* F = Result->getFunction("llvm.va_start")) {
1380 if (F->arg_size() != 0) {
1381 error("Obsolete va_start takes 0 argument");
1387 //bar = alloca typeof(foo)
1391 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1392 const Type* ArgTy = F->getFunctionType()->getReturnType();
1393 const Type* ArgTyPtr = PointerType::get(ArgTy);
1394 Function* NF = cast<Function>(Result->getOrInsertFunction(
1395 "llvm.va_start", RetTy, ArgTyPtr, (Type *)0));
1397 while (!F->use_empty()) {
1398 CallInst* CI = cast<CallInst>(F->use_back());
1399 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
1400 new CallInst(NF, bar, "", CI);
1401 Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
1402 CI->replaceAllUsesWith(foo);
1403 CI->getParent()->getInstList().erase(CI);
1405 Result->getFunctionList().erase(F);
1408 if(Function* F = Result->getFunction("llvm.va_end")) {
1409 if(F->arg_size() != 1) {
1410 error("Obsolete va_end takes 1 argument");
1416 //bar = alloca 1 of typeof(foo)
1418 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1419 const Type* ArgTy = F->getFunctionType()->getParamType(0);
1420 const Type* ArgTyPtr = PointerType::get(ArgTy);
1421 Function* NF = cast<Function>(Result->getOrInsertFunction(
1422 "llvm.va_end", RetTy, ArgTyPtr, (Type *)0));
1424 while (!F->use_empty()) {
1425 CallInst* CI = cast<CallInst>(F->use_back());
1426 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
1427 new StoreInst(CI->getOperand(1), bar, CI);
1428 new CallInst(NF, bar, "", CI);
1429 CI->getParent()->getInstList().erase(CI);
1431 Result->getFunctionList().erase(F);
1434 if(Function* F = Result->getFunction("llvm.va_copy")) {
1435 if(F->arg_size() != 1) {
1436 error("Obsolete va_copy takes 1 argument");
1441 //a = alloca 1 of typeof(foo)
1442 //b = alloca 1 of typeof(foo)
1447 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1448 const Type* ArgTy = F->getFunctionType()->getReturnType();
1449 const Type* ArgTyPtr = PointerType::get(ArgTy);
1450 Function* NF = cast<Function>(Result->getOrInsertFunction(
1451 "llvm.va_copy", RetTy, ArgTyPtr, ArgTyPtr, (Type *)0));
1453 while (!F->use_empty()) {
1454 CallInst* CI = cast<CallInst>(F->use_back());
1455 AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
1456 AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
1457 new StoreInst(CI->getOperand(1), b, CI);
1458 new CallInst(NF, a, b, "", CI);
1459 Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
1460 CI->replaceAllUsesWith(foo);
1461 CI->getParent()->getInstList().erase(CI);
1463 Result->getFunctionList().erase(F);
1470 } // end llvm namespace
1472 using namespace llvm;
1477 llvm::Module *ModuleVal;
1478 llvm::Function *FunctionVal;
1479 std::pair<llvm::PATypeInfo, char*> *ArgVal;
1480 llvm::BasicBlock *BasicBlockVal;
1481 llvm::TerminatorInst *TermInstVal;
1482 llvm::InstrInfo InstVal;
1483 llvm::ConstInfo ConstVal;
1484 llvm::ValueInfo ValueVal;
1485 llvm::PATypeInfo TypeVal;
1486 llvm::TypeInfo PrimType;
1487 llvm::PHIListInfo PHIList;
1488 std::list<llvm::PATypeInfo> *TypeList;
1489 std::vector<llvm::ValueInfo> *ValueList;
1490 std::vector<llvm::ConstInfo> *ConstVector;
1493 std::vector<std::pair<llvm::PATypeInfo,char*> > *ArgList;
1494 // Represent the RHS of PHI node
1495 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
1497 llvm::GlobalValue::LinkageTypes Linkage;
1505 char *StrVal; // This memory is strdup'd!
1506 llvm::ValID ValIDVal; // strdup'd memory maybe!
1508 llvm::BinaryOps BinaryOpVal;
1509 llvm::TermOps TermOpVal;
1510 llvm::MemoryOps MemOpVal;
1511 llvm::OtherOps OtherOpVal;
1512 llvm::CastOps CastOpVal;
1513 llvm::ICmpInst::Predicate IPred;
1514 llvm::FCmpInst::Predicate FPred;
1515 llvm::Module::Endianness Endianness;
1518 %type <ModuleVal> Module FunctionList
1519 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1520 %type <BasicBlockVal> BasicBlock InstructionList
1521 %type <TermInstVal> BBTerminatorInst
1522 %type <InstVal> Inst InstVal MemoryInst
1523 %type <ConstVal> ConstVal ConstExpr
1524 %type <ConstVector> ConstVector
1525 %type <ArgList> ArgList ArgListH
1526 %type <ArgVal> ArgVal
1527 %type <PHIList> PHIList
1528 %type <ValueList> ValueRefList ValueRefListE // For call param lists
1529 %type <ValueList> IndexList // For GEP derived indices
1530 %type <TypeList> TypeListI ArgTypeListI
1531 %type <JumpTable> JumpTable
1532 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1533 %type <BoolVal> OptVolatile // 'volatile' or not
1534 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1535 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
1536 %type <Linkage> OptLinkage FnDeclareLinkage
1537 %type <Endianness> BigOrLittle
1539 // ValueRef - Unresolved reference to a definition or BB
1540 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1541 %type <ValueVal> ResolvedVal // <type> <valref> pair
1543 // Tokens and types for handling constant integer values
1545 // ESINT64VAL - A negative number within long long range
1546 %token <SInt64Val> ESINT64VAL
1548 // EUINT64VAL - A positive number within uns. long long range
1549 %token <UInt64Val> EUINT64VAL
1550 %type <SInt64Val> EINT64VAL
1552 %token <SIntVal> SINTVAL // Signed 32 bit ints...
1553 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
1554 %type <SIntVal> INTVAL
1555 %token <FPVal> FPVAL // Float or Double constant
1557 // Built in types...
1558 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
1559 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
1560 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
1561 %token <PrimType> FLOAT DOUBLE TYPE LABEL
1563 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
1564 %type <StrVal> Name OptName OptAssign
1565 %type <UIntVal> OptAlign OptCAlign
1566 %type <StrVal> OptSection SectionString
1568 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1569 %token DECLARE GLOBAL CONSTANT SECTION VOLATILE
1570 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
1571 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
1572 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
1573 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1574 %token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
1575 %token X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1577 %type <UIntVal> OptCallingConv
1579 // Basic Block Terminating Operators
1580 %token <TermOpVal> RET BR SWITCH INVOKE UNREACHABLE
1581 %token UNWIND EXCEPT
1584 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
1585 %type <BinaryOpVal> ShiftOps
1586 %token <BinaryOpVal> ADD SUB MUL DIV UDIV SDIV FDIV REM UREM SREM FREM
1587 %token <BinaryOpVal> AND OR XOR SHL SHR ASHR LSHR
1588 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comparators
1589 %token <OtherOpVal> ICMP FCMP
1591 // Memory Instructions
1592 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1595 %token <OtherOpVal> PHI_TOK SELECT VAARG
1596 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1597 %token VAARG_old VANEXT_old //OBSOLETE
1599 // Support for ICmp/FCmp Predicates, which is 1.9++ but not 2.0
1600 %type <IPred> IPredicates
1601 %type <FPred> FPredicates
1602 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1603 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1605 %token <CastOpVal> CAST TRUNC ZEXT SEXT FPTRUNC FPEXT FPTOUI FPTOSI
1606 %token <CastOpVal> UITOFP SITOFP PTRTOINT INTTOPTR BITCAST
1607 %type <CastOpVal> CastOps
1613 // Handle constant integer size restriction and conversion...
1618 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
1619 error("Value too large for type");
1625 : ESINT64VAL // These have same type and can't cause problems...
1627 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
1628 error("Value too large for type");
1632 // Operations that are notably excluded from this list include:
1633 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1636 : ADD | SUB | MUL | DIV | UDIV | SDIV | FDIV | REM | UREM | SREM | FREM
1644 : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
1648 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1649 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1650 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1651 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1652 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1656 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1657 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1658 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1659 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1660 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1661 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1662 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1663 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1664 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1667 : SHL | SHR | ASHR | LSHR
1671 : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | FPTOUI | FPTOSI
1672 | UITOFP | SITOFP | PTRTOINT | INTTOPTR | BITCAST | CAST
1675 // These are some types that allow classification if we only want a particular
1676 // thing... for example, only a signed, unsigned, or integral type.
1678 : LONG | INT | SHORT | SBYTE
1682 : ULONG | UINT | USHORT | UBYTE
1686 : SIntType | UIntType
1693 // OptAssign - Value producing statements have an optional assignment component
1703 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1704 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1705 | WEAK { $$ = GlobalValue::WeakLinkage; }
1706 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1707 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1708 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1709 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1710 | /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1714 : /*empty*/ { $$ = OldCallingConv::C; }
1715 | CCC_TOK { $$ = OldCallingConv::C; }
1716 | CSRETCC_TOK { $$ = OldCallingConv::CSRet; }
1717 | FASTCC_TOK { $$ = OldCallingConv::Fast; }
1718 | COLDCC_TOK { $$ = OldCallingConv::Cold; }
1719 | X86_STDCALLCC_TOK { $$ = OldCallingConv::X86_StdCall; }
1720 | X86_FASTCALLCC_TOK { $$ = OldCallingConv::X86_FastCall; }
1721 | CC_TOK EUINT64VAL {
1722 if ((unsigned)$2 != $2)
1723 error("Calling conv too large");
1728 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1729 // a comma before it.
1731 : /*empty*/ { $$ = 0; }
1732 | ALIGN EUINT64VAL {
1734 if ($$ != 0 && !isPowerOf2_32($$))
1735 error("Alignment must be a power of two");
1740 : /*empty*/ { $$ = 0; }
1741 | ',' ALIGN EUINT64VAL {
1743 if ($$ != 0 && !isPowerOf2_32($$))
1744 error("Alignment must be a power of two");
1749 : SECTION STRINGCONSTANT {
1750 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1751 if ($2[i] == '"' || $2[i] == '\\')
1752 error("Invalid character in section name");
1758 : /*empty*/ { $$ = 0; }
1759 | SectionString { $$ = $1; }
1762 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1763 // is set to be the global we are processing.
1767 | ',' GlobalVarAttribute GlobalVarAttributes {}
1772 CurGV->setSection($1);
1775 | ALIGN EUINT64VAL {
1776 if ($2 != 0 && !isPowerOf2_32($2))
1777 error("Alignment must be a power of two");
1778 CurGV->setAlignment($2);
1783 //===----------------------------------------------------------------------===//
1784 // Types includes all predefined types... except void, because it can only be
1785 // used in specific contexts (function returning void for example). To have
1786 // access to it, a user must explicitly use TypesV.
1789 // TypesV includes all of 'Types', but it also includes the void type.
1793 $$.PAT = new PATypeHolder($1.T);
1801 $$.PAT = new PATypeHolder($1.T);
1808 if (!UpRefs.empty())
1809 error("Invalid upreference in type: " + (*$1.PAT)->getDescription());
1815 : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT
1816 | LONG | ULONG | FLOAT | DOUBLE | LABEL
1819 // Derived types are added later...
1822 $$.PAT = new PATypeHolder($1.T);
1826 $$.PAT = new PATypeHolder(OpaqueType::get());
1829 | SymbolicValueRef { // Named types are also simple types...
1830 const Type* tmp = getType($1);
1831 $$.PAT = new PATypeHolder(tmp);
1832 $$.S = $1.S; // FIXME: what if its signed?
1834 | '\\' EUINT64VAL { // Type UpReference
1835 if ($2 > (uint64_t)~0U)
1836 error("Value out of range");
1837 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1838 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1839 $$.PAT = new PATypeHolder(OT);
1841 UR_OUT("New Upreference!\n");
1843 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
1844 std::vector<const Type*> Params;
1845 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
1846 E = $3->end(); I != E; ++I) {
1847 Params.push_back(I->PAT->get());
1849 FunctionType::ParamAttrsList ParamAttrs;
1850 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1851 if (isVarArg) Params.pop_back();
1853 $$.PAT = new PATypeHolder(
1854 HandleUpRefs(FunctionType::get($1.PAT->get(), Params, isVarArg,
1857 delete $1.PAT; // Delete the return type handle
1858 delete $3; // Delete the argument list
1860 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
1861 $$.PAT = new PATypeHolder(HandleUpRefs(ArrayType::get($4.PAT->get(),
1866 | '<' EUINT64VAL 'x' UpRTypes '>' { // Vector type?
1867 const llvm::Type* ElemTy = $4.PAT->get();
1868 if ((unsigned)$2 != $2)
1869 error("Unsigned result not equal to signed result");
1870 if (!(ElemTy->isInteger() || ElemTy->isFloatingPoint()))
1871 error("Elements of a VectorType must be integer or floating point");
1872 if (!isPowerOf2_32($2))
1873 error("VectorType length should be a power of 2");
1874 $$.PAT = new PATypeHolder(HandleUpRefs(VectorType::get(ElemTy,
1879 | '{' TypeListI '}' { // Structure type?
1880 std::vector<const Type*> Elements;
1881 for (std::list<llvm::PATypeInfo>::iterator I = $2->begin(),
1882 E = $2->end(); I != E; ++I)
1883 Elements.push_back(I->PAT->get());
1884 $$.PAT = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1888 | '{' '}' { // Empty structure type?
1889 $$.PAT = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1892 | '<' '{' TypeListI '}' '>' { // Packed Structure type?
1893 std::vector<const Type*> Elements;
1894 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
1895 E = $3->end(); I != E; ++I) {
1896 Elements.push_back(I->PAT->get());
1899 $$.PAT = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1903 | '<' '{' '}' '>' { // Empty packed structure type?
1904 $$.PAT = new PATypeHolder(StructType::get(std::vector<const Type*>(),true));
1907 | UpRTypes '*' { // Pointer type?
1908 if ($1.PAT->get() == Type::LabelTy)
1909 error("Cannot form a pointer to a basic block");
1910 $$.PAT = new PATypeHolder(HandleUpRefs(PointerType::get($1.PAT->get())));
1916 // TypeList - Used for struct declarations and as a basis for function type
1917 // declaration type lists
1921 $$ = new std::list<PATypeInfo>();
1924 | TypeListI ',' UpRTypes {
1925 ($$=$1)->push_back($3);
1929 // ArgTypeList - List of types for a function type declaration...
1932 | TypeListI ',' DOTDOTDOT {
1934 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
1935 VoidTI.S = Signless;
1936 ($$=$1)->push_back(VoidTI);
1939 $$ = new std::list<PATypeInfo>();
1941 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
1942 VoidTI.S = Signless;
1943 $$->push_back(VoidTI);
1946 $$ = new std::list<PATypeInfo>();
1950 // ConstVal - The various declarations that go into the constant pool. This
1951 // production is used ONLY to represent constants that show up AFTER a 'const',
1952 // 'constant' or 'global' token at global scope. Constants that can be inlined
1953 // into other expressions (such as integers and constexprs) are handled by the
1954 // ResolvedVal, ValueRef and ConstValueRef productions.
1957 : Types '[' ConstVector ']' { // Nonempty unsized arr
1958 const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
1960 error("Cannot make array constant with type: '" +
1961 $1.PAT->get()->getDescription() + "'");
1962 const Type *ETy = ATy->getElementType();
1963 int NumElements = ATy->getNumElements();
1965 // Verify that we have the correct size...
1966 if (NumElements != -1 && NumElements != (int)$3->size())
1967 error("Type mismatch: constant sized array initialized with " +
1968 utostr($3->size()) + " arguments, but has size of " +
1969 itostr(NumElements) + "");
1971 // Verify all elements are correct type!
1972 std::vector<Constant*> Elems;
1973 for (unsigned i = 0; i < $3->size(); i++) {
1974 Constant *C = (*$3)[i].C;
1975 const Type* ValTy = C->getType();
1977 error("Element #" + utostr(i) + " is not of type '" +
1978 ETy->getDescription() +"' as required!\nIt is of type '"+
1979 ValTy->getDescription() + "'");
1982 $$.C = ConstantArray::get(ATy, Elems);
1988 const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
1990 error("Cannot make array constant with type: '" +
1991 $1.PAT->get()->getDescription() + "'");
1992 int NumElements = ATy->getNumElements();
1993 if (NumElements != -1 && NumElements != 0)
1994 error("Type mismatch: constant sized array initialized with 0"
1995 " arguments, but has size of " + itostr(NumElements) +"");
1996 $$.C = ConstantArray::get(ATy, std::vector<Constant*>());
2000 | Types 'c' STRINGCONSTANT {
2001 const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
2003 error("Cannot make array constant with type: '" +
2004 $1.PAT->get()->getDescription() + "'");
2005 int NumElements = ATy->getNumElements();
2006 const Type *ETy = dyn_cast<IntegerType>(ATy->getElementType());
2007 if (!ETy || cast<IntegerType>(ETy)->getBitWidth() != 8)
2008 error("String arrays require type i8, not '" + ETy->getDescription() +
2010 char *EndStr = UnEscapeLexed($3, true);
2011 if (NumElements != -1 && NumElements != (EndStr-$3))
2012 error("Can't build string constant of size " +
2013 itostr((int)(EndStr-$3)) + " when array has size " +
2014 itostr(NumElements) + "");
2015 std::vector<Constant*> Vals;
2016 for (char *C = (char *)$3; C != (char *)EndStr; ++C)
2017 Vals.push_back(ConstantInt::get(ETy, *C));
2019 $$.C = ConstantArray::get(ATy, Vals);
2023 | Types '<' ConstVector '>' { // Nonempty unsized arr
2024 const VectorType *PTy = dyn_cast<VectorType>($1.PAT->get());
2026 error("Cannot make packed constant with type: '" +
2027 $1.PAT->get()->getDescription() + "'");
2028 const Type *ETy = PTy->getElementType();
2029 int NumElements = PTy->getNumElements();
2030 // Verify that we have the correct size...
2031 if (NumElements != -1 && NumElements != (int)$3->size())
2032 error("Type mismatch: constant sized packed initialized with " +
2033 utostr($3->size()) + " arguments, but has size of " +
2034 itostr(NumElements) + "");
2035 // Verify all elements are correct type!
2036 std::vector<Constant*> Elems;
2037 for (unsigned i = 0; i < $3->size(); i++) {
2038 Constant *C = (*$3)[i].C;
2039 const Type* ValTy = C->getType();
2041 error("Element #" + utostr(i) + " is not of type '" +
2042 ETy->getDescription() +"' as required!\nIt is of type '"+
2043 ValTy->getDescription() + "'");
2046 $$.C = ConstantVector::get(PTy, Elems);
2051 | Types '{' ConstVector '}' {
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 ($3->size() != STy->getNumContainedTypes())
2057 error("Illegal number of initializers for structure type");
2059 // Check to ensure that constants are compatible with the type initializer!
2060 std::vector<Constant*> Fields;
2061 for (unsigned i = 0, e = $3->size(); i != e; ++i) {
2062 Constant *C = (*$3)[i].C;
2063 if (C->getType() != STy->getElementType(i))
2064 error("Expected type '" + STy->getElementType(i)->getDescription() +
2065 "' for element #" + utostr(i) + " of structure initializer");
2066 Fields.push_back(C);
2068 $$.C = ConstantStruct::get(STy, Fields);
2074 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2076 error("Cannot make struct constant with type: '" +
2077 $1.PAT->get()->getDescription() + "'");
2078 if (STy->getNumContainedTypes() != 0)
2079 error("Illegal number of initializers for structure type");
2080 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2084 | Types '<' '{' ConstVector '}' '>' {
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 ($4->size() != STy->getNumContainedTypes())
2090 error("Illegal number of initializers for packed structure type");
2092 // Check to ensure that constants are compatible with the type initializer!
2093 std::vector<Constant*> Fields;
2094 for (unsigned i = 0, e = $4->size(); i != e; ++i) {
2095 Constant *C = (*$4)[i].C;
2096 if (C->getType() != STy->getElementType(i))
2097 error("Expected type '" + STy->getElementType(i)->getDescription() +
2098 "' for element #" + utostr(i) + " of packed struct initializer");
2099 Fields.push_back(C);
2101 $$.C = ConstantStruct::get(STy, Fields);
2106 | Types '<' '{' '}' '>' {
2107 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2109 error("Cannot make packed struct constant with type: '" +
2110 $1.PAT->get()->getDescription() + "'");
2111 if (STy->getNumContainedTypes() != 0)
2112 error("Illegal number of initializers for packed structure type");
2113 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2118 const PointerType *PTy = dyn_cast<PointerType>($1.PAT->get());
2120 error("Cannot make null pointer constant with type: '" +
2121 $1.PAT->get()->getDescription() + "'");
2122 $$.C = ConstantPointerNull::get(PTy);
2127 $$.C = UndefValue::get($1.PAT->get());
2131 | Types SymbolicValueRef {
2132 const PointerType *Ty = dyn_cast<PointerType>($1.PAT->get());
2134 error("Global const reference must be a pointer type, not" +
2135 $1.PAT->get()->getDescription());
2137 // ConstExprs can exist in the body of a function, thus creating
2138 // GlobalValues whenever they refer to a variable. Because we are in
2139 // the context of a function, getExistingValue will search the functions
2140 // symbol table instead of the module symbol table for the global symbol,
2141 // which throws things all off. To get around this, we just tell
2142 // getExistingValue that we are at global scope here.
2144 Function *SavedCurFn = CurFun.CurrentFunction;
2145 CurFun.CurrentFunction = 0;
2146 Value *V = getExistingValue(Ty, $2);
2147 CurFun.CurrentFunction = SavedCurFn;
2149 // If this is an initializer for a constant pointer, which is referencing a
2150 // (currently) undefined variable, create a stub now that shall be replaced
2151 // in the future with the right type of variable.
2154 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers");
2155 const PointerType *PT = cast<PointerType>(Ty);
2157 // First check to see if the forward references value is already created!
2158 PerModuleInfo::GlobalRefsType::iterator I =
2159 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
2161 if (I != CurModule.GlobalRefs.end()) {
2162 V = I->second; // Placeholder already exists, use it...
2166 if ($2.Type == ValID::NameVal) Name = $2.Name;
2168 // Create the forward referenced global.
2170 if (const FunctionType *FTy =
2171 dyn_cast<FunctionType>(PT->getElementType())) {
2172 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
2173 CurModule.CurrentModule);
2175 GV = new GlobalVariable(PT->getElementType(), false,
2176 GlobalValue::ExternalLinkage, 0,
2177 Name, CurModule.CurrentModule);
2180 // Keep track of the fact that we have a forward ref to recycle it
2181 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
2185 $$.C = cast<GlobalValue>(V);
2187 delete $1.PAT; // Free the type handle
2190 if ($1.PAT->get() != $2.C->getType())
2191 error("Mismatched types for constant expression");
2196 | Types ZEROINITIALIZER {
2197 const Type *Ty = $1.PAT->get();
2198 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
2199 error("Cannot create a null initialized value of this type");
2200 $$.C = Constant::getNullValue(Ty);
2204 | SIntType EINT64VAL { // integral constants
2205 const Type *Ty = $1.T;
2206 if (!ConstantInt::isValueValidForType(Ty, $2))
2207 error("Constant value doesn't fit in type");
2208 $$.C = ConstantInt::get(Ty, $2);
2211 | UIntType EUINT64VAL { // integral constants
2212 const Type *Ty = $1.T;
2213 if (!ConstantInt::isValueValidForType(Ty, $2))
2214 error("Constant value doesn't fit in type");
2215 $$.C = ConstantInt::get(Ty, $2);
2218 | BOOL TRUETOK { // Boolean constants
2219 $$.C = ConstantInt::get(Type::Int1Ty, true);
2222 | BOOL FALSETOK { // Boolean constants
2223 $$.C = ConstantInt::get(Type::Int1Ty, false);
2226 | FPType FPVAL { // Float & Double constants
2227 if (!ConstantFP::isValueValidForType($1.T, $2))
2228 error("Floating point constant invalid for type");
2229 $$.C = ConstantFP::get($1.T, $2);
2235 : CastOps '(' ConstVal TO Types ')' {
2236 const Type* SrcTy = $3.C->getType();
2237 const Type* DstTy = $5.PAT->get();
2238 Signedness SrcSign = $3.S;
2239 Signedness DstSign = $5.S;
2240 if (!SrcTy->isFirstClassType())
2241 error("cast constant expression from a non-primitive type: '" +
2242 SrcTy->getDescription() + "'");
2243 if (!DstTy->isFirstClassType())
2244 error("cast constant expression to a non-primitive type: '" +
2245 DstTy->getDescription() + "'");
2246 $$.C = cast<Constant>(getCast($1, $3.C, SrcSign, DstTy, DstSign));
2250 | GETELEMENTPTR '(' ConstVal IndexList ')' {
2251 const Type *Ty = $3.C->getType();
2252 if (!isa<PointerType>(Ty))
2253 error("GetElementPtr requires a pointer operand");
2255 std::vector<Value*> VIndices;
2256 std::vector<Constant*> CIndices;
2257 upgradeGEPIndices($3.C->getType(), $4, VIndices, &CIndices);
2260 $$.C = ConstantExpr::getGetElementPtr($3.C, &CIndices[0], CIndices.size());
2263 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2264 if (!$3.C->getType()->isInteger() ||
2265 cast<IntegerType>($3.C->getType())->getBitWidth() != 1)
2266 error("Select condition must be bool type");
2267 if ($5.C->getType() != $7.C->getType())
2268 error("Select operand types must match");
2269 $$.C = ConstantExpr::getSelect($3.C, $5.C, $7.C);
2272 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
2273 const Type *Ty = $3.C->getType();
2274 if (Ty != $5.C->getType())
2275 error("Binary operator types must match");
2276 // First, make sure we're dealing with the right opcode by upgrading from
2277 // obsolete versions.
2278 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2280 // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
2281 // To retain backward compatibility with these early compilers, we emit a
2282 // cast to the appropriate integer type automatically if we are in the
2283 // broken case. See PR424 for more information.
2284 if (!isa<PointerType>(Ty)) {
2285 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2287 const Type *IntPtrTy = 0;
2288 switch (CurModule.CurrentModule->getPointerSize()) {
2289 case Module::Pointer32: IntPtrTy = Type::Int32Ty; break;
2290 case Module::Pointer64: IntPtrTy = Type::Int64Ty; break;
2291 default: error("invalid pointer binary constant expr");
2293 $$.C = ConstantExpr::get(Opcode,
2294 ConstantExpr::getCast(Instruction::PtrToInt, $3.C, IntPtrTy),
2295 ConstantExpr::getCast(Instruction::PtrToInt, $5.C, IntPtrTy));
2296 $$.C = ConstantExpr::getCast(Instruction::IntToPtr, $$.C, Ty);
2300 | LogicalOps '(' ConstVal ',' ConstVal ')' {
2301 const Type* Ty = $3.C->getType();
2302 if (Ty != $5.C->getType())
2303 error("Logical operator types must match");
2304 if (!Ty->isInteger()) {
2305 if (!isa<VectorType>(Ty) ||
2306 !cast<VectorType>(Ty)->getElementType()->isInteger())
2307 error("Logical operator requires integer operands");
2309 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2310 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2313 | SetCondOps '(' ConstVal ',' ConstVal ')' {
2314 const Type* Ty = $3.C->getType();
2315 if (Ty != $5.C->getType())
2316 error("setcc operand types must match");
2317 unsigned short pred;
2318 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $3.S);
2319 $$.C = ConstantExpr::getCompare(Opcode, $3.C, $5.C);
2322 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
2323 if ($4.C->getType() != $6.C->getType())
2324 error("icmp operand types must match");
2325 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2328 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
2329 if ($4.C->getType() != $6.C->getType())
2330 error("fcmp operand types must match");
2331 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2334 | ShiftOps '(' ConstVal ',' ConstVal ')' {
2335 if (!$5.C->getType()->isInteger() ||
2336 cast<IntegerType>($5.C->getType())->getBitWidth() != 8)
2337 error("Shift count for shift constant must be unsigned byte");
2338 const Type* Ty = $3.C->getType();
2339 if (!$3.C->getType()->isInteger())
2340 error("Shift constant expression requires integer operand");
2341 Constant *ShiftAmt = ConstantExpr::getZExt($5.C, Ty);
2342 $$.C = ConstantExpr::get(getBinaryOp($1, Ty, $3.S), $3.C, ShiftAmt);
2345 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
2346 if (!ExtractElementInst::isValidOperands($3.C, $5.C))
2347 error("Invalid extractelement operands");
2348 $$.C = ConstantExpr::getExtractElement($3.C, $5.C);
2351 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2352 if (!InsertElementInst::isValidOperands($3.C, $5.C, $7.C))
2353 error("Invalid insertelement operands");
2354 $$.C = ConstantExpr::getInsertElement($3.C, $5.C, $7.C);
2357 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2358 if (!ShuffleVectorInst::isValidOperands($3.C, $5.C, $7.C))
2359 error("Invalid shufflevector operands");
2360 $$.C = ConstantExpr::getShuffleVector($3.C, $5.C, $7.C);
2366 // ConstVector - A list of comma separated constants.
2368 : ConstVector ',' ConstVal { ($$ = $1)->push_back($3); }
2370 $$ = new std::vector<ConstInfo>();
2376 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
2378 : GLOBAL { $$ = false; }
2379 | CONSTANT { $$ = true; }
2383 //===----------------------------------------------------------------------===//
2384 // Rules to match Modules
2385 //===----------------------------------------------------------------------===//
2387 // Module rule: Capture the result of parsing the whole file into a result
2392 $$ = ParserResult = $1;
2393 CurModule.ModuleDone();
2397 // FunctionList - A list of functions, preceeded by a constant pool.
2400 : FunctionList Function { $$ = $1; CurFun.FunctionDone(); }
2401 | FunctionList FunctionProto { $$ = $1; }
2402 | FunctionList MODULE ASM_TOK AsmBlock { $$ = $1; }
2403 | FunctionList IMPLEMENTATION { $$ = $1; }
2405 $$ = CurModule.CurrentModule;
2406 // Emit an error if there are any unresolved types left.
2407 if (!CurModule.LateResolveTypes.empty()) {
2408 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
2409 if (DID.Type == ValID::NameVal) {
2410 error("Reference to an undefined type: '"+DID.getName() + "'");
2412 error("Reference to an undefined type: #" + itostr(DID.Num));
2418 // ConstPool - Constants with optional names assigned to them.
2420 : ConstPool OptAssign TYPE TypesV {
2421 // Eagerly resolve types. This is not an optimization, this is a
2422 // requirement that is due to the fact that we could have this:
2424 // %list = type { %list * }
2425 // %list = type { %list * } ; repeated type decl
2427 // If types are not resolved eagerly, then the two types will not be
2428 // determined to be the same type!
2430 const Type* Ty = $4.PAT->get();
2431 ResolveTypeTo($2, Ty, $4.S);
2433 if (!setTypeName(Ty, $2) && !$2) {
2434 // If this is a named type that is not a redefinition, add it to the slot
2436 CurModule.Types.push_back(Ty);
2440 | ConstPool FunctionProto { // Function prototypes can be in const pool
2442 | ConstPool MODULE ASM_TOK AsmBlock { // Asm blocks can be in the const pool
2444 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
2446 error("Global value initializer is not a constant");
2447 CurGV = ParseGlobalVariable($2, $3, $4, $5.C->getType(), $5.C, $5.S);
2448 } GlobalVarAttributes {
2451 | ConstPool OptAssign EXTERNAL GlobalType Types {
2452 const Type *Ty = $5.PAT->get();
2453 CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, Ty, 0,
2456 } GlobalVarAttributes {
2459 | ConstPool OptAssign DLLIMPORT GlobalType Types {
2460 const Type *Ty = $5.PAT->get();
2461 CurGV = ParseGlobalVariable($2, GlobalValue::DLLImportLinkage, $4, Ty, 0,
2464 } GlobalVarAttributes {
2467 | ConstPool OptAssign EXTERN_WEAK GlobalType Types {
2468 const Type *Ty = $5.PAT->get();
2470 ParseGlobalVariable($2, GlobalValue::ExternalWeakLinkage, $4, Ty, 0,
2473 } GlobalVarAttributes {
2476 | ConstPool TARGET TargetDefinition {
2478 | ConstPool DEPLIBS '=' LibrariesDefinition {
2480 | /* empty: end of list */ {
2486 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2487 char *EndStr = UnEscapeLexed($1, true);
2488 std::string NewAsm($1, EndStr);
2491 if (AsmSoFar.empty())
2492 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
2494 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
2499 : BIG { $$ = Module::BigEndian; }
2500 | LITTLE { $$ = Module::LittleEndian; }
2504 : ENDIAN '=' BigOrLittle {
2505 CurModule.setEndianness($3);
2507 | POINTERSIZE '=' EUINT64VAL {
2509 CurModule.setPointerSize(Module::Pointer32);
2511 CurModule.setPointerSize(Module::Pointer64);
2513 error("Invalid pointer size: '" + utostr($3) + "'");
2515 | TRIPLE '=' STRINGCONSTANT {
2516 CurModule.CurrentModule->setTargetTriple($3);
2519 | DATALAYOUT '=' STRINGCONSTANT {
2520 CurModule.CurrentModule->setDataLayout($3);
2530 : LibList ',' STRINGCONSTANT {
2531 CurModule.CurrentModule->addLibrary($3);
2535 CurModule.CurrentModule->addLibrary($1);
2538 | /* empty: end of list */ { }
2541 //===----------------------------------------------------------------------===//
2542 // Rules to match Function Headers
2543 //===----------------------------------------------------------------------===//
2546 : VAR_ID | STRINGCONSTANT
2551 | /*empty*/ { $$ = 0; }
2556 if ($1.PAT->get() == Type::VoidTy)
2557 error("void typed arguments are invalid");
2558 $$ = new std::pair<PATypeInfo, char*>($1, $2);
2563 : ArgListH ',' ArgVal {
2569 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2576 : ArgListH { $$ = $1; }
2577 | ArgListH ',' DOTDOTDOT {
2580 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2581 VoidTI.S = Signless;
2582 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2585 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2587 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2588 VoidTI.S = Signless;
2589 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2591 | /* empty */ { $$ = 0; }
2595 : OptCallingConv TypesV Name '(' ArgList ')' OptSection OptAlign {
2597 std::string FunctionName($3);
2598 free($3); // Free strdup'd memory!
2600 const Type* RetTy = $2.PAT->get();
2602 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
2603 error("LLVM functions cannot return aggregate types");
2605 std::vector<const Type*> ParamTyList;
2607 // In LLVM 2.0 the signatures of three varargs intrinsics changed to take
2608 // i8*. We check here for those names and override the parameter list
2609 // types to ensure the prototype is correct.
2610 if (FunctionName == "llvm.va_start" || FunctionName == "llvm.va_end") {
2611 ParamTyList.push_back(PointerType::get(Type::Int8Ty));
2612 } else if (FunctionName == "llvm.va_copy") {
2613 ParamTyList.push_back(PointerType::get(Type::Int8Ty));
2614 ParamTyList.push_back(PointerType::get(Type::Int8Ty));
2615 } else if ($5) { // If there are arguments...
2616 for (std::vector<std::pair<PATypeInfo,char*> >::iterator
2617 I = $5->begin(), E = $5->end(); I != E; ++I) {
2618 const Type *Ty = I->first.PAT->get();
2619 ParamTyList.push_back(Ty);
2623 bool isVarArg = ParamTyList.size() && ParamTyList.back() == Type::VoidTy;
2625 ParamTyList.pop_back();
2627 // Convert the CSRet calling convention into the corresponding parameter
2629 FunctionType::ParamAttrsList ParamAttrs;
2630 if ($1 == OldCallingConv::CSRet) {
2631 ParamAttrs.push_back(FunctionType::NoAttributeSet); // result
2632 ParamAttrs.push_back(FunctionType::StructRetAttribute); // first arg
2635 const FunctionType *FT = FunctionType::get(RetTy, ParamTyList, isVarArg,
2637 const PointerType *PFT = PointerType::get(FT);
2641 if (!FunctionName.empty()) {
2642 ID = ValID::create((char*)FunctionName.c_str(), $2.S);
2644 ID = ValID::create((int)CurModule.Values[PFT].size(), $2.S);
2648 Module* M = CurModule.CurrentModule;
2650 // See if this function was forward referenced. If so, recycle the object.
2651 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2652 // Move the function to the end of the list, from whereever it was
2653 // previously inserted.
2654 Fn = cast<Function>(FWRef);
2655 M->getFunctionList().remove(Fn);
2656 M->getFunctionList().push_back(Fn);
2657 } else if (!FunctionName.empty()) {
2658 GlobalValue *Conflict = M->getFunction(FunctionName);
2660 Conflict = M->getNamedGlobal(FunctionName);
2661 if (Conflict && PFT == Conflict->getType()) {
2662 if (!CurFun.isDeclare && !Conflict->isDeclaration()) {
2663 // We have two function definitions that conflict, same type, same
2664 // name. We should really check to make sure that this is the result
2665 // of integer type planes collapsing and generate an error if it is
2666 // not, but we'll just rename on the assumption that it is. However,
2667 // let's do it intelligently and rename the internal linkage one
2669 std::string NewName(makeNameUnique(FunctionName));
2670 if (Conflict->hasInternalLinkage()) {
2671 Conflict->setName(NewName);
2672 TypeInfo TI; TI.T = Conflict->getType(); TI.S = ID.S;
2673 RenameMapKey Key = std::make_pair(FunctionName,TI);
2674 CurModule.RenameMap[Key] = NewName;
2675 Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2676 InsertValue(Fn, CurModule.Values);
2678 Fn = new Function(FT, CurFun.Linkage, NewName, M);
2679 InsertValue(Fn, CurModule.Values);
2680 TypeInfo TI; TI.T = PFT; TI.S = ID.S;
2681 RenameMapKey Key = std::make_pair(FunctionName,TI);
2682 CurModule.RenameMap[Key] = NewName;
2685 // If they are not both definitions, then just use the function we
2686 // found since the types are the same.
2687 Fn = cast<Function>(Conflict);
2689 // Make sure to strip off any argument names so we can't get
2691 if (Fn->isDeclaration())
2692 for (Function::arg_iterator AI = Fn->arg_begin(),
2693 AE = Fn->arg_end(); AI != AE; ++AI)
2696 } else if (Conflict) {
2697 // We have two globals with the same name and different types.
2698 // Previously, this was permitted because the symbol table had
2699 // "type planes" and names only needed to be distinct within a
2700 // type plane. After PR411 was fixed, this is no loner the case.
2701 // To resolve this we must rename one of the two.
2702 if (Conflict->hasInternalLinkage()) {
2703 // We can safely renamed the Conflict.
2704 Conflict->setName(makeNameUnique(Conflict->getName()));
2705 TypeInfo TI; TI.T = Conflict->getType(); TI.S = ID.S;
2706 RenameMapKey Key = std::make_pair(FunctionName,TI);
2707 CurModule.RenameMap[Key] = Conflict->getName();
2708 Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2709 InsertValue(Fn, CurModule.Values);
2710 } else if (CurFun.Linkage == GlobalValue::InternalLinkage) {
2711 // We can safely rename the function we're defining
2712 std::string NewName = makeNameUnique(FunctionName);
2713 Fn = new Function(FT, CurFun.Linkage, NewName, M);
2714 InsertValue(Fn, CurModule.Values);
2715 TypeInfo TI; TI.T = PFT; TI.S = ID.S;
2716 RenameMapKey Key = std::make_pair(FunctionName,TI);
2717 CurModule.RenameMap[Key] = NewName;
2719 // We can't quietly rename either of these things, but we must
2720 // rename one of them. Generate a warning about the renaming and
2721 // elect to rename the thing we're now defining.
2722 std::string NewName = makeNameUnique(FunctionName);
2723 warning("Renaming function '" + FunctionName + "' as '" + NewName +
2724 "' may cause linkage errors");
2725 Fn = new Function(FT, CurFun.Linkage, NewName, M);
2726 InsertValue(Fn, CurModule.Values);
2727 TypeInfo TI; TI.T = PFT; TI.S = ID.S;
2728 RenameMapKey Key = std::make_pair(FunctionName,TI);
2729 CurModule.RenameMap[Key] = NewName;
2732 // There's no conflict, just define the function
2733 Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2734 InsertValue(Fn, CurModule.Values);
2738 CurFun.FunctionStart(Fn);
2740 if (CurFun.isDeclare) {
2741 // If we have declaration, always overwrite linkage. This will allow us
2742 // to correctly handle cases, when pointer to function is passed as
2743 // argument to another function.
2744 Fn->setLinkage(CurFun.Linkage);
2746 Fn->setCallingConv(upgradeCallingConv($1));
2747 Fn->setAlignment($8);
2753 // Add all of the arguments we parsed to the function...
2754 if ($5) { // Is null if empty...
2755 if (isVarArg) { // Nuke the last entry
2756 assert($5->back().first.PAT->get() == Type::VoidTy &&
2757 $5->back().second == 0 && "Not a varargs marker");
2758 delete $5->back().first.PAT;
2759 $5->pop_back(); // Delete the last entry
2761 Function::arg_iterator ArgIt = Fn->arg_begin();
2762 Function::arg_iterator ArgEnd = Fn->arg_end();
2763 std::vector<std::pair<PATypeInfo,char*> >::iterator I = $5->begin();
2764 std::vector<std::pair<PATypeInfo,char*> >::iterator E = $5->end();
2765 for ( ; I != E && ArgIt != ArgEnd; ++I, ++ArgIt) {
2766 delete I->first.PAT; // Delete the typeholder...
2767 ValueInfo VI; VI.V = ArgIt; VI.S = Signless; // FIXME: Sign
2768 setValueName(VI, I->second); // Insert arg into symtab...
2771 delete $5; // We're now done with the argument list
2777 : BEGINTOK | '{' // Allow BEGIN or '{' to start a function
2781 : OptLinkage FunctionHeaderH BEGIN {
2782 $$ = CurFun.CurrentFunction;
2784 // Make sure that we keep track of the linkage type even if there was a
2785 // previous "declare".
2791 : ENDTOK | '}' // Allow end of '}' to end a function
2795 : BasicBlockList END {
2800 : /*default*/ { $$ = GlobalValue::ExternalLinkage; }
2801 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
2802 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
2806 : DECLARE { CurFun.isDeclare = true; }
2807 FnDeclareLinkage { CurFun.Linkage = $3; } FunctionHeaderH {
2808 $$ = CurFun.CurrentFunction;
2809 CurFun.FunctionDone();
2814 //===----------------------------------------------------------------------===//
2815 // Rules to match Basic Blocks
2816 //===----------------------------------------------------------------------===//
2819 : /* empty */ { $$ = false; }
2820 | SIDEEFFECT { $$ = true; }
2824 // A reference to a direct constant
2825 : ESINT64VAL { $$ = ValID::create($1); }
2826 | EUINT64VAL { $$ = ValID::create($1); }
2827 | FPVAL { $$ = ValID::create($1); }
2829 $$ = ValID::create(ConstantInt::get(Type::Int1Ty, true), Signed);
2832 $$ = ValID::create(ConstantInt::get(Type::Int1Ty, false), Unsigned);
2834 | NULL_TOK { $$ = ValID::createNull(); }
2835 | UNDEF { $$ = ValID::createUndef(); }
2836 | ZEROINITIALIZER { $$ = ValID::createZeroInit(); }
2837 | '<' ConstVector '>' { // Nonempty unsized packed vector
2838 const Type *ETy = (*$2)[0].C->getType();
2839 int NumElements = $2->size();
2840 VectorType* pt = VectorType::get(ETy, NumElements);
2841 PATypeHolder* PTy = new PATypeHolder(
2842 HandleUpRefs(VectorType::get(ETy, NumElements)));
2844 // Verify all elements are correct type!
2845 std::vector<Constant*> Elems;
2846 for (unsigned i = 0; i < $2->size(); i++) {
2847 Constant *C = (*$2)[i].C;
2848 const Type *CTy = C->getType();
2850 error("Element #" + utostr(i) + " is not of type '" +
2851 ETy->getDescription() +"' as required!\nIt is of type '" +
2852 CTy->getDescription() + "'");
2855 $$ = ValID::create(ConstantVector::get(pt, Elems), Signless);
2856 delete PTy; delete $2;
2859 $$ = ValID::create($1.C, $1.S);
2861 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2862 char *End = UnEscapeLexed($3, true);
2863 std::string AsmStr = std::string($3, End);
2864 End = UnEscapeLexed($5, true);
2865 std::string Constraints = std::string($5, End);
2866 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2872 // SymbolicValueRef - Reference to one of two ways of symbolically refering to // another value.
2875 : INTVAL { $$ = ValID::create($1,Signless); }
2876 | Name { $$ = ValID::create($1,Signless); }
2879 // ValueRef - A reference to a definition... either constant or symbolic
2881 : SymbolicValueRef | ConstValueRef
2885 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2886 // type immediately preceeds the value reference, and allows complex constant
2887 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2890 const Type *Ty = $1.PAT->get();
2892 $$.V = getVal(Ty, $2);
2899 : BasicBlockList BasicBlock {
2902 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2907 // Basic blocks are terminated by branching instructions:
2908 // br, br/cc, switch, ret
2911 : InstructionList OptAssign BBTerminatorInst {
2912 ValueInfo VI; VI.V = $3; VI.S = Signless;
2913 setValueName(VI, $2);
2915 $1->getInstList().push_back($3);
2922 : InstructionList Inst {
2924 $1->getInstList().push_back($2.I);
2928 $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++,Signless),true);
2929 // Make sure to move the basic block to the correct location in the
2930 // function, instead of leaving it inserted wherever it was first
2932 Function::BasicBlockListType &BBL =
2933 CurFun.CurrentFunction->getBasicBlockList();
2934 BBL.splice(BBL.end(), BBL, $$);
2937 $$ = CurBB = getBBVal(ValID::create($1,Signless), true);
2938 // Make sure to move the basic block to the correct location in the
2939 // function, instead of leaving it inserted wherever it was first
2941 Function::BasicBlockListType &BBL =
2942 CurFun.CurrentFunction->getBasicBlockList();
2943 BBL.splice(BBL.end(), BBL, $$);
2947 Unwind : UNWIND | EXCEPT;
2950 : RET ResolvedVal { // Return with a result...
2951 $$ = new ReturnInst($2.V);
2953 | RET VOID { // Return with no result...
2954 $$ = new ReturnInst();
2956 | BR LABEL ValueRef { // Unconditional Branch...
2957 BasicBlock* tmpBB = getBBVal($3);
2958 $$ = new BranchInst(tmpBB);
2959 } // Conditional Branch...
2960 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2961 BasicBlock* tmpBBA = getBBVal($6);
2962 BasicBlock* tmpBBB = getBBVal($9);
2963 Value* tmpVal = getVal(Type::Int1Ty, $3);
2964 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2966 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2968 Value* tmpVal = getVal($2.T, $3);
2969 BasicBlock* tmpBB = getBBVal($6);
2970 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2972 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2974 for (; I != E; ++I) {
2975 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2976 S->addCase(CI, I->second);
2978 error("Switch case is constant, but not a simple integer");
2982 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2984 Value* tmpVal = getVal($2.T, $3);
2985 BasicBlock* tmpBB = getBBVal($6);
2986 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2989 | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
2990 TO LABEL ValueRef Unwind LABEL ValueRef {
2991 const PointerType *PFTy;
2992 const FunctionType *Ty;
2994 if (!(PFTy = dyn_cast<PointerType>($3.PAT->get())) ||
2995 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2996 // Pull out the types of all of the arguments...
2997 std::vector<const Type*> ParamTypes;
2999 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
3001 ParamTypes.push_back((*I).V->getType());
3003 FunctionType::ParamAttrsList ParamAttrs;
3004 if ($2 == OldCallingConv::CSRet) {
3005 ParamAttrs.push_back(FunctionType::NoAttributeSet);
3006 ParamAttrs.push_back(FunctionType::StructRetAttribute);
3008 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
3009 if (isVarArg) ParamTypes.pop_back();
3010 Ty = FunctionType::get($3.PAT->get(), ParamTypes, isVarArg, ParamAttrs);
3011 PFTy = PointerType::get(Ty);
3013 Value *V = getVal(PFTy, $4); // Get the function we're calling...
3014 BasicBlock *Normal = getBBVal($10);
3015 BasicBlock *Except = getBBVal($13);
3017 // Create the call node...
3018 if (!$6) { // Has no arguments?
3019 $$ = new InvokeInst(V, Normal, Except, 0, 0);
3020 } else { // Has arguments?
3021 // Loop through FunctionType's arguments and ensure they are specified
3024 FunctionType::param_iterator I = Ty->param_begin();
3025 FunctionType::param_iterator E = Ty->param_end();
3026 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
3028 std::vector<Value*> Args;
3029 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
3030 if ((*ArgI).V->getType() != *I)
3031 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
3032 (*I)->getDescription() + "'");
3033 Args.push_back((*ArgI).V);
3036 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
3037 error("Invalid number of parameters detected");
3039 $$ = new InvokeInst(V, Normal, Except, &Args[0], Args.size());
3041 cast<InvokeInst>($$)->setCallingConv(upgradeCallingConv($2));
3046 $$ = new UnwindInst();
3049 $$ = new UnreachableInst();
3054 : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
3057 Constant *V = cast<Constant>(getExistingValue($2.T, $3));
3060 error("May only switch on a constant pool value");
3062 BasicBlock* tmpBB = getBBVal($6);
3063 $$->push_back(std::make_pair(V, tmpBB));
3065 | IntType ConstValueRef ',' LABEL ValueRef {
3066 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
3068 Constant *V = cast<Constant>(getExistingValue($1.T, $2));
3071 error("May only switch on a constant pool value");
3073 BasicBlock* tmpBB = getBBVal($5);
3074 $$->push_back(std::make_pair(V, tmpBB));
3079 : OptAssign InstVal {
3082 if (BitCastInst *BCI = dyn_cast<BitCastInst>($2.I))
3083 if (BCI->getSrcTy() == BCI->getDestTy() &&
3084 BCI->getOperand(0)->getName() == $1)
3085 // This is a useless bit cast causing a name redefinition. It is
3086 // a bit cast from a type to the same type of an operand with the
3087 // same name as the name we would give this instruction. Since this
3088 // instruction results in no code generation, it is safe to omit
3089 // the instruction. This situation can occur because of collapsed
3090 // type planes. For example:
3091 // %X = add int %Y, %Z
3092 // %X = cast int %Y to uint
3093 // After upgrade, this looks like:
3094 // %X = add i32 %Y, %Z
3095 // %X = bitcast i32 to i32
3096 // The bitcast is clearly useless so we omit it.
3102 ValueInfo VI; VI.V = $2.I; VI.S = $2.S;
3103 setValueName(VI, $1);
3109 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
3110 $$.P = new std::list<std::pair<Value*, BasicBlock*> >();
3113 Value* tmpVal = getVal($1.PAT->get(), $3);
3114 BasicBlock* tmpBB = getBBVal($5);
3115 $$.P->push_back(std::make_pair(tmpVal, tmpBB));
3118 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
3121 Value* tmpVal = getVal($1.P->front().first->getType(), $4);
3122 BasicBlock* tmpBB = getBBVal($6);
3123 $1.P->push_back(std::make_pair(tmpVal, tmpBB));
3127 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
3128 $$ = new std::vector<ValueInfo>();
3131 | ValueRefList ',' ResolvedVal {
3136 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
3139 | /*empty*/ { $$ = 0; }
3152 : ArithmeticOps Types ValueRef ',' ValueRef {
3154 const Type* Ty = $2.PAT->get();
3155 if (!Ty->isInteger() && !Ty->isFloatingPoint() && !isa<VectorType>(Ty))
3156 error("Arithmetic operator requires integer, FP, or packed operands");
3157 if (isa<VectorType>(Ty) &&
3158 ($1 == URemOp || $1 == SRemOp || $1 == FRemOp || $1 == RemOp))
3159 error("Remainder not supported on vector types");
3160 // Upgrade the opcode from obsolete versions before we do anything with it.
3161 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3162 Value* val1 = getVal(Ty, $3);
3163 Value* val2 = getVal(Ty, $5);
3164 $$.I = BinaryOperator::create(Opcode, val1, val2);
3166 error("binary operator returned null");
3170 | LogicalOps Types ValueRef ',' ValueRef {
3172 const Type *Ty = $2.PAT->get();
3173 if (!Ty->isInteger()) {
3174 if (!isa<VectorType>(Ty) ||
3175 !cast<VectorType>(Ty)->getElementType()->isInteger())
3176 error("Logical operator requires integral operands");
3178 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3179 Value* tmpVal1 = getVal(Ty, $3);
3180 Value* tmpVal2 = getVal(Ty, $5);
3181 $$.I = BinaryOperator::create(Opcode, tmpVal1, tmpVal2);
3183 error("binary operator returned null");
3187 | SetCondOps Types ValueRef ',' ValueRef {
3189 const Type* Ty = $2.PAT->get();
3190 if(isa<VectorType>(Ty))
3191 error("VectorTypes currently not supported in setcc instructions");
3192 unsigned short pred;
3193 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $2.S);
3194 Value* tmpVal1 = getVal(Ty, $3);
3195 Value* tmpVal2 = getVal(Ty, $5);
3196 $$.I = CmpInst::create(Opcode, pred, tmpVal1, tmpVal2);
3198 error("binary operator returned null");
3202 | ICMP IPredicates Types ValueRef ',' ValueRef {
3204 const Type *Ty = $3.PAT->get();
3205 if (isa<VectorType>(Ty))
3206 error("VectorTypes currently not supported in icmp instructions");
3207 else if (!Ty->isInteger() && !isa<PointerType>(Ty))
3208 error("icmp requires integer or pointer typed operands");
3209 Value* tmpVal1 = getVal(Ty, $4);
3210 Value* tmpVal2 = getVal(Ty, $6);
3211 $$.I = new ICmpInst($2, tmpVal1, tmpVal2);
3215 | FCMP FPredicates Types ValueRef ',' ValueRef {
3217 const Type *Ty = $3.PAT->get();
3218 if (isa<VectorType>(Ty))
3219 error("VectorTypes currently not supported in fcmp instructions");
3220 else if (!Ty->isFloatingPoint())
3221 error("fcmp instruction requires floating point operands");
3222 Value* tmpVal1 = getVal(Ty, $4);
3223 Value* tmpVal2 = getVal(Ty, $6);
3224 $$.I = new FCmpInst($2, tmpVal1, tmpVal2);
3229 warning("Use of obsolete 'not' instruction: Replacing with 'xor");
3230 const Type *Ty = $2.V->getType();
3231 Value *Ones = ConstantInt::getAllOnesValue(Ty);
3233 error("Expected integral type for not instruction");
3234 $$.I = BinaryOperator::create(Instruction::Xor, $2.V, Ones);
3236 error("Could not create a xor instruction");
3239 | ShiftOps ResolvedVal ',' ResolvedVal {
3240 if (!$4.V->getType()->isInteger() ||
3241 cast<IntegerType>($4.V->getType())->getBitWidth() != 8)
3242 error("Shift amount must be int8");
3243 const Type* Ty = $2.V->getType();
3244 if (!Ty->isInteger())
3245 error("Shift constant expression requires integer operand");
3246 Value* ShiftAmt = 0;
3247 if (cast<IntegerType>(Ty)->getBitWidth() > Type::Int8Ty->getBitWidth())
3248 if (Constant *C = dyn_cast<Constant>($4.V))
3249 ShiftAmt = ConstantExpr::getZExt(C, Ty);
3251 ShiftAmt = new ZExtInst($4.V, Ty, makeNameUnique("shift"), CurBB);
3254 $$.I = BinaryOperator::create(getBinaryOp($1, Ty, $2.S), $2.V, ShiftAmt);
3257 | CastOps ResolvedVal TO Types {
3258 const Type *DstTy = $4.PAT->get();
3259 if (!DstTy->isFirstClassType())
3260 error("cast instruction to a non-primitive type: '" +
3261 DstTy->getDescription() + "'");
3262 $$.I = cast<Instruction>(getCast($1, $2.V, $2.S, DstTy, $4.S, true));
3266 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3267 if (!$2.V->getType()->isInteger() ||
3268 cast<IntegerType>($2.V->getType())->getBitWidth() != 1)
3269 error("select condition must be bool");
3270 if ($4.V->getType() != $6.V->getType())
3271 error("select value types should match");
3272 $$.I = new SelectInst($2.V, $4.V, $6.V);
3275 | VAARG ResolvedVal ',' Types {
3276 const Type *Ty = $4.PAT->get();
3278 $$.I = new VAArgInst($2.V, Ty);
3282 | VAARG_old ResolvedVal ',' Types {
3283 const Type* ArgTy = $2.V->getType();
3284 const Type* DstTy = $4.PAT->get();
3285 ObsoleteVarArgs = true;
3286 Function* NF = cast<Function>(CurModule.CurrentModule->
3287 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3290 //foo = alloca 1 of t
3294 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
3295 CurBB->getInstList().push_back(foo);
3296 CallInst* bar = new CallInst(NF, $2.V);
3297 CurBB->getInstList().push_back(bar);
3298 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3299 $$.I = new VAArgInst(foo, DstTy);
3303 | VANEXT_old ResolvedVal ',' Types {
3304 const Type* ArgTy = $2.V->getType();
3305 const Type* DstTy = $4.PAT->get();
3306 ObsoleteVarArgs = true;
3307 Function* NF = cast<Function>(CurModule.CurrentModule->
3308 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3310 //b = vanext a, t ->
3311 //foo = alloca 1 of t
3314 //tmp = vaarg foo, t
3316 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
3317 CurBB->getInstList().push_back(foo);
3318 CallInst* bar = new CallInst(NF, $2.V);
3319 CurBB->getInstList().push_back(bar);
3320 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3321 Instruction* tmp = new VAArgInst(foo, DstTy);
3322 CurBB->getInstList().push_back(tmp);
3323 $$.I = new LoadInst(foo);
3327 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
3328 if (!ExtractElementInst::isValidOperands($2.V, $4.V))
3329 error("Invalid extractelement operands");
3330 $$.I = new ExtractElementInst($2.V, $4.V);
3333 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3334 if (!InsertElementInst::isValidOperands($2.V, $4.V, $6.V))
3335 error("Invalid insertelement operands");
3336 $$.I = new InsertElementInst($2.V, $4.V, $6.V);
3339 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3340 if (!ShuffleVectorInst::isValidOperands($2.V, $4.V, $6.V))
3341 error("Invalid shufflevector operands");
3342 $$.I = new ShuffleVectorInst($2.V, $4.V, $6.V);
3346 const Type *Ty = $2.P->front().first->getType();
3347 if (!Ty->isFirstClassType())
3348 error("PHI node operands must be of first class type");
3349 PHINode *PHI = new PHINode(Ty);
3350 PHI->reserveOperandSpace($2.P->size());
3351 while ($2.P->begin() != $2.P->end()) {
3352 if ($2.P->front().first->getType() != Ty)
3353 error("All elements of a PHI node must be of the same type");
3354 PHI->addIncoming($2.P->front().first, $2.P->front().second);
3359 delete $2.P; // Free the list...
3361 | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')' {
3362 // Handle the short call syntax
3363 const PointerType *PFTy;
3364 const FunctionType *FTy;
3365 if (!(PFTy = dyn_cast<PointerType>($3.PAT->get())) ||
3366 !(FTy = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3367 // Pull out the types of all of the arguments...
3368 std::vector<const Type*> ParamTypes;
3370 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
3372 ParamTypes.push_back((*I).V->getType());
3375 FunctionType::ParamAttrsList ParamAttrs;
3376 if ($2 == OldCallingConv::CSRet) {
3377 ParamAttrs.push_back(FunctionType::NoAttributeSet);
3378 ParamAttrs.push_back(FunctionType::StructRetAttribute);
3380 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
3381 if (isVarArg) ParamTypes.pop_back();
3383 const Type *RetTy = $3.PAT->get();
3384 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
3385 error("Functions cannot return aggregate types");
3387 FTy = FunctionType::get(RetTy, ParamTypes, isVarArg, ParamAttrs);
3388 PFTy = PointerType::get(FTy);
3391 // First upgrade any intrinsic calls.
3392 std::vector<Value*> Args;
3394 for (unsigned i = 0, e = $6->size(); i < e; ++i)
3395 Args.push_back((*$6)[i].V);
3396 Instruction *Inst = upgradeIntrinsicCall(FTy, $4, Args);
3398 // If we got an upgraded intrinsic
3403 // Get the function we're calling
3404 Value *V = getVal(PFTy, $4);
3406 // Check the argument values match
3407 if (!$6) { // Has no arguments?
3408 // Make sure no arguments is a good thing!
3409 if (FTy->getNumParams() != 0)
3410 error("No arguments passed to a function that expects arguments");
3411 } else { // Has arguments?
3412 // Loop through FunctionType's arguments and ensure they are specified
3415 FunctionType::param_iterator I = FTy->param_begin();
3416 FunctionType::param_iterator E = FTy->param_end();
3417 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
3419 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
3420 if ((*ArgI).V->getType() != *I)
3421 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
3422 (*I)->getDescription() + "'");
3424 if (I != E || (ArgI != ArgE && !FTy->isVarArg()))
3425 error("Invalid number of parameters detected");
3428 // Create the call instruction
3429 CallInst *CI = new CallInst(V, &Args[0], Args.size());
3430 CI->setTailCall($1);
3431 CI->setCallingConv(upgradeCallingConv($2));
3444 // IndexList - List of indices for GEP based instructions...
3446 : ',' ValueRefList { $$ = $2; }
3447 | /* empty */ { $$ = new std::vector<ValueInfo>(); }
3451 : VOLATILE { $$ = true; }
3452 | /* empty */ { $$ = false; }
3456 : MALLOC Types OptCAlign {
3457 const Type *Ty = $2.PAT->get();
3459 $$.I = new MallocInst(Ty, 0, $3);
3462 | MALLOC Types ',' UINT ValueRef OptCAlign {
3463 const Type *Ty = $2.PAT->get();
3466 $$.I = new MallocInst(Ty, getVal($4.T, $5), $6);
3469 | ALLOCA Types OptCAlign {
3470 const Type *Ty = $2.PAT->get();
3472 $$.I = new AllocaInst(Ty, 0, $3);
3475 | ALLOCA Types ',' UINT ValueRef OptCAlign {
3476 const Type *Ty = $2.PAT->get();
3479 $$.I = new AllocaInst(Ty, getVal($4.T, $5), $6);
3482 | FREE ResolvedVal {
3483 const Type *PTy = $2.V->getType();
3484 if (!isa<PointerType>(PTy))
3485 error("Trying to free nonpointer type '" + PTy->getDescription() + "'");
3486 $$.I = new FreeInst($2.V);
3489 | OptVolatile LOAD Types ValueRef {
3490 const Type* Ty = $3.PAT->get();
3493 if (!isa<PointerType>(Ty))
3494 error("Can't load from nonpointer type: " + Ty->getDescription());
3495 if (!cast<PointerType>(Ty)->getElementType()->isFirstClassType())
3496 error("Can't load from pointer of non-first-class type: " +
3497 Ty->getDescription());
3498 Value* tmpVal = getVal(Ty, $4);
3499 $$.I = new LoadInst(tmpVal, "", $1);
3502 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
3504 const PointerType *PTy = dyn_cast<PointerType>($5.PAT->get());
3506 error("Can't store to a nonpointer type: " +
3507 $5.PAT->get()->getDescription());
3508 const Type *ElTy = PTy->getElementType();
3509 Value *StoreVal = $3.V;
3510 Value* tmpVal = getVal(PTy, $6);
3511 if (ElTy != $3.V->getType()) {
3512 StoreVal = handleSRetFuncTypeMerge($3.V, ElTy);
3514 error("Can't store '" + $3.V->getType()->getDescription() +
3515 "' into space of type '" + ElTy->getDescription() + "'");
3517 PTy = PointerType::get(StoreVal->getType());
3518 if (Constant *C = dyn_cast<Constant>(tmpVal))
3519 tmpVal = ConstantExpr::getBitCast(C, PTy);
3521 tmpVal = new BitCastInst(tmpVal, PTy, "upgrd.cast", CurBB);
3524 $$.I = new StoreInst(StoreVal, tmpVal, $1);
3528 | GETELEMENTPTR Types ValueRef IndexList {
3530 const Type* Ty = $2.PAT->get();
3531 if (!isa<PointerType>(Ty))
3532 error("getelementptr insn requires pointer operand");
3534 std::vector<Value*> VIndices;
3535 upgradeGEPIndices(Ty, $4, VIndices);
3537 Value* tmpVal = getVal(Ty, $3);
3538 $$.I = new GetElementPtrInst(tmpVal, &VIndices[0], VIndices.size());
3547 int yyerror(const char *ErrorMsg) {
3549 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3550 + ":" + llvm::utostr((unsigned) Upgradelineno) + ": ";
3551 std::string errMsg = where + "error: " + std::string(ErrorMsg);
3552 if (yychar != YYEMPTY && yychar != 0)
3553 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3555 std::cerr << "llvm-upgrade: " << errMsg << '\n';
3556 std::cout << "llvm-upgrade: parse failed.\n";
3560 void warning(const std::string& ErrorMsg) {
3562 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3563 + ":" + llvm::utostr((unsigned) Upgradelineno) + ": ";
3564 std::string errMsg = where + "warning: " + std::string(ErrorMsg);
3565 if (yychar != YYEMPTY && yychar != 0)
3566 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3568 std::cerr << "llvm-upgrade: " << errMsg << '\n';
3571 void error(const std::string& ErrorMsg, int LineNo) {
3572 if (LineNo == -1) LineNo = Upgradelineno;
3573 Upgradelineno = LineNo;
3574 yyerror(ErrorMsg.c_str());