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/MDNode.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.
50 std::string StrVal, StrVal2;
53 Constant *ConstantVal;
54 ValID() : APFloatVal(0.0) {}
58 /// Run: module ::= toplevelentity*
59 bool LLParser::Run() {
63 return ParseTopLevelEntities() ||
64 ValidateEndOfModule();
67 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
69 bool LLParser::ValidateEndOfModule() {
70 if (!ForwardRefTypes.empty())
71 return Error(ForwardRefTypes.begin()->second.second,
72 "use of undefined type named '" +
73 ForwardRefTypes.begin()->first + "'");
74 if (!ForwardRefTypeIDs.empty())
75 return Error(ForwardRefTypeIDs.begin()->second.second,
76 "use of undefined type '%" +
77 utostr(ForwardRefTypeIDs.begin()->first) + "'");
79 if (!ForwardRefVals.empty())
80 return Error(ForwardRefVals.begin()->second.second,
81 "use of undefined value '@" + ForwardRefVals.begin()->first +
84 if (!ForwardRefValIDs.empty())
85 return Error(ForwardRefValIDs.begin()->second.second,
86 "use of undefined value '@" +
87 utostr(ForwardRefValIDs.begin()->first) + "'");
89 if (!ForwardRefMDNodes.empty())
90 return Error(ForwardRefMDNodes.begin()->second.second,
91 "use of undefined metadata '!" +
92 utostr(ForwardRefMDNodes.begin()->first) + "'");
95 // Look for intrinsic functions and CallInst that need to be upgraded
96 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
97 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
102 //===----------------------------------------------------------------------===//
103 // Top-Level Entities
104 //===----------------------------------------------------------------------===//
106 bool LLParser::ParseTopLevelEntities() {
108 switch (Lex.getKind()) {
109 default: return TokError("expected top-level entity");
110 case lltok::Eof: return false;
111 //case lltok::kw_define:
112 case lltok::kw_declare: if (ParseDeclare()) return true; break;
113 case lltok::kw_define: if (ParseDefine()) return true; break;
114 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
115 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
116 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
117 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
118 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
119 case lltok::LocalVar: if (ParseNamedType()) return true; break;
120 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
121 case lltok::Metadata: if (ParseStandaloneMetadata()) return true; break;
123 // The Global variable production with no name can have many different
124 // optional leading prefixes, the production is:
125 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
126 // OptionalAddrSpace ('constant'|'global') ...
127 case lltok::kw_private : // OptionalLinkage
128 case lltok::kw_linker_private: // OptionalLinkage
129 case lltok::kw_internal: // OptionalLinkage
130 case lltok::kw_weak: // OptionalLinkage
131 case lltok::kw_weak_odr: // OptionalLinkage
132 case lltok::kw_linkonce: // OptionalLinkage
133 case lltok::kw_linkonce_odr: // OptionalLinkage
134 case lltok::kw_appending: // OptionalLinkage
135 case lltok::kw_dllexport: // OptionalLinkage
136 case lltok::kw_common: // OptionalLinkage
137 case lltok::kw_dllimport: // OptionalLinkage
138 case lltok::kw_extern_weak: // OptionalLinkage
139 case lltok::kw_external: { // OptionalLinkage
140 unsigned Linkage, Visibility;
141 if (ParseOptionalLinkage(Linkage) ||
142 ParseOptionalVisibility(Visibility) ||
143 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
147 case lltok::kw_default: // OptionalVisibility
148 case lltok::kw_hidden: // OptionalVisibility
149 case lltok::kw_protected: { // OptionalVisibility
151 if (ParseOptionalVisibility(Visibility) ||
152 ParseGlobal("", SMLoc(), 0, false, Visibility))
157 case lltok::kw_thread_local: // OptionalThreadLocal
158 case lltok::kw_addrspace: // OptionalAddrSpace
159 case lltok::kw_constant: // GlobalType
160 case lltok::kw_global: // GlobalType
161 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
169 /// ::= 'module' 'asm' STRINGCONSTANT
170 bool LLParser::ParseModuleAsm() {
171 assert(Lex.getKind() == lltok::kw_module);
175 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
176 ParseStringConstant(AsmStr)) return true;
178 const std::string &AsmSoFar = M->getModuleInlineAsm();
179 if (AsmSoFar.empty())
180 M->setModuleInlineAsm(AsmStr);
182 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
187 /// ::= 'target' 'triple' '=' STRINGCONSTANT
188 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
189 bool LLParser::ParseTargetDefinition() {
190 assert(Lex.getKind() == lltok::kw_target);
193 default: return TokError("unknown target property");
194 case lltok::kw_triple:
196 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
197 ParseStringConstant(Str))
199 M->setTargetTriple(Str);
201 case lltok::kw_datalayout:
203 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
204 ParseStringConstant(Str))
206 M->setDataLayout(Str);
212 /// ::= 'deplibs' '=' '[' ']'
213 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
214 bool LLParser::ParseDepLibs() {
215 assert(Lex.getKind() == lltok::kw_deplibs);
217 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
218 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
221 if (EatIfPresent(lltok::rsquare))
225 if (ParseStringConstant(Str)) return true;
228 while (EatIfPresent(lltok::comma)) {
229 if (ParseStringConstant(Str)) return true;
233 return ParseToken(lltok::rsquare, "expected ']' at end of list");
238 bool LLParser::ParseUnnamedType() {
239 assert(Lex.getKind() == lltok::kw_type);
240 LocTy TypeLoc = Lex.getLoc();
241 Lex.Lex(); // eat kw_type
243 PATypeHolder Ty(Type::VoidTy);
244 if (ParseType(Ty)) return true;
246 unsigned TypeID = NumberedTypes.size();
248 // See if this type was previously referenced.
249 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
250 FI = ForwardRefTypeIDs.find(TypeID);
251 if (FI != ForwardRefTypeIDs.end()) {
252 if (FI->second.first.get() == Ty)
253 return Error(TypeLoc, "self referential type is invalid");
255 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
256 Ty = FI->second.first.get();
257 ForwardRefTypeIDs.erase(FI);
260 NumberedTypes.push_back(Ty);
266 /// ::= LocalVar '=' 'type' type
267 bool LLParser::ParseNamedType() {
268 std::string Name = Lex.getStrVal();
269 LocTy NameLoc = Lex.getLoc();
270 Lex.Lex(); // eat LocalVar.
272 PATypeHolder Ty(Type::VoidTy);
274 if (ParseToken(lltok::equal, "expected '=' after name") ||
275 ParseToken(lltok::kw_type, "expected 'type' after name") ||
279 // Set the type name, checking for conflicts as we do so.
280 bool AlreadyExists = M->addTypeName(Name, Ty);
281 if (!AlreadyExists) return false;
283 // See if this type is a forward reference. We need to eagerly resolve
284 // types to allow recursive type redefinitions below.
285 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
286 FI = ForwardRefTypes.find(Name);
287 if (FI != ForwardRefTypes.end()) {
288 if (FI->second.first.get() == Ty)
289 return Error(NameLoc, "self referential type is invalid");
291 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
292 Ty = FI->second.first.get();
293 ForwardRefTypes.erase(FI);
296 // Inserting a name that is already defined, get the existing name.
297 const Type *Existing = M->getTypeByName(Name);
298 assert(Existing && "Conflict but no matching type?!");
300 // Otherwise, this is an attempt to redefine a type. That's okay if
301 // the redefinition is identical to the original.
302 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
303 if (Existing == Ty) return false;
305 // Any other kind of (non-equivalent) redefinition is an error.
306 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
307 Ty->getDescription() + "'");
312 /// ::= 'declare' FunctionHeader
313 bool LLParser::ParseDeclare() {
314 assert(Lex.getKind() == lltok::kw_declare);
318 return ParseFunctionHeader(F, false);
322 /// ::= 'define' FunctionHeader '{' ...
323 bool LLParser::ParseDefine() {
324 assert(Lex.getKind() == lltok::kw_define);
328 return ParseFunctionHeader(F, true) ||
329 ParseFunctionBody(*F);
335 bool LLParser::ParseGlobalType(bool &IsConstant) {
336 if (Lex.getKind() == lltok::kw_constant)
338 else if (Lex.getKind() == lltok::kw_global)
342 return TokError("expected 'global' or 'constant'");
348 /// ParseNamedGlobal:
349 /// GlobalVar '=' OptionalVisibility ALIAS ...
350 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
351 bool LLParser::ParseNamedGlobal() {
352 assert(Lex.getKind() == lltok::GlobalVar);
353 LocTy NameLoc = Lex.getLoc();
354 std::string Name = Lex.getStrVal();
358 unsigned Linkage, Visibility;
359 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
360 ParseOptionalLinkage(Linkage, HasLinkage) ||
361 ParseOptionalVisibility(Visibility))
364 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
365 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
366 return ParseAlias(Name, NameLoc, Visibility);
370 // ::= '!' STRINGCONSTANT
371 bool LLParser::ParseMDString(Constant *&MDS) {
373 if (ParseStringConstant(Str)) return true;
374 MDS = Context.getMDString(Str.data(), Str.data() + Str.size());
379 // ::= '!' MDNodeNumber
380 bool LLParser::ParseMDNode(Constant *&Node) {
381 // !{ ..., !42, ... }
383 if (ParseUInt32(MID)) return true;
385 // Check existing MDNode.
386 std::map<unsigned, Constant *>::iterator I = MetadataCache.find(MID);
387 if (I != MetadataCache.end()) {
392 // Check known forward references.
393 std::map<unsigned, std::pair<Constant *, LocTy> >::iterator
394 FI = ForwardRefMDNodes.find(MID);
395 if (FI != ForwardRefMDNodes.end()) {
396 Node = FI->second.first;
400 // Create MDNode forward reference
401 SmallVector<Value *, 1> Elts;
402 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
403 Elts.push_back(Context.getMDString(FwdRefName));
404 MDNode *FwdNode = Context.getMDNode(Elts.data(), Elts.size());
405 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
410 /// ParseStandaloneMetadata:
412 bool LLParser::ParseStandaloneMetadata() {
413 assert(Lex.getKind() == lltok::Metadata);
415 unsigned MetadataID = 0;
416 if (ParseUInt32(MetadataID))
418 if (MetadataCache.find(MetadataID) != MetadataCache.end())
419 return TokError("Metadata id is already used");
420 if (ParseToken(lltok::equal, "expected '=' here"))
424 PATypeHolder Ty(Type::VoidTy);
425 if (ParseType(Ty, TyLoc))
429 if (ParseGlobalValue(Ty, Init))
432 MetadataCache[MetadataID] = Init;
433 std::map<unsigned, std::pair<Constant *, LocTy> >::iterator
434 FI = ForwardRefMDNodes.find(MetadataID);
435 if (FI != ForwardRefMDNodes.end()) {
436 Constant *FwdNode = FI->second.first;
437 FwdNode->replaceAllUsesWith(Init);
438 ForwardRefMDNodes.erase(FI);
445 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
448 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
449 /// ::= 'getelementptr' '(' ... ')'
451 /// Everything through visibility has already been parsed.
453 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
454 unsigned Visibility) {
455 assert(Lex.getKind() == lltok::kw_alias);
458 LocTy LinkageLoc = Lex.getLoc();
459 if (ParseOptionalLinkage(Linkage))
462 if (Linkage != GlobalValue::ExternalLinkage &&
463 Linkage != GlobalValue::WeakAnyLinkage &&
464 Linkage != GlobalValue::WeakODRLinkage &&
465 Linkage != GlobalValue::InternalLinkage &&
466 Linkage != GlobalValue::PrivateLinkage &&
467 Linkage != GlobalValue::LinkerPrivateLinkage)
468 return Error(LinkageLoc, "invalid linkage type for alias");
471 LocTy AliaseeLoc = Lex.getLoc();
472 if (Lex.getKind() != lltok::kw_bitcast &&
473 Lex.getKind() != lltok::kw_getelementptr) {
474 if (ParseGlobalTypeAndValue(Aliasee)) return true;
476 // The bitcast dest type is not present, it is implied by the dest type.
478 if (ParseValID(ID)) return true;
479 if (ID.Kind != ValID::t_Constant)
480 return Error(AliaseeLoc, "invalid aliasee");
481 Aliasee = ID.ConstantVal;
484 if (!isa<PointerType>(Aliasee->getType()))
485 return Error(AliaseeLoc, "alias must have pointer type");
487 // Okay, create the alias but do not insert it into the module yet.
488 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
489 (GlobalValue::LinkageTypes)Linkage, Name,
491 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
493 // See if this value already exists in the symbol table. If so, it is either
494 // a redefinition or a definition of a forward reference.
495 if (GlobalValue *Val =
496 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
497 // See if this was a redefinition. If so, there is no entry in
499 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
500 I = ForwardRefVals.find(Name);
501 if (I == ForwardRefVals.end())
502 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
504 // Otherwise, this was a definition of forward ref. Verify that types
506 if (Val->getType() != GA->getType())
507 return Error(NameLoc,
508 "forward reference and definition of alias have different types");
510 // If they agree, just RAUW the old value with the alias and remove the
512 Val->replaceAllUsesWith(GA);
513 Val->eraseFromParent();
514 ForwardRefVals.erase(I);
517 // Insert into the module, we know its name won't collide now.
518 M->getAliasList().push_back(GA);
519 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
525 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
526 /// OptionalAddrSpace GlobalType Type Const
527 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
528 /// OptionalAddrSpace GlobalType Type Const
530 /// Everything through visibility has been parsed already.
532 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
533 unsigned Linkage, bool HasLinkage,
534 unsigned Visibility) {
536 bool ThreadLocal, IsConstant;
539 PATypeHolder Ty(Type::VoidTy);
540 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
541 ParseOptionalAddrSpace(AddrSpace) ||
542 ParseGlobalType(IsConstant) ||
543 ParseType(Ty, TyLoc))
546 // If the linkage is specified and is external, then no initializer is
549 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
550 Linkage != GlobalValue::ExternalWeakLinkage &&
551 Linkage != GlobalValue::ExternalLinkage)) {
552 if (ParseGlobalValue(Ty, Init))
556 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
557 return Error(TyLoc, "invalid type for global variable");
559 GlobalVariable *GV = 0;
561 // See if the global was forward referenced, if so, use the global.
563 if ((GV = M->getGlobalVariable(Name, true)) &&
564 !ForwardRefVals.erase(Name))
565 return Error(NameLoc, "redefinition of global '@" + Name + "'");
567 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
568 I = ForwardRefValIDs.find(NumberedVals.size());
569 if (I != ForwardRefValIDs.end()) {
570 GV = cast<GlobalVariable>(I->second.first);
571 ForwardRefValIDs.erase(I);
576 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
577 Name, 0, false, AddrSpace);
579 if (GV->getType()->getElementType() != Ty)
581 "forward reference and definition of global have different types");
583 // Move the forward-reference to the correct spot in the module.
584 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
588 NumberedVals.push_back(GV);
590 // Set the parsed properties on the global.
592 GV->setInitializer(Init);
593 GV->setConstant(IsConstant);
594 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
595 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
596 GV->setThreadLocal(ThreadLocal);
598 // Parse attributes on the global.
599 while (Lex.getKind() == lltok::comma) {
602 if (Lex.getKind() == lltok::kw_section) {
604 GV->setSection(Lex.getStrVal());
605 if (ParseToken(lltok::StringConstant, "expected global section string"))
607 } else if (Lex.getKind() == lltok::kw_align) {
609 if (ParseOptionalAlignment(Alignment)) return true;
610 GV->setAlignment(Alignment);
612 TokError("unknown global variable property!");
620 //===----------------------------------------------------------------------===//
621 // GlobalValue Reference/Resolution Routines.
622 //===----------------------------------------------------------------------===//
624 /// GetGlobalVal - Get a value with the specified name or ID, creating a
625 /// forward reference record if needed. This can return null if the value
626 /// exists but does not have the right type.
627 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
629 const PointerType *PTy = dyn_cast<PointerType>(Ty);
631 Error(Loc, "global variable reference must have pointer type");
635 // Look this name up in the normal function symbol table.
637 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
639 // If this is a forward reference for the value, see if we already created a
640 // forward ref record.
642 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
643 I = ForwardRefVals.find(Name);
644 if (I != ForwardRefVals.end())
645 Val = I->second.first;
648 // If we have the value in the symbol table or fwd-ref table, return it.
650 if (Val->getType() == Ty) return Val;
651 Error(Loc, "'@" + Name + "' defined with type '" +
652 Val->getType()->getDescription() + "'");
656 // Otherwise, create a new forward reference for this value and remember it.
658 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
659 // Function types can return opaque but functions can't.
660 if (isa<OpaqueType>(FT->getReturnType())) {
661 Error(Loc, "function may not return opaque type");
665 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
667 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
668 GlobalValue::ExternalWeakLinkage, 0, Name);
671 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
675 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
676 const PointerType *PTy = dyn_cast<PointerType>(Ty);
678 Error(Loc, "global variable reference must have pointer type");
682 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
684 // If this is a forward reference for the value, see if we already created a
685 // forward ref record.
687 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
688 I = ForwardRefValIDs.find(ID);
689 if (I != ForwardRefValIDs.end())
690 Val = I->second.first;
693 // If we have the value in the symbol table or fwd-ref table, return it.
695 if (Val->getType() == Ty) return Val;
696 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
697 Val->getType()->getDescription() + "'");
701 // Otherwise, create a new forward reference for this value and remember it.
703 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
704 // Function types can return opaque but functions can't.
705 if (isa<OpaqueType>(FT->getReturnType())) {
706 Error(Loc, "function may not return opaque type");
709 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
711 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
712 GlobalValue::ExternalWeakLinkage, 0, "");
715 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
720 //===----------------------------------------------------------------------===//
722 //===----------------------------------------------------------------------===//
724 /// ParseToken - If the current token has the specified kind, eat it and return
725 /// success. Otherwise, emit the specified error and return failure.
726 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
727 if (Lex.getKind() != T)
728 return TokError(ErrMsg);
733 /// ParseStringConstant
734 /// ::= StringConstant
735 bool LLParser::ParseStringConstant(std::string &Result) {
736 if (Lex.getKind() != lltok::StringConstant)
737 return TokError("expected string constant");
738 Result = Lex.getStrVal();
745 bool LLParser::ParseUInt32(unsigned &Val) {
746 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
747 return TokError("expected integer");
748 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
749 if (Val64 != unsigned(Val64))
750 return TokError("expected 32-bit integer (too large)");
757 /// ParseOptionalAddrSpace
759 /// := 'addrspace' '(' uint32 ')'
760 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
762 if (!EatIfPresent(lltok::kw_addrspace))
764 return ParseToken(lltok::lparen, "expected '(' in address space") ||
765 ParseUInt32(AddrSpace) ||
766 ParseToken(lltok::rparen, "expected ')' in address space");
769 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
770 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
771 /// 2: function attr.
772 /// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
773 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
774 Attrs = Attribute::None;
775 LocTy AttrLoc = Lex.getLoc();
778 switch (Lex.getKind()) {
781 // Treat these as signext/zeroext if they occur in the argument list after
782 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
783 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
785 // FIXME: REMOVE THIS IN LLVM 3.0
787 if (Lex.getKind() == lltok::kw_sext)
788 Attrs |= Attribute::SExt;
790 Attrs |= Attribute::ZExt;
794 default: // End of attributes.
795 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
796 return Error(AttrLoc, "invalid use of function-only attribute");
798 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
799 return Error(AttrLoc, "invalid use of parameter-only attribute");
802 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
803 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
804 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
805 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
806 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
807 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
808 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
809 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
811 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
812 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
813 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
814 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
815 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
816 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
817 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
818 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
819 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
820 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
821 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
822 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
824 case lltok::kw_align: {
826 if (ParseOptionalAlignment(Alignment))
828 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
836 /// ParseOptionalLinkage
839 /// ::= 'linker_private'
844 /// ::= 'linkonce_odr'
849 /// ::= 'extern_weak'
851 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
853 switch (Lex.getKind()) {
854 default: Res=GlobalValue::ExternalLinkage; return false;
855 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
856 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
857 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
858 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
859 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
860 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
861 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
862 case lltok::kw_available_externally:
863 Res = GlobalValue::AvailableExternallyLinkage;
865 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
866 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
867 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
868 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
869 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
870 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
877 /// ParseOptionalVisibility
883 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
884 switch (Lex.getKind()) {
885 default: Res = GlobalValue::DefaultVisibility; return false;
886 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
887 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
888 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
894 /// ParseOptionalCallingConv
899 /// ::= 'x86_stdcallcc'
900 /// ::= 'x86_fastcallcc'
902 /// ::= 'arm_aapcscc'
903 /// ::= 'arm_aapcs_vfpcc'
906 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
907 switch (Lex.getKind()) {
908 default: CC = CallingConv::C; return false;
909 case lltok::kw_ccc: CC = CallingConv::C; break;
910 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
911 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
912 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
913 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
914 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
915 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
916 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
917 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
923 /// ParseOptionalAlignment
926 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
928 if (!EatIfPresent(lltok::kw_align))
930 LocTy AlignLoc = Lex.getLoc();
931 if (ParseUInt32(Alignment)) return true;
932 if (!isPowerOf2_32(Alignment))
933 return Error(AlignLoc, "alignment is not a power of two");
937 /// ParseOptionalCommaAlignment
939 /// ::= ',' 'align' 4
940 bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
942 if (!EatIfPresent(lltok::comma))
944 return ParseToken(lltok::kw_align, "expected 'align'") ||
945 ParseUInt32(Alignment);
949 /// ::= (',' uint32)+
950 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
951 if (Lex.getKind() != lltok::comma)
952 return TokError("expected ',' as start of index list");
954 while (EatIfPresent(lltok::comma)) {
956 if (ParseUInt32(Idx)) return true;
957 Indices.push_back(Idx);
963 //===----------------------------------------------------------------------===//
965 //===----------------------------------------------------------------------===//
967 /// ParseType - Parse and resolve a full type.
968 bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
969 LocTy TypeLoc = Lex.getLoc();
970 if (ParseTypeRec(Result)) return true;
972 // Verify no unresolved uprefs.
974 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
976 if (!AllowVoid && Result.get() == Type::VoidTy)
977 return Error(TypeLoc, "void type only allowed for function results");
982 /// HandleUpRefs - Every time we finish a new layer of types, this function is
983 /// called. It loops through the UpRefs vector, which is a list of the
984 /// currently active types. For each type, if the up-reference is contained in
985 /// the newly completed type, we decrement the level count. When the level
986 /// count reaches zero, the up-referenced type is the type that is passed in:
987 /// thus we can complete the cycle.
989 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
990 // If Ty isn't abstract, or if there are no up-references in it, then there is
991 // nothing to resolve here.
992 if (!ty->isAbstract() || UpRefs.empty()) return ty;
996 errs() << "Type '" << Ty->getDescription()
997 << "' newly formed. Resolving upreferences.\n"
998 << UpRefs.size() << " upreferences active!\n";
1001 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1002 // to zero), we resolve them all together before we resolve them to Ty. At
1003 // the end of the loop, if there is anything to resolve to Ty, it will be in
1005 OpaqueType *TypeToResolve = 0;
1007 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1008 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1010 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1011 UpRefs[i].LastContainedTy) != Ty->subtype_end();
1014 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1015 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1016 << (ContainsType ? "true" : "false")
1017 << " level=" << UpRefs[i].NestingLevel << "\n";
1022 // Decrement level of upreference
1023 unsigned Level = --UpRefs[i].NestingLevel;
1024 UpRefs[i].LastContainedTy = Ty;
1026 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1031 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1034 TypeToResolve = UpRefs[i].UpRefTy;
1036 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1037 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1038 --i; // Do not skip the next element.
1042 TypeToResolve->refineAbstractTypeTo(Ty);
1048 /// ParseTypeRec - The recursive function used to process the internal
1049 /// implementation details of types.
1050 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1051 switch (Lex.getKind()) {
1053 return TokError("expected type");
1055 // TypeRec ::= 'float' | 'void' (etc)
1056 Result = Lex.getTyVal();
1059 case lltok::kw_opaque:
1060 // TypeRec ::= 'opaque'
1061 Result = Context.getOpaqueType();
1065 // TypeRec ::= '{' ... '}'
1066 if (ParseStructType(Result, false))
1069 case lltok::lsquare:
1070 // TypeRec ::= '[' ... ']'
1071 Lex.Lex(); // eat the lsquare.
1072 if (ParseArrayVectorType(Result, false))
1075 case lltok::less: // Either vector or packed struct.
1076 // TypeRec ::= '<' ... '>'
1078 if (Lex.getKind() == lltok::lbrace) {
1079 if (ParseStructType(Result, true) ||
1080 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1082 } else if (ParseArrayVectorType(Result, true))
1085 case lltok::LocalVar:
1086 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1088 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1091 Result = Context.getOpaqueType();
1092 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1093 std::make_pair(Result,
1095 M->addTypeName(Lex.getStrVal(), Result.get());
1100 case lltok::LocalVarID:
1102 if (Lex.getUIntVal() < NumberedTypes.size())
1103 Result = NumberedTypes[Lex.getUIntVal()];
1105 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1106 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1107 if (I != ForwardRefTypeIDs.end())
1108 Result = I->second.first;
1110 Result = Context.getOpaqueType();
1111 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1112 std::make_pair(Result,
1118 case lltok::backslash: {
1119 // TypeRec ::= '\' 4
1122 if (ParseUInt32(Val)) return true;
1123 OpaqueType *OT = Context.getOpaqueType(); //Use temporary placeholder.
1124 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1130 // Parse the type suffixes.
1132 switch (Lex.getKind()) {
1134 default: return false;
1136 // TypeRec ::= TypeRec '*'
1138 if (Result.get() == Type::LabelTy)
1139 return TokError("basic block pointers are invalid");
1140 if (Result.get() == Type::VoidTy)
1141 return TokError("pointers to void are invalid; use i8* instead");
1142 if (!PointerType::isValidElementType(Result.get()))
1143 return TokError("pointer to this type is invalid");
1144 Result = HandleUpRefs(Context.getPointerTypeUnqual(Result.get()));
1148 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1149 case lltok::kw_addrspace: {
1150 if (Result.get() == Type::LabelTy)
1151 return TokError("basic block pointers are invalid");
1152 if (Result.get() == Type::VoidTy)
1153 return TokError("pointers to void are invalid; use i8* instead");
1154 if (!PointerType::isValidElementType(Result.get()))
1155 return TokError("pointer to this type is invalid");
1157 if (ParseOptionalAddrSpace(AddrSpace) ||
1158 ParseToken(lltok::star, "expected '*' in address space"))
1161 Result = HandleUpRefs(Context.getPointerType(Result.get(), AddrSpace));
1165 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1167 if (ParseFunctionType(Result))
1174 /// ParseParameterList
1176 /// ::= '(' Arg (',' Arg)* ')'
1178 /// ::= Type OptionalAttributes Value OptionalAttributes
1179 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1180 PerFunctionState &PFS) {
1181 if (ParseToken(lltok::lparen, "expected '(' in call"))
1184 while (Lex.getKind() != lltok::rparen) {
1185 // If this isn't the first argument, we need a comma.
1186 if (!ArgList.empty() &&
1187 ParseToken(lltok::comma, "expected ',' in argument list"))
1190 // Parse the argument.
1192 PATypeHolder ArgTy(Type::VoidTy);
1193 unsigned ArgAttrs1, ArgAttrs2;
1195 if (ParseType(ArgTy, ArgLoc) ||
1196 ParseOptionalAttrs(ArgAttrs1, 0) ||
1197 ParseValue(ArgTy, V, PFS) ||
1198 // FIXME: Should not allow attributes after the argument, remove this in
1200 ParseOptionalAttrs(ArgAttrs2, 3))
1202 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1205 Lex.Lex(); // Lex the ')'.
1211 /// ParseArgumentList - Parse the argument list for a function type or function
1212 /// prototype. If 'inType' is true then we are parsing a FunctionType.
1213 /// ::= '(' ArgTypeListI ')'
1217 /// ::= ArgTypeList ',' '...'
1218 /// ::= ArgType (',' ArgType)*
1220 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1221 bool &isVarArg, bool inType) {
1223 assert(Lex.getKind() == lltok::lparen);
1224 Lex.Lex(); // eat the (.
1226 if (Lex.getKind() == lltok::rparen) {
1228 } else if (Lex.getKind() == lltok::dotdotdot) {
1232 LocTy TypeLoc = Lex.getLoc();
1233 PATypeHolder ArgTy(Type::VoidTy);
1237 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1238 // types (such as a function returning a pointer to itself). If parsing a
1239 // function prototype, we require fully resolved types.
1240 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1241 ParseOptionalAttrs(Attrs, 0)) return true;
1243 if (ArgTy == Type::VoidTy)
1244 return Error(TypeLoc, "argument can not have void type");
1246 if (Lex.getKind() == lltok::LocalVar ||
1247 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1248 Name = Lex.getStrVal();
1252 if (!FunctionType::isValidArgumentType(ArgTy))
1253 return Error(TypeLoc, "invalid type for function argument");
1255 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1257 while (EatIfPresent(lltok::comma)) {
1258 // Handle ... at end of arg list.
1259 if (EatIfPresent(lltok::dotdotdot)) {
1264 // Otherwise must be an argument type.
1265 TypeLoc = Lex.getLoc();
1266 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1267 ParseOptionalAttrs(Attrs, 0)) return true;
1269 if (ArgTy == Type::VoidTy)
1270 return Error(TypeLoc, "argument can not have void type");
1272 if (Lex.getKind() == lltok::LocalVar ||
1273 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1274 Name = Lex.getStrVal();
1280 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1281 return Error(TypeLoc, "invalid type for function argument");
1283 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1287 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1290 /// ParseFunctionType
1291 /// ::= Type ArgumentList OptionalAttrs
1292 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1293 assert(Lex.getKind() == lltok::lparen);
1295 if (!FunctionType::isValidReturnType(Result))
1296 return TokError("invalid function return type");
1298 std::vector<ArgInfo> ArgList;
1301 if (ParseArgumentList(ArgList, isVarArg, true) ||
1302 // FIXME: Allow, but ignore attributes on function types!
1303 // FIXME: Remove in LLVM 3.0
1304 ParseOptionalAttrs(Attrs, 2))
1307 // Reject names on the arguments lists.
1308 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1309 if (!ArgList[i].Name.empty())
1310 return Error(ArgList[i].Loc, "argument name invalid in function type");
1311 if (!ArgList[i].Attrs != 0) {
1312 // Allow but ignore attributes on function types; this permits
1314 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1318 std::vector<const Type*> ArgListTy;
1319 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1320 ArgListTy.push_back(ArgList[i].Type);
1322 Result = HandleUpRefs(Context.getFunctionType(Result.get(),
1323 ArgListTy, isVarArg));
1327 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1330 /// ::= '{' TypeRec (',' TypeRec)* '}'
1331 /// ::= '<' '{' '}' '>'
1332 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1333 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1334 assert(Lex.getKind() == lltok::lbrace);
1335 Lex.Lex(); // Consume the '{'
1337 if (EatIfPresent(lltok::rbrace)) {
1338 Result = Context.getStructType(Packed);
1342 std::vector<PATypeHolder> ParamsList;
1343 LocTy EltTyLoc = Lex.getLoc();
1344 if (ParseTypeRec(Result)) return true;
1345 ParamsList.push_back(Result);
1347 if (Result == Type::VoidTy)
1348 return Error(EltTyLoc, "struct element can not have void type");
1349 if (!StructType::isValidElementType(Result))
1350 return Error(EltTyLoc, "invalid element type for struct");
1352 while (EatIfPresent(lltok::comma)) {
1353 EltTyLoc = Lex.getLoc();
1354 if (ParseTypeRec(Result)) return true;
1356 if (Result == Type::VoidTy)
1357 return Error(EltTyLoc, "struct element can not have void type");
1358 if (!StructType::isValidElementType(Result))
1359 return Error(EltTyLoc, "invalid element type for struct");
1361 ParamsList.push_back(Result);
1364 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1367 std::vector<const Type*> ParamsListTy;
1368 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1369 ParamsListTy.push_back(ParamsList[i].get());
1370 Result = HandleUpRefs(Context.getStructType(ParamsListTy, Packed));
1374 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1375 /// token has already been consumed.
1377 /// ::= '[' APSINTVAL 'x' Types ']'
1378 /// ::= '<' APSINTVAL 'x' Types '>'
1379 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1380 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1381 Lex.getAPSIntVal().getBitWidth() > 64)
1382 return TokError("expected number in address space");
1384 LocTy SizeLoc = Lex.getLoc();
1385 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1388 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1391 LocTy TypeLoc = Lex.getLoc();
1392 PATypeHolder EltTy(Type::VoidTy);
1393 if (ParseTypeRec(EltTy)) return true;
1395 if (EltTy == Type::VoidTy)
1396 return Error(TypeLoc, "array and vector element type cannot be void");
1398 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1399 "expected end of sequential type"))
1404 return Error(SizeLoc, "zero element vector is illegal");
1405 if ((unsigned)Size != Size)
1406 return Error(SizeLoc, "size too large for vector");
1407 if (!VectorType::isValidElementType(EltTy))
1408 return Error(TypeLoc, "vector element type must be fp or integer");
1409 Result = Context.getVectorType(EltTy, unsigned(Size));
1411 if (!ArrayType::isValidElementType(EltTy))
1412 return Error(TypeLoc, "invalid array element type");
1413 Result = HandleUpRefs(Context.getArrayType(EltTy, Size));
1418 //===----------------------------------------------------------------------===//
1419 // Function Semantic Analysis.
1420 //===----------------------------------------------------------------------===//
1422 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1425 // Insert unnamed arguments into the NumberedVals list.
1426 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1429 NumberedVals.push_back(AI);
1432 LLParser::PerFunctionState::~PerFunctionState() {
1433 // If there were any forward referenced non-basicblock values, delete them.
1434 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1435 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1436 if (!isa<BasicBlock>(I->second.first)) {
1437 I->second.first->replaceAllUsesWith(
1438 P.getContext().getUndef(I->second.first->getType()));
1439 delete I->second.first;
1440 I->second.first = 0;
1443 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1444 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1445 if (!isa<BasicBlock>(I->second.first)) {
1446 I->second.first->replaceAllUsesWith(
1447 P.getContext().getUndef(I->second.first->getType()));
1448 delete I->second.first;
1449 I->second.first = 0;
1453 bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1454 if (!ForwardRefVals.empty())
1455 return P.Error(ForwardRefVals.begin()->second.second,
1456 "use of undefined value '%" + ForwardRefVals.begin()->first +
1458 if (!ForwardRefValIDs.empty())
1459 return P.Error(ForwardRefValIDs.begin()->second.second,
1460 "use of undefined value '%" +
1461 utostr(ForwardRefValIDs.begin()->first) + "'");
1466 /// GetVal - Get a value with the specified name or ID, creating a
1467 /// forward reference record if needed. This can return null if the value
1468 /// exists but does not have the right type.
1469 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1470 const Type *Ty, LocTy Loc) {
1471 // Look this name up in the normal function symbol table.
1472 Value *Val = F.getValueSymbolTable().lookup(Name);
1474 // If this is a forward reference for the value, see if we already created a
1475 // forward ref record.
1477 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1478 I = ForwardRefVals.find(Name);
1479 if (I != ForwardRefVals.end())
1480 Val = I->second.first;
1483 // If we have the value in the symbol table or fwd-ref table, return it.
1485 if (Val->getType() == Ty) return Val;
1486 if (Ty == Type::LabelTy)
1487 P.Error(Loc, "'%" + Name + "' is not a basic block");
1489 P.Error(Loc, "'%" + Name + "' defined with type '" +
1490 Val->getType()->getDescription() + "'");
1494 // Don't make placeholders with invalid type.
1495 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1496 P.Error(Loc, "invalid use of a non-first-class type");
1500 // Otherwise, create a new forward reference for this value and remember it.
1502 if (Ty == Type::LabelTy)
1503 FwdVal = BasicBlock::Create(Name, &F);
1505 FwdVal = new Argument(Ty, Name);
1507 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1511 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1513 // Look this name up in the normal function symbol table.
1514 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1516 // If this is a forward reference for the value, see if we already created a
1517 // forward ref record.
1519 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1520 I = ForwardRefValIDs.find(ID);
1521 if (I != ForwardRefValIDs.end())
1522 Val = I->second.first;
1525 // If we have the value in the symbol table or fwd-ref table, return it.
1527 if (Val->getType() == Ty) return Val;
1528 if (Ty == Type::LabelTy)
1529 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1531 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1532 Val->getType()->getDescription() + "'");
1536 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1537 P.Error(Loc, "invalid use of a non-first-class type");
1541 // Otherwise, create a new forward reference for this value and remember it.
1543 if (Ty == Type::LabelTy)
1544 FwdVal = BasicBlock::Create("", &F);
1546 FwdVal = new Argument(Ty);
1548 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1552 /// SetInstName - After an instruction is parsed and inserted into its
1553 /// basic block, this installs its name.
1554 bool LLParser::PerFunctionState::SetInstName(int NameID,
1555 const std::string &NameStr,
1556 LocTy NameLoc, Instruction *Inst) {
1557 // If this instruction has void type, it cannot have a name or ID specified.
1558 if (Inst->getType() == Type::VoidTy) {
1559 if (NameID != -1 || !NameStr.empty())
1560 return P.Error(NameLoc, "instructions returning void cannot have a name");
1564 // If this was a numbered instruction, verify that the instruction is the
1565 // expected value and resolve any forward references.
1566 if (NameStr.empty()) {
1567 // If neither a name nor an ID was specified, just use the next ID.
1569 NameID = NumberedVals.size();
1571 if (unsigned(NameID) != NumberedVals.size())
1572 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1573 utostr(NumberedVals.size()) + "'");
1575 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1576 ForwardRefValIDs.find(NameID);
1577 if (FI != ForwardRefValIDs.end()) {
1578 if (FI->second.first->getType() != Inst->getType())
1579 return P.Error(NameLoc, "instruction forward referenced with type '" +
1580 FI->second.first->getType()->getDescription() + "'");
1581 FI->second.first->replaceAllUsesWith(Inst);
1582 ForwardRefValIDs.erase(FI);
1585 NumberedVals.push_back(Inst);
1589 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1590 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1591 FI = ForwardRefVals.find(NameStr);
1592 if (FI != ForwardRefVals.end()) {
1593 if (FI->second.first->getType() != Inst->getType())
1594 return P.Error(NameLoc, "instruction forward referenced with type '" +
1595 FI->second.first->getType()->getDescription() + "'");
1596 FI->second.first->replaceAllUsesWith(Inst);
1597 ForwardRefVals.erase(FI);
1600 // Set the name on the instruction.
1601 Inst->setName(NameStr);
1603 if (Inst->getNameStr() != NameStr)
1604 return P.Error(NameLoc, "multiple definition of local value named '" +
1609 /// GetBB - Get a basic block with the specified name or ID, creating a
1610 /// forward reference record if needed.
1611 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1613 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1616 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1617 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1620 /// DefineBB - Define the specified basic block, which is either named or
1621 /// unnamed. If there is an error, this returns null otherwise it returns
1622 /// the block being defined.
1623 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1627 BB = GetBB(NumberedVals.size(), Loc);
1629 BB = GetBB(Name, Loc);
1630 if (BB == 0) return 0; // Already diagnosed error.
1632 // Move the block to the end of the function. Forward ref'd blocks are
1633 // inserted wherever they happen to be referenced.
1634 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1636 // Remove the block from forward ref sets.
1638 ForwardRefValIDs.erase(NumberedVals.size());
1639 NumberedVals.push_back(BB);
1641 // BB forward references are already in the function symbol table.
1642 ForwardRefVals.erase(Name);
1648 //===----------------------------------------------------------------------===//
1650 //===----------------------------------------------------------------------===//
1652 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1653 /// type implied. For example, if we parse "4" we don't know what integer type
1654 /// it has. The value will later be combined with its type and checked for
1656 bool LLParser::ParseValID(ValID &ID) {
1657 ID.Loc = Lex.getLoc();
1658 switch (Lex.getKind()) {
1659 default: return TokError("expected value token");
1660 case lltok::GlobalID: // @42
1661 ID.UIntVal = Lex.getUIntVal();
1662 ID.Kind = ValID::t_GlobalID;
1664 case lltok::GlobalVar: // @foo
1665 ID.StrVal = Lex.getStrVal();
1666 ID.Kind = ValID::t_GlobalName;
1668 case lltok::LocalVarID: // %42
1669 ID.UIntVal = Lex.getUIntVal();
1670 ID.Kind = ValID::t_LocalID;
1672 case lltok::LocalVar: // %foo
1673 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1674 ID.StrVal = Lex.getStrVal();
1675 ID.Kind = ValID::t_LocalName;
1677 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
1678 ID.Kind = ValID::t_Constant;
1680 if (Lex.getKind() == lltok::lbrace) {
1681 SmallVector<Value*, 16> Elts;
1682 if (ParseMDNodeVector(Elts) ||
1683 ParseToken(lltok::rbrace, "expected end of metadata node"))
1686 ID.ConstantVal = Context.getMDNode(Elts.data(), Elts.size());
1690 // Standalone metadata reference
1691 // !{ ..., !42, ... }
1692 if (!ParseMDNode(ID.ConstantVal))
1696 // ::= '!' STRINGCONSTANT
1697 if (ParseMDString(ID.ConstantVal)) return true;
1701 ID.APSIntVal = Lex.getAPSIntVal();
1702 ID.Kind = ValID::t_APSInt;
1704 case lltok::APFloat:
1705 ID.APFloatVal = Lex.getAPFloatVal();
1706 ID.Kind = ValID::t_APFloat;
1708 case lltok::kw_true:
1709 ID.ConstantVal = Context.getTrue();
1710 ID.Kind = ValID::t_Constant;
1712 case lltok::kw_false:
1713 ID.ConstantVal = Context.getFalse();
1714 ID.Kind = ValID::t_Constant;
1716 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1717 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1718 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1720 case lltok::lbrace: {
1721 // ValID ::= '{' ConstVector '}'
1723 SmallVector<Constant*, 16> Elts;
1724 if (ParseGlobalValueVector(Elts) ||
1725 ParseToken(lltok::rbrace, "expected end of struct constant"))
1728 ID.ConstantVal = Context.getConstantStruct(Elts.data(), Elts.size(), false);
1729 ID.Kind = ValID::t_Constant;
1733 // ValID ::= '<' ConstVector '>' --> Vector.
1734 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1736 bool isPackedStruct = EatIfPresent(lltok::lbrace);
1738 SmallVector<Constant*, 16> Elts;
1739 LocTy FirstEltLoc = Lex.getLoc();
1740 if (ParseGlobalValueVector(Elts) ||
1742 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1743 ParseToken(lltok::greater, "expected end of constant"))
1746 if (isPackedStruct) {
1748 Context.getConstantStruct(Elts.data(), Elts.size(), true);
1749 ID.Kind = ValID::t_Constant;
1754 return Error(ID.Loc, "constant vector must not be empty");
1756 if (!Elts[0]->getType()->isInteger() &&
1757 !Elts[0]->getType()->isFloatingPoint())
1758 return Error(FirstEltLoc,
1759 "vector elements must have integer or floating point type");
1761 // Verify that all the vector elements have the same type.
1762 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1763 if (Elts[i]->getType() != Elts[0]->getType())
1764 return Error(FirstEltLoc,
1765 "vector element #" + utostr(i) +
1766 " is not of type '" + Elts[0]->getType()->getDescription());
1768 ID.ConstantVal = Context.getConstantVector(Elts.data(), Elts.size());
1769 ID.Kind = ValID::t_Constant;
1772 case lltok::lsquare: { // Array Constant
1774 SmallVector<Constant*, 16> Elts;
1775 LocTy FirstEltLoc = Lex.getLoc();
1776 if (ParseGlobalValueVector(Elts) ||
1777 ParseToken(lltok::rsquare, "expected end of array constant"))
1780 // Handle empty element.
1782 // Use undef instead of an array because it's inconvenient to determine
1783 // the element type at this point, there being no elements to examine.
1784 ID.Kind = ValID::t_EmptyArray;
1788 if (!Elts[0]->getType()->isFirstClassType())
1789 return Error(FirstEltLoc, "invalid array element type: " +
1790 Elts[0]->getType()->getDescription());
1792 ArrayType *ATy = Context.getArrayType(Elts[0]->getType(), Elts.size());
1794 // Verify all elements are correct type!
1795 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
1796 if (Elts[i]->getType() != Elts[0]->getType())
1797 return Error(FirstEltLoc,
1798 "array element #" + utostr(i) +
1799 " is not of type '" +Elts[0]->getType()->getDescription());
1802 ID.ConstantVal = Context.getConstantArray(ATy, Elts.data(), Elts.size());
1803 ID.Kind = ValID::t_Constant;
1806 case lltok::kw_c: // c "foo"
1808 ID.ConstantVal = Context.getConstantArray(Lex.getStrVal(), false);
1809 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1810 ID.Kind = ValID::t_Constant;
1813 case lltok::kw_asm: {
1814 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1817 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
1818 ParseStringConstant(ID.StrVal) ||
1819 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
1820 ParseToken(lltok::StringConstant, "expected constraint string"))
1822 ID.StrVal2 = Lex.getStrVal();
1823 ID.UIntVal = HasSideEffect;
1824 ID.Kind = ValID::t_InlineAsm;
1828 case lltok::kw_trunc:
1829 case lltok::kw_zext:
1830 case lltok::kw_sext:
1831 case lltok::kw_fptrunc:
1832 case lltok::kw_fpext:
1833 case lltok::kw_bitcast:
1834 case lltok::kw_uitofp:
1835 case lltok::kw_sitofp:
1836 case lltok::kw_fptoui:
1837 case lltok::kw_fptosi:
1838 case lltok::kw_inttoptr:
1839 case lltok::kw_ptrtoint: {
1840 unsigned Opc = Lex.getUIntVal();
1841 PATypeHolder DestTy(Type::VoidTy);
1844 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1845 ParseGlobalTypeAndValue(SrcVal) ||
1846 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
1847 ParseType(DestTy) ||
1848 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1850 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1851 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1852 SrcVal->getType()->getDescription() + "' to '" +
1853 DestTy->getDescription() + "'");
1854 ID.ConstantVal = Context.getConstantExprCast((Instruction::CastOps)Opc,
1856 ID.Kind = ValID::t_Constant;
1859 case lltok::kw_extractvalue: {
1862 SmallVector<unsigned, 4> Indices;
1863 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1864 ParseGlobalTypeAndValue(Val) ||
1865 ParseIndexList(Indices) ||
1866 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1868 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1869 return Error(ID.Loc, "extractvalue operand must be array or struct");
1870 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1872 return Error(ID.Loc, "invalid indices for extractvalue");
1874 Context.getConstantExprExtractValue(Val, Indices.data(), Indices.size());
1875 ID.Kind = ValID::t_Constant;
1878 case lltok::kw_insertvalue: {
1880 Constant *Val0, *Val1;
1881 SmallVector<unsigned, 4> Indices;
1882 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1883 ParseGlobalTypeAndValue(Val0) ||
1884 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1885 ParseGlobalTypeAndValue(Val1) ||
1886 ParseIndexList(Indices) ||
1887 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1889 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1890 return Error(ID.Loc, "extractvalue operand must be array or struct");
1891 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1893 return Error(ID.Loc, "invalid indices for insertvalue");
1894 ID.ConstantVal = Context.getConstantExprInsertValue(Val0, Val1,
1895 Indices.data(), Indices.size());
1896 ID.Kind = ValID::t_Constant;
1899 case lltok::kw_icmp:
1900 case lltok::kw_fcmp: {
1901 unsigned PredVal, Opc = Lex.getUIntVal();
1902 Constant *Val0, *Val1;
1904 if (ParseCmpPredicate(PredVal, Opc) ||
1905 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1906 ParseGlobalTypeAndValue(Val0) ||
1907 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1908 ParseGlobalTypeAndValue(Val1) ||
1909 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1912 if (Val0->getType() != Val1->getType())
1913 return Error(ID.Loc, "compare operands must have the same type");
1915 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1917 if (Opc == Instruction::FCmp) {
1918 if (!Val0->getType()->isFPOrFPVector())
1919 return Error(ID.Loc, "fcmp requires floating point operands");
1920 ID.ConstantVal = Context.getConstantExprFCmp(Pred, Val0, Val1);
1922 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
1923 if (!Val0->getType()->isIntOrIntVector() &&
1924 !isa<PointerType>(Val0->getType()))
1925 return Error(ID.Loc, "icmp requires pointer or integer operands");
1926 ID.ConstantVal = Context.getConstantExprICmp(Pred, Val0, Val1);
1928 ID.Kind = ValID::t_Constant;
1932 // Binary Operators.
1934 case lltok::kw_fadd:
1936 case lltok::kw_fsub:
1938 case lltok::kw_fmul:
1939 case lltok::kw_udiv:
1940 case lltok::kw_sdiv:
1941 case lltok::kw_fdiv:
1942 case lltok::kw_urem:
1943 case lltok::kw_srem:
1944 case lltok::kw_frem: {
1945 unsigned Opc = Lex.getUIntVal();
1946 Constant *Val0, *Val1;
1948 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1949 ParseGlobalTypeAndValue(Val0) ||
1950 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1951 ParseGlobalTypeAndValue(Val1) ||
1952 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1954 if (Val0->getType() != Val1->getType())
1955 return Error(ID.Loc, "operands of constexpr must have same type");
1956 if (!Val0->getType()->isIntOrIntVector() &&
1957 !Val0->getType()->isFPOrFPVector())
1958 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
1959 ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
1960 ID.Kind = ValID::t_Constant;
1964 // Logical Operations
1966 case lltok::kw_lshr:
1967 case lltok::kw_ashr:
1970 case lltok::kw_xor: {
1971 unsigned Opc = Lex.getUIntVal();
1972 Constant *Val0, *Val1;
1974 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1975 ParseGlobalTypeAndValue(Val0) ||
1976 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1977 ParseGlobalTypeAndValue(Val1) ||
1978 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1980 if (Val0->getType() != Val1->getType())
1981 return Error(ID.Loc, "operands of constexpr must have same type");
1982 if (!Val0->getType()->isIntOrIntVector())
1983 return Error(ID.Loc,
1984 "constexpr requires integer or integer vector operands");
1985 ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
1986 ID.Kind = ValID::t_Constant;
1990 case lltok::kw_getelementptr:
1991 case lltok::kw_shufflevector:
1992 case lltok::kw_insertelement:
1993 case lltok::kw_extractelement:
1994 case lltok::kw_select: {
1995 unsigned Opc = Lex.getUIntVal();
1996 SmallVector<Constant*, 16> Elts;
1998 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
1999 ParseGlobalValueVector(Elts) ||
2000 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2003 if (Opc == Instruction::GetElementPtr) {
2004 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
2005 return Error(ID.Loc, "getelementptr requires pointer operand");
2007 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
2008 (Value**)&Elts[1], Elts.size()-1))
2009 return Error(ID.Loc, "invalid indices for getelementptr");
2010 ID.ConstantVal = Context.getConstantExprGetElementPtr(Elts[0],
2011 &Elts[1], Elts.size()-1);
2012 } else if (Opc == Instruction::Select) {
2013 if (Elts.size() != 3)
2014 return Error(ID.Loc, "expected three operands to select");
2015 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2017 return Error(ID.Loc, Reason);
2018 ID.ConstantVal = Context.getConstantExprSelect(Elts[0], Elts[1], Elts[2]);
2019 } else if (Opc == Instruction::ShuffleVector) {
2020 if (Elts.size() != 3)
2021 return Error(ID.Loc, "expected three operands to shufflevector");
2022 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2023 return Error(ID.Loc, "invalid operands to shufflevector");
2025 Context.getConstantExprShuffleVector(Elts[0], Elts[1],Elts[2]);
2026 } else if (Opc == Instruction::ExtractElement) {
2027 if (Elts.size() != 2)
2028 return Error(ID.Loc, "expected two operands to extractelement");
2029 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2030 return Error(ID.Loc, "invalid extractelement operands");
2031 ID.ConstantVal = Context.getConstantExprExtractElement(Elts[0], Elts[1]);
2033 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2034 if (Elts.size() != 3)
2035 return Error(ID.Loc, "expected three operands to insertelement");
2036 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2037 return Error(ID.Loc, "invalid insertelement operands");
2039 Context.getConstantExprInsertElement(Elts[0], Elts[1],Elts[2]);
2042 ID.Kind = ValID::t_Constant;
2045 case lltok::kw_signed: {
2047 bool AlsoUnsigned = EatIfPresent(lltok::kw_unsigned);
2048 if (Lex.getKind() != lltok::kw_add &&
2049 Lex.getKind() != lltok::kw_sub &&
2050 Lex.getKind() != lltok::kw_mul)
2051 return TokError("expected 'add', 'sub', or 'mul'");
2052 bool Result = LLParser::ParseValID(ID);
2054 cast<OverflowingBinaryOperator>(ID.ConstantVal)
2055 ->setHasNoSignedOverflow(true);
2057 cast<OverflowingBinaryOperator>(ID.ConstantVal)
2058 ->setHasNoUnsignedOverflow(true);
2062 case lltok::kw_unsigned: {
2064 bool AlsoSigned = EatIfPresent(lltok::kw_signed);
2065 if (Lex.getKind() != lltok::kw_add &&
2066 Lex.getKind() != lltok::kw_sub &&
2067 Lex.getKind() != lltok::kw_mul)
2068 return TokError("expected 'add', 'sub', or 'mul'");
2069 bool Result = LLParser::ParseValID(ID);
2071 cast<OverflowingBinaryOperator>(ID.ConstantVal)
2072 ->setHasNoUnsignedOverflow(true);
2074 cast<OverflowingBinaryOperator>(ID.ConstantVal)
2075 ->setHasNoSignedOverflow(true);
2079 case lltok::kw_exact: {
2081 if (Lex.getKind() != lltok::kw_sdiv)
2082 return TokError("expected 'sdiv'");
2083 bool Result = LLParser::ParseValID(ID);
2085 cast<SDivOperator>(ID.ConstantVal)->setIsExact(true);
2094 /// ParseGlobalValue - Parse a global value with the specified type.
2095 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2098 return ParseValID(ID) ||
2099 ConvertGlobalValIDToValue(Ty, ID, V);
2102 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2104 bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2106 if (isa<FunctionType>(Ty))
2107 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2110 default: llvm_unreachable("Unknown ValID!");
2111 case ValID::t_LocalID:
2112 case ValID::t_LocalName:
2113 return Error(ID.Loc, "invalid use of function-local name");
2114 case ValID::t_InlineAsm:
2115 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2116 case ValID::t_GlobalName:
2117 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2119 case ValID::t_GlobalID:
2120 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2122 case ValID::t_APSInt:
2123 if (!isa<IntegerType>(Ty))
2124 return Error(ID.Loc, "integer constant must have integer type");
2125 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2126 V = Context.getConstantInt(ID.APSIntVal);
2128 case ValID::t_APFloat:
2129 if (!Ty->isFloatingPoint() ||
2130 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2131 return Error(ID.Loc, "floating point constant invalid for type");
2133 // The lexer has no type info, so builds all float and double FP constants
2134 // as double. Fix this here. Long double does not need this.
2135 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2136 Ty == Type::FloatTy) {
2138 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2141 V = Context.getConstantFP(ID.APFloatVal);
2143 if (V->getType() != Ty)
2144 return Error(ID.Loc, "floating point constant does not have type '" +
2145 Ty->getDescription() + "'");
2149 if (!isa<PointerType>(Ty))
2150 return Error(ID.Loc, "null must be a pointer type");
2151 V = Context.getConstantPointerNull(cast<PointerType>(Ty));
2153 case ValID::t_Undef:
2154 // FIXME: LabelTy should not be a first-class type.
2155 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
2156 !isa<OpaqueType>(Ty))
2157 return Error(ID.Loc, "invalid type for undef constant");
2158 V = Context.getUndef(Ty);
2160 case ValID::t_EmptyArray:
2161 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2162 return Error(ID.Loc, "invalid empty array initializer");
2163 V = Context.getUndef(Ty);
2166 // FIXME: LabelTy should not be a first-class type.
2167 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
2168 return Error(ID.Loc, "invalid type for null constant");
2169 V = Context.getNullValue(Ty);
2171 case ValID::t_Constant:
2172 if (ID.ConstantVal->getType() != Ty)
2173 return Error(ID.Loc, "constant expression type mismatch");
2179 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2180 PATypeHolder Type(Type::VoidTy);
2181 return ParseType(Type) ||
2182 ParseGlobalValue(Type, V);
2185 /// ParseGlobalValueVector
2187 /// ::= TypeAndValue (',' TypeAndValue)*
2188 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2190 if (Lex.getKind() == lltok::rbrace ||
2191 Lex.getKind() == lltok::rsquare ||
2192 Lex.getKind() == lltok::greater ||
2193 Lex.getKind() == lltok::rparen)
2197 if (ParseGlobalTypeAndValue(C)) return true;
2200 while (EatIfPresent(lltok::comma)) {
2201 if (ParseGlobalTypeAndValue(C)) return true;
2209 //===----------------------------------------------------------------------===//
2210 // Function Parsing.
2211 //===----------------------------------------------------------------------===//
2213 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2214 PerFunctionState &PFS) {
2215 if (ID.Kind == ValID::t_LocalID)
2216 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2217 else if (ID.Kind == ValID::t_LocalName)
2218 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
2219 else if (ID.Kind == ValID::t_InlineAsm) {
2220 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2221 const FunctionType *FTy =
2222 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2223 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2224 return Error(ID.Loc, "invalid type for inline asm constraint string");
2225 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2229 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2237 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2240 return ParseValID(ID) ||
2241 ConvertValIDToValue(Ty, ID, V, PFS);
2244 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2245 PATypeHolder T(Type::VoidTy);
2246 return ParseType(T) ||
2247 ParseValue(T, V, PFS);
2251 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2252 /// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2253 /// OptionalAlign OptGC
2254 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2255 // Parse the linkage.
2256 LocTy LinkageLoc = Lex.getLoc();
2259 unsigned Visibility, CC, RetAttrs;
2260 PATypeHolder RetType(Type::VoidTy);
2261 LocTy RetTypeLoc = Lex.getLoc();
2262 if (ParseOptionalLinkage(Linkage) ||
2263 ParseOptionalVisibility(Visibility) ||
2264 ParseOptionalCallingConv(CC) ||
2265 ParseOptionalAttrs(RetAttrs, 1) ||
2266 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2269 // Verify that the linkage is ok.
2270 switch ((GlobalValue::LinkageTypes)Linkage) {
2271 case GlobalValue::ExternalLinkage:
2272 break; // always ok.
2273 case GlobalValue::DLLImportLinkage:
2274 case GlobalValue::ExternalWeakLinkage:
2276 return Error(LinkageLoc, "invalid linkage for function definition");
2278 case GlobalValue::PrivateLinkage:
2279 case GlobalValue::LinkerPrivateLinkage:
2280 case GlobalValue::InternalLinkage:
2281 case GlobalValue::AvailableExternallyLinkage:
2282 case GlobalValue::LinkOnceAnyLinkage:
2283 case GlobalValue::LinkOnceODRLinkage:
2284 case GlobalValue::WeakAnyLinkage:
2285 case GlobalValue::WeakODRLinkage:
2286 case GlobalValue::DLLExportLinkage:
2288 return Error(LinkageLoc, "invalid linkage for function declaration");
2290 case GlobalValue::AppendingLinkage:
2291 case GlobalValue::GhostLinkage:
2292 case GlobalValue::CommonLinkage:
2293 return Error(LinkageLoc, "invalid function linkage type");
2296 if (!FunctionType::isValidReturnType(RetType) ||
2297 isa<OpaqueType>(RetType))
2298 return Error(RetTypeLoc, "invalid function return type");
2300 LocTy NameLoc = Lex.getLoc();
2302 std::string FunctionName;
2303 if (Lex.getKind() == lltok::GlobalVar) {
2304 FunctionName = Lex.getStrVal();
2305 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2306 unsigned NameID = Lex.getUIntVal();
2308 if (NameID != NumberedVals.size())
2309 return TokError("function expected to be numbered '%" +
2310 utostr(NumberedVals.size()) + "'");
2312 return TokError("expected function name");
2317 if (Lex.getKind() != lltok::lparen)
2318 return TokError("expected '(' in function argument list");
2320 std::vector<ArgInfo> ArgList;
2323 std::string Section;
2327 if (ParseArgumentList(ArgList, isVarArg, false) ||
2328 ParseOptionalAttrs(FuncAttrs, 2) ||
2329 (EatIfPresent(lltok::kw_section) &&
2330 ParseStringConstant(Section)) ||
2331 ParseOptionalAlignment(Alignment) ||
2332 (EatIfPresent(lltok::kw_gc) &&
2333 ParseStringConstant(GC)))
2336 // If the alignment was parsed as an attribute, move to the alignment field.
2337 if (FuncAttrs & Attribute::Alignment) {
2338 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2339 FuncAttrs &= ~Attribute::Alignment;
2342 // Okay, if we got here, the function is syntactically valid. Convert types
2343 // and do semantic checks.
2344 std::vector<const Type*> ParamTypeList;
2345 SmallVector<AttributeWithIndex, 8> Attrs;
2346 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2348 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2349 if (FuncAttrs & ObsoleteFuncAttrs) {
2350 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2351 FuncAttrs &= ~ObsoleteFuncAttrs;
2354 if (RetAttrs != Attribute::None)
2355 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2357 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2358 ParamTypeList.push_back(ArgList[i].Type);
2359 if (ArgList[i].Attrs != Attribute::None)
2360 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2363 if (FuncAttrs != Attribute::None)
2364 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2366 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2368 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2369 RetType != Type::VoidTy)
2370 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2372 const FunctionType *FT =
2373 Context.getFunctionType(RetType, ParamTypeList, isVarArg);
2374 const PointerType *PFT = Context.getPointerTypeUnqual(FT);
2377 if (!FunctionName.empty()) {
2378 // If this was a definition of a forward reference, remove the definition
2379 // from the forward reference table and fill in the forward ref.
2380 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2381 ForwardRefVals.find(FunctionName);
2382 if (FRVI != ForwardRefVals.end()) {
2383 Fn = M->getFunction(FunctionName);
2384 ForwardRefVals.erase(FRVI);
2385 } else if ((Fn = M->getFunction(FunctionName))) {
2386 // If this function already exists in the symbol table, then it is
2387 // multiply defined. We accept a few cases for old backwards compat.
2388 // FIXME: Remove this stuff for LLVM 3.0.
2389 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2390 (!Fn->isDeclaration() && isDefine)) {
2391 // If the redefinition has different type or different attributes,
2392 // reject it. If both have bodies, reject it.
2393 return Error(NameLoc, "invalid redefinition of function '" +
2394 FunctionName + "'");
2395 } else if (Fn->isDeclaration()) {
2396 // Make sure to strip off any argument names so we can't get conflicts.
2397 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2403 } else if (FunctionName.empty()) {
2404 // If this is a definition of a forward referenced function, make sure the
2406 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2407 = ForwardRefValIDs.find(NumberedVals.size());
2408 if (I != ForwardRefValIDs.end()) {
2409 Fn = cast<Function>(I->second.first);
2410 if (Fn->getType() != PFT)
2411 return Error(NameLoc, "type of definition and forward reference of '@" +
2412 utostr(NumberedVals.size()) +"' disagree");
2413 ForwardRefValIDs.erase(I);
2418 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2419 else // Move the forward-reference to the correct spot in the module.
2420 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2422 if (FunctionName.empty())
2423 NumberedVals.push_back(Fn);
2425 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2426 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2427 Fn->setCallingConv(CC);
2428 Fn->setAttributes(PAL);
2429 Fn->setAlignment(Alignment);
2430 Fn->setSection(Section);
2431 if (!GC.empty()) Fn->setGC(GC.c_str());
2433 // Add all of the arguments we parsed to the function.
2434 Function::arg_iterator ArgIt = Fn->arg_begin();
2435 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2436 // If the argument has a name, insert it into the argument symbol table.
2437 if (ArgList[i].Name.empty()) continue;
2439 // Set the name, if it conflicted, it will be auto-renamed.
2440 ArgIt->setName(ArgList[i].Name);
2442 if (ArgIt->getNameStr() != ArgList[i].Name)
2443 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2444 ArgList[i].Name + "'");
2451 /// ParseFunctionBody
2452 /// ::= '{' BasicBlock+ '}'
2453 /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2455 bool LLParser::ParseFunctionBody(Function &Fn) {
2456 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2457 return TokError("expected '{' in function body");
2458 Lex.Lex(); // eat the {.
2460 PerFunctionState PFS(*this, Fn);
2462 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2463 if (ParseBasicBlock(PFS)) return true;
2468 // Verify function is ok.
2469 return PFS.VerifyFunctionComplete();
2473 /// ::= LabelStr? Instruction*
2474 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2475 // If this basic block starts out with a name, remember it.
2477 LocTy NameLoc = Lex.getLoc();
2478 if (Lex.getKind() == lltok::LabelStr) {
2479 Name = Lex.getStrVal();
2483 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2484 if (BB == 0) return true;
2486 std::string NameStr;
2488 // Parse the instructions in this block until we get a terminator.
2491 // This instruction may have three possibilities for a name: a) none
2492 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2493 LocTy NameLoc = Lex.getLoc();
2497 if (Lex.getKind() == lltok::LocalVarID) {
2498 NameID = Lex.getUIntVal();
2500 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2502 } else if (Lex.getKind() == lltok::LocalVar ||
2503 // FIXME: REMOVE IN LLVM 3.0
2504 Lex.getKind() == lltok::StringConstant) {
2505 NameStr = Lex.getStrVal();
2507 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2511 if (ParseInstruction(Inst, BB, PFS)) return true;
2513 BB->getInstList().push_back(Inst);
2515 // Set the name on the instruction.
2516 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2517 } while (!isa<TerminatorInst>(Inst));
2522 //===----------------------------------------------------------------------===//
2523 // Instruction Parsing.
2524 //===----------------------------------------------------------------------===//
2526 /// ParseInstruction - Parse one of the many different instructions.
2528 bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2529 PerFunctionState &PFS) {
2530 lltok::Kind Token = Lex.getKind();
2531 if (Token == lltok::Eof)
2532 return TokError("found end of file when expecting more instructions");
2533 LocTy Loc = Lex.getLoc();
2534 unsigned KeywordVal = Lex.getUIntVal();
2535 Lex.Lex(); // Eat the keyword.
2538 default: return Error(Loc, "expected instruction opcode");
2539 // Terminator Instructions.
2540 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2541 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2542 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2543 case lltok::kw_br: return ParseBr(Inst, PFS);
2544 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2545 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2546 // Binary Operators.
2550 // API compatibility: Accept either integer or floating-point types.
2551 return ParseArithmetic(Inst, PFS, KeywordVal, 0);
2552 case lltok::kw_fadd:
2553 case lltok::kw_fsub:
2554 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2556 case lltok::kw_udiv:
2557 case lltok::kw_sdiv:
2558 case lltok::kw_urem:
2559 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2560 case lltok::kw_fdiv:
2561 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2563 case lltok::kw_lshr:
2564 case lltok::kw_ashr:
2567 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
2568 case lltok::kw_icmp:
2569 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
2571 case lltok::kw_trunc:
2572 case lltok::kw_zext:
2573 case lltok::kw_sext:
2574 case lltok::kw_fptrunc:
2575 case lltok::kw_fpext:
2576 case lltok::kw_bitcast:
2577 case lltok::kw_uitofp:
2578 case lltok::kw_sitofp:
2579 case lltok::kw_fptoui:
2580 case lltok::kw_fptosi:
2581 case lltok::kw_inttoptr:
2582 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
2584 case lltok::kw_select: return ParseSelect(Inst, PFS);
2585 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
2586 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2587 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2588 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2589 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2590 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2591 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2593 case lltok::kw_alloca:
2594 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
2595 case lltok::kw_free: return ParseFree(Inst, PFS);
2596 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2597 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2598 case lltok::kw_volatile:
2599 if (EatIfPresent(lltok::kw_load))
2600 return ParseLoad(Inst, PFS, true);
2601 else if (EatIfPresent(lltok::kw_store))
2602 return ParseStore(Inst, PFS, true);
2604 return TokError("expected 'load' or 'store'");
2605 case lltok::kw_signed: {
2606 bool AlsoUnsigned = EatIfPresent(lltok::kw_unsigned);
2607 if (Lex.getKind() == lltok::kw_add ||
2608 Lex.getKind() == lltok::kw_sub ||
2609 Lex.getKind() == lltok::kw_mul) {
2611 KeywordVal = Lex.getUIntVal();
2612 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
2614 cast<OverflowingBinaryOperator>(Inst)->setHasNoSignedOverflow(true);
2616 cast<OverflowingBinaryOperator>(Inst)->setHasNoUnsignedOverflow(true);
2620 return TokError("expected 'add', 'sub', or 'mul'");
2622 case lltok::kw_unsigned: {
2623 bool AlsoSigned = EatIfPresent(lltok::kw_signed);
2624 if (Lex.getKind() == lltok::kw_add ||
2625 Lex.getKind() == lltok::kw_sub ||
2626 Lex.getKind() == lltok::kw_mul) {
2628 KeywordVal = Lex.getUIntVal();
2629 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2631 cast<OverflowingBinaryOperator>(Inst)->setHasNoUnsignedOverflow(true);
2633 cast<OverflowingBinaryOperator>(Inst)->setHasNoSignedOverflow(true);
2637 return TokError("expected 'add', 'sub', or 'mul'");
2639 case lltok::kw_exact:
2640 if (Lex.getKind() == lltok::kw_sdiv) {
2642 KeywordVal = Lex.getUIntVal();
2643 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2645 cast<SDivOperator>(Inst)->setIsExact(true);
2648 return TokError("expected 'udiv'");
2649 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2650 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2651 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2652 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2656 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2657 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2658 if (Opc == Instruction::FCmp) {
2659 switch (Lex.getKind()) {
2660 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2661 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2662 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2663 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2664 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2665 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2666 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2667 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2668 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2669 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2670 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2671 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2672 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2673 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2674 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2675 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2676 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2679 switch (Lex.getKind()) {
2680 default: TokError("expected icmp predicate (e.g. 'eq')");
2681 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2682 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2683 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2684 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2685 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2686 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2687 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2688 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2689 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2690 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2697 //===----------------------------------------------------------------------===//
2698 // Terminator Instructions.
2699 //===----------------------------------------------------------------------===//
2701 /// ParseRet - Parse a return instruction.
2703 /// ::= 'ret' TypeAndValue
2704 /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2705 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2706 PerFunctionState &PFS) {
2707 PATypeHolder Ty(Type::VoidTy);
2708 if (ParseType(Ty, true /*void allowed*/)) return true;
2710 if (Ty == Type::VoidTy) {
2711 Inst = ReturnInst::Create();
2716 if (ParseValue(Ty, RV, PFS)) return true;
2718 // The normal case is one return value.
2719 if (Lex.getKind() == lltok::comma) {
2720 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2721 // of 'ret {i32,i32} {i32 1, i32 2}'
2722 SmallVector<Value*, 8> RVs;
2725 while (EatIfPresent(lltok::comma)) {
2726 if (ParseTypeAndValue(RV, PFS)) return true;
2730 RV = Context.getUndef(PFS.getFunction().getReturnType());
2731 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2732 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2733 BB->getInstList().push_back(I);
2737 Inst = ReturnInst::Create(RV);
2743 /// ::= 'br' TypeAndValue
2744 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2745 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2747 Value *Op0, *Op1, *Op2;
2748 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2750 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2751 Inst = BranchInst::Create(BB);
2755 if (Op0->getType() != Type::Int1Ty)
2756 return Error(Loc, "branch condition must have 'i1' type");
2758 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2759 ParseTypeAndValue(Op1, Loc, PFS) ||
2760 ParseToken(lltok::comma, "expected ',' after true destination") ||
2761 ParseTypeAndValue(Op2, Loc2, PFS))
2764 if (!isa<BasicBlock>(Op1))
2765 return Error(Loc, "true destination of branch must be a basic block");
2766 if (!isa<BasicBlock>(Op2))
2767 return Error(Loc2, "true destination of branch must be a basic block");
2769 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2775 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2777 /// ::= (TypeAndValue ',' TypeAndValue)*
2778 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2779 LocTy CondLoc, BBLoc;
2780 Value *Cond, *DefaultBB;
2781 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2782 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2783 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2784 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2787 if (!isa<IntegerType>(Cond->getType()))
2788 return Error(CondLoc, "switch condition must have integer type");
2789 if (!isa<BasicBlock>(DefaultBB))
2790 return Error(BBLoc, "default destination must be a basic block");
2792 // Parse the jump table pairs.
2793 SmallPtrSet<Value*, 32> SeenCases;
2794 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2795 while (Lex.getKind() != lltok::rsquare) {
2796 Value *Constant, *DestBB;
2798 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2799 ParseToken(lltok::comma, "expected ',' after case value") ||
2800 ParseTypeAndValue(DestBB, BBLoc, PFS))
2803 if (!SeenCases.insert(Constant))
2804 return Error(CondLoc, "duplicate case value in switch");
2805 if (!isa<ConstantInt>(Constant))
2806 return Error(CondLoc, "case value is not a constant integer");
2807 if (!isa<BasicBlock>(DestBB))
2808 return Error(BBLoc, "case destination is not a basic block");
2810 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2811 cast<BasicBlock>(DestBB)));
2814 Lex.Lex(); // Eat the ']'.
2816 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2818 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2819 SI->addCase(Table[i].first, Table[i].second);
2825 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2826 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2827 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2828 LocTy CallLoc = Lex.getLoc();
2829 unsigned CC, RetAttrs, FnAttrs;
2830 PATypeHolder RetType(Type::VoidTy);
2833 SmallVector<ParamInfo, 16> ArgList;
2835 Value *NormalBB, *UnwindBB;
2836 if (ParseOptionalCallingConv(CC) ||
2837 ParseOptionalAttrs(RetAttrs, 1) ||
2838 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
2839 ParseValID(CalleeID) ||
2840 ParseParameterList(ArgList, PFS) ||
2841 ParseOptionalAttrs(FnAttrs, 2) ||
2842 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2843 ParseTypeAndValue(NormalBB, PFS) ||
2844 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2845 ParseTypeAndValue(UnwindBB, PFS))
2848 if (!isa<BasicBlock>(NormalBB))
2849 return Error(CallLoc, "normal destination is not a basic block");
2850 if (!isa<BasicBlock>(UnwindBB))
2851 return Error(CallLoc, "unwind destination is not a basic block");
2853 // If RetType is a non-function pointer type, then this is the short syntax
2854 // for the call, which means that RetType is just the return type. Infer the
2855 // rest of the function argument types from the arguments that are present.
2856 const PointerType *PFTy = 0;
2857 const FunctionType *Ty = 0;
2858 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2859 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2860 // Pull out the types of all of the arguments...
2861 std::vector<const Type*> ParamTypes;
2862 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2863 ParamTypes.push_back(ArgList[i].V->getType());
2865 if (!FunctionType::isValidReturnType(RetType))
2866 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2868 Ty = Context.getFunctionType(RetType, ParamTypes, false);
2869 PFTy = Context.getPointerTypeUnqual(Ty);
2872 // Look up the callee.
2874 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2876 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2877 // function attributes.
2878 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2879 if (FnAttrs & ObsoleteFuncAttrs) {
2880 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2881 FnAttrs &= ~ObsoleteFuncAttrs;
2884 // Set up the Attributes for the function.
2885 SmallVector<AttributeWithIndex, 8> Attrs;
2886 if (RetAttrs != Attribute::None)
2887 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2889 SmallVector<Value*, 8> Args;
2891 // Loop through FunctionType's arguments and ensure they are specified
2892 // correctly. Also, gather any parameter attributes.
2893 FunctionType::param_iterator I = Ty->param_begin();
2894 FunctionType::param_iterator E = Ty->param_end();
2895 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2896 const Type *ExpectedTy = 0;
2899 } else if (!Ty->isVarArg()) {
2900 return Error(ArgList[i].Loc, "too many arguments specified");
2903 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2904 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2905 ExpectedTy->getDescription() + "'");
2906 Args.push_back(ArgList[i].V);
2907 if (ArgList[i].Attrs != Attribute::None)
2908 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2912 return Error(CallLoc, "not enough parameters specified for call");
2914 if (FnAttrs != Attribute::None)
2915 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2917 // Finish off the Attributes and check them
2918 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2920 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2921 cast<BasicBlock>(UnwindBB),
2922 Args.begin(), Args.end());
2923 II->setCallingConv(CC);
2924 II->setAttributes(PAL);
2931 //===----------------------------------------------------------------------===//
2932 // Binary Operators.
2933 //===----------------------------------------------------------------------===//
2936 /// ::= ArithmeticOps TypeAndValue ',' Value
2938 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2939 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
2940 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
2941 unsigned Opc, unsigned OperandType) {
2942 LocTy Loc; Value *LHS, *RHS;
2943 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2944 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2945 ParseValue(LHS->getType(), RHS, PFS))
2949 switch (OperandType) {
2950 default: llvm_unreachable("Unknown operand type!");
2951 case 0: // int or FP.
2952 Valid = LHS->getType()->isIntOrIntVector() ||
2953 LHS->getType()->isFPOrFPVector();
2955 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2956 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2960 return Error(Loc, "invalid operand type for instruction");
2962 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2967 /// ::= ArithmeticOps TypeAndValue ',' Value {
2968 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2970 LocTy Loc; Value *LHS, *RHS;
2971 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2972 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2973 ParseValue(LHS->getType(), RHS, PFS))
2976 if (!LHS->getType()->isIntOrIntVector())
2977 return Error(Loc,"instruction requires integer or integer vector operands");
2979 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2985 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
2986 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
2987 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2989 // Parse the integer/fp comparison predicate.
2993 if (ParseCmpPredicate(Pred, Opc) ||
2994 ParseTypeAndValue(LHS, Loc, PFS) ||
2995 ParseToken(lltok::comma, "expected ',' after compare value") ||
2996 ParseValue(LHS->getType(), RHS, PFS))
2999 if (Opc == Instruction::FCmp) {
3000 if (!LHS->getType()->isFPOrFPVector())
3001 return Error(Loc, "fcmp requires floating point operands");
3002 Inst = new FCmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
3004 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3005 if (!LHS->getType()->isIntOrIntVector() &&
3006 !isa<PointerType>(LHS->getType()))
3007 return Error(Loc, "icmp requires integer operands");
3008 Inst = new ICmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
3013 //===----------------------------------------------------------------------===//
3014 // Other Instructions.
3015 //===----------------------------------------------------------------------===//
3019 /// ::= CastOpc TypeAndValue 'to' Type
3020 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3022 LocTy Loc; Value *Op;
3023 PATypeHolder DestTy(Type::VoidTy);
3024 if (ParseTypeAndValue(Op, Loc, PFS) ||
3025 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3029 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3030 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3031 return Error(Loc, "invalid cast opcode for cast from '" +
3032 Op->getType()->getDescription() + "' to '" +
3033 DestTy->getDescription() + "'");
3035 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3040 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3041 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3043 Value *Op0, *Op1, *Op2;
3044 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3045 ParseToken(lltok::comma, "expected ',' after select condition") ||
3046 ParseTypeAndValue(Op1, PFS) ||
3047 ParseToken(lltok::comma, "expected ',' after select value") ||
3048 ParseTypeAndValue(Op2, PFS))
3051 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3052 return Error(Loc, Reason);
3054 Inst = SelectInst::Create(Op0, Op1, Op2);
3059 /// ::= 'va_arg' TypeAndValue ',' Type
3060 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3062 PATypeHolder EltTy(Type::VoidTy);
3064 if (ParseTypeAndValue(Op, PFS) ||
3065 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3066 ParseType(EltTy, TypeLoc))
3069 if (!EltTy->isFirstClassType())
3070 return Error(TypeLoc, "va_arg requires operand with first class type");
3072 Inst = new VAArgInst(Op, EltTy);
3076 /// ParseExtractElement
3077 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3078 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3081 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3082 ParseToken(lltok::comma, "expected ',' after extract value") ||
3083 ParseTypeAndValue(Op1, PFS))
3086 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3087 return Error(Loc, "invalid extractelement operands");
3089 Inst = new ExtractElementInst(Op0, Op1);
3093 /// ParseInsertElement
3094 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3095 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3097 Value *Op0, *Op1, *Op2;
3098 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3099 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3100 ParseTypeAndValue(Op1, PFS) ||
3101 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3102 ParseTypeAndValue(Op2, PFS))
3105 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3106 return Error(Loc, "invalid extractelement operands");
3108 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3112 /// ParseShuffleVector
3113 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3114 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3116 Value *Op0, *Op1, *Op2;
3117 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3118 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3119 ParseTypeAndValue(Op1, PFS) ||
3120 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3121 ParseTypeAndValue(Op2, PFS))
3124 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3125 return Error(Loc, "invalid extractelement operands");
3127 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3132 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
3133 bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3134 PATypeHolder Ty(Type::VoidTy);
3136 LocTy TypeLoc = Lex.getLoc();
3138 if (ParseType(Ty) ||
3139 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3140 ParseValue(Ty, Op0, PFS) ||
3141 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3142 ParseValue(Type::LabelTy, Op1, PFS) ||
3143 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3146 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3148 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3150 if (!EatIfPresent(lltok::comma))
3153 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3154 ParseValue(Ty, Op0, PFS) ||
3155 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3156 ParseValue(Type::LabelTy, Op1, PFS) ||
3157 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3161 if (!Ty->isFirstClassType())
3162 return Error(TypeLoc, "phi node must have first class type");
3164 PHINode *PN = PHINode::Create(Ty);
3165 PN->reserveOperandSpace(PHIVals.size());
3166 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3167 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3173 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3174 /// ParameterList OptionalAttrs
3175 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3177 unsigned CC, RetAttrs, FnAttrs;
3178 PATypeHolder RetType(Type::VoidTy);
3181 SmallVector<ParamInfo, 16> ArgList;
3182 LocTy CallLoc = Lex.getLoc();
3184 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3185 ParseOptionalCallingConv(CC) ||
3186 ParseOptionalAttrs(RetAttrs, 1) ||
3187 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3188 ParseValID(CalleeID) ||
3189 ParseParameterList(ArgList, PFS) ||
3190 ParseOptionalAttrs(FnAttrs, 2))
3193 // If RetType is a non-function pointer type, then this is the short syntax
3194 // for the call, which means that RetType is just the return type. Infer the
3195 // rest of the function argument types from the arguments that are present.
3196 const PointerType *PFTy = 0;
3197 const FunctionType *Ty = 0;
3198 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3199 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3200 // Pull out the types of all of the arguments...
3201 std::vector<const Type*> ParamTypes;
3202 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3203 ParamTypes.push_back(ArgList[i].V->getType());
3205 if (!FunctionType::isValidReturnType(RetType))
3206 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3208 Ty = Context.getFunctionType(RetType, ParamTypes, false);
3209 PFTy = Context.getPointerTypeUnqual(Ty);
3212 // Look up the callee.
3214 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3216 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3217 // function attributes.
3218 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3219 if (FnAttrs & ObsoleteFuncAttrs) {
3220 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3221 FnAttrs &= ~ObsoleteFuncAttrs;
3224 // Set up the Attributes for the function.
3225 SmallVector<AttributeWithIndex, 8> Attrs;
3226 if (RetAttrs != Attribute::None)
3227 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3229 SmallVector<Value*, 8> Args;
3231 // Loop through FunctionType's arguments and ensure they are specified
3232 // correctly. Also, gather any parameter attributes.
3233 FunctionType::param_iterator I = Ty->param_begin();
3234 FunctionType::param_iterator E = Ty->param_end();
3235 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3236 const Type *ExpectedTy = 0;
3239 } else if (!Ty->isVarArg()) {
3240 return Error(ArgList[i].Loc, "too many arguments specified");
3243 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3244 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3245 ExpectedTy->getDescription() + "'");
3246 Args.push_back(ArgList[i].V);
3247 if (ArgList[i].Attrs != Attribute::None)
3248 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3252 return Error(CallLoc, "not enough parameters specified for call");
3254 if (FnAttrs != Attribute::None)
3255 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3257 // Finish off the Attributes and check them
3258 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3260 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3261 CI->setTailCall(isTail);
3262 CI->setCallingConv(CC);
3263 CI->setAttributes(PAL);
3268 //===----------------------------------------------------------------------===//
3269 // Memory Instructions.
3270 //===----------------------------------------------------------------------===//
3273 /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3274 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3275 bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3277 PATypeHolder Ty(Type::VoidTy);
3280 unsigned Alignment = 0;
3281 if (ParseType(Ty)) return true;
3283 if (EatIfPresent(lltok::comma)) {
3284 if (Lex.getKind() == lltok::kw_align) {
3285 if (ParseOptionalAlignment(Alignment)) return true;
3286 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3287 ParseOptionalCommaAlignment(Alignment)) {
3292 if (Size && Size->getType() != Type::Int32Ty)
3293 return Error(SizeLoc, "element count must be i32");
3295 if (Opc == Instruction::Malloc)
3296 Inst = new MallocInst(Ty, Size, Alignment);
3298 Inst = new AllocaInst(Ty, Size, Alignment);
3303 /// ::= 'free' TypeAndValue
3304 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3305 Value *Val; LocTy Loc;
3306 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3307 if (!isa<PointerType>(Val->getType()))
3308 return Error(Loc, "operand to free must be a pointer");
3309 Inst = new FreeInst(Val);
3314 /// ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
3315 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3317 Value *Val; LocTy Loc;
3319 if (ParseTypeAndValue(Val, Loc, PFS) ||
3320 ParseOptionalCommaAlignment(Alignment))
3323 if (!isa<PointerType>(Val->getType()) ||
3324 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3325 return Error(Loc, "load operand must be a pointer to a first class type");
3327 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3332 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3333 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3335 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3337 if (ParseTypeAndValue(Val, Loc, PFS) ||
3338 ParseToken(lltok::comma, "expected ',' after store operand") ||
3339 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3340 ParseOptionalCommaAlignment(Alignment))
3343 if (!isa<PointerType>(Ptr->getType()))
3344 return Error(PtrLoc, "store operand must be a pointer");
3345 if (!Val->getType()->isFirstClassType())
3346 return Error(Loc, "store operand must be a first class value");
3347 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3348 return Error(Loc, "stored value and pointer type do not match");
3350 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3355 /// ::= 'getresult' TypeAndValue ',' i32
3356 /// FIXME: Remove support for getresult in LLVM 3.0
3357 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3358 Value *Val; LocTy ValLoc, EltLoc;
3360 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3361 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3362 ParseUInt32(Element, EltLoc))
3365 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3366 return Error(ValLoc, "getresult inst requires an aggregate operand");
3367 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3368 return Error(EltLoc, "invalid getresult index for value");
3369 Inst = ExtractValueInst::Create(Val, Element);
3373 /// ParseGetElementPtr
3374 /// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3375 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3376 Value *Ptr, *Val; LocTy Loc, EltLoc;
3377 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3379 if (!isa<PointerType>(Ptr->getType()))
3380 return Error(Loc, "base of getelementptr must be a pointer");
3382 SmallVector<Value*, 16> Indices;
3383 while (EatIfPresent(lltok::comma)) {
3384 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3385 if (!isa<IntegerType>(Val->getType()))
3386 return Error(EltLoc, "getelementptr index must be an integer");
3387 Indices.push_back(Val);
3390 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3391 Indices.begin(), Indices.end()))
3392 return Error(Loc, "invalid getelementptr indices");
3393 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3397 /// ParseExtractValue
3398 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3399 bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3400 Value *Val; LocTy Loc;
3401 SmallVector<unsigned, 4> Indices;
3402 if (ParseTypeAndValue(Val, Loc, PFS) ||
3403 ParseIndexList(Indices))
3406 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3407 return Error(Loc, "extractvalue operand must be array or struct");
3409 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3411 return Error(Loc, "invalid indices for extractvalue");
3412 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3416 /// ParseInsertValue
3417 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3418 bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3419 Value *Val0, *Val1; LocTy Loc0, Loc1;
3420 SmallVector<unsigned, 4> Indices;
3421 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3422 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3423 ParseTypeAndValue(Val1, Loc1, PFS) ||
3424 ParseIndexList(Indices))
3427 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3428 return Error(Loc0, "extractvalue operand must be array or struct");
3430 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3432 return Error(Loc0, "invalid indices for insertvalue");
3433 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3437 //===----------------------------------------------------------------------===//
3438 // Embedded metadata.
3439 //===----------------------------------------------------------------------===//
3441 /// ParseMDNodeVector
3442 /// ::= Element (',' Element)*
3444 /// ::= 'null' | TypeAndValue
3445 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
3446 assert(Lex.getKind() == lltok::lbrace);
3450 if (Lex.getKind() == lltok::kw_null) {
3455 if (ParseGlobalTypeAndValue(C)) return true;
3459 } while (EatIfPresent(lltok::comma));