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(!GlobalAlias::isValidLinkage(Linkage))
638 return Error(LinkageLoc, "invalid linkage type for alias");
641 LocTy AliaseeLoc = Lex.getLoc();
642 if (Lex.getKind() != lltok::kw_bitcast &&
643 Lex.getKind() != lltok::kw_getelementptr) {
644 if (ParseGlobalTypeAndValue(Aliasee)) return true;
646 // The bitcast dest type is not present, it is implied by the dest type.
648 if (ParseValID(ID)) return true;
649 if (ID.Kind != ValID::t_Constant)
650 return Error(AliaseeLoc, "invalid aliasee");
651 Aliasee = ID.ConstantVal;
654 if (!Aliasee->getType()->isPointerTy())
655 return Error(AliaseeLoc, "alias must have pointer type");
657 // Okay, create the alias but do not insert it into the module yet.
658 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
659 (GlobalValue::LinkageTypes)Linkage, Name,
661 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
663 // See if this value already exists in the symbol table. If so, it is either
664 // a redefinition or a definition of a forward reference.
665 if (GlobalValue *Val = M->getNamedValue(Name)) {
666 // See if this was a redefinition. If so, there is no entry in
668 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
669 I = ForwardRefVals.find(Name);
670 if (I == ForwardRefVals.end())
671 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
673 // Otherwise, this was a definition of forward ref. Verify that types
675 if (Val->getType() != GA->getType())
676 return Error(NameLoc,
677 "forward reference and definition of alias have different types");
679 // If they agree, just RAUW the old value with the alias and remove the
681 Val->replaceAllUsesWith(GA);
682 Val->eraseFromParent();
683 ForwardRefVals.erase(I);
686 // Insert into the module, we know its name won't collide now.
687 M->getAliasList().push_back(GA);
688 assert(GA->getName() == Name && "Should not be a name conflict!");
694 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
695 /// OptionalAddrSpace OptionalUnNammedAddr
696 /// OptionalExternallyInitialized GlobalType Type Const
697 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
698 /// OptionalAddrSpace OptionalUnNammedAddr
699 /// OptionalExternallyInitialized GlobalType Type Const
701 /// Everything through visibility has been parsed already.
703 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
704 unsigned Linkage, bool HasLinkage,
705 unsigned Visibility) {
707 bool IsConstant, UnnamedAddr, IsExternallyInitialized;
708 GlobalVariable::ThreadLocalMode TLM;
709 LocTy UnnamedAddrLoc;
710 LocTy IsExternallyInitializedLoc;
714 if (ParseOptionalThreadLocal(TLM) ||
715 ParseOptionalAddrSpace(AddrSpace) ||
716 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
718 ParseOptionalToken(lltok::kw_externally_initialized,
719 IsExternallyInitialized,
720 &IsExternallyInitializedLoc) ||
721 ParseGlobalType(IsConstant) ||
722 ParseType(Ty, TyLoc))
725 // If the linkage is specified and is external, then no initializer is
728 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
729 Linkage != GlobalValue::ExternalWeakLinkage &&
730 Linkage != GlobalValue::ExternalLinkage)) {
731 if (ParseGlobalValue(Ty, Init))
735 if (Ty->isFunctionTy() || Ty->isLabelTy())
736 return Error(TyLoc, "invalid type for global variable");
738 GlobalVariable *GV = 0;
740 // See if the global was forward referenced, if so, use the global.
742 if (GlobalValue *GVal = M->getNamedValue(Name)) {
743 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
744 return Error(NameLoc, "redefinition of global '@" + Name + "'");
745 GV = cast<GlobalVariable>(GVal);
748 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
749 I = ForwardRefValIDs.find(NumberedVals.size());
750 if (I != ForwardRefValIDs.end()) {
751 GV = cast<GlobalVariable>(I->second.first);
752 ForwardRefValIDs.erase(I);
757 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
758 Name, 0, GlobalVariable::NotThreadLocal,
761 if (GV->getType()->getElementType() != Ty)
763 "forward reference and definition of global have different types");
765 // Move the forward-reference to the correct spot in the module.
766 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
770 NumberedVals.push_back(GV);
772 // Set the parsed properties on the global.
774 GV->setInitializer(Init);
775 GV->setConstant(IsConstant);
776 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
777 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
778 GV->setExternallyInitialized(IsExternallyInitialized);
779 GV->setThreadLocalMode(TLM);
780 GV->setUnnamedAddr(UnnamedAddr);
782 // Parse attributes on the global.
783 while (Lex.getKind() == lltok::comma) {
786 if (Lex.getKind() == lltok::kw_section) {
788 GV->setSection(Lex.getStrVal());
789 if (ParseToken(lltok::StringConstant, "expected global section string"))
791 } else if (Lex.getKind() == lltok::kw_align) {
793 if (ParseOptionalAlignment(Alignment)) return true;
794 GV->setAlignment(Alignment);
796 TokError("unknown global variable property!");
803 /// ParseUnnamedAttrGrp
804 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
805 bool LLParser::ParseUnnamedAttrGrp() {
806 assert(Lex.getKind() == lltok::kw_attributes);
807 LocTy AttrGrpLoc = Lex.getLoc();
810 assert(Lex.getKind() == lltok::AttrGrpID);
811 unsigned VarID = Lex.getUIntVal();
812 std::vector<unsigned> unused;
816 if (ParseToken(lltok::equal, "expected '=' here") ||
817 ParseToken(lltok::lbrace, "expected '{' here") ||
818 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
820 ParseToken(lltok::rbrace, "expected end of attribute group"))
823 if (!NumberedAttrBuilders[VarID].hasAttributes())
824 return Error(AttrGrpLoc, "attribute group has no attributes");
829 /// ParseFnAttributeValuePairs
830 /// ::= <attr> | <attr> '=' <value>
831 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
832 std::vector<unsigned> &FwdRefAttrGrps,
833 bool inAttrGrp, LocTy &BuiltinLoc) {
834 bool HaveError = false;
839 lltok::Kind Token = Lex.getKind();
840 if (Token == lltok::kw_builtin)
841 BuiltinLoc = Lex.getLoc();
844 if (!inAttrGrp) return HaveError;
845 return Error(Lex.getLoc(), "unterminated attribute group");
850 case lltok::AttrGrpID: {
851 // Allow a function to reference an attribute group:
853 // define void @foo() #1 { ... }
857 "cannot have an attribute group reference in an attribute group");
859 unsigned AttrGrpNum = Lex.getUIntVal();
860 if (inAttrGrp) break;
862 // Save the reference to the attribute group. We'll fill it in later.
863 FwdRefAttrGrps.push_back(AttrGrpNum);
866 // Target-dependent attributes:
867 case lltok::StringConstant: {
868 std::string Attr = Lex.getStrVal();
871 if (EatIfPresent(lltok::equal) &&
872 ParseStringConstant(Val))
875 B.addAttribute(Attr, Val);
879 // Target-independent attributes:
880 case lltok::kw_align: {
881 // As a hack, we allow function alignment to be initially parsed as an
882 // attribute on a function declaration/definition or added to an attribute
883 // group and later moved to the alignment field.
887 if (ParseToken(lltok::equal, "expected '=' here") ||
888 ParseUInt32(Alignment))
891 if (ParseOptionalAlignment(Alignment))
894 B.addAlignmentAttr(Alignment);
897 case lltok::kw_alignstack: {
901 if (ParseToken(lltok::equal, "expected '=' here") ||
902 ParseUInt32(Alignment))
905 if (ParseOptionalStackAlignment(Alignment))
908 B.addStackAlignmentAttr(Alignment);
911 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
912 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
913 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
914 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
915 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
916 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
917 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
918 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
919 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
920 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
921 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
922 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
923 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
924 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
925 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
926 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
927 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
928 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
929 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
930 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
931 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
932 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
933 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
934 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
935 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
936 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
939 case lltok::kw_inreg:
940 case lltok::kw_signext:
941 case lltok::kw_zeroext:
944 "invalid use of attribute on a function");
946 case lltok::kw_byval:
948 case lltok::kw_noalias:
949 case lltok::kw_nocapture:
950 case lltok::kw_returned:
954 "invalid use of parameter-only attribute on a function");
962 //===----------------------------------------------------------------------===//
963 // GlobalValue Reference/Resolution Routines.
964 //===----------------------------------------------------------------------===//
966 /// GetGlobalVal - Get a value with the specified name or ID, creating a
967 /// forward reference record if needed. This can return null if the value
968 /// exists but does not have the right type.
969 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
971 PointerType *PTy = dyn_cast<PointerType>(Ty);
973 Error(Loc, "global variable reference must have pointer type");
977 // Look this name up in the normal function symbol table.
979 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
981 // If this is a forward reference for the value, see if we already created a
982 // forward ref record.
984 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
985 I = ForwardRefVals.find(Name);
986 if (I != ForwardRefVals.end())
987 Val = I->second.first;
990 // If we have the value in the symbol table or fwd-ref table, return it.
992 if (Val->getType() == Ty) return Val;
993 Error(Loc, "'@" + Name + "' defined with type '" +
994 getTypeString(Val->getType()) + "'");
998 // Otherwise, create a new forward reference for this value and remember it.
1000 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1001 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1003 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1004 GlobalValue::ExternalWeakLinkage, 0, Name,
1005 0, GlobalVariable::NotThreadLocal,
1006 PTy->getAddressSpace());
1008 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1012 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1013 PointerType *PTy = dyn_cast<PointerType>(Ty);
1015 Error(Loc, "global variable reference must have pointer type");
1019 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1021 // If this is a forward reference for the value, see if we already created a
1022 // forward ref record.
1024 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1025 I = ForwardRefValIDs.find(ID);
1026 if (I != ForwardRefValIDs.end())
1027 Val = I->second.first;
1030 // If we have the value in the symbol table or fwd-ref table, return it.
1032 if (Val->getType() == Ty) return Val;
1033 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1034 getTypeString(Val->getType()) + "'");
1038 // Otherwise, create a new forward reference for this value and remember it.
1039 GlobalValue *FwdVal;
1040 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1041 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1043 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1044 GlobalValue::ExternalWeakLinkage, 0, "");
1046 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1051 //===----------------------------------------------------------------------===//
1053 //===----------------------------------------------------------------------===//
1055 /// ParseToken - If the current token has the specified kind, eat it and return
1056 /// success. Otherwise, emit the specified error and return failure.
1057 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1058 if (Lex.getKind() != T)
1059 return TokError(ErrMsg);
1064 /// ParseStringConstant
1065 /// ::= StringConstant
1066 bool LLParser::ParseStringConstant(std::string &Result) {
1067 if (Lex.getKind() != lltok::StringConstant)
1068 return TokError("expected string constant");
1069 Result = Lex.getStrVal();
1076 bool LLParser::ParseUInt32(unsigned &Val) {
1077 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1078 return TokError("expected integer");
1079 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1080 if (Val64 != unsigned(Val64))
1081 return TokError("expected 32-bit integer (too large)");
1088 /// := 'localdynamic'
1089 /// := 'initialexec'
1091 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1092 switch (Lex.getKind()) {
1094 return TokError("expected localdynamic, initialexec or localexec");
1095 case lltok::kw_localdynamic:
1096 TLM = GlobalVariable::LocalDynamicTLSModel;
1098 case lltok::kw_initialexec:
1099 TLM = GlobalVariable::InitialExecTLSModel;
1101 case lltok::kw_localexec:
1102 TLM = GlobalVariable::LocalExecTLSModel;
1110 /// ParseOptionalThreadLocal
1112 /// := 'thread_local'
1113 /// := 'thread_local' '(' tlsmodel ')'
1114 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1115 TLM = GlobalVariable::NotThreadLocal;
1116 if (!EatIfPresent(lltok::kw_thread_local))
1119 TLM = GlobalVariable::GeneralDynamicTLSModel;
1120 if (Lex.getKind() == lltok::lparen) {
1122 return ParseTLSModel(TLM) ||
1123 ParseToken(lltok::rparen, "expected ')' after thread local model");
1128 /// ParseOptionalAddrSpace
1130 /// := 'addrspace' '(' uint32 ')'
1131 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1133 if (!EatIfPresent(lltok::kw_addrspace))
1135 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1136 ParseUInt32(AddrSpace) ||
1137 ParseToken(lltok::rparen, "expected ')' in address space");
1140 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1141 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1142 bool HaveError = false;
1147 lltok::Kind Token = Lex.getKind();
1149 default: // End of attributes.
1151 case lltok::kw_align: {
1153 if (ParseOptionalAlignment(Alignment))
1155 B.addAlignmentAttr(Alignment);
1158 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1159 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1160 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1161 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1162 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1163 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1164 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1165 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1166 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1167 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1168 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1170 case lltok::kw_alignstack:
1171 case lltok::kw_alwaysinline:
1172 case lltok::kw_builtin:
1173 case lltok::kw_inlinehint:
1174 case lltok::kw_minsize:
1175 case lltok::kw_naked:
1176 case lltok::kw_nobuiltin:
1177 case lltok::kw_noduplicate:
1178 case lltok::kw_noimplicitfloat:
1179 case lltok::kw_noinline:
1180 case lltok::kw_nonlazybind:
1181 case lltok::kw_noredzone:
1182 case lltok::kw_noreturn:
1183 case lltok::kw_nounwind:
1184 case lltok::kw_optnone:
1185 case lltok::kw_optsize:
1186 case lltok::kw_returns_twice:
1187 case lltok::kw_sanitize_address:
1188 case lltok::kw_sanitize_memory:
1189 case lltok::kw_sanitize_thread:
1191 case lltok::kw_sspreq:
1192 case lltok::kw_sspstrong:
1193 case lltok::kw_uwtable:
1194 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1202 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1203 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1204 bool HaveError = false;
1209 lltok::Kind Token = Lex.getKind();
1211 default: // End of attributes.
1213 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1214 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1215 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1216 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1219 case lltok::kw_align:
1220 case lltok::kw_byval:
1221 case lltok::kw_nest:
1222 case lltok::kw_nocapture:
1223 case lltok::kw_returned:
1224 case lltok::kw_sret:
1225 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1228 case lltok::kw_alignstack:
1229 case lltok::kw_alwaysinline:
1230 case lltok::kw_builtin:
1231 case lltok::kw_cold:
1232 case lltok::kw_inlinehint:
1233 case lltok::kw_minsize:
1234 case lltok::kw_naked:
1235 case lltok::kw_nobuiltin:
1236 case lltok::kw_noduplicate:
1237 case lltok::kw_noimplicitfloat:
1238 case lltok::kw_noinline:
1239 case lltok::kw_nonlazybind:
1240 case lltok::kw_noredzone:
1241 case lltok::kw_noreturn:
1242 case lltok::kw_nounwind:
1243 case lltok::kw_optnone:
1244 case lltok::kw_optsize:
1245 case lltok::kw_returns_twice:
1246 case lltok::kw_sanitize_address:
1247 case lltok::kw_sanitize_memory:
1248 case lltok::kw_sanitize_thread:
1250 case lltok::kw_sspreq:
1251 case lltok::kw_sspstrong:
1252 case lltok::kw_uwtable:
1253 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1256 case lltok::kw_readnone:
1257 case lltok::kw_readonly:
1258 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1265 /// ParseOptionalLinkage
1268 /// ::= 'linker_private'
1269 /// ::= 'linker_private_weak'
1274 /// ::= 'linkonce_odr'
1275 /// ::= 'linkonce_odr_auto_hide'
1276 /// ::= 'available_externally'
1281 /// ::= 'extern_weak'
1283 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1285 switch (Lex.getKind()) {
1286 default: Res=GlobalValue::ExternalLinkage; return false;
1287 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1288 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
1289 case lltok::kw_linker_private_weak:
1290 Res = GlobalValue::LinkerPrivateWeakLinkage;
1292 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1293 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1294 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1295 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1296 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1297 case lltok::kw_linkonce_odr_auto_hide:
1298 case lltok::kw_linker_private_weak_def_auto: // FIXME: For backwards compat.
1299 Res = GlobalValue::LinkOnceODRAutoHideLinkage;
1301 case lltok::kw_available_externally:
1302 Res = GlobalValue::AvailableExternallyLinkage;
1304 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1305 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1306 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1307 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1308 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1309 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1316 /// ParseOptionalVisibility
1322 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1323 switch (Lex.getKind()) {
1324 default: Res = GlobalValue::DefaultVisibility; return false;
1325 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1326 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1327 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1333 /// ParseOptionalCallingConv
1337 /// ::= 'kw_intel_ocl_bicc'
1339 /// ::= 'x86_stdcallcc'
1340 /// ::= 'x86_fastcallcc'
1341 /// ::= 'x86_thiscallcc'
1342 /// ::= 'arm_apcscc'
1343 /// ::= 'arm_aapcscc'
1344 /// ::= 'arm_aapcs_vfpcc'
1345 /// ::= 'msp430_intrcc'
1346 /// ::= 'ptx_kernel'
1347 /// ::= 'ptx_device'
1349 /// ::= 'spir_kernel'
1350 /// ::= 'x86_64_sysvcc'
1351 /// ::= 'x86_64_win64cc'
1352 /// ::= 'webkit_jscc'
1355 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1356 switch (Lex.getKind()) {
1357 default: CC = CallingConv::C; return false;
1358 case lltok::kw_ccc: CC = CallingConv::C; break;
1359 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1360 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1361 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1362 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1363 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1364 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1365 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1366 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1367 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1368 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1369 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1370 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1371 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1372 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1373 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1374 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1375 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1376 case lltok::kw_cc: {
1377 unsigned ArbitraryCC;
1379 if (ParseUInt32(ArbitraryCC))
1381 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1390 /// ParseInstructionMetadata
1391 /// ::= !dbg !42 (',' !dbg !57)*
1392 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1393 PerFunctionState *PFS) {
1395 if (Lex.getKind() != lltok::MetadataVar)
1396 return TokError("expected metadata after comma");
1398 std::string Name = Lex.getStrVal();
1399 unsigned MDK = M->getMDKindID(Name);
1403 SMLoc Loc = Lex.getLoc();
1405 if (ParseToken(lltok::exclaim, "expected '!' here"))
1408 // This code is similar to that of ParseMetadataValue, however it needs to
1409 // have special-case code for a forward reference; see the comments on
1410 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1411 // at the top level here.
1412 if (Lex.getKind() == lltok::lbrace) {
1414 if (ParseMetadataListValue(ID, PFS))
1416 assert(ID.Kind == ValID::t_MDNode);
1417 Inst->setMetadata(MDK, ID.MDNodeVal);
1419 unsigned NodeID = 0;
1420 if (ParseMDNodeID(Node, NodeID))
1423 // If we got the node, add it to the instruction.
1424 Inst->setMetadata(MDK, Node);
1426 MDRef R = { Loc, MDK, NodeID };
1427 // Otherwise, remember that this should be resolved later.
1428 ForwardRefInstMetadata[Inst].push_back(R);
1432 if (MDK == LLVMContext::MD_tbaa)
1433 InstsWithTBAATag.push_back(Inst);
1435 // If this is the end of the list, we're done.
1436 } while (EatIfPresent(lltok::comma));
1440 /// ParseOptionalAlignment
1443 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1445 if (!EatIfPresent(lltok::kw_align))
1447 LocTy AlignLoc = Lex.getLoc();
1448 if (ParseUInt32(Alignment)) return true;
1449 if (!isPowerOf2_32(Alignment))
1450 return Error(AlignLoc, "alignment is not a power of two");
1451 if (Alignment > Value::MaximumAlignment)
1452 return Error(AlignLoc, "huge alignments are not supported yet");
1456 /// ParseOptionalCommaAlign
1460 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1462 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1463 bool &AteExtraComma) {
1464 AteExtraComma = false;
1465 while (EatIfPresent(lltok::comma)) {
1466 // Metadata at the end is an early exit.
1467 if (Lex.getKind() == lltok::MetadataVar) {
1468 AteExtraComma = true;
1472 if (Lex.getKind() != lltok::kw_align)
1473 return Error(Lex.getLoc(), "expected metadata or 'align'");
1475 if (ParseOptionalAlignment(Alignment)) return true;
1481 /// ParseScopeAndOrdering
1482 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1485 /// This sets Scope and Ordering to the parsed values.
1486 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1487 AtomicOrdering &Ordering) {
1491 Scope = CrossThread;
1492 if (EatIfPresent(lltok::kw_singlethread))
1493 Scope = SingleThread;
1494 switch (Lex.getKind()) {
1495 default: return TokError("Expected ordering on atomic instruction");
1496 case lltok::kw_unordered: Ordering = Unordered; break;
1497 case lltok::kw_monotonic: Ordering = Monotonic; break;
1498 case lltok::kw_acquire: Ordering = Acquire; break;
1499 case lltok::kw_release: Ordering = Release; break;
1500 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1501 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1507 /// ParseOptionalStackAlignment
1509 /// ::= 'alignstack' '(' 4 ')'
1510 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1512 if (!EatIfPresent(lltok::kw_alignstack))
1514 LocTy ParenLoc = Lex.getLoc();
1515 if (!EatIfPresent(lltok::lparen))
1516 return Error(ParenLoc, "expected '('");
1517 LocTy AlignLoc = Lex.getLoc();
1518 if (ParseUInt32(Alignment)) return true;
1519 ParenLoc = Lex.getLoc();
1520 if (!EatIfPresent(lltok::rparen))
1521 return Error(ParenLoc, "expected ')'");
1522 if (!isPowerOf2_32(Alignment))
1523 return Error(AlignLoc, "stack alignment is not a power of two");
1527 /// ParseIndexList - This parses the index list for an insert/extractvalue
1528 /// instruction. This sets AteExtraComma in the case where we eat an extra
1529 /// comma at the end of the line and find that it is followed by metadata.
1530 /// Clients that don't allow metadata can call the version of this function that
1531 /// only takes one argument.
1534 /// ::= (',' uint32)+
1536 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1537 bool &AteExtraComma) {
1538 AteExtraComma = false;
1540 if (Lex.getKind() != lltok::comma)
1541 return TokError("expected ',' as start of index list");
1543 while (EatIfPresent(lltok::comma)) {
1544 if (Lex.getKind() == lltok::MetadataVar) {
1545 AteExtraComma = true;
1549 if (ParseUInt32(Idx)) return true;
1550 Indices.push_back(Idx);
1556 //===----------------------------------------------------------------------===//
1558 //===----------------------------------------------------------------------===//
1560 /// ParseType - Parse a type.
1561 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1562 SMLoc TypeLoc = Lex.getLoc();
1563 switch (Lex.getKind()) {
1565 return TokError("expected type");
1567 // Type ::= 'float' | 'void' (etc)
1568 Result = Lex.getTyVal();
1572 // Type ::= StructType
1573 if (ParseAnonStructType(Result, false))
1576 case lltok::lsquare:
1577 // Type ::= '[' ... ']'
1578 Lex.Lex(); // eat the lsquare.
1579 if (ParseArrayVectorType(Result, false))
1582 case lltok::less: // Either vector or packed struct.
1583 // Type ::= '<' ... '>'
1585 if (Lex.getKind() == lltok::lbrace) {
1586 if (ParseAnonStructType(Result, true) ||
1587 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1589 } else if (ParseArrayVectorType(Result, true))
1592 case lltok::LocalVar: {
1594 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1596 // If the type hasn't been defined yet, create a forward definition and
1597 // remember where that forward def'n was seen (in case it never is defined).
1598 if (Entry.first == 0) {
1599 Entry.first = StructType::create(Context, Lex.getStrVal());
1600 Entry.second = Lex.getLoc();
1602 Result = Entry.first;
1607 case lltok::LocalVarID: {
1609 if (Lex.getUIntVal() >= NumberedTypes.size())
1610 NumberedTypes.resize(Lex.getUIntVal()+1);
1611 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1613 // If the type hasn't been defined yet, create a forward definition and
1614 // remember where that forward def'n was seen (in case it never is defined).
1615 if (Entry.first == 0) {
1616 Entry.first = StructType::create(Context);
1617 Entry.second = Lex.getLoc();
1619 Result = Entry.first;
1625 // Parse the type suffixes.
1627 switch (Lex.getKind()) {
1630 if (!AllowVoid && Result->isVoidTy())
1631 return Error(TypeLoc, "void type only allowed for function results");
1634 // Type ::= Type '*'
1636 if (Result->isLabelTy())
1637 return TokError("basic block pointers are invalid");
1638 if (Result->isVoidTy())
1639 return TokError("pointers to void are invalid - use i8* instead");
1640 if (!PointerType::isValidElementType(Result))
1641 return TokError("pointer to this type is invalid");
1642 Result = PointerType::getUnqual(Result);
1646 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1647 case lltok::kw_addrspace: {
1648 if (Result->isLabelTy())
1649 return TokError("basic block pointers are invalid");
1650 if (Result->isVoidTy())
1651 return TokError("pointers to void are invalid; use i8* instead");
1652 if (!PointerType::isValidElementType(Result))
1653 return TokError("pointer to this type is invalid");
1655 if (ParseOptionalAddrSpace(AddrSpace) ||
1656 ParseToken(lltok::star, "expected '*' in address space"))
1659 Result = PointerType::get(Result, AddrSpace);
1663 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1665 if (ParseFunctionType(Result))
1672 /// ParseParameterList
1674 /// ::= '(' Arg (',' Arg)* ')'
1676 /// ::= Type OptionalAttributes Value OptionalAttributes
1677 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1678 PerFunctionState &PFS) {
1679 if (ParseToken(lltok::lparen, "expected '(' in call"))
1682 unsigned AttrIndex = 1;
1683 while (Lex.getKind() != lltok::rparen) {
1684 // If this isn't the first argument, we need a comma.
1685 if (!ArgList.empty() &&
1686 ParseToken(lltok::comma, "expected ',' in argument list"))
1689 // Parse the argument.
1692 AttrBuilder ArgAttrs;
1694 if (ParseType(ArgTy, ArgLoc))
1697 // Otherwise, handle normal operands.
1698 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1700 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1705 Lex.Lex(); // Lex the ')'.
1711 /// ParseArgumentList - Parse the argument list for a function type or function
1713 /// ::= '(' ArgTypeListI ')'
1717 /// ::= ArgTypeList ',' '...'
1718 /// ::= ArgType (',' ArgType)*
1720 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1723 assert(Lex.getKind() == lltok::lparen);
1724 Lex.Lex(); // eat the (.
1726 if (Lex.getKind() == lltok::rparen) {
1728 } else if (Lex.getKind() == lltok::dotdotdot) {
1732 LocTy TypeLoc = Lex.getLoc();
1737 if (ParseType(ArgTy) ||
1738 ParseOptionalParamAttrs(Attrs)) return true;
1740 if (ArgTy->isVoidTy())
1741 return Error(TypeLoc, "argument can not have void type");
1743 if (Lex.getKind() == lltok::LocalVar) {
1744 Name = Lex.getStrVal();
1748 if (!FunctionType::isValidArgumentType(ArgTy))
1749 return Error(TypeLoc, "invalid type for function argument");
1751 unsigned AttrIndex = 1;
1752 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1753 AttributeSet::get(ArgTy->getContext(),
1754 AttrIndex++, Attrs), Name));
1756 while (EatIfPresent(lltok::comma)) {
1757 // Handle ... at end of arg list.
1758 if (EatIfPresent(lltok::dotdotdot)) {
1763 // Otherwise must be an argument type.
1764 TypeLoc = Lex.getLoc();
1765 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1767 if (ArgTy->isVoidTy())
1768 return Error(TypeLoc, "argument can not have void type");
1770 if (Lex.getKind() == lltok::LocalVar) {
1771 Name = Lex.getStrVal();
1777 if (!ArgTy->isFirstClassType())
1778 return Error(TypeLoc, "invalid type for function argument");
1780 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1781 AttributeSet::get(ArgTy->getContext(),
1782 AttrIndex++, Attrs),
1787 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1790 /// ParseFunctionType
1791 /// ::= Type ArgumentList OptionalAttrs
1792 bool LLParser::ParseFunctionType(Type *&Result) {
1793 assert(Lex.getKind() == lltok::lparen);
1795 if (!FunctionType::isValidReturnType(Result))
1796 return TokError("invalid function return type");
1798 SmallVector<ArgInfo, 8> ArgList;
1800 if (ParseArgumentList(ArgList, isVarArg))
1803 // Reject names on the arguments lists.
1804 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1805 if (!ArgList[i].Name.empty())
1806 return Error(ArgList[i].Loc, "argument name invalid in function type");
1807 if (ArgList[i].Attrs.hasAttributes(i + 1))
1808 return Error(ArgList[i].Loc,
1809 "argument attributes invalid in function type");
1812 SmallVector<Type*, 16> ArgListTy;
1813 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1814 ArgListTy.push_back(ArgList[i].Ty);
1816 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1820 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1822 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1823 SmallVector<Type*, 8> Elts;
1824 if (ParseStructBody(Elts)) return true;
1826 Result = StructType::get(Context, Elts, Packed);
1830 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1831 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1832 std::pair<Type*, LocTy> &Entry,
1834 // If the type was already defined, diagnose the redefinition.
1835 if (Entry.first && !Entry.second.isValid())
1836 return Error(TypeLoc, "redefinition of type");
1838 // If we have opaque, just return without filling in the definition for the
1839 // struct. This counts as a definition as far as the .ll file goes.
1840 if (EatIfPresent(lltok::kw_opaque)) {
1841 // This type is being defined, so clear the location to indicate this.
1842 Entry.second = SMLoc();
1844 // If this type number has never been uttered, create it.
1845 if (Entry.first == 0)
1846 Entry.first = StructType::create(Context, Name);
1847 ResultTy = Entry.first;
1851 // If the type starts with '<', then it is either a packed struct or a vector.
1852 bool isPacked = EatIfPresent(lltok::less);
1854 // If we don't have a struct, then we have a random type alias, which we
1855 // accept for compatibility with old files. These types are not allowed to be
1856 // forward referenced and not allowed to be recursive.
1857 if (Lex.getKind() != lltok::lbrace) {
1859 return Error(TypeLoc, "forward references to non-struct type");
1863 return ParseArrayVectorType(ResultTy, true);
1864 return ParseType(ResultTy);
1867 // This type is being defined, so clear the location to indicate this.
1868 Entry.second = SMLoc();
1870 // If this type number has never been uttered, create it.
1871 if (Entry.first == 0)
1872 Entry.first = StructType::create(Context, Name);
1874 StructType *STy = cast<StructType>(Entry.first);
1876 SmallVector<Type*, 8> Body;
1877 if (ParseStructBody(Body) ||
1878 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1881 STy->setBody(Body, isPacked);
1887 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1890 /// ::= '{' Type (',' Type)* '}'
1891 /// ::= '<' '{' '}' '>'
1892 /// ::= '<' '{' Type (',' Type)* '}' '>'
1893 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
1894 assert(Lex.getKind() == lltok::lbrace);
1895 Lex.Lex(); // Consume the '{'
1897 // Handle the empty struct.
1898 if (EatIfPresent(lltok::rbrace))
1901 LocTy EltTyLoc = Lex.getLoc();
1903 if (ParseType(Ty)) return true;
1906 if (!StructType::isValidElementType(Ty))
1907 return Error(EltTyLoc, "invalid element type for struct");
1909 while (EatIfPresent(lltok::comma)) {
1910 EltTyLoc = Lex.getLoc();
1911 if (ParseType(Ty)) return true;
1913 if (!StructType::isValidElementType(Ty))
1914 return Error(EltTyLoc, "invalid element type for struct");
1919 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
1922 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1923 /// token has already been consumed.
1925 /// ::= '[' APSINTVAL 'x' Types ']'
1926 /// ::= '<' APSINTVAL 'x' Types '>'
1927 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
1928 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1929 Lex.getAPSIntVal().getBitWidth() > 64)
1930 return TokError("expected number in address space");
1932 LocTy SizeLoc = Lex.getLoc();
1933 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1936 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1939 LocTy TypeLoc = Lex.getLoc();
1941 if (ParseType(EltTy)) return true;
1943 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1944 "expected end of sequential type"))
1949 return Error(SizeLoc, "zero element vector is illegal");
1950 if ((unsigned)Size != Size)
1951 return Error(SizeLoc, "size too large for vector");
1952 if (!VectorType::isValidElementType(EltTy))
1953 return Error(TypeLoc, "invalid vector element type");
1954 Result = VectorType::get(EltTy, unsigned(Size));
1956 if (!ArrayType::isValidElementType(EltTy))
1957 return Error(TypeLoc, "invalid array element type");
1958 Result = ArrayType::get(EltTy, Size);
1963 //===----------------------------------------------------------------------===//
1964 // Function Semantic Analysis.
1965 //===----------------------------------------------------------------------===//
1967 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1969 : P(p), F(f), FunctionNumber(functionNumber) {
1971 // Insert unnamed arguments into the NumberedVals list.
1972 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1975 NumberedVals.push_back(AI);
1978 LLParser::PerFunctionState::~PerFunctionState() {
1979 // If there were any forward referenced non-basicblock values, delete them.
1980 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1981 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1982 if (!isa<BasicBlock>(I->second.first)) {
1983 I->second.first->replaceAllUsesWith(
1984 UndefValue::get(I->second.first->getType()));
1985 delete I->second.first;
1986 I->second.first = 0;
1989 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1990 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1991 if (!isa<BasicBlock>(I->second.first)) {
1992 I->second.first->replaceAllUsesWith(
1993 UndefValue::get(I->second.first->getType()));
1994 delete I->second.first;
1995 I->second.first = 0;
1999 bool LLParser::PerFunctionState::FinishFunction() {
2000 // Check to see if someone took the address of labels in this block.
2001 if (!P.ForwardRefBlockAddresses.empty()) {
2003 if (!F.getName().empty()) {
2004 FunctionID.Kind = ValID::t_GlobalName;
2005 FunctionID.StrVal = F.getName();
2007 FunctionID.Kind = ValID::t_GlobalID;
2008 FunctionID.UIntVal = FunctionNumber;
2011 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
2012 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
2013 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
2014 // Resolve all these references.
2015 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
2018 P.ForwardRefBlockAddresses.erase(FRBAI);
2022 if (!ForwardRefVals.empty())
2023 return P.Error(ForwardRefVals.begin()->second.second,
2024 "use of undefined value '%" + ForwardRefVals.begin()->first +
2026 if (!ForwardRefValIDs.empty())
2027 return P.Error(ForwardRefValIDs.begin()->second.second,
2028 "use of undefined value '%" +
2029 Twine(ForwardRefValIDs.begin()->first) + "'");
2034 /// GetVal - Get a value with the specified name or ID, creating a
2035 /// forward reference record if needed. This can return null if the value
2036 /// exists but does not have the right type.
2037 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2038 Type *Ty, LocTy Loc) {
2039 // Look this name up in the normal function symbol table.
2040 Value *Val = F.getValueSymbolTable().lookup(Name);
2042 // If this is a forward reference for the value, see if we already created a
2043 // forward ref record.
2045 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2046 I = ForwardRefVals.find(Name);
2047 if (I != ForwardRefVals.end())
2048 Val = I->second.first;
2051 // If we have the value in the symbol table or fwd-ref table, return it.
2053 if (Val->getType() == Ty) return Val;
2054 if (Ty->isLabelTy())
2055 P.Error(Loc, "'%" + Name + "' is not a basic block");
2057 P.Error(Loc, "'%" + Name + "' defined with type '" +
2058 getTypeString(Val->getType()) + "'");
2062 // Don't make placeholders with invalid type.
2063 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2064 P.Error(Loc, "invalid use of a non-first-class type");
2068 // Otherwise, create a new forward reference for this value and remember it.
2070 if (Ty->isLabelTy())
2071 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2073 FwdVal = new Argument(Ty, Name);
2075 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2079 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2081 // Look this name up in the normal function symbol table.
2082 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
2084 // If this is a forward reference for the value, see if we already created a
2085 // forward ref record.
2087 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2088 I = ForwardRefValIDs.find(ID);
2089 if (I != ForwardRefValIDs.end())
2090 Val = I->second.first;
2093 // If we have the value in the symbol table or fwd-ref table, return it.
2095 if (Val->getType() == Ty) return Val;
2096 if (Ty->isLabelTy())
2097 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2099 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2100 getTypeString(Val->getType()) + "'");
2104 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2105 P.Error(Loc, "invalid use of a non-first-class type");
2109 // Otherwise, create a new forward reference for this value and remember it.
2111 if (Ty->isLabelTy())
2112 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2114 FwdVal = new Argument(Ty);
2116 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2120 /// SetInstName - After an instruction is parsed and inserted into its
2121 /// basic block, this installs its name.
2122 bool LLParser::PerFunctionState::SetInstName(int NameID,
2123 const std::string &NameStr,
2124 LocTy NameLoc, Instruction *Inst) {
2125 // If this instruction has void type, it cannot have a name or ID specified.
2126 if (Inst->getType()->isVoidTy()) {
2127 if (NameID != -1 || !NameStr.empty())
2128 return P.Error(NameLoc, "instructions returning void cannot have a name");
2132 // If this was a numbered instruction, verify that the instruction is the
2133 // expected value and resolve any forward references.
2134 if (NameStr.empty()) {
2135 // If neither a name nor an ID was specified, just use the next ID.
2137 NameID = NumberedVals.size();
2139 if (unsigned(NameID) != NumberedVals.size())
2140 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2141 Twine(NumberedVals.size()) + "'");
2143 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2144 ForwardRefValIDs.find(NameID);
2145 if (FI != ForwardRefValIDs.end()) {
2146 if (FI->second.first->getType() != Inst->getType())
2147 return P.Error(NameLoc, "instruction forward referenced with type '" +
2148 getTypeString(FI->second.first->getType()) + "'");
2149 FI->second.first->replaceAllUsesWith(Inst);
2150 delete FI->second.first;
2151 ForwardRefValIDs.erase(FI);
2154 NumberedVals.push_back(Inst);
2158 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2159 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2160 FI = ForwardRefVals.find(NameStr);
2161 if (FI != ForwardRefVals.end()) {
2162 if (FI->second.first->getType() != Inst->getType())
2163 return P.Error(NameLoc, "instruction forward referenced with type '" +
2164 getTypeString(FI->second.first->getType()) + "'");
2165 FI->second.first->replaceAllUsesWith(Inst);
2166 delete FI->second.first;
2167 ForwardRefVals.erase(FI);
2170 // Set the name on the instruction.
2171 Inst->setName(NameStr);
2173 if (Inst->getName() != NameStr)
2174 return P.Error(NameLoc, "multiple definition of local value named '" +
2179 /// GetBB - Get a basic block with the specified name or ID, creating a
2180 /// forward reference record if needed.
2181 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2183 return cast_or_null<BasicBlock>(GetVal(Name,
2184 Type::getLabelTy(F.getContext()), Loc));
2187 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2188 return cast_or_null<BasicBlock>(GetVal(ID,
2189 Type::getLabelTy(F.getContext()), Loc));
2192 /// DefineBB - Define the specified basic block, which is either named or
2193 /// unnamed. If there is an error, this returns null otherwise it returns
2194 /// the block being defined.
2195 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2199 BB = GetBB(NumberedVals.size(), Loc);
2201 BB = GetBB(Name, Loc);
2202 if (BB == 0) return 0; // Already diagnosed error.
2204 // Move the block to the end of the function. Forward ref'd blocks are
2205 // inserted wherever they happen to be referenced.
2206 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2208 // Remove the block from forward ref sets.
2210 ForwardRefValIDs.erase(NumberedVals.size());
2211 NumberedVals.push_back(BB);
2213 // BB forward references are already in the function symbol table.
2214 ForwardRefVals.erase(Name);
2220 //===----------------------------------------------------------------------===//
2222 //===----------------------------------------------------------------------===//
2224 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2225 /// type implied. For example, if we parse "4" we don't know what integer type
2226 /// it has. The value will later be combined with its type and checked for
2227 /// sanity. PFS is used to convert function-local operands of metadata (since
2228 /// metadata operands are not just parsed here but also converted to values).
2229 /// PFS can be null when we are not parsing metadata values inside a function.
2230 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2231 ID.Loc = Lex.getLoc();
2232 switch (Lex.getKind()) {
2233 default: return TokError("expected value token");
2234 case lltok::GlobalID: // @42
2235 ID.UIntVal = Lex.getUIntVal();
2236 ID.Kind = ValID::t_GlobalID;
2238 case lltok::GlobalVar: // @foo
2239 ID.StrVal = Lex.getStrVal();
2240 ID.Kind = ValID::t_GlobalName;
2242 case lltok::LocalVarID: // %42
2243 ID.UIntVal = Lex.getUIntVal();
2244 ID.Kind = ValID::t_LocalID;
2246 case lltok::LocalVar: // %foo
2247 ID.StrVal = Lex.getStrVal();
2248 ID.Kind = ValID::t_LocalName;
2250 case lltok::exclaim: // !42, !{...}, or !"foo"
2251 return ParseMetadataValue(ID, PFS);
2253 ID.APSIntVal = Lex.getAPSIntVal();
2254 ID.Kind = ValID::t_APSInt;
2256 case lltok::APFloat:
2257 ID.APFloatVal = Lex.getAPFloatVal();
2258 ID.Kind = ValID::t_APFloat;
2260 case lltok::kw_true:
2261 ID.ConstantVal = ConstantInt::getTrue(Context);
2262 ID.Kind = ValID::t_Constant;
2264 case lltok::kw_false:
2265 ID.ConstantVal = ConstantInt::getFalse(Context);
2266 ID.Kind = ValID::t_Constant;
2268 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2269 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2270 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2272 case lltok::lbrace: {
2273 // ValID ::= '{' ConstVector '}'
2275 SmallVector<Constant*, 16> Elts;
2276 if (ParseGlobalValueVector(Elts) ||
2277 ParseToken(lltok::rbrace, "expected end of struct constant"))
2280 ID.ConstantStructElts = new Constant*[Elts.size()];
2281 ID.UIntVal = Elts.size();
2282 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2283 ID.Kind = ValID::t_ConstantStruct;
2287 // ValID ::= '<' ConstVector '>' --> Vector.
2288 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2290 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2292 SmallVector<Constant*, 16> Elts;
2293 LocTy FirstEltLoc = Lex.getLoc();
2294 if (ParseGlobalValueVector(Elts) ||
2296 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2297 ParseToken(lltok::greater, "expected end of constant"))
2300 if (isPackedStruct) {
2301 ID.ConstantStructElts = new Constant*[Elts.size()];
2302 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2303 ID.UIntVal = Elts.size();
2304 ID.Kind = ValID::t_PackedConstantStruct;
2309 return Error(ID.Loc, "constant vector must not be empty");
2311 if (!Elts[0]->getType()->isIntegerTy() &&
2312 !Elts[0]->getType()->isFloatingPointTy() &&
2313 !Elts[0]->getType()->isPointerTy())
2314 return Error(FirstEltLoc,
2315 "vector elements must have integer, pointer or floating point type");
2317 // Verify that all the vector elements have the same type.
2318 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2319 if (Elts[i]->getType() != Elts[0]->getType())
2320 return Error(FirstEltLoc,
2321 "vector element #" + Twine(i) +
2322 " is not of type '" + getTypeString(Elts[0]->getType()));
2324 ID.ConstantVal = ConstantVector::get(Elts);
2325 ID.Kind = ValID::t_Constant;
2328 case lltok::lsquare: { // Array Constant
2330 SmallVector<Constant*, 16> Elts;
2331 LocTy FirstEltLoc = Lex.getLoc();
2332 if (ParseGlobalValueVector(Elts) ||
2333 ParseToken(lltok::rsquare, "expected end of array constant"))
2336 // Handle empty element.
2338 // Use undef instead of an array because it's inconvenient to determine
2339 // the element type at this point, there being no elements to examine.
2340 ID.Kind = ValID::t_EmptyArray;
2344 if (!Elts[0]->getType()->isFirstClassType())
2345 return Error(FirstEltLoc, "invalid array element type: " +
2346 getTypeString(Elts[0]->getType()));
2348 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2350 // Verify all elements are correct type!
2351 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2352 if (Elts[i]->getType() != Elts[0]->getType())
2353 return Error(FirstEltLoc,
2354 "array element #" + Twine(i) +
2355 " is not of type '" + getTypeString(Elts[0]->getType()));
2358 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2359 ID.Kind = ValID::t_Constant;
2362 case lltok::kw_c: // c "foo"
2364 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2366 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2367 ID.Kind = ValID::t_Constant;
2370 case lltok::kw_asm: {
2371 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2373 bool HasSideEffect, AlignStack, AsmDialect;
2375 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2376 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2377 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2378 ParseStringConstant(ID.StrVal) ||
2379 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2380 ParseToken(lltok::StringConstant, "expected constraint string"))
2382 ID.StrVal2 = Lex.getStrVal();
2383 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2384 (unsigned(AsmDialect)<<2);
2385 ID.Kind = ValID::t_InlineAsm;
2389 case lltok::kw_blockaddress: {
2390 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2395 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2397 ParseToken(lltok::comma, "expected comma in block address expression")||
2398 ParseValID(Label) ||
2399 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2402 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2403 return Error(Fn.Loc, "expected function name in blockaddress");
2404 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2405 return Error(Label.Loc, "expected basic block name in blockaddress");
2407 // Make a global variable as a placeholder for this reference.
2408 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2409 false, GlobalValue::InternalLinkage,
2411 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2412 ID.ConstantVal = FwdRef;
2413 ID.Kind = ValID::t_Constant;
2417 case lltok::kw_trunc:
2418 case lltok::kw_zext:
2419 case lltok::kw_sext:
2420 case lltok::kw_fptrunc:
2421 case lltok::kw_fpext:
2422 case lltok::kw_bitcast:
2423 case lltok::kw_uitofp:
2424 case lltok::kw_sitofp:
2425 case lltok::kw_fptoui:
2426 case lltok::kw_fptosi:
2427 case lltok::kw_inttoptr:
2428 case lltok::kw_ptrtoint: {
2429 unsigned Opc = Lex.getUIntVal();
2433 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2434 ParseGlobalTypeAndValue(SrcVal) ||
2435 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2436 ParseType(DestTy) ||
2437 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2439 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2440 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2441 getTypeString(SrcVal->getType()) + "' to '" +
2442 getTypeString(DestTy) + "'");
2443 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2445 ID.Kind = ValID::t_Constant;
2448 case lltok::kw_extractvalue: {
2451 SmallVector<unsigned, 4> Indices;
2452 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2453 ParseGlobalTypeAndValue(Val) ||
2454 ParseIndexList(Indices) ||
2455 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2458 if (!Val->getType()->isAggregateType())
2459 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2460 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2461 return Error(ID.Loc, "invalid indices for extractvalue");
2462 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2463 ID.Kind = ValID::t_Constant;
2466 case lltok::kw_insertvalue: {
2468 Constant *Val0, *Val1;
2469 SmallVector<unsigned, 4> Indices;
2470 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2471 ParseGlobalTypeAndValue(Val0) ||
2472 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2473 ParseGlobalTypeAndValue(Val1) ||
2474 ParseIndexList(Indices) ||
2475 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2477 if (!Val0->getType()->isAggregateType())
2478 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2479 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2480 return Error(ID.Loc, "invalid indices for insertvalue");
2481 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2482 ID.Kind = ValID::t_Constant;
2485 case lltok::kw_icmp:
2486 case lltok::kw_fcmp: {
2487 unsigned PredVal, Opc = Lex.getUIntVal();
2488 Constant *Val0, *Val1;
2490 if (ParseCmpPredicate(PredVal, Opc) ||
2491 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2492 ParseGlobalTypeAndValue(Val0) ||
2493 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2494 ParseGlobalTypeAndValue(Val1) ||
2495 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2498 if (Val0->getType() != Val1->getType())
2499 return Error(ID.Loc, "compare operands must have the same type");
2501 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2503 if (Opc == Instruction::FCmp) {
2504 if (!Val0->getType()->isFPOrFPVectorTy())
2505 return Error(ID.Loc, "fcmp requires floating point operands");
2506 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2508 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2509 if (!Val0->getType()->isIntOrIntVectorTy() &&
2510 !Val0->getType()->getScalarType()->isPointerTy())
2511 return Error(ID.Loc, "icmp requires pointer or integer operands");
2512 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2514 ID.Kind = ValID::t_Constant;
2518 // Binary Operators.
2520 case lltok::kw_fadd:
2522 case lltok::kw_fsub:
2524 case lltok::kw_fmul:
2525 case lltok::kw_udiv:
2526 case lltok::kw_sdiv:
2527 case lltok::kw_fdiv:
2528 case lltok::kw_urem:
2529 case lltok::kw_srem:
2530 case lltok::kw_frem:
2532 case lltok::kw_lshr:
2533 case lltok::kw_ashr: {
2537 unsigned Opc = Lex.getUIntVal();
2538 Constant *Val0, *Val1;
2540 LocTy ModifierLoc = Lex.getLoc();
2541 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2542 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2543 if (EatIfPresent(lltok::kw_nuw))
2545 if (EatIfPresent(lltok::kw_nsw)) {
2547 if (EatIfPresent(lltok::kw_nuw))
2550 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2551 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2552 if (EatIfPresent(lltok::kw_exact))
2555 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2556 ParseGlobalTypeAndValue(Val0) ||
2557 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2558 ParseGlobalTypeAndValue(Val1) ||
2559 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2561 if (Val0->getType() != Val1->getType())
2562 return Error(ID.Loc, "operands of constexpr must have same type");
2563 if (!Val0->getType()->isIntOrIntVectorTy()) {
2565 return Error(ModifierLoc, "nuw only applies to integer operations");
2567 return Error(ModifierLoc, "nsw only applies to integer operations");
2569 // Check that the type is valid for the operator.
2571 case Instruction::Add:
2572 case Instruction::Sub:
2573 case Instruction::Mul:
2574 case Instruction::UDiv:
2575 case Instruction::SDiv:
2576 case Instruction::URem:
2577 case Instruction::SRem:
2578 case Instruction::Shl:
2579 case Instruction::AShr:
2580 case Instruction::LShr:
2581 if (!Val0->getType()->isIntOrIntVectorTy())
2582 return Error(ID.Loc, "constexpr requires integer operands");
2584 case Instruction::FAdd:
2585 case Instruction::FSub:
2586 case Instruction::FMul:
2587 case Instruction::FDiv:
2588 case Instruction::FRem:
2589 if (!Val0->getType()->isFPOrFPVectorTy())
2590 return Error(ID.Loc, "constexpr requires fp operands");
2592 default: llvm_unreachable("Unknown binary operator!");
2595 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2596 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2597 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2598 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2600 ID.Kind = ValID::t_Constant;
2604 // Logical Operations
2607 case lltok::kw_xor: {
2608 unsigned Opc = Lex.getUIntVal();
2609 Constant *Val0, *Val1;
2611 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2612 ParseGlobalTypeAndValue(Val0) ||
2613 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2614 ParseGlobalTypeAndValue(Val1) ||
2615 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2617 if (Val0->getType() != Val1->getType())
2618 return Error(ID.Loc, "operands of constexpr must have same type");
2619 if (!Val0->getType()->isIntOrIntVectorTy())
2620 return Error(ID.Loc,
2621 "constexpr requires integer or integer vector operands");
2622 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2623 ID.Kind = ValID::t_Constant;
2627 case lltok::kw_getelementptr:
2628 case lltok::kw_shufflevector:
2629 case lltok::kw_insertelement:
2630 case lltok::kw_extractelement:
2631 case lltok::kw_select: {
2632 unsigned Opc = Lex.getUIntVal();
2633 SmallVector<Constant*, 16> Elts;
2634 bool InBounds = false;
2636 if (Opc == Instruction::GetElementPtr)
2637 InBounds = EatIfPresent(lltok::kw_inbounds);
2638 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2639 ParseGlobalValueVector(Elts) ||
2640 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2643 if (Opc == Instruction::GetElementPtr) {
2644 if (Elts.size() == 0 ||
2645 !Elts[0]->getType()->getScalarType()->isPointerTy())
2646 return Error(ID.Loc, "getelementptr requires pointer operand");
2648 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2649 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2650 return Error(ID.Loc, "invalid indices for getelementptr");
2651 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2653 } else if (Opc == Instruction::Select) {
2654 if (Elts.size() != 3)
2655 return Error(ID.Loc, "expected three operands to select");
2656 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2658 return Error(ID.Loc, Reason);
2659 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2660 } else if (Opc == Instruction::ShuffleVector) {
2661 if (Elts.size() != 3)
2662 return Error(ID.Loc, "expected three operands to shufflevector");
2663 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2664 return Error(ID.Loc, "invalid operands to shufflevector");
2666 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2667 } else if (Opc == Instruction::ExtractElement) {
2668 if (Elts.size() != 2)
2669 return Error(ID.Loc, "expected two operands to extractelement");
2670 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2671 return Error(ID.Loc, "invalid extractelement operands");
2672 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2674 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2675 if (Elts.size() != 3)
2676 return Error(ID.Loc, "expected three operands to insertelement");
2677 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2678 return Error(ID.Loc, "invalid insertelement operands");
2680 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2683 ID.Kind = ValID::t_Constant;
2692 /// ParseGlobalValue - Parse a global value with the specified type.
2693 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2697 bool Parsed = ParseValID(ID) ||
2698 ConvertValIDToValue(Ty, ID, V, NULL);
2699 if (V && !(C = dyn_cast<Constant>(V)))
2700 return Error(ID.Loc, "global values must be constants");
2704 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2706 return ParseType(Ty) ||
2707 ParseGlobalValue(Ty, V);
2710 /// ParseGlobalValueVector
2712 /// ::= TypeAndValue (',' TypeAndValue)*
2713 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2715 if (Lex.getKind() == lltok::rbrace ||
2716 Lex.getKind() == lltok::rsquare ||
2717 Lex.getKind() == lltok::greater ||
2718 Lex.getKind() == lltok::rparen)
2722 if (ParseGlobalTypeAndValue(C)) return true;
2725 while (EatIfPresent(lltok::comma)) {
2726 if (ParseGlobalTypeAndValue(C)) return true;
2733 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2734 assert(Lex.getKind() == lltok::lbrace);
2737 SmallVector<Value*, 16> Elts;
2738 if (ParseMDNodeVector(Elts, PFS) ||
2739 ParseToken(lltok::rbrace, "expected end of metadata node"))
2742 ID.MDNodeVal = MDNode::get(Context, Elts);
2743 ID.Kind = ValID::t_MDNode;
2747 /// ParseMetadataValue
2751 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2752 assert(Lex.getKind() == lltok::exclaim);
2757 if (Lex.getKind() == lltok::lbrace)
2758 return ParseMetadataListValue(ID, PFS);
2760 // Standalone metadata reference
2762 if (Lex.getKind() == lltok::APSInt) {
2763 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2764 ID.Kind = ValID::t_MDNode;
2769 // ::= '!' STRINGCONSTANT
2770 if (ParseMDString(ID.MDStringVal)) return true;
2771 ID.Kind = ValID::t_MDString;
2776 //===----------------------------------------------------------------------===//
2777 // Function Parsing.
2778 //===----------------------------------------------------------------------===//
2780 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2781 PerFunctionState *PFS) {
2782 if (Ty->isFunctionTy())
2783 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2786 case ValID::t_LocalID:
2787 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2788 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2790 case ValID::t_LocalName:
2791 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2792 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2794 case ValID::t_InlineAsm: {
2795 PointerType *PTy = dyn_cast<PointerType>(Ty);
2797 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2798 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2799 return Error(ID.Loc, "invalid type for inline asm constraint string");
2800 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
2801 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
2804 case ValID::t_MDNode:
2805 if (!Ty->isMetadataTy())
2806 return Error(ID.Loc, "metadata value must have metadata type");
2809 case ValID::t_MDString:
2810 if (!Ty->isMetadataTy())
2811 return Error(ID.Loc, "metadata value must have metadata type");
2814 case ValID::t_GlobalName:
2815 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2817 case ValID::t_GlobalID:
2818 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2820 case ValID::t_APSInt:
2821 if (!Ty->isIntegerTy())
2822 return Error(ID.Loc, "integer constant must have integer type");
2823 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2824 V = ConstantInt::get(Context, ID.APSIntVal);
2826 case ValID::t_APFloat:
2827 if (!Ty->isFloatingPointTy() ||
2828 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2829 return Error(ID.Loc, "floating point constant invalid for type");
2831 // The lexer has no type info, so builds all half, float, and double FP
2832 // constants as double. Fix this here. Long double does not need this.
2833 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
2836 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2838 else if (Ty->isFloatTy())
2839 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2842 V = ConstantFP::get(Context, ID.APFloatVal);
2844 if (V->getType() != Ty)
2845 return Error(ID.Loc, "floating point constant does not have type '" +
2846 getTypeString(Ty) + "'");
2850 if (!Ty->isPointerTy())
2851 return Error(ID.Loc, "null must be a pointer type");
2852 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2854 case ValID::t_Undef:
2855 // FIXME: LabelTy should not be a first-class type.
2856 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2857 return Error(ID.Loc, "invalid type for undef constant");
2858 V = UndefValue::get(Ty);
2860 case ValID::t_EmptyArray:
2861 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2862 return Error(ID.Loc, "invalid empty array initializer");
2863 V = UndefValue::get(Ty);
2866 // FIXME: LabelTy should not be a first-class type.
2867 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2868 return Error(ID.Loc, "invalid type for null constant");
2869 V = Constant::getNullValue(Ty);
2871 case ValID::t_Constant:
2872 if (ID.ConstantVal->getType() != Ty)
2873 return Error(ID.Loc, "constant expression type mismatch");
2877 case ValID::t_ConstantStruct:
2878 case ValID::t_PackedConstantStruct:
2879 if (StructType *ST = dyn_cast<StructType>(Ty)) {
2880 if (ST->getNumElements() != ID.UIntVal)
2881 return Error(ID.Loc,
2882 "initializer with struct type has wrong # elements");
2883 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2884 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2886 // Verify that the elements are compatible with the structtype.
2887 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2888 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2889 return Error(ID.Loc, "element " + Twine(i) +
2890 " of struct initializer doesn't match struct element type");
2892 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2895 return Error(ID.Loc, "constant expression type mismatch");
2898 llvm_unreachable("Invalid ValID");
2901 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
2904 return ParseValID(ID, PFS) ||
2905 ConvertValIDToValue(Ty, ID, V, PFS);
2908 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2910 return ParseType(Ty) ||
2911 ParseValue(Ty, V, PFS);
2914 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2915 PerFunctionState &PFS) {
2918 if (ParseTypeAndValue(V, PFS)) return true;
2919 if (!isa<BasicBlock>(V))
2920 return Error(Loc, "expected a basic block");
2921 BB = cast<BasicBlock>(V);
2927 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2928 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2929 /// OptionalAlign OptGC OptionalPrefix
2930 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2931 // Parse the linkage.
2932 LocTy LinkageLoc = Lex.getLoc();
2935 unsigned Visibility;
2936 AttrBuilder RetAttrs;
2939 LocTy RetTypeLoc = Lex.getLoc();
2940 if (ParseOptionalLinkage(Linkage) ||
2941 ParseOptionalVisibility(Visibility) ||
2942 ParseOptionalCallingConv(CC) ||
2943 ParseOptionalReturnAttrs(RetAttrs) ||
2944 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2947 // Verify that the linkage is ok.
2948 switch ((GlobalValue::LinkageTypes)Linkage) {
2949 case GlobalValue::ExternalLinkage:
2950 break; // always ok.
2951 case GlobalValue::DLLImportLinkage:
2952 case GlobalValue::ExternalWeakLinkage:
2954 return Error(LinkageLoc, "invalid linkage for function definition");
2956 case GlobalValue::PrivateLinkage:
2957 case GlobalValue::LinkerPrivateLinkage:
2958 case GlobalValue::LinkerPrivateWeakLinkage:
2959 case GlobalValue::InternalLinkage:
2960 case GlobalValue::AvailableExternallyLinkage:
2961 case GlobalValue::LinkOnceAnyLinkage:
2962 case GlobalValue::LinkOnceODRLinkage:
2963 case GlobalValue::LinkOnceODRAutoHideLinkage:
2964 case GlobalValue::WeakAnyLinkage:
2965 case GlobalValue::WeakODRLinkage:
2966 case GlobalValue::DLLExportLinkage:
2968 return Error(LinkageLoc, "invalid linkage for function declaration");
2970 case GlobalValue::AppendingLinkage:
2971 case GlobalValue::CommonLinkage:
2972 return Error(LinkageLoc, "invalid function linkage type");
2975 if (!FunctionType::isValidReturnType(RetType))
2976 return Error(RetTypeLoc, "invalid function return type");
2978 LocTy NameLoc = Lex.getLoc();
2980 std::string FunctionName;
2981 if (Lex.getKind() == lltok::GlobalVar) {
2982 FunctionName = Lex.getStrVal();
2983 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2984 unsigned NameID = Lex.getUIntVal();
2986 if (NameID != NumberedVals.size())
2987 return TokError("function expected to be numbered '%" +
2988 Twine(NumberedVals.size()) + "'");
2990 return TokError("expected function name");
2995 if (Lex.getKind() != lltok::lparen)
2996 return TokError("expected '(' in function argument list");
2998 SmallVector<ArgInfo, 8> ArgList;
3000 AttrBuilder FuncAttrs;
3001 std::vector<unsigned> FwdRefAttrGrps;
3003 std::string Section;
3007 LocTy UnnamedAddrLoc;
3008 Constant *Prefix = 0;
3010 if (ParseArgumentList(ArgList, isVarArg) ||
3011 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3013 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
3015 (EatIfPresent(lltok::kw_section) &&
3016 ParseStringConstant(Section)) ||
3017 ParseOptionalAlignment(Alignment) ||
3018 (EatIfPresent(lltok::kw_gc) &&
3019 ParseStringConstant(GC)) ||
3020 (EatIfPresent(lltok::kw_prefix) &&
3021 ParseGlobalTypeAndValue(Prefix)))
3024 if (FuncAttrs.contains(Attribute::Builtin))
3025 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
3027 // If the alignment was parsed as an attribute, move to the alignment field.
3028 if (FuncAttrs.hasAlignmentAttr()) {
3029 Alignment = FuncAttrs.getAlignment();
3030 FuncAttrs.removeAttribute(Attribute::Alignment);
3033 // Okay, if we got here, the function is syntactically valid. Convert types
3034 // and do semantic checks.
3035 std::vector<Type*> ParamTypeList;
3036 SmallVector<AttributeSet, 8> Attrs;
3038 if (RetAttrs.hasAttributes())
3039 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3040 AttributeSet::ReturnIndex,
3043 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3044 ParamTypeList.push_back(ArgList[i].Ty);
3045 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3046 AttrBuilder B(ArgList[i].Attrs, i + 1);
3047 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3051 if (FuncAttrs.hasAttributes())
3052 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3053 AttributeSet::FunctionIndex,
3056 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3058 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
3059 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3062 FunctionType::get(RetType, ParamTypeList, isVarArg);
3063 PointerType *PFT = PointerType::getUnqual(FT);
3066 if (!FunctionName.empty()) {
3067 // If this was a definition of a forward reference, remove the definition
3068 // from the forward reference table and fill in the forward ref.
3069 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3070 ForwardRefVals.find(FunctionName);
3071 if (FRVI != ForwardRefVals.end()) {
3072 Fn = M->getFunction(FunctionName);
3074 return Error(FRVI->second.second, "invalid forward reference to "
3075 "function as global value!");
3076 if (Fn->getType() != PFT)
3077 return Error(FRVI->second.second, "invalid forward reference to "
3078 "function '" + FunctionName + "' with wrong type!");
3080 ForwardRefVals.erase(FRVI);
3081 } else if ((Fn = M->getFunction(FunctionName))) {
3082 // Reject redefinitions.
3083 return Error(NameLoc, "invalid redefinition of function '" +
3084 FunctionName + "'");
3085 } else if (M->getNamedValue(FunctionName)) {
3086 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
3090 // If this is a definition of a forward referenced function, make sure the
3092 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3093 = ForwardRefValIDs.find(NumberedVals.size());
3094 if (I != ForwardRefValIDs.end()) {
3095 Fn = cast<Function>(I->second.first);
3096 if (Fn->getType() != PFT)
3097 return Error(NameLoc, "type of definition and forward reference of '@" +
3098 Twine(NumberedVals.size()) + "' disagree");
3099 ForwardRefValIDs.erase(I);
3104 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3105 else // Move the forward-reference to the correct spot in the module.
3106 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3108 if (FunctionName.empty())
3109 NumberedVals.push_back(Fn);
3111 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3112 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3113 Fn->setCallingConv(CC);
3114 Fn->setAttributes(PAL);
3115 Fn->setUnnamedAddr(UnnamedAddr);
3116 Fn->setAlignment(Alignment);
3117 Fn->setSection(Section);
3118 if (!GC.empty()) Fn->setGC(GC.c_str());
3119 Fn->setPrefixData(Prefix);
3120 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
3122 // Add all of the arguments we parsed to the function.
3123 Function::arg_iterator ArgIt = Fn->arg_begin();
3124 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3125 // If the argument has a name, insert it into the argument symbol table.
3126 if (ArgList[i].Name.empty()) continue;
3128 // Set the name, if it conflicted, it will be auto-renamed.
3129 ArgIt->setName(ArgList[i].Name);
3131 if (ArgIt->getName() != ArgList[i].Name)
3132 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3133 ArgList[i].Name + "'");
3140 /// ParseFunctionBody
3141 /// ::= '{' BasicBlock+ '}'
3143 bool LLParser::ParseFunctionBody(Function &Fn) {
3144 if (Lex.getKind() != lltok::lbrace)
3145 return TokError("expected '{' in function body");
3146 Lex.Lex(); // eat the {.
3148 int FunctionNumber = -1;
3149 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
3151 PerFunctionState PFS(*this, Fn, FunctionNumber);
3153 // We need at least one basic block.
3154 if (Lex.getKind() == lltok::rbrace)
3155 return TokError("function body requires at least one basic block");
3157 while (Lex.getKind() != lltok::rbrace)
3158 if (ParseBasicBlock(PFS)) return true;
3163 // Verify function is ok.
3164 return PFS.FinishFunction();
3168 /// ::= LabelStr? Instruction*
3169 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3170 // If this basic block starts out with a name, remember it.
3172 LocTy NameLoc = Lex.getLoc();
3173 if (Lex.getKind() == lltok::LabelStr) {
3174 Name = Lex.getStrVal();
3178 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3179 if (BB == 0) return true;
3181 std::string NameStr;
3183 // Parse the instructions in this block until we get a terminator.
3186 // This instruction may have three possibilities for a name: a) none
3187 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3188 LocTy NameLoc = Lex.getLoc();
3192 if (Lex.getKind() == lltok::LocalVarID) {
3193 NameID = Lex.getUIntVal();
3195 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3197 } else if (Lex.getKind() == lltok::LocalVar) {
3198 NameStr = Lex.getStrVal();
3200 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3204 switch (ParseInstruction(Inst, BB, PFS)) {
3205 default: llvm_unreachable("Unknown ParseInstruction result!");
3206 case InstError: return true;
3208 BB->getInstList().push_back(Inst);
3210 // With a normal result, we check to see if the instruction is followed by
3211 // a comma and metadata.
3212 if (EatIfPresent(lltok::comma))
3213 if (ParseInstructionMetadata(Inst, &PFS))
3216 case InstExtraComma:
3217 BB->getInstList().push_back(Inst);
3219 // If the instruction parser ate an extra comma at the end of it, it
3220 // *must* be followed by metadata.
3221 if (ParseInstructionMetadata(Inst, &PFS))
3226 // Set the name on the instruction.
3227 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3228 } while (!isa<TerminatorInst>(Inst));
3233 //===----------------------------------------------------------------------===//
3234 // Instruction Parsing.
3235 //===----------------------------------------------------------------------===//
3237 /// ParseInstruction - Parse one of the many different instructions.
3239 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3240 PerFunctionState &PFS) {
3241 lltok::Kind Token = Lex.getKind();
3242 if (Token == lltok::Eof)
3243 return TokError("found end of file when expecting more instructions");
3244 LocTy Loc = Lex.getLoc();
3245 unsigned KeywordVal = Lex.getUIntVal();
3246 Lex.Lex(); // Eat the keyword.
3249 default: return Error(Loc, "expected instruction opcode");
3250 // Terminator Instructions.
3251 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3252 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3253 case lltok::kw_br: return ParseBr(Inst, PFS);
3254 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
3255 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
3256 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3257 case lltok::kw_resume: return ParseResume(Inst, PFS);
3258 // Binary Operators.
3262 case lltok::kw_shl: {
3263 bool NUW = EatIfPresent(lltok::kw_nuw);
3264 bool NSW = EatIfPresent(lltok::kw_nsw);
3265 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3267 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3269 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3270 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3273 case lltok::kw_fadd:
3274 case lltok::kw_fsub:
3275 case lltok::kw_fmul:
3276 case lltok::kw_fdiv:
3277 case lltok::kw_frem: {
3278 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3279 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3283 Inst->setFastMathFlags(FMF);
3287 case lltok::kw_sdiv:
3288 case lltok::kw_udiv:
3289 case lltok::kw_lshr:
3290 case lltok::kw_ashr: {
3291 bool Exact = EatIfPresent(lltok::kw_exact);
3293 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3294 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3298 case lltok::kw_urem:
3299 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3302 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3303 case lltok::kw_icmp:
3304 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3306 case lltok::kw_trunc:
3307 case lltok::kw_zext:
3308 case lltok::kw_sext:
3309 case lltok::kw_fptrunc:
3310 case lltok::kw_fpext:
3311 case lltok::kw_bitcast:
3312 case lltok::kw_uitofp:
3313 case lltok::kw_sitofp:
3314 case lltok::kw_fptoui:
3315 case lltok::kw_fptosi:
3316 case lltok::kw_inttoptr:
3317 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3319 case lltok::kw_select: return ParseSelect(Inst, PFS);
3320 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3321 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3322 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3323 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3324 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3325 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3326 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3327 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3329 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3330 case lltok::kw_load: return ParseLoad(Inst, PFS);
3331 case lltok::kw_store: return ParseStore(Inst, PFS);
3332 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3333 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3334 case lltok::kw_fence: return ParseFence(Inst, PFS);
3335 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3336 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3337 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3341 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3342 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3343 if (Opc == Instruction::FCmp) {
3344 switch (Lex.getKind()) {
3345 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
3346 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3347 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3348 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3349 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3350 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3351 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3352 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3353 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3354 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3355 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3356 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3357 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3358 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3359 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3360 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3361 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3364 switch (Lex.getKind()) {
3365 default: return TokError("expected icmp predicate (e.g. 'eq')");
3366 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3367 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3368 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3369 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3370 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3371 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3372 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3373 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3374 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3375 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3382 //===----------------------------------------------------------------------===//
3383 // Terminator Instructions.
3384 //===----------------------------------------------------------------------===//
3386 /// ParseRet - Parse a return instruction.
3387 /// ::= 'ret' void (',' !dbg, !1)*
3388 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3389 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3390 PerFunctionState &PFS) {
3391 SMLoc TypeLoc = Lex.getLoc();
3393 if (ParseType(Ty, true /*void allowed*/)) return true;
3395 Type *ResType = PFS.getFunction().getReturnType();
3397 if (Ty->isVoidTy()) {
3398 if (!ResType->isVoidTy())
3399 return Error(TypeLoc, "value doesn't match function result type '" +
3400 getTypeString(ResType) + "'");
3402 Inst = ReturnInst::Create(Context);
3407 if (ParseValue(Ty, RV, PFS)) return true;
3409 if (ResType != RV->getType())
3410 return Error(TypeLoc, "value doesn't match function result type '" +
3411 getTypeString(ResType) + "'");
3413 Inst = ReturnInst::Create(Context, RV);
3419 /// ::= 'br' TypeAndValue
3420 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3421 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3424 BasicBlock *Op1, *Op2;
3425 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3427 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3428 Inst = BranchInst::Create(BB);
3432 if (Op0->getType() != Type::getInt1Ty(Context))
3433 return Error(Loc, "branch condition must have 'i1' type");
3435 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3436 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3437 ParseToken(lltok::comma, "expected ',' after true destination") ||
3438 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3441 Inst = BranchInst::Create(Op1, Op2, Op0);
3447 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3449 /// ::= (TypeAndValue ',' TypeAndValue)*
3450 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3451 LocTy CondLoc, BBLoc;
3453 BasicBlock *DefaultBB;
3454 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3455 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3456 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3457 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3460 if (!Cond->getType()->isIntegerTy())
3461 return Error(CondLoc, "switch condition must have integer type");
3463 // Parse the jump table pairs.
3464 SmallPtrSet<Value*, 32> SeenCases;
3465 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3466 while (Lex.getKind() != lltok::rsquare) {
3470 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3471 ParseToken(lltok::comma, "expected ',' after case value") ||
3472 ParseTypeAndBasicBlock(DestBB, PFS))
3475 if (!SeenCases.insert(Constant))
3476 return Error(CondLoc, "duplicate case value in switch");
3477 if (!isa<ConstantInt>(Constant))
3478 return Error(CondLoc, "case value is not a constant integer");
3480 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3483 Lex.Lex(); // Eat the ']'.
3485 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3486 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3487 SI->addCase(Table[i].first, Table[i].second);
3494 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3495 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3498 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3499 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3500 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3503 if (!Address->getType()->isPointerTy())
3504 return Error(AddrLoc, "indirectbr address must have pointer type");
3506 // Parse the destination list.
3507 SmallVector<BasicBlock*, 16> DestList;
3509 if (Lex.getKind() != lltok::rsquare) {
3511 if (ParseTypeAndBasicBlock(DestBB, PFS))
3513 DestList.push_back(DestBB);
3515 while (EatIfPresent(lltok::comma)) {
3516 if (ParseTypeAndBasicBlock(DestBB, PFS))
3518 DestList.push_back(DestBB);
3522 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3525 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3526 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3527 IBI->addDestination(DestList[i]);
3534 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3535 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3536 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3537 LocTy CallLoc = Lex.getLoc();
3538 AttrBuilder RetAttrs, FnAttrs;
3539 std::vector<unsigned> FwdRefAttrGrps;
3545 SmallVector<ParamInfo, 16> ArgList;
3547 BasicBlock *NormalBB, *UnwindBB;
3548 if (ParseOptionalCallingConv(CC) ||
3549 ParseOptionalReturnAttrs(RetAttrs) ||
3550 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3551 ParseValID(CalleeID) ||
3552 ParseParameterList(ArgList, PFS) ||
3553 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3555 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3556 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3557 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3558 ParseTypeAndBasicBlock(UnwindBB, PFS))
3561 // If RetType is a non-function pointer type, then this is the short syntax
3562 // for the call, which means that RetType is just the return type. Infer the
3563 // rest of the function argument types from the arguments that are present.
3564 PointerType *PFTy = 0;
3565 FunctionType *Ty = 0;
3566 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3567 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3568 // Pull out the types of all of the arguments...
3569 std::vector<Type*> ParamTypes;
3570 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3571 ParamTypes.push_back(ArgList[i].V->getType());
3573 if (!FunctionType::isValidReturnType(RetType))
3574 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3576 Ty = FunctionType::get(RetType, ParamTypes, false);
3577 PFTy = PointerType::getUnqual(Ty);
3580 // Look up the callee.
3582 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3584 // Set up the Attribute for the function.
3585 SmallVector<AttributeSet, 8> Attrs;
3586 if (RetAttrs.hasAttributes())
3587 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3588 AttributeSet::ReturnIndex,
3591 SmallVector<Value*, 8> Args;
3593 // Loop through FunctionType's arguments and ensure they are specified
3594 // correctly. Also, gather any parameter attributes.
3595 FunctionType::param_iterator I = Ty->param_begin();
3596 FunctionType::param_iterator E = Ty->param_end();
3597 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3598 Type *ExpectedTy = 0;
3601 } else if (!Ty->isVarArg()) {
3602 return Error(ArgList[i].Loc, "too many arguments specified");
3605 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3606 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3607 getTypeString(ExpectedTy) + "'");
3608 Args.push_back(ArgList[i].V);
3609 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3610 AttrBuilder B(ArgList[i].Attrs, i + 1);
3611 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3616 return Error(CallLoc, "not enough parameters specified for call");
3618 if (FnAttrs.hasAttributes())
3619 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3620 AttributeSet::FunctionIndex,
3623 // Finish off the Attribute and check them
3624 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3626 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3627 II->setCallingConv(CC);
3628 II->setAttributes(PAL);
3629 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
3635 /// ::= 'resume' TypeAndValue
3636 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3637 Value *Exn; LocTy ExnLoc;
3638 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3641 ResumeInst *RI = ResumeInst::Create(Exn);
3646 //===----------------------------------------------------------------------===//
3647 // Binary Operators.
3648 //===----------------------------------------------------------------------===//
3651 /// ::= ArithmeticOps TypeAndValue ',' Value
3653 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3654 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3655 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3656 unsigned Opc, unsigned OperandType) {
3657 LocTy Loc; Value *LHS, *RHS;
3658 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3659 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3660 ParseValue(LHS->getType(), RHS, PFS))
3664 switch (OperandType) {
3665 default: llvm_unreachable("Unknown operand type!");
3666 case 0: // int or FP.
3667 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3668 LHS->getType()->isFPOrFPVectorTy();
3670 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3671 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3675 return Error(Loc, "invalid operand type for instruction");
3677 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3682 /// ::= ArithmeticOps TypeAndValue ',' Value {
3683 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3685 LocTy Loc; Value *LHS, *RHS;
3686 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3687 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3688 ParseValue(LHS->getType(), RHS, PFS))
3691 if (!LHS->getType()->isIntOrIntVectorTy())
3692 return Error(Loc,"instruction requires integer or integer vector operands");
3694 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3700 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3701 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3702 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3704 // Parse the integer/fp comparison predicate.
3708 if (ParseCmpPredicate(Pred, Opc) ||
3709 ParseTypeAndValue(LHS, Loc, PFS) ||
3710 ParseToken(lltok::comma, "expected ',' after compare value") ||
3711 ParseValue(LHS->getType(), RHS, PFS))
3714 if (Opc == Instruction::FCmp) {
3715 if (!LHS->getType()->isFPOrFPVectorTy())
3716 return Error(Loc, "fcmp requires floating point operands");
3717 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3719 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3720 if (!LHS->getType()->isIntOrIntVectorTy() &&
3721 !LHS->getType()->getScalarType()->isPointerTy())
3722 return Error(Loc, "icmp requires integer operands");
3723 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3728 //===----------------------------------------------------------------------===//
3729 // Other Instructions.
3730 //===----------------------------------------------------------------------===//
3734 /// ::= CastOpc TypeAndValue 'to' Type
3735 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3740 if (ParseTypeAndValue(Op, Loc, PFS) ||
3741 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3745 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3746 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3747 return Error(Loc, "invalid cast opcode for cast from '" +
3748 getTypeString(Op->getType()) + "' to '" +
3749 getTypeString(DestTy) + "'");
3751 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3756 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3757 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3759 Value *Op0, *Op1, *Op2;
3760 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3761 ParseToken(lltok::comma, "expected ',' after select condition") ||
3762 ParseTypeAndValue(Op1, PFS) ||
3763 ParseToken(lltok::comma, "expected ',' after select value") ||
3764 ParseTypeAndValue(Op2, PFS))
3767 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3768 return Error(Loc, Reason);
3770 Inst = SelectInst::Create(Op0, Op1, Op2);
3775 /// ::= 'va_arg' TypeAndValue ',' Type
3776 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3780 if (ParseTypeAndValue(Op, PFS) ||
3781 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3782 ParseType(EltTy, TypeLoc))
3785 if (!EltTy->isFirstClassType())
3786 return Error(TypeLoc, "va_arg requires operand with first class type");
3788 Inst = new VAArgInst(Op, EltTy);
3792 /// ParseExtractElement
3793 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3794 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3797 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3798 ParseToken(lltok::comma, "expected ',' after extract value") ||
3799 ParseTypeAndValue(Op1, PFS))
3802 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3803 return Error(Loc, "invalid extractelement operands");
3805 Inst = ExtractElementInst::Create(Op0, Op1);
3809 /// ParseInsertElement
3810 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3811 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3813 Value *Op0, *Op1, *Op2;
3814 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3815 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3816 ParseTypeAndValue(Op1, PFS) ||
3817 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3818 ParseTypeAndValue(Op2, PFS))
3821 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3822 return Error(Loc, "invalid insertelement operands");
3824 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3828 /// ParseShuffleVector
3829 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3830 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3832 Value *Op0, *Op1, *Op2;
3833 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3834 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3835 ParseTypeAndValue(Op1, PFS) ||
3836 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3837 ParseTypeAndValue(Op2, PFS))
3840 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3841 return Error(Loc, "invalid shufflevector operands");
3843 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3848 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3849 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3850 Type *Ty = 0; LocTy TypeLoc;
3853 if (ParseType(Ty, TypeLoc) ||
3854 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3855 ParseValue(Ty, Op0, PFS) ||
3856 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3857 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3858 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3861 bool AteExtraComma = false;
3862 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3864 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3866 if (!EatIfPresent(lltok::comma))
3869 if (Lex.getKind() == lltok::MetadataVar) {
3870 AteExtraComma = true;
3874 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3875 ParseValue(Ty, Op0, PFS) ||
3876 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3877 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3878 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3882 if (!Ty->isFirstClassType())
3883 return Error(TypeLoc, "phi node must have first class type");
3885 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3886 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3887 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3889 return AteExtraComma ? InstExtraComma : InstNormal;
3893 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3895 /// ::= 'catch' TypeAndValue
3897 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3898 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3899 Type *Ty = 0; LocTy TyLoc;
3900 Value *PersFn; LocTy PersFnLoc;
3902 if (ParseType(Ty, TyLoc) ||
3903 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3904 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3907 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3908 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3910 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3911 LandingPadInst::ClauseType CT;
3912 if (EatIfPresent(lltok::kw_catch))
3913 CT = LandingPadInst::Catch;
3914 else if (EatIfPresent(lltok::kw_filter))
3915 CT = LandingPadInst::Filter;
3917 return TokError("expected 'catch' or 'filter' clause type");
3919 Value *V; LocTy VLoc;
3920 if (ParseTypeAndValue(V, VLoc, PFS)) {
3925 // A 'catch' type expects a non-array constant. A filter clause expects an
3927 if (CT == LandingPadInst::Catch) {
3928 if (isa<ArrayType>(V->getType()))
3929 Error(VLoc, "'catch' clause has an invalid type");
3931 if (!isa<ArrayType>(V->getType()))
3932 Error(VLoc, "'filter' clause has an invalid type");
3943 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3944 /// ParameterList OptionalAttrs
3945 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3947 AttrBuilder RetAttrs, FnAttrs;
3948 std::vector<unsigned> FwdRefAttrGrps;
3954 SmallVector<ParamInfo, 16> ArgList;
3955 LocTy CallLoc = Lex.getLoc();
3957 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3958 ParseOptionalCallingConv(CC) ||
3959 ParseOptionalReturnAttrs(RetAttrs) ||
3960 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3961 ParseValID(CalleeID) ||
3962 ParseParameterList(ArgList, PFS) ||
3963 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3967 // If RetType is a non-function pointer type, then this is the short syntax
3968 // for the call, which means that RetType is just the return type. Infer the
3969 // rest of the function argument types from the arguments that are present.
3970 PointerType *PFTy = 0;
3971 FunctionType *Ty = 0;
3972 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3973 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3974 // Pull out the types of all of the arguments...
3975 std::vector<Type*> ParamTypes;
3976 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3977 ParamTypes.push_back(ArgList[i].V->getType());
3979 if (!FunctionType::isValidReturnType(RetType))
3980 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3982 Ty = FunctionType::get(RetType, ParamTypes, false);
3983 PFTy = PointerType::getUnqual(Ty);
3986 // Look up the callee.
3988 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3990 // Set up the Attribute for the function.
3991 SmallVector<AttributeSet, 8> Attrs;
3992 if (RetAttrs.hasAttributes())
3993 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3994 AttributeSet::ReturnIndex,
3997 SmallVector<Value*, 8> Args;
3999 // Loop through FunctionType's arguments and ensure they are specified
4000 // correctly. Also, gather any parameter attributes.
4001 FunctionType::param_iterator I = Ty->param_begin();
4002 FunctionType::param_iterator E = Ty->param_end();
4003 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4004 Type *ExpectedTy = 0;
4007 } else if (!Ty->isVarArg()) {
4008 return Error(ArgList[i].Loc, "too many arguments specified");
4011 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4012 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4013 getTypeString(ExpectedTy) + "'");
4014 Args.push_back(ArgList[i].V);
4015 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4016 AttrBuilder B(ArgList[i].Attrs, i + 1);
4017 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4022 return Error(CallLoc, "not enough parameters specified for call");
4024 if (FnAttrs.hasAttributes())
4025 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4026 AttributeSet::FunctionIndex,
4029 // Finish off the Attribute and check them
4030 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4032 CallInst *CI = CallInst::Create(Callee, Args);
4033 CI->setTailCall(isTail);
4034 CI->setCallingConv(CC);
4035 CI->setAttributes(PAL);
4036 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
4041 //===----------------------------------------------------------------------===//
4042 // Memory Instructions.
4043 //===----------------------------------------------------------------------===//
4046 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
4047 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
4050 unsigned Alignment = 0;
4052 if (ParseType(Ty)) return true;
4054 bool AteExtraComma = false;
4055 if (EatIfPresent(lltok::comma)) {
4056 if (Lex.getKind() == lltok::kw_align) {
4057 if (ParseOptionalAlignment(Alignment)) return true;
4058 } else if (Lex.getKind() == lltok::MetadataVar) {
4059 AteExtraComma = true;
4061 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4062 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4067 if (Size && !Size->getType()->isIntegerTy())
4068 return Error(SizeLoc, "element count must have integer type");
4070 Inst = new AllocaInst(Ty, Size, Alignment);
4071 return AteExtraComma ? InstExtraComma : InstNormal;
4075 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
4076 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
4077 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4078 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
4079 Value *Val; LocTy Loc;
4080 unsigned Alignment = 0;
4081 bool AteExtraComma = false;
4082 bool isAtomic = false;
4083 AtomicOrdering Ordering = NotAtomic;
4084 SynchronizationScope Scope = CrossThread;
4086 if (Lex.getKind() == lltok::kw_atomic) {
4091 bool isVolatile = false;
4092 if (Lex.getKind() == lltok::kw_volatile) {
4097 if (ParseTypeAndValue(Val, Loc, PFS) ||
4098 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4099 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4102 if (!Val->getType()->isPointerTy() ||
4103 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4104 return Error(Loc, "load operand must be a pointer to a first class type");
4105 if (isAtomic && !Alignment)
4106 return Error(Loc, "atomic load must have explicit non-zero alignment");
4107 if (Ordering == Release || Ordering == AcquireRelease)
4108 return Error(Loc, "atomic load cannot use Release ordering");
4110 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
4111 return AteExtraComma ? InstExtraComma : InstNormal;
4116 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4117 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
4118 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4119 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
4120 Value *Val, *Ptr; LocTy Loc, PtrLoc;
4121 unsigned Alignment = 0;
4122 bool AteExtraComma = false;
4123 bool isAtomic = false;
4124 AtomicOrdering Ordering = NotAtomic;
4125 SynchronizationScope Scope = CrossThread;
4127 if (Lex.getKind() == lltok::kw_atomic) {
4132 bool isVolatile = false;
4133 if (Lex.getKind() == lltok::kw_volatile) {
4138 if (ParseTypeAndValue(Val, Loc, PFS) ||
4139 ParseToken(lltok::comma, "expected ',' after store operand") ||
4140 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4141 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4142 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4145 if (!Ptr->getType()->isPointerTy())
4146 return Error(PtrLoc, "store operand must be a pointer");
4147 if (!Val->getType()->isFirstClassType())
4148 return Error(Loc, "store operand must be a first class value");
4149 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4150 return Error(Loc, "stored value and pointer type do not match");
4151 if (isAtomic && !Alignment)
4152 return Error(Loc, "atomic store must have explicit non-zero alignment");
4153 if (Ordering == Acquire || Ordering == AcquireRelease)
4154 return Error(Loc, "atomic store cannot use Acquire ordering");
4156 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
4157 return AteExtraComma ? InstExtraComma : InstNormal;
4161 /// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
4162 /// 'singlethread'? AtomicOrdering
4163 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
4164 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4165 bool AteExtraComma = false;
4166 AtomicOrdering Ordering = NotAtomic;
4167 SynchronizationScope Scope = CrossThread;
4168 bool isVolatile = false;
4170 if (EatIfPresent(lltok::kw_volatile))
4173 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4174 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4175 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4176 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4177 ParseTypeAndValue(New, NewLoc, PFS) ||
4178 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4181 if (Ordering == Unordered)
4182 return TokError("cmpxchg cannot be unordered");
4183 if (!Ptr->getType()->isPointerTy())
4184 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4185 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4186 return Error(CmpLoc, "compare value and pointer type do not match");
4187 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4188 return Error(NewLoc, "new value and pointer type do not match");
4189 if (!New->getType()->isIntegerTy())
4190 return Error(NewLoc, "cmpxchg operand must be an integer");
4191 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4192 if (Size < 8 || (Size & (Size - 1)))
4193 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4196 AtomicCmpXchgInst *CXI =
4197 new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, Scope);
4198 CXI->setVolatile(isVolatile);
4200 return AteExtraComma ? InstExtraComma : InstNormal;
4204 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4205 /// 'singlethread'? AtomicOrdering
4206 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
4207 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4208 bool AteExtraComma = false;
4209 AtomicOrdering Ordering = NotAtomic;
4210 SynchronizationScope Scope = CrossThread;
4211 bool isVolatile = false;
4212 AtomicRMWInst::BinOp Operation;
4214 if (EatIfPresent(lltok::kw_volatile))
4217 switch (Lex.getKind()) {
4218 default: return TokError("expected binary operation in atomicrmw");
4219 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4220 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4221 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4222 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4223 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4224 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4225 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4226 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4227 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4228 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4229 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4231 Lex.Lex(); // Eat the operation.
4233 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4234 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4235 ParseTypeAndValue(Val, ValLoc, PFS) ||
4236 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4239 if (Ordering == Unordered)
4240 return TokError("atomicrmw cannot be unordered");
4241 if (!Ptr->getType()->isPointerTy())
4242 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4243 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4244 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4245 if (!Val->getType()->isIntegerTy())
4246 return Error(ValLoc, "atomicrmw operand must be an integer");
4247 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4248 if (Size < 8 || (Size & (Size - 1)))
4249 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4252 AtomicRMWInst *RMWI =
4253 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4254 RMWI->setVolatile(isVolatile);
4256 return AteExtraComma ? InstExtraComma : InstNormal;
4260 /// ::= 'fence' 'singlethread'? AtomicOrdering
4261 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4262 AtomicOrdering Ordering = NotAtomic;
4263 SynchronizationScope Scope = CrossThread;
4264 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4267 if (Ordering == Unordered)
4268 return TokError("fence cannot be unordered");
4269 if (Ordering == Monotonic)
4270 return TokError("fence cannot be monotonic");
4272 Inst = new FenceInst(Context, Ordering, Scope);
4276 /// ParseGetElementPtr
4277 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4278 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4283 bool InBounds = EatIfPresent(lltok::kw_inbounds);
4285 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4287 Type *BaseType = Ptr->getType();
4288 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4289 if (!BasePointerType)
4290 return Error(Loc, "base of getelementptr must be a pointer");
4292 SmallVector<Value*, 16> Indices;
4293 bool AteExtraComma = false;
4294 while (EatIfPresent(lltok::comma)) {
4295 if (Lex.getKind() == lltok::MetadataVar) {
4296 AteExtraComma = true;
4299 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4300 if (!Val->getType()->getScalarType()->isIntegerTy())
4301 return Error(EltLoc, "getelementptr index must be an integer");
4302 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4303 return Error(EltLoc, "getelementptr index type missmatch");
4304 if (Val->getType()->isVectorTy()) {
4305 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4306 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4307 if (ValNumEl != PtrNumEl)
4308 return Error(EltLoc,
4309 "getelementptr vector index has a wrong number of elements");
4311 Indices.push_back(Val);
4314 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4315 return Error(Loc, "base element of getelementptr must be sized");
4317 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
4318 return Error(Loc, "invalid getelementptr indices");
4319 Inst = GetElementPtrInst::Create(Ptr, Indices);
4321 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4322 return AteExtraComma ? InstExtraComma : InstNormal;
4325 /// ParseExtractValue
4326 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
4327 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4328 Value *Val; LocTy Loc;
4329 SmallVector<unsigned, 4> Indices;
4331 if (ParseTypeAndValue(Val, Loc, PFS) ||
4332 ParseIndexList(Indices, AteExtraComma))
4335 if (!Val->getType()->isAggregateType())
4336 return Error(Loc, "extractvalue operand must be aggregate type");
4338 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4339 return Error(Loc, "invalid indices for extractvalue");
4340 Inst = ExtractValueInst::Create(Val, Indices);
4341 return AteExtraComma ? InstExtraComma : InstNormal;
4344 /// ParseInsertValue
4345 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4346 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4347 Value *Val0, *Val1; LocTy Loc0, Loc1;
4348 SmallVector<unsigned, 4> Indices;
4350 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4351 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4352 ParseTypeAndValue(Val1, Loc1, PFS) ||
4353 ParseIndexList(Indices, AteExtraComma))
4356 if (!Val0->getType()->isAggregateType())
4357 return Error(Loc0, "insertvalue operand must be aggregate type");
4359 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4360 return Error(Loc0, "invalid indices for insertvalue");
4361 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4362 return AteExtraComma ? InstExtraComma : InstNormal;
4365 //===----------------------------------------------------------------------===//
4366 // Embedded metadata.
4367 //===----------------------------------------------------------------------===//
4369 /// ParseMDNodeVector
4370 /// ::= Element (',' Element)*
4372 /// ::= 'null' | TypeAndValue
4373 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4374 PerFunctionState *PFS) {
4375 // Check for an empty list.
4376 if (Lex.getKind() == lltok::rbrace)
4380 // Null is a special case since it is typeless.
4381 if (EatIfPresent(lltok::kw_null)) {
4387 if (ParseTypeAndValue(V, PFS)) return true;
4389 } while (EatIfPresent(lltok::comma));