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"
33 /// ValID - Represents a reference of a definition of some sort with no type.
34 /// There are several cases where we have to parse the value but where the
35 /// type can depend on later context. This may either be a numeric reference
36 /// or a symbolic (%var) reference. This is just a discriminated union.
39 t_LocalID, t_GlobalID, // ID in UIntVal.
40 t_LocalName, t_GlobalName, // Name in StrVal.
41 t_APSInt, t_APFloat, // Value in APSIntVal/APFloatVal.
42 t_Null, t_Undef, t_Zero, // No value.
43 t_EmptyArray, // No value: []
44 t_Constant, // Value in ConstantVal.
45 t_InlineAsm, // Value in StrVal/StrVal2/UIntVal.
46 t_Metadata // Value in MetadataVal.
51 std::string StrVal, StrVal2;
54 Constant *ConstantVal;
55 MetadataBase *MetadataVal;
56 ValID() : APFloatVal(0.0) {}
60 /// Run: module ::= toplevelentity*
61 bool LLParser::Run() {
65 return ParseTopLevelEntities() ||
66 ValidateEndOfModule();
69 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
71 bool LLParser::ValidateEndOfModule() {
72 if (!ForwardRefTypes.empty())
73 return Error(ForwardRefTypes.begin()->second.second,
74 "use of undefined type named '" +
75 ForwardRefTypes.begin()->first + "'");
76 if (!ForwardRefTypeIDs.empty())
77 return Error(ForwardRefTypeIDs.begin()->second.second,
78 "use of undefined type '%" +
79 utostr(ForwardRefTypeIDs.begin()->first) + "'");
81 if (!ForwardRefVals.empty())
82 return Error(ForwardRefVals.begin()->second.second,
83 "use of undefined value '@" + ForwardRefVals.begin()->first +
86 if (!ForwardRefValIDs.empty())
87 return Error(ForwardRefValIDs.begin()->second.second,
88 "use of undefined value '@" +
89 utostr(ForwardRefValIDs.begin()->first) + "'");
91 if (!ForwardRefMDNodes.empty())
92 return Error(ForwardRefMDNodes.begin()->second.second,
93 "use of undefined metadata '!" +
94 utostr(ForwardRefMDNodes.begin()->first) + "'");
97 // Look for intrinsic functions and CallInst that need to be upgraded
98 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
99 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
104 //===----------------------------------------------------------------------===//
105 // Top-Level Entities
106 //===----------------------------------------------------------------------===//
108 bool LLParser::ParseTopLevelEntities() {
110 switch (Lex.getKind()) {
111 default: return TokError("expected top-level entity");
112 case lltok::Eof: return false;
113 //case lltok::kw_define:
114 case lltok::kw_declare: if (ParseDeclare()) return true; break;
115 case lltok::kw_define: if (ParseDefine()) return true; break;
116 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
117 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
118 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
119 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
120 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
121 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
122 case lltok::LocalVar: if (ParseNamedType()) return true; break;
123 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
124 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
125 case lltok::Metadata: if (ParseStandaloneMetadata()) return true; break;
126 case lltok::NamedMD: if (ParseNamedMetadata()) return true; break;
128 // The Global variable production with no name can have many different
129 // optional leading prefixes, the production is:
130 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
131 // OptionalAddrSpace ('constant'|'global') ...
132 case lltok::kw_private : // OptionalLinkage
133 case lltok::kw_linker_private: // OptionalLinkage
134 case lltok::kw_internal: // OptionalLinkage
135 case lltok::kw_weak: // OptionalLinkage
136 case lltok::kw_weak_odr: // OptionalLinkage
137 case lltok::kw_linkonce: // OptionalLinkage
138 case lltok::kw_linkonce_odr: // OptionalLinkage
139 case lltok::kw_appending: // OptionalLinkage
140 case lltok::kw_dllexport: // OptionalLinkage
141 case lltok::kw_common: // OptionalLinkage
142 case lltok::kw_dllimport: // OptionalLinkage
143 case lltok::kw_extern_weak: // OptionalLinkage
144 case lltok::kw_external: { // OptionalLinkage
145 unsigned Linkage, Visibility;
146 if (ParseOptionalLinkage(Linkage) ||
147 ParseOptionalVisibility(Visibility) ||
148 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
152 case lltok::kw_default: // OptionalVisibility
153 case lltok::kw_hidden: // OptionalVisibility
154 case lltok::kw_protected: { // OptionalVisibility
156 if (ParseOptionalVisibility(Visibility) ||
157 ParseGlobal("", SMLoc(), 0, false, Visibility))
162 case lltok::kw_thread_local: // OptionalThreadLocal
163 case lltok::kw_addrspace: // OptionalAddrSpace
164 case lltok::kw_constant: // GlobalType
165 case lltok::kw_global: // GlobalType
166 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
174 /// ::= 'module' 'asm' STRINGCONSTANT
175 bool LLParser::ParseModuleAsm() {
176 assert(Lex.getKind() == lltok::kw_module);
180 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
181 ParseStringConstant(AsmStr)) return true;
183 const std::string &AsmSoFar = M->getModuleInlineAsm();
184 if (AsmSoFar.empty())
185 M->setModuleInlineAsm(AsmStr);
187 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
192 /// ::= 'target' 'triple' '=' STRINGCONSTANT
193 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
194 bool LLParser::ParseTargetDefinition() {
195 assert(Lex.getKind() == lltok::kw_target);
198 default: return TokError("unknown target property");
199 case lltok::kw_triple:
201 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
202 ParseStringConstant(Str))
204 M->setTargetTriple(Str);
206 case lltok::kw_datalayout:
208 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
209 ParseStringConstant(Str))
211 M->setDataLayout(Str);
217 /// ::= 'deplibs' '=' '[' ']'
218 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
219 bool LLParser::ParseDepLibs() {
220 assert(Lex.getKind() == lltok::kw_deplibs);
222 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
223 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
226 if (EatIfPresent(lltok::rsquare))
230 if (ParseStringConstant(Str)) return true;
233 while (EatIfPresent(lltok::comma)) {
234 if (ParseStringConstant(Str)) return true;
238 return ParseToken(lltok::rsquare, "expected ']' at end of list");
241 /// ParseUnnamedType:
243 /// ::= LocalVarID '=' 'type' type
244 bool LLParser::ParseUnnamedType() {
245 unsigned TypeID = NumberedTypes.size();
247 // Handle the LocalVarID form.
248 if (Lex.getKind() == lltok::LocalVarID) {
249 if (Lex.getUIntVal() != TypeID)
250 return Error(Lex.getLoc(), "type expected to be numbered '%" +
251 utostr(TypeID) + "'");
252 Lex.Lex(); // eat LocalVarID;
254 if (ParseToken(lltok::equal, "expected '=' after name"))
258 assert(Lex.getKind() == lltok::kw_type);
259 LocTy TypeLoc = Lex.getLoc();
260 Lex.Lex(); // eat kw_type
262 PATypeHolder Ty(Type::VoidTy);
263 if (ParseType(Ty)) return true;
265 // See if this type was previously referenced.
266 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
267 FI = ForwardRefTypeIDs.find(TypeID);
268 if (FI != ForwardRefTypeIDs.end()) {
269 if (FI->second.first.get() == Ty)
270 return Error(TypeLoc, "self referential type is invalid");
272 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
273 Ty = FI->second.first.get();
274 ForwardRefTypeIDs.erase(FI);
277 NumberedTypes.push_back(Ty);
283 /// ::= LocalVar '=' 'type' type
284 bool LLParser::ParseNamedType() {
285 std::string Name = Lex.getStrVal();
286 LocTy NameLoc = Lex.getLoc();
287 Lex.Lex(); // eat LocalVar.
289 PATypeHolder Ty(Type::VoidTy);
291 if (ParseToken(lltok::equal, "expected '=' after name") ||
292 ParseToken(lltok::kw_type, "expected 'type' after name") ||
296 // Set the type name, checking for conflicts as we do so.
297 bool AlreadyExists = M->addTypeName(Name, Ty);
298 if (!AlreadyExists) return false;
300 // See if this type is a forward reference. We need to eagerly resolve
301 // types to allow recursive type redefinitions below.
302 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
303 FI = ForwardRefTypes.find(Name);
304 if (FI != ForwardRefTypes.end()) {
305 if (FI->second.first.get() == Ty)
306 return Error(NameLoc, "self referential type is invalid");
308 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
309 Ty = FI->second.first.get();
310 ForwardRefTypes.erase(FI);
313 // Inserting a name that is already defined, get the existing name.
314 const Type *Existing = M->getTypeByName(Name);
315 assert(Existing && "Conflict but no matching type?!");
317 // Otherwise, this is an attempt to redefine a type. That's okay if
318 // the redefinition is identical to the original.
319 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
320 if (Existing == Ty) return false;
322 // Any other kind of (non-equivalent) redefinition is an error.
323 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
324 Ty->getDescription() + "'");
329 /// ::= 'declare' FunctionHeader
330 bool LLParser::ParseDeclare() {
331 assert(Lex.getKind() == lltok::kw_declare);
335 return ParseFunctionHeader(F, false);
339 /// ::= 'define' FunctionHeader '{' ...
340 bool LLParser::ParseDefine() {
341 assert(Lex.getKind() == lltok::kw_define);
345 return ParseFunctionHeader(F, true) ||
346 ParseFunctionBody(*F);
352 bool LLParser::ParseGlobalType(bool &IsConstant) {
353 if (Lex.getKind() == lltok::kw_constant)
355 else if (Lex.getKind() == lltok::kw_global)
359 return TokError("expected 'global' or 'constant'");
365 /// ParseUnnamedGlobal:
366 /// OptionalVisibility ALIAS ...
367 /// OptionalLinkage OptionalVisibility ... -> global variable
368 /// GlobalID '=' OptionalVisibility ALIAS ...
369 /// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
370 bool LLParser::ParseUnnamedGlobal() {
371 unsigned VarID = NumberedVals.size();
373 LocTy NameLoc = Lex.getLoc();
375 // Handle the GlobalID form.
376 if (Lex.getKind() == lltok::GlobalID) {
377 if (Lex.getUIntVal() != VarID)
378 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
379 utostr(VarID) + "'");
380 Lex.Lex(); // eat GlobalID;
382 if (ParseToken(lltok::equal, "expected '=' after name"))
387 unsigned Linkage, Visibility;
388 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
389 ParseOptionalVisibility(Visibility))
392 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
393 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
394 return ParseAlias(Name, NameLoc, Visibility);
397 /// ParseNamedGlobal:
398 /// GlobalVar '=' OptionalVisibility ALIAS ...
399 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
400 bool LLParser::ParseNamedGlobal() {
401 assert(Lex.getKind() == lltok::GlobalVar);
402 LocTy NameLoc = Lex.getLoc();
403 std::string Name = Lex.getStrVal();
407 unsigned Linkage, Visibility;
408 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
409 ParseOptionalLinkage(Linkage, HasLinkage) ||
410 ParseOptionalVisibility(Visibility))
413 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
414 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
415 return ParseAlias(Name, NameLoc, Visibility);
419 // ::= '!' STRINGCONSTANT
420 bool LLParser::ParseMDString(MetadataBase *&MDS) {
422 if (ParseStringConstant(Str)) return true;
423 MDS = MDString::get(Context, Str);
428 // ::= '!' MDNodeNumber
429 bool LLParser::ParseMDNode(MetadataBase *&Node) {
430 // !{ ..., !42, ... }
432 if (ParseUInt32(MID)) return true;
434 // Check existing MDNode.
435 std::map<unsigned, MetadataBase *>::iterator I = MetadataCache.find(MID);
436 if (I != MetadataCache.end()) {
441 // Check known forward references.
442 std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
443 FI = ForwardRefMDNodes.find(MID);
444 if (FI != ForwardRefMDNodes.end()) {
445 Node = FI->second.first;
449 // Create MDNode forward reference
450 SmallVector<Value *, 1> Elts;
451 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
452 Elts.push_back(MDString::get(Context, FwdRefName));
453 MDNode *FwdNode = MDNode::get(Context, Elts.data(), Elts.size());
454 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
459 ///ParseNamedMetadata:
460 /// !foo = !{ !1, !2 }
461 bool LLParser::ParseNamedMetadata() {
462 assert(Lex.getKind() == lltok::NamedMD);
464 std::string Name = Lex.getStrVal();
466 if (ParseToken(lltok::equal, "expected '=' here"))
469 if (Lex.getKind() != lltok::Metadata)
470 return TokError("Expected '!' here");
473 if (Lex.getKind() != lltok::lbrace)
474 return TokError("Expected '{' here");
476 SmallVector<MetadataBase *, 8> Elts;
478 if (Lex.getKind() != lltok::Metadata)
479 return TokError("Expected '!' here");
482 if (ParseMDNode(N)) return true;
484 } while (EatIfPresent(lltok::comma));
486 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
489 NamedMDNode::Create(Name, Elts.data(), Elts.size(), M);
493 /// ParseStandaloneMetadata:
495 bool LLParser::ParseStandaloneMetadata() {
496 assert(Lex.getKind() == lltok::Metadata);
498 unsigned MetadataID = 0;
499 if (ParseUInt32(MetadataID))
501 if (MetadataCache.find(MetadataID) != MetadataCache.end())
502 return TokError("Metadata id is already used");
503 if (ParseToken(lltok::equal, "expected '=' here"))
507 PATypeHolder Ty(Type::VoidTy);
508 if (ParseType(Ty, TyLoc))
511 if (Lex.getKind() != lltok::Metadata)
512 return TokError("Expected metadata here");
515 if (Lex.getKind() != lltok::lbrace)
516 return TokError("Expected '{' here");
518 SmallVector<Value *, 16> Elts;
519 if (ParseMDNodeVector(Elts)
520 || ParseToken(lltok::rbrace, "expected end of metadata node"))
523 MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
524 MetadataCache[MetadataID] = Init;
525 std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
526 FI = ForwardRefMDNodes.find(MetadataID);
527 if (FI != ForwardRefMDNodes.end()) {
528 MDNode *FwdNode = cast<MDNode>(FI->second.first);
529 FwdNode->replaceAllUsesWith(Init);
530 ForwardRefMDNodes.erase(FI);
537 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
540 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
541 /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
543 /// Everything through visibility has already been parsed.
545 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
546 unsigned Visibility) {
547 assert(Lex.getKind() == lltok::kw_alias);
550 LocTy LinkageLoc = Lex.getLoc();
551 if (ParseOptionalLinkage(Linkage))
554 if (Linkage != GlobalValue::ExternalLinkage &&
555 Linkage != GlobalValue::WeakAnyLinkage &&
556 Linkage != GlobalValue::WeakODRLinkage &&
557 Linkage != GlobalValue::InternalLinkage &&
558 Linkage != GlobalValue::PrivateLinkage &&
559 Linkage != GlobalValue::LinkerPrivateLinkage)
560 return Error(LinkageLoc, "invalid linkage type for alias");
563 LocTy AliaseeLoc = Lex.getLoc();
564 if (Lex.getKind() != lltok::kw_bitcast &&
565 Lex.getKind() != lltok::kw_getelementptr) {
566 if (ParseGlobalTypeAndValue(Aliasee)) return true;
568 // The bitcast dest type is not present, it is implied by the dest type.
570 if (ParseValID(ID)) return true;
571 if (ID.Kind != ValID::t_Constant)
572 return Error(AliaseeLoc, "invalid aliasee");
573 Aliasee = ID.ConstantVal;
576 if (!isa<PointerType>(Aliasee->getType()))
577 return Error(AliaseeLoc, "alias must have pointer type");
579 // Okay, create the alias but do not insert it into the module yet.
580 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
581 (GlobalValue::LinkageTypes)Linkage, Name,
583 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
585 // See if this value already exists in the symbol table. If so, it is either
586 // a redefinition or a definition of a forward reference.
587 if (GlobalValue *Val =
588 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
589 // See if this was a redefinition. If so, there is no entry in
591 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
592 I = ForwardRefVals.find(Name);
593 if (I == ForwardRefVals.end())
594 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
596 // Otherwise, this was a definition of forward ref. Verify that types
598 if (Val->getType() != GA->getType())
599 return Error(NameLoc,
600 "forward reference and definition of alias have different types");
602 // If they agree, just RAUW the old value with the alias and remove the
604 Val->replaceAllUsesWith(GA);
605 Val->eraseFromParent();
606 ForwardRefVals.erase(I);
609 // Insert into the module, we know its name won't collide now.
610 M->getAliasList().push_back(GA);
611 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
617 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
618 /// OptionalAddrSpace GlobalType Type Const
619 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
620 /// OptionalAddrSpace GlobalType Type Const
622 /// Everything through visibility has been parsed already.
624 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
625 unsigned Linkage, bool HasLinkage,
626 unsigned Visibility) {
628 bool ThreadLocal, IsConstant;
631 PATypeHolder Ty(Type::VoidTy);
632 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
633 ParseOptionalAddrSpace(AddrSpace) ||
634 ParseGlobalType(IsConstant) ||
635 ParseType(Ty, TyLoc))
638 // If the linkage is specified and is external, then no initializer is
641 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
642 Linkage != GlobalValue::ExternalWeakLinkage &&
643 Linkage != GlobalValue::ExternalLinkage)) {
644 if (ParseGlobalValue(Ty, Init))
648 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
649 return Error(TyLoc, "invalid type for global variable");
651 GlobalVariable *GV = 0;
653 // See if the global was forward referenced, if so, use the global.
655 if ((GV = M->getGlobalVariable(Name, true)) &&
656 !ForwardRefVals.erase(Name))
657 return Error(NameLoc, "redefinition of global '@" + Name + "'");
659 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
660 I = ForwardRefValIDs.find(NumberedVals.size());
661 if (I != ForwardRefValIDs.end()) {
662 GV = cast<GlobalVariable>(I->second.first);
663 ForwardRefValIDs.erase(I);
668 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
669 Name, 0, false, AddrSpace);
671 if (GV->getType()->getElementType() != Ty)
673 "forward reference and definition of global have different types");
675 // Move the forward-reference to the correct spot in the module.
676 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
680 NumberedVals.push_back(GV);
682 // Set the parsed properties on the global.
684 GV->setInitializer(Init);
685 GV->setConstant(IsConstant);
686 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
687 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
688 GV->setThreadLocal(ThreadLocal);
690 // Parse attributes on the global.
691 while (Lex.getKind() == lltok::comma) {
694 if (Lex.getKind() == lltok::kw_section) {
696 GV->setSection(Lex.getStrVal());
697 if (ParseToken(lltok::StringConstant, "expected global section string"))
699 } else if (Lex.getKind() == lltok::kw_align) {
701 if (ParseOptionalAlignment(Alignment)) return true;
702 GV->setAlignment(Alignment);
704 TokError("unknown global variable property!");
712 //===----------------------------------------------------------------------===//
713 // GlobalValue Reference/Resolution Routines.
714 //===----------------------------------------------------------------------===//
716 /// GetGlobalVal - Get a value with the specified name or ID, creating a
717 /// forward reference record if needed. This can return null if the value
718 /// exists but does not have the right type.
719 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
721 const PointerType *PTy = dyn_cast<PointerType>(Ty);
723 Error(Loc, "global variable reference must have pointer type");
727 // Look this name up in the normal function symbol table.
729 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
731 // If this is a forward reference for the value, see if we already created a
732 // forward ref record.
734 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
735 I = ForwardRefVals.find(Name);
736 if (I != ForwardRefVals.end())
737 Val = I->second.first;
740 // If we have the value in the symbol table or fwd-ref table, return it.
742 if (Val->getType() == Ty) return Val;
743 Error(Loc, "'@" + Name + "' defined with type '" +
744 Val->getType()->getDescription() + "'");
748 // Otherwise, create a new forward reference for this value and remember it.
750 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
751 // Function types can return opaque but functions can't.
752 if (isa<OpaqueType>(FT->getReturnType())) {
753 Error(Loc, "function may not return opaque type");
757 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
759 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
760 GlobalValue::ExternalWeakLinkage, 0, Name);
763 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
767 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
768 const PointerType *PTy = dyn_cast<PointerType>(Ty);
770 Error(Loc, "global variable reference must have pointer type");
774 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
776 // If this is a forward reference for the value, see if we already created a
777 // forward ref record.
779 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
780 I = ForwardRefValIDs.find(ID);
781 if (I != ForwardRefValIDs.end())
782 Val = I->second.first;
785 // If we have the value in the symbol table or fwd-ref table, return it.
787 if (Val->getType() == Ty) return Val;
788 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
789 Val->getType()->getDescription() + "'");
793 // Otherwise, create a new forward reference for this value and remember it.
795 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
796 // Function types can return opaque but functions can't.
797 if (isa<OpaqueType>(FT->getReturnType())) {
798 Error(Loc, "function may not return opaque type");
801 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
803 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
804 GlobalValue::ExternalWeakLinkage, 0, "");
807 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
812 //===----------------------------------------------------------------------===//
814 //===----------------------------------------------------------------------===//
816 /// ParseToken - If the current token has the specified kind, eat it and return
817 /// success. Otherwise, emit the specified error and return failure.
818 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
819 if (Lex.getKind() != T)
820 return TokError(ErrMsg);
825 /// ParseStringConstant
826 /// ::= StringConstant
827 bool LLParser::ParseStringConstant(std::string &Result) {
828 if (Lex.getKind() != lltok::StringConstant)
829 return TokError("expected string constant");
830 Result = Lex.getStrVal();
837 bool LLParser::ParseUInt32(unsigned &Val) {
838 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
839 return TokError("expected integer");
840 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
841 if (Val64 != unsigned(Val64))
842 return TokError("expected 32-bit integer (too large)");
849 /// ParseOptionalAddrSpace
851 /// := 'addrspace' '(' uint32 ')'
852 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
854 if (!EatIfPresent(lltok::kw_addrspace))
856 return ParseToken(lltok::lparen, "expected '(' in address space") ||
857 ParseUInt32(AddrSpace) ||
858 ParseToken(lltok::rparen, "expected ')' in address space");
861 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
862 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
863 /// 2: function attr.
864 /// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
865 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
866 Attrs = Attribute::None;
867 LocTy AttrLoc = Lex.getLoc();
870 switch (Lex.getKind()) {
873 // Treat these as signext/zeroext if they occur in the argument list after
874 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
875 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
877 // FIXME: REMOVE THIS IN LLVM 3.0
879 if (Lex.getKind() == lltok::kw_sext)
880 Attrs |= Attribute::SExt;
882 Attrs |= Attribute::ZExt;
886 default: // End of attributes.
887 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
888 return Error(AttrLoc, "invalid use of function-only attribute");
890 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
891 return Error(AttrLoc, "invalid use of parameter-only attribute");
894 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
895 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
896 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
897 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
898 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
899 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
900 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
901 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
903 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
904 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
905 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
906 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
907 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
908 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
909 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
910 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
911 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
912 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
913 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
914 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
916 case lltok::kw_align: {
918 if (ParseOptionalAlignment(Alignment))
920 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
928 /// ParseOptionalLinkage
931 /// ::= 'linker_private'
936 /// ::= 'linkonce_odr'
941 /// ::= 'extern_weak'
943 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
945 switch (Lex.getKind()) {
946 default: Res=GlobalValue::ExternalLinkage; return false;
947 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
948 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
949 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
950 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
951 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
952 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
953 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
954 case lltok::kw_available_externally:
955 Res = GlobalValue::AvailableExternallyLinkage;
957 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
958 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
959 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
960 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
961 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
962 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
969 /// ParseOptionalVisibility
975 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
976 switch (Lex.getKind()) {
977 default: Res = GlobalValue::DefaultVisibility; return false;
978 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
979 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
980 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
986 /// ParseOptionalCallingConv
991 /// ::= 'x86_stdcallcc'
992 /// ::= 'x86_fastcallcc'
994 /// ::= 'arm_aapcscc'
995 /// ::= 'arm_aapcs_vfpcc'
998 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
999 switch (Lex.getKind()) {
1000 default: CC = CallingConv::C; return false;
1001 case lltok::kw_ccc: CC = CallingConv::C; break;
1002 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1003 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1004 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1005 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1006 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1007 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1008 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1009 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
1015 /// ParseOptionalAlignment
1018 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1020 if (!EatIfPresent(lltok::kw_align))
1022 LocTy AlignLoc = Lex.getLoc();
1023 if (ParseUInt32(Alignment)) return true;
1024 if (!isPowerOf2_32(Alignment))
1025 return Error(AlignLoc, "alignment is not a power of two");
1029 /// ParseOptionalCommaAlignment
1031 /// ::= ',' 'align' 4
1032 bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
1034 if (!EatIfPresent(lltok::comma))
1036 return ParseToken(lltok::kw_align, "expected 'align'") ||
1037 ParseUInt32(Alignment);
1041 /// ::= (',' uint32)+
1042 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
1043 if (Lex.getKind() != lltok::comma)
1044 return TokError("expected ',' as start of index list");
1046 while (EatIfPresent(lltok::comma)) {
1048 if (ParseUInt32(Idx)) return true;
1049 Indices.push_back(Idx);
1055 //===----------------------------------------------------------------------===//
1057 //===----------------------------------------------------------------------===//
1059 /// ParseType - Parse and resolve a full type.
1060 bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1061 LocTy TypeLoc = Lex.getLoc();
1062 if (ParseTypeRec(Result)) return true;
1064 // Verify no unresolved uprefs.
1065 if (!UpRefs.empty())
1066 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
1068 if (!AllowVoid && Result.get() == Type::VoidTy)
1069 return Error(TypeLoc, "void type only allowed for function results");
1074 /// HandleUpRefs - Every time we finish a new layer of types, this function is
1075 /// called. It loops through the UpRefs vector, which is a list of the
1076 /// currently active types. For each type, if the up-reference is contained in
1077 /// the newly completed type, we decrement the level count. When the level
1078 /// count reaches zero, the up-referenced type is the type that is passed in:
1079 /// thus we can complete the cycle.
1081 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1082 // If Ty isn't abstract, or if there are no up-references in it, then there is
1083 // nothing to resolve here.
1084 if (!ty->isAbstract() || UpRefs.empty()) return ty;
1086 PATypeHolder Ty(ty);
1088 errs() << "Type '" << Ty->getDescription()
1089 << "' newly formed. Resolving upreferences.\n"
1090 << UpRefs.size() << " upreferences active!\n";
1093 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1094 // to zero), we resolve them all together before we resolve them to Ty. At
1095 // the end of the loop, if there is anything to resolve to Ty, it will be in
1097 OpaqueType *TypeToResolve = 0;
1099 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1100 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1102 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1103 UpRefs[i].LastContainedTy) != Ty->subtype_end();
1106 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1107 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1108 << (ContainsType ? "true" : "false")
1109 << " level=" << UpRefs[i].NestingLevel << "\n";
1114 // Decrement level of upreference
1115 unsigned Level = --UpRefs[i].NestingLevel;
1116 UpRefs[i].LastContainedTy = Ty;
1118 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1123 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1126 TypeToResolve = UpRefs[i].UpRefTy;
1128 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1129 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1130 --i; // Do not skip the next element.
1134 TypeToResolve->refineAbstractTypeTo(Ty);
1140 /// ParseTypeRec - The recursive function used to process the internal
1141 /// implementation details of types.
1142 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1143 switch (Lex.getKind()) {
1145 return TokError("expected type");
1147 // TypeRec ::= 'float' | 'void' (etc)
1148 Result = Lex.getTyVal();
1151 case lltok::kw_opaque:
1152 // TypeRec ::= 'opaque'
1153 Result = OpaqueType::get();
1157 // TypeRec ::= '{' ... '}'
1158 if (ParseStructType(Result, false))
1161 case lltok::lsquare:
1162 // TypeRec ::= '[' ... ']'
1163 Lex.Lex(); // eat the lsquare.
1164 if (ParseArrayVectorType(Result, false))
1167 case lltok::less: // Either vector or packed struct.
1168 // TypeRec ::= '<' ... '>'
1170 if (Lex.getKind() == lltok::lbrace) {
1171 if (ParseStructType(Result, true) ||
1172 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1174 } else if (ParseArrayVectorType(Result, true))
1177 case lltok::LocalVar:
1178 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1180 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1183 Result = OpaqueType::get();
1184 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1185 std::make_pair(Result,
1187 M->addTypeName(Lex.getStrVal(), Result.get());
1192 case lltok::LocalVarID:
1194 if (Lex.getUIntVal() < NumberedTypes.size())
1195 Result = NumberedTypes[Lex.getUIntVal()];
1197 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1198 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1199 if (I != ForwardRefTypeIDs.end())
1200 Result = I->second.first;
1202 Result = OpaqueType::get();
1203 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1204 std::make_pair(Result,
1210 case lltok::backslash: {
1211 // TypeRec ::= '\' 4
1214 if (ParseUInt32(Val)) return true;
1215 OpaqueType *OT = OpaqueType::get(); //Use temporary placeholder.
1216 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1222 // Parse the type suffixes.
1224 switch (Lex.getKind()) {
1226 default: return false;
1228 // TypeRec ::= TypeRec '*'
1230 if (Result.get() == Type::LabelTy)
1231 return TokError("basic block pointers are invalid");
1232 if (Result.get() == Type::VoidTy)
1233 return TokError("pointers to void are invalid; use i8* instead");
1234 if (!PointerType::isValidElementType(Result.get()))
1235 return TokError("pointer to this type is invalid");
1236 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1240 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1241 case lltok::kw_addrspace: {
1242 if (Result.get() == Type::LabelTy)
1243 return TokError("basic block pointers are invalid");
1244 if (Result.get() == Type::VoidTy)
1245 return TokError("pointers to void are invalid; use i8* instead");
1246 if (!PointerType::isValidElementType(Result.get()))
1247 return TokError("pointer to this type is invalid");
1249 if (ParseOptionalAddrSpace(AddrSpace) ||
1250 ParseToken(lltok::star, "expected '*' in address space"))
1253 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1257 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1259 if (ParseFunctionType(Result))
1266 /// ParseParameterList
1268 /// ::= '(' Arg (',' Arg)* ')'
1270 /// ::= Type OptionalAttributes Value OptionalAttributes
1271 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1272 PerFunctionState &PFS) {
1273 if (ParseToken(lltok::lparen, "expected '(' in call"))
1276 while (Lex.getKind() != lltok::rparen) {
1277 // If this isn't the first argument, we need a comma.
1278 if (!ArgList.empty() &&
1279 ParseToken(lltok::comma, "expected ',' in argument list"))
1282 // Parse the argument.
1284 PATypeHolder ArgTy(Type::VoidTy);
1285 unsigned ArgAttrs1, ArgAttrs2;
1287 if (ParseType(ArgTy, ArgLoc) ||
1288 ParseOptionalAttrs(ArgAttrs1, 0) ||
1289 ParseValue(ArgTy, V, PFS) ||
1290 // FIXME: Should not allow attributes after the argument, remove this in
1292 ParseOptionalAttrs(ArgAttrs2, 3))
1294 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1297 Lex.Lex(); // Lex the ')'.
1303 /// ParseArgumentList - Parse the argument list for a function type or function
1304 /// prototype. If 'inType' is true then we are parsing a FunctionType.
1305 /// ::= '(' ArgTypeListI ')'
1309 /// ::= ArgTypeList ',' '...'
1310 /// ::= ArgType (',' ArgType)*
1312 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1313 bool &isVarArg, bool inType) {
1315 assert(Lex.getKind() == lltok::lparen);
1316 Lex.Lex(); // eat the (.
1318 if (Lex.getKind() == lltok::rparen) {
1320 } else if (Lex.getKind() == lltok::dotdotdot) {
1324 LocTy TypeLoc = Lex.getLoc();
1325 PATypeHolder ArgTy(Type::VoidTy);
1329 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1330 // types (such as a function returning a pointer to itself). If parsing a
1331 // function prototype, we require fully resolved types.
1332 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1333 ParseOptionalAttrs(Attrs, 0)) return true;
1335 if (ArgTy == Type::VoidTy)
1336 return Error(TypeLoc, "argument can not have void type");
1338 if (Lex.getKind() == lltok::LocalVar ||
1339 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1340 Name = Lex.getStrVal();
1344 if (!FunctionType::isValidArgumentType(ArgTy))
1345 return Error(TypeLoc, "invalid type for function argument");
1347 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1349 while (EatIfPresent(lltok::comma)) {
1350 // Handle ... at end of arg list.
1351 if (EatIfPresent(lltok::dotdotdot)) {
1356 // Otherwise must be an argument type.
1357 TypeLoc = Lex.getLoc();
1358 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1359 ParseOptionalAttrs(Attrs, 0)) return true;
1361 if (ArgTy == Type::VoidTy)
1362 return Error(TypeLoc, "argument can not have void type");
1364 if (Lex.getKind() == lltok::LocalVar ||
1365 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1366 Name = Lex.getStrVal();
1372 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1373 return Error(TypeLoc, "invalid type for function argument");
1375 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1379 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1382 /// ParseFunctionType
1383 /// ::= Type ArgumentList OptionalAttrs
1384 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1385 assert(Lex.getKind() == lltok::lparen);
1387 if (!FunctionType::isValidReturnType(Result))
1388 return TokError("invalid function return type");
1390 std::vector<ArgInfo> ArgList;
1393 if (ParseArgumentList(ArgList, isVarArg, true) ||
1394 // FIXME: Allow, but ignore attributes on function types!
1395 // FIXME: Remove in LLVM 3.0
1396 ParseOptionalAttrs(Attrs, 2))
1399 // Reject names on the arguments lists.
1400 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1401 if (!ArgList[i].Name.empty())
1402 return Error(ArgList[i].Loc, "argument name invalid in function type");
1403 if (!ArgList[i].Attrs != 0) {
1404 // Allow but ignore attributes on function types; this permits
1406 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1410 std::vector<const Type*> ArgListTy;
1411 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1412 ArgListTy.push_back(ArgList[i].Type);
1414 Result = HandleUpRefs(FunctionType::get(Result.get(),
1415 ArgListTy, isVarArg));
1419 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1422 /// ::= '{' TypeRec (',' TypeRec)* '}'
1423 /// ::= '<' '{' '}' '>'
1424 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1425 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1426 assert(Lex.getKind() == lltok::lbrace);
1427 Lex.Lex(); // Consume the '{'
1429 if (EatIfPresent(lltok::rbrace)) {
1430 Result = StructType::get(Context, Packed);
1434 std::vector<PATypeHolder> ParamsList;
1435 LocTy EltTyLoc = Lex.getLoc();
1436 if (ParseTypeRec(Result)) return true;
1437 ParamsList.push_back(Result);
1439 if (Result == Type::VoidTy)
1440 return Error(EltTyLoc, "struct element can not have void type");
1441 if (!StructType::isValidElementType(Result))
1442 return Error(EltTyLoc, "invalid element type for struct");
1444 while (EatIfPresent(lltok::comma)) {
1445 EltTyLoc = Lex.getLoc();
1446 if (ParseTypeRec(Result)) return true;
1448 if (Result == Type::VoidTy)
1449 return Error(EltTyLoc, "struct element can not have void type");
1450 if (!StructType::isValidElementType(Result))
1451 return Error(EltTyLoc, "invalid element type for struct");
1453 ParamsList.push_back(Result);
1456 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1459 std::vector<const Type*> ParamsListTy;
1460 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1461 ParamsListTy.push_back(ParamsList[i].get());
1462 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
1466 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1467 /// token has already been consumed.
1469 /// ::= '[' APSINTVAL 'x' Types ']'
1470 /// ::= '<' APSINTVAL 'x' Types '>'
1471 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1472 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1473 Lex.getAPSIntVal().getBitWidth() > 64)
1474 return TokError("expected number in address space");
1476 LocTy SizeLoc = Lex.getLoc();
1477 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1480 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1483 LocTy TypeLoc = Lex.getLoc();
1484 PATypeHolder EltTy(Type::VoidTy);
1485 if (ParseTypeRec(EltTy)) return true;
1487 if (EltTy == Type::VoidTy)
1488 return Error(TypeLoc, "array and vector element type cannot be void");
1490 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1491 "expected end of sequential type"))
1496 return Error(SizeLoc, "zero element vector is illegal");
1497 if ((unsigned)Size != Size)
1498 return Error(SizeLoc, "size too large for vector");
1499 if (!VectorType::isValidElementType(EltTy))
1500 return Error(TypeLoc, "vector element type must be fp or integer");
1501 Result = VectorType::get(EltTy, unsigned(Size));
1503 if (!ArrayType::isValidElementType(EltTy))
1504 return Error(TypeLoc, "invalid array element type");
1505 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1510 //===----------------------------------------------------------------------===//
1511 // Function Semantic Analysis.
1512 //===----------------------------------------------------------------------===//
1514 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1517 // Insert unnamed arguments into the NumberedVals list.
1518 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1521 NumberedVals.push_back(AI);
1524 LLParser::PerFunctionState::~PerFunctionState() {
1525 // If there were any forward referenced non-basicblock values, delete them.
1526 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1527 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1528 if (!isa<BasicBlock>(I->second.first)) {
1529 I->second.first->replaceAllUsesWith(
1530 UndefValue::get(I->second.first->getType()));
1531 delete I->second.first;
1532 I->second.first = 0;
1535 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1536 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1537 if (!isa<BasicBlock>(I->second.first)) {
1538 I->second.first->replaceAllUsesWith(
1539 UndefValue::get(I->second.first->getType()));
1540 delete I->second.first;
1541 I->second.first = 0;
1545 bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1546 if (!ForwardRefVals.empty())
1547 return P.Error(ForwardRefVals.begin()->second.second,
1548 "use of undefined value '%" + ForwardRefVals.begin()->first +
1550 if (!ForwardRefValIDs.empty())
1551 return P.Error(ForwardRefValIDs.begin()->second.second,
1552 "use of undefined value '%" +
1553 utostr(ForwardRefValIDs.begin()->first) + "'");
1558 /// GetVal - Get a value with the specified name or ID, creating a
1559 /// forward reference record if needed. This can return null if the value
1560 /// exists but does not have the right type.
1561 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1562 const Type *Ty, LocTy Loc) {
1563 // Look this name up in the normal function symbol table.
1564 Value *Val = F.getValueSymbolTable().lookup(Name);
1566 // If this is a forward reference for the value, see if we already created a
1567 // forward ref record.
1569 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1570 I = ForwardRefVals.find(Name);
1571 if (I != ForwardRefVals.end())
1572 Val = I->second.first;
1575 // If we have the value in the symbol table or fwd-ref table, return it.
1577 if (Val->getType() == Ty) return Val;
1578 if (Ty == Type::LabelTy)
1579 P.Error(Loc, "'%" + Name + "' is not a basic block");
1581 P.Error(Loc, "'%" + Name + "' defined with type '" +
1582 Val->getType()->getDescription() + "'");
1586 // Don't make placeholders with invalid type.
1587 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1588 P.Error(Loc, "invalid use of a non-first-class type");
1592 // Otherwise, create a new forward reference for this value and remember it.
1594 if (Ty == Type::LabelTy)
1595 FwdVal = BasicBlock::Create(Name, &F);
1597 FwdVal = new Argument(Ty, Name);
1599 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1603 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1605 // Look this name up in the normal function symbol table.
1606 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1608 // If this is a forward reference for the value, see if we already created a
1609 // forward ref record.
1611 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1612 I = ForwardRefValIDs.find(ID);
1613 if (I != ForwardRefValIDs.end())
1614 Val = I->second.first;
1617 // If we have the value in the symbol table or fwd-ref table, return it.
1619 if (Val->getType() == Ty) return Val;
1620 if (Ty == Type::LabelTy)
1621 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1623 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1624 Val->getType()->getDescription() + "'");
1628 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1629 P.Error(Loc, "invalid use of a non-first-class type");
1633 // Otherwise, create a new forward reference for this value and remember it.
1635 if (Ty == Type::LabelTy)
1636 FwdVal = BasicBlock::Create("", &F);
1638 FwdVal = new Argument(Ty);
1640 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1644 /// SetInstName - After an instruction is parsed and inserted into its
1645 /// basic block, this installs its name.
1646 bool LLParser::PerFunctionState::SetInstName(int NameID,
1647 const std::string &NameStr,
1648 LocTy NameLoc, Instruction *Inst) {
1649 // If this instruction has void type, it cannot have a name or ID specified.
1650 if (Inst->getType() == Type::VoidTy) {
1651 if (NameID != -1 || !NameStr.empty())
1652 return P.Error(NameLoc, "instructions returning void cannot have a name");
1656 // If this was a numbered instruction, verify that the instruction is the
1657 // expected value and resolve any forward references.
1658 if (NameStr.empty()) {
1659 // If neither a name nor an ID was specified, just use the next ID.
1661 NameID = NumberedVals.size();
1663 if (unsigned(NameID) != NumberedVals.size())
1664 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1665 utostr(NumberedVals.size()) + "'");
1667 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1668 ForwardRefValIDs.find(NameID);
1669 if (FI != ForwardRefValIDs.end()) {
1670 if (FI->second.first->getType() != Inst->getType())
1671 return P.Error(NameLoc, "instruction forward referenced with type '" +
1672 FI->second.first->getType()->getDescription() + "'");
1673 FI->second.first->replaceAllUsesWith(Inst);
1674 ForwardRefValIDs.erase(FI);
1677 NumberedVals.push_back(Inst);
1681 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1682 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1683 FI = ForwardRefVals.find(NameStr);
1684 if (FI != ForwardRefVals.end()) {
1685 if (FI->second.first->getType() != Inst->getType())
1686 return P.Error(NameLoc, "instruction forward referenced with type '" +
1687 FI->second.first->getType()->getDescription() + "'");
1688 FI->second.first->replaceAllUsesWith(Inst);
1689 ForwardRefVals.erase(FI);
1692 // Set the name on the instruction.
1693 Inst->setName(NameStr);
1695 if (Inst->getNameStr() != NameStr)
1696 return P.Error(NameLoc, "multiple definition of local value named '" +
1701 /// GetBB - Get a basic block with the specified name or ID, creating a
1702 /// forward reference record if needed.
1703 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1705 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1708 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1709 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1712 /// DefineBB - Define the specified basic block, which is either named or
1713 /// unnamed. If there is an error, this returns null otherwise it returns
1714 /// the block being defined.
1715 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1719 BB = GetBB(NumberedVals.size(), Loc);
1721 BB = GetBB(Name, Loc);
1722 if (BB == 0) return 0; // Already diagnosed error.
1724 // Move the block to the end of the function. Forward ref'd blocks are
1725 // inserted wherever they happen to be referenced.
1726 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1728 // Remove the block from forward ref sets.
1730 ForwardRefValIDs.erase(NumberedVals.size());
1731 NumberedVals.push_back(BB);
1733 // BB forward references are already in the function symbol table.
1734 ForwardRefVals.erase(Name);
1740 //===----------------------------------------------------------------------===//
1742 //===----------------------------------------------------------------------===//
1744 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1745 /// type implied. For example, if we parse "4" we don't know what integer type
1746 /// it has. The value will later be combined with its type and checked for
1748 bool LLParser::ParseValID(ValID &ID) {
1749 ID.Loc = Lex.getLoc();
1750 switch (Lex.getKind()) {
1751 default: return TokError("expected value token");
1752 case lltok::GlobalID: // @42
1753 ID.UIntVal = Lex.getUIntVal();
1754 ID.Kind = ValID::t_GlobalID;
1756 case lltok::GlobalVar: // @foo
1757 ID.StrVal = Lex.getStrVal();
1758 ID.Kind = ValID::t_GlobalName;
1760 case lltok::LocalVarID: // %42
1761 ID.UIntVal = Lex.getUIntVal();
1762 ID.Kind = ValID::t_LocalID;
1764 case lltok::LocalVar: // %foo
1765 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1766 ID.StrVal = Lex.getStrVal();
1767 ID.Kind = ValID::t_LocalName;
1769 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
1770 ID.Kind = ValID::t_Metadata;
1772 if (Lex.getKind() == lltok::lbrace) {
1773 SmallVector<Value*, 16> Elts;
1774 if (ParseMDNodeVector(Elts) ||
1775 ParseToken(lltok::rbrace, "expected end of metadata node"))
1778 ID.MetadataVal = MDNode::get(Context, Elts.data(), Elts.size());
1782 // Standalone metadata reference
1783 // !{ ..., !42, ... }
1784 if (!ParseMDNode(ID.MetadataVal))
1788 // ::= '!' STRINGCONSTANT
1789 if (ParseMDString(ID.MetadataVal)) return true;
1790 ID.Kind = ValID::t_Metadata;
1794 ID.APSIntVal = Lex.getAPSIntVal();
1795 ID.Kind = ValID::t_APSInt;
1797 case lltok::APFloat:
1798 ID.APFloatVal = Lex.getAPFloatVal();
1799 ID.Kind = ValID::t_APFloat;
1801 case lltok::kw_true:
1802 ID.ConstantVal = ConstantInt::getTrue(Context);
1803 ID.Kind = ValID::t_Constant;
1805 case lltok::kw_false:
1806 ID.ConstantVal = ConstantInt::getFalse(Context);
1807 ID.Kind = ValID::t_Constant;
1809 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1810 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1811 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1813 case lltok::lbrace: {
1814 // ValID ::= '{' ConstVector '}'
1816 SmallVector<Constant*, 16> Elts;
1817 if (ParseGlobalValueVector(Elts) ||
1818 ParseToken(lltok::rbrace, "expected end of struct constant"))
1821 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
1822 Elts.size(), false);
1823 ID.Kind = ValID::t_Constant;
1827 // ValID ::= '<' ConstVector '>' --> Vector.
1828 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1830 bool isPackedStruct = EatIfPresent(lltok::lbrace);
1832 SmallVector<Constant*, 16> Elts;
1833 LocTy FirstEltLoc = Lex.getLoc();
1834 if (ParseGlobalValueVector(Elts) ||
1836 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1837 ParseToken(lltok::greater, "expected end of constant"))
1840 if (isPackedStruct) {
1842 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
1843 ID.Kind = ValID::t_Constant;
1848 return Error(ID.Loc, "constant vector must not be empty");
1850 if (!Elts[0]->getType()->isInteger() &&
1851 !Elts[0]->getType()->isFloatingPoint())
1852 return Error(FirstEltLoc,
1853 "vector elements must have integer or floating point type");
1855 // Verify that all the vector elements have the same type.
1856 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1857 if (Elts[i]->getType() != Elts[0]->getType())
1858 return Error(FirstEltLoc,
1859 "vector element #" + utostr(i) +
1860 " is not of type '" + Elts[0]->getType()->getDescription());
1862 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
1863 ID.Kind = ValID::t_Constant;
1866 case lltok::lsquare: { // Array Constant
1868 SmallVector<Constant*, 16> Elts;
1869 LocTy FirstEltLoc = Lex.getLoc();
1870 if (ParseGlobalValueVector(Elts) ||
1871 ParseToken(lltok::rsquare, "expected end of array constant"))
1874 // Handle empty element.
1876 // Use undef instead of an array because it's inconvenient to determine
1877 // the element type at this point, there being no elements to examine.
1878 ID.Kind = ValID::t_EmptyArray;
1882 if (!Elts[0]->getType()->isFirstClassType())
1883 return Error(FirstEltLoc, "invalid array element type: " +
1884 Elts[0]->getType()->getDescription());
1886 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
1888 // Verify all elements are correct type!
1889 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
1890 if (Elts[i]->getType() != Elts[0]->getType())
1891 return Error(FirstEltLoc,
1892 "array element #" + utostr(i) +
1893 " is not of type '" +Elts[0]->getType()->getDescription());
1896 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
1897 ID.Kind = ValID::t_Constant;
1900 case lltok::kw_c: // c "foo"
1902 ID.ConstantVal = ConstantArray::get(Lex.getStrVal(), false);
1903 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1904 ID.Kind = ValID::t_Constant;
1907 case lltok::kw_asm: {
1908 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1911 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
1912 ParseStringConstant(ID.StrVal) ||
1913 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
1914 ParseToken(lltok::StringConstant, "expected constraint string"))
1916 ID.StrVal2 = Lex.getStrVal();
1917 ID.UIntVal = HasSideEffect;
1918 ID.Kind = ValID::t_InlineAsm;
1922 case lltok::kw_trunc:
1923 case lltok::kw_zext:
1924 case lltok::kw_sext:
1925 case lltok::kw_fptrunc:
1926 case lltok::kw_fpext:
1927 case lltok::kw_bitcast:
1928 case lltok::kw_uitofp:
1929 case lltok::kw_sitofp:
1930 case lltok::kw_fptoui:
1931 case lltok::kw_fptosi:
1932 case lltok::kw_inttoptr:
1933 case lltok::kw_ptrtoint: {
1934 unsigned Opc = Lex.getUIntVal();
1935 PATypeHolder DestTy(Type::VoidTy);
1938 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1939 ParseGlobalTypeAndValue(SrcVal) ||
1940 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
1941 ParseType(DestTy) ||
1942 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1944 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1945 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1946 SrcVal->getType()->getDescription() + "' to '" +
1947 DestTy->getDescription() + "'");
1948 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
1950 ID.Kind = ValID::t_Constant;
1953 case lltok::kw_extractvalue: {
1956 SmallVector<unsigned, 4> Indices;
1957 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1958 ParseGlobalTypeAndValue(Val) ||
1959 ParseIndexList(Indices) ||
1960 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1962 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1963 return Error(ID.Loc, "extractvalue operand must be array or struct");
1964 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1966 return Error(ID.Loc, "invalid indices for extractvalue");
1968 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
1969 ID.Kind = ValID::t_Constant;
1972 case lltok::kw_insertvalue: {
1974 Constant *Val0, *Val1;
1975 SmallVector<unsigned, 4> Indices;
1976 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1977 ParseGlobalTypeAndValue(Val0) ||
1978 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1979 ParseGlobalTypeAndValue(Val1) ||
1980 ParseIndexList(Indices) ||
1981 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1983 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1984 return Error(ID.Loc, "extractvalue operand must be array or struct");
1985 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1987 return Error(ID.Loc, "invalid indices for insertvalue");
1988 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
1989 Indices.data(), Indices.size());
1990 ID.Kind = ValID::t_Constant;
1993 case lltok::kw_icmp:
1994 case lltok::kw_fcmp: {
1995 unsigned PredVal, Opc = Lex.getUIntVal();
1996 Constant *Val0, *Val1;
1998 if (ParseCmpPredicate(PredVal, Opc) ||
1999 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2000 ParseGlobalTypeAndValue(Val0) ||
2001 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2002 ParseGlobalTypeAndValue(Val1) ||
2003 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2006 if (Val0->getType() != Val1->getType())
2007 return Error(ID.Loc, "compare operands must have the same type");
2009 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2011 if (Opc == Instruction::FCmp) {
2012 if (!Val0->getType()->isFPOrFPVector())
2013 return Error(ID.Loc, "fcmp requires floating point operands");
2014 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2016 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2017 if (!Val0->getType()->isIntOrIntVector() &&
2018 !isa<PointerType>(Val0->getType()))
2019 return Error(ID.Loc, "icmp requires pointer or integer operands");
2020 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2022 ID.Kind = ValID::t_Constant;
2026 // Binary Operators.
2028 case lltok::kw_fadd:
2030 case lltok::kw_fsub:
2032 case lltok::kw_fmul:
2033 case lltok::kw_udiv:
2034 case lltok::kw_sdiv:
2035 case lltok::kw_fdiv:
2036 case lltok::kw_urem:
2037 case lltok::kw_srem:
2038 case lltok::kw_frem: {
2042 unsigned Opc = Lex.getUIntVal();
2043 Constant *Val0, *Val1;
2045 LocTy ModifierLoc = Lex.getLoc();
2046 if (Opc == Instruction::Add ||
2047 Opc == Instruction::Sub ||
2048 Opc == Instruction::Mul) {
2049 if (EatIfPresent(lltok::kw_nuw))
2051 if (EatIfPresent(lltok::kw_nsw)) {
2053 if (EatIfPresent(lltok::kw_nuw))
2056 } else if (Opc == Instruction::SDiv) {
2057 if (EatIfPresent(lltok::kw_exact))
2060 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2061 ParseGlobalTypeAndValue(Val0) ||
2062 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2063 ParseGlobalTypeAndValue(Val1) ||
2064 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2066 if (Val0->getType() != Val1->getType())
2067 return Error(ID.Loc, "operands of constexpr must have same type");
2068 if (!Val0->getType()->isIntOrIntVector()) {
2070 return Error(ModifierLoc, "nuw only applies to integer operations");
2072 return Error(ModifierLoc, "nsw only applies to integer operations");
2074 // API compatibility: Accept either integer or floating-point types with
2075 // add, sub, and mul.
2076 if (!Val0->getType()->isIntOrIntVector() &&
2077 !Val0->getType()->isFPOrFPVector())
2078 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
2079 Constant *C = ConstantExpr::get(Opc, Val0, Val1);
2081 cast<OverflowingBinaryOperator>(C)->setHasNoUnsignedOverflow(true);
2083 cast<OverflowingBinaryOperator>(C)->setHasNoSignedOverflow(true);
2085 cast<SDivOperator>(C)->setIsExact(true);
2087 ID.Kind = ValID::t_Constant;
2091 // Logical Operations
2093 case lltok::kw_lshr:
2094 case lltok::kw_ashr:
2097 case lltok::kw_xor: {
2098 unsigned Opc = Lex.getUIntVal();
2099 Constant *Val0, *Val1;
2101 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2102 ParseGlobalTypeAndValue(Val0) ||
2103 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2104 ParseGlobalTypeAndValue(Val1) ||
2105 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2107 if (Val0->getType() != Val1->getType())
2108 return Error(ID.Loc, "operands of constexpr must have same type");
2109 if (!Val0->getType()->isIntOrIntVector())
2110 return Error(ID.Loc,
2111 "constexpr requires integer or integer vector operands");
2112 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2113 ID.Kind = ValID::t_Constant;
2117 case lltok::kw_getelementptr:
2118 case lltok::kw_shufflevector:
2119 case lltok::kw_insertelement:
2120 case lltok::kw_extractelement:
2121 case lltok::kw_select: {
2122 unsigned Opc = Lex.getUIntVal();
2123 SmallVector<Constant*, 16> Elts;
2124 bool InBounds = false;
2126 if (Opc == Instruction::GetElementPtr)
2127 InBounds = EatIfPresent(lltok::kw_inbounds);
2128 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2129 ParseGlobalValueVector(Elts) ||
2130 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2133 if (Opc == Instruction::GetElementPtr) {
2134 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
2135 return Error(ID.Loc, "getelementptr requires pointer operand");
2137 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
2138 (Value**)(Elts.data() + 1),
2140 return Error(ID.Loc, "invalid indices for getelementptr");
2141 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0],
2142 Elts.data() + 1, Elts.size() - 1);
2144 cast<GEPOperator>(ID.ConstantVal)->setIsInBounds(true);
2145 } else if (Opc == Instruction::Select) {
2146 if (Elts.size() != 3)
2147 return Error(ID.Loc, "expected three operands to select");
2148 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2150 return Error(ID.Loc, Reason);
2151 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2152 } else if (Opc == Instruction::ShuffleVector) {
2153 if (Elts.size() != 3)
2154 return Error(ID.Loc, "expected three operands to shufflevector");
2155 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2156 return Error(ID.Loc, "invalid operands to shufflevector");
2158 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2159 } else if (Opc == Instruction::ExtractElement) {
2160 if (Elts.size() != 2)
2161 return Error(ID.Loc, "expected two operands to extractelement");
2162 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2163 return Error(ID.Loc, "invalid extractelement operands");
2164 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2166 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2167 if (Elts.size() != 3)
2168 return Error(ID.Loc, "expected three operands to insertelement");
2169 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2170 return Error(ID.Loc, "invalid insertelement operands");
2172 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2175 ID.Kind = ValID::t_Constant;
2184 /// ParseGlobalValue - Parse a global value with the specified type.
2185 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2188 return ParseValID(ID) ||
2189 ConvertGlobalValIDToValue(Ty, ID, V);
2192 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2194 bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2196 if (isa<FunctionType>(Ty))
2197 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2200 default: llvm_unreachable("Unknown ValID!");
2201 case ValID::t_Metadata:
2202 return Error(ID.Loc, "invalid use of metadata");
2203 case ValID::t_LocalID:
2204 case ValID::t_LocalName:
2205 return Error(ID.Loc, "invalid use of function-local name");
2206 case ValID::t_InlineAsm:
2207 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2208 case ValID::t_GlobalName:
2209 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2211 case ValID::t_GlobalID:
2212 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2214 case ValID::t_APSInt:
2215 if (!isa<IntegerType>(Ty))
2216 return Error(ID.Loc, "integer constant must have integer type");
2217 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2218 V = ConstantInt::get(Context, ID.APSIntVal);
2220 case ValID::t_APFloat:
2221 if (!Ty->isFloatingPoint() ||
2222 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2223 return Error(ID.Loc, "floating point constant invalid for type");
2225 // The lexer has no type info, so builds all float and double FP constants
2226 // as double. Fix this here. Long double does not need this.
2227 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2228 Ty == Type::FloatTy) {
2230 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2233 V = ConstantFP::get(Context, ID.APFloatVal);
2235 if (V->getType() != Ty)
2236 return Error(ID.Loc, "floating point constant does not have type '" +
2237 Ty->getDescription() + "'");
2241 if (!isa<PointerType>(Ty))
2242 return Error(ID.Loc, "null must be a pointer type");
2243 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2245 case ValID::t_Undef:
2246 // FIXME: LabelTy should not be a first-class type.
2247 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
2248 !isa<OpaqueType>(Ty))
2249 return Error(ID.Loc, "invalid type for undef constant");
2250 V = UndefValue::get(Ty);
2252 case ValID::t_EmptyArray:
2253 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2254 return Error(ID.Loc, "invalid empty array initializer");
2255 V = UndefValue::get(Ty);
2258 // FIXME: LabelTy should not be a first-class type.
2259 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
2260 return Error(ID.Loc, "invalid type for null constant");
2261 V = Constant::getNullValue(Ty);
2263 case ValID::t_Constant:
2264 if (ID.ConstantVal->getType() != Ty)
2265 return Error(ID.Loc, "constant expression type mismatch");
2271 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2272 PATypeHolder Type(Type::VoidTy);
2273 return ParseType(Type) ||
2274 ParseGlobalValue(Type, V);
2277 /// ParseGlobalValueVector
2279 /// ::= TypeAndValue (',' TypeAndValue)*
2280 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2282 if (Lex.getKind() == lltok::rbrace ||
2283 Lex.getKind() == lltok::rsquare ||
2284 Lex.getKind() == lltok::greater ||
2285 Lex.getKind() == lltok::rparen)
2289 if (ParseGlobalTypeAndValue(C)) return true;
2292 while (EatIfPresent(lltok::comma)) {
2293 if (ParseGlobalTypeAndValue(C)) return true;
2301 //===----------------------------------------------------------------------===//
2302 // Function Parsing.
2303 //===----------------------------------------------------------------------===//
2305 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2306 PerFunctionState &PFS) {
2307 if (ID.Kind == ValID::t_LocalID)
2308 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2309 else if (ID.Kind == ValID::t_LocalName)
2310 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
2311 else if (ID.Kind == ValID::t_InlineAsm) {
2312 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2313 const FunctionType *FTy =
2314 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2315 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2316 return Error(ID.Loc, "invalid type for inline asm constraint string");
2317 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2319 } else if (ID.Kind == ValID::t_Metadata) {
2323 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2331 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2334 return ParseValID(ID) ||
2335 ConvertValIDToValue(Ty, ID, V, PFS);
2338 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2339 PATypeHolder T(Type::VoidTy);
2340 return ParseType(T) ||
2341 ParseValue(T, V, PFS);
2345 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2346 /// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2347 /// OptionalAlign OptGC
2348 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2349 // Parse the linkage.
2350 LocTy LinkageLoc = Lex.getLoc();
2353 unsigned Visibility, CC, RetAttrs;
2354 PATypeHolder RetType(Type::VoidTy);
2355 LocTy RetTypeLoc = Lex.getLoc();
2356 if (ParseOptionalLinkage(Linkage) ||
2357 ParseOptionalVisibility(Visibility) ||
2358 ParseOptionalCallingConv(CC) ||
2359 ParseOptionalAttrs(RetAttrs, 1) ||
2360 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2363 // Verify that the linkage is ok.
2364 switch ((GlobalValue::LinkageTypes)Linkage) {
2365 case GlobalValue::ExternalLinkage:
2366 break; // always ok.
2367 case GlobalValue::DLLImportLinkage:
2368 case GlobalValue::ExternalWeakLinkage:
2370 return Error(LinkageLoc, "invalid linkage for function definition");
2372 case GlobalValue::PrivateLinkage:
2373 case GlobalValue::LinkerPrivateLinkage:
2374 case GlobalValue::InternalLinkage:
2375 case GlobalValue::AvailableExternallyLinkage:
2376 case GlobalValue::LinkOnceAnyLinkage:
2377 case GlobalValue::LinkOnceODRLinkage:
2378 case GlobalValue::WeakAnyLinkage:
2379 case GlobalValue::WeakODRLinkage:
2380 case GlobalValue::DLLExportLinkage:
2382 return Error(LinkageLoc, "invalid linkage for function declaration");
2384 case GlobalValue::AppendingLinkage:
2385 case GlobalValue::GhostLinkage:
2386 case GlobalValue::CommonLinkage:
2387 return Error(LinkageLoc, "invalid function linkage type");
2390 if (!FunctionType::isValidReturnType(RetType) ||
2391 isa<OpaqueType>(RetType))
2392 return Error(RetTypeLoc, "invalid function return type");
2394 LocTy NameLoc = Lex.getLoc();
2396 std::string FunctionName;
2397 if (Lex.getKind() == lltok::GlobalVar) {
2398 FunctionName = Lex.getStrVal();
2399 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2400 unsigned NameID = Lex.getUIntVal();
2402 if (NameID != NumberedVals.size())
2403 return TokError("function expected to be numbered '%" +
2404 utostr(NumberedVals.size()) + "'");
2406 return TokError("expected function name");
2411 if (Lex.getKind() != lltok::lparen)
2412 return TokError("expected '(' in function argument list");
2414 std::vector<ArgInfo> ArgList;
2417 std::string Section;
2421 if (ParseArgumentList(ArgList, isVarArg, false) ||
2422 ParseOptionalAttrs(FuncAttrs, 2) ||
2423 (EatIfPresent(lltok::kw_section) &&
2424 ParseStringConstant(Section)) ||
2425 ParseOptionalAlignment(Alignment) ||
2426 (EatIfPresent(lltok::kw_gc) &&
2427 ParseStringConstant(GC)))
2430 // If the alignment was parsed as an attribute, move to the alignment field.
2431 if (FuncAttrs & Attribute::Alignment) {
2432 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2433 FuncAttrs &= ~Attribute::Alignment;
2436 // Okay, if we got here, the function is syntactically valid. Convert types
2437 // and do semantic checks.
2438 std::vector<const Type*> ParamTypeList;
2439 SmallVector<AttributeWithIndex, 8> Attrs;
2440 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2442 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2443 if (FuncAttrs & ObsoleteFuncAttrs) {
2444 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2445 FuncAttrs &= ~ObsoleteFuncAttrs;
2448 if (RetAttrs != Attribute::None)
2449 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2451 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2452 ParamTypeList.push_back(ArgList[i].Type);
2453 if (ArgList[i].Attrs != Attribute::None)
2454 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2457 if (FuncAttrs != Attribute::None)
2458 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2460 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2462 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2463 RetType != Type::VoidTy)
2464 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2466 const FunctionType *FT =
2467 FunctionType::get(RetType, ParamTypeList, isVarArg);
2468 const PointerType *PFT = PointerType::getUnqual(FT);
2471 if (!FunctionName.empty()) {
2472 // If this was a definition of a forward reference, remove the definition
2473 // from the forward reference table and fill in the forward ref.
2474 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2475 ForwardRefVals.find(FunctionName);
2476 if (FRVI != ForwardRefVals.end()) {
2477 Fn = M->getFunction(FunctionName);
2478 ForwardRefVals.erase(FRVI);
2479 } else if ((Fn = M->getFunction(FunctionName))) {
2480 // If this function already exists in the symbol table, then it is
2481 // multiply defined. We accept a few cases for old backwards compat.
2482 // FIXME: Remove this stuff for LLVM 3.0.
2483 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2484 (!Fn->isDeclaration() && isDefine)) {
2485 // If the redefinition has different type or different attributes,
2486 // reject it. If both have bodies, reject it.
2487 return Error(NameLoc, "invalid redefinition of function '" +
2488 FunctionName + "'");
2489 } else if (Fn->isDeclaration()) {
2490 // Make sure to strip off any argument names so we can't get conflicts.
2491 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2497 } else if (FunctionName.empty()) {
2498 // If this is a definition of a forward referenced function, make sure the
2500 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2501 = ForwardRefValIDs.find(NumberedVals.size());
2502 if (I != ForwardRefValIDs.end()) {
2503 Fn = cast<Function>(I->second.first);
2504 if (Fn->getType() != PFT)
2505 return Error(NameLoc, "type of definition and forward reference of '@" +
2506 utostr(NumberedVals.size()) +"' disagree");
2507 ForwardRefValIDs.erase(I);
2512 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2513 else // Move the forward-reference to the correct spot in the module.
2514 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2516 if (FunctionName.empty())
2517 NumberedVals.push_back(Fn);
2519 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2520 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2521 Fn->setCallingConv(CC);
2522 Fn->setAttributes(PAL);
2523 Fn->setAlignment(Alignment);
2524 Fn->setSection(Section);
2525 if (!GC.empty()) Fn->setGC(GC.c_str());
2527 // Add all of the arguments we parsed to the function.
2528 Function::arg_iterator ArgIt = Fn->arg_begin();
2529 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2530 // If the argument has a name, insert it into the argument symbol table.
2531 if (ArgList[i].Name.empty()) continue;
2533 // Set the name, if it conflicted, it will be auto-renamed.
2534 ArgIt->setName(ArgList[i].Name);
2536 if (ArgIt->getNameStr() != ArgList[i].Name)
2537 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2538 ArgList[i].Name + "'");
2545 /// ParseFunctionBody
2546 /// ::= '{' BasicBlock+ '}'
2547 /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2549 bool LLParser::ParseFunctionBody(Function &Fn) {
2550 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2551 return TokError("expected '{' in function body");
2552 Lex.Lex(); // eat the {.
2554 PerFunctionState PFS(*this, Fn);
2556 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2557 if (ParseBasicBlock(PFS)) return true;
2562 // Verify function is ok.
2563 return PFS.VerifyFunctionComplete();
2567 /// ::= LabelStr? Instruction*
2568 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2569 // If this basic block starts out with a name, remember it.
2571 LocTy NameLoc = Lex.getLoc();
2572 if (Lex.getKind() == lltok::LabelStr) {
2573 Name = Lex.getStrVal();
2577 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2578 if (BB == 0) return true;
2580 std::string NameStr;
2582 // Parse the instructions in this block until we get a terminator.
2585 // This instruction may have three possibilities for a name: a) none
2586 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2587 LocTy NameLoc = Lex.getLoc();
2591 if (Lex.getKind() == lltok::LocalVarID) {
2592 NameID = Lex.getUIntVal();
2594 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2596 } else if (Lex.getKind() == lltok::LocalVar ||
2597 // FIXME: REMOVE IN LLVM 3.0
2598 Lex.getKind() == lltok::StringConstant) {
2599 NameStr = Lex.getStrVal();
2601 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2605 if (ParseInstruction(Inst, BB, PFS)) return true;
2607 BB->getInstList().push_back(Inst);
2609 // Set the name on the instruction.
2610 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2611 } while (!isa<TerminatorInst>(Inst));
2616 //===----------------------------------------------------------------------===//
2617 // Instruction Parsing.
2618 //===----------------------------------------------------------------------===//
2620 /// ParseInstruction - Parse one of the many different instructions.
2622 bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2623 PerFunctionState &PFS) {
2624 lltok::Kind Token = Lex.getKind();
2625 if (Token == lltok::Eof)
2626 return TokError("found end of file when expecting more instructions");
2627 LocTy Loc = Lex.getLoc();
2628 unsigned KeywordVal = Lex.getUIntVal();
2629 Lex.Lex(); // Eat the keyword.
2632 default: return Error(Loc, "expected instruction opcode");
2633 // Terminator Instructions.
2634 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2635 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2636 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2637 case lltok::kw_br: return ParseBr(Inst, PFS);
2638 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2639 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2640 // Binary Operators.
2643 case lltok::kw_mul: {
2646 LocTy ModifierLoc = Lex.getLoc();
2647 if (EatIfPresent(lltok::kw_nuw))
2649 if (EatIfPresent(lltok::kw_nsw)) {
2651 if (EatIfPresent(lltok::kw_nuw))
2654 // API compatibility: Accept either integer or floating-point types.
2655 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
2657 if (!Inst->getType()->isIntOrIntVector()) {
2659 return Error(ModifierLoc, "nuw only applies to integer operations");
2661 return Error(ModifierLoc, "nsw only applies to integer operations");
2664 cast<OverflowingBinaryOperator>(Inst)->setHasNoUnsignedOverflow(true);
2666 cast<OverflowingBinaryOperator>(Inst)->setHasNoSignedOverflow(true);
2670 case lltok::kw_fadd:
2671 case lltok::kw_fsub:
2672 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2674 case lltok::kw_sdiv: {
2676 if (EatIfPresent(lltok::kw_exact))
2678 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2681 cast<SDivOperator>(Inst)->setIsExact(true);
2685 case lltok::kw_udiv:
2686 case lltok::kw_urem:
2687 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2688 case lltok::kw_fdiv:
2689 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2691 case lltok::kw_lshr:
2692 case lltok::kw_ashr:
2695 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
2696 case lltok::kw_icmp:
2697 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
2699 case lltok::kw_trunc:
2700 case lltok::kw_zext:
2701 case lltok::kw_sext:
2702 case lltok::kw_fptrunc:
2703 case lltok::kw_fpext:
2704 case lltok::kw_bitcast:
2705 case lltok::kw_uitofp:
2706 case lltok::kw_sitofp:
2707 case lltok::kw_fptoui:
2708 case lltok::kw_fptosi:
2709 case lltok::kw_inttoptr:
2710 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
2712 case lltok::kw_select: return ParseSelect(Inst, PFS);
2713 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
2714 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2715 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2716 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2717 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2718 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2719 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2721 case lltok::kw_alloca:
2722 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
2723 case lltok::kw_free: return ParseFree(Inst, PFS);
2724 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2725 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2726 case lltok::kw_volatile:
2727 if (EatIfPresent(lltok::kw_load))
2728 return ParseLoad(Inst, PFS, true);
2729 else if (EatIfPresent(lltok::kw_store))
2730 return ParseStore(Inst, PFS, true);
2732 return TokError("expected 'load' or 'store'");
2733 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2734 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2735 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2736 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2740 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2741 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2742 if (Opc == Instruction::FCmp) {
2743 switch (Lex.getKind()) {
2744 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2745 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2746 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2747 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2748 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2749 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2750 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2751 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2752 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2753 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2754 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2755 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2756 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2757 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2758 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2759 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2760 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2763 switch (Lex.getKind()) {
2764 default: TokError("expected icmp predicate (e.g. 'eq')");
2765 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2766 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2767 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2768 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2769 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2770 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2771 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2772 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2773 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2774 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2781 //===----------------------------------------------------------------------===//
2782 // Terminator Instructions.
2783 //===----------------------------------------------------------------------===//
2785 /// ParseRet - Parse a return instruction.
2787 /// ::= 'ret' TypeAndValue
2788 /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2789 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2790 PerFunctionState &PFS) {
2791 PATypeHolder Ty(Type::VoidTy);
2792 if (ParseType(Ty, true /*void allowed*/)) return true;
2794 if (Ty == Type::VoidTy) {
2795 Inst = ReturnInst::Create();
2800 if (ParseValue(Ty, RV, PFS)) return true;
2802 // The normal case is one return value.
2803 if (Lex.getKind() == lltok::comma) {
2804 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2805 // of 'ret {i32,i32} {i32 1, i32 2}'
2806 SmallVector<Value*, 8> RVs;
2809 while (EatIfPresent(lltok::comma)) {
2810 if (ParseTypeAndValue(RV, PFS)) return true;
2814 RV = UndefValue::get(PFS.getFunction().getReturnType());
2815 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2816 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2817 BB->getInstList().push_back(I);
2821 Inst = ReturnInst::Create(RV);
2827 /// ::= 'br' TypeAndValue
2828 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2829 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2831 Value *Op0, *Op1, *Op2;
2832 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2834 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2835 Inst = BranchInst::Create(BB);
2839 if (Op0->getType() != Type::Int1Ty)
2840 return Error(Loc, "branch condition must have 'i1' type");
2842 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2843 ParseTypeAndValue(Op1, Loc, PFS) ||
2844 ParseToken(lltok::comma, "expected ',' after true destination") ||
2845 ParseTypeAndValue(Op2, Loc2, PFS))
2848 if (!isa<BasicBlock>(Op1))
2849 return Error(Loc, "true destination of branch must be a basic block");
2850 if (!isa<BasicBlock>(Op2))
2851 return Error(Loc2, "true destination of branch must be a basic block");
2853 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2859 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2861 /// ::= (TypeAndValue ',' TypeAndValue)*
2862 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2863 LocTy CondLoc, BBLoc;
2864 Value *Cond, *DefaultBB;
2865 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2866 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2867 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2868 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2871 if (!isa<IntegerType>(Cond->getType()))
2872 return Error(CondLoc, "switch condition must have integer type");
2873 if (!isa<BasicBlock>(DefaultBB))
2874 return Error(BBLoc, "default destination must be a basic block");
2876 // Parse the jump table pairs.
2877 SmallPtrSet<Value*, 32> SeenCases;
2878 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2879 while (Lex.getKind() != lltok::rsquare) {
2880 Value *Constant, *DestBB;
2882 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2883 ParseToken(lltok::comma, "expected ',' after case value") ||
2884 ParseTypeAndValue(DestBB, BBLoc, PFS))
2887 if (!SeenCases.insert(Constant))
2888 return Error(CondLoc, "duplicate case value in switch");
2889 if (!isa<ConstantInt>(Constant))
2890 return Error(CondLoc, "case value is not a constant integer");
2891 if (!isa<BasicBlock>(DestBB))
2892 return Error(BBLoc, "case destination is not a basic block");
2894 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2895 cast<BasicBlock>(DestBB)));
2898 Lex.Lex(); // Eat the ']'.
2900 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2902 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2903 SI->addCase(Table[i].first, Table[i].second);
2909 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2910 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2911 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2912 LocTy CallLoc = Lex.getLoc();
2913 unsigned CC, RetAttrs, FnAttrs;
2914 PATypeHolder RetType(Type::VoidTy);
2917 SmallVector<ParamInfo, 16> ArgList;
2919 Value *NormalBB, *UnwindBB;
2920 if (ParseOptionalCallingConv(CC) ||
2921 ParseOptionalAttrs(RetAttrs, 1) ||
2922 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
2923 ParseValID(CalleeID) ||
2924 ParseParameterList(ArgList, PFS) ||
2925 ParseOptionalAttrs(FnAttrs, 2) ||
2926 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2927 ParseTypeAndValue(NormalBB, PFS) ||
2928 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2929 ParseTypeAndValue(UnwindBB, PFS))
2932 if (!isa<BasicBlock>(NormalBB))
2933 return Error(CallLoc, "normal destination is not a basic block");
2934 if (!isa<BasicBlock>(UnwindBB))
2935 return Error(CallLoc, "unwind destination is not a basic block");
2937 // If RetType is a non-function pointer type, then this is the short syntax
2938 // for the call, which means that RetType is just the return type. Infer the
2939 // rest of the function argument types from the arguments that are present.
2940 const PointerType *PFTy = 0;
2941 const FunctionType *Ty = 0;
2942 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2943 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2944 // Pull out the types of all of the arguments...
2945 std::vector<const Type*> ParamTypes;
2946 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2947 ParamTypes.push_back(ArgList[i].V->getType());
2949 if (!FunctionType::isValidReturnType(RetType))
2950 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2952 Ty = FunctionType::get(RetType, ParamTypes, false);
2953 PFTy = PointerType::getUnqual(Ty);
2956 // Look up the callee.
2958 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2960 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2961 // function attributes.
2962 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2963 if (FnAttrs & ObsoleteFuncAttrs) {
2964 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2965 FnAttrs &= ~ObsoleteFuncAttrs;
2968 // Set up the Attributes for the function.
2969 SmallVector<AttributeWithIndex, 8> Attrs;
2970 if (RetAttrs != Attribute::None)
2971 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2973 SmallVector<Value*, 8> Args;
2975 // Loop through FunctionType's arguments and ensure they are specified
2976 // correctly. Also, gather any parameter attributes.
2977 FunctionType::param_iterator I = Ty->param_begin();
2978 FunctionType::param_iterator E = Ty->param_end();
2979 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2980 const Type *ExpectedTy = 0;
2983 } else if (!Ty->isVarArg()) {
2984 return Error(ArgList[i].Loc, "too many arguments specified");
2987 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2988 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2989 ExpectedTy->getDescription() + "'");
2990 Args.push_back(ArgList[i].V);
2991 if (ArgList[i].Attrs != Attribute::None)
2992 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2996 return Error(CallLoc, "not enough parameters specified for call");
2998 if (FnAttrs != Attribute::None)
2999 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3001 // Finish off the Attributes and check them
3002 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3004 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
3005 cast<BasicBlock>(UnwindBB),
3006 Args.begin(), Args.end());
3007 II->setCallingConv(CC);
3008 II->setAttributes(PAL);
3015 //===----------------------------------------------------------------------===//
3016 // Binary Operators.
3017 //===----------------------------------------------------------------------===//
3020 /// ::= ArithmeticOps TypeAndValue ',' Value
3022 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3023 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3024 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3025 unsigned Opc, unsigned OperandType) {
3026 LocTy Loc; Value *LHS, *RHS;
3027 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3028 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3029 ParseValue(LHS->getType(), RHS, PFS))
3033 switch (OperandType) {
3034 default: llvm_unreachable("Unknown operand type!");
3035 case 0: // int or FP.
3036 Valid = LHS->getType()->isIntOrIntVector() ||
3037 LHS->getType()->isFPOrFPVector();
3039 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
3040 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
3044 return Error(Loc, "invalid operand type for instruction");
3046 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3051 /// ::= ArithmeticOps TypeAndValue ',' Value {
3052 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3054 LocTy Loc; Value *LHS, *RHS;
3055 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3056 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3057 ParseValue(LHS->getType(), RHS, PFS))
3060 if (!LHS->getType()->isIntOrIntVector())
3061 return Error(Loc,"instruction requires integer or integer vector operands");
3063 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3069 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3070 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3071 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3073 // Parse the integer/fp comparison predicate.
3077 if (ParseCmpPredicate(Pred, Opc) ||
3078 ParseTypeAndValue(LHS, Loc, PFS) ||
3079 ParseToken(lltok::comma, "expected ',' after compare value") ||
3080 ParseValue(LHS->getType(), RHS, PFS))
3083 if (Opc == Instruction::FCmp) {
3084 if (!LHS->getType()->isFPOrFPVector())
3085 return Error(Loc, "fcmp requires floating point operands");
3086 Inst = new FCmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
3088 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3089 if (!LHS->getType()->isIntOrIntVector() &&
3090 !isa<PointerType>(LHS->getType()))
3091 return Error(Loc, "icmp requires integer operands");
3092 Inst = new ICmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
3097 //===----------------------------------------------------------------------===//
3098 // Other Instructions.
3099 //===----------------------------------------------------------------------===//
3103 /// ::= CastOpc TypeAndValue 'to' Type
3104 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3106 LocTy Loc; Value *Op;
3107 PATypeHolder DestTy(Type::VoidTy);
3108 if (ParseTypeAndValue(Op, Loc, PFS) ||
3109 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3113 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3114 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3115 return Error(Loc, "invalid cast opcode for cast from '" +
3116 Op->getType()->getDescription() + "' to '" +
3117 DestTy->getDescription() + "'");
3119 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3124 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3125 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3127 Value *Op0, *Op1, *Op2;
3128 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3129 ParseToken(lltok::comma, "expected ',' after select condition") ||
3130 ParseTypeAndValue(Op1, PFS) ||
3131 ParseToken(lltok::comma, "expected ',' after select value") ||
3132 ParseTypeAndValue(Op2, PFS))
3135 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3136 return Error(Loc, Reason);
3138 Inst = SelectInst::Create(Op0, Op1, Op2);
3143 /// ::= 'va_arg' TypeAndValue ',' Type
3144 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3146 PATypeHolder EltTy(Type::VoidTy);
3148 if (ParseTypeAndValue(Op, PFS) ||
3149 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3150 ParseType(EltTy, TypeLoc))
3153 if (!EltTy->isFirstClassType())
3154 return Error(TypeLoc, "va_arg requires operand with first class type");
3156 Inst = new VAArgInst(Op, EltTy);
3160 /// ParseExtractElement
3161 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3162 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3165 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3166 ParseToken(lltok::comma, "expected ',' after extract value") ||
3167 ParseTypeAndValue(Op1, PFS))
3170 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3171 return Error(Loc, "invalid extractelement operands");
3173 Inst = ExtractElementInst::Create(Op0, Op1);
3177 /// ParseInsertElement
3178 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3179 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3181 Value *Op0, *Op1, *Op2;
3182 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3183 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3184 ParseTypeAndValue(Op1, PFS) ||
3185 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3186 ParseTypeAndValue(Op2, PFS))
3189 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3190 return Error(Loc, "invalid insertelement operands");
3192 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3196 /// ParseShuffleVector
3197 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3198 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3200 Value *Op0, *Op1, *Op2;
3201 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3202 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3203 ParseTypeAndValue(Op1, PFS) ||
3204 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3205 ParseTypeAndValue(Op2, PFS))
3208 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3209 return Error(Loc, "invalid extractelement operands");
3211 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3216 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
3217 bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3218 PATypeHolder Ty(Type::VoidTy);
3220 LocTy TypeLoc = Lex.getLoc();
3222 if (ParseType(Ty) ||
3223 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3224 ParseValue(Ty, Op0, PFS) ||
3225 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3226 ParseValue(Type::LabelTy, Op1, PFS) ||
3227 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3230 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3232 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3234 if (!EatIfPresent(lltok::comma))
3237 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3238 ParseValue(Ty, Op0, PFS) ||
3239 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3240 ParseValue(Type::LabelTy, Op1, PFS) ||
3241 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3245 if (!Ty->isFirstClassType())
3246 return Error(TypeLoc, "phi node must have first class type");
3248 PHINode *PN = PHINode::Create(Ty);
3249 PN->reserveOperandSpace(PHIVals.size());
3250 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3251 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3257 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3258 /// ParameterList OptionalAttrs
3259 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3261 unsigned CC, RetAttrs, FnAttrs;
3262 PATypeHolder RetType(Type::VoidTy);
3265 SmallVector<ParamInfo, 16> ArgList;
3266 LocTy CallLoc = Lex.getLoc();
3268 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3269 ParseOptionalCallingConv(CC) ||
3270 ParseOptionalAttrs(RetAttrs, 1) ||
3271 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3272 ParseValID(CalleeID) ||
3273 ParseParameterList(ArgList, PFS) ||
3274 ParseOptionalAttrs(FnAttrs, 2))
3277 // If RetType is a non-function pointer type, then this is the short syntax
3278 // for the call, which means that RetType is just the return type. Infer the
3279 // rest of the function argument types from the arguments that are present.
3280 const PointerType *PFTy = 0;
3281 const FunctionType *Ty = 0;
3282 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3283 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3284 // Pull out the types of all of the arguments...
3285 std::vector<const Type*> ParamTypes;
3286 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3287 ParamTypes.push_back(ArgList[i].V->getType());
3289 if (!FunctionType::isValidReturnType(RetType))
3290 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3292 Ty = FunctionType::get(RetType, ParamTypes, false);
3293 PFTy = PointerType::getUnqual(Ty);
3296 // Look up the callee.
3298 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3300 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3301 // function attributes.
3302 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3303 if (FnAttrs & ObsoleteFuncAttrs) {
3304 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3305 FnAttrs &= ~ObsoleteFuncAttrs;
3308 // Set up the Attributes for the function.
3309 SmallVector<AttributeWithIndex, 8> Attrs;
3310 if (RetAttrs != Attribute::None)
3311 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3313 SmallVector<Value*, 8> Args;
3315 // Loop through FunctionType's arguments and ensure they are specified
3316 // correctly. Also, gather any parameter attributes.
3317 FunctionType::param_iterator I = Ty->param_begin();
3318 FunctionType::param_iterator E = Ty->param_end();
3319 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3320 const Type *ExpectedTy = 0;
3323 } else if (!Ty->isVarArg()) {
3324 return Error(ArgList[i].Loc, "too many arguments specified");
3327 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3328 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3329 ExpectedTy->getDescription() + "'");
3330 Args.push_back(ArgList[i].V);
3331 if (ArgList[i].Attrs != Attribute::None)
3332 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3336 return Error(CallLoc, "not enough parameters specified for call");
3338 if (FnAttrs != Attribute::None)
3339 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3341 // Finish off the Attributes and check them
3342 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3344 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3345 CI->setTailCall(isTail);
3346 CI->setCallingConv(CC);
3347 CI->setAttributes(PAL);
3352 //===----------------------------------------------------------------------===//
3353 // Memory Instructions.
3354 //===----------------------------------------------------------------------===//
3357 /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3358 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3359 bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3361 PATypeHolder Ty(Type::VoidTy);
3364 unsigned Alignment = 0;
3365 if (ParseType(Ty)) return true;
3367 if (EatIfPresent(lltok::comma)) {
3368 if (Lex.getKind() == lltok::kw_align) {
3369 if (ParseOptionalAlignment(Alignment)) return true;
3370 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3371 ParseOptionalCommaAlignment(Alignment)) {
3376 if (Size && Size->getType() != Type::Int32Ty)
3377 return Error(SizeLoc, "element count must be i32");
3379 if (Opc == Instruction::Malloc)
3380 Inst = new MallocInst(Ty, Size, Alignment);
3382 Inst = new AllocaInst(Ty, Size, Alignment);
3387 /// ::= 'free' TypeAndValue
3388 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3389 Value *Val; LocTy Loc;
3390 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3391 if (!isa<PointerType>(Val->getType()))
3392 return Error(Loc, "operand to free must be a pointer");
3393 Inst = new FreeInst(Val);
3398 /// ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
3399 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3401 Value *Val; LocTy Loc;
3403 if (ParseTypeAndValue(Val, Loc, PFS) ||
3404 ParseOptionalCommaAlignment(Alignment))
3407 if (!isa<PointerType>(Val->getType()) ||
3408 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3409 return Error(Loc, "load operand must be a pointer to a first class type");
3411 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3416 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3417 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3419 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3421 if (ParseTypeAndValue(Val, Loc, PFS) ||
3422 ParseToken(lltok::comma, "expected ',' after store operand") ||
3423 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3424 ParseOptionalCommaAlignment(Alignment))
3427 if (!isa<PointerType>(Ptr->getType()))
3428 return Error(PtrLoc, "store operand must be a pointer");
3429 if (!Val->getType()->isFirstClassType())
3430 return Error(Loc, "store operand must be a first class value");
3431 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3432 return Error(Loc, "stored value and pointer type do not match");
3434 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3439 /// ::= 'getresult' TypeAndValue ',' i32
3440 /// FIXME: Remove support for getresult in LLVM 3.0
3441 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3442 Value *Val; LocTy ValLoc, EltLoc;
3444 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3445 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3446 ParseUInt32(Element, EltLoc))
3449 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3450 return Error(ValLoc, "getresult inst requires an aggregate operand");
3451 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3452 return Error(EltLoc, "invalid getresult index for value");
3453 Inst = ExtractValueInst::Create(Val, Element);
3457 /// ParseGetElementPtr
3458 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
3459 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3460 Value *Ptr, *Val; LocTy Loc, EltLoc;
3462 bool InBounds = EatIfPresent(lltok::kw_inbounds);
3464 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3466 if (!isa<PointerType>(Ptr->getType()))
3467 return Error(Loc, "base of getelementptr must be a pointer");
3469 SmallVector<Value*, 16> Indices;
3470 while (EatIfPresent(lltok::comma)) {
3471 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3472 if (!isa<IntegerType>(Val->getType()))
3473 return Error(EltLoc, "getelementptr index must be an integer");
3474 Indices.push_back(Val);
3477 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3478 Indices.begin(), Indices.end()))
3479 return Error(Loc, "invalid getelementptr indices");
3480 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3482 cast<GEPOperator>(Inst)->setIsInBounds(true);
3486 /// ParseExtractValue
3487 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3488 bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3489 Value *Val; LocTy Loc;
3490 SmallVector<unsigned, 4> Indices;
3491 if (ParseTypeAndValue(Val, Loc, PFS) ||
3492 ParseIndexList(Indices))
3495 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3496 return Error(Loc, "extractvalue operand must be array or struct");
3498 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3500 return Error(Loc, "invalid indices for extractvalue");
3501 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3505 /// ParseInsertValue
3506 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3507 bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3508 Value *Val0, *Val1; LocTy Loc0, Loc1;
3509 SmallVector<unsigned, 4> Indices;
3510 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3511 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3512 ParseTypeAndValue(Val1, Loc1, PFS) ||
3513 ParseIndexList(Indices))
3516 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3517 return Error(Loc0, "extractvalue operand must be array or struct");
3519 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3521 return Error(Loc0, "invalid indices for insertvalue");
3522 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3526 //===----------------------------------------------------------------------===//
3527 // Embedded metadata.
3528 //===----------------------------------------------------------------------===//
3530 /// ParseMDNodeVector
3531 /// ::= Element (',' Element)*
3533 /// ::= 'null' | TypeAndValue
3534 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
3535 assert(Lex.getKind() == lltok::lbrace);
3539 if (Lex.getKind() == lltok::kw_null) {
3543 PATypeHolder Ty(Type::VoidTy);
3544 if (ParseType(Ty)) return true;
3545 if (Lex.getKind() == lltok::Metadata) {
3547 MetadataBase *Node = 0;
3548 if (!ParseMDNode(Node))
3551 MetadataBase *MDS = 0;
3552 if (ParseMDString(MDS)) return true;
3557 if (ParseGlobalValue(Ty, C)) return true;
3562 } while (EatIfPresent(lltok::comma));