1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the parser class for .ll files.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/AutoUpgrade.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Metadata.h"
23 #include "llvm/Module.h"
24 #include "llvm/Operator.h"
25 #include "llvm/ValueSymbolTable.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
33 /// ValID - Represents a reference of a definition of some sort with no type.
34 /// There are several cases where we have to parse the value but where the
35 /// type can depend on later context. This may either be a numeric reference
36 /// or a symbolic (%var) reference. This is just a discriminated union.
39 t_LocalID, t_GlobalID, // ID in UIntVal.
40 t_LocalName, t_GlobalName, // Name in StrVal.
41 t_APSInt, t_APFloat, // Value in APSIntVal/APFloatVal.
42 t_Null, t_Undef, t_Zero, // No value.
43 t_EmptyArray, // No value: []
44 t_Constant, // Value in ConstantVal.
45 t_InlineAsm, // Value in StrVal/StrVal2/UIntVal.
46 t_Metadata // Value in MetadataVal.
51 std::string StrVal, StrVal2;
54 Constant *ConstantVal;
55 MetadataBase *MetadataVal;
56 ValID() : APFloatVal(0.0) {}
60 /// Run: module ::= toplevelentity*
61 bool LLParser::Run() {
65 return ParseTopLevelEntities() ||
66 ValidateEndOfModule();
69 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
71 bool LLParser::ValidateEndOfModule() {
72 // Update auto-upgraded malloc calls to "malloc".
73 // FIXME: Remove in LLVM 3.0.
75 MallocF->setName("malloc");
76 // If setName() does not set the name to "malloc", then there is already a
77 // declaration of "malloc". In that case, iterate over all calls to MallocF
78 // and get them to call the declared "malloc" instead.
79 if (MallocF->getName() != "malloc") {
80 Constant* RealMallocF = M->getFunction("malloc");
81 if (RealMallocF->getType() != MallocF->getType())
82 RealMallocF = ConstantExpr::getBitCast(RealMallocF, MallocF->getType());
83 MallocF->replaceAllUsesWith(RealMallocF);
84 MallocF->eraseFromParent();
89 if (!ForwardRefTypes.empty())
90 return Error(ForwardRefTypes.begin()->second.second,
91 "use of undefined type named '" +
92 ForwardRefTypes.begin()->first + "'");
93 if (!ForwardRefTypeIDs.empty())
94 return Error(ForwardRefTypeIDs.begin()->second.second,
95 "use of undefined type '%" +
96 utostr(ForwardRefTypeIDs.begin()->first) + "'");
98 if (!ForwardRefVals.empty())
99 return Error(ForwardRefVals.begin()->second.second,
100 "use of undefined value '@" + ForwardRefVals.begin()->first +
103 if (!ForwardRefValIDs.empty())
104 return Error(ForwardRefValIDs.begin()->second.second,
105 "use of undefined value '@" +
106 utostr(ForwardRefValIDs.begin()->first) + "'");
108 if (!ForwardRefMDNodes.empty())
109 return Error(ForwardRefMDNodes.begin()->second.second,
110 "use of undefined metadata '!" +
111 utostr(ForwardRefMDNodes.begin()->first) + "'");
114 // Look for intrinsic functions and CallInst that need to be upgraded
115 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
116 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
118 // Check debug info intrinsics.
119 CheckDebugInfoIntrinsics(M);
123 //===----------------------------------------------------------------------===//
124 // Top-Level Entities
125 //===----------------------------------------------------------------------===//
127 bool LLParser::ParseTopLevelEntities() {
129 switch (Lex.getKind()) {
130 default: return TokError("expected top-level entity");
131 case lltok::Eof: return false;
132 //case lltok::kw_define:
133 case lltok::kw_declare: if (ParseDeclare()) return true; break;
134 case lltok::kw_define: if (ParseDefine()) return true; break;
135 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
136 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
137 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
138 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
139 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
140 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
141 case lltok::LocalVar: if (ParseNamedType()) return true; break;
142 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
143 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
144 case lltok::Metadata: if (ParseStandaloneMetadata()) return true; break;
145 case lltok::NamedOrCustomMD: if (ParseNamedMetadata()) return true; break;
147 // The Global variable production with no name can have many different
148 // optional leading prefixes, the production is:
149 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
150 // OptionalAddrSpace ('constant'|'global') ...
151 case lltok::kw_private : // OptionalLinkage
152 case lltok::kw_linker_private: // OptionalLinkage
153 case lltok::kw_internal: // OptionalLinkage
154 case lltok::kw_weak: // OptionalLinkage
155 case lltok::kw_weak_odr: // OptionalLinkage
156 case lltok::kw_linkonce: // OptionalLinkage
157 case lltok::kw_linkonce_odr: // OptionalLinkage
158 case lltok::kw_appending: // OptionalLinkage
159 case lltok::kw_dllexport: // OptionalLinkage
160 case lltok::kw_common: // OptionalLinkage
161 case lltok::kw_dllimport: // OptionalLinkage
162 case lltok::kw_extern_weak: // OptionalLinkage
163 case lltok::kw_external: { // OptionalLinkage
164 unsigned Linkage, Visibility;
165 if (ParseOptionalLinkage(Linkage) ||
166 ParseOptionalVisibility(Visibility) ||
167 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
171 case lltok::kw_default: // OptionalVisibility
172 case lltok::kw_hidden: // OptionalVisibility
173 case lltok::kw_protected: { // OptionalVisibility
175 if (ParseOptionalVisibility(Visibility) ||
176 ParseGlobal("", SMLoc(), 0, false, Visibility))
181 case lltok::kw_thread_local: // OptionalThreadLocal
182 case lltok::kw_addrspace: // OptionalAddrSpace
183 case lltok::kw_constant: // GlobalType
184 case lltok::kw_global: // GlobalType
185 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
193 /// ::= 'module' 'asm' STRINGCONSTANT
194 bool LLParser::ParseModuleAsm() {
195 assert(Lex.getKind() == lltok::kw_module);
199 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
200 ParseStringConstant(AsmStr)) return true;
202 const std::string &AsmSoFar = M->getModuleInlineAsm();
203 if (AsmSoFar.empty())
204 M->setModuleInlineAsm(AsmStr);
206 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
211 /// ::= 'target' 'triple' '=' STRINGCONSTANT
212 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
213 bool LLParser::ParseTargetDefinition() {
214 assert(Lex.getKind() == lltok::kw_target);
217 default: return TokError("unknown target property");
218 case lltok::kw_triple:
220 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
221 ParseStringConstant(Str))
223 M->setTargetTriple(Str);
225 case lltok::kw_datalayout:
227 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
228 ParseStringConstant(Str))
230 M->setDataLayout(Str);
236 /// ::= 'deplibs' '=' '[' ']'
237 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
238 bool LLParser::ParseDepLibs() {
239 assert(Lex.getKind() == lltok::kw_deplibs);
241 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
242 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
245 if (EatIfPresent(lltok::rsquare))
249 if (ParseStringConstant(Str)) return true;
252 while (EatIfPresent(lltok::comma)) {
253 if (ParseStringConstant(Str)) return true;
257 return ParseToken(lltok::rsquare, "expected ']' at end of list");
260 /// ParseUnnamedType:
262 /// ::= LocalVarID '=' 'type' type
263 bool LLParser::ParseUnnamedType() {
264 unsigned TypeID = NumberedTypes.size();
266 // Handle the LocalVarID form.
267 if (Lex.getKind() == lltok::LocalVarID) {
268 if (Lex.getUIntVal() != TypeID)
269 return Error(Lex.getLoc(), "type expected to be numbered '%" +
270 utostr(TypeID) + "'");
271 Lex.Lex(); // eat LocalVarID;
273 if (ParseToken(lltok::equal, "expected '=' after name"))
277 assert(Lex.getKind() == lltok::kw_type);
278 LocTy TypeLoc = Lex.getLoc();
279 Lex.Lex(); // eat kw_type
281 PATypeHolder Ty(Type::getVoidTy(Context));
282 if (ParseType(Ty)) return true;
284 // See if this type was previously referenced.
285 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
286 FI = ForwardRefTypeIDs.find(TypeID);
287 if (FI != ForwardRefTypeIDs.end()) {
288 if (FI->second.first.get() == Ty)
289 return Error(TypeLoc, "self referential type is invalid");
291 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
292 Ty = FI->second.first.get();
293 ForwardRefTypeIDs.erase(FI);
296 NumberedTypes.push_back(Ty);
302 /// ::= LocalVar '=' 'type' type
303 bool LLParser::ParseNamedType() {
304 std::string Name = Lex.getStrVal();
305 LocTy NameLoc = Lex.getLoc();
306 Lex.Lex(); // eat LocalVar.
308 PATypeHolder Ty(Type::getVoidTy(Context));
310 if (ParseToken(lltok::equal, "expected '=' after name") ||
311 ParseToken(lltok::kw_type, "expected 'type' after name") ||
315 // Set the type name, checking for conflicts as we do so.
316 bool AlreadyExists = M->addTypeName(Name, Ty);
317 if (!AlreadyExists) return false;
319 // See if this type is a forward reference. We need to eagerly resolve
320 // types to allow recursive type redefinitions below.
321 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
322 FI = ForwardRefTypes.find(Name);
323 if (FI != ForwardRefTypes.end()) {
324 if (FI->second.first.get() == Ty)
325 return Error(NameLoc, "self referential type is invalid");
327 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
328 Ty = FI->second.first.get();
329 ForwardRefTypes.erase(FI);
332 // Inserting a name that is already defined, get the existing name.
333 const Type *Existing = M->getTypeByName(Name);
334 assert(Existing && "Conflict but no matching type?!");
336 // Otherwise, this is an attempt to redefine a type. That's okay if
337 // the redefinition is identical to the original.
338 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
339 if (Existing == Ty) return false;
341 // Any other kind of (non-equivalent) redefinition is an error.
342 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
343 Ty->getDescription() + "'");
348 /// ::= 'declare' FunctionHeader
349 bool LLParser::ParseDeclare() {
350 assert(Lex.getKind() == lltok::kw_declare);
354 return ParseFunctionHeader(F, false);
358 /// ::= 'define' FunctionHeader '{' ...
359 bool LLParser::ParseDefine() {
360 assert(Lex.getKind() == lltok::kw_define);
364 return ParseFunctionHeader(F, true) ||
365 ParseFunctionBody(*F);
371 bool LLParser::ParseGlobalType(bool &IsConstant) {
372 if (Lex.getKind() == lltok::kw_constant)
374 else if (Lex.getKind() == lltok::kw_global)
378 return TokError("expected 'global' or 'constant'");
384 /// ParseUnnamedGlobal:
385 /// OptionalVisibility ALIAS ...
386 /// OptionalLinkage OptionalVisibility ... -> global variable
387 /// GlobalID '=' OptionalVisibility ALIAS ...
388 /// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
389 bool LLParser::ParseUnnamedGlobal() {
390 unsigned VarID = NumberedVals.size();
392 LocTy NameLoc = Lex.getLoc();
394 // Handle the GlobalID form.
395 if (Lex.getKind() == lltok::GlobalID) {
396 if (Lex.getUIntVal() != VarID)
397 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
398 utostr(VarID) + "'");
399 Lex.Lex(); // eat GlobalID;
401 if (ParseToken(lltok::equal, "expected '=' after name"))
406 unsigned Linkage, Visibility;
407 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
408 ParseOptionalVisibility(Visibility))
411 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
412 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
413 return ParseAlias(Name, NameLoc, Visibility);
416 /// ParseNamedGlobal:
417 /// GlobalVar '=' OptionalVisibility ALIAS ...
418 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
419 bool LLParser::ParseNamedGlobal() {
420 assert(Lex.getKind() == lltok::GlobalVar);
421 LocTy NameLoc = Lex.getLoc();
422 std::string Name = Lex.getStrVal();
426 unsigned Linkage, Visibility;
427 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
428 ParseOptionalLinkage(Linkage, HasLinkage) ||
429 ParseOptionalVisibility(Visibility))
432 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
433 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
434 return ParseAlias(Name, NameLoc, Visibility);
438 // ::= '!' STRINGCONSTANT
439 bool LLParser::ParseMDString(MetadataBase *&MDS) {
441 if (ParseStringConstant(Str)) return true;
442 MDS = MDString::get(Context, Str);
447 // ::= '!' MDNodeNumber
448 bool LLParser::ParseMDNode(MetadataBase *&Node) {
449 // !{ ..., !42, ... }
451 if (ParseUInt32(MID)) return true;
453 // Check existing MDNode.
454 std::map<unsigned, MetadataBase *>::iterator I = MetadataCache.find(MID);
455 if (I != MetadataCache.end()) {
460 // Check known forward references.
461 std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
462 FI = ForwardRefMDNodes.find(MID);
463 if (FI != ForwardRefMDNodes.end()) {
464 Node = FI->second.first;
468 // Create MDNode forward reference
469 SmallVector<Value *, 1> Elts;
470 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
471 Elts.push_back(MDString::get(Context, FwdRefName));
472 MDNode *FwdNode = MDNode::get(Context, Elts.data(), Elts.size());
473 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
478 ///ParseNamedMetadata:
479 /// !foo = !{ !1, !2 }
480 bool LLParser::ParseNamedMetadata() {
481 assert(Lex.getKind() == lltok::NamedOrCustomMD);
483 std::string Name = Lex.getStrVal();
485 if (ParseToken(lltok::equal, "expected '=' here"))
488 if (Lex.getKind() != lltok::Metadata)
489 return TokError("Expected '!' here");
492 if (Lex.getKind() != lltok::lbrace)
493 return TokError("Expected '{' here");
495 SmallVector<MetadataBase *, 8> Elts;
497 if (Lex.getKind() != lltok::Metadata)
498 return TokError("Expected '!' here");
501 if (ParseMDNode(N)) return true;
503 } while (EatIfPresent(lltok::comma));
505 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
508 NamedMDNode::Create(Context, Name, Elts.data(), Elts.size(), M);
512 /// ParseStandaloneMetadata:
514 bool LLParser::ParseStandaloneMetadata() {
515 assert(Lex.getKind() == lltok::Metadata);
517 unsigned MetadataID = 0;
518 if (ParseUInt32(MetadataID))
520 if (MetadataCache.find(MetadataID) != MetadataCache.end())
521 return TokError("Metadata id is already used");
522 if (ParseToken(lltok::equal, "expected '=' here"))
526 PATypeHolder Ty(Type::getVoidTy(Context));
527 if (ParseType(Ty, TyLoc))
530 if (Lex.getKind() != lltok::Metadata)
531 return TokError("Expected metadata here");
534 if (Lex.getKind() != lltok::lbrace)
535 return TokError("Expected '{' here");
537 SmallVector<Value *, 16> Elts;
538 if (ParseMDNodeVector(Elts)
539 || ParseToken(lltok::rbrace, "expected end of metadata node"))
542 MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
543 MetadataCache[MetadataID] = Init;
544 std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
545 FI = ForwardRefMDNodes.find(MetadataID);
546 if (FI != ForwardRefMDNodes.end()) {
547 MDNode *FwdNode = cast<MDNode>(FI->second.first);
548 FwdNode->replaceAllUsesWith(Init);
549 ForwardRefMDNodes.erase(FI);
556 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
559 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
560 /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
562 /// Everything through visibility has already been parsed.
564 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
565 unsigned Visibility) {
566 assert(Lex.getKind() == lltok::kw_alias);
569 LocTy LinkageLoc = Lex.getLoc();
570 if (ParseOptionalLinkage(Linkage))
573 if (Linkage != GlobalValue::ExternalLinkage &&
574 Linkage != GlobalValue::WeakAnyLinkage &&
575 Linkage != GlobalValue::WeakODRLinkage &&
576 Linkage != GlobalValue::InternalLinkage &&
577 Linkage != GlobalValue::PrivateLinkage &&
578 Linkage != GlobalValue::LinkerPrivateLinkage)
579 return Error(LinkageLoc, "invalid linkage type for alias");
582 LocTy AliaseeLoc = Lex.getLoc();
583 if (Lex.getKind() != lltok::kw_bitcast &&
584 Lex.getKind() != lltok::kw_getelementptr) {
585 if (ParseGlobalTypeAndValue(Aliasee)) return true;
587 // The bitcast dest type is not present, it is implied by the dest type.
589 if (ParseValID(ID)) return true;
590 if (ID.Kind != ValID::t_Constant)
591 return Error(AliaseeLoc, "invalid aliasee");
592 Aliasee = ID.ConstantVal;
595 if (!isa<PointerType>(Aliasee->getType()))
596 return Error(AliaseeLoc, "alias must have pointer type");
598 // Okay, create the alias but do not insert it into the module yet.
599 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
600 (GlobalValue::LinkageTypes)Linkage, Name,
602 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
604 // See if this value already exists in the symbol table. If so, it is either
605 // a redefinition or a definition of a forward reference.
606 if (GlobalValue *Val = M->getNamedValue(Name)) {
607 // See if this was a redefinition. If so, there is no entry in
609 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
610 I = ForwardRefVals.find(Name);
611 if (I == ForwardRefVals.end())
612 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
614 // Otherwise, this was a definition of forward ref. Verify that types
616 if (Val->getType() != GA->getType())
617 return Error(NameLoc,
618 "forward reference and definition of alias have different types");
620 // If they agree, just RAUW the old value with the alias and remove the
622 Val->replaceAllUsesWith(GA);
623 Val->eraseFromParent();
624 ForwardRefVals.erase(I);
627 // Insert into the module, we know its name won't collide now.
628 M->getAliasList().push_back(GA);
629 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
635 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
636 /// OptionalAddrSpace GlobalType Type Const
637 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
638 /// OptionalAddrSpace GlobalType Type Const
640 /// Everything through visibility has been parsed already.
642 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
643 unsigned Linkage, bool HasLinkage,
644 unsigned Visibility) {
646 bool ThreadLocal, IsConstant;
649 PATypeHolder Ty(Type::getVoidTy(Context));
650 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
651 ParseOptionalAddrSpace(AddrSpace) ||
652 ParseGlobalType(IsConstant) ||
653 ParseType(Ty, TyLoc))
656 // If the linkage is specified and is external, then no initializer is
659 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
660 Linkage != GlobalValue::ExternalWeakLinkage &&
661 Linkage != GlobalValue::ExternalLinkage)) {
662 if (ParseGlobalValue(Ty, Init))
666 if (isa<FunctionType>(Ty) || Ty->isLabelTy())
667 return Error(TyLoc, "invalid type for global variable");
669 GlobalVariable *GV = 0;
671 // See if the global was forward referenced, if so, use the global.
673 if (GlobalValue *GVal = M->getNamedValue(Name)) {
674 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
675 return Error(NameLoc, "redefinition of global '@" + Name + "'");
676 GV = cast<GlobalVariable>(GVal);
679 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
680 I = ForwardRefValIDs.find(NumberedVals.size());
681 if (I != ForwardRefValIDs.end()) {
682 GV = cast<GlobalVariable>(I->second.first);
683 ForwardRefValIDs.erase(I);
688 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
689 Name, 0, false, AddrSpace);
691 if (GV->getType()->getElementType() != Ty)
693 "forward reference and definition of global have different types");
695 // Move the forward-reference to the correct spot in the module.
696 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
700 NumberedVals.push_back(GV);
702 // Set the parsed properties on the global.
704 GV->setInitializer(Init);
705 GV->setConstant(IsConstant);
706 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
707 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
708 GV->setThreadLocal(ThreadLocal);
710 // Parse attributes on the global.
711 while (Lex.getKind() == lltok::comma) {
714 if (Lex.getKind() == lltok::kw_section) {
716 GV->setSection(Lex.getStrVal());
717 if (ParseToken(lltok::StringConstant, "expected global section string"))
719 } else if (Lex.getKind() == lltok::kw_align) {
721 if (ParseOptionalAlignment(Alignment)) return true;
722 GV->setAlignment(Alignment);
724 TokError("unknown global variable property!");
732 //===----------------------------------------------------------------------===//
733 // GlobalValue Reference/Resolution Routines.
734 //===----------------------------------------------------------------------===//
736 /// GetGlobalVal - Get a value with the specified name or ID, creating a
737 /// forward reference record if needed. This can return null if the value
738 /// exists but does not have the right type.
739 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
741 const PointerType *PTy = dyn_cast<PointerType>(Ty);
743 Error(Loc, "global variable reference must have pointer type");
747 // Look this name up in the normal function symbol table.
749 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
751 // If this is a forward reference for the value, see if we already created a
752 // forward ref record.
754 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
755 I = ForwardRefVals.find(Name);
756 if (I != ForwardRefVals.end())
757 Val = I->second.first;
760 // If we have the value in the symbol table or fwd-ref table, return it.
762 if (Val->getType() == Ty) return Val;
763 Error(Loc, "'@" + Name + "' defined with type '" +
764 Val->getType()->getDescription() + "'");
768 // Otherwise, create a new forward reference for this value and remember it.
770 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
771 // Function types can return opaque but functions can't.
772 if (isa<OpaqueType>(FT->getReturnType())) {
773 Error(Loc, "function may not return opaque type");
777 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
779 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
780 GlobalValue::ExternalWeakLinkage, 0, Name);
783 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
787 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
788 const PointerType *PTy = dyn_cast<PointerType>(Ty);
790 Error(Loc, "global variable reference must have pointer type");
794 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
796 // If this is a forward reference for the value, see if we already created a
797 // forward ref record.
799 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
800 I = ForwardRefValIDs.find(ID);
801 if (I != ForwardRefValIDs.end())
802 Val = I->second.first;
805 // If we have the value in the symbol table or fwd-ref table, return it.
807 if (Val->getType() == Ty) return Val;
808 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
809 Val->getType()->getDescription() + "'");
813 // Otherwise, create a new forward reference for this value and remember it.
815 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
816 // Function types can return opaque but functions can't.
817 if (isa<OpaqueType>(FT->getReturnType())) {
818 Error(Loc, "function may not return opaque type");
821 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
823 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
824 GlobalValue::ExternalWeakLinkage, 0, "");
827 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
832 //===----------------------------------------------------------------------===//
834 //===----------------------------------------------------------------------===//
836 /// ParseToken - If the current token has the specified kind, eat it and return
837 /// success. Otherwise, emit the specified error and return failure.
838 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
839 if (Lex.getKind() != T)
840 return TokError(ErrMsg);
845 /// ParseStringConstant
846 /// ::= StringConstant
847 bool LLParser::ParseStringConstant(std::string &Result) {
848 if (Lex.getKind() != lltok::StringConstant)
849 return TokError("expected string constant");
850 Result = Lex.getStrVal();
857 bool LLParser::ParseUInt32(unsigned &Val) {
858 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
859 return TokError("expected integer");
860 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
861 if (Val64 != unsigned(Val64))
862 return TokError("expected 32-bit integer (too large)");
869 /// ParseOptionalAddrSpace
871 /// := 'addrspace' '(' uint32 ')'
872 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
874 if (!EatIfPresent(lltok::kw_addrspace))
876 return ParseToken(lltok::lparen, "expected '(' in address space") ||
877 ParseUInt32(AddrSpace) ||
878 ParseToken(lltok::rparen, "expected ')' in address space");
881 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
882 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
883 /// 2: function attr.
884 /// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
885 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
886 Attrs = Attribute::None;
887 LocTy AttrLoc = Lex.getLoc();
890 switch (Lex.getKind()) {
893 // Treat these as signext/zeroext if they occur in the argument list after
894 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
895 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
897 // FIXME: REMOVE THIS IN LLVM 3.0
899 if (Lex.getKind() == lltok::kw_sext)
900 Attrs |= Attribute::SExt;
902 Attrs |= Attribute::ZExt;
906 default: // End of attributes.
907 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
908 return Error(AttrLoc, "invalid use of function-only attribute");
910 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
911 return Error(AttrLoc, "invalid use of parameter-only attribute");
914 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
915 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
916 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
917 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
918 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
919 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
920 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
921 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
923 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
924 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
925 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
926 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
927 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
928 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
929 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
930 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
931 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
932 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
933 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
934 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
935 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
937 case lltok::kw_align: {
939 if (ParseOptionalAlignment(Alignment))
941 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
949 /// ParseOptionalLinkage
952 /// ::= 'linker_private'
957 /// ::= 'linkonce_odr'
962 /// ::= 'extern_weak'
964 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
966 switch (Lex.getKind()) {
967 default: Res=GlobalValue::ExternalLinkage; return false;
968 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
969 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
970 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
971 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
972 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
973 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
974 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
975 case lltok::kw_available_externally:
976 Res = GlobalValue::AvailableExternallyLinkage;
978 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
979 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
980 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
981 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
982 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
983 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
990 /// ParseOptionalVisibility
996 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
997 switch (Lex.getKind()) {
998 default: Res = GlobalValue::DefaultVisibility; return false;
999 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1000 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1001 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1007 /// ParseOptionalCallingConv
1012 /// ::= 'x86_stdcallcc'
1013 /// ::= 'x86_fastcallcc'
1014 /// ::= 'arm_apcscc'
1015 /// ::= 'arm_aapcscc'
1016 /// ::= 'arm_aapcs_vfpcc'
1019 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1020 switch (Lex.getKind()) {
1021 default: CC = CallingConv::C; return false;
1022 case lltok::kw_ccc: CC = CallingConv::C; break;
1023 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1024 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1025 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1026 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1027 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1028 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1029 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1030 case lltok::kw_cc: {
1031 unsigned ArbitraryCC;
1033 if (ParseUInt32(ArbitraryCC)) {
1036 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1046 /// ParseOptionalCustomMetadata
1049 bool LLParser::ParseOptionalCustomMetadata() {
1050 if (Lex.getKind() != lltok::NamedOrCustomMD)
1053 std::string Name = Lex.getStrVal();
1056 if (Lex.getKind() != lltok::Metadata)
1057 return TokError("Expected '!' here");
1061 if (ParseMDNode(Node)) return true;
1063 MetadataContext &TheMetadata = M->getContext().getMetadata();
1064 unsigned MDK = TheMetadata.getMDKind(Name.c_str());
1066 MDK = TheMetadata.registerMDKind(Name.c_str());
1067 MDsOnInst.push_back(std::make_pair(MDK, cast<MDNode>(Node)));
1072 /// ParseOptionalAlignment
1075 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1077 if (!EatIfPresent(lltok::kw_align))
1079 LocTy AlignLoc = Lex.getLoc();
1080 if (ParseUInt32(Alignment)) return true;
1081 if (!isPowerOf2_32(Alignment))
1082 return Error(AlignLoc, "alignment is not a power of two");
1086 /// ParseOptionalInfo
1087 /// ::= OptionalInfo (',' OptionalInfo)+
1088 bool LLParser::ParseOptionalInfo(unsigned &Alignment) {
1090 // FIXME: Handle customized metadata info attached with an instruction.
1092 if (Lex.getKind() == lltok::NamedOrCustomMD) {
1093 if (ParseOptionalCustomMetadata()) return true;
1094 } else if (Lex.getKind() == lltok::kw_align) {
1095 if (ParseOptionalAlignment(Alignment)) return true;
1098 } while (EatIfPresent(lltok::comma));
1105 /// ::= (',' uint32)+
1106 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
1107 if (Lex.getKind() != lltok::comma)
1108 return TokError("expected ',' as start of index list");
1110 while (EatIfPresent(lltok::comma)) {
1112 if (ParseUInt32(Idx)) return true;
1113 Indices.push_back(Idx);
1119 //===----------------------------------------------------------------------===//
1121 //===----------------------------------------------------------------------===//
1123 /// ParseType - Parse and resolve a full type.
1124 bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1125 LocTy TypeLoc = Lex.getLoc();
1126 if (ParseTypeRec(Result)) return true;
1128 // Verify no unresolved uprefs.
1129 if (!UpRefs.empty())
1130 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
1132 if (!AllowVoid && Result.get()->isVoidTy())
1133 return Error(TypeLoc, "void type only allowed for function results");
1138 /// HandleUpRefs - Every time we finish a new layer of types, this function is
1139 /// called. It loops through the UpRefs vector, which is a list of the
1140 /// currently active types. For each type, if the up-reference is contained in
1141 /// the newly completed type, we decrement the level count. When the level
1142 /// count reaches zero, the up-referenced type is the type that is passed in:
1143 /// thus we can complete the cycle.
1145 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1146 // If Ty isn't abstract, or if there are no up-references in it, then there is
1147 // nothing to resolve here.
1148 if (!ty->isAbstract() || UpRefs.empty()) return ty;
1150 PATypeHolder Ty(ty);
1152 errs() << "Type '" << Ty->getDescription()
1153 << "' newly formed. Resolving upreferences.\n"
1154 << UpRefs.size() << " upreferences active!\n";
1157 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1158 // to zero), we resolve them all together before we resolve them to Ty. At
1159 // the end of the loop, if there is anything to resolve to Ty, it will be in
1161 OpaqueType *TypeToResolve = 0;
1163 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1164 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1166 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1167 UpRefs[i].LastContainedTy) != Ty->subtype_end();
1170 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1171 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1172 << (ContainsType ? "true" : "false")
1173 << " level=" << UpRefs[i].NestingLevel << "\n";
1178 // Decrement level of upreference
1179 unsigned Level = --UpRefs[i].NestingLevel;
1180 UpRefs[i].LastContainedTy = Ty;
1182 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1187 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1190 TypeToResolve = UpRefs[i].UpRefTy;
1192 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1193 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1194 --i; // Do not skip the next element.
1198 TypeToResolve->refineAbstractTypeTo(Ty);
1204 /// ParseTypeRec - The recursive function used to process the internal
1205 /// implementation details of types.
1206 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1207 switch (Lex.getKind()) {
1209 return TokError("expected type");
1211 // TypeRec ::= 'float' | 'void' (etc)
1212 Result = Lex.getTyVal();
1215 case lltok::kw_opaque:
1216 // TypeRec ::= 'opaque'
1217 Result = OpaqueType::get(Context);
1221 // TypeRec ::= '{' ... '}'
1222 if (ParseStructType(Result, false))
1225 case lltok::lsquare:
1226 // TypeRec ::= '[' ... ']'
1227 Lex.Lex(); // eat the lsquare.
1228 if (ParseArrayVectorType(Result, false))
1231 case lltok::less: // Either vector or packed struct.
1232 // TypeRec ::= '<' ... '>'
1234 if (Lex.getKind() == lltok::lbrace) {
1235 if (ParseStructType(Result, true) ||
1236 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1238 } else if (ParseArrayVectorType(Result, true))
1241 case lltok::LocalVar:
1242 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1244 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1247 Result = OpaqueType::get(Context);
1248 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1249 std::make_pair(Result,
1251 M->addTypeName(Lex.getStrVal(), Result.get());
1256 case lltok::LocalVarID:
1258 if (Lex.getUIntVal() < NumberedTypes.size())
1259 Result = NumberedTypes[Lex.getUIntVal()];
1261 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1262 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1263 if (I != ForwardRefTypeIDs.end())
1264 Result = I->second.first;
1266 Result = OpaqueType::get(Context);
1267 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1268 std::make_pair(Result,
1274 case lltok::backslash: {
1275 // TypeRec ::= '\' 4
1278 if (ParseUInt32(Val)) return true;
1279 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
1280 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1286 // Parse the type suffixes.
1288 switch (Lex.getKind()) {
1290 default: return false;
1292 // TypeRec ::= TypeRec '*'
1294 if (Result.get()->isLabelTy())
1295 return TokError("basic block pointers are invalid");
1296 if (Result.get()->isVoidTy())
1297 return TokError("pointers to void are invalid; use i8* instead");
1298 if (!PointerType::isValidElementType(Result.get()))
1299 return TokError("pointer to this type is invalid");
1300 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1304 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1305 case lltok::kw_addrspace: {
1306 if (Result.get()->isLabelTy())
1307 return TokError("basic block pointers are invalid");
1308 if (Result.get()->isVoidTy())
1309 return TokError("pointers to void are invalid; use i8* instead");
1310 if (!PointerType::isValidElementType(Result.get()))
1311 return TokError("pointer to this type is invalid");
1313 if (ParseOptionalAddrSpace(AddrSpace) ||
1314 ParseToken(lltok::star, "expected '*' in address space"))
1317 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1321 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1323 if (ParseFunctionType(Result))
1330 /// ParseParameterList
1332 /// ::= '(' Arg (',' Arg)* ')'
1334 /// ::= Type OptionalAttributes Value OptionalAttributes
1335 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1336 PerFunctionState &PFS) {
1337 if (ParseToken(lltok::lparen, "expected '(' in call"))
1340 while (Lex.getKind() != lltok::rparen) {
1341 // If this isn't the first argument, we need a comma.
1342 if (!ArgList.empty() &&
1343 ParseToken(lltok::comma, "expected ',' in argument list"))
1346 // Parse the argument.
1348 PATypeHolder ArgTy(Type::getVoidTy(Context));
1349 unsigned ArgAttrs1, ArgAttrs2;
1351 if (ParseType(ArgTy, ArgLoc) ||
1352 ParseOptionalAttrs(ArgAttrs1, 0) ||
1353 ParseValue(ArgTy, V, PFS) ||
1354 // FIXME: Should not allow attributes after the argument, remove this in
1356 ParseOptionalAttrs(ArgAttrs2, 3))
1358 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1361 Lex.Lex(); // Lex the ')'.
1367 /// ParseArgumentList - Parse the argument list for a function type or function
1368 /// prototype. If 'inType' is true then we are parsing a FunctionType.
1369 /// ::= '(' ArgTypeListI ')'
1373 /// ::= ArgTypeList ',' '...'
1374 /// ::= ArgType (',' ArgType)*
1376 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1377 bool &isVarArg, bool inType) {
1379 assert(Lex.getKind() == lltok::lparen);
1380 Lex.Lex(); // eat the (.
1382 if (Lex.getKind() == lltok::rparen) {
1384 } else if (Lex.getKind() == lltok::dotdotdot) {
1388 LocTy TypeLoc = Lex.getLoc();
1389 PATypeHolder ArgTy(Type::getVoidTy(Context));
1393 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1394 // types (such as a function returning a pointer to itself). If parsing a
1395 // function prototype, we require fully resolved types.
1396 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1397 ParseOptionalAttrs(Attrs, 0)) return true;
1399 if (ArgTy->isVoidTy())
1400 return Error(TypeLoc, "argument can not have void type");
1402 if (Lex.getKind() == lltok::LocalVar ||
1403 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1404 Name = Lex.getStrVal();
1408 if (!FunctionType::isValidArgumentType(ArgTy))
1409 return Error(TypeLoc, "invalid type for function argument");
1411 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1413 while (EatIfPresent(lltok::comma)) {
1414 // Handle ... at end of arg list.
1415 if (EatIfPresent(lltok::dotdotdot)) {
1420 // Otherwise must be an argument type.
1421 TypeLoc = Lex.getLoc();
1422 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1423 ParseOptionalAttrs(Attrs, 0)) return true;
1425 if (ArgTy->isVoidTy())
1426 return Error(TypeLoc, "argument can not have void type");
1428 if (Lex.getKind() == lltok::LocalVar ||
1429 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1430 Name = Lex.getStrVal();
1436 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1437 return Error(TypeLoc, "invalid type for function argument");
1439 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1443 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1446 /// ParseFunctionType
1447 /// ::= Type ArgumentList OptionalAttrs
1448 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1449 assert(Lex.getKind() == lltok::lparen);
1451 if (!FunctionType::isValidReturnType(Result))
1452 return TokError("invalid function return type");
1454 std::vector<ArgInfo> ArgList;
1457 if (ParseArgumentList(ArgList, isVarArg, true) ||
1458 // FIXME: Allow, but ignore attributes on function types!
1459 // FIXME: Remove in LLVM 3.0
1460 ParseOptionalAttrs(Attrs, 2))
1463 // Reject names on the arguments lists.
1464 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1465 if (!ArgList[i].Name.empty())
1466 return Error(ArgList[i].Loc, "argument name invalid in function type");
1467 if (!ArgList[i].Attrs != 0) {
1468 // Allow but ignore attributes on function types; this permits
1470 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1474 std::vector<const Type*> ArgListTy;
1475 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1476 ArgListTy.push_back(ArgList[i].Type);
1478 Result = HandleUpRefs(FunctionType::get(Result.get(),
1479 ArgListTy, isVarArg));
1483 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1486 /// ::= '{' TypeRec (',' TypeRec)* '}'
1487 /// ::= '<' '{' '}' '>'
1488 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1489 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1490 assert(Lex.getKind() == lltok::lbrace);
1491 Lex.Lex(); // Consume the '{'
1493 if (EatIfPresent(lltok::rbrace)) {
1494 Result = StructType::get(Context, Packed);
1498 std::vector<PATypeHolder> ParamsList;
1499 LocTy EltTyLoc = Lex.getLoc();
1500 if (ParseTypeRec(Result)) return true;
1501 ParamsList.push_back(Result);
1503 if (Result->isVoidTy())
1504 return Error(EltTyLoc, "struct element can not have void type");
1505 if (!StructType::isValidElementType(Result))
1506 return Error(EltTyLoc, "invalid element type for struct");
1508 while (EatIfPresent(lltok::comma)) {
1509 EltTyLoc = Lex.getLoc();
1510 if (ParseTypeRec(Result)) return true;
1512 if (Result->isVoidTy())
1513 return Error(EltTyLoc, "struct element can not have void type");
1514 if (!StructType::isValidElementType(Result))
1515 return Error(EltTyLoc, "invalid element type for struct");
1517 ParamsList.push_back(Result);
1520 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1523 std::vector<const Type*> ParamsListTy;
1524 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1525 ParamsListTy.push_back(ParamsList[i].get());
1526 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
1530 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1531 /// token has already been consumed.
1533 /// ::= '[' APSINTVAL 'x' Types ']'
1534 /// ::= '<' APSINTVAL 'x' Types '>'
1535 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1536 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1537 Lex.getAPSIntVal().getBitWidth() > 64)
1538 return TokError("expected number in address space");
1540 LocTy SizeLoc = Lex.getLoc();
1541 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1544 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1547 LocTy TypeLoc = Lex.getLoc();
1548 PATypeHolder EltTy(Type::getVoidTy(Context));
1549 if (ParseTypeRec(EltTy)) return true;
1551 if (EltTy->isVoidTy())
1552 return Error(TypeLoc, "array and vector element type cannot be void");
1554 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1555 "expected end of sequential type"))
1560 return Error(SizeLoc, "zero element vector is illegal");
1561 if ((unsigned)Size != Size)
1562 return Error(SizeLoc, "size too large for vector");
1563 if (!VectorType::isValidElementType(EltTy))
1564 return Error(TypeLoc, "vector element type must be fp or integer");
1565 Result = VectorType::get(EltTy, unsigned(Size));
1567 if (!ArrayType::isValidElementType(EltTy))
1568 return Error(TypeLoc, "invalid array element type");
1569 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1574 //===----------------------------------------------------------------------===//
1575 // Function Semantic Analysis.
1576 //===----------------------------------------------------------------------===//
1578 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1581 // Insert unnamed arguments into the NumberedVals list.
1582 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1585 NumberedVals.push_back(AI);
1588 LLParser::PerFunctionState::~PerFunctionState() {
1589 // If there were any forward referenced non-basicblock values, delete them.
1590 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1591 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1592 if (!isa<BasicBlock>(I->second.first)) {
1593 I->second.first->replaceAllUsesWith(
1594 UndefValue::get(I->second.first->getType()));
1595 delete I->second.first;
1596 I->second.first = 0;
1599 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1600 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1601 if (!isa<BasicBlock>(I->second.first)) {
1602 I->second.first->replaceAllUsesWith(
1603 UndefValue::get(I->second.first->getType()));
1604 delete I->second.first;
1605 I->second.first = 0;
1609 bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1610 if (!ForwardRefVals.empty())
1611 return P.Error(ForwardRefVals.begin()->second.second,
1612 "use of undefined value '%" + ForwardRefVals.begin()->first +
1614 if (!ForwardRefValIDs.empty())
1615 return P.Error(ForwardRefValIDs.begin()->second.second,
1616 "use of undefined value '%" +
1617 utostr(ForwardRefValIDs.begin()->first) + "'");
1622 /// GetVal - Get a value with the specified name or ID, creating a
1623 /// forward reference record if needed. This can return null if the value
1624 /// exists but does not have the right type.
1625 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1626 const Type *Ty, LocTy Loc) {
1627 // Look this name up in the normal function symbol table.
1628 Value *Val = F.getValueSymbolTable().lookup(Name);
1630 // If this is a forward reference for the value, see if we already created a
1631 // forward ref record.
1633 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1634 I = ForwardRefVals.find(Name);
1635 if (I != ForwardRefVals.end())
1636 Val = I->second.first;
1639 // If we have the value in the symbol table or fwd-ref table, return it.
1641 if (Val->getType() == Ty) return Val;
1642 if (Ty->isLabelTy())
1643 P.Error(Loc, "'%" + Name + "' is not a basic block");
1645 P.Error(Loc, "'%" + Name + "' defined with type '" +
1646 Val->getType()->getDescription() + "'");
1650 // Don't make placeholders with invalid type.
1651 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1652 Ty != Type::getLabelTy(F.getContext())) {
1653 P.Error(Loc, "invalid use of a non-first-class type");
1657 // Otherwise, create a new forward reference for this value and remember it.
1659 if (Ty->isLabelTy())
1660 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
1662 FwdVal = new Argument(Ty, Name);
1664 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1668 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1670 // Look this name up in the normal function symbol table.
1671 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1673 // If this is a forward reference for the value, see if we already created a
1674 // forward ref record.
1676 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1677 I = ForwardRefValIDs.find(ID);
1678 if (I != ForwardRefValIDs.end())
1679 Val = I->second.first;
1682 // If we have the value in the symbol table or fwd-ref table, return it.
1684 if (Val->getType() == Ty) return Val;
1685 if (Ty->isLabelTy())
1686 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1688 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1689 Val->getType()->getDescription() + "'");
1693 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1694 Ty != Type::getLabelTy(F.getContext())) {
1695 P.Error(Loc, "invalid use of a non-first-class type");
1699 // Otherwise, create a new forward reference for this value and remember it.
1701 if (Ty->isLabelTy())
1702 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
1704 FwdVal = new Argument(Ty);
1706 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1710 /// SetInstName - After an instruction is parsed and inserted into its
1711 /// basic block, this installs its name.
1712 bool LLParser::PerFunctionState::SetInstName(int NameID,
1713 const std::string &NameStr,
1714 LocTy NameLoc, Instruction *Inst) {
1715 // If this instruction has void type, it cannot have a name or ID specified.
1716 if (Inst->getType()->isVoidTy()) {
1717 if (NameID != -1 || !NameStr.empty())
1718 return P.Error(NameLoc, "instructions returning void cannot have a name");
1722 // If this was a numbered instruction, verify that the instruction is the
1723 // expected value and resolve any forward references.
1724 if (NameStr.empty()) {
1725 // If neither a name nor an ID was specified, just use the next ID.
1727 NameID = NumberedVals.size();
1729 if (unsigned(NameID) != NumberedVals.size())
1730 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1731 utostr(NumberedVals.size()) + "'");
1733 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1734 ForwardRefValIDs.find(NameID);
1735 if (FI != ForwardRefValIDs.end()) {
1736 if (FI->second.first->getType() != Inst->getType())
1737 return P.Error(NameLoc, "instruction forward referenced with type '" +
1738 FI->second.first->getType()->getDescription() + "'");
1739 FI->second.first->replaceAllUsesWith(Inst);
1740 delete FI->second.first;
1741 ForwardRefValIDs.erase(FI);
1744 NumberedVals.push_back(Inst);
1748 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1749 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1750 FI = ForwardRefVals.find(NameStr);
1751 if (FI != ForwardRefVals.end()) {
1752 if (FI->second.first->getType() != Inst->getType())
1753 return P.Error(NameLoc, "instruction forward referenced with type '" +
1754 FI->second.first->getType()->getDescription() + "'");
1755 FI->second.first->replaceAllUsesWith(Inst);
1756 delete FI->second.first;
1757 ForwardRefVals.erase(FI);
1760 // Set the name on the instruction.
1761 Inst->setName(NameStr);
1763 if (Inst->getNameStr() != NameStr)
1764 return P.Error(NameLoc, "multiple definition of local value named '" +
1769 /// GetBB - Get a basic block with the specified name or ID, creating a
1770 /// forward reference record if needed.
1771 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1773 return cast_or_null<BasicBlock>(GetVal(Name,
1774 Type::getLabelTy(F.getContext()), Loc));
1777 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1778 return cast_or_null<BasicBlock>(GetVal(ID,
1779 Type::getLabelTy(F.getContext()), Loc));
1782 /// DefineBB - Define the specified basic block, which is either named or
1783 /// unnamed. If there is an error, this returns null otherwise it returns
1784 /// the block being defined.
1785 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1789 BB = GetBB(NumberedVals.size(), Loc);
1791 BB = GetBB(Name, Loc);
1792 if (BB == 0) return 0; // Already diagnosed error.
1794 // Move the block to the end of the function. Forward ref'd blocks are
1795 // inserted wherever they happen to be referenced.
1796 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1798 // Remove the block from forward ref sets.
1800 ForwardRefValIDs.erase(NumberedVals.size());
1801 NumberedVals.push_back(BB);
1803 // BB forward references are already in the function symbol table.
1804 ForwardRefVals.erase(Name);
1810 //===----------------------------------------------------------------------===//
1812 //===----------------------------------------------------------------------===//
1814 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1815 /// type implied. For example, if we parse "4" we don't know what integer type
1816 /// it has. The value will later be combined with its type and checked for
1818 bool LLParser::ParseValID(ValID &ID) {
1819 ID.Loc = Lex.getLoc();
1820 switch (Lex.getKind()) {
1821 default: return TokError("expected value token");
1822 case lltok::GlobalID: // @42
1823 ID.UIntVal = Lex.getUIntVal();
1824 ID.Kind = ValID::t_GlobalID;
1826 case lltok::GlobalVar: // @foo
1827 ID.StrVal = Lex.getStrVal();
1828 ID.Kind = ValID::t_GlobalName;
1830 case lltok::LocalVarID: // %42
1831 ID.UIntVal = Lex.getUIntVal();
1832 ID.Kind = ValID::t_LocalID;
1834 case lltok::LocalVar: // %foo
1835 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1836 ID.StrVal = Lex.getStrVal();
1837 ID.Kind = ValID::t_LocalName;
1839 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
1840 ID.Kind = ValID::t_Metadata;
1842 if (Lex.getKind() == lltok::lbrace) {
1843 SmallVector<Value*, 16> Elts;
1844 if (ParseMDNodeVector(Elts) ||
1845 ParseToken(lltok::rbrace, "expected end of metadata node"))
1848 ID.MetadataVal = MDNode::get(Context, Elts.data(), Elts.size());
1852 // Standalone metadata reference
1853 // !{ ..., !42, ... }
1854 if (!ParseMDNode(ID.MetadataVal))
1858 // ::= '!' STRINGCONSTANT
1859 if (ParseMDString(ID.MetadataVal)) return true;
1860 ID.Kind = ValID::t_Metadata;
1864 ID.APSIntVal = Lex.getAPSIntVal();
1865 ID.Kind = ValID::t_APSInt;
1867 case lltok::APFloat:
1868 ID.APFloatVal = Lex.getAPFloatVal();
1869 ID.Kind = ValID::t_APFloat;
1871 case lltok::kw_true:
1872 ID.ConstantVal = ConstantInt::getTrue(Context);
1873 ID.Kind = ValID::t_Constant;
1875 case lltok::kw_false:
1876 ID.ConstantVal = ConstantInt::getFalse(Context);
1877 ID.Kind = ValID::t_Constant;
1879 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1880 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1881 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1883 case lltok::lbrace: {
1884 // ValID ::= '{' ConstVector '}'
1886 SmallVector<Constant*, 16> Elts;
1887 if (ParseGlobalValueVector(Elts) ||
1888 ParseToken(lltok::rbrace, "expected end of struct constant"))
1891 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
1892 Elts.size(), false);
1893 ID.Kind = ValID::t_Constant;
1897 // ValID ::= '<' ConstVector '>' --> Vector.
1898 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1900 bool isPackedStruct = EatIfPresent(lltok::lbrace);
1902 SmallVector<Constant*, 16> Elts;
1903 LocTy FirstEltLoc = Lex.getLoc();
1904 if (ParseGlobalValueVector(Elts) ||
1906 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1907 ParseToken(lltok::greater, "expected end of constant"))
1910 if (isPackedStruct) {
1912 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
1913 ID.Kind = ValID::t_Constant;
1918 return Error(ID.Loc, "constant vector must not be empty");
1920 if (!Elts[0]->getType()->isInteger() &&
1921 !Elts[0]->getType()->isFloatingPoint())
1922 return Error(FirstEltLoc,
1923 "vector elements must have integer or floating point type");
1925 // Verify that all the vector elements have the same type.
1926 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1927 if (Elts[i]->getType() != Elts[0]->getType())
1928 return Error(FirstEltLoc,
1929 "vector element #" + utostr(i) +
1930 " is not of type '" + Elts[0]->getType()->getDescription());
1932 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
1933 ID.Kind = ValID::t_Constant;
1936 case lltok::lsquare: { // Array Constant
1938 SmallVector<Constant*, 16> Elts;
1939 LocTy FirstEltLoc = Lex.getLoc();
1940 if (ParseGlobalValueVector(Elts) ||
1941 ParseToken(lltok::rsquare, "expected end of array constant"))
1944 // Handle empty element.
1946 // Use undef instead of an array because it's inconvenient to determine
1947 // the element type at this point, there being no elements to examine.
1948 ID.Kind = ValID::t_EmptyArray;
1952 if (!Elts[0]->getType()->isFirstClassType())
1953 return Error(FirstEltLoc, "invalid array element type: " +
1954 Elts[0]->getType()->getDescription());
1956 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
1958 // Verify all elements are correct type!
1959 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
1960 if (Elts[i]->getType() != Elts[0]->getType())
1961 return Error(FirstEltLoc,
1962 "array element #" + utostr(i) +
1963 " is not of type '" +Elts[0]->getType()->getDescription());
1966 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
1967 ID.Kind = ValID::t_Constant;
1970 case lltok::kw_c: // c "foo"
1972 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
1973 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1974 ID.Kind = ValID::t_Constant;
1977 case lltok::kw_asm: {
1978 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
1979 bool HasSideEffect, AlignStack;
1981 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
1982 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
1983 ParseStringConstant(ID.StrVal) ||
1984 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
1985 ParseToken(lltok::StringConstant, "expected constraint string"))
1987 ID.StrVal2 = Lex.getStrVal();
1988 ID.UIntVal = HasSideEffect | ((unsigned)AlignStack<<1);
1989 ID.Kind = ValID::t_InlineAsm;
1993 case lltok::kw_trunc:
1994 case lltok::kw_zext:
1995 case lltok::kw_sext:
1996 case lltok::kw_fptrunc:
1997 case lltok::kw_fpext:
1998 case lltok::kw_bitcast:
1999 case lltok::kw_uitofp:
2000 case lltok::kw_sitofp:
2001 case lltok::kw_fptoui:
2002 case lltok::kw_fptosi:
2003 case lltok::kw_inttoptr:
2004 case lltok::kw_ptrtoint: {
2005 unsigned Opc = Lex.getUIntVal();
2006 PATypeHolder DestTy(Type::getVoidTy(Context));
2009 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2010 ParseGlobalTypeAndValue(SrcVal) ||
2011 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2012 ParseType(DestTy) ||
2013 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2015 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2016 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2017 SrcVal->getType()->getDescription() + "' to '" +
2018 DestTy->getDescription() + "'");
2019 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2021 ID.Kind = ValID::t_Constant;
2024 case lltok::kw_extractvalue: {
2027 SmallVector<unsigned, 4> Indices;
2028 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2029 ParseGlobalTypeAndValue(Val) ||
2030 ParseIndexList(Indices) ||
2031 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2033 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
2034 return Error(ID.Loc, "extractvalue operand must be array or struct");
2035 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2037 return Error(ID.Loc, "invalid indices for extractvalue");
2039 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
2040 ID.Kind = ValID::t_Constant;
2043 case lltok::kw_insertvalue: {
2045 Constant *Val0, *Val1;
2046 SmallVector<unsigned, 4> Indices;
2047 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2048 ParseGlobalTypeAndValue(Val0) ||
2049 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2050 ParseGlobalTypeAndValue(Val1) ||
2051 ParseIndexList(Indices) ||
2052 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2054 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
2055 return Error(ID.Loc, "extractvalue operand must be array or struct");
2056 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2058 return Error(ID.Loc, "invalid indices for insertvalue");
2059 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
2060 Indices.data(), Indices.size());
2061 ID.Kind = ValID::t_Constant;
2064 case lltok::kw_icmp:
2065 case lltok::kw_fcmp: {
2066 unsigned PredVal, Opc = Lex.getUIntVal();
2067 Constant *Val0, *Val1;
2069 if (ParseCmpPredicate(PredVal, Opc) ||
2070 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2071 ParseGlobalTypeAndValue(Val0) ||
2072 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2073 ParseGlobalTypeAndValue(Val1) ||
2074 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2077 if (Val0->getType() != Val1->getType())
2078 return Error(ID.Loc, "compare operands must have the same type");
2080 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2082 if (Opc == Instruction::FCmp) {
2083 if (!Val0->getType()->isFPOrFPVector())
2084 return Error(ID.Loc, "fcmp requires floating point operands");
2085 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2087 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2088 if (!Val0->getType()->isIntOrIntVector() &&
2089 !isa<PointerType>(Val0->getType()))
2090 return Error(ID.Loc, "icmp requires pointer or integer operands");
2091 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2093 ID.Kind = ValID::t_Constant;
2097 // Binary Operators.
2099 case lltok::kw_fadd:
2101 case lltok::kw_fsub:
2103 case lltok::kw_fmul:
2104 case lltok::kw_udiv:
2105 case lltok::kw_sdiv:
2106 case lltok::kw_fdiv:
2107 case lltok::kw_urem:
2108 case lltok::kw_srem:
2109 case lltok::kw_frem: {
2113 unsigned Opc = Lex.getUIntVal();
2114 Constant *Val0, *Val1;
2116 LocTy ModifierLoc = Lex.getLoc();
2117 if (Opc == Instruction::Add ||
2118 Opc == Instruction::Sub ||
2119 Opc == Instruction::Mul) {
2120 if (EatIfPresent(lltok::kw_nuw))
2122 if (EatIfPresent(lltok::kw_nsw)) {
2124 if (EatIfPresent(lltok::kw_nuw))
2127 } else if (Opc == Instruction::SDiv) {
2128 if (EatIfPresent(lltok::kw_exact))
2131 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2132 ParseGlobalTypeAndValue(Val0) ||
2133 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2134 ParseGlobalTypeAndValue(Val1) ||
2135 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2137 if (Val0->getType() != Val1->getType())
2138 return Error(ID.Loc, "operands of constexpr must have same type");
2139 if (!Val0->getType()->isIntOrIntVector()) {
2141 return Error(ModifierLoc, "nuw only applies to integer operations");
2143 return Error(ModifierLoc, "nsw only applies to integer operations");
2145 // API compatibility: Accept either integer or floating-point types with
2146 // add, sub, and mul.
2147 if (!Val0->getType()->isIntOrIntVector() &&
2148 !Val0->getType()->isFPOrFPVector())
2149 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
2151 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2152 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2153 if (Exact) Flags |= SDivOperator::IsExact;
2154 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2156 ID.Kind = ValID::t_Constant;
2160 // Logical Operations
2162 case lltok::kw_lshr:
2163 case lltok::kw_ashr:
2166 case lltok::kw_xor: {
2167 unsigned Opc = Lex.getUIntVal();
2168 Constant *Val0, *Val1;
2170 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2171 ParseGlobalTypeAndValue(Val0) ||
2172 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2173 ParseGlobalTypeAndValue(Val1) ||
2174 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2176 if (Val0->getType() != Val1->getType())
2177 return Error(ID.Loc, "operands of constexpr must have same type");
2178 if (!Val0->getType()->isIntOrIntVector())
2179 return Error(ID.Loc,
2180 "constexpr requires integer or integer vector operands");
2181 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2182 ID.Kind = ValID::t_Constant;
2186 case lltok::kw_getelementptr:
2187 case lltok::kw_shufflevector:
2188 case lltok::kw_insertelement:
2189 case lltok::kw_extractelement:
2190 case lltok::kw_select: {
2191 unsigned Opc = Lex.getUIntVal();
2192 SmallVector<Constant*, 16> Elts;
2193 bool InBounds = false;
2195 if (Opc == Instruction::GetElementPtr)
2196 InBounds = EatIfPresent(lltok::kw_inbounds);
2197 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2198 ParseGlobalValueVector(Elts) ||
2199 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2202 if (Opc == Instruction::GetElementPtr) {
2203 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
2204 return Error(ID.Loc, "getelementptr requires pointer operand");
2206 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
2207 (Value**)(Elts.data() + 1),
2209 return Error(ID.Loc, "invalid indices for getelementptr");
2210 ID.ConstantVal = InBounds ?
2211 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2214 ConstantExpr::getGetElementPtr(Elts[0],
2215 Elts.data() + 1, Elts.size() - 1);
2216 } else if (Opc == Instruction::Select) {
2217 if (Elts.size() != 3)
2218 return Error(ID.Loc, "expected three operands to select");
2219 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2221 return Error(ID.Loc, Reason);
2222 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2223 } else if (Opc == Instruction::ShuffleVector) {
2224 if (Elts.size() != 3)
2225 return Error(ID.Loc, "expected three operands to shufflevector");
2226 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2227 return Error(ID.Loc, "invalid operands to shufflevector");
2229 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2230 } else if (Opc == Instruction::ExtractElement) {
2231 if (Elts.size() != 2)
2232 return Error(ID.Loc, "expected two operands to extractelement");
2233 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2234 return Error(ID.Loc, "invalid extractelement operands");
2235 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2237 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2238 if (Elts.size() != 3)
2239 return Error(ID.Loc, "expected three operands to insertelement");
2240 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2241 return Error(ID.Loc, "invalid insertelement operands");
2243 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2246 ID.Kind = ValID::t_Constant;
2255 /// ParseGlobalValue - Parse a global value with the specified type.
2256 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2259 return ParseValID(ID) ||
2260 ConvertGlobalValIDToValue(Ty, ID, V);
2263 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2265 bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2267 if (isa<FunctionType>(Ty))
2268 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2271 default: llvm_unreachable("Unknown ValID!");
2272 case ValID::t_Metadata:
2273 return Error(ID.Loc, "invalid use of metadata");
2274 case ValID::t_LocalID:
2275 case ValID::t_LocalName:
2276 return Error(ID.Loc, "invalid use of function-local name");
2277 case ValID::t_InlineAsm:
2278 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2279 case ValID::t_GlobalName:
2280 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2282 case ValID::t_GlobalID:
2283 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2285 case ValID::t_APSInt:
2286 if (!isa<IntegerType>(Ty))
2287 return Error(ID.Loc, "integer constant must have integer type");
2288 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2289 V = ConstantInt::get(Context, ID.APSIntVal);
2291 case ValID::t_APFloat:
2292 if (!Ty->isFloatingPoint() ||
2293 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2294 return Error(ID.Loc, "floating point constant invalid for type");
2296 // The lexer has no type info, so builds all float and double FP constants
2297 // as double. Fix this here. Long double does not need this.
2298 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2301 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2304 V = ConstantFP::get(Context, ID.APFloatVal);
2306 if (V->getType() != Ty)
2307 return Error(ID.Loc, "floating point constant does not have type '" +
2308 Ty->getDescription() + "'");
2312 if (!isa<PointerType>(Ty))
2313 return Error(ID.Loc, "null must be a pointer type");
2314 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2316 case ValID::t_Undef:
2317 // FIXME: LabelTy should not be a first-class type.
2318 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
2319 !isa<OpaqueType>(Ty))
2320 return Error(ID.Loc, "invalid type for undef constant");
2321 V = UndefValue::get(Ty);
2323 case ValID::t_EmptyArray:
2324 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2325 return Error(ID.Loc, "invalid empty array initializer");
2326 V = UndefValue::get(Ty);
2329 // FIXME: LabelTy should not be a first-class type.
2330 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2331 return Error(ID.Loc, "invalid type for null constant");
2332 V = Constant::getNullValue(Ty);
2334 case ValID::t_Constant:
2335 if (ID.ConstantVal->getType() != Ty)
2336 return Error(ID.Loc, "constant expression type mismatch");
2342 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2343 PATypeHolder Type(Type::getVoidTy(Context));
2344 return ParseType(Type) ||
2345 ParseGlobalValue(Type, V);
2348 /// ParseGlobalValueVector
2350 /// ::= TypeAndValue (',' TypeAndValue)*
2351 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2353 if (Lex.getKind() == lltok::rbrace ||
2354 Lex.getKind() == lltok::rsquare ||
2355 Lex.getKind() == lltok::greater ||
2356 Lex.getKind() == lltok::rparen)
2360 if (ParseGlobalTypeAndValue(C)) return true;
2363 while (EatIfPresent(lltok::comma)) {
2364 if (ParseGlobalTypeAndValue(C)) return true;
2372 //===----------------------------------------------------------------------===//
2373 // Function Parsing.
2374 //===----------------------------------------------------------------------===//
2376 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2377 PerFunctionState &PFS) {
2378 if (ID.Kind == ValID::t_LocalID)
2379 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2380 else if (ID.Kind == ValID::t_LocalName)
2381 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
2382 else if (ID.Kind == ValID::t_InlineAsm) {
2383 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2384 const FunctionType *FTy =
2385 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2386 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2387 return Error(ID.Loc, "invalid type for inline asm constraint string");
2388 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2390 } else if (ID.Kind == ValID::t_Metadata) {
2394 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2402 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2405 return ParseValID(ID) ||
2406 ConvertValIDToValue(Ty, ID, V, PFS);
2409 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2410 PATypeHolder T(Type::getVoidTy(Context));
2411 return ParseType(T) ||
2412 ParseValue(T, V, PFS);
2415 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2416 PerFunctionState &PFS) {
2419 if (ParseTypeAndValue(V, PFS)) return true;
2420 if (!isa<BasicBlock>(V))
2421 return Error(Loc, "expected a basic block");
2422 BB = cast<BasicBlock>(V);
2428 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2429 /// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2430 /// OptionalAlign OptGC
2431 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2432 // Parse the linkage.
2433 LocTy LinkageLoc = Lex.getLoc();
2436 unsigned Visibility, RetAttrs;
2438 PATypeHolder RetType(Type::getVoidTy(Context));
2439 LocTy RetTypeLoc = Lex.getLoc();
2440 if (ParseOptionalLinkage(Linkage) ||
2441 ParseOptionalVisibility(Visibility) ||
2442 ParseOptionalCallingConv(CC) ||
2443 ParseOptionalAttrs(RetAttrs, 1) ||
2444 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2447 // Verify that the linkage is ok.
2448 switch ((GlobalValue::LinkageTypes)Linkage) {
2449 case GlobalValue::ExternalLinkage:
2450 break; // always ok.
2451 case GlobalValue::DLLImportLinkage:
2452 case GlobalValue::ExternalWeakLinkage:
2454 return Error(LinkageLoc, "invalid linkage for function definition");
2456 case GlobalValue::PrivateLinkage:
2457 case GlobalValue::LinkerPrivateLinkage:
2458 case GlobalValue::InternalLinkage:
2459 case GlobalValue::AvailableExternallyLinkage:
2460 case GlobalValue::LinkOnceAnyLinkage:
2461 case GlobalValue::LinkOnceODRLinkage:
2462 case GlobalValue::WeakAnyLinkage:
2463 case GlobalValue::WeakODRLinkage:
2464 case GlobalValue::DLLExportLinkage:
2466 return Error(LinkageLoc, "invalid linkage for function declaration");
2468 case GlobalValue::AppendingLinkage:
2469 case GlobalValue::GhostLinkage:
2470 case GlobalValue::CommonLinkage:
2471 return Error(LinkageLoc, "invalid function linkage type");
2474 if (!FunctionType::isValidReturnType(RetType) ||
2475 isa<OpaqueType>(RetType))
2476 return Error(RetTypeLoc, "invalid function return type");
2478 LocTy NameLoc = Lex.getLoc();
2480 std::string FunctionName;
2481 if (Lex.getKind() == lltok::GlobalVar) {
2482 FunctionName = Lex.getStrVal();
2483 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2484 unsigned NameID = Lex.getUIntVal();
2486 if (NameID != NumberedVals.size())
2487 return TokError("function expected to be numbered '%" +
2488 utostr(NumberedVals.size()) + "'");
2490 return TokError("expected function name");
2495 if (Lex.getKind() != lltok::lparen)
2496 return TokError("expected '(' in function argument list");
2498 std::vector<ArgInfo> ArgList;
2501 std::string Section;
2505 if (ParseArgumentList(ArgList, isVarArg, false) ||
2506 ParseOptionalAttrs(FuncAttrs, 2) ||
2507 (EatIfPresent(lltok::kw_section) &&
2508 ParseStringConstant(Section)) ||
2509 ParseOptionalAlignment(Alignment) ||
2510 (EatIfPresent(lltok::kw_gc) &&
2511 ParseStringConstant(GC)))
2514 // If the alignment was parsed as an attribute, move to the alignment field.
2515 if (FuncAttrs & Attribute::Alignment) {
2516 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2517 FuncAttrs &= ~Attribute::Alignment;
2520 // Okay, if we got here, the function is syntactically valid. Convert types
2521 // and do semantic checks.
2522 std::vector<const Type*> ParamTypeList;
2523 SmallVector<AttributeWithIndex, 8> Attrs;
2524 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2526 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2527 if (FuncAttrs & ObsoleteFuncAttrs) {
2528 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2529 FuncAttrs &= ~ObsoleteFuncAttrs;
2532 if (RetAttrs != Attribute::None)
2533 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2535 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2536 ParamTypeList.push_back(ArgList[i].Type);
2537 if (ArgList[i].Attrs != Attribute::None)
2538 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2541 if (FuncAttrs != Attribute::None)
2542 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2544 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2546 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2547 RetType != Type::getVoidTy(Context))
2548 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2550 const FunctionType *FT =
2551 FunctionType::get(RetType, ParamTypeList, isVarArg);
2552 const PointerType *PFT = PointerType::getUnqual(FT);
2555 if (!FunctionName.empty()) {
2556 // If this was a definition of a forward reference, remove the definition
2557 // from the forward reference table and fill in the forward ref.
2558 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2559 ForwardRefVals.find(FunctionName);
2560 if (FRVI != ForwardRefVals.end()) {
2561 Fn = M->getFunction(FunctionName);
2562 ForwardRefVals.erase(FRVI);
2563 } else if ((Fn = M->getFunction(FunctionName))) {
2564 // If this function already exists in the symbol table, then it is
2565 // multiply defined. We accept a few cases for old backwards compat.
2566 // FIXME: Remove this stuff for LLVM 3.0.
2567 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2568 (!Fn->isDeclaration() && isDefine)) {
2569 // If the redefinition has different type or different attributes,
2570 // reject it. If both have bodies, reject it.
2571 return Error(NameLoc, "invalid redefinition of function '" +
2572 FunctionName + "'");
2573 } else if (Fn->isDeclaration()) {
2574 // Make sure to strip off any argument names so we can't get conflicts.
2575 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2579 } else if (M->getNamedValue(FunctionName)) {
2580 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
2584 // If this is a definition of a forward referenced function, make sure the
2586 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2587 = ForwardRefValIDs.find(NumberedVals.size());
2588 if (I != ForwardRefValIDs.end()) {
2589 Fn = cast<Function>(I->second.first);
2590 if (Fn->getType() != PFT)
2591 return Error(NameLoc, "type of definition and forward reference of '@" +
2592 utostr(NumberedVals.size()) +"' disagree");
2593 ForwardRefValIDs.erase(I);
2598 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2599 else // Move the forward-reference to the correct spot in the module.
2600 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2602 if (FunctionName.empty())
2603 NumberedVals.push_back(Fn);
2605 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2606 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2607 Fn->setCallingConv(CC);
2608 Fn->setAttributes(PAL);
2609 Fn->setAlignment(Alignment);
2610 Fn->setSection(Section);
2611 if (!GC.empty()) Fn->setGC(GC.c_str());
2613 // Add all of the arguments we parsed to the function.
2614 Function::arg_iterator ArgIt = Fn->arg_begin();
2615 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2616 // If the argument has a name, insert it into the argument symbol table.
2617 if (ArgList[i].Name.empty()) continue;
2619 // Set the name, if it conflicted, it will be auto-renamed.
2620 ArgIt->setName(ArgList[i].Name);
2622 if (ArgIt->getNameStr() != ArgList[i].Name)
2623 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2624 ArgList[i].Name + "'");
2631 /// ParseFunctionBody
2632 /// ::= '{' BasicBlock+ '}'
2633 /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2635 bool LLParser::ParseFunctionBody(Function &Fn) {
2636 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2637 return TokError("expected '{' in function body");
2638 Lex.Lex(); // eat the {.
2640 PerFunctionState PFS(*this, Fn);
2642 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2643 if (ParseBasicBlock(PFS)) return true;
2648 // Verify function is ok.
2649 return PFS.VerifyFunctionComplete();
2653 /// ::= LabelStr? Instruction*
2654 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2655 // If this basic block starts out with a name, remember it.
2657 LocTy NameLoc = Lex.getLoc();
2658 if (Lex.getKind() == lltok::LabelStr) {
2659 Name = Lex.getStrVal();
2663 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2664 if (BB == 0) return true;
2666 std::string NameStr;
2668 // Parse the instructions in this block until we get a terminator.
2671 // This instruction may have three possibilities for a name: a) none
2672 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2673 LocTy NameLoc = Lex.getLoc();
2677 if (Lex.getKind() == lltok::LocalVarID) {
2678 NameID = Lex.getUIntVal();
2680 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2682 } else if (Lex.getKind() == lltok::LocalVar ||
2683 // FIXME: REMOVE IN LLVM 3.0
2684 Lex.getKind() == lltok::StringConstant) {
2685 NameStr = Lex.getStrVal();
2687 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2691 if (ParseInstruction(Inst, BB, PFS)) return true;
2692 if (EatIfPresent(lltok::comma))
2693 ParseOptionalCustomMetadata();
2695 // Set metadata attached with this instruction.
2696 MetadataContext &TheMetadata = M->getContext().getMetadata();
2697 for (SmallVector<std::pair<unsigned, MDNode *>, 2>::iterator
2698 MDI = MDsOnInst.begin(), MDE = MDsOnInst.end(); MDI != MDE; ++MDI)
2699 TheMetadata.addMD(MDI->first, MDI->second, Inst);
2702 BB->getInstList().push_back(Inst);
2704 // Set the name on the instruction.
2705 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2706 } while (!isa<TerminatorInst>(Inst));
2711 //===----------------------------------------------------------------------===//
2712 // Instruction Parsing.
2713 //===----------------------------------------------------------------------===//
2715 /// ParseInstruction - Parse one of the many different instructions.
2717 bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2718 PerFunctionState &PFS) {
2719 lltok::Kind Token = Lex.getKind();
2720 if (Token == lltok::Eof)
2721 return TokError("found end of file when expecting more instructions");
2722 LocTy Loc = Lex.getLoc();
2723 unsigned KeywordVal = Lex.getUIntVal();
2724 Lex.Lex(); // Eat the keyword.
2727 default: return Error(Loc, "expected instruction opcode");
2728 // Terminator Instructions.
2729 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2730 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
2731 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2732 case lltok::kw_br: return ParseBr(Inst, PFS);
2733 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2734 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
2735 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2736 // Binary Operators.
2739 case lltok::kw_mul: {
2742 LocTy ModifierLoc = Lex.getLoc();
2743 if (EatIfPresent(lltok::kw_nuw))
2745 if (EatIfPresent(lltok::kw_nsw)) {
2747 if (EatIfPresent(lltok::kw_nuw))
2750 // API compatibility: Accept either integer or floating-point types.
2751 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
2753 if (!Inst->getType()->isIntOrIntVector()) {
2755 return Error(ModifierLoc, "nuw only applies to integer operations");
2757 return Error(ModifierLoc, "nsw only applies to integer operations");
2760 cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
2762 cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
2766 case lltok::kw_fadd:
2767 case lltok::kw_fsub:
2768 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2770 case lltok::kw_sdiv: {
2772 if (EatIfPresent(lltok::kw_exact))
2774 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2777 cast<BinaryOperator>(Inst)->setIsExact(true);
2781 case lltok::kw_udiv:
2782 case lltok::kw_urem:
2783 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2784 case lltok::kw_fdiv:
2785 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2787 case lltok::kw_lshr:
2788 case lltok::kw_ashr:
2791 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
2792 case lltok::kw_icmp:
2793 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
2795 case lltok::kw_trunc:
2796 case lltok::kw_zext:
2797 case lltok::kw_sext:
2798 case lltok::kw_fptrunc:
2799 case lltok::kw_fpext:
2800 case lltok::kw_bitcast:
2801 case lltok::kw_uitofp:
2802 case lltok::kw_sitofp:
2803 case lltok::kw_fptoui:
2804 case lltok::kw_fptosi:
2805 case lltok::kw_inttoptr:
2806 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
2808 case lltok::kw_select: return ParseSelect(Inst, PFS);
2809 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
2810 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2811 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2812 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2813 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2814 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2815 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2817 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
2818 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, BB, false);
2819 case lltok::kw_free: return ParseFree(Inst, PFS, BB);
2820 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2821 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2822 case lltok::kw_volatile:
2823 if (EatIfPresent(lltok::kw_load))
2824 return ParseLoad(Inst, PFS, true);
2825 else if (EatIfPresent(lltok::kw_store))
2826 return ParseStore(Inst, PFS, true);
2828 return TokError("expected 'load' or 'store'");
2829 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2830 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2831 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2832 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2836 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2837 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2838 if (Opc == Instruction::FCmp) {
2839 switch (Lex.getKind()) {
2840 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2841 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2842 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2843 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2844 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2845 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2846 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2847 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2848 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2849 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2850 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2851 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2852 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2853 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2854 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2855 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2856 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2859 switch (Lex.getKind()) {
2860 default: TokError("expected icmp predicate (e.g. 'eq')");
2861 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2862 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2863 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2864 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2865 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2866 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2867 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2868 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2869 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2870 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2877 //===----------------------------------------------------------------------===//
2878 // Terminator Instructions.
2879 //===----------------------------------------------------------------------===//
2881 /// ParseRet - Parse a return instruction.
2882 /// ::= 'ret' void (',' !dbg, !1)
2883 /// ::= 'ret' TypeAndValue (',' !dbg, !1)
2884 /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)
2885 /// [[obsolete: LLVM 3.0]]
2886 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2887 PerFunctionState &PFS) {
2888 PATypeHolder Ty(Type::getVoidTy(Context));
2889 if (ParseType(Ty, true /*void allowed*/)) return true;
2891 if (Ty->isVoidTy()) {
2892 Inst = ReturnInst::Create(Context);
2897 if (ParseValue(Ty, RV, PFS)) return true;
2899 if (EatIfPresent(lltok::comma)) {
2900 // Parse optional custom metadata, e.g. !dbg
2901 if (Lex.getKind() == lltok::NamedOrCustomMD) {
2902 if (ParseOptionalCustomMetadata()) return true;
2904 // The normal case is one return value.
2905 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2906 // of 'ret {i32,i32} {i32 1, i32 2}'
2907 SmallVector<Value*, 8> RVs;
2911 // If optional custom metadata, e.g. !dbg is seen then this is the
2913 if (Lex.getKind() == lltok::NamedOrCustomMD)
2915 if (ParseTypeAndValue(RV, PFS)) return true;
2917 } while (EatIfPresent(lltok::comma));
2919 RV = UndefValue::get(PFS.getFunction().getReturnType());
2920 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2921 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2922 BB->getInstList().push_back(I);
2928 Inst = ReturnInst::Create(Context, RV);
2934 /// ::= 'br' TypeAndValue
2935 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2936 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2939 BasicBlock *Op1, *Op2;
2940 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2942 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2943 Inst = BranchInst::Create(BB);
2947 if (Op0->getType() != Type::getInt1Ty(Context))
2948 return Error(Loc, "branch condition must have 'i1' type");
2950 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2951 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
2952 ParseToken(lltok::comma, "expected ',' after true destination") ||
2953 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
2956 Inst = BranchInst::Create(Op1, Op2, Op0);
2962 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2964 /// ::= (TypeAndValue ',' TypeAndValue)*
2965 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2966 LocTy CondLoc, BBLoc;
2968 BasicBlock *DefaultBB;
2969 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2970 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2971 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
2972 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2975 if (!isa<IntegerType>(Cond->getType()))
2976 return Error(CondLoc, "switch condition must have integer type");
2978 // Parse the jump table pairs.
2979 SmallPtrSet<Value*, 32> SeenCases;
2980 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2981 while (Lex.getKind() != lltok::rsquare) {
2985 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2986 ParseToken(lltok::comma, "expected ',' after case value") ||
2987 ParseTypeAndBasicBlock(DestBB, PFS))
2990 if (!SeenCases.insert(Constant))
2991 return Error(CondLoc, "duplicate case value in switch");
2992 if (!isa<ConstantInt>(Constant))
2993 return Error(CondLoc, "case value is not a constant integer");
2995 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
2998 Lex.Lex(); // Eat the ']'.
3000 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3001 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3002 SI->addCase(Table[i].first, Table[i].second);
3009 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3010 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3013 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3014 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3015 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3018 if (!isa<PointerType>(Address->getType()))
3019 return Error(AddrLoc, "indirectbr address must have pointer type");
3021 // Parse the destination list.
3022 SmallVector<BasicBlock*, 16> DestList;
3024 if (Lex.getKind() != lltok::rsquare) {
3026 if (ParseTypeAndBasicBlock(DestBB, PFS))
3028 DestList.push_back(DestBB);
3030 while (EatIfPresent(lltok::comma)) {
3031 if (ParseTypeAndBasicBlock(DestBB, PFS))
3033 DestList.push_back(DestBB);
3037 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3040 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3041 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3042 IBI->addDestination(DestList[i]);
3049 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3050 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3051 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3052 LocTy CallLoc = Lex.getLoc();
3053 unsigned RetAttrs, FnAttrs;
3055 PATypeHolder RetType(Type::getVoidTy(Context));
3058 SmallVector<ParamInfo, 16> ArgList;
3060 BasicBlock *NormalBB, *UnwindBB;
3061 if (ParseOptionalCallingConv(CC) ||
3062 ParseOptionalAttrs(RetAttrs, 1) ||
3063 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3064 ParseValID(CalleeID) ||
3065 ParseParameterList(ArgList, PFS) ||
3066 ParseOptionalAttrs(FnAttrs, 2) ||
3067 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3068 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3069 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3070 ParseTypeAndBasicBlock(UnwindBB, PFS))
3073 // If RetType is a non-function pointer type, then this is the short syntax
3074 // for the call, which means that RetType is just the return type. Infer the
3075 // rest of the function argument types from the arguments that are present.
3076 const PointerType *PFTy = 0;
3077 const FunctionType *Ty = 0;
3078 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3079 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3080 // Pull out the types of all of the arguments...
3081 std::vector<const Type*> ParamTypes;
3082 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3083 ParamTypes.push_back(ArgList[i].V->getType());
3085 if (!FunctionType::isValidReturnType(RetType))
3086 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3088 Ty = FunctionType::get(RetType, ParamTypes, false);
3089 PFTy = PointerType::getUnqual(Ty);
3092 // Look up the callee.
3094 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3096 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3097 // function attributes.
3098 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3099 if (FnAttrs & ObsoleteFuncAttrs) {
3100 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3101 FnAttrs &= ~ObsoleteFuncAttrs;
3104 // Set up the Attributes for the function.
3105 SmallVector<AttributeWithIndex, 8> Attrs;
3106 if (RetAttrs != Attribute::None)
3107 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3109 SmallVector<Value*, 8> Args;
3111 // Loop through FunctionType's arguments and ensure they are specified
3112 // correctly. Also, gather any parameter attributes.
3113 FunctionType::param_iterator I = Ty->param_begin();
3114 FunctionType::param_iterator E = Ty->param_end();
3115 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3116 const Type *ExpectedTy = 0;
3119 } else if (!Ty->isVarArg()) {
3120 return Error(ArgList[i].Loc, "too many arguments specified");
3123 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3124 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3125 ExpectedTy->getDescription() + "'");
3126 Args.push_back(ArgList[i].V);
3127 if (ArgList[i].Attrs != Attribute::None)
3128 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3132 return Error(CallLoc, "not enough parameters specified for call");
3134 if (FnAttrs != Attribute::None)
3135 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3137 // Finish off the Attributes and check them
3138 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3140 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
3141 Args.begin(), Args.end());
3142 II->setCallingConv(CC);
3143 II->setAttributes(PAL);
3150 //===----------------------------------------------------------------------===//
3151 // Binary Operators.
3152 //===----------------------------------------------------------------------===//
3155 /// ::= ArithmeticOps TypeAndValue ',' Value
3157 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3158 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3159 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3160 unsigned Opc, unsigned OperandType) {
3161 LocTy Loc; Value *LHS, *RHS;
3162 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3163 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3164 ParseValue(LHS->getType(), RHS, PFS))
3168 switch (OperandType) {
3169 default: llvm_unreachable("Unknown operand type!");
3170 case 0: // int or FP.
3171 Valid = LHS->getType()->isIntOrIntVector() ||
3172 LHS->getType()->isFPOrFPVector();
3174 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
3175 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
3179 return Error(Loc, "invalid operand type for instruction");
3181 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3186 /// ::= ArithmeticOps TypeAndValue ',' Value {
3187 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3189 LocTy Loc; Value *LHS, *RHS;
3190 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3191 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3192 ParseValue(LHS->getType(), RHS, PFS))
3195 if (!LHS->getType()->isIntOrIntVector())
3196 return Error(Loc,"instruction requires integer or integer vector operands");
3198 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3204 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3205 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3206 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3208 // Parse the integer/fp comparison predicate.
3212 if (ParseCmpPredicate(Pred, Opc) ||
3213 ParseTypeAndValue(LHS, Loc, PFS) ||
3214 ParseToken(lltok::comma, "expected ',' after compare value") ||
3215 ParseValue(LHS->getType(), RHS, PFS))
3218 if (Opc == Instruction::FCmp) {
3219 if (!LHS->getType()->isFPOrFPVector())
3220 return Error(Loc, "fcmp requires floating point operands");
3221 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3223 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3224 if (!LHS->getType()->isIntOrIntVector() &&
3225 !isa<PointerType>(LHS->getType()))
3226 return Error(Loc, "icmp requires integer operands");
3227 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3232 //===----------------------------------------------------------------------===//
3233 // Other Instructions.
3234 //===----------------------------------------------------------------------===//
3238 /// ::= CastOpc TypeAndValue 'to' Type
3239 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3241 LocTy Loc; Value *Op;
3242 PATypeHolder DestTy(Type::getVoidTy(Context));
3243 if (ParseTypeAndValue(Op, Loc, PFS) ||
3244 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3248 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3249 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3250 return Error(Loc, "invalid cast opcode for cast from '" +
3251 Op->getType()->getDescription() + "' to '" +
3252 DestTy->getDescription() + "'");
3254 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3259 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3260 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3262 Value *Op0, *Op1, *Op2;
3263 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3264 ParseToken(lltok::comma, "expected ',' after select condition") ||
3265 ParseTypeAndValue(Op1, PFS) ||
3266 ParseToken(lltok::comma, "expected ',' after select value") ||
3267 ParseTypeAndValue(Op2, PFS))
3270 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3271 return Error(Loc, Reason);
3273 Inst = SelectInst::Create(Op0, Op1, Op2);
3278 /// ::= 'va_arg' TypeAndValue ',' Type
3279 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3281 PATypeHolder EltTy(Type::getVoidTy(Context));
3283 if (ParseTypeAndValue(Op, PFS) ||
3284 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3285 ParseType(EltTy, TypeLoc))
3288 if (!EltTy->isFirstClassType())
3289 return Error(TypeLoc, "va_arg requires operand with first class type");
3291 Inst = new VAArgInst(Op, EltTy);
3295 /// ParseExtractElement
3296 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3297 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3300 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3301 ParseToken(lltok::comma, "expected ',' after extract value") ||
3302 ParseTypeAndValue(Op1, PFS))
3305 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3306 return Error(Loc, "invalid extractelement operands");
3308 Inst = ExtractElementInst::Create(Op0, Op1);
3312 /// ParseInsertElement
3313 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3314 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3316 Value *Op0, *Op1, *Op2;
3317 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3318 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3319 ParseTypeAndValue(Op1, PFS) ||
3320 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3321 ParseTypeAndValue(Op2, PFS))
3324 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3325 return Error(Loc, "invalid insertelement operands");
3327 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3331 /// ParseShuffleVector
3332 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3333 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3335 Value *Op0, *Op1, *Op2;
3336 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3337 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3338 ParseTypeAndValue(Op1, PFS) ||
3339 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3340 ParseTypeAndValue(Op2, PFS))
3343 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3344 return Error(Loc, "invalid extractelement operands");
3346 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3351 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3352 bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3353 PATypeHolder Ty(Type::getVoidTy(Context));
3355 LocTy TypeLoc = Lex.getLoc();
3357 if (ParseType(Ty) ||
3358 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3359 ParseValue(Ty, Op0, PFS) ||
3360 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3361 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3362 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3365 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3367 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3369 if (!EatIfPresent(lltok::comma))
3372 if (Lex.getKind() == lltok::NamedOrCustomMD)
3375 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3376 ParseValue(Ty, Op0, PFS) ||
3377 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3378 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3379 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3383 if (Lex.getKind() == lltok::NamedOrCustomMD)
3384 if (ParseOptionalCustomMetadata()) return true;
3386 if (!Ty->isFirstClassType())
3387 return Error(TypeLoc, "phi node must have first class type");
3389 PHINode *PN = PHINode::Create(Ty);
3390 PN->reserveOperandSpace(PHIVals.size());
3391 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3392 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3398 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3399 /// ParameterList OptionalAttrs
3400 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3402 unsigned RetAttrs, FnAttrs;
3404 PATypeHolder RetType(Type::getVoidTy(Context));
3407 SmallVector<ParamInfo, 16> ArgList;
3408 LocTy CallLoc = Lex.getLoc();
3410 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3411 ParseOptionalCallingConv(CC) ||
3412 ParseOptionalAttrs(RetAttrs, 1) ||
3413 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3414 ParseValID(CalleeID) ||
3415 ParseParameterList(ArgList, PFS) ||
3416 ParseOptionalAttrs(FnAttrs, 2))
3419 // If RetType is a non-function pointer type, then this is the short syntax
3420 // for the call, which means that RetType is just the return type. Infer the
3421 // rest of the function argument types from the arguments that are present.
3422 const PointerType *PFTy = 0;
3423 const FunctionType *Ty = 0;
3424 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3425 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3426 // Pull out the types of all of the arguments...
3427 std::vector<const Type*> ParamTypes;
3428 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3429 ParamTypes.push_back(ArgList[i].V->getType());
3431 if (!FunctionType::isValidReturnType(RetType))
3432 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3434 Ty = FunctionType::get(RetType, ParamTypes, false);
3435 PFTy = PointerType::getUnqual(Ty);
3438 // Look up the callee.
3440 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3442 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3443 // function attributes.
3444 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3445 if (FnAttrs & ObsoleteFuncAttrs) {
3446 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3447 FnAttrs &= ~ObsoleteFuncAttrs;
3450 // Set up the Attributes for the function.
3451 SmallVector<AttributeWithIndex, 8> Attrs;
3452 if (RetAttrs != Attribute::None)
3453 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3455 SmallVector<Value*, 8> Args;
3457 // Loop through FunctionType's arguments and ensure they are specified
3458 // correctly. Also, gather any parameter attributes.
3459 FunctionType::param_iterator I = Ty->param_begin();
3460 FunctionType::param_iterator E = Ty->param_end();
3461 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3462 const Type *ExpectedTy = 0;
3465 } else if (!Ty->isVarArg()) {
3466 return Error(ArgList[i].Loc, "too many arguments specified");
3469 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3470 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3471 ExpectedTy->getDescription() + "'");
3472 Args.push_back(ArgList[i].V);
3473 if (ArgList[i].Attrs != Attribute::None)
3474 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3478 return Error(CallLoc, "not enough parameters specified for call");
3480 if (FnAttrs != Attribute::None)
3481 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3483 // Finish off the Attributes and check them
3484 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3486 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3487 CI->setTailCall(isTail);
3488 CI->setCallingConv(CC);
3489 CI->setAttributes(PAL);
3494 //===----------------------------------------------------------------------===//
3495 // Memory Instructions.
3496 //===----------------------------------------------------------------------===//
3499 /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3500 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
3501 bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3502 BasicBlock* BB, bool isAlloca) {
3503 PATypeHolder Ty(Type::getVoidTy(Context));
3506 unsigned Alignment = 0;
3507 if (ParseType(Ty)) return true;
3509 if (EatIfPresent(lltok::comma)) {
3510 if (Lex.getKind() == lltok::kw_align
3511 || Lex.getKind() == lltok::NamedOrCustomMD) {
3512 if (ParseOptionalInfo(Alignment)) return true;
3514 if (ParseTypeAndValue(Size, SizeLoc, PFS)) return true;
3515 if (EatIfPresent(lltok::comma))
3516 if (ParseOptionalInfo(Alignment)) return true;
3520 if (Size && Size->getType() != Type::getInt32Ty(Context))
3521 return Error(SizeLoc, "element count must be i32");
3524 Inst = new AllocaInst(Ty, Size, Alignment);
3528 // Autoupgrade old malloc instruction to malloc call.
3529 // FIXME: Remove in LLVM 3.0.
3530 const Type *IntPtrTy = Type::getInt32Ty(Context);
3532 // Prototype malloc as "void *(int32)".
3533 // This function is renamed as "malloc" in ValidateEndOfModule().
3534 MallocF = cast<Function>(
3535 M->getOrInsertFunction("", Type::getInt8PtrTy(Context), IntPtrTy, NULL));
3536 Inst = CallInst::CreateMalloc(BB, IntPtrTy, Ty, Size, MallocF);
3541 /// ::= 'free' TypeAndValue
3542 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS,
3544 Value *Val; LocTy Loc;
3545 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3546 if (!isa<PointerType>(Val->getType()))
3547 return Error(Loc, "operand to free must be a pointer");
3548 Inst = CallInst::CreateFree(Val, BB);
3553 /// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
3554 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3556 Value *Val; LocTy Loc;
3557 unsigned Alignment = 0;
3558 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3560 if (EatIfPresent(lltok::comma))
3561 if (ParseOptionalInfo(Alignment)) return true;
3563 if (!isa<PointerType>(Val->getType()) ||
3564 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3565 return Error(Loc, "load operand must be a pointer to a first class type");
3567 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3572 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3573 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3575 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3576 unsigned Alignment = 0;
3577 if (ParseTypeAndValue(Val, Loc, PFS) ||
3578 ParseToken(lltok::comma, "expected ',' after store operand") ||
3579 ParseTypeAndValue(Ptr, PtrLoc, PFS))
3582 if (EatIfPresent(lltok::comma))
3583 if (ParseOptionalInfo(Alignment)) return true;
3585 if (!isa<PointerType>(Ptr->getType()))
3586 return Error(PtrLoc, "store operand must be a pointer");
3587 if (!Val->getType()->isFirstClassType())
3588 return Error(Loc, "store operand must be a first class value");
3589 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3590 return Error(Loc, "stored value and pointer type do not match");
3592 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3597 /// ::= 'getresult' TypeAndValue ',' i32
3598 /// FIXME: Remove support for getresult in LLVM 3.0
3599 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3600 Value *Val; LocTy ValLoc, EltLoc;
3602 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3603 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3604 ParseUInt32(Element, EltLoc))
3607 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3608 return Error(ValLoc, "getresult inst requires an aggregate operand");
3609 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3610 return Error(EltLoc, "invalid getresult index for value");
3611 Inst = ExtractValueInst::Create(Val, Element);
3615 /// ParseGetElementPtr
3616 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
3617 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3618 Value *Ptr, *Val; LocTy Loc, EltLoc;
3620 bool InBounds = EatIfPresent(lltok::kw_inbounds);
3622 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3624 if (!isa<PointerType>(Ptr->getType()))
3625 return Error(Loc, "base of getelementptr must be a pointer");
3627 SmallVector<Value*, 16> Indices;
3628 while (EatIfPresent(lltok::comma)) {
3629 if (Lex.getKind() == lltok::NamedOrCustomMD)
3631 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3632 if (!isa<IntegerType>(Val->getType()))
3633 return Error(EltLoc, "getelementptr index must be an integer");
3634 Indices.push_back(Val);
3636 if (Lex.getKind() == lltok::NamedOrCustomMD)
3637 if (ParseOptionalCustomMetadata()) return true;
3639 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3640 Indices.begin(), Indices.end()))
3641 return Error(Loc, "invalid getelementptr indices");
3642 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3644 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
3648 /// ParseExtractValue
3649 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3650 bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3651 Value *Val; LocTy Loc;
3652 SmallVector<unsigned, 4> Indices;
3653 if (ParseTypeAndValue(Val, Loc, PFS) ||
3654 ParseIndexList(Indices))
3657 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3658 return Error(Loc, "extractvalue operand must be array or struct");
3660 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3662 return Error(Loc, "invalid indices for extractvalue");
3663 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3667 /// ParseInsertValue
3668 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3669 bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3670 Value *Val0, *Val1; LocTy Loc0, Loc1;
3671 SmallVector<unsigned, 4> Indices;
3672 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3673 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3674 ParseTypeAndValue(Val1, Loc1, PFS) ||
3675 ParseIndexList(Indices))
3678 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3679 return Error(Loc0, "extractvalue operand must be array or struct");
3681 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3683 return Error(Loc0, "invalid indices for insertvalue");
3684 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3688 //===----------------------------------------------------------------------===//
3689 // Embedded metadata.
3690 //===----------------------------------------------------------------------===//
3692 /// ParseMDNodeVector
3693 /// ::= Element (',' Element)*
3695 /// ::= 'null' | TypeAndValue
3696 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
3697 assert(Lex.getKind() == lltok::lbrace);
3701 if (Lex.getKind() == lltok::kw_null) {
3705 PATypeHolder Ty(Type::getVoidTy(Context));
3706 if (ParseType(Ty)) return true;
3707 if (Lex.getKind() == lltok::Metadata) {
3709 MetadataBase *Node = 0;
3710 if (!ParseMDNode(Node))
3713 MetadataBase *MDS = 0;
3714 if (ParseMDString(MDS)) return true;
3719 if (ParseGlobalValue(Ty, C)) return true;
3724 } while (EatIfPresent(lltok::comma));