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/ADT/SmallPtrSet.h"
16 #include "llvm/AutoUpgrade.h"
17 #include "llvm/IR/CallingConv.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/InlineAsm.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Operator.h"
25 #include "llvm/IR/ValueSymbolTable.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
30 static std::string getTypeString(Type *T) {
32 raw_string_ostream Tmp(Result);
37 /// Run: module ::= toplevelentity*
38 bool LLParser::Run() {
42 return ParseTopLevelEntities() ||
43 ValidateEndOfModule();
46 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
48 bool LLParser::ValidateEndOfModule() {
49 // Handle any instruction metadata forward references.
50 if (!ForwardRefInstMetadata.empty()) {
51 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
52 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
54 Instruction *Inst = I->first;
55 const std::vector<MDRef> &MDList = I->second;
57 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
58 unsigned SlotNo = MDList[i].MDSlot;
60 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
61 return Error(MDList[i].Loc, "use of undefined metadata '!" +
63 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
66 ForwardRefInstMetadata.clear();
69 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
70 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
72 // Handle any function attribute group forward references.
73 for (std::map<Value*, std::vector<unsigned> >::iterator
74 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
77 std::vector<unsigned> &Vec = I->second;
80 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
82 B.merge(NumberedAttrBuilders[*VI]);
84 if (Function *Fn = dyn_cast<Function>(V)) {
85 AttributeSet AS = Fn->getAttributes();
86 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
87 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
88 AS.getFnAttributes());
92 // If the alignment was parsed as an attribute, move to the alignment
94 if (FnAttrs.hasAlignmentAttr()) {
95 Fn->setAlignment(FnAttrs.getAlignment());
96 FnAttrs.removeAttribute(Attribute::Alignment);
99 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
100 AttributeSet::get(Context,
101 AttributeSet::FunctionIndex,
103 Fn->setAttributes(AS);
104 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
105 AttributeSet AS = CI->getAttributes();
106 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
107 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
108 AS.getFnAttributes());
110 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
111 AttributeSet::get(Context,
112 AttributeSet::FunctionIndex,
114 CI->setAttributes(AS);
115 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
116 AttributeSet AS = II->getAttributes();
117 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
118 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
119 AS.getFnAttributes());
121 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
122 AttributeSet::get(Context,
123 AttributeSet::FunctionIndex,
125 II->setAttributes(AS);
127 llvm_unreachable("invalid object with forward attribute group reference");
131 // If there are entries in ForwardRefBlockAddresses at this point, they are
132 // references after the function was defined. Resolve those now.
133 while (!ForwardRefBlockAddresses.empty()) {
134 // Okay, we are referencing an already-parsed function, resolve them now.
136 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
137 if (Fn.Kind == ValID::t_GlobalName)
138 TheFn = M->getFunction(Fn.StrVal);
139 else if (Fn.UIntVal < NumberedVals.size())
140 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
143 return Error(Fn.Loc, "unknown function referenced by blockaddress");
145 // Resolve all these references.
146 if (ResolveForwardRefBlockAddresses(TheFn,
147 ForwardRefBlockAddresses.begin()->second,
151 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
154 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
155 if (NumberedTypes[i].second.isValid())
156 return Error(NumberedTypes[i].second,
157 "use of undefined type '%" + Twine(i) + "'");
159 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
160 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
161 if (I->second.second.isValid())
162 return Error(I->second.second,
163 "use of undefined type named '" + I->getKey() + "'");
165 if (!ForwardRefVals.empty())
166 return Error(ForwardRefVals.begin()->second.second,
167 "use of undefined value '@" + ForwardRefVals.begin()->first +
170 if (!ForwardRefValIDs.empty())
171 return Error(ForwardRefValIDs.begin()->second.second,
172 "use of undefined value '@" +
173 Twine(ForwardRefValIDs.begin()->first) + "'");
175 if (!ForwardRefMDNodes.empty())
176 return Error(ForwardRefMDNodes.begin()->second.second,
177 "use of undefined metadata '!" +
178 Twine(ForwardRefMDNodes.begin()->first) + "'");
181 // Look for intrinsic functions and CallInst that need to be upgraded
182 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
183 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
188 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
189 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
190 PerFunctionState *PFS) {
191 // Loop over all the references, resolving them.
192 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
195 if (Refs[i].first.Kind == ValID::t_LocalName)
196 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
198 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
199 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
200 return Error(Refs[i].first.Loc,
201 "cannot take address of numeric label after the function is defined");
203 Res = dyn_cast_or_null<BasicBlock>(
204 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
208 return Error(Refs[i].first.Loc,
209 "referenced value is not a basic block");
211 // Get the BlockAddress for this and update references to use it.
212 BlockAddress *BA = BlockAddress::get(TheFn, Res);
213 Refs[i].second->replaceAllUsesWith(BA);
214 Refs[i].second->eraseFromParent();
220 //===----------------------------------------------------------------------===//
221 // Top-Level Entities
222 //===----------------------------------------------------------------------===//
224 bool LLParser::ParseTopLevelEntities() {
226 switch (Lex.getKind()) {
227 default: return TokError("expected top-level entity");
228 case lltok::Eof: return false;
229 case lltok::kw_declare: if (ParseDeclare()) return true; break;
230 case lltok::kw_define: if (ParseDefine()) return true; break;
231 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
232 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
233 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
234 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
235 case lltok::LocalVar: if (ParseNamedType()) return true; break;
236 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
237 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
238 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
239 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
241 // The Global variable production with no name can have many different
242 // optional leading prefixes, the production is:
243 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
244 // OptionalAddrSpace OptionalUnNammedAddr
245 // ('constant'|'global') ...
246 case lltok::kw_private: // OptionalLinkage
247 case lltok::kw_linker_private: // OptionalLinkage
248 case lltok::kw_linker_private_weak: // OptionalLinkage
249 case lltok::kw_linker_private_weak_def_auto: // FIXME: backwards compat.
250 case lltok::kw_internal: // OptionalLinkage
251 case lltok::kw_weak: // OptionalLinkage
252 case lltok::kw_weak_odr: // OptionalLinkage
253 case lltok::kw_linkonce: // OptionalLinkage
254 case lltok::kw_linkonce_odr: // OptionalLinkage
255 case lltok::kw_linkonce_odr_auto_hide: // OptionalLinkage
256 case lltok::kw_appending: // OptionalLinkage
257 case lltok::kw_dllexport: // OptionalLinkage
258 case lltok::kw_common: // OptionalLinkage
259 case lltok::kw_dllimport: // OptionalLinkage
260 case lltok::kw_extern_weak: // OptionalLinkage
261 case lltok::kw_external: { // OptionalLinkage
262 unsigned Linkage, Visibility;
263 if (ParseOptionalLinkage(Linkage) ||
264 ParseOptionalVisibility(Visibility) ||
265 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
269 case lltok::kw_default: // OptionalVisibility
270 case lltok::kw_hidden: // OptionalVisibility
271 case lltok::kw_protected: { // OptionalVisibility
273 if (ParseOptionalVisibility(Visibility) ||
274 ParseGlobal("", SMLoc(), 0, false, Visibility))
279 case lltok::kw_thread_local: // OptionalThreadLocal
280 case lltok::kw_addrspace: // OptionalAddrSpace
281 case lltok::kw_constant: // GlobalType
282 case lltok::kw_global: // GlobalType
283 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
286 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
293 /// ::= 'module' 'asm' STRINGCONSTANT
294 bool LLParser::ParseModuleAsm() {
295 assert(Lex.getKind() == lltok::kw_module);
299 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
300 ParseStringConstant(AsmStr)) return true;
302 M->appendModuleInlineAsm(AsmStr);
307 /// ::= 'target' 'triple' '=' STRINGCONSTANT
308 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
309 bool LLParser::ParseTargetDefinition() {
310 assert(Lex.getKind() == lltok::kw_target);
313 default: return TokError("unknown target property");
314 case lltok::kw_triple:
316 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
317 ParseStringConstant(Str))
319 M->setTargetTriple(Str);
321 case lltok::kw_datalayout:
323 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
324 ParseStringConstant(Str))
326 M->setDataLayout(Str);
332 /// ::= 'deplibs' '=' '[' ']'
333 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
334 /// FIXME: Remove in 4.0. Currently parse, but ignore.
335 bool LLParser::ParseDepLibs() {
336 assert(Lex.getKind() == lltok::kw_deplibs);
338 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
339 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
342 if (EatIfPresent(lltok::rsquare))
347 if (ParseStringConstant(Str)) return true;
348 } while (EatIfPresent(lltok::comma));
350 return ParseToken(lltok::rsquare, "expected ']' at end of list");
353 /// ParseUnnamedType:
354 /// ::= LocalVarID '=' 'type' type
355 bool LLParser::ParseUnnamedType() {
356 LocTy TypeLoc = Lex.getLoc();
357 unsigned TypeID = Lex.getUIntVal();
358 Lex.Lex(); // eat LocalVarID;
360 if (ParseToken(lltok::equal, "expected '=' after name") ||
361 ParseToken(lltok::kw_type, "expected 'type' after '='"))
364 if (TypeID >= NumberedTypes.size())
365 NumberedTypes.resize(TypeID+1);
368 if (ParseStructDefinition(TypeLoc, "",
369 NumberedTypes[TypeID], Result)) return true;
371 if (!isa<StructType>(Result)) {
372 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
374 return Error(TypeLoc, "non-struct types may not be recursive");
375 Entry.first = Result;
376 Entry.second = SMLoc();
384 /// ::= LocalVar '=' 'type' type
385 bool LLParser::ParseNamedType() {
386 std::string Name = Lex.getStrVal();
387 LocTy NameLoc = Lex.getLoc();
388 Lex.Lex(); // eat LocalVar.
390 if (ParseToken(lltok::equal, "expected '=' after name") ||
391 ParseToken(lltok::kw_type, "expected 'type' after name"))
395 if (ParseStructDefinition(NameLoc, Name,
396 NamedTypes[Name], Result)) return true;
398 if (!isa<StructType>(Result)) {
399 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
401 return Error(NameLoc, "non-struct types may not be recursive");
402 Entry.first = Result;
403 Entry.second = SMLoc();
411 /// ::= 'declare' FunctionHeader
412 bool LLParser::ParseDeclare() {
413 assert(Lex.getKind() == lltok::kw_declare);
417 return ParseFunctionHeader(F, false);
421 /// ::= 'define' FunctionHeader '{' ...
422 bool LLParser::ParseDefine() {
423 assert(Lex.getKind() == lltok::kw_define);
427 return ParseFunctionHeader(F, true) ||
428 ParseFunctionBody(*F);
434 bool LLParser::ParseGlobalType(bool &IsConstant) {
435 if (Lex.getKind() == lltok::kw_constant)
437 else if (Lex.getKind() == lltok::kw_global)
441 return TokError("expected 'global' or 'constant'");
447 /// ParseUnnamedGlobal:
448 /// OptionalVisibility ALIAS ...
449 /// OptionalLinkage OptionalVisibility ... -> global variable
450 /// GlobalID '=' OptionalVisibility ALIAS ...
451 /// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
452 bool LLParser::ParseUnnamedGlobal() {
453 unsigned VarID = NumberedVals.size();
455 LocTy NameLoc = Lex.getLoc();
457 // Handle the GlobalID form.
458 if (Lex.getKind() == lltok::GlobalID) {
459 if (Lex.getUIntVal() != VarID)
460 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
462 Lex.Lex(); // eat GlobalID;
464 if (ParseToken(lltok::equal, "expected '=' after name"))
469 unsigned Linkage, Visibility;
470 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
471 ParseOptionalVisibility(Visibility))
474 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
475 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
476 return ParseAlias(Name, NameLoc, Visibility);
479 /// ParseNamedGlobal:
480 /// GlobalVar '=' OptionalVisibility ALIAS ...
481 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
482 bool LLParser::ParseNamedGlobal() {
483 assert(Lex.getKind() == lltok::GlobalVar);
484 LocTy NameLoc = Lex.getLoc();
485 std::string Name = Lex.getStrVal();
489 unsigned Linkage, Visibility;
490 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
491 ParseOptionalLinkage(Linkage, HasLinkage) ||
492 ParseOptionalVisibility(Visibility))
495 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
496 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
497 return ParseAlias(Name, NameLoc, Visibility);
501 // ::= '!' STRINGCONSTANT
502 bool LLParser::ParseMDString(MDString *&Result) {
504 if (ParseStringConstant(Str)) return true;
505 Result = MDString::get(Context, Str);
510 // ::= '!' MDNodeNumber
512 /// This version of ParseMDNodeID returns the slot number and null in the case
513 /// of a forward reference.
514 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
515 // !{ ..., !42, ... }
516 if (ParseUInt32(SlotNo)) return true;
518 // Check existing MDNode.
519 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
520 Result = NumberedMetadata[SlotNo];
526 bool LLParser::ParseMDNodeID(MDNode *&Result) {
527 // !{ ..., !42, ... }
529 if (ParseMDNodeID(Result, MID)) return true;
531 // If not a forward reference, just return it now.
532 if (Result) return false;
534 // Otherwise, create MDNode forward reference.
535 MDNode *FwdNode = MDNode::getTemporary(Context, None);
536 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
538 if (NumberedMetadata.size() <= MID)
539 NumberedMetadata.resize(MID+1);
540 NumberedMetadata[MID] = FwdNode;
545 /// ParseNamedMetadata:
546 /// !foo = !{ !1, !2 }
547 bool LLParser::ParseNamedMetadata() {
548 assert(Lex.getKind() == lltok::MetadataVar);
549 std::string Name = Lex.getStrVal();
552 if (ParseToken(lltok::equal, "expected '=' here") ||
553 ParseToken(lltok::exclaim, "Expected '!' here") ||
554 ParseToken(lltok::lbrace, "Expected '{' here"))
557 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
558 if (Lex.getKind() != lltok::rbrace)
560 if (ParseToken(lltok::exclaim, "Expected '!' here"))
564 if (ParseMDNodeID(N)) return true;
566 } while (EatIfPresent(lltok::comma));
568 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
574 /// ParseStandaloneMetadata:
576 bool LLParser::ParseStandaloneMetadata() {
577 assert(Lex.getKind() == lltok::exclaim);
579 unsigned MetadataID = 0;
583 SmallVector<Value *, 16> Elts;
584 if (ParseUInt32(MetadataID) ||
585 ParseToken(lltok::equal, "expected '=' here") ||
586 ParseType(Ty, TyLoc) ||
587 ParseToken(lltok::exclaim, "Expected '!' here") ||
588 ParseToken(lltok::lbrace, "Expected '{' here") ||
589 ParseMDNodeVector(Elts, NULL) ||
590 ParseToken(lltok::rbrace, "expected end of metadata node"))
593 MDNode *Init = MDNode::get(Context, Elts);
595 // See if this was forward referenced, if so, handle it.
596 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
597 FI = ForwardRefMDNodes.find(MetadataID);
598 if (FI != ForwardRefMDNodes.end()) {
599 MDNode *Temp = FI->second.first;
600 Temp->replaceAllUsesWith(Init);
601 MDNode::deleteTemporary(Temp);
602 ForwardRefMDNodes.erase(FI);
604 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
606 if (MetadataID >= NumberedMetadata.size())
607 NumberedMetadata.resize(MetadataID+1);
609 if (NumberedMetadata[MetadataID] != 0)
610 return TokError("Metadata id is already used");
611 NumberedMetadata[MetadataID] = Init;
618 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
621 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
622 /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
624 /// Everything through visibility has already been parsed.
626 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
627 unsigned Visibility) {
628 assert(Lex.getKind() == lltok::kw_alias);
630 LocTy LinkageLoc = Lex.getLoc();
632 if (ParseOptionalLinkage(L))
635 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
637 if(!GlobalValue::isExternalLinkage(Linkage) &&
638 !GlobalValue::isLocalLinkage(Linkage) &&
639 !GlobalValue::isWeakLinkage(Linkage) &&
640 !GlobalValue::isLinkOnceLinkage(Linkage))
641 return Error(LinkageLoc, "invalid linkage type for alias");
644 LocTy AliaseeLoc = Lex.getLoc();
645 if (Lex.getKind() != lltok::kw_bitcast &&
646 Lex.getKind() != lltok::kw_getelementptr) {
647 if (ParseGlobalTypeAndValue(Aliasee)) return true;
649 // The bitcast dest type is not present, it is implied by the dest type.
651 if (ParseValID(ID)) return true;
652 if (ID.Kind != ValID::t_Constant)
653 return Error(AliaseeLoc, "invalid aliasee");
654 Aliasee = ID.ConstantVal;
657 if (!Aliasee->getType()->isPointerTy())
658 return Error(AliaseeLoc, "alias must have pointer type");
660 // Okay, create the alias but do not insert it into the module yet.
661 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
662 (GlobalValue::LinkageTypes)Linkage, Name,
664 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
666 // See if this value already exists in the symbol table. If so, it is either
667 // a redefinition or a definition of a forward reference.
668 if (GlobalValue *Val = M->getNamedValue(Name)) {
669 // See if this was a redefinition. If so, there is no entry in
671 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
672 I = ForwardRefVals.find(Name);
673 if (I == ForwardRefVals.end())
674 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
676 // Otherwise, this was a definition of forward ref. Verify that types
678 if (Val->getType() != GA->getType())
679 return Error(NameLoc,
680 "forward reference and definition of alias have different types");
682 // If they agree, just RAUW the old value with the alias and remove the
684 Val->replaceAllUsesWith(GA);
685 Val->eraseFromParent();
686 ForwardRefVals.erase(I);
689 // Insert into the module, we know its name won't collide now.
690 M->getAliasList().push_back(GA);
691 assert(GA->getName() == Name && "Should not be a name conflict!");
697 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
698 /// OptionalAddrSpace OptionalUnNammedAddr
699 /// OptionalExternallyInitialized GlobalType Type Const
700 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
701 /// OptionalAddrSpace OptionalUnNammedAddr
702 /// OptionalExternallyInitialized GlobalType Type Const
704 /// Everything through visibility has been parsed already.
706 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
707 unsigned Linkage, bool HasLinkage,
708 unsigned Visibility) {
710 bool IsConstant, UnnamedAddr, IsExternallyInitialized;
711 GlobalVariable::ThreadLocalMode TLM;
712 LocTy UnnamedAddrLoc;
713 LocTy IsExternallyInitializedLoc;
717 if (ParseOptionalThreadLocal(TLM) ||
718 ParseOptionalAddrSpace(AddrSpace) ||
719 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
721 ParseOptionalToken(lltok::kw_externally_initialized,
722 IsExternallyInitialized,
723 &IsExternallyInitializedLoc) ||
724 ParseGlobalType(IsConstant) ||
725 ParseType(Ty, TyLoc))
728 // If the linkage is specified and is external, then no initializer is
731 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
732 Linkage != GlobalValue::ExternalWeakLinkage &&
733 Linkage != GlobalValue::ExternalLinkage)) {
734 if (ParseGlobalValue(Ty, Init))
738 if (Ty->isFunctionTy() || Ty->isLabelTy())
739 return Error(TyLoc, "invalid type for global variable");
741 GlobalVariable *GV = 0;
743 // See if the global was forward referenced, if so, use the global.
745 if (GlobalValue *GVal = M->getNamedValue(Name)) {
746 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
747 return Error(NameLoc, "redefinition of global '@" + Name + "'");
748 GV = cast<GlobalVariable>(GVal);
751 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
752 I = ForwardRefValIDs.find(NumberedVals.size());
753 if (I != ForwardRefValIDs.end()) {
754 GV = cast<GlobalVariable>(I->second.first);
755 ForwardRefValIDs.erase(I);
760 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
761 Name, 0, GlobalVariable::NotThreadLocal,
764 if (GV->getType()->getElementType() != Ty)
766 "forward reference and definition of global have different types");
768 // Move the forward-reference to the correct spot in the module.
769 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
773 NumberedVals.push_back(GV);
775 // Set the parsed properties on the global.
777 GV->setInitializer(Init);
778 GV->setConstant(IsConstant);
779 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
780 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
781 GV->setExternallyInitialized(IsExternallyInitialized);
782 GV->setThreadLocalMode(TLM);
783 GV->setUnnamedAddr(UnnamedAddr);
785 // Parse attributes on the global.
786 while (Lex.getKind() == lltok::comma) {
789 if (Lex.getKind() == lltok::kw_section) {
791 GV->setSection(Lex.getStrVal());
792 if (ParseToken(lltok::StringConstant, "expected global section string"))
794 } else if (Lex.getKind() == lltok::kw_align) {
796 if (ParseOptionalAlignment(Alignment)) return true;
797 GV->setAlignment(Alignment);
799 TokError("unknown global variable property!");
806 /// ParseUnnamedAttrGrp
807 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
808 bool LLParser::ParseUnnamedAttrGrp() {
809 assert(Lex.getKind() == lltok::kw_attributes);
810 LocTy AttrGrpLoc = Lex.getLoc();
813 assert(Lex.getKind() == lltok::AttrGrpID);
814 unsigned VarID = Lex.getUIntVal();
815 std::vector<unsigned> unused;
819 if (ParseToken(lltok::equal, "expected '=' here") ||
820 ParseToken(lltok::lbrace, "expected '{' here") ||
821 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
823 ParseToken(lltok::rbrace, "expected end of attribute group"))
826 if (!NumberedAttrBuilders[VarID].hasAttributes())
827 return Error(AttrGrpLoc, "attribute group has no attributes");
832 /// ParseFnAttributeValuePairs
833 /// ::= <attr> | <attr> '=' <value>
834 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
835 std::vector<unsigned> &FwdRefAttrGrps,
836 bool inAttrGrp, LocTy &BuiltinLoc) {
837 bool HaveError = false;
842 lltok::Kind Token = Lex.getKind();
843 if (Token == lltok::kw_builtin)
844 BuiltinLoc = Lex.getLoc();
847 if (!inAttrGrp) return HaveError;
848 return Error(Lex.getLoc(), "unterminated attribute group");
853 case lltok::AttrGrpID: {
854 // Allow a function to reference an attribute group:
856 // define void @foo() #1 { ... }
860 "cannot have an attribute group reference in an attribute group");
862 unsigned AttrGrpNum = Lex.getUIntVal();
863 if (inAttrGrp) break;
865 // Save the reference to the attribute group. We'll fill it in later.
866 FwdRefAttrGrps.push_back(AttrGrpNum);
869 // Target-dependent attributes:
870 case lltok::StringConstant: {
871 std::string Attr = Lex.getStrVal();
874 if (EatIfPresent(lltok::equal) &&
875 ParseStringConstant(Val))
878 B.addAttribute(Attr, Val);
882 // Target-independent attributes:
883 case lltok::kw_align: {
884 // As a hack, we allow function alignment to be initially parsed as an
885 // attribute on a function declaration/definition or added to an attribute
886 // group and later moved to the alignment field.
890 if (ParseToken(lltok::equal, "expected '=' here") ||
891 ParseUInt32(Alignment))
894 if (ParseOptionalAlignment(Alignment))
897 B.addAlignmentAttr(Alignment);
900 case lltok::kw_alignstack: {
904 if (ParseToken(lltok::equal, "expected '=' here") ||
905 ParseUInt32(Alignment))
908 if (ParseOptionalStackAlignment(Alignment))
911 B.addStackAlignmentAttr(Alignment);
914 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
915 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
916 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
917 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
918 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
919 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
920 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
921 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
922 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
923 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
924 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
925 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
926 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
927 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
928 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
929 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
930 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
931 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
932 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
933 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
934 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
935 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
936 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
937 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
938 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
939 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
942 case lltok::kw_inreg:
943 case lltok::kw_signext:
944 case lltok::kw_zeroext:
947 "invalid use of attribute on a function");
949 case lltok::kw_byval:
951 case lltok::kw_noalias:
952 case lltok::kw_nocapture:
953 case lltok::kw_returned:
957 "invalid use of parameter-only attribute on a function");
965 //===----------------------------------------------------------------------===//
966 // GlobalValue Reference/Resolution Routines.
967 //===----------------------------------------------------------------------===//
969 /// GetGlobalVal - Get a value with the specified name or ID, creating a
970 /// forward reference record if needed. This can return null if the value
971 /// exists but does not have the right type.
972 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
974 PointerType *PTy = dyn_cast<PointerType>(Ty);
976 Error(Loc, "global variable reference must have pointer type");
980 // Look this name up in the normal function symbol table.
982 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
984 // If this is a forward reference for the value, see if we already created a
985 // forward ref record.
987 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
988 I = ForwardRefVals.find(Name);
989 if (I != ForwardRefVals.end())
990 Val = I->second.first;
993 // If we have the value in the symbol table or fwd-ref table, return it.
995 if (Val->getType() == Ty) return Val;
996 Error(Loc, "'@" + Name + "' defined with type '" +
997 getTypeString(Val->getType()) + "'");
1001 // Otherwise, create a new forward reference for this value and remember it.
1002 GlobalValue *FwdVal;
1003 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1004 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1006 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1007 GlobalValue::ExternalWeakLinkage, 0, Name,
1008 0, GlobalVariable::NotThreadLocal,
1009 PTy->getAddressSpace());
1011 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1015 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1016 PointerType *PTy = dyn_cast<PointerType>(Ty);
1018 Error(Loc, "global variable reference must have pointer type");
1022 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1024 // If this is a forward reference for the value, see if we already created a
1025 // forward ref record.
1027 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1028 I = ForwardRefValIDs.find(ID);
1029 if (I != ForwardRefValIDs.end())
1030 Val = I->second.first;
1033 // If we have the value in the symbol table or fwd-ref table, return it.
1035 if (Val->getType() == Ty) return Val;
1036 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1037 getTypeString(Val->getType()) + "'");
1041 // Otherwise, create a new forward reference for this value and remember it.
1042 GlobalValue *FwdVal;
1043 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1044 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1046 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1047 GlobalValue::ExternalWeakLinkage, 0, "");
1049 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1054 //===----------------------------------------------------------------------===//
1056 //===----------------------------------------------------------------------===//
1058 /// ParseToken - If the current token has the specified kind, eat it and return
1059 /// success. Otherwise, emit the specified error and return failure.
1060 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1061 if (Lex.getKind() != T)
1062 return TokError(ErrMsg);
1067 /// ParseStringConstant
1068 /// ::= StringConstant
1069 bool LLParser::ParseStringConstant(std::string &Result) {
1070 if (Lex.getKind() != lltok::StringConstant)
1071 return TokError("expected string constant");
1072 Result = Lex.getStrVal();
1079 bool LLParser::ParseUInt32(unsigned &Val) {
1080 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1081 return TokError("expected integer");
1082 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1083 if (Val64 != unsigned(Val64))
1084 return TokError("expected 32-bit integer (too large)");
1091 /// := 'localdynamic'
1092 /// := 'initialexec'
1094 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1095 switch (Lex.getKind()) {
1097 return TokError("expected localdynamic, initialexec or localexec");
1098 case lltok::kw_localdynamic:
1099 TLM = GlobalVariable::LocalDynamicTLSModel;
1101 case lltok::kw_initialexec:
1102 TLM = GlobalVariable::InitialExecTLSModel;
1104 case lltok::kw_localexec:
1105 TLM = GlobalVariable::LocalExecTLSModel;
1113 /// ParseOptionalThreadLocal
1115 /// := 'thread_local'
1116 /// := 'thread_local' '(' tlsmodel ')'
1117 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1118 TLM = GlobalVariable::NotThreadLocal;
1119 if (!EatIfPresent(lltok::kw_thread_local))
1122 TLM = GlobalVariable::GeneralDynamicTLSModel;
1123 if (Lex.getKind() == lltok::lparen) {
1125 return ParseTLSModel(TLM) ||
1126 ParseToken(lltok::rparen, "expected ')' after thread local model");
1131 /// ParseOptionalAddrSpace
1133 /// := 'addrspace' '(' uint32 ')'
1134 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1136 if (!EatIfPresent(lltok::kw_addrspace))
1138 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1139 ParseUInt32(AddrSpace) ||
1140 ParseToken(lltok::rparen, "expected ')' in address space");
1143 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1144 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1145 bool HaveError = false;
1150 lltok::Kind Token = Lex.getKind();
1152 default: // End of attributes.
1154 case lltok::kw_align: {
1156 if (ParseOptionalAlignment(Alignment))
1158 B.addAlignmentAttr(Alignment);
1161 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1162 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1163 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1164 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1165 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1166 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1167 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1168 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1169 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1170 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1171 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1173 case lltok::kw_alignstack:
1174 case lltok::kw_alwaysinline:
1175 case lltok::kw_builtin:
1176 case lltok::kw_inlinehint:
1177 case lltok::kw_minsize:
1178 case lltok::kw_naked:
1179 case lltok::kw_nobuiltin:
1180 case lltok::kw_noduplicate:
1181 case lltok::kw_noimplicitfloat:
1182 case lltok::kw_noinline:
1183 case lltok::kw_nonlazybind:
1184 case lltok::kw_noredzone:
1185 case lltok::kw_noreturn:
1186 case lltok::kw_nounwind:
1187 case lltok::kw_optnone:
1188 case lltok::kw_optsize:
1189 case lltok::kw_returns_twice:
1190 case lltok::kw_sanitize_address:
1191 case lltok::kw_sanitize_memory:
1192 case lltok::kw_sanitize_thread:
1194 case lltok::kw_sspreq:
1195 case lltok::kw_sspstrong:
1196 case lltok::kw_uwtable:
1197 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1205 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1206 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1207 bool HaveError = false;
1212 lltok::Kind Token = Lex.getKind();
1214 default: // End of attributes.
1216 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1217 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1218 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1219 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1222 case lltok::kw_align:
1223 case lltok::kw_byval:
1224 case lltok::kw_nest:
1225 case lltok::kw_nocapture:
1226 case lltok::kw_returned:
1227 case lltok::kw_sret:
1228 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1231 case lltok::kw_alignstack:
1232 case lltok::kw_alwaysinline:
1233 case lltok::kw_builtin:
1234 case lltok::kw_cold:
1235 case lltok::kw_inlinehint:
1236 case lltok::kw_minsize:
1237 case lltok::kw_naked:
1238 case lltok::kw_nobuiltin:
1239 case lltok::kw_noduplicate:
1240 case lltok::kw_noimplicitfloat:
1241 case lltok::kw_noinline:
1242 case lltok::kw_nonlazybind:
1243 case lltok::kw_noredzone:
1244 case lltok::kw_noreturn:
1245 case lltok::kw_nounwind:
1246 case lltok::kw_optnone:
1247 case lltok::kw_optsize:
1248 case lltok::kw_returns_twice:
1249 case lltok::kw_sanitize_address:
1250 case lltok::kw_sanitize_memory:
1251 case lltok::kw_sanitize_thread:
1253 case lltok::kw_sspreq:
1254 case lltok::kw_sspstrong:
1255 case lltok::kw_uwtable:
1256 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1259 case lltok::kw_readnone:
1260 case lltok::kw_readonly:
1261 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1268 /// ParseOptionalLinkage
1271 /// ::= 'linker_private'
1272 /// ::= 'linker_private_weak'
1277 /// ::= 'linkonce_odr'
1278 /// ::= 'linkonce_odr_auto_hide'
1279 /// ::= 'available_externally'
1284 /// ::= 'extern_weak'
1286 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1288 switch (Lex.getKind()) {
1289 default: Res=GlobalValue::ExternalLinkage; return false;
1290 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1291 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
1292 case lltok::kw_linker_private_weak:
1293 Res = GlobalValue::LinkerPrivateWeakLinkage;
1295 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1296 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1297 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1298 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1299 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1300 case lltok::kw_linkonce_odr_auto_hide:
1301 case lltok::kw_linker_private_weak_def_auto: // FIXME: For backwards compat.
1302 Res = GlobalValue::LinkOnceODRAutoHideLinkage;
1304 case lltok::kw_available_externally:
1305 Res = GlobalValue::AvailableExternallyLinkage;
1307 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1308 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1309 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1310 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1311 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1312 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1319 /// ParseOptionalVisibility
1325 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1326 switch (Lex.getKind()) {
1327 default: Res = GlobalValue::DefaultVisibility; return false;
1328 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1329 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1330 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1336 /// ParseOptionalCallingConv
1340 /// ::= 'kw_intel_ocl_bicc'
1342 /// ::= 'x86_stdcallcc'
1343 /// ::= 'x86_fastcallcc'
1344 /// ::= 'x86_thiscallcc'
1345 /// ::= 'arm_apcscc'
1346 /// ::= 'arm_aapcscc'
1347 /// ::= 'arm_aapcs_vfpcc'
1348 /// ::= 'msp430_intrcc'
1349 /// ::= 'ptx_kernel'
1350 /// ::= 'ptx_device'
1352 /// ::= 'spir_kernel'
1353 /// ::= 'x86_64_sysvcc'
1354 /// ::= 'x86_64_win64cc'
1357 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1358 switch (Lex.getKind()) {
1359 default: CC = CallingConv::C; return false;
1360 case lltok::kw_ccc: CC = CallingConv::C; break;
1361 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1362 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1363 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1364 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1365 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1366 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1367 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1368 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1369 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1370 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1371 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1372 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1373 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1374 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1375 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1376 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1377 case lltok::kw_cc: {
1378 unsigned ArbitraryCC;
1380 if (ParseUInt32(ArbitraryCC))
1382 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1391 /// ParseInstructionMetadata
1392 /// ::= !dbg !42 (',' !dbg !57)*
1393 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1394 PerFunctionState *PFS) {
1396 if (Lex.getKind() != lltok::MetadataVar)
1397 return TokError("expected metadata after comma");
1399 std::string Name = Lex.getStrVal();
1400 unsigned MDK = M->getMDKindID(Name);
1404 SMLoc Loc = Lex.getLoc();
1406 if (ParseToken(lltok::exclaim, "expected '!' here"))
1409 // This code is similar to that of ParseMetadataValue, however it needs to
1410 // have special-case code for a forward reference; see the comments on
1411 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1412 // at the top level here.
1413 if (Lex.getKind() == lltok::lbrace) {
1415 if (ParseMetadataListValue(ID, PFS))
1417 assert(ID.Kind == ValID::t_MDNode);
1418 Inst->setMetadata(MDK, ID.MDNodeVal);
1420 unsigned NodeID = 0;
1421 if (ParseMDNodeID(Node, NodeID))
1424 // If we got the node, add it to the instruction.
1425 Inst->setMetadata(MDK, Node);
1427 MDRef R = { Loc, MDK, NodeID };
1428 // Otherwise, remember that this should be resolved later.
1429 ForwardRefInstMetadata[Inst].push_back(R);
1433 if (MDK == LLVMContext::MD_tbaa)
1434 InstsWithTBAATag.push_back(Inst);
1436 // If this is the end of the list, we're done.
1437 } while (EatIfPresent(lltok::comma));
1441 /// ParseOptionalAlignment
1444 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1446 if (!EatIfPresent(lltok::kw_align))
1448 LocTy AlignLoc = Lex.getLoc();
1449 if (ParseUInt32(Alignment)) return true;
1450 if (!isPowerOf2_32(Alignment))
1451 return Error(AlignLoc, "alignment is not a power of two");
1452 if (Alignment > Value::MaximumAlignment)
1453 return Error(AlignLoc, "huge alignments are not supported yet");
1457 /// ParseOptionalCommaAlign
1461 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1463 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1464 bool &AteExtraComma) {
1465 AteExtraComma = false;
1466 while (EatIfPresent(lltok::comma)) {
1467 // Metadata at the end is an early exit.
1468 if (Lex.getKind() == lltok::MetadataVar) {
1469 AteExtraComma = true;
1473 if (Lex.getKind() != lltok::kw_align)
1474 return Error(Lex.getLoc(), "expected metadata or 'align'");
1476 if (ParseOptionalAlignment(Alignment)) return true;
1482 /// ParseScopeAndOrdering
1483 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1486 /// This sets Scope and Ordering to the parsed values.
1487 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1488 AtomicOrdering &Ordering) {
1492 Scope = CrossThread;
1493 if (EatIfPresent(lltok::kw_singlethread))
1494 Scope = SingleThread;
1495 switch (Lex.getKind()) {
1496 default: return TokError("Expected ordering on atomic instruction");
1497 case lltok::kw_unordered: Ordering = Unordered; break;
1498 case lltok::kw_monotonic: Ordering = Monotonic; break;
1499 case lltok::kw_acquire: Ordering = Acquire; break;
1500 case lltok::kw_release: Ordering = Release; break;
1501 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1502 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1508 /// ParseOptionalStackAlignment
1510 /// ::= 'alignstack' '(' 4 ')'
1511 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1513 if (!EatIfPresent(lltok::kw_alignstack))
1515 LocTy ParenLoc = Lex.getLoc();
1516 if (!EatIfPresent(lltok::lparen))
1517 return Error(ParenLoc, "expected '('");
1518 LocTy AlignLoc = Lex.getLoc();
1519 if (ParseUInt32(Alignment)) return true;
1520 ParenLoc = Lex.getLoc();
1521 if (!EatIfPresent(lltok::rparen))
1522 return Error(ParenLoc, "expected ')'");
1523 if (!isPowerOf2_32(Alignment))
1524 return Error(AlignLoc, "stack alignment is not a power of two");
1528 /// ParseIndexList - This parses the index list for an insert/extractvalue
1529 /// instruction. This sets AteExtraComma in the case where we eat an extra
1530 /// comma at the end of the line and find that it is followed by metadata.
1531 /// Clients that don't allow metadata can call the version of this function that
1532 /// only takes one argument.
1535 /// ::= (',' uint32)+
1537 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1538 bool &AteExtraComma) {
1539 AteExtraComma = false;
1541 if (Lex.getKind() != lltok::comma)
1542 return TokError("expected ',' as start of index list");
1544 while (EatIfPresent(lltok::comma)) {
1545 if (Lex.getKind() == lltok::MetadataVar) {
1546 AteExtraComma = true;
1550 if (ParseUInt32(Idx)) return true;
1551 Indices.push_back(Idx);
1557 //===----------------------------------------------------------------------===//
1559 //===----------------------------------------------------------------------===//
1561 /// ParseType - Parse a type.
1562 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1563 SMLoc TypeLoc = Lex.getLoc();
1564 switch (Lex.getKind()) {
1566 return TokError("expected type");
1568 // Type ::= 'float' | 'void' (etc)
1569 Result = Lex.getTyVal();
1573 // Type ::= StructType
1574 if (ParseAnonStructType(Result, false))
1577 case lltok::lsquare:
1578 // Type ::= '[' ... ']'
1579 Lex.Lex(); // eat the lsquare.
1580 if (ParseArrayVectorType(Result, false))
1583 case lltok::less: // Either vector or packed struct.
1584 // Type ::= '<' ... '>'
1586 if (Lex.getKind() == lltok::lbrace) {
1587 if (ParseAnonStructType(Result, true) ||
1588 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1590 } else if (ParseArrayVectorType(Result, true))
1593 case lltok::LocalVar: {
1595 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1597 // If the type hasn't been defined yet, create a forward definition and
1598 // remember where that forward def'n was seen (in case it never is defined).
1599 if (Entry.first == 0) {
1600 Entry.first = StructType::create(Context, Lex.getStrVal());
1601 Entry.second = Lex.getLoc();
1603 Result = Entry.first;
1608 case lltok::LocalVarID: {
1610 if (Lex.getUIntVal() >= NumberedTypes.size())
1611 NumberedTypes.resize(Lex.getUIntVal()+1);
1612 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1614 // If the type hasn't been defined yet, create a forward definition and
1615 // remember where that forward def'n was seen (in case it never is defined).
1616 if (Entry.first == 0) {
1617 Entry.first = StructType::create(Context);
1618 Entry.second = Lex.getLoc();
1620 Result = Entry.first;
1626 // Parse the type suffixes.
1628 switch (Lex.getKind()) {
1631 if (!AllowVoid && Result->isVoidTy())
1632 return Error(TypeLoc, "void type only allowed for function results");
1635 // Type ::= Type '*'
1637 if (Result->isLabelTy())
1638 return TokError("basic block pointers are invalid");
1639 if (Result->isVoidTy())
1640 return TokError("pointers to void are invalid - use i8* instead");
1641 if (!PointerType::isValidElementType(Result))
1642 return TokError("pointer to this type is invalid");
1643 Result = PointerType::getUnqual(Result);
1647 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1648 case lltok::kw_addrspace: {
1649 if (Result->isLabelTy())
1650 return TokError("basic block pointers are invalid");
1651 if (Result->isVoidTy())
1652 return TokError("pointers to void are invalid; use i8* instead");
1653 if (!PointerType::isValidElementType(Result))
1654 return TokError("pointer to this type is invalid");
1656 if (ParseOptionalAddrSpace(AddrSpace) ||
1657 ParseToken(lltok::star, "expected '*' in address space"))
1660 Result = PointerType::get(Result, AddrSpace);
1664 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1666 if (ParseFunctionType(Result))
1673 /// ParseParameterList
1675 /// ::= '(' Arg (',' Arg)* ')'
1677 /// ::= Type OptionalAttributes Value OptionalAttributes
1678 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1679 PerFunctionState &PFS) {
1680 if (ParseToken(lltok::lparen, "expected '(' in call"))
1683 unsigned AttrIndex = 1;
1684 while (Lex.getKind() != lltok::rparen) {
1685 // If this isn't the first argument, we need a comma.
1686 if (!ArgList.empty() &&
1687 ParseToken(lltok::comma, "expected ',' in argument list"))
1690 // Parse the argument.
1693 AttrBuilder ArgAttrs;
1695 if (ParseType(ArgTy, ArgLoc))
1698 // Otherwise, handle normal operands.
1699 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1701 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1706 Lex.Lex(); // Lex the ')'.
1712 /// ParseArgumentList - Parse the argument list for a function type or function
1714 /// ::= '(' ArgTypeListI ')'
1718 /// ::= ArgTypeList ',' '...'
1719 /// ::= ArgType (',' ArgType)*
1721 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1724 assert(Lex.getKind() == lltok::lparen);
1725 Lex.Lex(); // eat the (.
1727 if (Lex.getKind() == lltok::rparen) {
1729 } else if (Lex.getKind() == lltok::dotdotdot) {
1733 LocTy TypeLoc = Lex.getLoc();
1738 if (ParseType(ArgTy) ||
1739 ParseOptionalParamAttrs(Attrs)) return true;
1741 if (ArgTy->isVoidTy())
1742 return Error(TypeLoc, "argument can not have void type");
1744 if (Lex.getKind() == lltok::LocalVar) {
1745 Name = Lex.getStrVal();
1749 if (!FunctionType::isValidArgumentType(ArgTy))
1750 return Error(TypeLoc, "invalid type for function argument");
1752 unsigned AttrIndex = 1;
1753 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1754 AttributeSet::get(ArgTy->getContext(),
1755 AttrIndex++, Attrs), Name));
1757 while (EatIfPresent(lltok::comma)) {
1758 // Handle ... at end of arg list.
1759 if (EatIfPresent(lltok::dotdotdot)) {
1764 // Otherwise must be an argument type.
1765 TypeLoc = Lex.getLoc();
1766 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1768 if (ArgTy->isVoidTy())
1769 return Error(TypeLoc, "argument can not have void type");
1771 if (Lex.getKind() == lltok::LocalVar) {
1772 Name = Lex.getStrVal();
1778 if (!ArgTy->isFirstClassType())
1779 return Error(TypeLoc, "invalid type for function argument");
1781 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1782 AttributeSet::get(ArgTy->getContext(),
1783 AttrIndex++, Attrs),
1788 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1791 /// ParseFunctionType
1792 /// ::= Type ArgumentList OptionalAttrs
1793 bool LLParser::ParseFunctionType(Type *&Result) {
1794 assert(Lex.getKind() == lltok::lparen);
1796 if (!FunctionType::isValidReturnType(Result))
1797 return TokError("invalid function return type");
1799 SmallVector<ArgInfo, 8> ArgList;
1801 if (ParseArgumentList(ArgList, isVarArg))
1804 // Reject names on the arguments lists.
1805 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1806 if (!ArgList[i].Name.empty())
1807 return Error(ArgList[i].Loc, "argument name invalid in function type");
1808 if (ArgList[i].Attrs.hasAttributes(i + 1))
1809 return Error(ArgList[i].Loc,
1810 "argument attributes invalid in function type");
1813 SmallVector<Type*, 16> ArgListTy;
1814 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1815 ArgListTy.push_back(ArgList[i].Ty);
1817 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1821 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1823 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1824 SmallVector<Type*, 8> Elts;
1825 if (ParseStructBody(Elts)) return true;
1827 Result = StructType::get(Context, Elts, Packed);
1831 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1832 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1833 std::pair<Type*, LocTy> &Entry,
1835 // If the type was already defined, diagnose the redefinition.
1836 if (Entry.first && !Entry.second.isValid())
1837 return Error(TypeLoc, "redefinition of type");
1839 // If we have opaque, just return without filling in the definition for the
1840 // struct. This counts as a definition as far as the .ll file goes.
1841 if (EatIfPresent(lltok::kw_opaque)) {
1842 // This type is being defined, so clear the location to indicate this.
1843 Entry.second = SMLoc();
1845 // If this type number has never been uttered, create it.
1846 if (Entry.first == 0)
1847 Entry.first = StructType::create(Context, Name);
1848 ResultTy = Entry.first;
1852 // If the type starts with '<', then it is either a packed struct or a vector.
1853 bool isPacked = EatIfPresent(lltok::less);
1855 // If we don't have a struct, then we have a random type alias, which we
1856 // accept for compatibility with old files. These types are not allowed to be
1857 // forward referenced and not allowed to be recursive.
1858 if (Lex.getKind() != lltok::lbrace) {
1860 return Error(TypeLoc, "forward references to non-struct type");
1864 return ParseArrayVectorType(ResultTy, true);
1865 return ParseType(ResultTy);
1868 // This type is being defined, so clear the location to indicate this.
1869 Entry.second = SMLoc();
1871 // If this type number has never been uttered, create it.
1872 if (Entry.first == 0)
1873 Entry.first = StructType::create(Context, Name);
1875 StructType *STy = cast<StructType>(Entry.first);
1877 SmallVector<Type*, 8> Body;
1878 if (ParseStructBody(Body) ||
1879 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1882 STy->setBody(Body, isPacked);
1888 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1891 /// ::= '{' Type (',' Type)* '}'
1892 /// ::= '<' '{' '}' '>'
1893 /// ::= '<' '{' Type (',' Type)* '}' '>'
1894 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
1895 assert(Lex.getKind() == lltok::lbrace);
1896 Lex.Lex(); // Consume the '{'
1898 // Handle the empty struct.
1899 if (EatIfPresent(lltok::rbrace))
1902 LocTy EltTyLoc = Lex.getLoc();
1904 if (ParseType(Ty)) return true;
1907 if (!StructType::isValidElementType(Ty))
1908 return Error(EltTyLoc, "invalid element type for struct");
1910 while (EatIfPresent(lltok::comma)) {
1911 EltTyLoc = Lex.getLoc();
1912 if (ParseType(Ty)) return true;
1914 if (!StructType::isValidElementType(Ty))
1915 return Error(EltTyLoc, "invalid element type for struct");
1920 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
1923 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1924 /// token has already been consumed.
1926 /// ::= '[' APSINTVAL 'x' Types ']'
1927 /// ::= '<' APSINTVAL 'x' Types '>'
1928 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
1929 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1930 Lex.getAPSIntVal().getBitWidth() > 64)
1931 return TokError("expected number in address space");
1933 LocTy SizeLoc = Lex.getLoc();
1934 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1937 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1940 LocTy TypeLoc = Lex.getLoc();
1942 if (ParseType(EltTy)) return true;
1944 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1945 "expected end of sequential type"))
1950 return Error(SizeLoc, "zero element vector is illegal");
1951 if ((unsigned)Size != Size)
1952 return Error(SizeLoc, "size too large for vector");
1953 if (!VectorType::isValidElementType(EltTy))
1954 return Error(TypeLoc, "invalid vector element type");
1955 Result = VectorType::get(EltTy, unsigned(Size));
1957 if (!ArrayType::isValidElementType(EltTy))
1958 return Error(TypeLoc, "invalid array element type");
1959 Result = ArrayType::get(EltTy, Size);
1964 //===----------------------------------------------------------------------===//
1965 // Function Semantic Analysis.
1966 //===----------------------------------------------------------------------===//
1968 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1970 : P(p), F(f), FunctionNumber(functionNumber) {
1972 // Insert unnamed arguments into the NumberedVals list.
1973 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1976 NumberedVals.push_back(AI);
1979 LLParser::PerFunctionState::~PerFunctionState() {
1980 // If there were any forward referenced non-basicblock values, delete them.
1981 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1982 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1983 if (!isa<BasicBlock>(I->second.first)) {
1984 I->second.first->replaceAllUsesWith(
1985 UndefValue::get(I->second.first->getType()));
1986 delete I->second.first;
1987 I->second.first = 0;
1990 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1991 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1992 if (!isa<BasicBlock>(I->second.first)) {
1993 I->second.first->replaceAllUsesWith(
1994 UndefValue::get(I->second.first->getType()));
1995 delete I->second.first;
1996 I->second.first = 0;
2000 bool LLParser::PerFunctionState::FinishFunction() {
2001 // Check to see if someone took the address of labels in this block.
2002 if (!P.ForwardRefBlockAddresses.empty()) {
2004 if (!F.getName().empty()) {
2005 FunctionID.Kind = ValID::t_GlobalName;
2006 FunctionID.StrVal = F.getName();
2008 FunctionID.Kind = ValID::t_GlobalID;
2009 FunctionID.UIntVal = FunctionNumber;
2012 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
2013 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
2014 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
2015 // Resolve all these references.
2016 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
2019 P.ForwardRefBlockAddresses.erase(FRBAI);
2023 if (!ForwardRefVals.empty())
2024 return P.Error(ForwardRefVals.begin()->second.second,
2025 "use of undefined value '%" + ForwardRefVals.begin()->first +
2027 if (!ForwardRefValIDs.empty())
2028 return P.Error(ForwardRefValIDs.begin()->second.second,
2029 "use of undefined value '%" +
2030 Twine(ForwardRefValIDs.begin()->first) + "'");
2035 /// GetVal - Get a value with the specified name or ID, creating a
2036 /// forward reference record if needed. This can return null if the value
2037 /// exists but does not have the right type.
2038 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2039 Type *Ty, LocTy Loc) {
2040 // Look this name up in the normal function symbol table.
2041 Value *Val = F.getValueSymbolTable().lookup(Name);
2043 // If this is a forward reference for the value, see if we already created a
2044 // forward ref record.
2046 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2047 I = ForwardRefVals.find(Name);
2048 if (I != ForwardRefVals.end())
2049 Val = I->second.first;
2052 // If we have the value in the symbol table or fwd-ref table, return it.
2054 if (Val->getType() == Ty) return Val;
2055 if (Ty->isLabelTy())
2056 P.Error(Loc, "'%" + Name + "' is not a basic block");
2058 P.Error(Loc, "'%" + Name + "' defined with type '" +
2059 getTypeString(Val->getType()) + "'");
2063 // Don't make placeholders with invalid type.
2064 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2065 P.Error(Loc, "invalid use of a non-first-class type");
2069 // Otherwise, create a new forward reference for this value and remember it.
2071 if (Ty->isLabelTy())
2072 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2074 FwdVal = new Argument(Ty, Name);
2076 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2080 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2082 // Look this name up in the normal function symbol table.
2083 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
2085 // If this is a forward reference for the value, see if we already created a
2086 // forward ref record.
2088 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2089 I = ForwardRefValIDs.find(ID);
2090 if (I != ForwardRefValIDs.end())
2091 Val = I->second.first;
2094 // If we have the value in the symbol table or fwd-ref table, return it.
2096 if (Val->getType() == Ty) return Val;
2097 if (Ty->isLabelTy())
2098 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2100 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2101 getTypeString(Val->getType()) + "'");
2105 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2106 P.Error(Loc, "invalid use of a non-first-class type");
2110 // Otherwise, create a new forward reference for this value and remember it.
2112 if (Ty->isLabelTy())
2113 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2115 FwdVal = new Argument(Ty);
2117 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2121 /// SetInstName - After an instruction is parsed and inserted into its
2122 /// basic block, this installs its name.
2123 bool LLParser::PerFunctionState::SetInstName(int NameID,
2124 const std::string &NameStr,
2125 LocTy NameLoc, Instruction *Inst) {
2126 // If this instruction has void type, it cannot have a name or ID specified.
2127 if (Inst->getType()->isVoidTy()) {
2128 if (NameID != -1 || !NameStr.empty())
2129 return P.Error(NameLoc, "instructions returning void cannot have a name");
2133 // If this was a numbered instruction, verify that the instruction is the
2134 // expected value and resolve any forward references.
2135 if (NameStr.empty()) {
2136 // If neither a name nor an ID was specified, just use the next ID.
2138 NameID = NumberedVals.size();
2140 if (unsigned(NameID) != NumberedVals.size())
2141 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2142 Twine(NumberedVals.size()) + "'");
2144 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2145 ForwardRefValIDs.find(NameID);
2146 if (FI != ForwardRefValIDs.end()) {
2147 if (FI->second.first->getType() != Inst->getType())
2148 return P.Error(NameLoc, "instruction forward referenced with type '" +
2149 getTypeString(FI->second.first->getType()) + "'");
2150 FI->second.first->replaceAllUsesWith(Inst);
2151 delete FI->second.first;
2152 ForwardRefValIDs.erase(FI);
2155 NumberedVals.push_back(Inst);
2159 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2160 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2161 FI = ForwardRefVals.find(NameStr);
2162 if (FI != ForwardRefVals.end()) {
2163 if (FI->second.first->getType() != Inst->getType())
2164 return P.Error(NameLoc, "instruction forward referenced with type '" +
2165 getTypeString(FI->second.first->getType()) + "'");
2166 FI->second.first->replaceAllUsesWith(Inst);
2167 delete FI->second.first;
2168 ForwardRefVals.erase(FI);
2171 // Set the name on the instruction.
2172 Inst->setName(NameStr);
2174 if (Inst->getName() != NameStr)
2175 return P.Error(NameLoc, "multiple definition of local value named '" +
2180 /// GetBB - Get a basic block with the specified name or ID, creating a
2181 /// forward reference record if needed.
2182 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2184 return cast_or_null<BasicBlock>(GetVal(Name,
2185 Type::getLabelTy(F.getContext()), Loc));
2188 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2189 return cast_or_null<BasicBlock>(GetVal(ID,
2190 Type::getLabelTy(F.getContext()), Loc));
2193 /// DefineBB - Define the specified basic block, which is either named or
2194 /// unnamed. If there is an error, this returns null otherwise it returns
2195 /// the block being defined.
2196 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2200 BB = GetBB(NumberedVals.size(), Loc);
2202 BB = GetBB(Name, Loc);
2203 if (BB == 0) return 0; // Already diagnosed error.
2205 // Move the block to the end of the function. Forward ref'd blocks are
2206 // inserted wherever they happen to be referenced.
2207 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2209 // Remove the block from forward ref sets.
2211 ForwardRefValIDs.erase(NumberedVals.size());
2212 NumberedVals.push_back(BB);
2214 // BB forward references are already in the function symbol table.
2215 ForwardRefVals.erase(Name);
2221 //===----------------------------------------------------------------------===//
2223 //===----------------------------------------------------------------------===//
2225 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2226 /// type implied. For example, if we parse "4" we don't know what integer type
2227 /// it has. The value will later be combined with its type and checked for
2228 /// sanity. PFS is used to convert function-local operands of metadata (since
2229 /// metadata operands are not just parsed here but also converted to values).
2230 /// PFS can be null when we are not parsing metadata values inside a function.
2231 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2232 ID.Loc = Lex.getLoc();
2233 switch (Lex.getKind()) {
2234 default: return TokError("expected value token");
2235 case lltok::GlobalID: // @42
2236 ID.UIntVal = Lex.getUIntVal();
2237 ID.Kind = ValID::t_GlobalID;
2239 case lltok::GlobalVar: // @foo
2240 ID.StrVal = Lex.getStrVal();
2241 ID.Kind = ValID::t_GlobalName;
2243 case lltok::LocalVarID: // %42
2244 ID.UIntVal = Lex.getUIntVal();
2245 ID.Kind = ValID::t_LocalID;
2247 case lltok::LocalVar: // %foo
2248 ID.StrVal = Lex.getStrVal();
2249 ID.Kind = ValID::t_LocalName;
2251 case lltok::exclaim: // !42, !{...}, or !"foo"
2252 return ParseMetadataValue(ID, PFS);
2254 ID.APSIntVal = Lex.getAPSIntVal();
2255 ID.Kind = ValID::t_APSInt;
2257 case lltok::APFloat:
2258 ID.APFloatVal = Lex.getAPFloatVal();
2259 ID.Kind = ValID::t_APFloat;
2261 case lltok::kw_true:
2262 ID.ConstantVal = ConstantInt::getTrue(Context);
2263 ID.Kind = ValID::t_Constant;
2265 case lltok::kw_false:
2266 ID.ConstantVal = ConstantInt::getFalse(Context);
2267 ID.Kind = ValID::t_Constant;
2269 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2270 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2271 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2273 case lltok::lbrace: {
2274 // ValID ::= '{' ConstVector '}'
2276 SmallVector<Constant*, 16> Elts;
2277 if (ParseGlobalValueVector(Elts) ||
2278 ParseToken(lltok::rbrace, "expected end of struct constant"))
2281 ID.ConstantStructElts = new Constant*[Elts.size()];
2282 ID.UIntVal = Elts.size();
2283 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2284 ID.Kind = ValID::t_ConstantStruct;
2288 // ValID ::= '<' ConstVector '>' --> Vector.
2289 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2291 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2293 SmallVector<Constant*, 16> Elts;
2294 LocTy FirstEltLoc = Lex.getLoc();
2295 if (ParseGlobalValueVector(Elts) ||
2297 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2298 ParseToken(lltok::greater, "expected end of constant"))
2301 if (isPackedStruct) {
2302 ID.ConstantStructElts = new Constant*[Elts.size()];
2303 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2304 ID.UIntVal = Elts.size();
2305 ID.Kind = ValID::t_PackedConstantStruct;
2310 return Error(ID.Loc, "constant vector must not be empty");
2312 if (!Elts[0]->getType()->isIntegerTy() &&
2313 !Elts[0]->getType()->isFloatingPointTy() &&
2314 !Elts[0]->getType()->isPointerTy())
2315 return Error(FirstEltLoc,
2316 "vector elements must have integer, pointer or floating point type");
2318 // Verify that all the vector elements have the same type.
2319 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2320 if (Elts[i]->getType() != Elts[0]->getType())
2321 return Error(FirstEltLoc,
2322 "vector element #" + Twine(i) +
2323 " is not of type '" + getTypeString(Elts[0]->getType()));
2325 ID.ConstantVal = ConstantVector::get(Elts);
2326 ID.Kind = ValID::t_Constant;
2329 case lltok::lsquare: { // Array Constant
2331 SmallVector<Constant*, 16> Elts;
2332 LocTy FirstEltLoc = Lex.getLoc();
2333 if (ParseGlobalValueVector(Elts) ||
2334 ParseToken(lltok::rsquare, "expected end of array constant"))
2337 // Handle empty element.
2339 // Use undef instead of an array because it's inconvenient to determine
2340 // the element type at this point, there being no elements to examine.
2341 ID.Kind = ValID::t_EmptyArray;
2345 if (!Elts[0]->getType()->isFirstClassType())
2346 return Error(FirstEltLoc, "invalid array element type: " +
2347 getTypeString(Elts[0]->getType()));
2349 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2351 // Verify all elements are correct type!
2352 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2353 if (Elts[i]->getType() != Elts[0]->getType())
2354 return Error(FirstEltLoc,
2355 "array element #" + Twine(i) +
2356 " is not of type '" + getTypeString(Elts[0]->getType()));
2359 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2360 ID.Kind = ValID::t_Constant;
2363 case lltok::kw_c: // c "foo"
2365 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2367 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2368 ID.Kind = ValID::t_Constant;
2371 case lltok::kw_asm: {
2372 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2374 bool HasSideEffect, AlignStack, AsmDialect;
2376 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2377 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2378 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2379 ParseStringConstant(ID.StrVal) ||
2380 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2381 ParseToken(lltok::StringConstant, "expected constraint string"))
2383 ID.StrVal2 = Lex.getStrVal();
2384 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2385 (unsigned(AsmDialect)<<2);
2386 ID.Kind = ValID::t_InlineAsm;
2390 case lltok::kw_blockaddress: {
2391 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2396 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2398 ParseToken(lltok::comma, "expected comma in block address expression")||
2399 ParseValID(Label) ||
2400 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2403 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2404 return Error(Fn.Loc, "expected function name in blockaddress");
2405 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2406 return Error(Label.Loc, "expected basic block name in blockaddress");
2408 // Make a global variable as a placeholder for this reference.
2409 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2410 false, GlobalValue::InternalLinkage,
2412 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2413 ID.ConstantVal = FwdRef;
2414 ID.Kind = ValID::t_Constant;
2418 case lltok::kw_trunc:
2419 case lltok::kw_zext:
2420 case lltok::kw_sext:
2421 case lltok::kw_fptrunc:
2422 case lltok::kw_fpext:
2423 case lltok::kw_bitcast:
2424 case lltok::kw_uitofp:
2425 case lltok::kw_sitofp:
2426 case lltok::kw_fptoui:
2427 case lltok::kw_fptosi:
2428 case lltok::kw_inttoptr:
2429 case lltok::kw_ptrtoint: {
2430 unsigned Opc = Lex.getUIntVal();
2434 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2435 ParseGlobalTypeAndValue(SrcVal) ||
2436 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2437 ParseType(DestTy) ||
2438 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2440 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2441 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2442 getTypeString(SrcVal->getType()) + "' to '" +
2443 getTypeString(DestTy) + "'");
2444 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2446 ID.Kind = ValID::t_Constant;
2449 case lltok::kw_extractvalue: {
2452 SmallVector<unsigned, 4> Indices;
2453 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2454 ParseGlobalTypeAndValue(Val) ||
2455 ParseIndexList(Indices) ||
2456 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2459 if (!Val->getType()->isAggregateType())
2460 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2461 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2462 return Error(ID.Loc, "invalid indices for extractvalue");
2463 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2464 ID.Kind = ValID::t_Constant;
2467 case lltok::kw_insertvalue: {
2469 Constant *Val0, *Val1;
2470 SmallVector<unsigned, 4> Indices;
2471 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2472 ParseGlobalTypeAndValue(Val0) ||
2473 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2474 ParseGlobalTypeAndValue(Val1) ||
2475 ParseIndexList(Indices) ||
2476 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2478 if (!Val0->getType()->isAggregateType())
2479 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2480 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2481 return Error(ID.Loc, "invalid indices for insertvalue");
2482 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2483 ID.Kind = ValID::t_Constant;
2486 case lltok::kw_icmp:
2487 case lltok::kw_fcmp: {
2488 unsigned PredVal, Opc = Lex.getUIntVal();
2489 Constant *Val0, *Val1;
2491 if (ParseCmpPredicate(PredVal, Opc) ||
2492 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2493 ParseGlobalTypeAndValue(Val0) ||
2494 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2495 ParseGlobalTypeAndValue(Val1) ||
2496 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2499 if (Val0->getType() != Val1->getType())
2500 return Error(ID.Loc, "compare operands must have the same type");
2502 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2504 if (Opc == Instruction::FCmp) {
2505 if (!Val0->getType()->isFPOrFPVectorTy())
2506 return Error(ID.Loc, "fcmp requires floating point operands");
2507 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2509 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2510 if (!Val0->getType()->isIntOrIntVectorTy() &&
2511 !Val0->getType()->getScalarType()->isPointerTy())
2512 return Error(ID.Loc, "icmp requires pointer or integer operands");
2513 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2515 ID.Kind = ValID::t_Constant;
2519 // Binary Operators.
2521 case lltok::kw_fadd:
2523 case lltok::kw_fsub:
2525 case lltok::kw_fmul:
2526 case lltok::kw_udiv:
2527 case lltok::kw_sdiv:
2528 case lltok::kw_fdiv:
2529 case lltok::kw_urem:
2530 case lltok::kw_srem:
2531 case lltok::kw_frem:
2533 case lltok::kw_lshr:
2534 case lltok::kw_ashr: {
2538 unsigned Opc = Lex.getUIntVal();
2539 Constant *Val0, *Val1;
2541 LocTy ModifierLoc = Lex.getLoc();
2542 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2543 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2544 if (EatIfPresent(lltok::kw_nuw))
2546 if (EatIfPresent(lltok::kw_nsw)) {
2548 if (EatIfPresent(lltok::kw_nuw))
2551 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2552 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2553 if (EatIfPresent(lltok::kw_exact))
2556 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2557 ParseGlobalTypeAndValue(Val0) ||
2558 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2559 ParseGlobalTypeAndValue(Val1) ||
2560 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2562 if (Val0->getType() != Val1->getType())
2563 return Error(ID.Loc, "operands of constexpr must have same type");
2564 if (!Val0->getType()->isIntOrIntVectorTy()) {
2566 return Error(ModifierLoc, "nuw only applies to integer operations");
2568 return Error(ModifierLoc, "nsw only applies to integer operations");
2570 // Check that the type is valid for the operator.
2572 case Instruction::Add:
2573 case Instruction::Sub:
2574 case Instruction::Mul:
2575 case Instruction::UDiv:
2576 case Instruction::SDiv:
2577 case Instruction::URem:
2578 case Instruction::SRem:
2579 case Instruction::Shl:
2580 case Instruction::AShr:
2581 case Instruction::LShr:
2582 if (!Val0->getType()->isIntOrIntVectorTy())
2583 return Error(ID.Loc, "constexpr requires integer operands");
2585 case Instruction::FAdd:
2586 case Instruction::FSub:
2587 case Instruction::FMul:
2588 case Instruction::FDiv:
2589 case Instruction::FRem:
2590 if (!Val0->getType()->isFPOrFPVectorTy())
2591 return Error(ID.Loc, "constexpr requires fp operands");
2593 default: llvm_unreachable("Unknown binary operator!");
2596 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2597 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2598 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2599 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2601 ID.Kind = ValID::t_Constant;
2605 // Logical Operations
2608 case lltok::kw_xor: {
2609 unsigned Opc = Lex.getUIntVal();
2610 Constant *Val0, *Val1;
2612 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2613 ParseGlobalTypeAndValue(Val0) ||
2614 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2615 ParseGlobalTypeAndValue(Val1) ||
2616 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2618 if (Val0->getType() != Val1->getType())
2619 return Error(ID.Loc, "operands of constexpr must have same type");
2620 if (!Val0->getType()->isIntOrIntVectorTy())
2621 return Error(ID.Loc,
2622 "constexpr requires integer or integer vector operands");
2623 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2624 ID.Kind = ValID::t_Constant;
2628 case lltok::kw_getelementptr:
2629 case lltok::kw_shufflevector:
2630 case lltok::kw_insertelement:
2631 case lltok::kw_extractelement:
2632 case lltok::kw_select: {
2633 unsigned Opc = Lex.getUIntVal();
2634 SmallVector<Constant*, 16> Elts;
2635 bool InBounds = false;
2637 if (Opc == Instruction::GetElementPtr)
2638 InBounds = EatIfPresent(lltok::kw_inbounds);
2639 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2640 ParseGlobalValueVector(Elts) ||
2641 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2644 if (Opc == Instruction::GetElementPtr) {
2645 if (Elts.size() == 0 ||
2646 !Elts[0]->getType()->getScalarType()->isPointerTy())
2647 return Error(ID.Loc, "getelementptr requires pointer operand");
2649 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2650 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2651 return Error(ID.Loc, "invalid indices for getelementptr");
2652 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2654 } else if (Opc == Instruction::Select) {
2655 if (Elts.size() != 3)
2656 return Error(ID.Loc, "expected three operands to select");
2657 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2659 return Error(ID.Loc, Reason);
2660 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2661 } else if (Opc == Instruction::ShuffleVector) {
2662 if (Elts.size() != 3)
2663 return Error(ID.Loc, "expected three operands to shufflevector");
2664 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2665 return Error(ID.Loc, "invalid operands to shufflevector");
2667 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2668 } else if (Opc == Instruction::ExtractElement) {
2669 if (Elts.size() != 2)
2670 return Error(ID.Loc, "expected two operands to extractelement");
2671 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2672 return Error(ID.Loc, "invalid extractelement operands");
2673 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2675 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2676 if (Elts.size() != 3)
2677 return Error(ID.Loc, "expected three operands to insertelement");
2678 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2679 return Error(ID.Loc, "invalid insertelement operands");
2681 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2684 ID.Kind = ValID::t_Constant;
2693 /// ParseGlobalValue - Parse a global value with the specified type.
2694 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2698 bool Parsed = ParseValID(ID) ||
2699 ConvertValIDToValue(Ty, ID, V, NULL);
2700 if (V && !(C = dyn_cast<Constant>(V)))
2701 return Error(ID.Loc, "global values must be constants");
2705 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2707 return ParseType(Ty) ||
2708 ParseGlobalValue(Ty, V);
2711 /// ParseGlobalValueVector
2713 /// ::= TypeAndValue (',' TypeAndValue)*
2714 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2716 if (Lex.getKind() == lltok::rbrace ||
2717 Lex.getKind() == lltok::rsquare ||
2718 Lex.getKind() == lltok::greater ||
2719 Lex.getKind() == lltok::rparen)
2723 if (ParseGlobalTypeAndValue(C)) return true;
2726 while (EatIfPresent(lltok::comma)) {
2727 if (ParseGlobalTypeAndValue(C)) return true;
2734 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2735 assert(Lex.getKind() == lltok::lbrace);
2738 SmallVector<Value*, 16> Elts;
2739 if (ParseMDNodeVector(Elts, PFS) ||
2740 ParseToken(lltok::rbrace, "expected end of metadata node"))
2743 ID.MDNodeVal = MDNode::get(Context, Elts);
2744 ID.Kind = ValID::t_MDNode;
2748 /// ParseMetadataValue
2752 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2753 assert(Lex.getKind() == lltok::exclaim);
2758 if (Lex.getKind() == lltok::lbrace)
2759 return ParseMetadataListValue(ID, PFS);
2761 // Standalone metadata reference
2763 if (Lex.getKind() == lltok::APSInt) {
2764 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2765 ID.Kind = ValID::t_MDNode;
2770 // ::= '!' STRINGCONSTANT
2771 if (ParseMDString(ID.MDStringVal)) return true;
2772 ID.Kind = ValID::t_MDString;
2777 //===----------------------------------------------------------------------===//
2778 // Function Parsing.
2779 //===----------------------------------------------------------------------===//
2781 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2782 PerFunctionState *PFS) {
2783 if (Ty->isFunctionTy())
2784 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2787 case ValID::t_LocalID:
2788 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2789 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2791 case ValID::t_LocalName:
2792 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2793 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2795 case ValID::t_InlineAsm: {
2796 PointerType *PTy = dyn_cast<PointerType>(Ty);
2798 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2799 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2800 return Error(ID.Loc, "invalid type for inline asm constraint string");
2801 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
2802 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
2805 case ValID::t_MDNode:
2806 if (!Ty->isMetadataTy())
2807 return Error(ID.Loc, "metadata value must have metadata type");
2810 case ValID::t_MDString:
2811 if (!Ty->isMetadataTy())
2812 return Error(ID.Loc, "metadata value must have metadata type");
2815 case ValID::t_GlobalName:
2816 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2818 case ValID::t_GlobalID:
2819 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2821 case ValID::t_APSInt:
2822 if (!Ty->isIntegerTy())
2823 return Error(ID.Loc, "integer constant must have integer type");
2824 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2825 V = ConstantInt::get(Context, ID.APSIntVal);
2827 case ValID::t_APFloat:
2828 if (!Ty->isFloatingPointTy() ||
2829 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2830 return Error(ID.Loc, "floating point constant invalid for type");
2832 // The lexer has no type info, so builds all half, float, and double FP
2833 // constants as double. Fix this here. Long double does not need this.
2834 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
2837 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2839 else if (Ty->isFloatTy())
2840 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2843 V = ConstantFP::get(Context, ID.APFloatVal);
2845 if (V->getType() != Ty)
2846 return Error(ID.Loc, "floating point constant does not have type '" +
2847 getTypeString(Ty) + "'");
2851 if (!Ty->isPointerTy())
2852 return Error(ID.Loc, "null must be a pointer type");
2853 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2855 case ValID::t_Undef:
2856 // FIXME: LabelTy should not be a first-class type.
2857 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2858 return Error(ID.Loc, "invalid type for undef constant");
2859 V = UndefValue::get(Ty);
2861 case ValID::t_EmptyArray:
2862 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2863 return Error(ID.Loc, "invalid empty array initializer");
2864 V = UndefValue::get(Ty);
2867 // FIXME: LabelTy should not be a first-class type.
2868 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2869 return Error(ID.Loc, "invalid type for null constant");
2870 V = Constant::getNullValue(Ty);
2872 case ValID::t_Constant:
2873 if (ID.ConstantVal->getType() != Ty)
2874 return Error(ID.Loc, "constant expression type mismatch");
2878 case ValID::t_ConstantStruct:
2879 case ValID::t_PackedConstantStruct:
2880 if (StructType *ST = dyn_cast<StructType>(Ty)) {
2881 if (ST->getNumElements() != ID.UIntVal)
2882 return Error(ID.Loc,
2883 "initializer with struct type has wrong # elements");
2884 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2885 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2887 // Verify that the elements are compatible with the structtype.
2888 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2889 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2890 return Error(ID.Loc, "element " + Twine(i) +
2891 " of struct initializer doesn't match struct element type");
2893 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2896 return Error(ID.Loc, "constant expression type mismatch");
2899 llvm_unreachable("Invalid ValID");
2902 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
2905 return ParseValID(ID, PFS) ||
2906 ConvertValIDToValue(Ty, ID, V, PFS);
2909 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2911 return ParseType(Ty) ||
2912 ParseValue(Ty, V, PFS);
2915 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2916 PerFunctionState &PFS) {
2919 if (ParseTypeAndValue(V, PFS)) return true;
2920 if (!isa<BasicBlock>(V))
2921 return Error(Loc, "expected a basic block");
2922 BB = cast<BasicBlock>(V);
2928 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2929 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2930 /// OptionalAlign OptGC OptionalPrefix
2931 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2932 // Parse the linkage.
2933 LocTy LinkageLoc = Lex.getLoc();
2936 unsigned Visibility;
2937 AttrBuilder RetAttrs;
2940 LocTy RetTypeLoc = Lex.getLoc();
2941 if (ParseOptionalLinkage(Linkage) ||
2942 ParseOptionalVisibility(Visibility) ||
2943 ParseOptionalCallingConv(CC) ||
2944 ParseOptionalReturnAttrs(RetAttrs) ||
2945 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2948 // Verify that the linkage is ok.
2949 switch ((GlobalValue::LinkageTypes)Linkage) {
2950 case GlobalValue::ExternalLinkage:
2951 break; // always ok.
2952 case GlobalValue::DLLImportLinkage:
2953 case GlobalValue::ExternalWeakLinkage:
2955 return Error(LinkageLoc, "invalid linkage for function definition");
2957 case GlobalValue::PrivateLinkage:
2958 case GlobalValue::LinkerPrivateLinkage:
2959 case GlobalValue::LinkerPrivateWeakLinkage:
2960 case GlobalValue::InternalLinkage:
2961 case GlobalValue::AvailableExternallyLinkage:
2962 case GlobalValue::LinkOnceAnyLinkage:
2963 case GlobalValue::LinkOnceODRLinkage:
2964 case GlobalValue::LinkOnceODRAutoHideLinkage:
2965 case GlobalValue::WeakAnyLinkage:
2966 case GlobalValue::WeakODRLinkage:
2967 case GlobalValue::DLLExportLinkage:
2969 return Error(LinkageLoc, "invalid linkage for function declaration");
2971 case GlobalValue::AppendingLinkage:
2972 case GlobalValue::CommonLinkage:
2973 return Error(LinkageLoc, "invalid function linkage type");
2976 if (!FunctionType::isValidReturnType(RetType))
2977 return Error(RetTypeLoc, "invalid function return type");
2979 LocTy NameLoc = Lex.getLoc();
2981 std::string FunctionName;
2982 if (Lex.getKind() == lltok::GlobalVar) {
2983 FunctionName = Lex.getStrVal();
2984 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2985 unsigned NameID = Lex.getUIntVal();
2987 if (NameID != NumberedVals.size())
2988 return TokError("function expected to be numbered '%" +
2989 Twine(NumberedVals.size()) + "'");
2991 return TokError("expected function name");
2996 if (Lex.getKind() != lltok::lparen)
2997 return TokError("expected '(' in function argument list");
2999 SmallVector<ArgInfo, 8> ArgList;
3001 AttrBuilder FuncAttrs;
3002 std::vector<unsigned> FwdRefAttrGrps;
3004 std::string Section;
3008 LocTy UnnamedAddrLoc;
3009 Constant *Prefix = 0;
3011 if (ParseArgumentList(ArgList, isVarArg) ||
3012 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3014 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
3016 (EatIfPresent(lltok::kw_section) &&
3017 ParseStringConstant(Section)) ||
3018 ParseOptionalAlignment(Alignment) ||
3019 (EatIfPresent(lltok::kw_gc) &&
3020 ParseStringConstant(GC)) ||
3021 (EatIfPresent(lltok::kw_prefix) &&
3022 ParseGlobalTypeAndValue(Prefix)))
3025 if (FuncAttrs.contains(Attribute::Builtin))
3026 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
3028 // If the alignment was parsed as an attribute, move to the alignment field.
3029 if (FuncAttrs.hasAlignmentAttr()) {
3030 Alignment = FuncAttrs.getAlignment();
3031 FuncAttrs.removeAttribute(Attribute::Alignment);
3034 // Okay, if we got here, the function is syntactically valid. Convert types
3035 // and do semantic checks.
3036 std::vector<Type*> ParamTypeList;
3037 SmallVector<AttributeSet, 8> Attrs;
3039 if (RetAttrs.hasAttributes())
3040 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3041 AttributeSet::ReturnIndex,
3044 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3045 ParamTypeList.push_back(ArgList[i].Ty);
3046 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3047 AttrBuilder B(ArgList[i].Attrs, i + 1);
3048 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3052 if (FuncAttrs.hasAttributes())
3053 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3054 AttributeSet::FunctionIndex,
3057 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3059 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
3060 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3063 FunctionType::get(RetType, ParamTypeList, isVarArg);
3064 PointerType *PFT = PointerType::getUnqual(FT);
3067 if (!FunctionName.empty()) {
3068 // If this was a definition of a forward reference, remove the definition
3069 // from the forward reference table and fill in the forward ref.
3070 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3071 ForwardRefVals.find(FunctionName);
3072 if (FRVI != ForwardRefVals.end()) {
3073 Fn = M->getFunction(FunctionName);
3075 return Error(FRVI->second.second, "invalid forward reference to "
3076 "function as global value!");
3077 if (Fn->getType() != PFT)
3078 return Error(FRVI->second.second, "invalid forward reference to "
3079 "function '" + FunctionName + "' with wrong type!");
3081 ForwardRefVals.erase(FRVI);
3082 } else if ((Fn = M->getFunction(FunctionName))) {
3083 // Reject redefinitions.
3084 return Error(NameLoc, "invalid redefinition of function '" +
3085 FunctionName + "'");
3086 } else if (M->getNamedValue(FunctionName)) {
3087 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
3091 // If this is a definition of a forward referenced function, make sure the
3093 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3094 = ForwardRefValIDs.find(NumberedVals.size());
3095 if (I != ForwardRefValIDs.end()) {
3096 Fn = cast<Function>(I->second.first);
3097 if (Fn->getType() != PFT)
3098 return Error(NameLoc, "type of definition and forward reference of '@" +
3099 Twine(NumberedVals.size()) + "' disagree");
3100 ForwardRefValIDs.erase(I);
3105 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3106 else // Move the forward-reference to the correct spot in the module.
3107 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3109 if (FunctionName.empty())
3110 NumberedVals.push_back(Fn);
3112 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3113 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3114 Fn->setCallingConv(CC);
3115 Fn->setAttributes(PAL);
3116 Fn->setUnnamedAddr(UnnamedAddr);
3117 Fn->setAlignment(Alignment);
3118 Fn->setSection(Section);
3119 if (!GC.empty()) Fn->setGC(GC.c_str());
3120 Fn->setPrefixData(Prefix);
3121 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
3123 // Add all of the arguments we parsed to the function.
3124 Function::arg_iterator ArgIt = Fn->arg_begin();
3125 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3126 // If the argument has a name, insert it into the argument symbol table.
3127 if (ArgList[i].Name.empty()) continue;
3129 // Set the name, if it conflicted, it will be auto-renamed.
3130 ArgIt->setName(ArgList[i].Name);
3132 if (ArgIt->getName() != ArgList[i].Name)
3133 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3134 ArgList[i].Name + "'");
3141 /// ParseFunctionBody
3142 /// ::= '{' BasicBlock+ '}'
3144 bool LLParser::ParseFunctionBody(Function &Fn) {
3145 if (Lex.getKind() != lltok::lbrace)
3146 return TokError("expected '{' in function body");
3147 Lex.Lex(); // eat the {.
3149 int FunctionNumber = -1;
3150 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
3152 PerFunctionState PFS(*this, Fn, FunctionNumber);
3154 // We need at least one basic block.
3155 if (Lex.getKind() == lltok::rbrace)
3156 return TokError("function body requires at least one basic block");
3158 while (Lex.getKind() != lltok::rbrace)
3159 if (ParseBasicBlock(PFS)) return true;
3164 // Verify function is ok.
3165 return PFS.FinishFunction();
3169 /// ::= LabelStr? Instruction*
3170 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3171 // If this basic block starts out with a name, remember it.
3173 LocTy NameLoc = Lex.getLoc();
3174 if (Lex.getKind() == lltok::LabelStr) {
3175 Name = Lex.getStrVal();
3179 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3180 if (BB == 0) return true;
3182 std::string NameStr;
3184 // Parse the instructions in this block until we get a terminator.
3187 // This instruction may have three possibilities for a name: a) none
3188 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3189 LocTy NameLoc = Lex.getLoc();
3193 if (Lex.getKind() == lltok::LocalVarID) {
3194 NameID = Lex.getUIntVal();
3196 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3198 } else if (Lex.getKind() == lltok::LocalVar) {
3199 NameStr = Lex.getStrVal();
3201 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3205 switch (ParseInstruction(Inst, BB, PFS)) {
3206 default: llvm_unreachable("Unknown ParseInstruction result!");
3207 case InstError: return true;
3209 BB->getInstList().push_back(Inst);
3211 // With a normal result, we check to see if the instruction is followed by
3212 // a comma and metadata.
3213 if (EatIfPresent(lltok::comma))
3214 if (ParseInstructionMetadata(Inst, &PFS))
3217 case InstExtraComma:
3218 BB->getInstList().push_back(Inst);
3220 // If the instruction parser ate an extra comma at the end of it, it
3221 // *must* be followed by metadata.
3222 if (ParseInstructionMetadata(Inst, &PFS))
3227 // Set the name on the instruction.
3228 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3229 } while (!isa<TerminatorInst>(Inst));
3234 //===----------------------------------------------------------------------===//
3235 // Instruction Parsing.
3236 //===----------------------------------------------------------------------===//
3238 /// ParseInstruction - Parse one of the many different instructions.
3240 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3241 PerFunctionState &PFS) {
3242 lltok::Kind Token = Lex.getKind();
3243 if (Token == lltok::Eof)
3244 return TokError("found end of file when expecting more instructions");
3245 LocTy Loc = Lex.getLoc();
3246 unsigned KeywordVal = Lex.getUIntVal();
3247 Lex.Lex(); // Eat the keyword.
3250 default: return Error(Loc, "expected instruction opcode");
3251 // Terminator Instructions.
3252 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3253 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3254 case lltok::kw_br: return ParseBr(Inst, PFS);
3255 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
3256 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
3257 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3258 case lltok::kw_resume: return ParseResume(Inst, PFS);
3259 // Binary Operators.
3263 case lltok::kw_shl: {
3264 bool NUW = EatIfPresent(lltok::kw_nuw);
3265 bool NSW = EatIfPresent(lltok::kw_nsw);
3266 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3268 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3270 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3271 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3274 case lltok::kw_fadd:
3275 case lltok::kw_fsub:
3276 case lltok::kw_fmul:
3277 case lltok::kw_fdiv:
3278 case lltok::kw_frem: {
3279 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3280 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3284 Inst->setFastMathFlags(FMF);
3288 case lltok::kw_sdiv:
3289 case lltok::kw_udiv:
3290 case lltok::kw_lshr:
3291 case lltok::kw_ashr: {
3292 bool Exact = EatIfPresent(lltok::kw_exact);
3294 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3295 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3299 case lltok::kw_urem:
3300 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3303 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3304 case lltok::kw_icmp:
3305 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3307 case lltok::kw_trunc:
3308 case lltok::kw_zext:
3309 case lltok::kw_sext:
3310 case lltok::kw_fptrunc:
3311 case lltok::kw_fpext:
3312 case lltok::kw_bitcast:
3313 case lltok::kw_uitofp:
3314 case lltok::kw_sitofp:
3315 case lltok::kw_fptoui:
3316 case lltok::kw_fptosi:
3317 case lltok::kw_inttoptr:
3318 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3320 case lltok::kw_select: return ParseSelect(Inst, PFS);
3321 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3322 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3323 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3324 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3325 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3326 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3327 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3328 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3330 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3331 case lltok::kw_load: return ParseLoad(Inst, PFS);
3332 case lltok::kw_store: return ParseStore(Inst, PFS);
3333 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3334 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3335 case lltok::kw_fence: return ParseFence(Inst, PFS);
3336 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3337 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3338 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3342 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3343 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3344 if (Opc == Instruction::FCmp) {
3345 switch (Lex.getKind()) {
3346 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
3347 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3348 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3349 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3350 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3351 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3352 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3353 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3354 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3355 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3356 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3357 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3358 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3359 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3360 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3361 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3362 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3365 switch (Lex.getKind()) {
3366 default: return TokError("expected icmp predicate (e.g. 'eq')");
3367 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3368 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3369 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3370 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3371 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3372 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3373 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3374 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3375 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3376 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3383 //===----------------------------------------------------------------------===//
3384 // Terminator Instructions.
3385 //===----------------------------------------------------------------------===//
3387 /// ParseRet - Parse a return instruction.
3388 /// ::= 'ret' void (',' !dbg, !1)*
3389 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3390 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3391 PerFunctionState &PFS) {
3392 SMLoc TypeLoc = Lex.getLoc();
3394 if (ParseType(Ty, true /*void allowed*/)) return true;
3396 Type *ResType = PFS.getFunction().getReturnType();
3398 if (Ty->isVoidTy()) {
3399 if (!ResType->isVoidTy())
3400 return Error(TypeLoc, "value doesn't match function result type '" +
3401 getTypeString(ResType) + "'");
3403 Inst = ReturnInst::Create(Context);
3408 if (ParseValue(Ty, RV, PFS)) return true;
3410 if (ResType != RV->getType())
3411 return Error(TypeLoc, "value doesn't match function result type '" +
3412 getTypeString(ResType) + "'");
3414 Inst = ReturnInst::Create(Context, RV);
3420 /// ::= 'br' TypeAndValue
3421 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3422 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3425 BasicBlock *Op1, *Op2;
3426 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3428 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3429 Inst = BranchInst::Create(BB);
3433 if (Op0->getType() != Type::getInt1Ty(Context))
3434 return Error(Loc, "branch condition must have 'i1' type");
3436 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3437 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3438 ParseToken(lltok::comma, "expected ',' after true destination") ||
3439 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3442 Inst = BranchInst::Create(Op1, Op2, Op0);
3448 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3450 /// ::= (TypeAndValue ',' TypeAndValue)*
3451 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3452 LocTy CondLoc, BBLoc;
3454 BasicBlock *DefaultBB;
3455 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3456 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3457 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3458 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3461 if (!Cond->getType()->isIntegerTy())
3462 return Error(CondLoc, "switch condition must have integer type");
3464 // Parse the jump table pairs.
3465 SmallPtrSet<Value*, 32> SeenCases;
3466 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3467 while (Lex.getKind() != lltok::rsquare) {
3471 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3472 ParseToken(lltok::comma, "expected ',' after case value") ||
3473 ParseTypeAndBasicBlock(DestBB, PFS))
3476 if (!SeenCases.insert(Constant))
3477 return Error(CondLoc, "duplicate case value in switch");
3478 if (!isa<ConstantInt>(Constant))
3479 return Error(CondLoc, "case value is not a constant integer");
3481 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3484 Lex.Lex(); // Eat the ']'.
3486 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3487 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3488 SI->addCase(Table[i].first, Table[i].second);
3495 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3496 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3499 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3500 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3501 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3504 if (!Address->getType()->isPointerTy())
3505 return Error(AddrLoc, "indirectbr address must have pointer type");
3507 // Parse the destination list.
3508 SmallVector<BasicBlock*, 16> DestList;
3510 if (Lex.getKind() != lltok::rsquare) {
3512 if (ParseTypeAndBasicBlock(DestBB, PFS))
3514 DestList.push_back(DestBB);
3516 while (EatIfPresent(lltok::comma)) {
3517 if (ParseTypeAndBasicBlock(DestBB, PFS))
3519 DestList.push_back(DestBB);
3523 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3526 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3527 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3528 IBI->addDestination(DestList[i]);
3535 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3536 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3537 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3538 LocTy CallLoc = Lex.getLoc();
3539 AttrBuilder RetAttrs, FnAttrs;
3540 std::vector<unsigned> FwdRefAttrGrps;
3546 SmallVector<ParamInfo, 16> ArgList;
3548 BasicBlock *NormalBB, *UnwindBB;
3549 if (ParseOptionalCallingConv(CC) ||
3550 ParseOptionalReturnAttrs(RetAttrs) ||
3551 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3552 ParseValID(CalleeID) ||
3553 ParseParameterList(ArgList, PFS) ||
3554 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3556 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3557 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3558 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3559 ParseTypeAndBasicBlock(UnwindBB, PFS))
3562 // If RetType is a non-function pointer type, then this is the short syntax
3563 // for the call, which means that RetType is just the return type. Infer the
3564 // rest of the function argument types from the arguments that are present.
3565 PointerType *PFTy = 0;
3566 FunctionType *Ty = 0;
3567 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3568 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3569 // Pull out the types of all of the arguments...
3570 std::vector<Type*> ParamTypes;
3571 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3572 ParamTypes.push_back(ArgList[i].V->getType());
3574 if (!FunctionType::isValidReturnType(RetType))
3575 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3577 Ty = FunctionType::get(RetType, ParamTypes, false);
3578 PFTy = PointerType::getUnqual(Ty);
3581 // Look up the callee.
3583 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3585 // Set up the Attribute for the function.
3586 SmallVector<AttributeSet, 8> Attrs;
3587 if (RetAttrs.hasAttributes())
3588 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3589 AttributeSet::ReturnIndex,
3592 SmallVector<Value*, 8> Args;
3594 // Loop through FunctionType's arguments and ensure they are specified
3595 // correctly. Also, gather any parameter attributes.
3596 FunctionType::param_iterator I = Ty->param_begin();
3597 FunctionType::param_iterator E = Ty->param_end();
3598 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3599 Type *ExpectedTy = 0;
3602 } else if (!Ty->isVarArg()) {
3603 return Error(ArgList[i].Loc, "too many arguments specified");
3606 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3607 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3608 getTypeString(ExpectedTy) + "'");
3609 Args.push_back(ArgList[i].V);
3610 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3611 AttrBuilder B(ArgList[i].Attrs, i + 1);
3612 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3617 return Error(CallLoc, "not enough parameters specified for call");
3619 if (FnAttrs.hasAttributes())
3620 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3621 AttributeSet::FunctionIndex,
3624 // Finish off the Attribute and check them
3625 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3627 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3628 II->setCallingConv(CC);
3629 II->setAttributes(PAL);
3630 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
3636 /// ::= 'resume' TypeAndValue
3637 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3638 Value *Exn; LocTy ExnLoc;
3639 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3642 ResumeInst *RI = ResumeInst::Create(Exn);
3647 //===----------------------------------------------------------------------===//
3648 // Binary Operators.
3649 //===----------------------------------------------------------------------===//
3652 /// ::= ArithmeticOps TypeAndValue ',' Value
3654 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3655 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3656 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3657 unsigned Opc, unsigned OperandType) {
3658 LocTy Loc; Value *LHS, *RHS;
3659 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3660 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3661 ParseValue(LHS->getType(), RHS, PFS))
3665 switch (OperandType) {
3666 default: llvm_unreachable("Unknown operand type!");
3667 case 0: // int or FP.
3668 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3669 LHS->getType()->isFPOrFPVectorTy();
3671 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3672 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3676 return Error(Loc, "invalid operand type for instruction");
3678 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3683 /// ::= ArithmeticOps TypeAndValue ',' Value {
3684 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3686 LocTy Loc; Value *LHS, *RHS;
3687 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3688 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3689 ParseValue(LHS->getType(), RHS, PFS))
3692 if (!LHS->getType()->isIntOrIntVectorTy())
3693 return Error(Loc,"instruction requires integer or integer vector operands");
3695 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3701 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3702 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3703 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3705 // Parse the integer/fp comparison predicate.
3709 if (ParseCmpPredicate(Pred, Opc) ||
3710 ParseTypeAndValue(LHS, Loc, PFS) ||
3711 ParseToken(lltok::comma, "expected ',' after compare value") ||
3712 ParseValue(LHS->getType(), RHS, PFS))
3715 if (Opc == Instruction::FCmp) {
3716 if (!LHS->getType()->isFPOrFPVectorTy())
3717 return Error(Loc, "fcmp requires floating point operands");
3718 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3720 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3721 if (!LHS->getType()->isIntOrIntVectorTy() &&
3722 !LHS->getType()->getScalarType()->isPointerTy())
3723 return Error(Loc, "icmp requires integer operands");
3724 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3729 //===----------------------------------------------------------------------===//
3730 // Other Instructions.
3731 //===----------------------------------------------------------------------===//
3735 /// ::= CastOpc TypeAndValue 'to' Type
3736 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3741 if (ParseTypeAndValue(Op, Loc, PFS) ||
3742 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3746 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3747 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3748 return Error(Loc, "invalid cast opcode for cast from '" +
3749 getTypeString(Op->getType()) + "' to '" +
3750 getTypeString(DestTy) + "'");
3752 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3757 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3758 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3760 Value *Op0, *Op1, *Op2;
3761 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3762 ParseToken(lltok::comma, "expected ',' after select condition") ||
3763 ParseTypeAndValue(Op1, PFS) ||
3764 ParseToken(lltok::comma, "expected ',' after select value") ||
3765 ParseTypeAndValue(Op2, PFS))
3768 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3769 return Error(Loc, Reason);
3771 Inst = SelectInst::Create(Op0, Op1, Op2);
3776 /// ::= 'va_arg' TypeAndValue ',' Type
3777 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3781 if (ParseTypeAndValue(Op, PFS) ||
3782 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3783 ParseType(EltTy, TypeLoc))
3786 if (!EltTy->isFirstClassType())
3787 return Error(TypeLoc, "va_arg requires operand with first class type");
3789 Inst = new VAArgInst(Op, EltTy);
3793 /// ParseExtractElement
3794 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3795 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3798 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3799 ParseToken(lltok::comma, "expected ',' after extract value") ||
3800 ParseTypeAndValue(Op1, PFS))
3803 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3804 return Error(Loc, "invalid extractelement operands");
3806 Inst = ExtractElementInst::Create(Op0, Op1);
3810 /// ParseInsertElement
3811 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3812 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3814 Value *Op0, *Op1, *Op2;
3815 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3816 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3817 ParseTypeAndValue(Op1, PFS) ||
3818 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3819 ParseTypeAndValue(Op2, PFS))
3822 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3823 return Error(Loc, "invalid insertelement operands");
3825 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3829 /// ParseShuffleVector
3830 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3831 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3833 Value *Op0, *Op1, *Op2;
3834 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3835 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3836 ParseTypeAndValue(Op1, PFS) ||
3837 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3838 ParseTypeAndValue(Op2, PFS))
3841 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3842 return Error(Loc, "invalid shufflevector operands");
3844 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3849 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3850 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3851 Type *Ty = 0; LocTy TypeLoc;
3854 if (ParseType(Ty, TypeLoc) ||
3855 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3856 ParseValue(Ty, Op0, PFS) ||
3857 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3858 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3859 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3862 bool AteExtraComma = false;
3863 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3865 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3867 if (!EatIfPresent(lltok::comma))
3870 if (Lex.getKind() == lltok::MetadataVar) {
3871 AteExtraComma = true;
3875 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3876 ParseValue(Ty, Op0, PFS) ||
3877 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3878 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3879 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3883 if (!Ty->isFirstClassType())
3884 return Error(TypeLoc, "phi node must have first class type");
3886 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3887 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3888 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3890 return AteExtraComma ? InstExtraComma : InstNormal;
3894 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3896 /// ::= 'catch' TypeAndValue
3898 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3899 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3900 Type *Ty = 0; LocTy TyLoc;
3901 Value *PersFn; LocTy PersFnLoc;
3903 if (ParseType(Ty, TyLoc) ||
3904 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3905 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3908 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3909 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3911 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3912 LandingPadInst::ClauseType CT;
3913 if (EatIfPresent(lltok::kw_catch))
3914 CT = LandingPadInst::Catch;
3915 else if (EatIfPresent(lltok::kw_filter))
3916 CT = LandingPadInst::Filter;
3918 return TokError("expected 'catch' or 'filter' clause type");
3920 Value *V; LocTy VLoc;
3921 if (ParseTypeAndValue(V, VLoc, PFS)) {
3926 // A 'catch' type expects a non-array constant. A filter clause expects an
3928 if (CT == LandingPadInst::Catch) {
3929 if (isa<ArrayType>(V->getType()))
3930 Error(VLoc, "'catch' clause has an invalid type");
3932 if (!isa<ArrayType>(V->getType()))
3933 Error(VLoc, "'filter' clause has an invalid type");
3944 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3945 /// ParameterList OptionalAttrs
3946 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3948 AttrBuilder RetAttrs, FnAttrs;
3949 std::vector<unsigned> FwdRefAttrGrps;
3955 SmallVector<ParamInfo, 16> ArgList;
3956 LocTy CallLoc = Lex.getLoc();
3958 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3959 ParseOptionalCallingConv(CC) ||
3960 ParseOptionalReturnAttrs(RetAttrs) ||
3961 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3962 ParseValID(CalleeID) ||
3963 ParseParameterList(ArgList, PFS) ||
3964 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3968 // If RetType is a non-function pointer type, then this is the short syntax
3969 // for the call, which means that RetType is just the return type. Infer the
3970 // rest of the function argument types from the arguments that are present.
3971 PointerType *PFTy = 0;
3972 FunctionType *Ty = 0;
3973 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3974 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3975 // Pull out the types of all of the arguments...
3976 std::vector<Type*> ParamTypes;
3977 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3978 ParamTypes.push_back(ArgList[i].V->getType());
3980 if (!FunctionType::isValidReturnType(RetType))
3981 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3983 Ty = FunctionType::get(RetType, ParamTypes, false);
3984 PFTy = PointerType::getUnqual(Ty);
3987 // Look up the callee.
3989 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3991 // Set up the Attribute for the function.
3992 SmallVector<AttributeSet, 8> Attrs;
3993 if (RetAttrs.hasAttributes())
3994 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3995 AttributeSet::ReturnIndex,
3998 SmallVector<Value*, 8> Args;
4000 // Loop through FunctionType's arguments and ensure they are specified
4001 // correctly. Also, gather any parameter attributes.
4002 FunctionType::param_iterator I = Ty->param_begin();
4003 FunctionType::param_iterator E = Ty->param_end();
4004 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4005 Type *ExpectedTy = 0;
4008 } else if (!Ty->isVarArg()) {
4009 return Error(ArgList[i].Loc, "too many arguments specified");
4012 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4013 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4014 getTypeString(ExpectedTy) + "'");
4015 Args.push_back(ArgList[i].V);
4016 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4017 AttrBuilder B(ArgList[i].Attrs, i + 1);
4018 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4023 return Error(CallLoc, "not enough parameters specified for call");
4025 if (FnAttrs.hasAttributes())
4026 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4027 AttributeSet::FunctionIndex,
4030 // Finish off the Attribute and check them
4031 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4033 CallInst *CI = CallInst::Create(Callee, Args);
4034 CI->setTailCall(isTail);
4035 CI->setCallingConv(CC);
4036 CI->setAttributes(PAL);
4037 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
4042 //===----------------------------------------------------------------------===//
4043 // Memory Instructions.
4044 //===----------------------------------------------------------------------===//
4047 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
4048 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
4051 unsigned Alignment = 0;
4053 if (ParseType(Ty)) return true;
4055 bool AteExtraComma = false;
4056 if (EatIfPresent(lltok::comma)) {
4057 if (Lex.getKind() == lltok::kw_align) {
4058 if (ParseOptionalAlignment(Alignment)) return true;
4059 } else if (Lex.getKind() == lltok::MetadataVar) {
4060 AteExtraComma = true;
4062 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4063 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4068 if (Size && !Size->getType()->isIntegerTy())
4069 return Error(SizeLoc, "element count must have integer type");
4071 Inst = new AllocaInst(Ty, Size, Alignment);
4072 return AteExtraComma ? InstExtraComma : InstNormal;
4076 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
4077 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
4078 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4079 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
4080 Value *Val; LocTy Loc;
4081 unsigned Alignment = 0;
4082 bool AteExtraComma = false;
4083 bool isAtomic = false;
4084 AtomicOrdering Ordering = NotAtomic;
4085 SynchronizationScope Scope = CrossThread;
4087 if (Lex.getKind() == lltok::kw_atomic) {
4092 bool isVolatile = false;
4093 if (Lex.getKind() == lltok::kw_volatile) {
4098 if (ParseTypeAndValue(Val, Loc, PFS) ||
4099 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4100 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4103 if (!Val->getType()->isPointerTy() ||
4104 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4105 return Error(Loc, "load operand must be a pointer to a first class type");
4106 if (isAtomic && !Alignment)
4107 return Error(Loc, "atomic load must have explicit non-zero alignment");
4108 if (Ordering == Release || Ordering == AcquireRelease)
4109 return Error(Loc, "atomic load cannot use Release ordering");
4111 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
4112 return AteExtraComma ? InstExtraComma : InstNormal;
4117 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4118 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
4119 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4120 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
4121 Value *Val, *Ptr; LocTy Loc, PtrLoc;
4122 unsigned Alignment = 0;
4123 bool AteExtraComma = false;
4124 bool isAtomic = false;
4125 AtomicOrdering Ordering = NotAtomic;
4126 SynchronizationScope Scope = CrossThread;
4128 if (Lex.getKind() == lltok::kw_atomic) {
4133 bool isVolatile = false;
4134 if (Lex.getKind() == lltok::kw_volatile) {
4139 if (ParseTypeAndValue(Val, Loc, PFS) ||
4140 ParseToken(lltok::comma, "expected ',' after store operand") ||
4141 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4142 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4143 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4146 if (!Ptr->getType()->isPointerTy())
4147 return Error(PtrLoc, "store operand must be a pointer");
4148 if (!Val->getType()->isFirstClassType())
4149 return Error(Loc, "store operand must be a first class value");
4150 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4151 return Error(Loc, "stored value and pointer type do not match");
4152 if (isAtomic && !Alignment)
4153 return Error(Loc, "atomic store must have explicit non-zero alignment");
4154 if (Ordering == Acquire || Ordering == AcquireRelease)
4155 return Error(Loc, "atomic store cannot use Acquire ordering");
4157 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
4158 return AteExtraComma ? InstExtraComma : InstNormal;
4162 /// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
4163 /// 'singlethread'? AtomicOrdering
4164 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
4165 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4166 bool AteExtraComma = false;
4167 AtomicOrdering Ordering = NotAtomic;
4168 SynchronizationScope Scope = CrossThread;
4169 bool isVolatile = false;
4171 if (EatIfPresent(lltok::kw_volatile))
4174 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4175 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4176 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4177 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4178 ParseTypeAndValue(New, NewLoc, PFS) ||
4179 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4182 if (Ordering == Unordered)
4183 return TokError("cmpxchg cannot be unordered");
4184 if (!Ptr->getType()->isPointerTy())
4185 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4186 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4187 return Error(CmpLoc, "compare value and pointer type do not match");
4188 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4189 return Error(NewLoc, "new value and pointer type do not match");
4190 if (!New->getType()->isIntegerTy())
4191 return Error(NewLoc, "cmpxchg operand must be an integer");
4192 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4193 if (Size < 8 || (Size & (Size - 1)))
4194 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4197 AtomicCmpXchgInst *CXI =
4198 new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, Scope);
4199 CXI->setVolatile(isVolatile);
4201 return AteExtraComma ? InstExtraComma : InstNormal;
4205 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4206 /// 'singlethread'? AtomicOrdering
4207 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
4208 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4209 bool AteExtraComma = false;
4210 AtomicOrdering Ordering = NotAtomic;
4211 SynchronizationScope Scope = CrossThread;
4212 bool isVolatile = false;
4213 AtomicRMWInst::BinOp Operation;
4215 if (EatIfPresent(lltok::kw_volatile))
4218 switch (Lex.getKind()) {
4219 default: return TokError("expected binary operation in atomicrmw");
4220 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4221 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4222 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4223 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4224 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4225 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4226 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4227 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4228 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4229 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4230 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4232 Lex.Lex(); // Eat the operation.
4234 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4235 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4236 ParseTypeAndValue(Val, ValLoc, PFS) ||
4237 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4240 if (Ordering == Unordered)
4241 return TokError("atomicrmw cannot be unordered");
4242 if (!Ptr->getType()->isPointerTy())
4243 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4244 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4245 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4246 if (!Val->getType()->isIntegerTy())
4247 return Error(ValLoc, "atomicrmw operand must be an integer");
4248 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4249 if (Size < 8 || (Size & (Size - 1)))
4250 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4253 AtomicRMWInst *RMWI =
4254 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4255 RMWI->setVolatile(isVolatile);
4257 return AteExtraComma ? InstExtraComma : InstNormal;
4261 /// ::= 'fence' 'singlethread'? AtomicOrdering
4262 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4263 AtomicOrdering Ordering = NotAtomic;
4264 SynchronizationScope Scope = CrossThread;
4265 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4268 if (Ordering == Unordered)
4269 return TokError("fence cannot be unordered");
4270 if (Ordering == Monotonic)
4271 return TokError("fence cannot be monotonic");
4273 Inst = new FenceInst(Context, Ordering, Scope);
4277 /// ParseGetElementPtr
4278 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4279 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4284 bool InBounds = EatIfPresent(lltok::kw_inbounds);
4286 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4288 Type *BaseType = Ptr->getType();
4289 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4290 if (!BasePointerType)
4291 return Error(Loc, "base of getelementptr must be a pointer");
4293 SmallVector<Value*, 16> Indices;
4294 bool AteExtraComma = false;
4295 while (EatIfPresent(lltok::comma)) {
4296 if (Lex.getKind() == lltok::MetadataVar) {
4297 AteExtraComma = true;
4300 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4301 if (!Val->getType()->getScalarType()->isIntegerTy())
4302 return Error(EltLoc, "getelementptr index must be an integer");
4303 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4304 return Error(EltLoc, "getelementptr index type missmatch");
4305 if (Val->getType()->isVectorTy()) {
4306 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4307 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4308 if (ValNumEl != PtrNumEl)
4309 return Error(EltLoc,
4310 "getelementptr vector index has a wrong number of elements");
4312 Indices.push_back(Val);
4315 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4316 return Error(Loc, "base element of getelementptr must be sized");
4318 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
4319 return Error(Loc, "invalid getelementptr indices");
4320 Inst = GetElementPtrInst::Create(Ptr, Indices);
4322 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4323 return AteExtraComma ? InstExtraComma : InstNormal;
4326 /// ParseExtractValue
4327 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
4328 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4329 Value *Val; LocTy Loc;
4330 SmallVector<unsigned, 4> Indices;
4332 if (ParseTypeAndValue(Val, Loc, PFS) ||
4333 ParseIndexList(Indices, AteExtraComma))
4336 if (!Val->getType()->isAggregateType())
4337 return Error(Loc, "extractvalue operand must be aggregate type");
4339 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4340 return Error(Loc, "invalid indices for extractvalue");
4341 Inst = ExtractValueInst::Create(Val, Indices);
4342 return AteExtraComma ? InstExtraComma : InstNormal;
4345 /// ParseInsertValue
4346 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4347 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4348 Value *Val0, *Val1; LocTy Loc0, Loc1;
4349 SmallVector<unsigned, 4> Indices;
4351 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4352 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4353 ParseTypeAndValue(Val1, Loc1, PFS) ||
4354 ParseIndexList(Indices, AteExtraComma))
4357 if (!Val0->getType()->isAggregateType())
4358 return Error(Loc0, "insertvalue operand must be aggregate type");
4360 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4361 return Error(Loc0, "invalid indices for insertvalue");
4362 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4363 return AteExtraComma ? InstExtraComma : InstNormal;
4366 //===----------------------------------------------------------------------===//
4367 // Embedded metadata.
4368 //===----------------------------------------------------------------------===//
4370 /// ParseMDNodeVector
4371 /// ::= Element (',' Element)*
4373 /// ::= 'null' | TypeAndValue
4374 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4375 PerFunctionState *PFS) {
4376 // Check for an empty list.
4377 if (Lex.getKind() == lltok::rbrace)
4381 // Null is a special case since it is typeless.
4382 if (EatIfPresent(lltok::kw_null)) {
4388 if (ParseTypeAndValue(V, PFS)) return true;
4390 } while (EatIfPresent(lltok::comma));