1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the parser class for .ll files.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/AutoUpgrade.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Metadata.h"
23 #include "llvm/Module.h"
24 #include "llvm/Operator.h"
25 #include "llvm/ValueSymbolTable.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
32 /// Run: module ::= toplevelentity*
33 bool LLParser::Run() {
37 return ParseTopLevelEntities() ||
38 ValidateEndOfModule();
41 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
43 bool LLParser::ValidateEndOfModule() {
44 // Update auto-upgraded malloc calls to "malloc".
45 // FIXME: Remove in LLVM 3.0.
47 MallocF->setName("malloc");
48 // If setName() does not set the name to "malloc", then there is already a
49 // declaration of "malloc". In that case, iterate over all calls to MallocF
50 // and get them to call the declared "malloc" instead.
51 if (MallocF->getName() != "malloc") {
52 Constant *RealMallocF = M->getFunction("malloc");
53 if (RealMallocF->getType() != MallocF->getType())
54 RealMallocF = ConstantExpr::getBitCast(RealMallocF, MallocF->getType());
55 MallocF->replaceAllUsesWith(RealMallocF);
56 MallocF->eraseFromParent();
62 // If there are entries in ForwardRefBlockAddresses at this point, they are
63 // references after the function was defined. Resolve those now.
64 while (!ForwardRefBlockAddresses.empty()) {
65 // Okay, we are referencing an already-parsed function, resolve them now.
67 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
68 if (Fn.Kind == ValID::t_GlobalName)
69 TheFn = M->getFunction(Fn.StrVal);
70 else if (Fn.UIntVal < NumberedVals.size())
71 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
74 return Error(Fn.Loc, "unknown function referenced by blockaddress");
76 // Resolve all these references.
77 if (ResolveForwardRefBlockAddresses(TheFn,
78 ForwardRefBlockAddresses.begin()->second,
82 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
86 if (!ForwardRefTypes.empty())
87 return Error(ForwardRefTypes.begin()->second.second,
88 "use of undefined type named '" +
89 ForwardRefTypes.begin()->first + "'");
90 if (!ForwardRefTypeIDs.empty())
91 return Error(ForwardRefTypeIDs.begin()->second.second,
92 "use of undefined type '%" +
93 utostr(ForwardRefTypeIDs.begin()->first) + "'");
95 if (!ForwardRefVals.empty())
96 return Error(ForwardRefVals.begin()->second.second,
97 "use of undefined value '@" + ForwardRefVals.begin()->first +
100 if (!ForwardRefValIDs.empty())
101 return Error(ForwardRefValIDs.begin()->second.second,
102 "use of undefined value '@" +
103 utostr(ForwardRefValIDs.begin()->first) + "'");
105 if (!ForwardRefMDNodes.empty())
106 return Error(ForwardRefMDNodes.begin()->second.second,
107 "use of undefined metadata '!" +
108 utostr(ForwardRefMDNodes.begin()->first) + "'");
111 // Look for intrinsic functions and CallInst that need to be upgraded
112 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
113 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
115 // Check debug info intrinsics.
116 CheckDebugInfoIntrinsics(M);
120 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
121 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
122 PerFunctionState *PFS) {
123 // Loop over all the references, resolving them.
124 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
127 if (Refs[i].first.Kind == ValID::t_LocalName)
128 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
130 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
131 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
132 return Error(Refs[i].first.Loc,
133 "cannot take address of numeric label after the function is defined");
135 Res = dyn_cast_or_null<BasicBlock>(
136 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
140 return Error(Refs[i].first.Loc,
141 "referenced value is not a basic block");
143 // Get the BlockAddress for this and update references to use it.
144 BlockAddress *BA = BlockAddress::get(TheFn, Res);
145 Refs[i].second->replaceAllUsesWith(BA);
146 Refs[i].second->eraseFromParent();
152 //===----------------------------------------------------------------------===//
153 // Top-Level Entities
154 //===----------------------------------------------------------------------===//
156 bool LLParser::ParseTopLevelEntities() {
158 switch (Lex.getKind()) {
159 default: return TokError("expected top-level entity");
160 case lltok::Eof: return false;
161 //case lltok::kw_define:
162 case lltok::kw_declare: if (ParseDeclare()) return true; break;
163 case lltok::kw_define: if (ParseDefine()) return true; break;
164 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
165 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
166 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
167 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
168 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
169 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
170 case lltok::LocalVar: if (ParseNamedType()) return true; break;
171 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
172 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
173 case lltok::Metadata: if (ParseStandaloneMetadata()) return true; break;
174 case lltok::NamedOrCustomMD: if (ParseNamedMetadata()) return true; break;
176 // The Global variable production with no name can have many different
177 // optional leading prefixes, the production is:
178 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
179 // OptionalAddrSpace ('constant'|'global') ...
180 case lltok::kw_private : // OptionalLinkage
181 case lltok::kw_linker_private: // OptionalLinkage
182 case lltok::kw_internal: // OptionalLinkage
183 case lltok::kw_weak: // OptionalLinkage
184 case lltok::kw_weak_odr: // OptionalLinkage
185 case lltok::kw_linkonce: // OptionalLinkage
186 case lltok::kw_linkonce_odr: // OptionalLinkage
187 case lltok::kw_appending: // OptionalLinkage
188 case lltok::kw_dllexport: // OptionalLinkage
189 case lltok::kw_common: // OptionalLinkage
190 case lltok::kw_dllimport: // OptionalLinkage
191 case lltok::kw_extern_weak: // OptionalLinkage
192 case lltok::kw_external: { // OptionalLinkage
193 unsigned Linkage, Visibility;
194 if (ParseOptionalLinkage(Linkage) ||
195 ParseOptionalVisibility(Visibility) ||
196 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
200 case lltok::kw_default: // OptionalVisibility
201 case lltok::kw_hidden: // OptionalVisibility
202 case lltok::kw_protected: { // OptionalVisibility
204 if (ParseOptionalVisibility(Visibility) ||
205 ParseGlobal("", SMLoc(), 0, false, Visibility))
210 case lltok::kw_thread_local: // OptionalThreadLocal
211 case lltok::kw_addrspace: // OptionalAddrSpace
212 case lltok::kw_constant: // GlobalType
213 case lltok::kw_global: // GlobalType
214 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
222 /// ::= 'module' 'asm' STRINGCONSTANT
223 bool LLParser::ParseModuleAsm() {
224 assert(Lex.getKind() == lltok::kw_module);
228 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
229 ParseStringConstant(AsmStr)) return true;
231 const std::string &AsmSoFar = M->getModuleInlineAsm();
232 if (AsmSoFar.empty())
233 M->setModuleInlineAsm(AsmStr);
235 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
240 /// ::= 'target' 'triple' '=' STRINGCONSTANT
241 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
242 bool LLParser::ParseTargetDefinition() {
243 assert(Lex.getKind() == lltok::kw_target);
246 default: return TokError("unknown target property");
247 case lltok::kw_triple:
249 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
250 ParseStringConstant(Str))
252 M->setTargetTriple(Str);
254 case lltok::kw_datalayout:
256 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
257 ParseStringConstant(Str))
259 M->setDataLayout(Str);
265 /// ::= 'deplibs' '=' '[' ']'
266 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
267 bool LLParser::ParseDepLibs() {
268 assert(Lex.getKind() == lltok::kw_deplibs);
270 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
271 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
274 if (EatIfPresent(lltok::rsquare))
278 if (ParseStringConstant(Str)) return true;
281 while (EatIfPresent(lltok::comma)) {
282 if (ParseStringConstant(Str)) return true;
286 return ParseToken(lltok::rsquare, "expected ']' at end of list");
289 /// ParseUnnamedType:
291 /// ::= LocalVarID '=' 'type' type
292 bool LLParser::ParseUnnamedType() {
293 unsigned TypeID = NumberedTypes.size();
295 // Handle the LocalVarID form.
296 if (Lex.getKind() == lltok::LocalVarID) {
297 if (Lex.getUIntVal() != TypeID)
298 return Error(Lex.getLoc(), "type expected to be numbered '%" +
299 utostr(TypeID) + "'");
300 Lex.Lex(); // eat LocalVarID;
302 if (ParseToken(lltok::equal, "expected '=' after name"))
306 assert(Lex.getKind() == lltok::kw_type);
307 LocTy TypeLoc = Lex.getLoc();
308 Lex.Lex(); // eat kw_type
310 PATypeHolder Ty(Type::getVoidTy(Context));
311 if (ParseType(Ty)) return true;
313 // See if this type was previously referenced.
314 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
315 FI = ForwardRefTypeIDs.find(TypeID);
316 if (FI != ForwardRefTypeIDs.end()) {
317 if (FI->second.first.get() == Ty)
318 return Error(TypeLoc, "self referential type is invalid");
320 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
321 Ty = FI->second.first.get();
322 ForwardRefTypeIDs.erase(FI);
325 NumberedTypes.push_back(Ty);
331 /// ::= LocalVar '=' 'type' type
332 bool LLParser::ParseNamedType() {
333 std::string Name = Lex.getStrVal();
334 LocTy NameLoc = Lex.getLoc();
335 Lex.Lex(); // eat LocalVar.
337 PATypeHolder Ty(Type::getVoidTy(Context));
339 if (ParseToken(lltok::equal, "expected '=' after name") ||
340 ParseToken(lltok::kw_type, "expected 'type' after name") ||
344 // Set the type name, checking for conflicts as we do so.
345 bool AlreadyExists = M->addTypeName(Name, Ty);
346 if (!AlreadyExists) return false;
348 // See if this type is a forward reference. We need to eagerly resolve
349 // types to allow recursive type redefinitions below.
350 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
351 FI = ForwardRefTypes.find(Name);
352 if (FI != ForwardRefTypes.end()) {
353 if (FI->second.first.get() == Ty)
354 return Error(NameLoc, "self referential type is invalid");
356 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
357 Ty = FI->second.first.get();
358 ForwardRefTypes.erase(FI);
361 // Inserting a name that is already defined, get the existing name.
362 const Type *Existing = M->getTypeByName(Name);
363 assert(Existing && "Conflict but no matching type?!");
365 // Otherwise, this is an attempt to redefine a type. That's okay if
366 // the redefinition is identical to the original.
367 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
368 if (Existing == Ty) return false;
370 // Any other kind of (non-equivalent) redefinition is an error.
371 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
372 Ty->getDescription() + "'");
377 /// ::= 'declare' FunctionHeader
378 bool LLParser::ParseDeclare() {
379 assert(Lex.getKind() == lltok::kw_declare);
383 return ParseFunctionHeader(F, false);
387 /// ::= 'define' FunctionHeader '{' ...
388 bool LLParser::ParseDefine() {
389 assert(Lex.getKind() == lltok::kw_define);
393 return ParseFunctionHeader(F, true) ||
394 ParseFunctionBody(*F);
400 bool LLParser::ParseGlobalType(bool &IsConstant) {
401 if (Lex.getKind() == lltok::kw_constant)
403 else if (Lex.getKind() == lltok::kw_global)
407 return TokError("expected 'global' or 'constant'");
413 /// ParseUnnamedGlobal:
414 /// OptionalVisibility ALIAS ...
415 /// OptionalLinkage OptionalVisibility ... -> global variable
416 /// GlobalID '=' OptionalVisibility ALIAS ...
417 /// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
418 bool LLParser::ParseUnnamedGlobal() {
419 unsigned VarID = NumberedVals.size();
421 LocTy NameLoc = Lex.getLoc();
423 // Handle the GlobalID form.
424 if (Lex.getKind() == lltok::GlobalID) {
425 if (Lex.getUIntVal() != VarID)
426 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
427 utostr(VarID) + "'");
428 Lex.Lex(); // eat GlobalID;
430 if (ParseToken(lltok::equal, "expected '=' after name"))
435 unsigned Linkage, Visibility;
436 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
437 ParseOptionalVisibility(Visibility))
440 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
441 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
442 return ParseAlias(Name, NameLoc, Visibility);
445 /// ParseNamedGlobal:
446 /// GlobalVar '=' OptionalVisibility ALIAS ...
447 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
448 bool LLParser::ParseNamedGlobal() {
449 assert(Lex.getKind() == lltok::GlobalVar);
450 LocTy NameLoc = Lex.getLoc();
451 std::string Name = Lex.getStrVal();
455 unsigned Linkage, Visibility;
456 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
457 ParseOptionalLinkage(Linkage, HasLinkage) ||
458 ParseOptionalVisibility(Visibility))
461 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
462 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
463 return ParseAlias(Name, NameLoc, Visibility);
467 // ::= '!' STRINGCONSTANT
468 bool LLParser::ParseMDString(MetadataBase *&MDS) {
470 if (ParseStringConstant(Str)) return true;
471 MDS = MDString::get(Context, Str);
476 // ::= '!' MDNodeNumber
477 bool LLParser::ParseMDNode(MetadataBase *&Node) {
478 // !{ ..., !42, ... }
480 if (ParseUInt32(MID)) return true;
482 // Check existing MDNode.
483 std::map<unsigned, WeakVH>::iterator I = MetadataCache.find(MID);
484 if (I != MetadataCache.end()) {
485 Node = cast<MetadataBase>(I->second);
489 // Check known forward references.
490 std::map<unsigned, std::pair<WeakVH, LocTy> >::iterator
491 FI = ForwardRefMDNodes.find(MID);
492 if (FI != ForwardRefMDNodes.end()) {
493 Node = cast<MetadataBase>(FI->second.first);
497 // Create MDNode forward reference
498 SmallVector<Value *, 1> Elts;
499 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
500 Elts.push_back(MDString::get(Context, FwdRefName));
501 MDNode *FwdNode = MDNode::get(Context, Elts.data(), Elts.size());
502 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
507 ///ParseNamedMetadata:
508 /// !foo = !{ !1, !2 }
509 bool LLParser::ParseNamedMetadata() {
510 assert(Lex.getKind() == lltok::NamedOrCustomMD);
512 std::string Name = Lex.getStrVal();
514 if (ParseToken(lltok::equal, "expected '=' here"))
517 if (Lex.getKind() != lltok::Metadata)
518 return TokError("Expected '!' here");
521 if (Lex.getKind() != lltok::lbrace)
522 return TokError("Expected '{' here");
524 SmallVector<MetadataBase *, 8> Elts;
526 if (Lex.getKind() != lltok::Metadata)
527 return TokError("Expected '!' here");
530 if (ParseMDNode(N)) return true;
532 } while (EatIfPresent(lltok::comma));
534 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
537 NamedMDNode::Create(Context, Name, Elts.data(), Elts.size(), M);
541 /// ParseStandaloneMetadata:
543 bool LLParser::ParseStandaloneMetadata() {
544 assert(Lex.getKind() == lltok::Metadata);
546 unsigned MetadataID = 0;
547 if (ParseUInt32(MetadataID))
549 if (MetadataCache.find(MetadataID) != MetadataCache.end())
550 return TokError("Metadata id is already used");
551 if (ParseToken(lltok::equal, "expected '=' here"))
555 PATypeHolder Ty(Type::getVoidTy(Context));
556 if (ParseType(Ty, TyLoc))
559 if (Lex.getKind() != lltok::Metadata)
560 return TokError("Expected metadata here");
563 if (Lex.getKind() != lltok::lbrace)
564 return TokError("Expected '{' here");
566 SmallVector<Value *, 16> Elts;
567 if (ParseMDNodeVector(Elts)
568 || ParseToken(lltok::rbrace, "expected end of metadata node"))
571 MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
572 MetadataCache[MetadataID] = Init;
573 std::map<unsigned, std::pair<WeakVH, LocTy> >::iterator
574 FI = ForwardRefMDNodes.find(MetadataID);
575 if (FI != ForwardRefMDNodes.end()) {
576 MDNode *FwdNode = cast<MDNode>(FI->second.first);
577 FwdNode->replaceAllUsesWith(Init);
578 ForwardRefMDNodes.erase(FI);
585 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
588 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
589 /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
591 /// Everything through visibility has already been parsed.
593 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
594 unsigned Visibility) {
595 assert(Lex.getKind() == lltok::kw_alias);
598 LocTy LinkageLoc = Lex.getLoc();
599 if (ParseOptionalLinkage(Linkage))
602 if (Linkage != GlobalValue::ExternalLinkage &&
603 Linkage != GlobalValue::WeakAnyLinkage &&
604 Linkage != GlobalValue::WeakODRLinkage &&
605 Linkage != GlobalValue::InternalLinkage &&
606 Linkage != GlobalValue::PrivateLinkage &&
607 Linkage != GlobalValue::LinkerPrivateLinkage)
608 return Error(LinkageLoc, "invalid linkage type for alias");
611 LocTy AliaseeLoc = Lex.getLoc();
612 if (Lex.getKind() != lltok::kw_bitcast &&
613 Lex.getKind() != lltok::kw_getelementptr) {
614 if (ParseGlobalTypeAndValue(Aliasee)) return true;
616 // The bitcast dest type is not present, it is implied by the dest type.
618 if (ParseValID(ID)) return true;
619 if (ID.Kind != ValID::t_Constant)
620 return Error(AliaseeLoc, "invalid aliasee");
621 Aliasee = ID.ConstantVal;
624 if (!isa<PointerType>(Aliasee->getType()))
625 return Error(AliaseeLoc, "alias must have pointer type");
627 // Okay, create the alias but do not insert it into the module yet.
628 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
629 (GlobalValue::LinkageTypes)Linkage, Name,
631 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
633 // See if this value already exists in the symbol table. If so, it is either
634 // a redefinition or a definition of a forward reference.
635 if (GlobalValue *Val = M->getNamedValue(Name)) {
636 // See if this was a redefinition. If so, there is no entry in
638 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
639 I = ForwardRefVals.find(Name);
640 if (I == ForwardRefVals.end())
641 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
643 // Otherwise, this was a definition of forward ref. Verify that types
645 if (Val->getType() != GA->getType())
646 return Error(NameLoc,
647 "forward reference and definition of alias have different types");
649 // If they agree, just RAUW the old value with the alias and remove the
651 Val->replaceAllUsesWith(GA);
652 Val->eraseFromParent();
653 ForwardRefVals.erase(I);
656 // Insert into the module, we know its name won't collide now.
657 M->getAliasList().push_back(GA);
658 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
664 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
665 /// OptionalAddrSpace GlobalType Type Const
666 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
667 /// OptionalAddrSpace GlobalType Type Const
669 /// Everything through visibility has been parsed already.
671 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
672 unsigned Linkage, bool HasLinkage,
673 unsigned Visibility) {
675 bool ThreadLocal, IsConstant;
678 PATypeHolder Ty(Type::getVoidTy(Context));
679 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
680 ParseOptionalAddrSpace(AddrSpace) ||
681 ParseGlobalType(IsConstant) ||
682 ParseType(Ty, TyLoc))
685 // If the linkage is specified and is external, then no initializer is
688 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
689 Linkage != GlobalValue::ExternalWeakLinkage &&
690 Linkage != GlobalValue::ExternalLinkage)) {
691 if (ParseGlobalValue(Ty, Init))
695 if (isa<FunctionType>(Ty) || Ty->isLabelTy())
696 return Error(TyLoc, "invalid type for global variable");
698 GlobalVariable *GV = 0;
700 // See if the global was forward referenced, if so, use the global.
702 if (GlobalValue *GVal = M->getNamedValue(Name)) {
703 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
704 return Error(NameLoc, "redefinition of global '@" + Name + "'");
705 GV = cast<GlobalVariable>(GVal);
708 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
709 I = ForwardRefValIDs.find(NumberedVals.size());
710 if (I != ForwardRefValIDs.end()) {
711 GV = cast<GlobalVariable>(I->second.first);
712 ForwardRefValIDs.erase(I);
717 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
718 Name, 0, false, AddrSpace);
720 if (GV->getType()->getElementType() != Ty)
722 "forward reference and definition of global have different types");
724 // Move the forward-reference to the correct spot in the module.
725 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
729 NumberedVals.push_back(GV);
731 // Set the parsed properties on the global.
733 GV->setInitializer(Init);
734 GV->setConstant(IsConstant);
735 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
736 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
737 GV->setThreadLocal(ThreadLocal);
739 // Parse attributes on the global.
740 while (Lex.getKind() == lltok::comma) {
743 if (Lex.getKind() == lltok::kw_section) {
745 GV->setSection(Lex.getStrVal());
746 if (ParseToken(lltok::StringConstant, "expected global section string"))
748 } else if (Lex.getKind() == lltok::kw_align) {
750 if (ParseOptionalAlignment(Alignment)) return true;
751 GV->setAlignment(Alignment);
753 TokError("unknown global variable property!");
761 //===----------------------------------------------------------------------===//
762 // GlobalValue Reference/Resolution Routines.
763 //===----------------------------------------------------------------------===//
765 /// GetGlobalVal - Get a value with the specified name or ID, creating a
766 /// forward reference record if needed. This can return null if the value
767 /// exists but does not have the right type.
768 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
770 const PointerType *PTy = dyn_cast<PointerType>(Ty);
772 Error(Loc, "global variable reference must have pointer type");
776 // Look this name up in the normal function symbol table.
778 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
780 // If this is a forward reference for the value, see if we already created a
781 // forward ref record.
783 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
784 I = ForwardRefVals.find(Name);
785 if (I != ForwardRefVals.end())
786 Val = I->second.first;
789 // If we have the value in the symbol table or fwd-ref table, return it.
791 if (Val->getType() == Ty) return Val;
792 Error(Loc, "'@" + Name + "' defined with type '" +
793 Val->getType()->getDescription() + "'");
797 // Otherwise, create a new forward reference for this value and remember it.
799 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
800 // Function types can return opaque but functions can't.
801 if (isa<OpaqueType>(FT->getReturnType())) {
802 Error(Loc, "function may not return opaque type");
806 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
808 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
809 GlobalValue::ExternalWeakLinkage, 0, Name);
812 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
816 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
817 const PointerType *PTy = dyn_cast<PointerType>(Ty);
819 Error(Loc, "global variable reference must have pointer type");
823 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
825 // If this is a forward reference for the value, see if we already created a
826 // forward ref record.
828 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
829 I = ForwardRefValIDs.find(ID);
830 if (I != ForwardRefValIDs.end())
831 Val = I->second.first;
834 // If we have the value in the symbol table or fwd-ref table, return it.
836 if (Val->getType() == Ty) return Val;
837 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
838 Val->getType()->getDescription() + "'");
842 // Otherwise, create a new forward reference for this value and remember it.
844 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
845 // Function types can return opaque but functions can't.
846 if (isa<OpaqueType>(FT->getReturnType())) {
847 Error(Loc, "function may not return opaque type");
850 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
852 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
853 GlobalValue::ExternalWeakLinkage, 0, "");
856 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
861 //===----------------------------------------------------------------------===//
863 //===----------------------------------------------------------------------===//
865 /// ParseToken - If the current token has the specified kind, eat it and return
866 /// success. Otherwise, emit the specified error and return failure.
867 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
868 if (Lex.getKind() != T)
869 return TokError(ErrMsg);
874 /// ParseStringConstant
875 /// ::= StringConstant
876 bool LLParser::ParseStringConstant(std::string &Result) {
877 if (Lex.getKind() != lltok::StringConstant)
878 return TokError("expected string constant");
879 Result = Lex.getStrVal();
886 bool LLParser::ParseUInt32(unsigned &Val) {
887 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
888 return TokError("expected integer");
889 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
890 if (Val64 != unsigned(Val64))
891 return TokError("expected 32-bit integer (too large)");
898 /// ParseOptionalAddrSpace
900 /// := 'addrspace' '(' uint32 ')'
901 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
903 if (!EatIfPresent(lltok::kw_addrspace))
905 return ParseToken(lltok::lparen, "expected '(' in address space") ||
906 ParseUInt32(AddrSpace) ||
907 ParseToken(lltok::rparen, "expected ')' in address space");
910 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
911 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
912 /// 2: function attr.
913 /// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
914 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
915 Attrs = Attribute::None;
916 LocTy AttrLoc = Lex.getLoc();
919 switch (Lex.getKind()) {
922 // Treat these as signext/zeroext if they occur in the argument list after
923 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
924 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
926 // FIXME: REMOVE THIS IN LLVM 3.0
928 if (Lex.getKind() == lltok::kw_sext)
929 Attrs |= Attribute::SExt;
931 Attrs |= Attribute::ZExt;
935 default: // End of attributes.
936 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
937 return Error(AttrLoc, "invalid use of function-only attribute");
939 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
940 return Error(AttrLoc, "invalid use of parameter-only attribute");
943 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
944 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
945 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
946 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
947 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
948 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
949 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
950 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
952 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
953 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
954 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
955 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
956 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
957 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
958 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
959 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
960 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
961 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
962 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
963 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
964 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
966 case lltok::kw_align: {
968 if (ParseOptionalAlignment(Alignment))
970 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
978 /// ParseOptionalLinkage
981 /// ::= 'linker_private'
986 /// ::= 'linkonce_odr'
991 /// ::= 'extern_weak'
993 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
995 switch (Lex.getKind()) {
996 default: Res=GlobalValue::ExternalLinkage; return false;
997 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
998 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
999 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1000 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1001 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1002 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1003 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1004 case lltok::kw_available_externally:
1005 Res = GlobalValue::AvailableExternallyLinkage;
1007 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1008 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1009 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1010 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1011 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1012 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1019 /// ParseOptionalVisibility
1025 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1026 switch (Lex.getKind()) {
1027 default: Res = GlobalValue::DefaultVisibility; return false;
1028 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1029 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1030 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1036 /// ParseOptionalCallingConv
1041 /// ::= 'x86_stdcallcc'
1042 /// ::= 'x86_fastcallcc'
1043 /// ::= 'arm_apcscc'
1044 /// ::= 'arm_aapcscc'
1045 /// ::= 'arm_aapcs_vfpcc'
1048 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1049 switch (Lex.getKind()) {
1050 default: CC = CallingConv::C; return false;
1051 case lltok::kw_ccc: CC = CallingConv::C; break;
1052 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1053 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1054 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1055 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1056 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1057 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1058 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1059 case lltok::kw_cc: {
1060 unsigned ArbitraryCC;
1062 if (ParseUInt32(ArbitraryCC)) {
1065 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1075 /// ParseOptionalCustomMetadata
1078 bool LLParser::ParseOptionalCustomMetadata() {
1079 if (Lex.getKind() != lltok::NamedOrCustomMD)
1082 std::string Name = Lex.getStrVal();
1085 if (Lex.getKind() != lltok::Metadata)
1086 return TokError("Expected '!' here");
1090 if (ParseMDNode(Node)) return true;
1092 MetadataContext &TheMetadata = M->getContext().getMetadata();
1093 unsigned MDK = TheMetadata.getMDKind(Name.c_str());
1095 MDK = TheMetadata.registerMDKind(Name.c_str());
1096 MDsOnInst.push_back(std::make_pair(MDK, cast<MDNode>(Node)));
1101 /// ParseOptionalAlignment
1104 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1106 if (!EatIfPresent(lltok::kw_align))
1108 LocTy AlignLoc = Lex.getLoc();
1109 if (ParseUInt32(Alignment)) return true;
1110 if (!isPowerOf2_32(Alignment))
1111 return Error(AlignLoc, "alignment is not a power of two");
1115 /// ParseOptionalInfo
1116 /// ::= OptionalInfo (',' OptionalInfo)+
1117 bool LLParser::ParseOptionalInfo(unsigned &Alignment) {
1119 // FIXME: Handle customized metadata info attached with an instruction.
1121 if (Lex.getKind() == lltok::NamedOrCustomMD) {
1122 if (ParseOptionalCustomMetadata()) return true;
1123 } else if (Lex.getKind() == lltok::kw_align) {
1124 if (ParseOptionalAlignment(Alignment)) return true;
1127 } while (EatIfPresent(lltok::comma));
1134 /// ::= (',' uint32)+
1135 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
1136 if (Lex.getKind() != lltok::comma)
1137 return TokError("expected ',' as start of index list");
1139 while (EatIfPresent(lltok::comma)) {
1140 if (Lex.getKind() == lltok::NamedOrCustomMD)
1143 if (ParseUInt32(Idx)) return true;
1144 Indices.push_back(Idx);
1150 //===----------------------------------------------------------------------===//
1152 //===----------------------------------------------------------------------===//
1154 /// ParseType - Parse and resolve a full type.
1155 bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1156 LocTy TypeLoc = Lex.getLoc();
1157 if (ParseTypeRec(Result)) return true;
1159 // Verify no unresolved uprefs.
1160 if (!UpRefs.empty())
1161 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
1163 if (!AllowVoid && Result.get()->isVoidTy())
1164 return Error(TypeLoc, "void type only allowed for function results");
1169 /// HandleUpRefs - Every time we finish a new layer of types, this function is
1170 /// called. It loops through the UpRefs vector, which is a list of the
1171 /// currently active types. For each type, if the up-reference is contained in
1172 /// the newly completed type, we decrement the level count. When the level
1173 /// count reaches zero, the up-referenced type is the type that is passed in:
1174 /// thus we can complete the cycle.
1176 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1177 // If Ty isn't abstract, or if there are no up-references in it, then there is
1178 // nothing to resolve here.
1179 if (!ty->isAbstract() || UpRefs.empty()) return ty;
1181 PATypeHolder Ty(ty);
1183 errs() << "Type '" << Ty->getDescription()
1184 << "' newly formed. Resolving upreferences.\n"
1185 << UpRefs.size() << " upreferences active!\n";
1188 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1189 // to zero), we resolve them all together before we resolve them to Ty. At
1190 // the end of the loop, if there is anything to resolve to Ty, it will be in
1192 OpaqueType *TypeToResolve = 0;
1194 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1195 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1197 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1198 UpRefs[i].LastContainedTy) != Ty->subtype_end();
1201 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1202 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1203 << (ContainsType ? "true" : "false")
1204 << " level=" << UpRefs[i].NestingLevel << "\n";
1209 // Decrement level of upreference
1210 unsigned Level = --UpRefs[i].NestingLevel;
1211 UpRefs[i].LastContainedTy = Ty;
1213 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1218 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1221 TypeToResolve = UpRefs[i].UpRefTy;
1223 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1224 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1225 --i; // Do not skip the next element.
1229 TypeToResolve->refineAbstractTypeTo(Ty);
1235 /// ParseTypeRec - The recursive function used to process the internal
1236 /// implementation details of types.
1237 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1238 switch (Lex.getKind()) {
1240 return TokError("expected type");
1242 // TypeRec ::= 'float' | 'void' (etc)
1243 Result = Lex.getTyVal();
1246 case lltok::kw_opaque:
1247 // TypeRec ::= 'opaque'
1248 Result = OpaqueType::get(Context);
1252 // TypeRec ::= '{' ... '}'
1253 if (ParseStructType(Result, false))
1256 case lltok::lsquare:
1257 // TypeRec ::= '[' ... ']'
1258 Lex.Lex(); // eat the lsquare.
1259 if (ParseArrayVectorType(Result, false))
1262 case lltok::less: // Either vector or packed struct.
1263 // TypeRec ::= '<' ... '>'
1265 if (Lex.getKind() == lltok::lbrace) {
1266 if (ParseStructType(Result, true) ||
1267 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1269 } else if (ParseArrayVectorType(Result, true))
1272 case lltok::LocalVar:
1273 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1275 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1278 Result = OpaqueType::get(Context);
1279 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1280 std::make_pair(Result,
1282 M->addTypeName(Lex.getStrVal(), Result.get());
1287 case lltok::LocalVarID:
1289 if (Lex.getUIntVal() < NumberedTypes.size())
1290 Result = NumberedTypes[Lex.getUIntVal()];
1292 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1293 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1294 if (I != ForwardRefTypeIDs.end())
1295 Result = I->second.first;
1297 Result = OpaqueType::get(Context);
1298 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1299 std::make_pair(Result,
1305 case lltok::backslash: {
1306 // TypeRec ::= '\' 4
1309 if (ParseUInt32(Val)) return true;
1310 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
1311 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1317 // Parse the type suffixes.
1319 switch (Lex.getKind()) {
1321 default: return false;
1323 // TypeRec ::= TypeRec '*'
1325 if (Result.get()->isLabelTy())
1326 return TokError("basic block pointers are invalid");
1327 if (Result.get()->isVoidTy())
1328 return TokError("pointers to void are invalid; use i8* instead");
1329 if (!PointerType::isValidElementType(Result.get()))
1330 return TokError("pointer to this type is invalid");
1331 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1335 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1336 case lltok::kw_addrspace: {
1337 if (Result.get()->isLabelTy())
1338 return TokError("basic block pointers are invalid");
1339 if (Result.get()->isVoidTy())
1340 return TokError("pointers to void are invalid; use i8* instead");
1341 if (!PointerType::isValidElementType(Result.get()))
1342 return TokError("pointer to this type is invalid");
1344 if (ParseOptionalAddrSpace(AddrSpace) ||
1345 ParseToken(lltok::star, "expected '*' in address space"))
1348 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1352 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1354 if (ParseFunctionType(Result))
1361 /// ParseParameterList
1363 /// ::= '(' Arg (',' Arg)* ')'
1365 /// ::= Type OptionalAttributes Value OptionalAttributes
1366 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1367 PerFunctionState &PFS) {
1368 if (ParseToken(lltok::lparen, "expected '(' in call"))
1371 while (Lex.getKind() != lltok::rparen) {
1372 // If this isn't the first argument, we need a comma.
1373 if (!ArgList.empty() &&
1374 ParseToken(lltok::comma, "expected ',' in argument list"))
1377 // Parse the argument.
1379 PATypeHolder ArgTy(Type::getVoidTy(Context));
1380 unsigned ArgAttrs1, ArgAttrs2;
1382 if (ParseType(ArgTy, ArgLoc) ||
1383 ParseOptionalAttrs(ArgAttrs1, 0) ||
1384 ParseValue(ArgTy, V, PFS) ||
1385 // FIXME: Should not allow attributes after the argument, remove this in
1387 ParseOptionalAttrs(ArgAttrs2, 3))
1389 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1392 Lex.Lex(); // Lex the ')'.
1398 /// ParseArgumentList - Parse the argument list for a function type or function
1399 /// prototype. If 'inType' is true then we are parsing a FunctionType.
1400 /// ::= '(' ArgTypeListI ')'
1404 /// ::= ArgTypeList ',' '...'
1405 /// ::= ArgType (',' ArgType)*
1407 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1408 bool &isVarArg, bool inType) {
1410 assert(Lex.getKind() == lltok::lparen);
1411 Lex.Lex(); // eat the (.
1413 if (Lex.getKind() == lltok::rparen) {
1415 } else if (Lex.getKind() == lltok::dotdotdot) {
1419 LocTy TypeLoc = Lex.getLoc();
1420 PATypeHolder ArgTy(Type::getVoidTy(Context));
1424 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1425 // types (such as a function returning a pointer to itself). If parsing a
1426 // function prototype, we require fully resolved types.
1427 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1428 ParseOptionalAttrs(Attrs, 0)) return true;
1430 if (ArgTy->isVoidTy())
1431 return Error(TypeLoc, "argument can not have void type");
1433 if (Lex.getKind() == lltok::LocalVar ||
1434 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1435 Name = Lex.getStrVal();
1439 if (!FunctionType::isValidArgumentType(ArgTy))
1440 return Error(TypeLoc, "invalid type for function argument");
1442 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1444 while (EatIfPresent(lltok::comma)) {
1445 // Handle ... at end of arg list.
1446 if (EatIfPresent(lltok::dotdotdot)) {
1451 // Otherwise must be an argument type.
1452 TypeLoc = Lex.getLoc();
1453 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1454 ParseOptionalAttrs(Attrs, 0)) return true;
1456 if (ArgTy->isVoidTy())
1457 return Error(TypeLoc, "argument can not have void type");
1459 if (Lex.getKind() == lltok::LocalVar ||
1460 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1461 Name = Lex.getStrVal();
1467 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1468 return Error(TypeLoc, "invalid type for function argument");
1470 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1474 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1477 /// ParseFunctionType
1478 /// ::= Type ArgumentList OptionalAttrs
1479 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1480 assert(Lex.getKind() == lltok::lparen);
1482 if (!FunctionType::isValidReturnType(Result))
1483 return TokError("invalid function return type");
1485 std::vector<ArgInfo> ArgList;
1488 if (ParseArgumentList(ArgList, isVarArg, true) ||
1489 // FIXME: Allow, but ignore attributes on function types!
1490 // FIXME: Remove in LLVM 3.0
1491 ParseOptionalAttrs(Attrs, 2))
1494 // Reject names on the arguments lists.
1495 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1496 if (!ArgList[i].Name.empty())
1497 return Error(ArgList[i].Loc, "argument name invalid in function type");
1498 if (!ArgList[i].Attrs != 0) {
1499 // Allow but ignore attributes on function types; this permits
1501 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1505 std::vector<const Type*> ArgListTy;
1506 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1507 ArgListTy.push_back(ArgList[i].Type);
1509 Result = HandleUpRefs(FunctionType::get(Result.get(),
1510 ArgListTy, isVarArg));
1514 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1517 /// ::= '{' TypeRec (',' TypeRec)* '}'
1518 /// ::= '<' '{' '}' '>'
1519 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1520 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1521 assert(Lex.getKind() == lltok::lbrace);
1522 Lex.Lex(); // Consume the '{'
1524 if (EatIfPresent(lltok::rbrace)) {
1525 Result = StructType::get(Context, Packed);
1529 std::vector<PATypeHolder> ParamsList;
1530 LocTy EltTyLoc = Lex.getLoc();
1531 if (ParseTypeRec(Result)) return true;
1532 ParamsList.push_back(Result);
1534 if (Result->isVoidTy())
1535 return Error(EltTyLoc, "struct element can not have void type");
1536 if (!StructType::isValidElementType(Result))
1537 return Error(EltTyLoc, "invalid element type for struct");
1539 while (EatIfPresent(lltok::comma)) {
1540 EltTyLoc = Lex.getLoc();
1541 if (ParseTypeRec(Result)) return true;
1543 if (Result->isVoidTy())
1544 return Error(EltTyLoc, "struct element can not have void type");
1545 if (!StructType::isValidElementType(Result))
1546 return Error(EltTyLoc, "invalid element type for struct");
1548 ParamsList.push_back(Result);
1551 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1554 std::vector<const Type*> ParamsListTy;
1555 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1556 ParamsListTy.push_back(ParamsList[i].get());
1557 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
1561 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1562 /// token has already been consumed.
1564 /// ::= '[' APSINTVAL 'x' Types ']'
1565 /// ::= '<' APSINTVAL 'x' Types '>'
1566 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1567 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1568 Lex.getAPSIntVal().getBitWidth() > 64)
1569 return TokError("expected number in address space");
1571 LocTy SizeLoc = Lex.getLoc();
1572 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1575 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1578 LocTy TypeLoc = Lex.getLoc();
1579 PATypeHolder EltTy(Type::getVoidTy(Context));
1580 if (ParseTypeRec(EltTy)) return true;
1582 if (EltTy->isVoidTy())
1583 return Error(TypeLoc, "array and vector element type cannot be void");
1585 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1586 "expected end of sequential type"))
1591 return Error(SizeLoc, "zero element vector is illegal");
1592 if ((unsigned)Size != Size)
1593 return Error(SizeLoc, "size too large for vector");
1594 if (!VectorType::isValidElementType(EltTy))
1595 return Error(TypeLoc, "vector element type must be fp or integer");
1596 Result = VectorType::get(EltTy, unsigned(Size));
1598 if (!ArrayType::isValidElementType(EltTy))
1599 return Error(TypeLoc, "invalid array element type");
1600 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1605 //===----------------------------------------------------------------------===//
1606 // Function Semantic Analysis.
1607 //===----------------------------------------------------------------------===//
1609 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1611 : P(p), F(f), FunctionNumber(functionNumber) {
1613 // Insert unnamed arguments into the NumberedVals list.
1614 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1617 NumberedVals.push_back(AI);
1620 LLParser::PerFunctionState::~PerFunctionState() {
1621 // If there were any forward referenced non-basicblock values, delete them.
1622 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1623 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1624 if (!isa<BasicBlock>(I->second.first)) {
1625 I->second.first->replaceAllUsesWith(
1626 UndefValue::get(I->second.first->getType()));
1627 delete I->second.first;
1628 I->second.first = 0;
1631 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1632 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1633 if (!isa<BasicBlock>(I->second.first)) {
1634 I->second.first->replaceAllUsesWith(
1635 UndefValue::get(I->second.first->getType()));
1636 delete I->second.first;
1637 I->second.first = 0;
1641 bool LLParser::PerFunctionState::FinishFunction() {
1642 // Check to see if someone took the address of labels in this block.
1643 if (!P.ForwardRefBlockAddresses.empty()) {
1645 if (!F.getName().empty()) {
1646 FunctionID.Kind = ValID::t_GlobalName;
1647 FunctionID.StrVal = F.getName();
1649 FunctionID.Kind = ValID::t_GlobalID;
1650 FunctionID.UIntVal = FunctionNumber;
1653 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1654 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1655 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1656 // Resolve all these references.
1657 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1660 P.ForwardRefBlockAddresses.erase(FRBAI);
1664 if (!ForwardRefVals.empty())
1665 return P.Error(ForwardRefVals.begin()->second.second,
1666 "use of undefined value '%" + ForwardRefVals.begin()->first +
1668 if (!ForwardRefValIDs.empty())
1669 return P.Error(ForwardRefValIDs.begin()->second.second,
1670 "use of undefined value '%" +
1671 utostr(ForwardRefValIDs.begin()->first) + "'");
1676 /// GetVal - Get a value with the specified name or ID, creating a
1677 /// forward reference record if needed. This can return null if the value
1678 /// exists but does not have the right type.
1679 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1680 const Type *Ty, LocTy Loc) {
1681 // Look this name up in the normal function symbol table.
1682 Value *Val = F.getValueSymbolTable().lookup(Name);
1684 // If this is a forward reference for the value, see if we already created a
1685 // forward ref record.
1687 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1688 I = ForwardRefVals.find(Name);
1689 if (I != ForwardRefVals.end())
1690 Val = I->second.first;
1693 // If we have the value in the symbol table or fwd-ref table, return it.
1695 if (Val->getType() == Ty) return Val;
1696 if (Ty->isLabelTy())
1697 P.Error(Loc, "'%" + Name + "' is not a basic block");
1699 P.Error(Loc, "'%" + Name + "' defined with type '" +
1700 Val->getType()->getDescription() + "'");
1704 // Don't make placeholders with invalid type.
1705 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1706 Ty != Type::getLabelTy(F.getContext())) {
1707 P.Error(Loc, "invalid use of a non-first-class type");
1711 // Otherwise, create a new forward reference for this value and remember it.
1713 if (Ty->isLabelTy())
1714 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
1716 FwdVal = new Argument(Ty, Name);
1718 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1722 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1724 // Look this name up in the normal function symbol table.
1725 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1727 // If this is a forward reference for the value, see if we already created a
1728 // forward ref record.
1730 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1731 I = ForwardRefValIDs.find(ID);
1732 if (I != ForwardRefValIDs.end())
1733 Val = I->second.first;
1736 // If we have the value in the symbol table or fwd-ref table, return it.
1738 if (Val->getType() == Ty) return Val;
1739 if (Ty->isLabelTy())
1740 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1742 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1743 Val->getType()->getDescription() + "'");
1747 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1748 Ty != Type::getLabelTy(F.getContext())) {
1749 P.Error(Loc, "invalid use of a non-first-class type");
1753 // Otherwise, create a new forward reference for this value and remember it.
1755 if (Ty->isLabelTy())
1756 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
1758 FwdVal = new Argument(Ty);
1760 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1764 /// SetInstName - After an instruction is parsed and inserted into its
1765 /// basic block, this installs its name.
1766 bool LLParser::PerFunctionState::SetInstName(int NameID,
1767 const std::string &NameStr,
1768 LocTy NameLoc, Instruction *Inst) {
1769 // If this instruction has void type, it cannot have a name or ID specified.
1770 if (Inst->getType()->isVoidTy()) {
1771 if (NameID != -1 || !NameStr.empty())
1772 return P.Error(NameLoc, "instructions returning void cannot have a name");
1776 // If this was a numbered instruction, verify that the instruction is the
1777 // expected value and resolve any forward references.
1778 if (NameStr.empty()) {
1779 // If neither a name nor an ID was specified, just use the next ID.
1781 NameID = NumberedVals.size();
1783 if (unsigned(NameID) != NumberedVals.size())
1784 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1785 utostr(NumberedVals.size()) + "'");
1787 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1788 ForwardRefValIDs.find(NameID);
1789 if (FI != ForwardRefValIDs.end()) {
1790 if (FI->second.first->getType() != Inst->getType())
1791 return P.Error(NameLoc, "instruction forward referenced with type '" +
1792 FI->second.first->getType()->getDescription() + "'");
1793 FI->second.first->replaceAllUsesWith(Inst);
1794 delete FI->second.first;
1795 ForwardRefValIDs.erase(FI);
1798 NumberedVals.push_back(Inst);
1802 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1803 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1804 FI = ForwardRefVals.find(NameStr);
1805 if (FI != ForwardRefVals.end()) {
1806 if (FI->second.first->getType() != Inst->getType())
1807 return P.Error(NameLoc, "instruction forward referenced with type '" +
1808 FI->second.first->getType()->getDescription() + "'");
1809 FI->second.first->replaceAllUsesWith(Inst);
1810 delete FI->second.first;
1811 ForwardRefVals.erase(FI);
1814 // Set the name on the instruction.
1815 Inst->setName(NameStr);
1817 if (Inst->getNameStr() != NameStr)
1818 return P.Error(NameLoc, "multiple definition of local value named '" +
1823 /// GetBB - Get a basic block with the specified name or ID, creating a
1824 /// forward reference record if needed.
1825 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1827 return cast_or_null<BasicBlock>(GetVal(Name,
1828 Type::getLabelTy(F.getContext()), Loc));
1831 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1832 return cast_or_null<BasicBlock>(GetVal(ID,
1833 Type::getLabelTy(F.getContext()), Loc));
1836 /// DefineBB - Define the specified basic block, which is either named or
1837 /// unnamed. If there is an error, this returns null otherwise it returns
1838 /// the block being defined.
1839 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1843 BB = GetBB(NumberedVals.size(), Loc);
1845 BB = GetBB(Name, Loc);
1846 if (BB == 0) return 0; // Already diagnosed error.
1848 // Move the block to the end of the function. Forward ref'd blocks are
1849 // inserted wherever they happen to be referenced.
1850 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1852 // Remove the block from forward ref sets.
1854 ForwardRefValIDs.erase(NumberedVals.size());
1855 NumberedVals.push_back(BB);
1857 // BB forward references are already in the function symbol table.
1858 ForwardRefVals.erase(Name);
1864 //===----------------------------------------------------------------------===//
1866 //===----------------------------------------------------------------------===//
1868 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1869 /// type implied. For example, if we parse "4" we don't know what integer type
1870 /// it has. The value will later be combined with its type and checked for
1872 bool LLParser::ParseValID(ValID &ID) {
1873 ID.Loc = Lex.getLoc();
1874 switch (Lex.getKind()) {
1875 default: return TokError("expected value token");
1876 case lltok::GlobalID: // @42
1877 ID.UIntVal = Lex.getUIntVal();
1878 ID.Kind = ValID::t_GlobalID;
1880 case lltok::GlobalVar: // @foo
1881 ID.StrVal = Lex.getStrVal();
1882 ID.Kind = ValID::t_GlobalName;
1884 case lltok::LocalVarID: // %42
1885 ID.UIntVal = Lex.getUIntVal();
1886 ID.Kind = ValID::t_LocalID;
1888 case lltok::LocalVar: // %foo
1889 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1890 ID.StrVal = Lex.getStrVal();
1891 ID.Kind = ValID::t_LocalName;
1893 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
1894 ID.Kind = ValID::t_Metadata;
1896 if (Lex.getKind() == lltok::lbrace) {
1897 SmallVector<Value*, 16> Elts;
1898 if (ParseMDNodeVector(Elts) ||
1899 ParseToken(lltok::rbrace, "expected end of metadata node"))
1902 ID.MetadataVal = MDNode::get(Context, Elts.data(), Elts.size());
1906 // Standalone metadata reference
1907 // !{ ..., !42, ... }
1908 if (!ParseMDNode(ID.MetadataVal))
1912 // ::= '!' STRINGCONSTANT
1913 if (ParseMDString(ID.MetadataVal)) return true;
1914 ID.Kind = ValID::t_Metadata;
1918 ID.APSIntVal = Lex.getAPSIntVal();
1919 ID.Kind = ValID::t_APSInt;
1921 case lltok::APFloat:
1922 ID.APFloatVal = Lex.getAPFloatVal();
1923 ID.Kind = ValID::t_APFloat;
1925 case lltok::kw_true:
1926 ID.ConstantVal = ConstantInt::getTrue(Context);
1927 ID.Kind = ValID::t_Constant;
1929 case lltok::kw_false:
1930 ID.ConstantVal = ConstantInt::getFalse(Context);
1931 ID.Kind = ValID::t_Constant;
1933 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1934 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1935 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1937 case lltok::lbrace: {
1938 // ValID ::= '{' ConstVector '}'
1940 SmallVector<Constant*, 16> Elts;
1941 if (ParseGlobalValueVector(Elts) ||
1942 ParseToken(lltok::rbrace, "expected end of struct constant"))
1945 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
1946 Elts.size(), false);
1947 ID.Kind = ValID::t_Constant;
1951 // ValID ::= '<' ConstVector '>' --> Vector.
1952 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1954 bool isPackedStruct = EatIfPresent(lltok::lbrace);
1956 SmallVector<Constant*, 16> Elts;
1957 LocTy FirstEltLoc = Lex.getLoc();
1958 if (ParseGlobalValueVector(Elts) ||
1960 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1961 ParseToken(lltok::greater, "expected end of constant"))
1964 if (isPackedStruct) {
1966 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
1967 ID.Kind = ValID::t_Constant;
1972 return Error(ID.Loc, "constant vector must not be empty");
1974 if (!Elts[0]->getType()->isInteger() &&
1975 !Elts[0]->getType()->isFloatingPoint())
1976 return Error(FirstEltLoc,
1977 "vector elements must have integer or floating point type");
1979 // Verify that all the vector elements have the same type.
1980 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1981 if (Elts[i]->getType() != Elts[0]->getType())
1982 return Error(FirstEltLoc,
1983 "vector element #" + utostr(i) +
1984 " is not of type '" + Elts[0]->getType()->getDescription());
1986 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
1987 ID.Kind = ValID::t_Constant;
1990 case lltok::lsquare: { // Array Constant
1992 SmallVector<Constant*, 16> Elts;
1993 LocTy FirstEltLoc = Lex.getLoc();
1994 if (ParseGlobalValueVector(Elts) ||
1995 ParseToken(lltok::rsquare, "expected end of array constant"))
1998 // Handle empty element.
2000 // Use undef instead of an array because it's inconvenient to determine
2001 // the element type at this point, there being no elements to examine.
2002 ID.Kind = ValID::t_EmptyArray;
2006 if (!Elts[0]->getType()->isFirstClassType())
2007 return Error(FirstEltLoc, "invalid array element type: " +
2008 Elts[0]->getType()->getDescription());
2010 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2012 // Verify all elements are correct type!
2013 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2014 if (Elts[i]->getType() != Elts[0]->getType())
2015 return Error(FirstEltLoc,
2016 "array element #" + utostr(i) +
2017 " is not of type '" +Elts[0]->getType()->getDescription());
2020 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
2021 ID.Kind = ValID::t_Constant;
2024 case lltok::kw_c: // c "foo"
2026 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
2027 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2028 ID.Kind = ValID::t_Constant;
2031 case lltok::kw_asm: {
2032 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2033 bool HasSideEffect, AlignStack;
2035 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2036 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2037 ParseStringConstant(ID.StrVal) ||
2038 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2039 ParseToken(lltok::StringConstant, "expected constraint string"))
2041 ID.StrVal2 = Lex.getStrVal();
2042 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
2043 ID.Kind = ValID::t_InlineAsm;
2047 case lltok::kw_blockaddress: {
2048 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2052 LocTy FnLoc, LabelLoc;
2054 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2056 ParseToken(lltok::comma, "expected comma in block address expression")||
2057 ParseValID(Label) ||
2058 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2061 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2062 return Error(Fn.Loc, "expected function name in blockaddress");
2063 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2064 return Error(Label.Loc, "expected basic block name in blockaddress");
2066 // Make a global variable as a placeholder for this reference.
2067 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2068 false, GlobalValue::InternalLinkage,
2070 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2071 ID.ConstantVal = FwdRef;
2072 ID.Kind = ValID::t_Constant;
2076 case lltok::kw_trunc:
2077 case lltok::kw_zext:
2078 case lltok::kw_sext:
2079 case lltok::kw_fptrunc:
2080 case lltok::kw_fpext:
2081 case lltok::kw_bitcast:
2082 case lltok::kw_uitofp:
2083 case lltok::kw_sitofp:
2084 case lltok::kw_fptoui:
2085 case lltok::kw_fptosi:
2086 case lltok::kw_inttoptr:
2087 case lltok::kw_ptrtoint: {
2088 unsigned Opc = Lex.getUIntVal();
2089 PATypeHolder DestTy(Type::getVoidTy(Context));
2092 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2093 ParseGlobalTypeAndValue(SrcVal) ||
2094 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2095 ParseType(DestTy) ||
2096 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2098 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2099 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2100 SrcVal->getType()->getDescription() + "' to '" +
2101 DestTy->getDescription() + "'");
2102 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2104 ID.Kind = ValID::t_Constant;
2107 case lltok::kw_extractvalue: {
2110 SmallVector<unsigned, 4> Indices;
2111 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2112 ParseGlobalTypeAndValue(Val) ||
2113 ParseIndexList(Indices) ||
2114 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2116 if (Lex.getKind() == lltok::NamedOrCustomMD)
2117 if (ParseOptionalCustomMetadata()) return true;
2119 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
2120 return Error(ID.Loc, "extractvalue operand must be array or struct");
2121 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2123 return Error(ID.Loc, "invalid indices for extractvalue");
2125 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
2126 ID.Kind = ValID::t_Constant;
2129 case lltok::kw_insertvalue: {
2131 Constant *Val0, *Val1;
2132 SmallVector<unsigned, 4> Indices;
2133 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2134 ParseGlobalTypeAndValue(Val0) ||
2135 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2136 ParseGlobalTypeAndValue(Val1) ||
2137 ParseIndexList(Indices) ||
2138 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2140 if (Lex.getKind() == lltok::NamedOrCustomMD)
2141 if (ParseOptionalCustomMetadata()) return true;
2142 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
2143 return Error(ID.Loc, "extractvalue operand must be array or struct");
2144 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2146 return Error(ID.Loc, "invalid indices for insertvalue");
2147 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
2148 Indices.data(), Indices.size());
2149 ID.Kind = ValID::t_Constant;
2152 case lltok::kw_icmp:
2153 case lltok::kw_fcmp: {
2154 unsigned PredVal, Opc = Lex.getUIntVal();
2155 Constant *Val0, *Val1;
2157 if (ParseCmpPredicate(PredVal, Opc) ||
2158 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2159 ParseGlobalTypeAndValue(Val0) ||
2160 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2161 ParseGlobalTypeAndValue(Val1) ||
2162 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2165 if (Val0->getType() != Val1->getType())
2166 return Error(ID.Loc, "compare operands must have the same type");
2168 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2170 if (Opc == Instruction::FCmp) {
2171 if (!Val0->getType()->isFPOrFPVector())
2172 return Error(ID.Loc, "fcmp requires floating point operands");
2173 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2175 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2176 if (!Val0->getType()->isIntOrIntVector() &&
2177 !isa<PointerType>(Val0->getType()))
2178 return Error(ID.Loc, "icmp requires pointer or integer operands");
2179 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2181 ID.Kind = ValID::t_Constant;
2185 // Binary Operators.
2187 case lltok::kw_fadd:
2189 case lltok::kw_fsub:
2191 case lltok::kw_fmul:
2192 case lltok::kw_udiv:
2193 case lltok::kw_sdiv:
2194 case lltok::kw_fdiv:
2195 case lltok::kw_urem:
2196 case lltok::kw_srem:
2197 case lltok::kw_frem: {
2201 unsigned Opc = Lex.getUIntVal();
2202 Constant *Val0, *Val1;
2204 LocTy ModifierLoc = Lex.getLoc();
2205 if (Opc == Instruction::Add ||
2206 Opc == Instruction::Sub ||
2207 Opc == Instruction::Mul) {
2208 if (EatIfPresent(lltok::kw_nuw))
2210 if (EatIfPresent(lltok::kw_nsw)) {
2212 if (EatIfPresent(lltok::kw_nuw))
2215 } else if (Opc == Instruction::SDiv) {
2216 if (EatIfPresent(lltok::kw_exact))
2219 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2220 ParseGlobalTypeAndValue(Val0) ||
2221 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2222 ParseGlobalTypeAndValue(Val1) ||
2223 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2225 if (Val0->getType() != Val1->getType())
2226 return Error(ID.Loc, "operands of constexpr must have same type");
2227 if (!Val0->getType()->isIntOrIntVector()) {
2229 return Error(ModifierLoc, "nuw only applies to integer operations");
2231 return Error(ModifierLoc, "nsw only applies to integer operations");
2233 // API compatibility: Accept either integer or floating-point types with
2234 // add, sub, and mul.
2235 if (!Val0->getType()->isIntOrIntVector() &&
2236 !Val0->getType()->isFPOrFPVector())
2237 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
2239 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2240 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2241 if (Exact) Flags |= SDivOperator::IsExact;
2242 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2244 ID.Kind = ValID::t_Constant;
2248 // Logical Operations
2250 case lltok::kw_lshr:
2251 case lltok::kw_ashr:
2254 case lltok::kw_xor: {
2255 unsigned Opc = Lex.getUIntVal();
2256 Constant *Val0, *Val1;
2258 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2259 ParseGlobalTypeAndValue(Val0) ||
2260 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2261 ParseGlobalTypeAndValue(Val1) ||
2262 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2264 if (Val0->getType() != Val1->getType())
2265 return Error(ID.Loc, "operands of constexpr must have same type");
2266 if (!Val0->getType()->isIntOrIntVector())
2267 return Error(ID.Loc,
2268 "constexpr requires integer or integer vector operands");
2269 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2270 ID.Kind = ValID::t_Constant;
2274 case lltok::kw_getelementptr:
2275 case lltok::kw_shufflevector:
2276 case lltok::kw_insertelement:
2277 case lltok::kw_extractelement:
2278 case lltok::kw_select: {
2279 unsigned Opc = Lex.getUIntVal();
2280 SmallVector<Constant*, 16> Elts;
2281 bool InBounds = false;
2283 if (Opc == Instruction::GetElementPtr)
2284 InBounds = EatIfPresent(lltok::kw_inbounds);
2285 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2286 ParseGlobalValueVector(Elts) ||
2287 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2290 if (Opc == Instruction::GetElementPtr) {
2291 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
2292 return Error(ID.Loc, "getelementptr requires pointer operand");
2294 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
2295 (Value**)(Elts.data() + 1),
2297 return Error(ID.Loc, "invalid indices for getelementptr");
2298 ID.ConstantVal = InBounds ?
2299 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2302 ConstantExpr::getGetElementPtr(Elts[0],
2303 Elts.data() + 1, Elts.size() - 1);
2304 } else if (Opc == Instruction::Select) {
2305 if (Elts.size() != 3)
2306 return Error(ID.Loc, "expected three operands to select");
2307 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2309 return Error(ID.Loc, Reason);
2310 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2311 } else if (Opc == Instruction::ShuffleVector) {
2312 if (Elts.size() != 3)
2313 return Error(ID.Loc, "expected three operands to shufflevector");
2314 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2315 return Error(ID.Loc, "invalid operands to shufflevector");
2317 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2318 } else if (Opc == Instruction::ExtractElement) {
2319 if (Elts.size() != 2)
2320 return Error(ID.Loc, "expected two operands to extractelement");
2321 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2322 return Error(ID.Loc, "invalid extractelement operands");
2323 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2325 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2326 if (Elts.size() != 3)
2327 return Error(ID.Loc, "expected three operands to insertelement");
2328 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2329 return Error(ID.Loc, "invalid insertelement operands");
2331 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2334 ID.Kind = ValID::t_Constant;
2343 /// ParseGlobalValue - Parse a global value with the specified type.
2344 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2347 return ParseValID(ID) ||
2348 ConvertGlobalValIDToValue(Ty, ID, V);
2351 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2353 bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2355 if (isa<FunctionType>(Ty))
2356 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2359 default: llvm_unreachable("Unknown ValID!");
2360 case ValID::t_Metadata:
2361 return Error(ID.Loc, "invalid use of metadata");
2362 case ValID::t_LocalID:
2363 case ValID::t_LocalName:
2364 return Error(ID.Loc, "invalid use of function-local name");
2365 case ValID::t_InlineAsm:
2366 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2367 case ValID::t_GlobalName:
2368 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2370 case ValID::t_GlobalID:
2371 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2373 case ValID::t_APSInt:
2374 if (!isa<IntegerType>(Ty))
2375 return Error(ID.Loc, "integer constant must have integer type");
2376 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2377 V = ConstantInt::get(Context, ID.APSIntVal);
2379 case ValID::t_APFloat:
2380 if (!Ty->isFloatingPoint() ||
2381 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2382 return Error(ID.Loc, "floating point constant invalid for type");
2384 // The lexer has no type info, so builds all float and double FP constants
2385 // as double. Fix this here. Long double does not need this.
2386 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2389 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2392 V = ConstantFP::get(Context, ID.APFloatVal);
2394 if (V->getType() != Ty)
2395 return Error(ID.Loc, "floating point constant does not have type '" +
2396 Ty->getDescription() + "'");
2400 if (!isa<PointerType>(Ty))
2401 return Error(ID.Loc, "null must be a pointer type");
2402 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2404 case ValID::t_Undef:
2405 // FIXME: LabelTy should not be a first-class type.
2406 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
2407 !isa<OpaqueType>(Ty))
2408 return Error(ID.Loc, "invalid type for undef constant");
2409 V = UndefValue::get(Ty);
2411 case ValID::t_EmptyArray:
2412 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2413 return Error(ID.Loc, "invalid empty array initializer");
2414 V = UndefValue::get(Ty);
2417 // FIXME: LabelTy should not be a first-class type.
2418 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2419 return Error(ID.Loc, "invalid type for null constant");
2420 V = Constant::getNullValue(Ty);
2422 case ValID::t_Constant:
2423 if (ID.ConstantVal->getType() != Ty)
2424 return Error(ID.Loc, "constant expression type mismatch");
2430 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2431 PATypeHolder Type(Type::getVoidTy(Context));
2432 return ParseType(Type) ||
2433 ParseGlobalValue(Type, V);
2436 /// ParseGlobalValueVector
2438 /// ::= TypeAndValue (',' TypeAndValue)*
2439 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2441 if (Lex.getKind() == lltok::rbrace ||
2442 Lex.getKind() == lltok::rsquare ||
2443 Lex.getKind() == lltok::greater ||
2444 Lex.getKind() == lltok::rparen)
2448 if (ParseGlobalTypeAndValue(C)) return true;
2451 while (EatIfPresent(lltok::comma)) {
2452 if (ParseGlobalTypeAndValue(C)) return true;
2460 //===----------------------------------------------------------------------===//
2461 // Function Parsing.
2462 //===----------------------------------------------------------------------===//
2464 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2465 PerFunctionState &PFS) {
2466 if (ID.Kind == ValID::t_LocalID)
2467 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2468 else if (ID.Kind == ValID::t_LocalName)
2469 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
2470 else if (ID.Kind == ValID::t_InlineAsm) {
2471 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2472 const FunctionType *FTy =
2473 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2474 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2475 return Error(ID.Loc, "invalid type for inline asm constraint string");
2476 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2478 } else if (ID.Kind == ValID::t_Metadata) {
2482 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2490 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2493 return ParseValID(ID) ||
2494 ConvertValIDToValue(Ty, ID, V, PFS);
2497 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2498 PATypeHolder T(Type::getVoidTy(Context));
2499 return ParseType(T) ||
2500 ParseValue(T, V, PFS);
2503 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2504 PerFunctionState &PFS) {
2507 if (ParseTypeAndValue(V, PFS)) return true;
2508 if (!isa<BasicBlock>(V))
2509 return Error(Loc, "expected a basic block");
2510 BB = cast<BasicBlock>(V);
2516 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2517 /// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2518 /// OptionalAlign OptGC
2519 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2520 // Parse the linkage.
2521 LocTy LinkageLoc = Lex.getLoc();
2524 unsigned Visibility, RetAttrs;
2526 PATypeHolder RetType(Type::getVoidTy(Context));
2527 LocTy RetTypeLoc = Lex.getLoc();
2528 if (ParseOptionalLinkage(Linkage) ||
2529 ParseOptionalVisibility(Visibility) ||
2530 ParseOptionalCallingConv(CC) ||
2531 ParseOptionalAttrs(RetAttrs, 1) ||
2532 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2535 // Verify that the linkage is ok.
2536 switch ((GlobalValue::LinkageTypes)Linkage) {
2537 case GlobalValue::ExternalLinkage:
2538 break; // always ok.
2539 case GlobalValue::DLLImportLinkage:
2540 case GlobalValue::ExternalWeakLinkage:
2542 return Error(LinkageLoc, "invalid linkage for function definition");
2544 case GlobalValue::PrivateLinkage:
2545 case GlobalValue::LinkerPrivateLinkage:
2546 case GlobalValue::InternalLinkage:
2547 case GlobalValue::AvailableExternallyLinkage:
2548 case GlobalValue::LinkOnceAnyLinkage:
2549 case GlobalValue::LinkOnceODRLinkage:
2550 case GlobalValue::WeakAnyLinkage:
2551 case GlobalValue::WeakODRLinkage:
2552 case GlobalValue::DLLExportLinkage:
2554 return Error(LinkageLoc, "invalid linkage for function declaration");
2556 case GlobalValue::AppendingLinkage:
2557 case GlobalValue::GhostLinkage:
2558 case GlobalValue::CommonLinkage:
2559 return Error(LinkageLoc, "invalid function linkage type");
2562 if (!FunctionType::isValidReturnType(RetType) ||
2563 isa<OpaqueType>(RetType))
2564 return Error(RetTypeLoc, "invalid function return type");
2566 LocTy NameLoc = Lex.getLoc();
2568 std::string FunctionName;
2569 if (Lex.getKind() == lltok::GlobalVar) {
2570 FunctionName = Lex.getStrVal();
2571 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2572 unsigned NameID = Lex.getUIntVal();
2574 if (NameID != NumberedVals.size())
2575 return TokError("function expected to be numbered '%" +
2576 utostr(NumberedVals.size()) + "'");
2578 return TokError("expected function name");
2583 if (Lex.getKind() != lltok::lparen)
2584 return TokError("expected '(' in function argument list");
2586 std::vector<ArgInfo> ArgList;
2589 std::string Section;
2593 if (ParseArgumentList(ArgList, isVarArg, false) ||
2594 ParseOptionalAttrs(FuncAttrs, 2) ||
2595 (EatIfPresent(lltok::kw_section) &&
2596 ParseStringConstant(Section)) ||
2597 ParseOptionalAlignment(Alignment) ||
2598 (EatIfPresent(lltok::kw_gc) &&
2599 ParseStringConstant(GC)))
2602 // If the alignment was parsed as an attribute, move to the alignment field.
2603 if (FuncAttrs & Attribute::Alignment) {
2604 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2605 FuncAttrs &= ~Attribute::Alignment;
2608 // Okay, if we got here, the function is syntactically valid. Convert types
2609 // and do semantic checks.
2610 std::vector<const Type*> ParamTypeList;
2611 SmallVector<AttributeWithIndex, 8> Attrs;
2612 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2614 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2615 if (FuncAttrs & ObsoleteFuncAttrs) {
2616 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2617 FuncAttrs &= ~ObsoleteFuncAttrs;
2620 if (RetAttrs != Attribute::None)
2621 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2623 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2624 ParamTypeList.push_back(ArgList[i].Type);
2625 if (ArgList[i].Attrs != Attribute::None)
2626 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2629 if (FuncAttrs != Attribute::None)
2630 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2632 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2634 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2635 RetType != Type::getVoidTy(Context))
2636 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2638 const FunctionType *FT =
2639 FunctionType::get(RetType, ParamTypeList, isVarArg);
2640 const PointerType *PFT = PointerType::getUnqual(FT);
2643 if (!FunctionName.empty()) {
2644 // If this was a definition of a forward reference, remove the definition
2645 // from the forward reference table and fill in the forward ref.
2646 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2647 ForwardRefVals.find(FunctionName);
2648 if (FRVI != ForwardRefVals.end()) {
2649 Fn = M->getFunction(FunctionName);
2650 ForwardRefVals.erase(FRVI);
2651 } else if ((Fn = M->getFunction(FunctionName))) {
2652 // If this function already exists in the symbol table, then it is
2653 // multiply defined. We accept a few cases for old backwards compat.
2654 // FIXME: Remove this stuff for LLVM 3.0.
2655 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2656 (!Fn->isDeclaration() && isDefine)) {
2657 // If the redefinition has different type or different attributes,
2658 // reject it. If both have bodies, reject it.
2659 return Error(NameLoc, "invalid redefinition of function '" +
2660 FunctionName + "'");
2661 } else if (Fn->isDeclaration()) {
2662 // Make sure to strip off any argument names so we can't get conflicts.
2663 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2667 } else if (M->getNamedValue(FunctionName)) {
2668 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
2672 // If this is a definition of a forward referenced function, make sure the
2674 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2675 = ForwardRefValIDs.find(NumberedVals.size());
2676 if (I != ForwardRefValIDs.end()) {
2677 Fn = cast<Function>(I->second.first);
2678 if (Fn->getType() != PFT)
2679 return Error(NameLoc, "type of definition and forward reference of '@" +
2680 utostr(NumberedVals.size()) +"' disagree");
2681 ForwardRefValIDs.erase(I);
2686 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2687 else // Move the forward-reference to the correct spot in the module.
2688 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2690 if (FunctionName.empty())
2691 NumberedVals.push_back(Fn);
2693 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2694 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2695 Fn->setCallingConv(CC);
2696 Fn->setAttributes(PAL);
2697 Fn->setAlignment(Alignment);
2698 Fn->setSection(Section);
2699 if (!GC.empty()) Fn->setGC(GC.c_str());
2701 // Add all of the arguments we parsed to the function.
2702 Function::arg_iterator ArgIt = Fn->arg_begin();
2703 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2704 // If the argument has a name, insert it into the argument symbol table.
2705 if (ArgList[i].Name.empty()) continue;
2707 // Set the name, if it conflicted, it will be auto-renamed.
2708 ArgIt->setName(ArgList[i].Name);
2710 if (ArgIt->getNameStr() != ArgList[i].Name)
2711 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2712 ArgList[i].Name + "'");
2719 /// ParseFunctionBody
2720 /// ::= '{' BasicBlock+ '}'
2721 /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2723 bool LLParser::ParseFunctionBody(Function &Fn) {
2724 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2725 return TokError("expected '{' in function body");
2726 Lex.Lex(); // eat the {.
2728 int FunctionNumber = -1;
2729 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2731 PerFunctionState PFS(*this, Fn, FunctionNumber);
2733 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2734 if (ParseBasicBlock(PFS)) return true;
2739 // Verify function is ok.
2740 return PFS.FinishFunction();
2744 /// ::= LabelStr? Instruction*
2745 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2746 // If this basic block starts out with a name, remember it.
2748 LocTy NameLoc = Lex.getLoc();
2749 if (Lex.getKind() == lltok::LabelStr) {
2750 Name = Lex.getStrVal();
2754 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2755 if (BB == 0) return true;
2757 std::string NameStr;
2759 // Parse the instructions in this block until we get a terminator.
2762 // This instruction may have three possibilities for a name: a) none
2763 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2764 LocTy NameLoc = Lex.getLoc();
2768 if (Lex.getKind() == lltok::LocalVarID) {
2769 NameID = Lex.getUIntVal();
2771 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2773 } else if (Lex.getKind() == lltok::LocalVar ||
2774 // FIXME: REMOVE IN LLVM 3.0
2775 Lex.getKind() == lltok::StringConstant) {
2776 NameStr = Lex.getStrVal();
2778 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2782 if (ParseInstruction(Inst, BB, PFS)) return true;
2783 if (EatIfPresent(lltok::comma))
2784 ParseOptionalCustomMetadata();
2786 // Set metadata attached with this instruction.
2787 MetadataContext &TheMetadata = M->getContext().getMetadata();
2788 for (SmallVector<std::pair<unsigned, MDNode *>, 2>::iterator
2789 MDI = MDsOnInst.begin(), MDE = MDsOnInst.end(); MDI != MDE; ++MDI)
2790 TheMetadata.addMD(MDI->first, MDI->second, Inst);
2793 BB->getInstList().push_back(Inst);
2795 // Set the name on the instruction.
2796 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2797 } while (!isa<TerminatorInst>(Inst));
2802 //===----------------------------------------------------------------------===//
2803 // Instruction Parsing.
2804 //===----------------------------------------------------------------------===//
2806 /// ParseInstruction - Parse one of the many different instructions.
2808 bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2809 PerFunctionState &PFS) {
2810 lltok::Kind Token = Lex.getKind();
2811 if (Token == lltok::Eof)
2812 return TokError("found end of file when expecting more instructions");
2813 LocTy Loc = Lex.getLoc();
2814 unsigned KeywordVal = Lex.getUIntVal();
2815 Lex.Lex(); // Eat the keyword.
2818 default: return Error(Loc, "expected instruction opcode");
2819 // Terminator Instructions.
2820 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2821 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
2822 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2823 case lltok::kw_br: return ParseBr(Inst, PFS);
2824 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2825 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
2826 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2827 // Binary Operators.
2830 case lltok::kw_mul: {
2833 LocTy ModifierLoc = Lex.getLoc();
2834 if (EatIfPresent(lltok::kw_nuw))
2836 if (EatIfPresent(lltok::kw_nsw)) {
2838 if (EatIfPresent(lltok::kw_nuw))
2841 // API compatibility: Accept either integer or floating-point types.
2842 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
2844 if (!Inst->getType()->isIntOrIntVector()) {
2846 return Error(ModifierLoc, "nuw only applies to integer operations");
2848 return Error(ModifierLoc, "nsw only applies to integer operations");
2851 cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
2853 cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
2857 case lltok::kw_fadd:
2858 case lltok::kw_fsub:
2859 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2861 case lltok::kw_sdiv: {
2863 if (EatIfPresent(lltok::kw_exact))
2865 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2868 cast<BinaryOperator>(Inst)->setIsExact(true);
2872 case lltok::kw_udiv:
2873 case lltok::kw_urem:
2874 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2875 case lltok::kw_fdiv:
2876 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2878 case lltok::kw_lshr:
2879 case lltok::kw_ashr:
2882 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
2883 case lltok::kw_icmp:
2884 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
2886 case lltok::kw_trunc:
2887 case lltok::kw_zext:
2888 case lltok::kw_sext:
2889 case lltok::kw_fptrunc:
2890 case lltok::kw_fpext:
2891 case lltok::kw_bitcast:
2892 case lltok::kw_uitofp:
2893 case lltok::kw_sitofp:
2894 case lltok::kw_fptoui:
2895 case lltok::kw_fptosi:
2896 case lltok::kw_inttoptr:
2897 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
2899 case lltok::kw_select: return ParseSelect(Inst, PFS);
2900 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
2901 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2902 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2903 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2904 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2905 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2906 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2908 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
2909 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, BB, false);
2910 case lltok::kw_free: return ParseFree(Inst, PFS, BB);
2911 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2912 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2913 case lltok::kw_volatile:
2914 if (EatIfPresent(lltok::kw_load))
2915 return ParseLoad(Inst, PFS, true);
2916 else if (EatIfPresent(lltok::kw_store))
2917 return ParseStore(Inst, PFS, true);
2919 return TokError("expected 'load' or 'store'");
2920 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2921 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2922 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2923 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2927 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2928 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2929 if (Opc == Instruction::FCmp) {
2930 switch (Lex.getKind()) {
2931 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2932 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2933 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2934 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2935 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2936 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2937 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2938 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2939 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2940 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2941 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2942 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2943 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2944 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2945 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2946 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2947 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2950 switch (Lex.getKind()) {
2951 default: TokError("expected icmp predicate (e.g. 'eq')");
2952 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2953 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2954 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2955 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2956 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2957 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2958 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2959 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2960 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2961 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2968 //===----------------------------------------------------------------------===//
2969 // Terminator Instructions.
2970 //===----------------------------------------------------------------------===//
2972 /// ParseRet - Parse a return instruction.
2973 /// ::= 'ret' void (',' !dbg, !1)
2974 /// ::= 'ret' TypeAndValue (',' !dbg, !1)
2975 /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)
2976 /// [[obsolete: LLVM 3.0]]
2977 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2978 PerFunctionState &PFS) {
2979 PATypeHolder Ty(Type::getVoidTy(Context));
2980 if (ParseType(Ty, true /*void allowed*/)) return true;
2982 if (Ty->isVoidTy()) {
2983 Inst = ReturnInst::Create(Context);
2988 if (ParseValue(Ty, RV, PFS)) return true;
2990 if (EatIfPresent(lltok::comma)) {
2991 // Parse optional custom metadata, e.g. !dbg
2992 if (Lex.getKind() == lltok::NamedOrCustomMD) {
2993 if (ParseOptionalCustomMetadata()) return true;
2995 // The normal case is one return value.
2996 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2997 // of 'ret {i32,i32} {i32 1, i32 2}'
2998 SmallVector<Value*, 8> RVs;
3002 // If optional custom metadata, e.g. !dbg is seen then this is the
3004 if (Lex.getKind() == lltok::NamedOrCustomMD)
3006 if (ParseTypeAndValue(RV, PFS)) return true;
3008 } while (EatIfPresent(lltok::comma));
3010 RV = UndefValue::get(PFS.getFunction().getReturnType());
3011 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
3012 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
3013 BB->getInstList().push_back(I);
3019 Inst = ReturnInst::Create(Context, RV);
3025 /// ::= 'br' TypeAndValue
3026 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3027 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3030 BasicBlock *Op1, *Op2;
3031 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3033 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3034 Inst = BranchInst::Create(BB);
3038 if (Op0->getType() != Type::getInt1Ty(Context))
3039 return Error(Loc, "branch condition must have 'i1' type");
3041 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3042 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3043 ParseToken(lltok::comma, "expected ',' after true destination") ||
3044 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3047 Inst = BranchInst::Create(Op1, Op2, Op0);
3053 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3055 /// ::= (TypeAndValue ',' TypeAndValue)*
3056 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3057 LocTy CondLoc, BBLoc;
3059 BasicBlock *DefaultBB;
3060 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3061 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3062 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3063 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3066 if (!isa<IntegerType>(Cond->getType()))
3067 return Error(CondLoc, "switch condition must have integer type");
3069 // Parse the jump table pairs.
3070 SmallPtrSet<Value*, 32> SeenCases;
3071 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3072 while (Lex.getKind() != lltok::rsquare) {
3076 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3077 ParseToken(lltok::comma, "expected ',' after case value") ||
3078 ParseTypeAndBasicBlock(DestBB, PFS))
3081 if (!SeenCases.insert(Constant))
3082 return Error(CondLoc, "duplicate case value in switch");
3083 if (!isa<ConstantInt>(Constant))
3084 return Error(CondLoc, "case value is not a constant integer");
3086 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3089 Lex.Lex(); // Eat the ']'.
3091 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3092 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3093 SI->addCase(Table[i].first, Table[i].second);
3100 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3101 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3104 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3105 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3106 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3109 if (!isa<PointerType>(Address->getType()))
3110 return Error(AddrLoc, "indirectbr address must have pointer type");
3112 // Parse the destination list.
3113 SmallVector<BasicBlock*, 16> DestList;
3115 if (Lex.getKind() != lltok::rsquare) {
3117 if (ParseTypeAndBasicBlock(DestBB, PFS))
3119 DestList.push_back(DestBB);
3121 while (EatIfPresent(lltok::comma)) {
3122 if (ParseTypeAndBasicBlock(DestBB, PFS))
3124 DestList.push_back(DestBB);
3128 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3131 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3132 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3133 IBI->addDestination(DestList[i]);
3140 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3141 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3142 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3143 LocTy CallLoc = Lex.getLoc();
3144 unsigned RetAttrs, FnAttrs;
3146 PATypeHolder RetType(Type::getVoidTy(Context));
3149 SmallVector<ParamInfo, 16> ArgList;
3151 BasicBlock *NormalBB, *UnwindBB;
3152 if (ParseOptionalCallingConv(CC) ||
3153 ParseOptionalAttrs(RetAttrs, 1) ||
3154 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3155 ParseValID(CalleeID) ||
3156 ParseParameterList(ArgList, PFS) ||
3157 ParseOptionalAttrs(FnAttrs, 2) ||
3158 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3159 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3160 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3161 ParseTypeAndBasicBlock(UnwindBB, PFS))
3164 // If RetType is a non-function pointer type, then this is the short syntax
3165 // for the call, which means that RetType is just the return type. Infer the
3166 // rest of the function argument types from the arguments that are present.
3167 const PointerType *PFTy = 0;
3168 const FunctionType *Ty = 0;
3169 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3170 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3171 // Pull out the types of all of the arguments...
3172 std::vector<const Type*> ParamTypes;
3173 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3174 ParamTypes.push_back(ArgList[i].V->getType());
3176 if (!FunctionType::isValidReturnType(RetType))
3177 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3179 Ty = FunctionType::get(RetType, ParamTypes, false);
3180 PFTy = PointerType::getUnqual(Ty);
3183 // Look up the callee.
3185 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3187 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3188 // function attributes.
3189 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3190 if (FnAttrs & ObsoleteFuncAttrs) {
3191 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3192 FnAttrs &= ~ObsoleteFuncAttrs;
3195 // Set up the Attributes for the function.
3196 SmallVector<AttributeWithIndex, 8> Attrs;
3197 if (RetAttrs != Attribute::None)
3198 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3200 SmallVector<Value*, 8> Args;
3202 // Loop through FunctionType's arguments and ensure they are specified
3203 // correctly. Also, gather any parameter attributes.
3204 FunctionType::param_iterator I = Ty->param_begin();
3205 FunctionType::param_iterator E = Ty->param_end();
3206 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3207 const Type *ExpectedTy = 0;
3210 } else if (!Ty->isVarArg()) {
3211 return Error(ArgList[i].Loc, "too many arguments specified");
3214 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3215 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3216 ExpectedTy->getDescription() + "'");
3217 Args.push_back(ArgList[i].V);
3218 if (ArgList[i].Attrs != Attribute::None)
3219 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3223 return Error(CallLoc, "not enough parameters specified for call");
3225 if (FnAttrs != Attribute::None)
3226 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3228 // Finish off the Attributes and check them
3229 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3231 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
3232 Args.begin(), Args.end());
3233 II->setCallingConv(CC);
3234 II->setAttributes(PAL);
3241 //===----------------------------------------------------------------------===//
3242 // Binary Operators.
3243 //===----------------------------------------------------------------------===//
3246 /// ::= ArithmeticOps TypeAndValue ',' Value
3248 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3249 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3250 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3251 unsigned Opc, unsigned OperandType) {
3252 LocTy Loc; Value *LHS, *RHS;
3253 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3254 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3255 ParseValue(LHS->getType(), RHS, PFS))
3259 switch (OperandType) {
3260 default: llvm_unreachable("Unknown operand type!");
3261 case 0: // int or FP.
3262 Valid = LHS->getType()->isIntOrIntVector() ||
3263 LHS->getType()->isFPOrFPVector();
3265 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
3266 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
3270 return Error(Loc, "invalid operand type for instruction");
3272 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3277 /// ::= ArithmeticOps TypeAndValue ',' Value {
3278 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3280 LocTy Loc; Value *LHS, *RHS;
3281 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3282 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3283 ParseValue(LHS->getType(), RHS, PFS))
3286 if (!LHS->getType()->isIntOrIntVector())
3287 return Error(Loc,"instruction requires integer or integer vector operands");
3289 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3295 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3296 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3297 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3299 // Parse the integer/fp comparison predicate.
3303 if (ParseCmpPredicate(Pred, Opc) ||
3304 ParseTypeAndValue(LHS, Loc, PFS) ||
3305 ParseToken(lltok::comma, "expected ',' after compare value") ||
3306 ParseValue(LHS->getType(), RHS, PFS))
3309 if (Opc == Instruction::FCmp) {
3310 if (!LHS->getType()->isFPOrFPVector())
3311 return Error(Loc, "fcmp requires floating point operands");
3312 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3314 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3315 if (!LHS->getType()->isIntOrIntVector() &&
3316 !isa<PointerType>(LHS->getType()))
3317 return Error(Loc, "icmp requires integer operands");
3318 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3323 //===----------------------------------------------------------------------===//
3324 // Other Instructions.
3325 //===----------------------------------------------------------------------===//
3329 /// ::= CastOpc TypeAndValue 'to' Type
3330 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3332 LocTy Loc; Value *Op;
3333 PATypeHolder DestTy(Type::getVoidTy(Context));
3334 if (ParseTypeAndValue(Op, Loc, PFS) ||
3335 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3339 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3340 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3341 return Error(Loc, "invalid cast opcode for cast from '" +
3342 Op->getType()->getDescription() + "' to '" +
3343 DestTy->getDescription() + "'");
3345 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3350 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3351 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3353 Value *Op0, *Op1, *Op2;
3354 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3355 ParseToken(lltok::comma, "expected ',' after select condition") ||
3356 ParseTypeAndValue(Op1, PFS) ||
3357 ParseToken(lltok::comma, "expected ',' after select value") ||
3358 ParseTypeAndValue(Op2, PFS))
3361 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3362 return Error(Loc, Reason);
3364 Inst = SelectInst::Create(Op0, Op1, Op2);
3369 /// ::= 'va_arg' TypeAndValue ',' Type
3370 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3372 PATypeHolder EltTy(Type::getVoidTy(Context));
3374 if (ParseTypeAndValue(Op, PFS) ||
3375 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3376 ParseType(EltTy, TypeLoc))
3379 if (!EltTy->isFirstClassType())
3380 return Error(TypeLoc, "va_arg requires operand with first class type");
3382 Inst = new VAArgInst(Op, EltTy);
3386 /// ParseExtractElement
3387 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3388 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3391 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3392 ParseToken(lltok::comma, "expected ',' after extract value") ||
3393 ParseTypeAndValue(Op1, PFS))
3396 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3397 return Error(Loc, "invalid extractelement operands");
3399 Inst = ExtractElementInst::Create(Op0, Op1);
3403 /// ParseInsertElement
3404 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3405 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3407 Value *Op0, *Op1, *Op2;
3408 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3409 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3410 ParseTypeAndValue(Op1, PFS) ||
3411 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3412 ParseTypeAndValue(Op2, PFS))
3415 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3416 return Error(Loc, "invalid insertelement operands");
3418 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3422 /// ParseShuffleVector
3423 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3424 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3426 Value *Op0, *Op1, *Op2;
3427 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3428 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3429 ParseTypeAndValue(Op1, PFS) ||
3430 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3431 ParseTypeAndValue(Op2, PFS))
3434 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3435 return Error(Loc, "invalid extractelement operands");
3437 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3442 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3443 bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3444 PATypeHolder Ty(Type::getVoidTy(Context));
3446 LocTy TypeLoc = Lex.getLoc();
3448 if (ParseType(Ty) ||
3449 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3450 ParseValue(Ty, Op0, PFS) ||
3451 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3452 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3453 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3456 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3458 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3460 if (!EatIfPresent(lltok::comma))
3463 if (Lex.getKind() == lltok::NamedOrCustomMD)
3466 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3467 ParseValue(Ty, Op0, PFS) ||
3468 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3469 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3470 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3474 if (Lex.getKind() == lltok::NamedOrCustomMD)
3475 if (ParseOptionalCustomMetadata()) return true;
3477 if (!Ty->isFirstClassType())
3478 return Error(TypeLoc, "phi node must have first class type");
3480 PHINode *PN = PHINode::Create(Ty);
3481 PN->reserveOperandSpace(PHIVals.size());
3482 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3483 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3489 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3490 /// ParameterList OptionalAttrs
3491 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3493 unsigned RetAttrs, FnAttrs;
3495 PATypeHolder RetType(Type::getVoidTy(Context));
3498 SmallVector<ParamInfo, 16> ArgList;
3499 LocTy CallLoc = Lex.getLoc();
3501 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3502 ParseOptionalCallingConv(CC) ||
3503 ParseOptionalAttrs(RetAttrs, 1) ||
3504 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3505 ParseValID(CalleeID) ||
3506 ParseParameterList(ArgList, PFS) ||
3507 ParseOptionalAttrs(FnAttrs, 2))
3510 // If RetType is a non-function pointer type, then this is the short syntax
3511 // for the call, which means that RetType is just the return type. Infer the
3512 // rest of the function argument types from the arguments that are present.
3513 const PointerType *PFTy = 0;
3514 const FunctionType *Ty = 0;
3515 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3516 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3517 // Pull out the types of all of the arguments...
3518 std::vector<const Type*> ParamTypes;
3519 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3520 ParamTypes.push_back(ArgList[i].V->getType());
3522 if (!FunctionType::isValidReturnType(RetType))
3523 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3525 Ty = FunctionType::get(RetType, ParamTypes, false);
3526 PFTy = PointerType::getUnqual(Ty);
3529 // Look up the callee.
3531 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3533 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3534 // function attributes.
3535 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3536 if (FnAttrs & ObsoleteFuncAttrs) {
3537 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3538 FnAttrs &= ~ObsoleteFuncAttrs;
3541 // Set up the Attributes for the function.
3542 SmallVector<AttributeWithIndex, 8> Attrs;
3543 if (RetAttrs != Attribute::None)
3544 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3546 SmallVector<Value*, 8> Args;
3548 // Loop through FunctionType's arguments and ensure they are specified
3549 // correctly. Also, gather any parameter attributes.
3550 FunctionType::param_iterator I = Ty->param_begin();
3551 FunctionType::param_iterator E = Ty->param_end();
3552 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3553 const Type *ExpectedTy = 0;
3556 } else if (!Ty->isVarArg()) {
3557 return Error(ArgList[i].Loc, "too many arguments specified");
3560 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3561 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3562 ExpectedTy->getDescription() + "'");
3563 Args.push_back(ArgList[i].V);
3564 if (ArgList[i].Attrs != Attribute::None)
3565 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3569 return Error(CallLoc, "not enough parameters specified for call");
3571 if (FnAttrs != Attribute::None)
3572 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3574 // Finish off the Attributes and check them
3575 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3577 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3578 CI->setTailCall(isTail);
3579 CI->setCallingConv(CC);
3580 CI->setAttributes(PAL);
3585 //===----------------------------------------------------------------------===//
3586 // Memory Instructions.
3587 //===----------------------------------------------------------------------===//
3590 /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3591 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
3592 bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3593 BasicBlock* BB, bool isAlloca) {
3594 PATypeHolder Ty(Type::getVoidTy(Context));
3597 unsigned Alignment = 0;
3598 if (ParseType(Ty)) return true;
3600 if (EatIfPresent(lltok::comma)) {
3601 if (Lex.getKind() == lltok::kw_align
3602 || Lex.getKind() == lltok::NamedOrCustomMD) {
3603 if (ParseOptionalInfo(Alignment)) return true;
3605 if (ParseTypeAndValue(Size, SizeLoc, PFS)) return true;
3606 if (EatIfPresent(lltok::comma))
3607 if (ParseOptionalInfo(Alignment)) return true;
3611 if (Size && Size->getType() != Type::getInt32Ty(Context))
3612 return Error(SizeLoc, "element count must be i32");
3615 Inst = new AllocaInst(Ty, Size, Alignment);
3619 // Autoupgrade old malloc instruction to malloc call.
3620 // FIXME: Remove in LLVM 3.0.
3621 const Type *IntPtrTy = Type::getInt32Ty(Context);
3622 Constant *AllocSize = ConstantExpr::getSizeOf(Ty);
3623 AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, IntPtrTy);
3625 // Prototype malloc as "void *(int32)".
3626 // This function is renamed as "malloc" in ValidateEndOfModule().
3627 MallocF = cast<Function>(
3628 M->getOrInsertFunction("", Type::getInt8PtrTy(Context), IntPtrTy, NULL));
3629 Inst = CallInst::CreateMalloc(BB, IntPtrTy, Ty, AllocSize, Size, MallocF);
3634 /// ::= 'free' TypeAndValue
3635 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS,
3637 Value *Val; LocTy Loc;
3638 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3639 if (!isa<PointerType>(Val->getType()))
3640 return Error(Loc, "operand to free must be a pointer");
3641 Inst = CallInst::CreateFree(Val, BB);
3646 /// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
3647 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3649 Value *Val; LocTy Loc;
3650 unsigned Alignment = 0;
3651 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3653 if (EatIfPresent(lltok::comma))
3654 if (ParseOptionalInfo(Alignment)) return true;
3656 if (!isa<PointerType>(Val->getType()) ||
3657 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3658 return Error(Loc, "load operand must be a pointer to a first class type");
3660 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3665 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3666 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3668 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3669 unsigned Alignment = 0;
3670 if (ParseTypeAndValue(Val, Loc, PFS) ||
3671 ParseToken(lltok::comma, "expected ',' after store operand") ||
3672 ParseTypeAndValue(Ptr, PtrLoc, PFS))
3675 if (EatIfPresent(lltok::comma))
3676 if (ParseOptionalInfo(Alignment)) return true;
3678 if (!isa<PointerType>(Ptr->getType()))
3679 return Error(PtrLoc, "store operand must be a pointer");
3680 if (!Val->getType()->isFirstClassType())
3681 return Error(Loc, "store operand must be a first class value");
3682 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3683 return Error(Loc, "stored value and pointer type do not match");
3685 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3690 /// ::= 'getresult' TypeAndValue ',' i32
3691 /// FIXME: Remove support for getresult in LLVM 3.0
3692 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3693 Value *Val; LocTy ValLoc, EltLoc;
3695 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3696 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3697 ParseUInt32(Element, EltLoc))
3700 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3701 return Error(ValLoc, "getresult inst requires an aggregate operand");
3702 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3703 return Error(EltLoc, "invalid getresult index for value");
3704 Inst = ExtractValueInst::Create(Val, Element);
3708 /// ParseGetElementPtr
3709 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
3710 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3711 Value *Ptr, *Val; LocTy Loc, EltLoc;
3713 bool InBounds = EatIfPresent(lltok::kw_inbounds);
3715 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3717 if (!isa<PointerType>(Ptr->getType()))
3718 return Error(Loc, "base of getelementptr must be a pointer");
3720 SmallVector<Value*, 16> Indices;
3721 while (EatIfPresent(lltok::comma)) {
3722 if (Lex.getKind() == lltok::NamedOrCustomMD)
3724 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3725 if (!isa<IntegerType>(Val->getType()))
3726 return Error(EltLoc, "getelementptr index must be an integer");
3727 Indices.push_back(Val);
3729 if (Lex.getKind() == lltok::NamedOrCustomMD)
3730 if (ParseOptionalCustomMetadata()) return true;
3732 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3733 Indices.begin(), Indices.end()))
3734 return Error(Loc, "invalid getelementptr indices");
3735 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3737 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
3741 /// ParseExtractValue
3742 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3743 bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3744 Value *Val; LocTy Loc;
3745 SmallVector<unsigned, 4> Indices;
3746 if (ParseTypeAndValue(Val, Loc, PFS) ||
3747 ParseIndexList(Indices))
3749 if (Lex.getKind() == lltok::NamedOrCustomMD)
3750 if (ParseOptionalCustomMetadata()) return true;
3752 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3753 return Error(Loc, "extractvalue operand must be array or struct");
3755 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3757 return Error(Loc, "invalid indices for extractvalue");
3758 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3762 /// ParseInsertValue
3763 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3764 bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3765 Value *Val0, *Val1; LocTy Loc0, Loc1;
3766 SmallVector<unsigned, 4> Indices;
3767 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3768 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3769 ParseTypeAndValue(Val1, Loc1, PFS) ||
3770 ParseIndexList(Indices))
3772 if (Lex.getKind() == lltok::NamedOrCustomMD)
3773 if (ParseOptionalCustomMetadata()) return true;
3775 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3776 return Error(Loc0, "extractvalue operand must be array or struct");
3778 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3780 return Error(Loc0, "invalid indices for insertvalue");
3781 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3785 //===----------------------------------------------------------------------===//
3786 // Embedded metadata.
3787 //===----------------------------------------------------------------------===//
3789 /// ParseMDNodeVector
3790 /// ::= Element (',' Element)*
3792 /// ::= 'null' | TypeAndValue
3793 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
3794 assert(Lex.getKind() == lltok::lbrace);
3798 if (Lex.getKind() == lltok::kw_null) {
3802 PATypeHolder Ty(Type::getVoidTy(Context));
3803 if (ParseType(Ty)) return true;
3804 if (Lex.getKind() == lltok::Metadata) {
3806 MetadataBase *Node = 0;
3807 if (!ParseMDNode(Node))
3810 MetadataBase *MDS = 0;
3811 if (ParseMDString(MDS)) return true;
3816 if (ParseGlobalValue(Ty, C)) return true;
3821 } while (EatIfPresent(lltok::comma));