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
185 UpgradeDebugInfo(*M);
190 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
191 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
192 PerFunctionState *PFS) {
193 // Loop over all the references, resolving them.
194 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
197 if (Refs[i].first.Kind == ValID::t_LocalName)
198 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
200 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
201 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
202 return Error(Refs[i].first.Loc,
203 "cannot take address of numeric label after the function is defined");
205 Res = dyn_cast_or_null<BasicBlock>(
206 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
210 return Error(Refs[i].first.Loc,
211 "referenced value is not a basic block");
213 // Get the BlockAddress for this and update references to use it.
214 BlockAddress *BA = BlockAddress::get(TheFn, Res);
215 Refs[i].second->replaceAllUsesWith(BA);
216 Refs[i].second->eraseFromParent();
222 //===----------------------------------------------------------------------===//
223 // Top-Level Entities
224 //===----------------------------------------------------------------------===//
226 bool LLParser::ParseTopLevelEntities() {
228 switch (Lex.getKind()) {
229 default: return TokError("expected top-level entity");
230 case lltok::Eof: return false;
231 case lltok::kw_declare: if (ParseDeclare()) return true; break;
232 case lltok::kw_define: if (ParseDefine()) return true; break;
233 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
234 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
235 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
236 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
237 case lltok::LocalVar: if (ParseNamedType()) return true; break;
238 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
239 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
240 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
241 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
243 // The Global variable production with no name can have many different
244 // optional leading prefixes, the production is:
245 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
246 // OptionalAddrSpace OptionalUnNammedAddr
247 // ('constant'|'global') ...
248 case lltok::kw_private: // OptionalLinkage
249 case lltok::kw_linker_private: // OptionalLinkage
250 case lltok::kw_linker_private_weak: // OptionalLinkage
251 case lltok::kw_internal: // OptionalLinkage
252 case lltok::kw_weak: // OptionalLinkage
253 case lltok::kw_weak_odr: // OptionalLinkage
254 case lltok::kw_linkonce: // OptionalLinkage
255 case lltok::kw_linkonce_odr: // 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 /// ::= 'available_externally'
1280 /// ::= 'extern_weak'
1282 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1284 switch (Lex.getKind()) {
1285 default: Res=GlobalValue::ExternalLinkage; return false;
1286 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1287 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
1288 case lltok::kw_linker_private_weak:
1289 Res = GlobalValue::LinkerPrivateWeakLinkage;
1291 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1292 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1293 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1294 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1295 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1296 case lltok::kw_available_externally:
1297 Res = GlobalValue::AvailableExternallyLinkage;
1299 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1300 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1301 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1302 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1303 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1304 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1311 /// ParseOptionalVisibility
1317 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1318 switch (Lex.getKind()) {
1319 default: Res = GlobalValue::DefaultVisibility; return false;
1320 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1321 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1322 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1328 /// ParseOptionalCallingConv
1332 /// ::= 'kw_intel_ocl_bicc'
1334 /// ::= 'x86_stdcallcc'
1335 /// ::= 'x86_fastcallcc'
1336 /// ::= 'x86_thiscallcc'
1337 /// ::= 'arm_apcscc'
1338 /// ::= 'arm_aapcscc'
1339 /// ::= 'arm_aapcs_vfpcc'
1340 /// ::= 'msp430_intrcc'
1341 /// ::= 'ptx_kernel'
1342 /// ::= 'ptx_device'
1344 /// ::= 'spir_kernel'
1345 /// ::= 'x86_64_sysvcc'
1346 /// ::= 'x86_64_win64cc'
1347 /// ::= 'webkit_jscc'
1351 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1352 switch (Lex.getKind()) {
1353 default: CC = CallingConv::C; return false;
1354 case lltok::kw_ccc: CC = CallingConv::C; break;
1355 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1356 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1357 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1358 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1359 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1360 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1361 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1362 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1363 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1364 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1365 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1366 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1367 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1368 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1369 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1370 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1371 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1372 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1373 case lltok::kw_cc: {
1374 unsigned ArbitraryCC;
1376 if (ParseUInt32(ArbitraryCC))
1378 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1387 /// ParseInstructionMetadata
1388 /// ::= !dbg !42 (',' !dbg !57)*
1389 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1390 PerFunctionState *PFS) {
1392 if (Lex.getKind() != lltok::MetadataVar)
1393 return TokError("expected metadata after comma");
1395 std::string Name = Lex.getStrVal();
1396 unsigned MDK = M->getMDKindID(Name);
1400 SMLoc Loc = Lex.getLoc();
1402 if (ParseToken(lltok::exclaim, "expected '!' here"))
1405 // This code is similar to that of ParseMetadataValue, however it needs to
1406 // have special-case code for a forward reference; see the comments on
1407 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1408 // at the top level here.
1409 if (Lex.getKind() == lltok::lbrace) {
1411 if (ParseMetadataListValue(ID, PFS))
1413 assert(ID.Kind == ValID::t_MDNode);
1414 Inst->setMetadata(MDK, ID.MDNodeVal);
1416 unsigned NodeID = 0;
1417 if (ParseMDNodeID(Node, NodeID))
1420 // If we got the node, add it to the instruction.
1421 Inst->setMetadata(MDK, Node);
1423 MDRef R = { Loc, MDK, NodeID };
1424 // Otherwise, remember that this should be resolved later.
1425 ForwardRefInstMetadata[Inst].push_back(R);
1429 if (MDK == LLVMContext::MD_tbaa)
1430 InstsWithTBAATag.push_back(Inst);
1432 // If this is the end of the list, we're done.
1433 } while (EatIfPresent(lltok::comma));
1437 /// ParseOptionalAlignment
1440 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1442 if (!EatIfPresent(lltok::kw_align))
1444 LocTy AlignLoc = Lex.getLoc();
1445 if (ParseUInt32(Alignment)) return true;
1446 if (!isPowerOf2_32(Alignment))
1447 return Error(AlignLoc, "alignment is not a power of two");
1448 if (Alignment > Value::MaximumAlignment)
1449 return Error(AlignLoc, "huge alignments are not supported yet");
1453 /// ParseOptionalCommaAlign
1457 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1459 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1460 bool &AteExtraComma) {
1461 AteExtraComma = false;
1462 while (EatIfPresent(lltok::comma)) {
1463 // Metadata at the end is an early exit.
1464 if (Lex.getKind() == lltok::MetadataVar) {
1465 AteExtraComma = true;
1469 if (Lex.getKind() != lltok::kw_align)
1470 return Error(Lex.getLoc(), "expected metadata or 'align'");
1472 if (ParseOptionalAlignment(Alignment)) return true;
1478 /// ParseScopeAndOrdering
1479 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1482 /// This sets Scope and Ordering to the parsed values.
1483 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1484 AtomicOrdering &Ordering) {
1488 Scope = CrossThread;
1489 if (EatIfPresent(lltok::kw_singlethread))
1490 Scope = SingleThread;
1491 switch (Lex.getKind()) {
1492 default: return TokError("Expected ordering on atomic instruction");
1493 case lltok::kw_unordered: Ordering = Unordered; break;
1494 case lltok::kw_monotonic: Ordering = Monotonic; break;
1495 case lltok::kw_acquire: Ordering = Acquire; break;
1496 case lltok::kw_release: Ordering = Release; break;
1497 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1498 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1504 /// ParseOptionalStackAlignment
1506 /// ::= 'alignstack' '(' 4 ')'
1507 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1509 if (!EatIfPresent(lltok::kw_alignstack))
1511 LocTy ParenLoc = Lex.getLoc();
1512 if (!EatIfPresent(lltok::lparen))
1513 return Error(ParenLoc, "expected '('");
1514 LocTy AlignLoc = Lex.getLoc();
1515 if (ParseUInt32(Alignment)) return true;
1516 ParenLoc = Lex.getLoc();
1517 if (!EatIfPresent(lltok::rparen))
1518 return Error(ParenLoc, "expected ')'");
1519 if (!isPowerOf2_32(Alignment))
1520 return Error(AlignLoc, "stack alignment is not a power of two");
1524 /// ParseIndexList - This parses the index list for an insert/extractvalue
1525 /// instruction. This sets AteExtraComma in the case where we eat an extra
1526 /// comma at the end of the line and find that it is followed by metadata.
1527 /// Clients that don't allow metadata can call the version of this function that
1528 /// only takes one argument.
1531 /// ::= (',' uint32)+
1533 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1534 bool &AteExtraComma) {
1535 AteExtraComma = false;
1537 if (Lex.getKind() != lltok::comma)
1538 return TokError("expected ',' as start of index list");
1540 while (EatIfPresent(lltok::comma)) {
1541 if (Lex.getKind() == lltok::MetadataVar) {
1542 AteExtraComma = true;
1546 if (ParseUInt32(Idx)) return true;
1547 Indices.push_back(Idx);
1553 //===----------------------------------------------------------------------===//
1555 //===----------------------------------------------------------------------===//
1557 /// ParseType - Parse a type.
1558 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1559 SMLoc TypeLoc = Lex.getLoc();
1560 switch (Lex.getKind()) {
1562 return TokError("expected type");
1564 // Type ::= 'float' | 'void' (etc)
1565 Result = Lex.getTyVal();
1569 // Type ::= StructType
1570 if (ParseAnonStructType(Result, false))
1573 case lltok::lsquare:
1574 // Type ::= '[' ... ']'
1575 Lex.Lex(); // eat the lsquare.
1576 if (ParseArrayVectorType(Result, false))
1579 case lltok::less: // Either vector or packed struct.
1580 // Type ::= '<' ... '>'
1582 if (Lex.getKind() == lltok::lbrace) {
1583 if (ParseAnonStructType(Result, true) ||
1584 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1586 } else if (ParseArrayVectorType(Result, true))
1589 case lltok::LocalVar: {
1591 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1593 // If the type hasn't been defined yet, create a forward definition and
1594 // remember where that forward def'n was seen (in case it never is defined).
1595 if (Entry.first == 0) {
1596 Entry.first = StructType::create(Context, Lex.getStrVal());
1597 Entry.second = Lex.getLoc();
1599 Result = Entry.first;
1604 case lltok::LocalVarID: {
1606 if (Lex.getUIntVal() >= NumberedTypes.size())
1607 NumberedTypes.resize(Lex.getUIntVal()+1);
1608 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1610 // If the type hasn't been defined yet, create a forward definition and
1611 // remember where that forward def'n was seen (in case it never is defined).
1612 if (Entry.first == 0) {
1613 Entry.first = StructType::create(Context);
1614 Entry.second = Lex.getLoc();
1616 Result = Entry.first;
1622 // Parse the type suffixes.
1624 switch (Lex.getKind()) {
1627 if (!AllowVoid && Result->isVoidTy())
1628 return Error(TypeLoc, "void type only allowed for function results");
1631 // Type ::= Type '*'
1633 if (Result->isLabelTy())
1634 return TokError("basic block pointers are invalid");
1635 if (Result->isVoidTy())
1636 return TokError("pointers to void are invalid - use i8* instead");
1637 if (!PointerType::isValidElementType(Result))
1638 return TokError("pointer to this type is invalid");
1639 Result = PointerType::getUnqual(Result);
1643 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1644 case lltok::kw_addrspace: {
1645 if (Result->isLabelTy())
1646 return TokError("basic block pointers are invalid");
1647 if (Result->isVoidTy())
1648 return TokError("pointers to void are invalid; use i8* instead");
1649 if (!PointerType::isValidElementType(Result))
1650 return TokError("pointer to this type is invalid");
1652 if (ParseOptionalAddrSpace(AddrSpace) ||
1653 ParseToken(lltok::star, "expected '*' in address space"))
1656 Result = PointerType::get(Result, AddrSpace);
1660 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1662 if (ParseFunctionType(Result))
1669 /// ParseParameterList
1671 /// ::= '(' Arg (',' Arg)* ')'
1673 /// ::= Type OptionalAttributes Value OptionalAttributes
1674 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1675 PerFunctionState &PFS) {
1676 if (ParseToken(lltok::lparen, "expected '(' in call"))
1679 unsigned AttrIndex = 1;
1680 while (Lex.getKind() != lltok::rparen) {
1681 // If this isn't the first argument, we need a comma.
1682 if (!ArgList.empty() &&
1683 ParseToken(lltok::comma, "expected ',' in argument list"))
1686 // Parse the argument.
1689 AttrBuilder ArgAttrs;
1691 if (ParseType(ArgTy, ArgLoc))
1694 // Otherwise, handle normal operands.
1695 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1697 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1702 Lex.Lex(); // Lex the ')'.
1708 /// ParseArgumentList - Parse the argument list for a function type or function
1710 /// ::= '(' ArgTypeListI ')'
1714 /// ::= ArgTypeList ',' '...'
1715 /// ::= ArgType (',' ArgType)*
1717 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1720 assert(Lex.getKind() == lltok::lparen);
1721 Lex.Lex(); // eat the (.
1723 if (Lex.getKind() == lltok::rparen) {
1725 } else if (Lex.getKind() == lltok::dotdotdot) {
1729 LocTy TypeLoc = Lex.getLoc();
1734 if (ParseType(ArgTy) ||
1735 ParseOptionalParamAttrs(Attrs)) return true;
1737 if (ArgTy->isVoidTy())
1738 return Error(TypeLoc, "argument can not have void type");
1740 if (Lex.getKind() == lltok::LocalVar) {
1741 Name = Lex.getStrVal();
1745 if (!FunctionType::isValidArgumentType(ArgTy))
1746 return Error(TypeLoc, "invalid type for function argument");
1748 unsigned AttrIndex = 1;
1749 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1750 AttributeSet::get(ArgTy->getContext(),
1751 AttrIndex++, Attrs), Name));
1753 while (EatIfPresent(lltok::comma)) {
1754 // Handle ... at end of arg list.
1755 if (EatIfPresent(lltok::dotdotdot)) {
1760 // Otherwise must be an argument type.
1761 TypeLoc = Lex.getLoc();
1762 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1764 if (ArgTy->isVoidTy())
1765 return Error(TypeLoc, "argument can not have void type");
1767 if (Lex.getKind() == lltok::LocalVar) {
1768 Name = Lex.getStrVal();
1774 if (!ArgTy->isFirstClassType())
1775 return Error(TypeLoc, "invalid type for function argument");
1777 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1778 AttributeSet::get(ArgTy->getContext(),
1779 AttrIndex++, Attrs),
1784 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1787 /// ParseFunctionType
1788 /// ::= Type ArgumentList OptionalAttrs
1789 bool LLParser::ParseFunctionType(Type *&Result) {
1790 assert(Lex.getKind() == lltok::lparen);
1792 if (!FunctionType::isValidReturnType(Result))
1793 return TokError("invalid function return type");
1795 SmallVector<ArgInfo, 8> ArgList;
1797 if (ParseArgumentList(ArgList, isVarArg))
1800 // Reject names on the arguments lists.
1801 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1802 if (!ArgList[i].Name.empty())
1803 return Error(ArgList[i].Loc, "argument name invalid in function type");
1804 if (ArgList[i].Attrs.hasAttributes(i + 1))
1805 return Error(ArgList[i].Loc,
1806 "argument attributes invalid in function type");
1809 SmallVector<Type*, 16> ArgListTy;
1810 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1811 ArgListTy.push_back(ArgList[i].Ty);
1813 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1817 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1819 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1820 SmallVector<Type*, 8> Elts;
1821 if (ParseStructBody(Elts)) return true;
1823 Result = StructType::get(Context, Elts, Packed);
1827 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1828 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1829 std::pair<Type*, LocTy> &Entry,
1831 // If the type was already defined, diagnose the redefinition.
1832 if (Entry.first && !Entry.second.isValid())
1833 return Error(TypeLoc, "redefinition of type");
1835 // If we have opaque, just return without filling in the definition for the
1836 // struct. This counts as a definition as far as the .ll file goes.
1837 if (EatIfPresent(lltok::kw_opaque)) {
1838 // This type is being defined, so clear the location to indicate this.
1839 Entry.second = SMLoc();
1841 // If this type number has never been uttered, create it.
1842 if (Entry.first == 0)
1843 Entry.first = StructType::create(Context, Name);
1844 ResultTy = Entry.first;
1848 // If the type starts with '<', then it is either a packed struct or a vector.
1849 bool isPacked = EatIfPresent(lltok::less);
1851 // If we don't have a struct, then we have a random type alias, which we
1852 // accept for compatibility with old files. These types are not allowed to be
1853 // forward referenced and not allowed to be recursive.
1854 if (Lex.getKind() != lltok::lbrace) {
1856 return Error(TypeLoc, "forward references to non-struct type");
1860 return ParseArrayVectorType(ResultTy, true);
1861 return ParseType(ResultTy);
1864 // This type is being defined, so clear the location to indicate this.
1865 Entry.second = SMLoc();
1867 // If this type number has never been uttered, create it.
1868 if (Entry.first == 0)
1869 Entry.first = StructType::create(Context, Name);
1871 StructType *STy = cast<StructType>(Entry.first);
1873 SmallVector<Type*, 8> Body;
1874 if (ParseStructBody(Body) ||
1875 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1878 STy->setBody(Body, isPacked);
1884 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1887 /// ::= '{' Type (',' Type)* '}'
1888 /// ::= '<' '{' '}' '>'
1889 /// ::= '<' '{' Type (',' Type)* '}' '>'
1890 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
1891 assert(Lex.getKind() == lltok::lbrace);
1892 Lex.Lex(); // Consume the '{'
1894 // Handle the empty struct.
1895 if (EatIfPresent(lltok::rbrace))
1898 LocTy EltTyLoc = Lex.getLoc();
1900 if (ParseType(Ty)) return true;
1903 if (!StructType::isValidElementType(Ty))
1904 return Error(EltTyLoc, "invalid element type for struct");
1906 while (EatIfPresent(lltok::comma)) {
1907 EltTyLoc = Lex.getLoc();
1908 if (ParseType(Ty)) return true;
1910 if (!StructType::isValidElementType(Ty))
1911 return Error(EltTyLoc, "invalid element type for struct");
1916 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
1919 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1920 /// token has already been consumed.
1922 /// ::= '[' APSINTVAL 'x' Types ']'
1923 /// ::= '<' APSINTVAL 'x' Types '>'
1924 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
1925 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1926 Lex.getAPSIntVal().getBitWidth() > 64)
1927 return TokError("expected number in address space");
1929 LocTy SizeLoc = Lex.getLoc();
1930 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1933 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1936 LocTy TypeLoc = Lex.getLoc();
1938 if (ParseType(EltTy)) return true;
1940 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1941 "expected end of sequential type"))
1946 return Error(SizeLoc, "zero element vector is illegal");
1947 if ((unsigned)Size != Size)
1948 return Error(SizeLoc, "size too large for vector");
1949 if (!VectorType::isValidElementType(EltTy))
1950 return Error(TypeLoc, "invalid vector element type");
1951 Result = VectorType::get(EltTy, unsigned(Size));
1953 if (!ArrayType::isValidElementType(EltTy))
1954 return Error(TypeLoc, "invalid array element type");
1955 Result = ArrayType::get(EltTy, Size);
1960 //===----------------------------------------------------------------------===//
1961 // Function Semantic Analysis.
1962 //===----------------------------------------------------------------------===//
1964 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1966 : P(p), F(f), FunctionNumber(functionNumber) {
1968 // Insert unnamed arguments into the NumberedVals list.
1969 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1972 NumberedVals.push_back(AI);
1975 LLParser::PerFunctionState::~PerFunctionState() {
1976 // If there were any forward referenced non-basicblock values, delete them.
1977 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1978 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1979 if (!isa<BasicBlock>(I->second.first)) {
1980 I->second.first->replaceAllUsesWith(
1981 UndefValue::get(I->second.first->getType()));
1982 delete I->second.first;
1983 I->second.first = 0;
1986 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1987 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1988 if (!isa<BasicBlock>(I->second.first)) {
1989 I->second.first->replaceAllUsesWith(
1990 UndefValue::get(I->second.first->getType()));
1991 delete I->second.first;
1992 I->second.first = 0;
1996 bool LLParser::PerFunctionState::FinishFunction() {
1997 // Check to see if someone took the address of labels in this block.
1998 if (!P.ForwardRefBlockAddresses.empty()) {
2000 if (!F.getName().empty()) {
2001 FunctionID.Kind = ValID::t_GlobalName;
2002 FunctionID.StrVal = F.getName();
2004 FunctionID.Kind = ValID::t_GlobalID;
2005 FunctionID.UIntVal = FunctionNumber;
2008 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
2009 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
2010 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
2011 // Resolve all these references.
2012 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
2015 P.ForwardRefBlockAddresses.erase(FRBAI);
2019 if (!ForwardRefVals.empty())
2020 return P.Error(ForwardRefVals.begin()->second.second,
2021 "use of undefined value '%" + ForwardRefVals.begin()->first +
2023 if (!ForwardRefValIDs.empty())
2024 return P.Error(ForwardRefValIDs.begin()->second.second,
2025 "use of undefined value '%" +
2026 Twine(ForwardRefValIDs.begin()->first) + "'");
2031 /// GetVal - Get a value with the specified name or ID, creating a
2032 /// forward reference record if needed. This can return null if the value
2033 /// exists but does not have the right type.
2034 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2035 Type *Ty, LocTy Loc) {
2036 // Look this name up in the normal function symbol table.
2037 Value *Val = F.getValueSymbolTable().lookup(Name);
2039 // If this is a forward reference for the value, see if we already created a
2040 // forward ref record.
2042 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2043 I = ForwardRefVals.find(Name);
2044 if (I != ForwardRefVals.end())
2045 Val = I->second.first;
2048 // If we have the value in the symbol table or fwd-ref table, return it.
2050 if (Val->getType() == Ty) return Val;
2051 if (Ty->isLabelTy())
2052 P.Error(Loc, "'%" + Name + "' is not a basic block");
2054 P.Error(Loc, "'%" + Name + "' defined with type '" +
2055 getTypeString(Val->getType()) + "'");
2059 // Don't make placeholders with invalid type.
2060 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2061 P.Error(Loc, "invalid use of a non-first-class type");
2065 // Otherwise, create a new forward reference for this value and remember it.
2067 if (Ty->isLabelTy())
2068 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2070 FwdVal = new Argument(Ty, Name);
2072 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2076 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2078 // Look this name up in the normal function symbol table.
2079 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
2081 // If this is a forward reference for the value, see if we already created a
2082 // forward ref record.
2084 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2085 I = ForwardRefValIDs.find(ID);
2086 if (I != ForwardRefValIDs.end())
2087 Val = I->second.first;
2090 // If we have the value in the symbol table or fwd-ref table, return it.
2092 if (Val->getType() == Ty) return Val;
2093 if (Ty->isLabelTy())
2094 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2096 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2097 getTypeString(Val->getType()) + "'");
2101 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2102 P.Error(Loc, "invalid use of a non-first-class type");
2106 // Otherwise, create a new forward reference for this value and remember it.
2108 if (Ty->isLabelTy())
2109 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2111 FwdVal = new Argument(Ty);
2113 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2117 /// SetInstName - After an instruction is parsed and inserted into its
2118 /// basic block, this installs its name.
2119 bool LLParser::PerFunctionState::SetInstName(int NameID,
2120 const std::string &NameStr,
2121 LocTy NameLoc, Instruction *Inst) {
2122 // If this instruction has void type, it cannot have a name or ID specified.
2123 if (Inst->getType()->isVoidTy()) {
2124 if (NameID != -1 || !NameStr.empty())
2125 return P.Error(NameLoc, "instructions returning void cannot have a name");
2129 // If this was a numbered instruction, verify that the instruction is the
2130 // expected value and resolve any forward references.
2131 if (NameStr.empty()) {
2132 // If neither a name nor an ID was specified, just use the next ID.
2134 NameID = NumberedVals.size();
2136 if (unsigned(NameID) != NumberedVals.size())
2137 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2138 Twine(NumberedVals.size()) + "'");
2140 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2141 ForwardRefValIDs.find(NameID);
2142 if (FI != ForwardRefValIDs.end()) {
2143 if (FI->second.first->getType() != Inst->getType())
2144 return P.Error(NameLoc, "instruction forward referenced with type '" +
2145 getTypeString(FI->second.first->getType()) + "'");
2146 FI->second.first->replaceAllUsesWith(Inst);
2147 delete FI->second.first;
2148 ForwardRefValIDs.erase(FI);
2151 NumberedVals.push_back(Inst);
2155 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2156 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2157 FI = ForwardRefVals.find(NameStr);
2158 if (FI != ForwardRefVals.end()) {
2159 if (FI->second.first->getType() != Inst->getType())
2160 return P.Error(NameLoc, "instruction forward referenced with type '" +
2161 getTypeString(FI->second.first->getType()) + "'");
2162 FI->second.first->replaceAllUsesWith(Inst);
2163 delete FI->second.first;
2164 ForwardRefVals.erase(FI);
2167 // Set the name on the instruction.
2168 Inst->setName(NameStr);
2170 if (Inst->getName() != NameStr)
2171 return P.Error(NameLoc, "multiple definition of local value named '" +
2176 /// GetBB - Get a basic block with the specified name or ID, creating a
2177 /// forward reference record if needed.
2178 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2180 return cast_or_null<BasicBlock>(GetVal(Name,
2181 Type::getLabelTy(F.getContext()), Loc));
2184 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2185 return cast_or_null<BasicBlock>(GetVal(ID,
2186 Type::getLabelTy(F.getContext()), Loc));
2189 /// DefineBB - Define the specified basic block, which is either named or
2190 /// unnamed. If there is an error, this returns null otherwise it returns
2191 /// the block being defined.
2192 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2196 BB = GetBB(NumberedVals.size(), Loc);
2198 BB = GetBB(Name, Loc);
2199 if (BB == 0) return 0; // Already diagnosed error.
2201 // Move the block to the end of the function. Forward ref'd blocks are
2202 // inserted wherever they happen to be referenced.
2203 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2205 // Remove the block from forward ref sets.
2207 ForwardRefValIDs.erase(NumberedVals.size());
2208 NumberedVals.push_back(BB);
2210 // BB forward references are already in the function symbol table.
2211 ForwardRefVals.erase(Name);
2217 //===----------------------------------------------------------------------===//
2219 //===----------------------------------------------------------------------===//
2221 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2222 /// type implied. For example, if we parse "4" we don't know what integer type
2223 /// it has. The value will later be combined with its type and checked for
2224 /// sanity. PFS is used to convert function-local operands of metadata (since
2225 /// metadata operands are not just parsed here but also converted to values).
2226 /// PFS can be null when we are not parsing metadata values inside a function.
2227 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2228 ID.Loc = Lex.getLoc();
2229 switch (Lex.getKind()) {
2230 default: return TokError("expected value token");
2231 case lltok::GlobalID: // @42
2232 ID.UIntVal = Lex.getUIntVal();
2233 ID.Kind = ValID::t_GlobalID;
2235 case lltok::GlobalVar: // @foo
2236 ID.StrVal = Lex.getStrVal();
2237 ID.Kind = ValID::t_GlobalName;
2239 case lltok::LocalVarID: // %42
2240 ID.UIntVal = Lex.getUIntVal();
2241 ID.Kind = ValID::t_LocalID;
2243 case lltok::LocalVar: // %foo
2244 ID.StrVal = Lex.getStrVal();
2245 ID.Kind = ValID::t_LocalName;
2247 case lltok::exclaim: // !42, !{...}, or !"foo"
2248 return ParseMetadataValue(ID, PFS);
2250 ID.APSIntVal = Lex.getAPSIntVal();
2251 ID.Kind = ValID::t_APSInt;
2253 case lltok::APFloat:
2254 ID.APFloatVal = Lex.getAPFloatVal();
2255 ID.Kind = ValID::t_APFloat;
2257 case lltok::kw_true:
2258 ID.ConstantVal = ConstantInt::getTrue(Context);
2259 ID.Kind = ValID::t_Constant;
2261 case lltok::kw_false:
2262 ID.ConstantVal = ConstantInt::getFalse(Context);
2263 ID.Kind = ValID::t_Constant;
2265 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2266 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2267 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2269 case lltok::lbrace: {
2270 // ValID ::= '{' ConstVector '}'
2272 SmallVector<Constant*, 16> Elts;
2273 if (ParseGlobalValueVector(Elts) ||
2274 ParseToken(lltok::rbrace, "expected end of struct constant"))
2277 ID.ConstantStructElts = new Constant*[Elts.size()];
2278 ID.UIntVal = Elts.size();
2279 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2280 ID.Kind = ValID::t_ConstantStruct;
2284 // ValID ::= '<' ConstVector '>' --> Vector.
2285 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2287 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2289 SmallVector<Constant*, 16> Elts;
2290 LocTy FirstEltLoc = Lex.getLoc();
2291 if (ParseGlobalValueVector(Elts) ||
2293 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2294 ParseToken(lltok::greater, "expected end of constant"))
2297 if (isPackedStruct) {
2298 ID.ConstantStructElts = new Constant*[Elts.size()];
2299 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2300 ID.UIntVal = Elts.size();
2301 ID.Kind = ValID::t_PackedConstantStruct;
2306 return Error(ID.Loc, "constant vector must not be empty");
2308 if (!Elts[0]->getType()->isIntegerTy() &&
2309 !Elts[0]->getType()->isFloatingPointTy() &&
2310 !Elts[0]->getType()->isPointerTy())
2311 return Error(FirstEltLoc,
2312 "vector elements must have integer, pointer or floating point type");
2314 // Verify that all the vector elements have the same type.
2315 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2316 if (Elts[i]->getType() != Elts[0]->getType())
2317 return Error(FirstEltLoc,
2318 "vector element #" + Twine(i) +
2319 " is not of type '" + getTypeString(Elts[0]->getType()));
2321 ID.ConstantVal = ConstantVector::get(Elts);
2322 ID.Kind = ValID::t_Constant;
2325 case lltok::lsquare: { // Array Constant
2327 SmallVector<Constant*, 16> Elts;
2328 LocTy FirstEltLoc = Lex.getLoc();
2329 if (ParseGlobalValueVector(Elts) ||
2330 ParseToken(lltok::rsquare, "expected end of array constant"))
2333 // Handle empty element.
2335 // Use undef instead of an array because it's inconvenient to determine
2336 // the element type at this point, there being no elements to examine.
2337 ID.Kind = ValID::t_EmptyArray;
2341 if (!Elts[0]->getType()->isFirstClassType())
2342 return Error(FirstEltLoc, "invalid array element type: " +
2343 getTypeString(Elts[0]->getType()));
2345 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2347 // Verify all elements are correct type!
2348 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2349 if (Elts[i]->getType() != Elts[0]->getType())
2350 return Error(FirstEltLoc,
2351 "array element #" + Twine(i) +
2352 " is not of type '" + getTypeString(Elts[0]->getType()));
2355 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2356 ID.Kind = ValID::t_Constant;
2359 case lltok::kw_c: // c "foo"
2361 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2363 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2364 ID.Kind = ValID::t_Constant;
2367 case lltok::kw_asm: {
2368 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2370 bool HasSideEffect, AlignStack, AsmDialect;
2372 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2373 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2374 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2375 ParseStringConstant(ID.StrVal) ||
2376 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2377 ParseToken(lltok::StringConstant, "expected constraint string"))
2379 ID.StrVal2 = Lex.getStrVal();
2380 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2381 (unsigned(AsmDialect)<<2);
2382 ID.Kind = ValID::t_InlineAsm;
2386 case lltok::kw_blockaddress: {
2387 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2392 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2394 ParseToken(lltok::comma, "expected comma in block address expression")||
2395 ParseValID(Label) ||
2396 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2399 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2400 return Error(Fn.Loc, "expected function name in blockaddress");
2401 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2402 return Error(Label.Loc, "expected basic block name in blockaddress");
2404 // Make a global variable as a placeholder for this reference.
2405 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2406 false, GlobalValue::InternalLinkage,
2408 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2409 ID.ConstantVal = FwdRef;
2410 ID.Kind = ValID::t_Constant;
2414 case lltok::kw_trunc:
2415 case lltok::kw_zext:
2416 case lltok::kw_sext:
2417 case lltok::kw_fptrunc:
2418 case lltok::kw_fpext:
2419 case lltok::kw_bitcast:
2420 case lltok::kw_addrspacecast:
2421 case lltok::kw_uitofp:
2422 case lltok::kw_sitofp:
2423 case lltok::kw_fptoui:
2424 case lltok::kw_fptosi:
2425 case lltok::kw_inttoptr:
2426 case lltok::kw_ptrtoint: {
2427 unsigned Opc = Lex.getUIntVal();
2431 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2432 ParseGlobalTypeAndValue(SrcVal) ||
2433 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2434 ParseType(DestTy) ||
2435 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2437 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2438 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2439 getTypeString(SrcVal->getType()) + "' to '" +
2440 getTypeString(DestTy) + "'");
2441 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2443 ID.Kind = ValID::t_Constant;
2446 case lltok::kw_extractvalue: {
2449 SmallVector<unsigned, 4> Indices;
2450 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2451 ParseGlobalTypeAndValue(Val) ||
2452 ParseIndexList(Indices) ||
2453 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2456 if (!Val->getType()->isAggregateType())
2457 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2458 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2459 return Error(ID.Loc, "invalid indices for extractvalue");
2460 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2461 ID.Kind = ValID::t_Constant;
2464 case lltok::kw_insertvalue: {
2466 Constant *Val0, *Val1;
2467 SmallVector<unsigned, 4> Indices;
2468 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2469 ParseGlobalTypeAndValue(Val0) ||
2470 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2471 ParseGlobalTypeAndValue(Val1) ||
2472 ParseIndexList(Indices) ||
2473 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2475 if (!Val0->getType()->isAggregateType())
2476 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2477 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2478 return Error(ID.Loc, "invalid indices for insertvalue");
2479 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2480 ID.Kind = ValID::t_Constant;
2483 case lltok::kw_icmp:
2484 case lltok::kw_fcmp: {
2485 unsigned PredVal, Opc = Lex.getUIntVal();
2486 Constant *Val0, *Val1;
2488 if (ParseCmpPredicate(PredVal, Opc) ||
2489 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2490 ParseGlobalTypeAndValue(Val0) ||
2491 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2492 ParseGlobalTypeAndValue(Val1) ||
2493 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2496 if (Val0->getType() != Val1->getType())
2497 return Error(ID.Loc, "compare operands must have the same type");
2499 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2501 if (Opc == Instruction::FCmp) {
2502 if (!Val0->getType()->isFPOrFPVectorTy())
2503 return Error(ID.Loc, "fcmp requires floating point operands");
2504 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2506 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2507 if (!Val0->getType()->isIntOrIntVectorTy() &&
2508 !Val0->getType()->getScalarType()->isPointerTy())
2509 return Error(ID.Loc, "icmp requires pointer or integer operands");
2510 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2512 ID.Kind = ValID::t_Constant;
2516 // Binary Operators.
2518 case lltok::kw_fadd:
2520 case lltok::kw_fsub:
2522 case lltok::kw_fmul:
2523 case lltok::kw_udiv:
2524 case lltok::kw_sdiv:
2525 case lltok::kw_fdiv:
2526 case lltok::kw_urem:
2527 case lltok::kw_srem:
2528 case lltok::kw_frem:
2530 case lltok::kw_lshr:
2531 case lltok::kw_ashr: {
2535 unsigned Opc = Lex.getUIntVal();
2536 Constant *Val0, *Val1;
2538 LocTy ModifierLoc = Lex.getLoc();
2539 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2540 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2541 if (EatIfPresent(lltok::kw_nuw))
2543 if (EatIfPresent(lltok::kw_nsw)) {
2545 if (EatIfPresent(lltok::kw_nuw))
2548 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2549 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2550 if (EatIfPresent(lltok::kw_exact))
2553 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2554 ParseGlobalTypeAndValue(Val0) ||
2555 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2556 ParseGlobalTypeAndValue(Val1) ||
2557 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2559 if (Val0->getType() != Val1->getType())
2560 return Error(ID.Loc, "operands of constexpr must have same type");
2561 if (!Val0->getType()->isIntOrIntVectorTy()) {
2563 return Error(ModifierLoc, "nuw only applies to integer operations");
2565 return Error(ModifierLoc, "nsw only applies to integer operations");
2567 // Check that the type is valid for the operator.
2569 case Instruction::Add:
2570 case Instruction::Sub:
2571 case Instruction::Mul:
2572 case Instruction::UDiv:
2573 case Instruction::SDiv:
2574 case Instruction::URem:
2575 case Instruction::SRem:
2576 case Instruction::Shl:
2577 case Instruction::AShr:
2578 case Instruction::LShr:
2579 if (!Val0->getType()->isIntOrIntVectorTy())
2580 return Error(ID.Loc, "constexpr requires integer operands");
2582 case Instruction::FAdd:
2583 case Instruction::FSub:
2584 case Instruction::FMul:
2585 case Instruction::FDiv:
2586 case Instruction::FRem:
2587 if (!Val0->getType()->isFPOrFPVectorTy())
2588 return Error(ID.Loc, "constexpr requires fp operands");
2590 default: llvm_unreachable("Unknown binary operator!");
2593 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2594 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2595 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2596 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2598 ID.Kind = ValID::t_Constant;
2602 // Logical Operations
2605 case lltok::kw_xor: {
2606 unsigned Opc = Lex.getUIntVal();
2607 Constant *Val0, *Val1;
2609 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2610 ParseGlobalTypeAndValue(Val0) ||
2611 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2612 ParseGlobalTypeAndValue(Val1) ||
2613 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2615 if (Val0->getType() != Val1->getType())
2616 return Error(ID.Loc, "operands of constexpr must have same type");
2617 if (!Val0->getType()->isIntOrIntVectorTy())
2618 return Error(ID.Loc,
2619 "constexpr requires integer or integer vector operands");
2620 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2621 ID.Kind = ValID::t_Constant;
2625 case lltok::kw_getelementptr:
2626 case lltok::kw_shufflevector:
2627 case lltok::kw_insertelement:
2628 case lltok::kw_extractelement:
2629 case lltok::kw_select: {
2630 unsigned Opc = Lex.getUIntVal();
2631 SmallVector<Constant*, 16> Elts;
2632 bool InBounds = false;
2634 if (Opc == Instruction::GetElementPtr)
2635 InBounds = EatIfPresent(lltok::kw_inbounds);
2636 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2637 ParseGlobalValueVector(Elts) ||
2638 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2641 if (Opc == Instruction::GetElementPtr) {
2642 if (Elts.size() == 0 ||
2643 !Elts[0]->getType()->getScalarType()->isPointerTy())
2644 return Error(ID.Loc, "getelementptr requires pointer operand");
2646 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2647 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2648 return Error(ID.Loc, "invalid indices for getelementptr");
2649 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2651 } else if (Opc == Instruction::Select) {
2652 if (Elts.size() != 3)
2653 return Error(ID.Loc, "expected three operands to select");
2654 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2656 return Error(ID.Loc, Reason);
2657 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2658 } else if (Opc == Instruction::ShuffleVector) {
2659 if (Elts.size() != 3)
2660 return Error(ID.Loc, "expected three operands to shufflevector");
2661 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2662 return Error(ID.Loc, "invalid operands to shufflevector");
2664 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2665 } else if (Opc == Instruction::ExtractElement) {
2666 if (Elts.size() != 2)
2667 return Error(ID.Loc, "expected two operands to extractelement");
2668 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2669 return Error(ID.Loc, "invalid extractelement operands");
2670 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2672 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2673 if (Elts.size() != 3)
2674 return Error(ID.Loc, "expected three operands to insertelement");
2675 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2676 return Error(ID.Loc, "invalid insertelement operands");
2678 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2681 ID.Kind = ValID::t_Constant;
2690 /// ParseGlobalValue - Parse a global value with the specified type.
2691 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2695 bool Parsed = ParseValID(ID) ||
2696 ConvertValIDToValue(Ty, ID, V, NULL);
2697 if (V && !(C = dyn_cast<Constant>(V)))
2698 return Error(ID.Loc, "global values must be constants");
2702 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2704 return ParseType(Ty) ||
2705 ParseGlobalValue(Ty, V);
2708 /// ParseGlobalValueVector
2710 /// ::= TypeAndValue (',' TypeAndValue)*
2711 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2713 if (Lex.getKind() == lltok::rbrace ||
2714 Lex.getKind() == lltok::rsquare ||
2715 Lex.getKind() == lltok::greater ||
2716 Lex.getKind() == lltok::rparen)
2720 if (ParseGlobalTypeAndValue(C)) return true;
2723 while (EatIfPresent(lltok::comma)) {
2724 if (ParseGlobalTypeAndValue(C)) return true;
2731 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2732 assert(Lex.getKind() == lltok::lbrace);
2735 SmallVector<Value*, 16> Elts;
2736 if (ParseMDNodeVector(Elts, PFS) ||
2737 ParseToken(lltok::rbrace, "expected end of metadata node"))
2740 ID.MDNodeVal = MDNode::get(Context, Elts);
2741 ID.Kind = ValID::t_MDNode;
2745 /// ParseMetadataValue
2749 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2750 assert(Lex.getKind() == lltok::exclaim);
2755 if (Lex.getKind() == lltok::lbrace)
2756 return ParseMetadataListValue(ID, PFS);
2758 // Standalone metadata reference
2760 if (Lex.getKind() == lltok::APSInt) {
2761 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2762 ID.Kind = ValID::t_MDNode;
2767 // ::= '!' STRINGCONSTANT
2768 if (ParseMDString(ID.MDStringVal)) return true;
2769 ID.Kind = ValID::t_MDString;
2774 //===----------------------------------------------------------------------===//
2775 // Function Parsing.
2776 //===----------------------------------------------------------------------===//
2778 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2779 PerFunctionState *PFS) {
2780 if (Ty->isFunctionTy())
2781 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2784 case ValID::t_LocalID:
2785 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2786 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2788 case ValID::t_LocalName:
2789 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2790 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2792 case ValID::t_InlineAsm: {
2793 PointerType *PTy = dyn_cast<PointerType>(Ty);
2795 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2796 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2797 return Error(ID.Loc, "invalid type for inline asm constraint string");
2798 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
2799 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
2802 case ValID::t_MDNode:
2803 if (!Ty->isMetadataTy())
2804 return Error(ID.Loc, "metadata value must have metadata type");
2807 case ValID::t_MDString:
2808 if (!Ty->isMetadataTy())
2809 return Error(ID.Loc, "metadata value must have metadata type");
2812 case ValID::t_GlobalName:
2813 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2815 case ValID::t_GlobalID:
2816 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2818 case ValID::t_APSInt:
2819 if (!Ty->isIntegerTy())
2820 return Error(ID.Loc, "integer constant must have integer type");
2821 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2822 V = ConstantInt::get(Context, ID.APSIntVal);
2824 case ValID::t_APFloat:
2825 if (!Ty->isFloatingPointTy() ||
2826 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2827 return Error(ID.Loc, "floating point constant invalid for type");
2829 // The lexer has no type info, so builds all half, float, and double FP
2830 // constants as double. Fix this here. Long double does not need this.
2831 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
2834 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2836 else if (Ty->isFloatTy())
2837 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2840 V = ConstantFP::get(Context, ID.APFloatVal);
2842 if (V->getType() != Ty)
2843 return Error(ID.Loc, "floating point constant does not have type '" +
2844 getTypeString(Ty) + "'");
2848 if (!Ty->isPointerTy())
2849 return Error(ID.Loc, "null must be a pointer type");
2850 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2852 case ValID::t_Undef:
2853 // FIXME: LabelTy should not be a first-class type.
2854 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2855 return Error(ID.Loc, "invalid type for undef constant");
2856 V = UndefValue::get(Ty);
2858 case ValID::t_EmptyArray:
2859 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2860 return Error(ID.Loc, "invalid empty array initializer");
2861 V = UndefValue::get(Ty);
2864 // FIXME: LabelTy should not be a first-class type.
2865 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2866 return Error(ID.Loc, "invalid type for null constant");
2867 V = Constant::getNullValue(Ty);
2869 case ValID::t_Constant:
2870 if (ID.ConstantVal->getType() != Ty)
2871 return Error(ID.Loc, "constant expression type mismatch");
2875 case ValID::t_ConstantStruct:
2876 case ValID::t_PackedConstantStruct:
2877 if (StructType *ST = dyn_cast<StructType>(Ty)) {
2878 if (ST->getNumElements() != ID.UIntVal)
2879 return Error(ID.Loc,
2880 "initializer with struct type has wrong # elements");
2881 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2882 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2884 // Verify that the elements are compatible with the structtype.
2885 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2886 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2887 return Error(ID.Loc, "element " + Twine(i) +
2888 " of struct initializer doesn't match struct element type");
2890 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2893 return Error(ID.Loc, "constant expression type mismatch");
2896 llvm_unreachable("Invalid ValID");
2899 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
2902 return ParseValID(ID, PFS) ||
2903 ConvertValIDToValue(Ty, ID, V, PFS);
2906 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2908 return ParseType(Ty) ||
2909 ParseValue(Ty, V, PFS);
2912 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2913 PerFunctionState &PFS) {
2916 if (ParseTypeAndValue(V, PFS)) return true;
2917 if (!isa<BasicBlock>(V))
2918 return Error(Loc, "expected a basic block");
2919 BB = cast<BasicBlock>(V);
2925 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2926 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2927 /// OptionalAlign OptGC OptionalPrefix
2928 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2929 // Parse the linkage.
2930 LocTy LinkageLoc = Lex.getLoc();
2933 unsigned Visibility;
2934 AttrBuilder RetAttrs;
2937 LocTy RetTypeLoc = Lex.getLoc();
2938 if (ParseOptionalLinkage(Linkage) ||
2939 ParseOptionalVisibility(Visibility) ||
2940 ParseOptionalCallingConv(CC) ||
2941 ParseOptionalReturnAttrs(RetAttrs) ||
2942 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2945 // Verify that the linkage is ok.
2946 switch ((GlobalValue::LinkageTypes)Linkage) {
2947 case GlobalValue::ExternalLinkage:
2948 break; // always ok.
2949 case GlobalValue::DLLImportLinkage:
2950 case GlobalValue::ExternalWeakLinkage:
2952 return Error(LinkageLoc, "invalid linkage for function definition");
2954 case GlobalValue::PrivateLinkage:
2955 case GlobalValue::LinkerPrivateLinkage:
2956 case GlobalValue::LinkerPrivateWeakLinkage:
2957 case GlobalValue::InternalLinkage:
2958 case GlobalValue::AvailableExternallyLinkage:
2959 case GlobalValue::LinkOnceAnyLinkage:
2960 case GlobalValue::LinkOnceODRLinkage:
2961 case GlobalValue::WeakAnyLinkage:
2962 case GlobalValue::WeakODRLinkage:
2963 case GlobalValue::DLLExportLinkage:
2965 return Error(LinkageLoc, "invalid linkage for function declaration");
2967 case GlobalValue::AppendingLinkage:
2968 case GlobalValue::CommonLinkage:
2969 return Error(LinkageLoc, "invalid function linkage type");
2972 if (!FunctionType::isValidReturnType(RetType))
2973 return Error(RetTypeLoc, "invalid function return type");
2975 LocTy NameLoc = Lex.getLoc();
2977 std::string FunctionName;
2978 if (Lex.getKind() == lltok::GlobalVar) {
2979 FunctionName = Lex.getStrVal();
2980 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2981 unsigned NameID = Lex.getUIntVal();
2983 if (NameID != NumberedVals.size())
2984 return TokError("function expected to be numbered '%" +
2985 Twine(NumberedVals.size()) + "'");
2987 return TokError("expected function name");
2992 if (Lex.getKind() != lltok::lparen)
2993 return TokError("expected '(' in function argument list");
2995 SmallVector<ArgInfo, 8> ArgList;
2997 AttrBuilder FuncAttrs;
2998 std::vector<unsigned> FwdRefAttrGrps;
3000 std::string Section;
3004 LocTy UnnamedAddrLoc;
3005 Constant *Prefix = 0;
3007 if (ParseArgumentList(ArgList, isVarArg) ||
3008 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3010 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
3012 (EatIfPresent(lltok::kw_section) &&
3013 ParseStringConstant(Section)) ||
3014 ParseOptionalAlignment(Alignment) ||
3015 (EatIfPresent(lltok::kw_gc) &&
3016 ParseStringConstant(GC)) ||
3017 (EatIfPresent(lltok::kw_prefix) &&
3018 ParseGlobalTypeAndValue(Prefix)))
3021 if (FuncAttrs.contains(Attribute::Builtin))
3022 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
3024 // If the alignment was parsed as an attribute, move to the alignment field.
3025 if (FuncAttrs.hasAlignmentAttr()) {
3026 Alignment = FuncAttrs.getAlignment();
3027 FuncAttrs.removeAttribute(Attribute::Alignment);
3030 // Okay, if we got here, the function is syntactically valid. Convert types
3031 // and do semantic checks.
3032 std::vector<Type*> ParamTypeList;
3033 SmallVector<AttributeSet, 8> Attrs;
3035 if (RetAttrs.hasAttributes())
3036 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3037 AttributeSet::ReturnIndex,
3040 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3041 ParamTypeList.push_back(ArgList[i].Ty);
3042 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3043 AttrBuilder B(ArgList[i].Attrs, i + 1);
3044 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3048 if (FuncAttrs.hasAttributes())
3049 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3050 AttributeSet::FunctionIndex,
3053 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3055 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
3056 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3059 FunctionType::get(RetType, ParamTypeList, isVarArg);
3060 PointerType *PFT = PointerType::getUnqual(FT);
3063 if (!FunctionName.empty()) {
3064 // If this was a definition of a forward reference, remove the definition
3065 // from the forward reference table and fill in the forward ref.
3066 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3067 ForwardRefVals.find(FunctionName);
3068 if (FRVI != ForwardRefVals.end()) {
3069 Fn = M->getFunction(FunctionName);
3071 return Error(FRVI->second.second, "invalid forward reference to "
3072 "function as global value!");
3073 if (Fn->getType() != PFT)
3074 return Error(FRVI->second.second, "invalid forward reference to "
3075 "function '" + FunctionName + "' with wrong type!");
3077 ForwardRefVals.erase(FRVI);
3078 } else if ((Fn = M->getFunction(FunctionName))) {
3079 // Reject redefinitions.
3080 return Error(NameLoc, "invalid redefinition of function '" +
3081 FunctionName + "'");
3082 } else if (M->getNamedValue(FunctionName)) {
3083 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
3087 // If this is a definition of a forward referenced function, make sure the
3089 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3090 = ForwardRefValIDs.find(NumberedVals.size());
3091 if (I != ForwardRefValIDs.end()) {
3092 Fn = cast<Function>(I->second.first);
3093 if (Fn->getType() != PFT)
3094 return Error(NameLoc, "type of definition and forward reference of '@" +
3095 Twine(NumberedVals.size()) + "' disagree");
3096 ForwardRefValIDs.erase(I);
3101 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3102 else // Move the forward-reference to the correct spot in the module.
3103 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3105 if (FunctionName.empty())
3106 NumberedVals.push_back(Fn);
3108 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3109 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3110 Fn->setCallingConv(CC);
3111 Fn->setAttributes(PAL);
3112 Fn->setUnnamedAddr(UnnamedAddr);
3113 Fn->setAlignment(Alignment);
3114 Fn->setSection(Section);
3115 if (!GC.empty()) Fn->setGC(GC.c_str());
3116 Fn->setPrefixData(Prefix);
3117 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
3119 // Add all of the arguments we parsed to the function.
3120 Function::arg_iterator ArgIt = Fn->arg_begin();
3121 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3122 // If the argument has a name, insert it into the argument symbol table.
3123 if (ArgList[i].Name.empty()) continue;
3125 // Set the name, if it conflicted, it will be auto-renamed.
3126 ArgIt->setName(ArgList[i].Name);
3128 if (ArgIt->getName() != ArgList[i].Name)
3129 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3130 ArgList[i].Name + "'");
3137 /// ParseFunctionBody
3138 /// ::= '{' BasicBlock+ '}'
3140 bool LLParser::ParseFunctionBody(Function &Fn) {
3141 if (Lex.getKind() != lltok::lbrace)
3142 return TokError("expected '{' in function body");
3143 Lex.Lex(); // eat the {.
3145 int FunctionNumber = -1;
3146 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
3148 PerFunctionState PFS(*this, Fn, FunctionNumber);
3150 // We need at least one basic block.
3151 if (Lex.getKind() == lltok::rbrace)
3152 return TokError("function body requires at least one basic block");
3154 while (Lex.getKind() != lltok::rbrace)
3155 if (ParseBasicBlock(PFS)) return true;
3160 // Verify function is ok.
3161 return PFS.FinishFunction();
3165 /// ::= LabelStr? Instruction*
3166 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3167 // If this basic block starts out with a name, remember it.
3169 LocTy NameLoc = Lex.getLoc();
3170 if (Lex.getKind() == lltok::LabelStr) {
3171 Name = Lex.getStrVal();
3175 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3176 if (BB == 0) return true;
3178 std::string NameStr;
3180 // Parse the instructions in this block until we get a terminator.
3183 // This instruction may have three possibilities for a name: a) none
3184 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3185 LocTy NameLoc = Lex.getLoc();
3189 if (Lex.getKind() == lltok::LocalVarID) {
3190 NameID = Lex.getUIntVal();
3192 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3194 } else if (Lex.getKind() == lltok::LocalVar) {
3195 NameStr = Lex.getStrVal();
3197 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3201 switch (ParseInstruction(Inst, BB, PFS)) {
3202 default: llvm_unreachable("Unknown ParseInstruction result!");
3203 case InstError: return true;
3205 BB->getInstList().push_back(Inst);
3207 // With a normal result, we check to see if the instruction is followed by
3208 // a comma and metadata.
3209 if (EatIfPresent(lltok::comma))
3210 if (ParseInstructionMetadata(Inst, &PFS))
3213 case InstExtraComma:
3214 BB->getInstList().push_back(Inst);
3216 // If the instruction parser ate an extra comma at the end of it, it
3217 // *must* be followed by metadata.
3218 if (ParseInstructionMetadata(Inst, &PFS))
3223 // Set the name on the instruction.
3224 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3225 } while (!isa<TerminatorInst>(Inst));
3230 //===----------------------------------------------------------------------===//
3231 // Instruction Parsing.
3232 //===----------------------------------------------------------------------===//
3234 /// ParseInstruction - Parse one of the many different instructions.
3236 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3237 PerFunctionState &PFS) {
3238 lltok::Kind Token = Lex.getKind();
3239 if (Token == lltok::Eof)
3240 return TokError("found end of file when expecting more instructions");
3241 LocTy Loc = Lex.getLoc();
3242 unsigned KeywordVal = Lex.getUIntVal();
3243 Lex.Lex(); // Eat the keyword.
3246 default: return Error(Loc, "expected instruction opcode");
3247 // Terminator Instructions.
3248 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3249 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3250 case lltok::kw_br: return ParseBr(Inst, PFS);
3251 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
3252 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
3253 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3254 case lltok::kw_resume: return ParseResume(Inst, PFS);
3255 // Binary Operators.
3259 case lltok::kw_shl: {
3260 bool NUW = EatIfPresent(lltok::kw_nuw);
3261 bool NSW = EatIfPresent(lltok::kw_nsw);
3262 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3264 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3266 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3267 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3270 case lltok::kw_fadd:
3271 case lltok::kw_fsub:
3272 case lltok::kw_fmul:
3273 case lltok::kw_fdiv:
3274 case lltok::kw_frem: {
3275 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3276 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3280 Inst->setFastMathFlags(FMF);
3284 case lltok::kw_sdiv:
3285 case lltok::kw_udiv:
3286 case lltok::kw_lshr:
3287 case lltok::kw_ashr: {
3288 bool Exact = EatIfPresent(lltok::kw_exact);
3290 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3291 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3295 case lltok::kw_urem:
3296 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3299 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3300 case lltok::kw_icmp:
3301 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3303 case lltok::kw_trunc:
3304 case lltok::kw_zext:
3305 case lltok::kw_sext:
3306 case lltok::kw_fptrunc:
3307 case lltok::kw_fpext:
3308 case lltok::kw_bitcast:
3309 case lltok::kw_addrspacecast:
3310 case lltok::kw_uitofp:
3311 case lltok::kw_sitofp:
3312 case lltok::kw_fptoui:
3313 case lltok::kw_fptosi:
3314 case lltok::kw_inttoptr:
3315 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3317 case lltok::kw_select: return ParseSelect(Inst, PFS);
3318 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3319 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3320 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3321 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3322 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3323 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3324 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3325 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3327 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3328 case lltok::kw_load: return ParseLoad(Inst, PFS);
3329 case lltok::kw_store: return ParseStore(Inst, PFS);
3330 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3331 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3332 case lltok::kw_fence: return ParseFence(Inst, PFS);
3333 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3334 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3335 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3339 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3340 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3341 if (Opc == Instruction::FCmp) {
3342 switch (Lex.getKind()) {
3343 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
3344 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3345 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3346 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3347 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3348 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3349 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3350 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3351 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3352 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3353 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3354 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3355 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3356 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3357 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3358 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3359 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3362 switch (Lex.getKind()) {
3363 default: return TokError("expected icmp predicate (e.g. 'eq')");
3364 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3365 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3366 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3367 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3368 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3369 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3370 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3371 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3372 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3373 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3380 //===----------------------------------------------------------------------===//
3381 // Terminator Instructions.
3382 //===----------------------------------------------------------------------===//
3384 /// ParseRet - Parse a return instruction.
3385 /// ::= 'ret' void (',' !dbg, !1)*
3386 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3387 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3388 PerFunctionState &PFS) {
3389 SMLoc TypeLoc = Lex.getLoc();
3391 if (ParseType(Ty, true /*void allowed*/)) return true;
3393 Type *ResType = PFS.getFunction().getReturnType();
3395 if (Ty->isVoidTy()) {
3396 if (!ResType->isVoidTy())
3397 return Error(TypeLoc, "value doesn't match function result type '" +
3398 getTypeString(ResType) + "'");
3400 Inst = ReturnInst::Create(Context);
3405 if (ParseValue(Ty, RV, PFS)) return true;
3407 if (ResType != RV->getType())
3408 return Error(TypeLoc, "value doesn't match function result type '" +
3409 getTypeString(ResType) + "'");
3411 Inst = ReturnInst::Create(Context, RV);
3417 /// ::= 'br' TypeAndValue
3418 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3419 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3422 BasicBlock *Op1, *Op2;
3423 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3425 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3426 Inst = BranchInst::Create(BB);
3430 if (Op0->getType() != Type::getInt1Ty(Context))
3431 return Error(Loc, "branch condition must have 'i1' type");
3433 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3434 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3435 ParseToken(lltok::comma, "expected ',' after true destination") ||
3436 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3439 Inst = BranchInst::Create(Op1, Op2, Op0);
3445 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3447 /// ::= (TypeAndValue ',' TypeAndValue)*
3448 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3449 LocTy CondLoc, BBLoc;
3451 BasicBlock *DefaultBB;
3452 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3453 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3454 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3455 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3458 if (!Cond->getType()->isIntegerTy())
3459 return Error(CondLoc, "switch condition must have integer type");
3461 // Parse the jump table pairs.
3462 SmallPtrSet<Value*, 32> SeenCases;
3463 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3464 while (Lex.getKind() != lltok::rsquare) {
3468 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3469 ParseToken(lltok::comma, "expected ',' after case value") ||
3470 ParseTypeAndBasicBlock(DestBB, PFS))
3473 if (!SeenCases.insert(Constant))
3474 return Error(CondLoc, "duplicate case value in switch");
3475 if (!isa<ConstantInt>(Constant))
3476 return Error(CondLoc, "case value is not a constant integer");
3478 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3481 Lex.Lex(); // Eat the ']'.
3483 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3484 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3485 SI->addCase(Table[i].first, Table[i].second);
3492 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3493 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3496 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3497 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3498 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3501 if (!Address->getType()->isPointerTy())
3502 return Error(AddrLoc, "indirectbr address must have pointer type");
3504 // Parse the destination list.
3505 SmallVector<BasicBlock*, 16> DestList;
3507 if (Lex.getKind() != lltok::rsquare) {
3509 if (ParseTypeAndBasicBlock(DestBB, PFS))
3511 DestList.push_back(DestBB);
3513 while (EatIfPresent(lltok::comma)) {
3514 if (ParseTypeAndBasicBlock(DestBB, PFS))
3516 DestList.push_back(DestBB);
3520 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3523 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3524 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3525 IBI->addDestination(DestList[i]);
3532 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3533 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3534 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3535 LocTy CallLoc = Lex.getLoc();
3536 AttrBuilder RetAttrs, FnAttrs;
3537 std::vector<unsigned> FwdRefAttrGrps;
3543 SmallVector<ParamInfo, 16> ArgList;
3545 BasicBlock *NormalBB, *UnwindBB;
3546 if (ParseOptionalCallingConv(CC) ||
3547 ParseOptionalReturnAttrs(RetAttrs) ||
3548 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3549 ParseValID(CalleeID) ||
3550 ParseParameterList(ArgList, PFS) ||
3551 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3553 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3554 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3555 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3556 ParseTypeAndBasicBlock(UnwindBB, PFS))
3559 // If RetType is a non-function pointer type, then this is the short syntax
3560 // for the call, which means that RetType is just the return type. Infer the
3561 // rest of the function argument types from the arguments that are present.
3562 PointerType *PFTy = 0;
3563 FunctionType *Ty = 0;
3564 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3565 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3566 // Pull out the types of all of the arguments...
3567 std::vector<Type*> ParamTypes;
3568 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3569 ParamTypes.push_back(ArgList[i].V->getType());
3571 if (!FunctionType::isValidReturnType(RetType))
3572 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3574 Ty = FunctionType::get(RetType, ParamTypes, false);
3575 PFTy = PointerType::getUnqual(Ty);
3578 // Look up the callee.
3580 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3582 // Set up the Attribute for the function.
3583 SmallVector<AttributeSet, 8> Attrs;
3584 if (RetAttrs.hasAttributes())
3585 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3586 AttributeSet::ReturnIndex,
3589 SmallVector<Value*, 8> Args;
3591 // Loop through FunctionType's arguments and ensure they are specified
3592 // correctly. Also, gather any parameter attributes.
3593 FunctionType::param_iterator I = Ty->param_begin();
3594 FunctionType::param_iterator E = Ty->param_end();
3595 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3596 Type *ExpectedTy = 0;
3599 } else if (!Ty->isVarArg()) {
3600 return Error(ArgList[i].Loc, "too many arguments specified");
3603 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3604 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3605 getTypeString(ExpectedTy) + "'");
3606 Args.push_back(ArgList[i].V);
3607 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3608 AttrBuilder B(ArgList[i].Attrs, i + 1);
3609 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3614 return Error(CallLoc, "not enough parameters specified for call");
3616 if (FnAttrs.hasAttributes())
3617 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3618 AttributeSet::FunctionIndex,
3621 // Finish off the Attribute and check them
3622 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3624 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3625 II->setCallingConv(CC);
3626 II->setAttributes(PAL);
3627 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
3633 /// ::= 'resume' TypeAndValue
3634 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3635 Value *Exn; LocTy ExnLoc;
3636 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3639 ResumeInst *RI = ResumeInst::Create(Exn);
3644 //===----------------------------------------------------------------------===//
3645 // Binary Operators.
3646 //===----------------------------------------------------------------------===//
3649 /// ::= ArithmeticOps TypeAndValue ',' Value
3651 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3652 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3653 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3654 unsigned Opc, unsigned OperandType) {
3655 LocTy Loc; Value *LHS, *RHS;
3656 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3657 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3658 ParseValue(LHS->getType(), RHS, PFS))
3662 switch (OperandType) {
3663 default: llvm_unreachable("Unknown operand type!");
3664 case 0: // int or FP.
3665 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3666 LHS->getType()->isFPOrFPVectorTy();
3668 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3669 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3673 return Error(Loc, "invalid operand type for instruction");
3675 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3680 /// ::= ArithmeticOps TypeAndValue ',' Value {
3681 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3683 LocTy Loc; Value *LHS, *RHS;
3684 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3685 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3686 ParseValue(LHS->getType(), RHS, PFS))
3689 if (!LHS->getType()->isIntOrIntVectorTy())
3690 return Error(Loc,"instruction requires integer or integer vector operands");
3692 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3698 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3699 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3700 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3702 // Parse the integer/fp comparison predicate.
3706 if (ParseCmpPredicate(Pred, Opc) ||
3707 ParseTypeAndValue(LHS, Loc, PFS) ||
3708 ParseToken(lltok::comma, "expected ',' after compare value") ||
3709 ParseValue(LHS->getType(), RHS, PFS))
3712 if (Opc == Instruction::FCmp) {
3713 if (!LHS->getType()->isFPOrFPVectorTy())
3714 return Error(Loc, "fcmp requires floating point operands");
3715 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3717 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3718 if (!LHS->getType()->isIntOrIntVectorTy() &&
3719 !LHS->getType()->getScalarType()->isPointerTy())
3720 return Error(Loc, "icmp requires integer operands");
3721 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3726 //===----------------------------------------------------------------------===//
3727 // Other Instructions.
3728 //===----------------------------------------------------------------------===//
3732 /// ::= CastOpc TypeAndValue 'to' Type
3733 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3738 if (ParseTypeAndValue(Op, Loc, PFS) ||
3739 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3743 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3744 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3745 return Error(Loc, "invalid cast opcode for cast from '" +
3746 getTypeString(Op->getType()) + "' to '" +
3747 getTypeString(DestTy) + "'");
3749 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3754 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3755 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3757 Value *Op0, *Op1, *Op2;
3758 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3759 ParseToken(lltok::comma, "expected ',' after select condition") ||
3760 ParseTypeAndValue(Op1, PFS) ||
3761 ParseToken(lltok::comma, "expected ',' after select value") ||
3762 ParseTypeAndValue(Op2, PFS))
3765 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3766 return Error(Loc, Reason);
3768 Inst = SelectInst::Create(Op0, Op1, Op2);
3773 /// ::= 'va_arg' TypeAndValue ',' Type
3774 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3778 if (ParseTypeAndValue(Op, PFS) ||
3779 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3780 ParseType(EltTy, TypeLoc))
3783 if (!EltTy->isFirstClassType())
3784 return Error(TypeLoc, "va_arg requires operand with first class type");
3786 Inst = new VAArgInst(Op, EltTy);
3790 /// ParseExtractElement
3791 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3792 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3795 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3796 ParseToken(lltok::comma, "expected ',' after extract value") ||
3797 ParseTypeAndValue(Op1, PFS))
3800 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3801 return Error(Loc, "invalid extractelement operands");
3803 Inst = ExtractElementInst::Create(Op0, Op1);
3807 /// ParseInsertElement
3808 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3809 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3811 Value *Op0, *Op1, *Op2;
3812 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3813 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3814 ParseTypeAndValue(Op1, PFS) ||
3815 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3816 ParseTypeAndValue(Op2, PFS))
3819 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3820 return Error(Loc, "invalid insertelement operands");
3822 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3826 /// ParseShuffleVector
3827 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3828 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3830 Value *Op0, *Op1, *Op2;
3831 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3832 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3833 ParseTypeAndValue(Op1, PFS) ||
3834 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3835 ParseTypeAndValue(Op2, PFS))
3838 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3839 return Error(Loc, "invalid shufflevector operands");
3841 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3846 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3847 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3848 Type *Ty = 0; LocTy TypeLoc;
3851 if (ParseType(Ty, TypeLoc) ||
3852 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3853 ParseValue(Ty, Op0, PFS) ||
3854 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3855 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3856 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3859 bool AteExtraComma = false;
3860 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3862 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3864 if (!EatIfPresent(lltok::comma))
3867 if (Lex.getKind() == lltok::MetadataVar) {
3868 AteExtraComma = true;
3872 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3873 ParseValue(Ty, Op0, PFS) ||
3874 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3875 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3876 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3880 if (!Ty->isFirstClassType())
3881 return Error(TypeLoc, "phi node must have first class type");
3883 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3884 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3885 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3887 return AteExtraComma ? InstExtraComma : InstNormal;
3891 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3893 /// ::= 'catch' TypeAndValue
3895 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3896 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3897 Type *Ty = 0; LocTy TyLoc;
3898 Value *PersFn; LocTy PersFnLoc;
3900 if (ParseType(Ty, TyLoc) ||
3901 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3902 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3905 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3906 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3908 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3909 LandingPadInst::ClauseType CT;
3910 if (EatIfPresent(lltok::kw_catch))
3911 CT = LandingPadInst::Catch;
3912 else if (EatIfPresent(lltok::kw_filter))
3913 CT = LandingPadInst::Filter;
3915 return TokError("expected 'catch' or 'filter' clause type");
3917 Value *V; LocTy VLoc;
3918 if (ParseTypeAndValue(V, VLoc, PFS)) {
3923 // A 'catch' type expects a non-array constant. A filter clause expects an
3925 if (CT == LandingPadInst::Catch) {
3926 if (isa<ArrayType>(V->getType()))
3927 Error(VLoc, "'catch' clause has an invalid type");
3929 if (!isa<ArrayType>(V->getType()))
3930 Error(VLoc, "'filter' clause has an invalid type");
3941 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3942 /// ParameterList OptionalAttrs
3943 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3945 AttrBuilder RetAttrs, FnAttrs;
3946 std::vector<unsigned> FwdRefAttrGrps;
3952 SmallVector<ParamInfo, 16> ArgList;
3953 LocTy CallLoc = Lex.getLoc();
3955 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3956 ParseOptionalCallingConv(CC) ||
3957 ParseOptionalReturnAttrs(RetAttrs) ||
3958 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3959 ParseValID(CalleeID) ||
3960 ParseParameterList(ArgList, PFS) ||
3961 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3965 // If RetType is a non-function pointer type, then this is the short syntax
3966 // for the call, which means that RetType is just the return type. Infer the
3967 // rest of the function argument types from the arguments that are present.
3968 PointerType *PFTy = 0;
3969 FunctionType *Ty = 0;
3970 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3971 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3972 // Pull out the types of all of the arguments...
3973 std::vector<Type*> ParamTypes;
3974 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3975 ParamTypes.push_back(ArgList[i].V->getType());
3977 if (!FunctionType::isValidReturnType(RetType))
3978 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3980 Ty = FunctionType::get(RetType, ParamTypes, false);
3981 PFTy = PointerType::getUnqual(Ty);
3984 // Look up the callee.
3986 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3988 // Set up the Attribute for the function.
3989 SmallVector<AttributeSet, 8> Attrs;
3990 if (RetAttrs.hasAttributes())
3991 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3992 AttributeSet::ReturnIndex,
3995 SmallVector<Value*, 8> Args;
3997 // Loop through FunctionType's arguments and ensure they are specified
3998 // correctly. Also, gather any parameter attributes.
3999 FunctionType::param_iterator I = Ty->param_begin();
4000 FunctionType::param_iterator E = Ty->param_end();
4001 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4002 Type *ExpectedTy = 0;
4005 } else if (!Ty->isVarArg()) {
4006 return Error(ArgList[i].Loc, "too many arguments specified");
4009 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4010 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4011 getTypeString(ExpectedTy) + "'");
4012 Args.push_back(ArgList[i].V);
4013 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4014 AttrBuilder B(ArgList[i].Attrs, i + 1);
4015 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4020 return Error(CallLoc, "not enough parameters specified for call");
4022 if (FnAttrs.hasAttributes())
4023 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4024 AttributeSet::FunctionIndex,
4027 // Finish off the Attribute and check them
4028 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4030 CallInst *CI = CallInst::Create(Callee, Args);
4031 CI->setTailCall(isTail);
4032 CI->setCallingConv(CC);
4033 CI->setAttributes(PAL);
4034 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
4039 //===----------------------------------------------------------------------===//
4040 // Memory Instructions.
4041 //===----------------------------------------------------------------------===//
4044 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
4045 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
4048 unsigned Alignment = 0;
4050 if (ParseType(Ty)) return true;
4052 bool AteExtraComma = false;
4053 if (EatIfPresent(lltok::comma)) {
4054 if (Lex.getKind() == lltok::kw_align) {
4055 if (ParseOptionalAlignment(Alignment)) return true;
4056 } else if (Lex.getKind() == lltok::MetadataVar) {
4057 AteExtraComma = true;
4059 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4060 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4065 if (Size && !Size->getType()->isIntegerTy())
4066 return Error(SizeLoc, "element count must have integer type");
4068 Inst = new AllocaInst(Ty, Size, Alignment);
4069 return AteExtraComma ? InstExtraComma : InstNormal;
4073 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
4074 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
4075 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4076 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
4077 Value *Val; LocTy Loc;
4078 unsigned Alignment = 0;
4079 bool AteExtraComma = false;
4080 bool isAtomic = false;
4081 AtomicOrdering Ordering = NotAtomic;
4082 SynchronizationScope Scope = CrossThread;
4084 if (Lex.getKind() == lltok::kw_atomic) {
4089 bool isVolatile = false;
4090 if (Lex.getKind() == lltok::kw_volatile) {
4095 if (ParseTypeAndValue(Val, Loc, PFS) ||
4096 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4097 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4100 if (!Val->getType()->isPointerTy() ||
4101 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4102 return Error(Loc, "load operand must be a pointer to a first class type");
4103 if (isAtomic && !Alignment)
4104 return Error(Loc, "atomic load must have explicit non-zero alignment");
4105 if (Ordering == Release || Ordering == AcquireRelease)
4106 return Error(Loc, "atomic load cannot use Release ordering");
4108 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
4109 return AteExtraComma ? InstExtraComma : InstNormal;
4114 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4115 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
4116 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4117 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
4118 Value *Val, *Ptr; LocTy Loc, PtrLoc;
4119 unsigned Alignment = 0;
4120 bool AteExtraComma = false;
4121 bool isAtomic = false;
4122 AtomicOrdering Ordering = NotAtomic;
4123 SynchronizationScope Scope = CrossThread;
4125 if (Lex.getKind() == lltok::kw_atomic) {
4130 bool isVolatile = false;
4131 if (Lex.getKind() == lltok::kw_volatile) {
4136 if (ParseTypeAndValue(Val, Loc, PFS) ||
4137 ParseToken(lltok::comma, "expected ',' after store operand") ||
4138 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4139 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4140 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4143 if (!Ptr->getType()->isPointerTy())
4144 return Error(PtrLoc, "store operand must be a pointer");
4145 if (!Val->getType()->isFirstClassType())
4146 return Error(Loc, "store operand must be a first class value");
4147 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4148 return Error(Loc, "stored value and pointer type do not match");
4149 if (isAtomic && !Alignment)
4150 return Error(Loc, "atomic store must have explicit non-zero alignment");
4151 if (Ordering == Acquire || Ordering == AcquireRelease)
4152 return Error(Loc, "atomic store cannot use Acquire ordering");
4154 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
4155 return AteExtraComma ? InstExtraComma : InstNormal;
4159 /// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
4160 /// 'singlethread'? AtomicOrdering
4161 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
4162 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4163 bool AteExtraComma = false;
4164 AtomicOrdering Ordering = NotAtomic;
4165 SynchronizationScope Scope = CrossThread;
4166 bool isVolatile = false;
4168 if (EatIfPresent(lltok::kw_volatile))
4171 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4172 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4173 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4174 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4175 ParseTypeAndValue(New, NewLoc, PFS) ||
4176 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4179 if (Ordering == Unordered)
4180 return TokError("cmpxchg cannot be unordered");
4181 if (!Ptr->getType()->isPointerTy())
4182 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4183 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4184 return Error(CmpLoc, "compare value and pointer type do not match");
4185 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4186 return Error(NewLoc, "new value and pointer type do not match");
4187 if (!New->getType()->isIntegerTy())
4188 return Error(NewLoc, "cmpxchg operand must be an integer");
4189 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4190 if (Size < 8 || (Size & (Size - 1)))
4191 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4194 AtomicCmpXchgInst *CXI =
4195 new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, Scope);
4196 CXI->setVolatile(isVolatile);
4198 return AteExtraComma ? InstExtraComma : InstNormal;
4202 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4203 /// 'singlethread'? AtomicOrdering
4204 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
4205 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4206 bool AteExtraComma = false;
4207 AtomicOrdering Ordering = NotAtomic;
4208 SynchronizationScope Scope = CrossThread;
4209 bool isVolatile = false;
4210 AtomicRMWInst::BinOp Operation;
4212 if (EatIfPresent(lltok::kw_volatile))
4215 switch (Lex.getKind()) {
4216 default: return TokError("expected binary operation in atomicrmw");
4217 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4218 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4219 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4220 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4221 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4222 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4223 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4224 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4225 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4226 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4227 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4229 Lex.Lex(); // Eat the operation.
4231 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4232 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4233 ParseTypeAndValue(Val, ValLoc, PFS) ||
4234 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4237 if (Ordering == Unordered)
4238 return TokError("atomicrmw cannot be unordered");
4239 if (!Ptr->getType()->isPointerTy())
4240 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4241 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4242 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4243 if (!Val->getType()->isIntegerTy())
4244 return Error(ValLoc, "atomicrmw operand must be an integer");
4245 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4246 if (Size < 8 || (Size & (Size - 1)))
4247 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4250 AtomicRMWInst *RMWI =
4251 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4252 RMWI->setVolatile(isVolatile);
4254 return AteExtraComma ? InstExtraComma : InstNormal;
4258 /// ::= 'fence' 'singlethread'? AtomicOrdering
4259 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4260 AtomicOrdering Ordering = NotAtomic;
4261 SynchronizationScope Scope = CrossThread;
4262 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4265 if (Ordering == Unordered)
4266 return TokError("fence cannot be unordered");
4267 if (Ordering == Monotonic)
4268 return TokError("fence cannot be monotonic");
4270 Inst = new FenceInst(Context, Ordering, Scope);
4274 /// ParseGetElementPtr
4275 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4276 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4281 bool InBounds = EatIfPresent(lltok::kw_inbounds);
4283 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4285 Type *BaseType = Ptr->getType();
4286 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4287 if (!BasePointerType)
4288 return Error(Loc, "base of getelementptr must be a pointer");
4290 SmallVector<Value*, 16> Indices;
4291 bool AteExtraComma = false;
4292 while (EatIfPresent(lltok::comma)) {
4293 if (Lex.getKind() == lltok::MetadataVar) {
4294 AteExtraComma = true;
4297 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4298 if (!Val->getType()->getScalarType()->isIntegerTy())
4299 return Error(EltLoc, "getelementptr index must be an integer");
4300 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4301 return Error(EltLoc, "getelementptr index type missmatch");
4302 if (Val->getType()->isVectorTy()) {
4303 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4304 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4305 if (ValNumEl != PtrNumEl)
4306 return Error(EltLoc,
4307 "getelementptr vector index has a wrong number of elements");
4309 Indices.push_back(Val);
4312 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4313 return Error(Loc, "base element of getelementptr must be sized");
4315 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
4316 return Error(Loc, "invalid getelementptr indices");
4317 Inst = GetElementPtrInst::Create(Ptr, Indices);
4319 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4320 return AteExtraComma ? InstExtraComma : InstNormal;
4323 /// ParseExtractValue
4324 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
4325 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4326 Value *Val; LocTy Loc;
4327 SmallVector<unsigned, 4> Indices;
4329 if (ParseTypeAndValue(Val, Loc, PFS) ||
4330 ParseIndexList(Indices, AteExtraComma))
4333 if (!Val->getType()->isAggregateType())
4334 return Error(Loc, "extractvalue operand must be aggregate type");
4336 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4337 return Error(Loc, "invalid indices for extractvalue");
4338 Inst = ExtractValueInst::Create(Val, Indices);
4339 return AteExtraComma ? InstExtraComma : InstNormal;
4342 /// ParseInsertValue
4343 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4344 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4345 Value *Val0, *Val1; LocTy Loc0, Loc1;
4346 SmallVector<unsigned, 4> Indices;
4348 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4349 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4350 ParseTypeAndValue(Val1, Loc1, PFS) ||
4351 ParseIndexList(Indices, AteExtraComma))
4354 if (!Val0->getType()->isAggregateType())
4355 return Error(Loc0, "insertvalue operand must be aggregate type");
4357 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4358 return Error(Loc0, "invalid indices for insertvalue");
4359 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4360 return AteExtraComma ? InstExtraComma : InstNormal;
4363 //===----------------------------------------------------------------------===//
4364 // Embedded metadata.
4365 //===----------------------------------------------------------------------===//
4367 /// ParseMDNodeVector
4368 /// ::= Element (',' Element)*
4370 /// ::= 'null' | TypeAndValue
4371 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4372 PerFunctionState *PFS) {
4373 // Check for an empty list.
4374 if (Lex.getKind() == lltok::rbrace)
4378 // Null is a special case since it is typeless.
4379 if (EatIfPresent(lltok::kw_null)) {
4385 if (ParseTypeAndValue(V, PFS)) return true;
4387 } while (EatIfPresent(lltok::comma));