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/IR/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 OptionalDLLStorageClass
246 // OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
247 // ('constant'|'global') ...
248 case lltok::kw_private: // OptionalLinkage
249 case lltok::kw_internal: // OptionalLinkage
250 case lltok::kw_weak: // OptionalLinkage
251 case lltok::kw_weak_odr: // OptionalLinkage
252 case lltok::kw_linkonce: // OptionalLinkage
253 case lltok::kw_linkonce_odr: // OptionalLinkage
254 case lltok::kw_appending: // OptionalLinkage
255 case lltok::kw_common: // OptionalLinkage
256 case lltok::kw_extern_weak: // OptionalLinkage
257 case lltok::kw_external: { // OptionalLinkage
258 unsigned Linkage, Visibility, DLLStorageClass;
259 if (ParseOptionalLinkage(Linkage) ||
260 ParseOptionalVisibility(Visibility) ||
261 ParseOptionalDLLStorageClass(DLLStorageClass) ||
262 ParseGlobal("", SMLoc(), Linkage, true, Visibility, DLLStorageClass))
266 case lltok::kw_default: // OptionalVisibility
267 case lltok::kw_hidden: // OptionalVisibility
268 case lltok::kw_protected: { // OptionalVisibility
269 unsigned Visibility, DLLStorageClass;
270 if (ParseOptionalVisibility(Visibility) ||
271 ParseOptionalDLLStorageClass(DLLStorageClass) ||
272 ParseGlobal("", SMLoc(), 0, false, Visibility, DLLStorageClass))
277 case lltok::kw_thread_local: // OptionalThreadLocal
278 case lltok::kw_addrspace: // OptionalAddrSpace
279 case lltok::kw_constant: // GlobalType
280 case lltok::kw_global: // GlobalType
281 if (ParseGlobal("", SMLoc(), 0, false, 0, 0)) return true;
284 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
291 /// ::= 'module' 'asm' STRINGCONSTANT
292 bool LLParser::ParseModuleAsm() {
293 assert(Lex.getKind() == lltok::kw_module);
297 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
298 ParseStringConstant(AsmStr)) return true;
300 M->appendModuleInlineAsm(AsmStr);
305 /// ::= 'target' 'triple' '=' STRINGCONSTANT
306 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
307 bool LLParser::ParseTargetDefinition() {
308 assert(Lex.getKind() == lltok::kw_target);
311 default: return TokError("unknown target property");
312 case lltok::kw_triple:
314 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
315 ParseStringConstant(Str))
317 M->setTargetTriple(Str);
319 case lltok::kw_datalayout:
321 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
322 ParseStringConstant(Str))
324 M->setDataLayout(Str);
330 /// ::= 'deplibs' '=' '[' ']'
331 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
332 /// FIXME: Remove in 4.0. Currently parse, but ignore.
333 bool LLParser::ParseDepLibs() {
334 assert(Lex.getKind() == lltok::kw_deplibs);
336 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
337 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
340 if (EatIfPresent(lltok::rsquare))
345 if (ParseStringConstant(Str)) return true;
346 } while (EatIfPresent(lltok::comma));
348 return ParseToken(lltok::rsquare, "expected ']' at end of list");
351 /// ParseUnnamedType:
352 /// ::= LocalVarID '=' 'type' type
353 bool LLParser::ParseUnnamedType() {
354 LocTy TypeLoc = Lex.getLoc();
355 unsigned TypeID = Lex.getUIntVal();
356 Lex.Lex(); // eat LocalVarID;
358 if (ParseToken(lltok::equal, "expected '=' after name") ||
359 ParseToken(lltok::kw_type, "expected 'type' after '='"))
362 if (TypeID >= NumberedTypes.size())
363 NumberedTypes.resize(TypeID+1);
366 if (ParseStructDefinition(TypeLoc, "",
367 NumberedTypes[TypeID], Result)) return true;
369 if (!isa<StructType>(Result)) {
370 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
372 return Error(TypeLoc, "non-struct types may not be recursive");
373 Entry.first = Result;
374 Entry.second = SMLoc();
382 /// ::= LocalVar '=' 'type' type
383 bool LLParser::ParseNamedType() {
384 std::string Name = Lex.getStrVal();
385 LocTy NameLoc = Lex.getLoc();
386 Lex.Lex(); // eat LocalVar.
388 if (ParseToken(lltok::equal, "expected '=' after name") ||
389 ParseToken(lltok::kw_type, "expected 'type' after name"))
393 if (ParseStructDefinition(NameLoc, Name,
394 NamedTypes[Name], Result)) return true;
396 if (!isa<StructType>(Result)) {
397 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
399 return Error(NameLoc, "non-struct types may not be recursive");
400 Entry.first = Result;
401 Entry.second = SMLoc();
409 /// ::= 'declare' FunctionHeader
410 bool LLParser::ParseDeclare() {
411 assert(Lex.getKind() == lltok::kw_declare);
415 return ParseFunctionHeader(F, false);
419 /// ::= 'define' FunctionHeader '{' ...
420 bool LLParser::ParseDefine() {
421 assert(Lex.getKind() == lltok::kw_define);
425 return ParseFunctionHeader(F, true) ||
426 ParseFunctionBody(*F);
432 bool LLParser::ParseGlobalType(bool &IsConstant) {
433 if (Lex.getKind() == lltok::kw_constant)
435 else if (Lex.getKind() == lltok::kw_global)
439 return TokError("expected 'global' or 'constant'");
445 /// ParseUnnamedGlobal:
446 /// OptionalVisibility ALIAS ...
447 /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
448 /// ... -> global variable
449 /// GlobalID '=' OptionalVisibility ALIAS ...
450 /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
451 /// ... -> 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, DLLStorageClass;
470 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
471 ParseOptionalVisibility(Visibility) ||
472 ParseOptionalDLLStorageClass(DLLStorageClass))
475 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
476 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
478 return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass);
481 /// ParseNamedGlobal:
482 /// GlobalVar '=' OptionalVisibility ALIAS ...
483 /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
484 /// ... -> global variable
485 bool LLParser::ParseNamedGlobal() {
486 assert(Lex.getKind() == lltok::GlobalVar);
487 LocTy NameLoc = Lex.getLoc();
488 std::string Name = Lex.getStrVal();
492 unsigned Linkage, Visibility, DLLStorageClass;
493 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
494 ParseOptionalLinkage(Linkage, HasLinkage) ||
495 ParseOptionalVisibility(Visibility) ||
496 ParseOptionalDLLStorageClass(DLLStorageClass))
499 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
500 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
502 return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass);
506 // ::= '!' STRINGCONSTANT
507 bool LLParser::ParseMDString(MDString *&Result) {
509 if (ParseStringConstant(Str)) return true;
510 Result = MDString::get(Context, Str);
515 // ::= '!' MDNodeNumber
517 /// This version of ParseMDNodeID returns the slot number and null in the case
518 /// of a forward reference.
519 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
520 // !{ ..., !42, ... }
521 if (ParseUInt32(SlotNo)) return true;
523 // Check existing MDNode.
524 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
525 Result = NumberedMetadata[SlotNo];
531 bool LLParser::ParseMDNodeID(MDNode *&Result) {
532 // !{ ..., !42, ... }
534 if (ParseMDNodeID(Result, MID)) return true;
536 // If not a forward reference, just return it now.
537 if (Result) return false;
539 // Otherwise, create MDNode forward reference.
540 MDNode *FwdNode = MDNode::getTemporary(Context, None);
541 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
543 if (NumberedMetadata.size() <= MID)
544 NumberedMetadata.resize(MID+1);
545 NumberedMetadata[MID] = FwdNode;
550 /// ParseNamedMetadata:
551 /// !foo = !{ !1, !2 }
552 bool LLParser::ParseNamedMetadata() {
553 assert(Lex.getKind() == lltok::MetadataVar);
554 std::string Name = Lex.getStrVal();
557 if (ParseToken(lltok::equal, "expected '=' here") ||
558 ParseToken(lltok::exclaim, "Expected '!' here") ||
559 ParseToken(lltok::lbrace, "Expected '{' here"))
562 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
563 if (Lex.getKind() != lltok::rbrace)
565 if (ParseToken(lltok::exclaim, "Expected '!' here"))
569 if (ParseMDNodeID(N)) return true;
571 } while (EatIfPresent(lltok::comma));
573 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
579 /// ParseStandaloneMetadata:
581 bool LLParser::ParseStandaloneMetadata() {
582 assert(Lex.getKind() == lltok::exclaim);
584 unsigned MetadataID = 0;
588 SmallVector<Value *, 16> Elts;
589 if (ParseUInt32(MetadataID) ||
590 ParseToken(lltok::equal, "expected '=' here") ||
591 ParseType(Ty, TyLoc) ||
592 ParseToken(lltok::exclaim, "Expected '!' here") ||
593 ParseToken(lltok::lbrace, "Expected '{' here") ||
594 ParseMDNodeVector(Elts, NULL) ||
595 ParseToken(lltok::rbrace, "expected end of metadata node"))
598 MDNode *Init = MDNode::get(Context, Elts);
600 // See if this was forward referenced, if so, handle it.
601 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
602 FI = ForwardRefMDNodes.find(MetadataID);
603 if (FI != ForwardRefMDNodes.end()) {
604 MDNode *Temp = FI->second.first;
605 Temp->replaceAllUsesWith(Init);
606 MDNode::deleteTemporary(Temp);
607 ForwardRefMDNodes.erase(FI);
609 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
611 if (MetadataID >= NumberedMetadata.size())
612 NumberedMetadata.resize(MetadataID+1);
614 if (NumberedMetadata[MetadataID] != 0)
615 return TokError("Metadata id is already used");
616 NumberedMetadata[MetadataID] = Init;
623 /// ::= GlobalVar '=' OptionalVisibility OptionalDLLStorageClass 'alias'
624 /// OptionalLinkage Aliasee
627 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
628 /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
630 /// Everything through DLL storage class has already been parsed.
632 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
633 unsigned Visibility, unsigned DLLStorageClass) {
634 assert(Lex.getKind() == lltok::kw_alias);
636 LocTy LinkageLoc = Lex.getLoc();
638 if (ParseOptionalLinkage(L))
641 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
643 if(!GlobalAlias::isValidLinkage(Linkage))
644 return Error(LinkageLoc, "invalid linkage type for alias");
647 LocTy AliaseeLoc = Lex.getLoc();
648 if (Lex.getKind() != lltok::kw_bitcast &&
649 Lex.getKind() != lltok::kw_getelementptr) {
650 if (ParseGlobalTypeAndValue(Aliasee)) return true;
652 // The bitcast dest type is not present, it is implied by the dest type.
654 if (ParseValID(ID)) return true;
655 if (ID.Kind != ValID::t_Constant)
656 return Error(AliaseeLoc, "invalid aliasee");
657 Aliasee = ID.ConstantVal;
660 if (!Aliasee->getType()->isPointerTy())
661 return Error(AliaseeLoc, "alias must have pointer type");
663 // Okay, create the alias but do not insert it into the module yet.
664 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
665 (GlobalValue::LinkageTypes)Linkage, Name,
667 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
668 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
670 // See if this value already exists in the symbol table. If so, it is either
671 // a redefinition or a definition of a forward reference.
672 if (GlobalValue *Val = M->getNamedValue(Name)) {
673 // See if this was a redefinition. If so, there is no entry in
675 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
676 I = ForwardRefVals.find(Name);
677 if (I == ForwardRefVals.end())
678 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
680 // Otherwise, this was a definition of forward ref. Verify that types
682 if (Val->getType() != GA->getType())
683 return Error(NameLoc,
684 "forward reference and definition of alias have different types");
686 // If they agree, just RAUW the old value with the alias and remove the
688 Val->replaceAllUsesWith(GA);
689 Val->eraseFromParent();
690 ForwardRefVals.erase(I);
693 // Insert into the module, we know its name won't collide now.
694 M->getAliasList().push_back(GA);
695 assert(GA->getName() == Name && "Should not be a name conflict!");
701 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
702 /// OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
703 /// OptionalExternallyInitialized GlobalType Type Const
704 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
705 /// OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
706 /// OptionalExternallyInitialized GlobalType Type Const
708 /// Everything up to and including OptionalDLLStorageClass has been parsed
711 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
712 unsigned Linkage, bool HasLinkage,
713 unsigned Visibility, unsigned DLLStorageClass) {
715 bool IsConstant, UnnamedAddr, IsExternallyInitialized;
716 GlobalVariable::ThreadLocalMode TLM;
717 LocTy UnnamedAddrLoc;
718 LocTy IsExternallyInitializedLoc;
722 if (ParseOptionalThreadLocal(TLM) ||
723 ParseOptionalAddrSpace(AddrSpace) ||
724 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
726 ParseOptionalToken(lltok::kw_externally_initialized,
727 IsExternallyInitialized,
728 &IsExternallyInitializedLoc) ||
729 ParseGlobalType(IsConstant) ||
730 ParseType(Ty, TyLoc))
733 // If the linkage is specified and is external, then no initializer is
736 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
737 Linkage != GlobalValue::ExternalLinkage)) {
738 if (ParseGlobalValue(Ty, Init))
742 if (Ty->isFunctionTy() || Ty->isLabelTy())
743 return Error(TyLoc, "invalid type for global variable");
745 GlobalVariable *GV = 0;
747 // See if the global was forward referenced, if so, use the global.
749 if (GlobalValue *GVal = M->getNamedValue(Name)) {
750 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
751 return Error(NameLoc, "redefinition of global '@" + Name + "'");
752 GV = cast<GlobalVariable>(GVal);
755 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
756 I = ForwardRefValIDs.find(NumberedVals.size());
757 if (I != ForwardRefValIDs.end()) {
758 GV = cast<GlobalVariable>(I->second.first);
759 ForwardRefValIDs.erase(I);
764 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
765 Name, 0, GlobalVariable::NotThreadLocal,
768 if (GV->getType()->getElementType() != Ty)
770 "forward reference and definition of global have different types");
772 // Move the forward-reference to the correct spot in the module.
773 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
777 NumberedVals.push_back(GV);
779 // Set the parsed properties on the global.
781 GV->setInitializer(Init);
782 GV->setConstant(IsConstant);
783 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
784 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
785 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
786 GV->setExternallyInitialized(IsExternallyInitialized);
787 GV->setThreadLocalMode(TLM);
788 GV->setUnnamedAddr(UnnamedAddr);
790 // Parse attributes on the global.
791 while (Lex.getKind() == lltok::comma) {
794 if (Lex.getKind() == lltok::kw_section) {
796 GV->setSection(Lex.getStrVal());
797 if (ParseToken(lltok::StringConstant, "expected global section string"))
799 } else if (Lex.getKind() == lltok::kw_align) {
801 if (ParseOptionalAlignment(Alignment)) return true;
802 GV->setAlignment(Alignment);
804 TokError("unknown global variable property!");
811 /// ParseUnnamedAttrGrp
812 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
813 bool LLParser::ParseUnnamedAttrGrp() {
814 assert(Lex.getKind() == lltok::kw_attributes);
815 LocTy AttrGrpLoc = Lex.getLoc();
818 assert(Lex.getKind() == lltok::AttrGrpID);
819 unsigned VarID = Lex.getUIntVal();
820 std::vector<unsigned> unused;
824 if (ParseToken(lltok::equal, "expected '=' here") ||
825 ParseToken(lltok::lbrace, "expected '{' here") ||
826 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
828 ParseToken(lltok::rbrace, "expected end of attribute group"))
831 if (!NumberedAttrBuilders[VarID].hasAttributes())
832 return Error(AttrGrpLoc, "attribute group has no attributes");
837 /// ParseFnAttributeValuePairs
838 /// ::= <attr> | <attr> '=' <value>
839 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
840 std::vector<unsigned> &FwdRefAttrGrps,
841 bool inAttrGrp, LocTy &BuiltinLoc) {
842 bool HaveError = false;
847 lltok::Kind Token = Lex.getKind();
848 if (Token == lltok::kw_builtin)
849 BuiltinLoc = Lex.getLoc();
852 if (!inAttrGrp) return HaveError;
853 return Error(Lex.getLoc(), "unterminated attribute group");
858 case lltok::AttrGrpID: {
859 // Allow a function to reference an attribute group:
861 // define void @foo() #1 { ... }
865 "cannot have an attribute group reference in an attribute group");
867 unsigned AttrGrpNum = Lex.getUIntVal();
868 if (inAttrGrp) break;
870 // Save the reference to the attribute group. We'll fill it in later.
871 FwdRefAttrGrps.push_back(AttrGrpNum);
874 // Target-dependent attributes:
875 case lltok::StringConstant: {
876 std::string Attr = Lex.getStrVal();
879 if (EatIfPresent(lltok::equal) &&
880 ParseStringConstant(Val))
883 B.addAttribute(Attr, Val);
887 // Target-independent attributes:
888 case lltok::kw_align: {
889 // As a hack, we allow function alignment to be initially parsed as an
890 // attribute on a function declaration/definition or added to an attribute
891 // group and later moved to the alignment field.
895 if (ParseToken(lltok::equal, "expected '=' here") ||
896 ParseUInt32(Alignment))
899 if (ParseOptionalAlignment(Alignment))
902 B.addAlignmentAttr(Alignment);
905 case lltok::kw_alignstack: {
909 if (ParseToken(lltok::equal, "expected '=' here") ||
910 ParseUInt32(Alignment))
913 if (ParseOptionalStackAlignment(Alignment))
916 B.addStackAlignmentAttr(Alignment);
919 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
920 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
921 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
922 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
923 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
924 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
925 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
926 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
927 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
928 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
929 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
930 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
931 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
932 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
933 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
934 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
935 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
936 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
937 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
938 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
939 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
940 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
941 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
942 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
943 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
944 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
947 case lltok::kw_inreg:
948 case lltok::kw_signext:
949 case lltok::kw_zeroext:
952 "invalid use of attribute on a function");
954 case lltok::kw_byval:
955 case lltok::kw_inalloca:
957 case lltok::kw_noalias:
958 case lltok::kw_nocapture:
959 case lltok::kw_returned:
963 "invalid use of parameter-only attribute on a function");
971 //===----------------------------------------------------------------------===//
972 // GlobalValue Reference/Resolution Routines.
973 //===----------------------------------------------------------------------===//
975 /// GetGlobalVal - Get a value with the specified name or ID, creating a
976 /// forward reference record if needed. This can return null if the value
977 /// exists but does not have the right type.
978 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
980 PointerType *PTy = dyn_cast<PointerType>(Ty);
982 Error(Loc, "global variable reference must have pointer type");
986 // Look this name up in the normal function symbol table.
988 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
990 // If this is a forward reference for the value, see if we already created a
991 // forward ref record.
993 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
994 I = ForwardRefVals.find(Name);
995 if (I != ForwardRefVals.end())
996 Val = I->second.first;
999 // If we have the value in the symbol table or fwd-ref table, return it.
1001 if (Val->getType() == Ty) return Val;
1002 Error(Loc, "'@" + Name + "' defined with type '" +
1003 getTypeString(Val->getType()) + "'");
1007 // Otherwise, create a new forward reference for this value and remember it.
1008 GlobalValue *FwdVal;
1009 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1010 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1012 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1013 GlobalValue::ExternalWeakLinkage, 0, Name,
1014 0, GlobalVariable::NotThreadLocal,
1015 PTy->getAddressSpace());
1017 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1021 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1022 PointerType *PTy = dyn_cast<PointerType>(Ty);
1024 Error(Loc, "global variable reference must have pointer type");
1028 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1030 // If this is a forward reference for the value, see if we already created a
1031 // forward ref record.
1033 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1034 I = ForwardRefValIDs.find(ID);
1035 if (I != ForwardRefValIDs.end())
1036 Val = I->second.first;
1039 // If we have the value in the symbol table or fwd-ref table, return it.
1041 if (Val->getType() == Ty) return Val;
1042 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1043 getTypeString(Val->getType()) + "'");
1047 // Otherwise, create a new forward reference for this value and remember it.
1048 GlobalValue *FwdVal;
1049 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1050 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1052 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1053 GlobalValue::ExternalWeakLinkage, 0, "");
1055 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1060 //===----------------------------------------------------------------------===//
1062 //===----------------------------------------------------------------------===//
1064 /// ParseToken - If the current token has the specified kind, eat it and return
1065 /// success. Otherwise, emit the specified error and return failure.
1066 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1067 if (Lex.getKind() != T)
1068 return TokError(ErrMsg);
1073 /// ParseStringConstant
1074 /// ::= StringConstant
1075 bool LLParser::ParseStringConstant(std::string &Result) {
1076 if (Lex.getKind() != lltok::StringConstant)
1077 return TokError("expected string constant");
1078 Result = Lex.getStrVal();
1085 bool LLParser::ParseUInt32(unsigned &Val) {
1086 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1087 return TokError("expected integer");
1088 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1089 if (Val64 != unsigned(Val64))
1090 return TokError("expected 32-bit integer (too large)");
1097 /// := 'localdynamic'
1098 /// := 'initialexec'
1100 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1101 switch (Lex.getKind()) {
1103 return TokError("expected localdynamic, initialexec or localexec");
1104 case lltok::kw_localdynamic:
1105 TLM = GlobalVariable::LocalDynamicTLSModel;
1107 case lltok::kw_initialexec:
1108 TLM = GlobalVariable::InitialExecTLSModel;
1110 case lltok::kw_localexec:
1111 TLM = GlobalVariable::LocalExecTLSModel;
1119 /// ParseOptionalThreadLocal
1121 /// := 'thread_local'
1122 /// := 'thread_local' '(' tlsmodel ')'
1123 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1124 TLM = GlobalVariable::NotThreadLocal;
1125 if (!EatIfPresent(lltok::kw_thread_local))
1128 TLM = GlobalVariable::GeneralDynamicTLSModel;
1129 if (Lex.getKind() == lltok::lparen) {
1131 return ParseTLSModel(TLM) ||
1132 ParseToken(lltok::rparen, "expected ')' after thread local model");
1137 /// ParseOptionalAddrSpace
1139 /// := 'addrspace' '(' uint32 ')'
1140 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1142 if (!EatIfPresent(lltok::kw_addrspace))
1144 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1145 ParseUInt32(AddrSpace) ||
1146 ParseToken(lltok::rparen, "expected ')' in address space");
1149 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1150 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1151 bool HaveError = false;
1156 lltok::Kind Token = Lex.getKind();
1158 default: // End of attributes.
1160 case lltok::kw_align: {
1162 if (ParseOptionalAlignment(Alignment))
1164 B.addAlignmentAttr(Alignment);
1167 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1168 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1169 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1170 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1171 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1172 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1173 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1174 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1175 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1176 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1177 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1178 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1180 case lltok::kw_alignstack:
1181 case lltok::kw_alwaysinline:
1182 case lltok::kw_builtin:
1183 case lltok::kw_inlinehint:
1184 case lltok::kw_minsize:
1185 case lltok::kw_naked:
1186 case lltok::kw_nobuiltin:
1187 case lltok::kw_noduplicate:
1188 case lltok::kw_noimplicitfloat:
1189 case lltok::kw_noinline:
1190 case lltok::kw_nonlazybind:
1191 case lltok::kw_noredzone:
1192 case lltok::kw_noreturn:
1193 case lltok::kw_nounwind:
1194 case lltok::kw_optnone:
1195 case lltok::kw_optsize:
1196 case lltok::kw_returns_twice:
1197 case lltok::kw_sanitize_address:
1198 case lltok::kw_sanitize_memory:
1199 case lltok::kw_sanitize_thread:
1201 case lltok::kw_sspreq:
1202 case lltok::kw_sspstrong:
1203 case lltok::kw_uwtable:
1204 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1212 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1213 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1214 bool HaveError = false;
1219 lltok::Kind Token = Lex.getKind();
1221 default: // End of attributes.
1223 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1224 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1225 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1226 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1229 case lltok::kw_align:
1230 case lltok::kw_byval:
1231 case lltok::kw_inalloca:
1232 case lltok::kw_nest:
1233 case lltok::kw_nocapture:
1234 case lltok::kw_returned:
1235 case lltok::kw_sret:
1236 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1239 case lltok::kw_alignstack:
1240 case lltok::kw_alwaysinline:
1241 case lltok::kw_builtin:
1242 case lltok::kw_cold:
1243 case lltok::kw_inlinehint:
1244 case lltok::kw_minsize:
1245 case lltok::kw_naked:
1246 case lltok::kw_nobuiltin:
1247 case lltok::kw_noduplicate:
1248 case lltok::kw_noimplicitfloat:
1249 case lltok::kw_noinline:
1250 case lltok::kw_nonlazybind:
1251 case lltok::kw_noredzone:
1252 case lltok::kw_noreturn:
1253 case lltok::kw_nounwind:
1254 case lltok::kw_optnone:
1255 case lltok::kw_optsize:
1256 case lltok::kw_returns_twice:
1257 case lltok::kw_sanitize_address:
1258 case lltok::kw_sanitize_memory:
1259 case lltok::kw_sanitize_thread:
1261 case lltok::kw_sspreq:
1262 case lltok::kw_sspstrong:
1263 case lltok::kw_uwtable:
1264 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1267 case lltok::kw_readnone:
1268 case lltok::kw_readonly:
1269 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1276 /// ParseOptionalLinkage
1283 /// ::= 'linkonce_odr'
1284 /// ::= 'available_externally'
1287 /// ::= 'extern_weak'
1289 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1291 switch (Lex.getKind()) {
1292 default: Res=GlobalValue::ExternalLinkage; return false;
1293 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1294 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1295 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1296 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1297 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1298 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1299 case lltok::kw_available_externally:
1300 Res = GlobalValue::AvailableExternallyLinkage;
1302 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1303 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1304 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1305 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1312 /// ParseOptionalVisibility
1318 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1319 switch (Lex.getKind()) {
1320 default: Res = GlobalValue::DefaultVisibility; return false;
1321 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1322 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1323 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1329 /// ParseOptionalDLLStorageClass
1334 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1335 switch (Lex.getKind()) {
1336 default: Res = GlobalValue::DefaultStorageClass; return false;
1337 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1338 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1344 /// ParseOptionalCallingConv
1348 /// ::= 'kw_intel_ocl_bicc'
1350 /// ::= 'x86_stdcallcc'
1351 /// ::= 'x86_fastcallcc'
1352 /// ::= 'x86_thiscallcc'
1353 /// ::= 'x86_cdeclmethodcc'
1354 /// ::= 'arm_apcscc'
1355 /// ::= 'arm_aapcscc'
1356 /// ::= 'arm_aapcs_vfpcc'
1357 /// ::= 'msp430_intrcc'
1358 /// ::= 'ptx_kernel'
1359 /// ::= 'ptx_device'
1361 /// ::= 'spir_kernel'
1362 /// ::= 'x86_64_sysvcc'
1363 /// ::= 'x86_64_win64cc'
1364 /// ::= 'webkit_jscc'
1366 /// ::= 'preserve_mostcc'
1367 /// ::= 'preserve_allcc'
1370 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1371 switch (Lex.getKind()) {
1372 default: CC = CallingConv::C; return false;
1373 case lltok::kw_ccc: CC = CallingConv::C; break;
1374 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1375 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1376 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1377 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1378 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1379 case lltok::kw_x86_cdeclmethodcc:CC = CallingConv::X86_CDeclMethod; break;
1380 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1381 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1382 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1383 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1384 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1385 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1386 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1387 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1388 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1389 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1390 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1391 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1392 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1393 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1394 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1395 case lltok::kw_cc: {
1396 unsigned ArbitraryCC;
1398 if (ParseUInt32(ArbitraryCC))
1400 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1409 /// ParseInstructionMetadata
1410 /// ::= !dbg !42 (',' !dbg !57)*
1411 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1412 PerFunctionState *PFS) {
1414 if (Lex.getKind() != lltok::MetadataVar)
1415 return TokError("expected metadata after comma");
1417 std::string Name = Lex.getStrVal();
1418 unsigned MDK = M->getMDKindID(Name);
1422 SMLoc Loc = Lex.getLoc();
1424 if (ParseToken(lltok::exclaim, "expected '!' here"))
1427 // This code is similar to that of ParseMetadataValue, however it needs to
1428 // have special-case code for a forward reference; see the comments on
1429 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1430 // at the top level here.
1431 if (Lex.getKind() == lltok::lbrace) {
1433 if (ParseMetadataListValue(ID, PFS))
1435 assert(ID.Kind == ValID::t_MDNode);
1436 Inst->setMetadata(MDK, ID.MDNodeVal);
1438 unsigned NodeID = 0;
1439 if (ParseMDNodeID(Node, NodeID))
1442 // If we got the node, add it to the instruction.
1443 Inst->setMetadata(MDK, Node);
1445 MDRef R = { Loc, MDK, NodeID };
1446 // Otherwise, remember that this should be resolved later.
1447 ForwardRefInstMetadata[Inst].push_back(R);
1451 if (MDK == LLVMContext::MD_tbaa)
1452 InstsWithTBAATag.push_back(Inst);
1454 // If this is the end of the list, we're done.
1455 } while (EatIfPresent(lltok::comma));
1459 /// ParseOptionalAlignment
1462 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1464 if (!EatIfPresent(lltok::kw_align))
1466 LocTy AlignLoc = Lex.getLoc();
1467 if (ParseUInt32(Alignment)) return true;
1468 if (!isPowerOf2_32(Alignment))
1469 return Error(AlignLoc, "alignment is not a power of two");
1470 if (Alignment > Value::MaximumAlignment)
1471 return Error(AlignLoc, "huge alignments are not supported yet");
1475 /// ParseOptionalCommaAlign
1479 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1481 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1482 bool &AteExtraComma) {
1483 AteExtraComma = false;
1484 while (EatIfPresent(lltok::comma)) {
1485 // Metadata at the end is an early exit.
1486 if (Lex.getKind() == lltok::MetadataVar) {
1487 AteExtraComma = true;
1491 if (Lex.getKind() != lltok::kw_align)
1492 return Error(Lex.getLoc(), "expected metadata or 'align'");
1494 if (ParseOptionalAlignment(Alignment)) return true;
1500 /// ParseScopeAndOrdering
1501 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1504 /// This sets Scope and Ordering to the parsed values.
1505 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1506 AtomicOrdering &Ordering) {
1510 Scope = CrossThread;
1511 if (EatIfPresent(lltok::kw_singlethread))
1512 Scope = SingleThread;
1514 return ParseOrdering(Ordering);
1518 /// ::= AtomicOrdering
1520 /// This sets Ordering to the parsed value.
1521 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1522 switch (Lex.getKind()) {
1523 default: return TokError("Expected ordering on atomic instruction");
1524 case lltok::kw_unordered: Ordering = Unordered; break;
1525 case lltok::kw_monotonic: Ordering = Monotonic; break;
1526 case lltok::kw_acquire: Ordering = Acquire; break;
1527 case lltok::kw_release: Ordering = Release; break;
1528 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1529 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1535 /// ParseOptionalStackAlignment
1537 /// ::= 'alignstack' '(' 4 ')'
1538 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1540 if (!EatIfPresent(lltok::kw_alignstack))
1542 LocTy ParenLoc = Lex.getLoc();
1543 if (!EatIfPresent(lltok::lparen))
1544 return Error(ParenLoc, "expected '('");
1545 LocTy AlignLoc = Lex.getLoc();
1546 if (ParseUInt32(Alignment)) return true;
1547 ParenLoc = Lex.getLoc();
1548 if (!EatIfPresent(lltok::rparen))
1549 return Error(ParenLoc, "expected ')'");
1550 if (!isPowerOf2_32(Alignment))
1551 return Error(AlignLoc, "stack alignment is not a power of two");
1555 /// ParseIndexList - This parses the index list for an insert/extractvalue
1556 /// instruction. This sets AteExtraComma in the case where we eat an extra
1557 /// comma at the end of the line and find that it is followed by metadata.
1558 /// Clients that don't allow metadata can call the version of this function that
1559 /// only takes one argument.
1562 /// ::= (',' uint32)+
1564 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1565 bool &AteExtraComma) {
1566 AteExtraComma = false;
1568 if (Lex.getKind() != lltok::comma)
1569 return TokError("expected ',' as start of index list");
1571 while (EatIfPresent(lltok::comma)) {
1572 if (Lex.getKind() == lltok::MetadataVar) {
1573 AteExtraComma = true;
1577 if (ParseUInt32(Idx)) return true;
1578 Indices.push_back(Idx);
1584 //===----------------------------------------------------------------------===//
1586 //===----------------------------------------------------------------------===//
1588 /// ParseType - Parse a type.
1589 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1590 SMLoc TypeLoc = Lex.getLoc();
1591 switch (Lex.getKind()) {
1593 return TokError("expected type");
1595 // Type ::= 'float' | 'void' (etc)
1596 Result = Lex.getTyVal();
1600 // Type ::= StructType
1601 if (ParseAnonStructType(Result, false))
1604 case lltok::lsquare:
1605 // Type ::= '[' ... ']'
1606 Lex.Lex(); // eat the lsquare.
1607 if (ParseArrayVectorType(Result, false))
1610 case lltok::less: // Either vector or packed struct.
1611 // Type ::= '<' ... '>'
1613 if (Lex.getKind() == lltok::lbrace) {
1614 if (ParseAnonStructType(Result, true) ||
1615 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1617 } else if (ParseArrayVectorType(Result, true))
1620 case lltok::LocalVar: {
1622 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1624 // If the type hasn't been defined yet, create a forward definition and
1625 // remember where that forward def'n was seen (in case it never is defined).
1626 if (Entry.first == 0) {
1627 Entry.first = StructType::create(Context, Lex.getStrVal());
1628 Entry.second = Lex.getLoc();
1630 Result = Entry.first;
1635 case lltok::LocalVarID: {
1637 if (Lex.getUIntVal() >= NumberedTypes.size())
1638 NumberedTypes.resize(Lex.getUIntVal()+1);
1639 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1641 // If the type hasn't been defined yet, create a forward definition and
1642 // remember where that forward def'n was seen (in case it never is defined).
1643 if (Entry.first == 0) {
1644 Entry.first = StructType::create(Context);
1645 Entry.second = Lex.getLoc();
1647 Result = Entry.first;
1653 // Parse the type suffixes.
1655 switch (Lex.getKind()) {
1658 if (!AllowVoid && Result->isVoidTy())
1659 return Error(TypeLoc, "void type only allowed for function results");
1662 // Type ::= Type '*'
1664 if (Result->isLabelTy())
1665 return TokError("basic block pointers are invalid");
1666 if (Result->isVoidTy())
1667 return TokError("pointers to void are invalid - use i8* instead");
1668 if (!PointerType::isValidElementType(Result))
1669 return TokError("pointer to this type is invalid");
1670 Result = PointerType::getUnqual(Result);
1674 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1675 case lltok::kw_addrspace: {
1676 if (Result->isLabelTy())
1677 return TokError("basic block pointers are invalid");
1678 if (Result->isVoidTy())
1679 return TokError("pointers to void are invalid; use i8* instead");
1680 if (!PointerType::isValidElementType(Result))
1681 return TokError("pointer to this type is invalid");
1683 if (ParseOptionalAddrSpace(AddrSpace) ||
1684 ParseToken(lltok::star, "expected '*' in address space"))
1687 Result = PointerType::get(Result, AddrSpace);
1691 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1693 if (ParseFunctionType(Result))
1700 /// ParseParameterList
1702 /// ::= '(' Arg (',' Arg)* ')'
1704 /// ::= Type OptionalAttributes Value OptionalAttributes
1705 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1706 PerFunctionState &PFS) {
1707 if (ParseToken(lltok::lparen, "expected '(' in call"))
1710 unsigned AttrIndex = 1;
1711 while (Lex.getKind() != lltok::rparen) {
1712 // If this isn't the first argument, we need a comma.
1713 if (!ArgList.empty() &&
1714 ParseToken(lltok::comma, "expected ',' in argument list"))
1717 // Parse the argument.
1720 AttrBuilder ArgAttrs;
1722 if (ParseType(ArgTy, ArgLoc))
1725 // Otherwise, handle normal operands.
1726 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1728 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1733 Lex.Lex(); // Lex the ')'.
1739 /// ParseArgumentList - Parse the argument list for a function type or function
1741 /// ::= '(' ArgTypeListI ')'
1745 /// ::= ArgTypeList ',' '...'
1746 /// ::= ArgType (',' ArgType)*
1748 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1751 assert(Lex.getKind() == lltok::lparen);
1752 Lex.Lex(); // eat the (.
1754 if (Lex.getKind() == lltok::rparen) {
1756 } else if (Lex.getKind() == lltok::dotdotdot) {
1760 LocTy TypeLoc = Lex.getLoc();
1765 if (ParseType(ArgTy) ||
1766 ParseOptionalParamAttrs(Attrs)) return true;
1768 if (ArgTy->isVoidTy())
1769 return Error(TypeLoc, "argument can not have void type");
1771 if (Lex.getKind() == lltok::LocalVar) {
1772 Name = Lex.getStrVal();
1776 if (!FunctionType::isValidArgumentType(ArgTy))
1777 return Error(TypeLoc, "invalid type for function argument");
1779 unsigned AttrIndex = 1;
1780 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1781 AttributeSet::get(ArgTy->getContext(),
1782 AttrIndex++, Attrs), Name));
1784 while (EatIfPresent(lltok::comma)) {
1785 // Handle ... at end of arg list.
1786 if (EatIfPresent(lltok::dotdotdot)) {
1791 // Otherwise must be an argument type.
1792 TypeLoc = Lex.getLoc();
1793 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1795 if (ArgTy->isVoidTy())
1796 return Error(TypeLoc, "argument can not have void type");
1798 if (Lex.getKind() == lltok::LocalVar) {
1799 Name = Lex.getStrVal();
1805 if (!ArgTy->isFirstClassType())
1806 return Error(TypeLoc, "invalid type for function argument");
1808 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1809 AttributeSet::get(ArgTy->getContext(),
1810 AttrIndex++, Attrs),
1815 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1818 /// ParseFunctionType
1819 /// ::= Type ArgumentList OptionalAttrs
1820 bool LLParser::ParseFunctionType(Type *&Result) {
1821 assert(Lex.getKind() == lltok::lparen);
1823 if (!FunctionType::isValidReturnType(Result))
1824 return TokError("invalid function return type");
1826 SmallVector<ArgInfo, 8> ArgList;
1828 if (ParseArgumentList(ArgList, isVarArg))
1831 // Reject names on the arguments lists.
1832 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1833 if (!ArgList[i].Name.empty())
1834 return Error(ArgList[i].Loc, "argument name invalid in function type");
1835 if (ArgList[i].Attrs.hasAttributes(i + 1))
1836 return Error(ArgList[i].Loc,
1837 "argument attributes invalid in function type");
1840 SmallVector<Type*, 16> ArgListTy;
1841 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1842 ArgListTy.push_back(ArgList[i].Ty);
1844 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1848 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1850 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1851 SmallVector<Type*, 8> Elts;
1852 if (ParseStructBody(Elts)) return true;
1854 Result = StructType::get(Context, Elts, Packed);
1858 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1859 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1860 std::pair<Type*, LocTy> &Entry,
1862 // If the type was already defined, diagnose the redefinition.
1863 if (Entry.first && !Entry.second.isValid())
1864 return Error(TypeLoc, "redefinition of type");
1866 // If we have opaque, just return without filling in the definition for the
1867 // struct. This counts as a definition as far as the .ll file goes.
1868 if (EatIfPresent(lltok::kw_opaque)) {
1869 // This type is being defined, so clear the location to indicate this.
1870 Entry.second = SMLoc();
1872 // If this type number has never been uttered, create it.
1873 if (Entry.first == 0)
1874 Entry.first = StructType::create(Context, Name);
1875 ResultTy = Entry.first;
1879 // If the type starts with '<', then it is either a packed struct or a vector.
1880 bool isPacked = EatIfPresent(lltok::less);
1882 // If we don't have a struct, then we have a random type alias, which we
1883 // accept for compatibility with old files. These types are not allowed to be
1884 // forward referenced and not allowed to be recursive.
1885 if (Lex.getKind() != lltok::lbrace) {
1887 return Error(TypeLoc, "forward references to non-struct type");
1891 return ParseArrayVectorType(ResultTy, true);
1892 return ParseType(ResultTy);
1895 // This type is being defined, so clear the location to indicate this.
1896 Entry.second = SMLoc();
1898 // If this type number has never been uttered, create it.
1899 if (Entry.first == 0)
1900 Entry.first = StructType::create(Context, Name);
1902 StructType *STy = cast<StructType>(Entry.first);
1904 SmallVector<Type*, 8> Body;
1905 if (ParseStructBody(Body) ||
1906 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1909 STy->setBody(Body, isPacked);
1915 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1918 /// ::= '{' Type (',' Type)* '}'
1919 /// ::= '<' '{' '}' '>'
1920 /// ::= '<' '{' Type (',' Type)* '}' '>'
1921 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
1922 assert(Lex.getKind() == lltok::lbrace);
1923 Lex.Lex(); // Consume the '{'
1925 // Handle the empty struct.
1926 if (EatIfPresent(lltok::rbrace))
1929 LocTy EltTyLoc = Lex.getLoc();
1931 if (ParseType(Ty)) return true;
1934 if (!StructType::isValidElementType(Ty))
1935 return Error(EltTyLoc, "invalid element type for struct");
1937 while (EatIfPresent(lltok::comma)) {
1938 EltTyLoc = Lex.getLoc();
1939 if (ParseType(Ty)) return true;
1941 if (!StructType::isValidElementType(Ty))
1942 return Error(EltTyLoc, "invalid element type for struct");
1947 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
1950 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1951 /// token has already been consumed.
1953 /// ::= '[' APSINTVAL 'x' Types ']'
1954 /// ::= '<' APSINTVAL 'x' Types '>'
1955 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
1956 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1957 Lex.getAPSIntVal().getBitWidth() > 64)
1958 return TokError("expected number in address space");
1960 LocTy SizeLoc = Lex.getLoc();
1961 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1964 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1967 LocTy TypeLoc = Lex.getLoc();
1969 if (ParseType(EltTy)) return true;
1971 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1972 "expected end of sequential type"))
1977 return Error(SizeLoc, "zero element vector is illegal");
1978 if ((unsigned)Size != Size)
1979 return Error(SizeLoc, "size too large for vector");
1980 if (!VectorType::isValidElementType(EltTy))
1981 return Error(TypeLoc, "invalid vector element type");
1982 Result = VectorType::get(EltTy, unsigned(Size));
1984 if (!ArrayType::isValidElementType(EltTy))
1985 return Error(TypeLoc, "invalid array element type");
1986 Result = ArrayType::get(EltTy, Size);
1991 //===----------------------------------------------------------------------===//
1992 // Function Semantic Analysis.
1993 //===----------------------------------------------------------------------===//
1995 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1997 : P(p), F(f), FunctionNumber(functionNumber) {
1999 // Insert unnamed arguments into the NumberedVals list.
2000 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2003 NumberedVals.push_back(AI);
2006 LLParser::PerFunctionState::~PerFunctionState() {
2007 // If there were any forward referenced non-basicblock values, delete them.
2008 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2009 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2010 if (!isa<BasicBlock>(I->second.first)) {
2011 I->second.first->replaceAllUsesWith(
2012 UndefValue::get(I->second.first->getType()));
2013 delete I->second.first;
2014 I->second.first = 0;
2017 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2018 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2019 if (!isa<BasicBlock>(I->second.first)) {
2020 I->second.first->replaceAllUsesWith(
2021 UndefValue::get(I->second.first->getType()));
2022 delete I->second.first;
2023 I->second.first = 0;
2027 bool LLParser::PerFunctionState::FinishFunction() {
2028 // Check to see if someone took the address of labels in this block.
2029 if (!P.ForwardRefBlockAddresses.empty()) {
2031 if (!F.getName().empty()) {
2032 FunctionID.Kind = ValID::t_GlobalName;
2033 FunctionID.StrVal = F.getName();
2035 FunctionID.Kind = ValID::t_GlobalID;
2036 FunctionID.UIntVal = FunctionNumber;
2039 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
2040 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
2041 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
2042 // Resolve all these references.
2043 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
2046 P.ForwardRefBlockAddresses.erase(FRBAI);
2050 if (!ForwardRefVals.empty())
2051 return P.Error(ForwardRefVals.begin()->second.second,
2052 "use of undefined value '%" + ForwardRefVals.begin()->first +
2054 if (!ForwardRefValIDs.empty())
2055 return P.Error(ForwardRefValIDs.begin()->second.second,
2056 "use of undefined value '%" +
2057 Twine(ForwardRefValIDs.begin()->first) + "'");
2062 /// GetVal - Get a value with the specified name or ID, creating a
2063 /// forward reference record if needed. This can return null if the value
2064 /// exists but does not have the right type.
2065 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2066 Type *Ty, LocTy Loc) {
2067 // Look this name up in the normal function symbol table.
2068 Value *Val = F.getValueSymbolTable().lookup(Name);
2070 // If this is a forward reference for the value, see if we already created a
2071 // forward ref record.
2073 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2074 I = ForwardRefVals.find(Name);
2075 if (I != ForwardRefVals.end())
2076 Val = I->second.first;
2079 // If we have the value in the symbol table or fwd-ref table, return it.
2081 if (Val->getType() == Ty) return Val;
2082 if (Ty->isLabelTy())
2083 P.Error(Loc, "'%" + Name + "' is not a basic block");
2085 P.Error(Loc, "'%" + Name + "' defined with type '" +
2086 getTypeString(Val->getType()) + "'");
2090 // Don't make placeholders with invalid type.
2091 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2092 P.Error(Loc, "invalid use of a non-first-class type");
2096 // Otherwise, create a new forward reference for this value and remember it.
2098 if (Ty->isLabelTy())
2099 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2101 FwdVal = new Argument(Ty, Name);
2103 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2107 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2109 // Look this name up in the normal function symbol table.
2110 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
2112 // If this is a forward reference for the value, see if we already created a
2113 // forward ref record.
2115 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2116 I = ForwardRefValIDs.find(ID);
2117 if (I != ForwardRefValIDs.end())
2118 Val = I->second.first;
2121 // If we have the value in the symbol table or fwd-ref table, return it.
2123 if (Val->getType() == Ty) return Val;
2124 if (Ty->isLabelTy())
2125 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2127 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2128 getTypeString(Val->getType()) + "'");
2132 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2133 P.Error(Loc, "invalid use of a non-first-class type");
2137 // Otherwise, create a new forward reference for this value and remember it.
2139 if (Ty->isLabelTy())
2140 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2142 FwdVal = new Argument(Ty);
2144 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2148 /// SetInstName - After an instruction is parsed and inserted into its
2149 /// basic block, this installs its name.
2150 bool LLParser::PerFunctionState::SetInstName(int NameID,
2151 const std::string &NameStr,
2152 LocTy NameLoc, Instruction *Inst) {
2153 // If this instruction has void type, it cannot have a name or ID specified.
2154 if (Inst->getType()->isVoidTy()) {
2155 if (NameID != -1 || !NameStr.empty())
2156 return P.Error(NameLoc, "instructions returning void cannot have a name");
2160 // If this was a numbered instruction, verify that the instruction is the
2161 // expected value and resolve any forward references.
2162 if (NameStr.empty()) {
2163 // If neither a name nor an ID was specified, just use the next ID.
2165 NameID = NumberedVals.size();
2167 if (unsigned(NameID) != NumberedVals.size())
2168 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2169 Twine(NumberedVals.size()) + "'");
2171 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2172 ForwardRefValIDs.find(NameID);
2173 if (FI != ForwardRefValIDs.end()) {
2174 if (FI->second.first->getType() != Inst->getType())
2175 return P.Error(NameLoc, "instruction forward referenced with type '" +
2176 getTypeString(FI->second.first->getType()) + "'");
2177 FI->second.first->replaceAllUsesWith(Inst);
2178 delete FI->second.first;
2179 ForwardRefValIDs.erase(FI);
2182 NumberedVals.push_back(Inst);
2186 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2187 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2188 FI = ForwardRefVals.find(NameStr);
2189 if (FI != ForwardRefVals.end()) {
2190 if (FI->second.first->getType() != Inst->getType())
2191 return P.Error(NameLoc, "instruction forward referenced with type '" +
2192 getTypeString(FI->second.first->getType()) + "'");
2193 FI->second.first->replaceAllUsesWith(Inst);
2194 delete FI->second.first;
2195 ForwardRefVals.erase(FI);
2198 // Set the name on the instruction.
2199 Inst->setName(NameStr);
2201 if (Inst->getName() != NameStr)
2202 return P.Error(NameLoc, "multiple definition of local value named '" +
2207 /// GetBB - Get a basic block with the specified name or ID, creating a
2208 /// forward reference record if needed.
2209 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2211 return cast_or_null<BasicBlock>(GetVal(Name,
2212 Type::getLabelTy(F.getContext()), Loc));
2215 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2216 return cast_or_null<BasicBlock>(GetVal(ID,
2217 Type::getLabelTy(F.getContext()), Loc));
2220 /// DefineBB - Define the specified basic block, which is either named or
2221 /// unnamed. If there is an error, this returns null otherwise it returns
2222 /// the block being defined.
2223 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2227 BB = GetBB(NumberedVals.size(), Loc);
2229 BB = GetBB(Name, Loc);
2230 if (BB == 0) return 0; // Already diagnosed error.
2232 // Move the block to the end of the function. Forward ref'd blocks are
2233 // inserted wherever they happen to be referenced.
2234 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2236 // Remove the block from forward ref sets.
2238 ForwardRefValIDs.erase(NumberedVals.size());
2239 NumberedVals.push_back(BB);
2241 // BB forward references are already in the function symbol table.
2242 ForwardRefVals.erase(Name);
2248 //===----------------------------------------------------------------------===//
2250 //===----------------------------------------------------------------------===//
2252 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2253 /// type implied. For example, if we parse "4" we don't know what integer type
2254 /// it has. The value will later be combined with its type and checked for
2255 /// sanity. PFS is used to convert function-local operands of metadata (since
2256 /// metadata operands are not just parsed here but also converted to values).
2257 /// PFS can be null when we are not parsing metadata values inside a function.
2258 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2259 ID.Loc = Lex.getLoc();
2260 switch (Lex.getKind()) {
2261 default: return TokError("expected value token");
2262 case lltok::GlobalID: // @42
2263 ID.UIntVal = Lex.getUIntVal();
2264 ID.Kind = ValID::t_GlobalID;
2266 case lltok::GlobalVar: // @foo
2267 ID.StrVal = Lex.getStrVal();
2268 ID.Kind = ValID::t_GlobalName;
2270 case lltok::LocalVarID: // %42
2271 ID.UIntVal = Lex.getUIntVal();
2272 ID.Kind = ValID::t_LocalID;
2274 case lltok::LocalVar: // %foo
2275 ID.StrVal = Lex.getStrVal();
2276 ID.Kind = ValID::t_LocalName;
2278 case lltok::exclaim: // !42, !{...}, or !"foo"
2279 return ParseMetadataValue(ID, PFS);
2281 ID.APSIntVal = Lex.getAPSIntVal();
2282 ID.Kind = ValID::t_APSInt;
2284 case lltok::APFloat:
2285 ID.APFloatVal = Lex.getAPFloatVal();
2286 ID.Kind = ValID::t_APFloat;
2288 case lltok::kw_true:
2289 ID.ConstantVal = ConstantInt::getTrue(Context);
2290 ID.Kind = ValID::t_Constant;
2292 case lltok::kw_false:
2293 ID.ConstantVal = ConstantInt::getFalse(Context);
2294 ID.Kind = ValID::t_Constant;
2296 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2297 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2298 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2300 case lltok::lbrace: {
2301 // ValID ::= '{' ConstVector '}'
2303 SmallVector<Constant*, 16> Elts;
2304 if (ParseGlobalValueVector(Elts) ||
2305 ParseToken(lltok::rbrace, "expected end of struct constant"))
2308 ID.ConstantStructElts = new Constant*[Elts.size()];
2309 ID.UIntVal = Elts.size();
2310 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2311 ID.Kind = ValID::t_ConstantStruct;
2315 // ValID ::= '<' ConstVector '>' --> Vector.
2316 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2318 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2320 SmallVector<Constant*, 16> Elts;
2321 LocTy FirstEltLoc = Lex.getLoc();
2322 if (ParseGlobalValueVector(Elts) ||
2324 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2325 ParseToken(lltok::greater, "expected end of constant"))
2328 if (isPackedStruct) {
2329 ID.ConstantStructElts = new Constant*[Elts.size()];
2330 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2331 ID.UIntVal = Elts.size();
2332 ID.Kind = ValID::t_PackedConstantStruct;
2337 return Error(ID.Loc, "constant vector must not be empty");
2339 if (!Elts[0]->getType()->isIntegerTy() &&
2340 !Elts[0]->getType()->isFloatingPointTy() &&
2341 !Elts[0]->getType()->isPointerTy())
2342 return Error(FirstEltLoc,
2343 "vector elements must have integer, pointer or floating point type");
2345 // Verify that all the vector elements have the same type.
2346 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2347 if (Elts[i]->getType() != Elts[0]->getType())
2348 return Error(FirstEltLoc,
2349 "vector element #" + Twine(i) +
2350 " is not of type '" + getTypeString(Elts[0]->getType()));
2352 ID.ConstantVal = ConstantVector::get(Elts);
2353 ID.Kind = ValID::t_Constant;
2356 case lltok::lsquare: { // Array Constant
2358 SmallVector<Constant*, 16> Elts;
2359 LocTy FirstEltLoc = Lex.getLoc();
2360 if (ParseGlobalValueVector(Elts) ||
2361 ParseToken(lltok::rsquare, "expected end of array constant"))
2364 // Handle empty element.
2366 // Use undef instead of an array because it's inconvenient to determine
2367 // the element type at this point, there being no elements to examine.
2368 ID.Kind = ValID::t_EmptyArray;
2372 if (!Elts[0]->getType()->isFirstClassType())
2373 return Error(FirstEltLoc, "invalid array element type: " +
2374 getTypeString(Elts[0]->getType()));
2376 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2378 // Verify all elements are correct type!
2379 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2380 if (Elts[i]->getType() != Elts[0]->getType())
2381 return Error(FirstEltLoc,
2382 "array element #" + Twine(i) +
2383 " is not of type '" + getTypeString(Elts[0]->getType()));
2386 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2387 ID.Kind = ValID::t_Constant;
2390 case lltok::kw_c: // c "foo"
2392 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2394 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2395 ID.Kind = ValID::t_Constant;
2398 case lltok::kw_asm: {
2399 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2401 bool HasSideEffect, AlignStack, AsmDialect;
2403 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2404 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2405 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2406 ParseStringConstant(ID.StrVal) ||
2407 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2408 ParseToken(lltok::StringConstant, "expected constraint string"))
2410 ID.StrVal2 = Lex.getStrVal();
2411 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2412 (unsigned(AsmDialect)<<2);
2413 ID.Kind = ValID::t_InlineAsm;
2417 case lltok::kw_blockaddress: {
2418 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2423 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2425 ParseToken(lltok::comma, "expected comma in block address expression")||
2426 ParseValID(Label) ||
2427 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2430 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2431 return Error(Fn.Loc, "expected function name in blockaddress");
2432 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2433 return Error(Label.Loc, "expected basic block name in blockaddress");
2435 // Make a global variable as a placeholder for this reference.
2436 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2437 false, GlobalValue::InternalLinkage,
2439 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2440 ID.ConstantVal = FwdRef;
2441 ID.Kind = ValID::t_Constant;
2445 case lltok::kw_trunc:
2446 case lltok::kw_zext:
2447 case lltok::kw_sext:
2448 case lltok::kw_fptrunc:
2449 case lltok::kw_fpext:
2450 case lltok::kw_bitcast:
2451 case lltok::kw_addrspacecast:
2452 case lltok::kw_uitofp:
2453 case lltok::kw_sitofp:
2454 case lltok::kw_fptoui:
2455 case lltok::kw_fptosi:
2456 case lltok::kw_inttoptr:
2457 case lltok::kw_ptrtoint: {
2458 unsigned Opc = Lex.getUIntVal();
2462 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2463 ParseGlobalTypeAndValue(SrcVal) ||
2464 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2465 ParseType(DestTy) ||
2466 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2468 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2469 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2470 getTypeString(SrcVal->getType()) + "' to '" +
2471 getTypeString(DestTy) + "'");
2472 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2474 ID.Kind = ValID::t_Constant;
2477 case lltok::kw_extractvalue: {
2480 SmallVector<unsigned, 4> Indices;
2481 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2482 ParseGlobalTypeAndValue(Val) ||
2483 ParseIndexList(Indices) ||
2484 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2487 if (!Val->getType()->isAggregateType())
2488 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2489 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2490 return Error(ID.Loc, "invalid indices for extractvalue");
2491 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2492 ID.Kind = ValID::t_Constant;
2495 case lltok::kw_insertvalue: {
2497 Constant *Val0, *Val1;
2498 SmallVector<unsigned, 4> Indices;
2499 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2500 ParseGlobalTypeAndValue(Val0) ||
2501 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2502 ParseGlobalTypeAndValue(Val1) ||
2503 ParseIndexList(Indices) ||
2504 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2506 if (!Val0->getType()->isAggregateType())
2507 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2508 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2509 return Error(ID.Loc, "invalid indices for insertvalue");
2510 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2511 ID.Kind = ValID::t_Constant;
2514 case lltok::kw_icmp:
2515 case lltok::kw_fcmp: {
2516 unsigned PredVal, Opc = Lex.getUIntVal();
2517 Constant *Val0, *Val1;
2519 if (ParseCmpPredicate(PredVal, Opc) ||
2520 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2521 ParseGlobalTypeAndValue(Val0) ||
2522 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2523 ParseGlobalTypeAndValue(Val1) ||
2524 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2527 if (Val0->getType() != Val1->getType())
2528 return Error(ID.Loc, "compare operands must have the same type");
2530 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2532 if (Opc == Instruction::FCmp) {
2533 if (!Val0->getType()->isFPOrFPVectorTy())
2534 return Error(ID.Loc, "fcmp requires floating point operands");
2535 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2537 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2538 if (!Val0->getType()->isIntOrIntVectorTy() &&
2539 !Val0->getType()->getScalarType()->isPointerTy())
2540 return Error(ID.Loc, "icmp requires pointer or integer operands");
2541 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2543 ID.Kind = ValID::t_Constant;
2547 // Binary Operators.
2549 case lltok::kw_fadd:
2551 case lltok::kw_fsub:
2553 case lltok::kw_fmul:
2554 case lltok::kw_udiv:
2555 case lltok::kw_sdiv:
2556 case lltok::kw_fdiv:
2557 case lltok::kw_urem:
2558 case lltok::kw_srem:
2559 case lltok::kw_frem:
2561 case lltok::kw_lshr:
2562 case lltok::kw_ashr: {
2566 unsigned Opc = Lex.getUIntVal();
2567 Constant *Val0, *Val1;
2569 LocTy ModifierLoc = Lex.getLoc();
2570 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2571 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2572 if (EatIfPresent(lltok::kw_nuw))
2574 if (EatIfPresent(lltok::kw_nsw)) {
2576 if (EatIfPresent(lltok::kw_nuw))
2579 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2580 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2581 if (EatIfPresent(lltok::kw_exact))
2584 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2585 ParseGlobalTypeAndValue(Val0) ||
2586 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2587 ParseGlobalTypeAndValue(Val1) ||
2588 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2590 if (Val0->getType() != Val1->getType())
2591 return Error(ID.Loc, "operands of constexpr must have same type");
2592 if (!Val0->getType()->isIntOrIntVectorTy()) {
2594 return Error(ModifierLoc, "nuw only applies to integer operations");
2596 return Error(ModifierLoc, "nsw only applies to integer operations");
2598 // Check that the type is valid for the operator.
2600 case Instruction::Add:
2601 case Instruction::Sub:
2602 case Instruction::Mul:
2603 case Instruction::UDiv:
2604 case Instruction::SDiv:
2605 case Instruction::URem:
2606 case Instruction::SRem:
2607 case Instruction::Shl:
2608 case Instruction::AShr:
2609 case Instruction::LShr:
2610 if (!Val0->getType()->isIntOrIntVectorTy())
2611 return Error(ID.Loc, "constexpr requires integer operands");
2613 case Instruction::FAdd:
2614 case Instruction::FSub:
2615 case Instruction::FMul:
2616 case Instruction::FDiv:
2617 case Instruction::FRem:
2618 if (!Val0->getType()->isFPOrFPVectorTy())
2619 return Error(ID.Loc, "constexpr requires fp operands");
2621 default: llvm_unreachable("Unknown binary operator!");
2624 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2625 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2626 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2627 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2629 ID.Kind = ValID::t_Constant;
2633 // Logical Operations
2636 case lltok::kw_xor: {
2637 unsigned Opc = Lex.getUIntVal();
2638 Constant *Val0, *Val1;
2640 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2641 ParseGlobalTypeAndValue(Val0) ||
2642 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2643 ParseGlobalTypeAndValue(Val1) ||
2644 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2646 if (Val0->getType() != Val1->getType())
2647 return Error(ID.Loc, "operands of constexpr must have same type");
2648 if (!Val0->getType()->isIntOrIntVectorTy())
2649 return Error(ID.Loc,
2650 "constexpr requires integer or integer vector operands");
2651 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2652 ID.Kind = ValID::t_Constant;
2656 case lltok::kw_getelementptr:
2657 case lltok::kw_shufflevector:
2658 case lltok::kw_insertelement:
2659 case lltok::kw_extractelement:
2660 case lltok::kw_select: {
2661 unsigned Opc = Lex.getUIntVal();
2662 SmallVector<Constant*, 16> Elts;
2663 bool InBounds = false;
2665 if (Opc == Instruction::GetElementPtr)
2666 InBounds = EatIfPresent(lltok::kw_inbounds);
2667 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2668 ParseGlobalValueVector(Elts) ||
2669 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2672 if (Opc == Instruction::GetElementPtr) {
2673 if (Elts.size() == 0 ||
2674 !Elts[0]->getType()->getScalarType()->isPointerTy())
2675 return Error(ID.Loc, "getelementptr requires pointer operand");
2677 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2678 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2679 return Error(ID.Loc, "invalid indices for getelementptr");
2680 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2682 } else if (Opc == Instruction::Select) {
2683 if (Elts.size() != 3)
2684 return Error(ID.Loc, "expected three operands to select");
2685 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2687 return Error(ID.Loc, Reason);
2688 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2689 } else if (Opc == Instruction::ShuffleVector) {
2690 if (Elts.size() != 3)
2691 return Error(ID.Loc, "expected three operands to shufflevector");
2692 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2693 return Error(ID.Loc, "invalid operands to shufflevector");
2695 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2696 } else if (Opc == Instruction::ExtractElement) {
2697 if (Elts.size() != 2)
2698 return Error(ID.Loc, "expected two operands to extractelement");
2699 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2700 return Error(ID.Loc, "invalid extractelement operands");
2701 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2703 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2704 if (Elts.size() != 3)
2705 return Error(ID.Loc, "expected three operands to insertelement");
2706 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2707 return Error(ID.Loc, "invalid insertelement operands");
2709 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2712 ID.Kind = ValID::t_Constant;
2721 /// ParseGlobalValue - Parse a global value with the specified type.
2722 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2726 bool Parsed = ParseValID(ID) ||
2727 ConvertValIDToValue(Ty, ID, V, NULL);
2728 if (V && !(C = dyn_cast<Constant>(V)))
2729 return Error(ID.Loc, "global values must be constants");
2733 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2735 return ParseType(Ty) ||
2736 ParseGlobalValue(Ty, V);
2739 /// ParseGlobalValueVector
2741 /// ::= TypeAndValue (',' TypeAndValue)*
2742 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2744 if (Lex.getKind() == lltok::rbrace ||
2745 Lex.getKind() == lltok::rsquare ||
2746 Lex.getKind() == lltok::greater ||
2747 Lex.getKind() == lltok::rparen)
2751 if (ParseGlobalTypeAndValue(C)) return true;
2754 while (EatIfPresent(lltok::comma)) {
2755 if (ParseGlobalTypeAndValue(C)) return true;
2762 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2763 assert(Lex.getKind() == lltok::lbrace);
2766 SmallVector<Value*, 16> Elts;
2767 if (ParseMDNodeVector(Elts, PFS) ||
2768 ParseToken(lltok::rbrace, "expected end of metadata node"))
2771 ID.MDNodeVal = MDNode::get(Context, Elts);
2772 ID.Kind = ValID::t_MDNode;
2776 /// ParseMetadataValue
2780 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2781 assert(Lex.getKind() == lltok::exclaim);
2786 if (Lex.getKind() == lltok::lbrace)
2787 return ParseMetadataListValue(ID, PFS);
2789 // Standalone metadata reference
2791 if (Lex.getKind() == lltok::APSInt) {
2792 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2793 ID.Kind = ValID::t_MDNode;
2798 // ::= '!' STRINGCONSTANT
2799 if (ParseMDString(ID.MDStringVal)) return true;
2800 ID.Kind = ValID::t_MDString;
2805 //===----------------------------------------------------------------------===//
2806 // Function Parsing.
2807 //===----------------------------------------------------------------------===//
2809 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2810 PerFunctionState *PFS) {
2811 if (Ty->isFunctionTy())
2812 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2815 case ValID::t_LocalID:
2816 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2817 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2819 case ValID::t_LocalName:
2820 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2821 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2823 case ValID::t_InlineAsm: {
2824 PointerType *PTy = dyn_cast<PointerType>(Ty);
2826 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2827 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2828 return Error(ID.Loc, "invalid type for inline asm constraint string");
2829 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
2830 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
2833 case ValID::t_MDNode:
2834 if (!Ty->isMetadataTy())
2835 return Error(ID.Loc, "metadata value must have metadata type");
2838 case ValID::t_MDString:
2839 if (!Ty->isMetadataTy())
2840 return Error(ID.Loc, "metadata value must have metadata type");
2843 case ValID::t_GlobalName:
2844 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2846 case ValID::t_GlobalID:
2847 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2849 case ValID::t_APSInt:
2850 if (!Ty->isIntegerTy())
2851 return Error(ID.Loc, "integer constant must have integer type");
2852 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2853 V = ConstantInt::get(Context, ID.APSIntVal);
2855 case ValID::t_APFloat:
2856 if (!Ty->isFloatingPointTy() ||
2857 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2858 return Error(ID.Loc, "floating point constant invalid for type");
2860 // The lexer has no type info, so builds all half, float, and double FP
2861 // constants as double. Fix this here. Long double does not need this.
2862 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
2865 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2867 else if (Ty->isFloatTy())
2868 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2871 V = ConstantFP::get(Context, ID.APFloatVal);
2873 if (V->getType() != Ty)
2874 return Error(ID.Loc, "floating point constant does not have type '" +
2875 getTypeString(Ty) + "'");
2879 if (!Ty->isPointerTy())
2880 return Error(ID.Loc, "null must be a pointer type");
2881 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2883 case ValID::t_Undef:
2884 // FIXME: LabelTy should not be a first-class type.
2885 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2886 return Error(ID.Loc, "invalid type for undef constant");
2887 V = UndefValue::get(Ty);
2889 case ValID::t_EmptyArray:
2890 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2891 return Error(ID.Loc, "invalid empty array initializer");
2892 V = UndefValue::get(Ty);
2895 // FIXME: LabelTy should not be a first-class type.
2896 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2897 return Error(ID.Loc, "invalid type for null constant");
2898 V = Constant::getNullValue(Ty);
2900 case ValID::t_Constant:
2901 if (ID.ConstantVal->getType() != Ty)
2902 return Error(ID.Loc, "constant expression type mismatch");
2906 case ValID::t_ConstantStruct:
2907 case ValID::t_PackedConstantStruct:
2908 if (StructType *ST = dyn_cast<StructType>(Ty)) {
2909 if (ST->getNumElements() != ID.UIntVal)
2910 return Error(ID.Loc,
2911 "initializer with struct type has wrong # elements");
2912 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2913 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2915 // Verify that the elements are compatible with the structtype.
2916 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2917 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2918 return Error(ID.Loc, "element " + Twine(i) +
2919 " of struct initializer doesn't match struct element type");
2921 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2924 return Error(ID.Loc, "constant expression type mismatch");
2927 llvm_unreachable("Invalid ValID");
2930 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
2933 return ParseValID(ID, PFS) ||
2934 ConvertValIDToValue(Ty, ID, V, PFS);
2937 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2939 return ParseType(Ty) ||
2940 ParseValue(Ty, V, PFS);
2943 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2944 PerFunctionState &PFS) {
2947 if (ParseTypeAndValue(V, PFS)) return true;
2948 if (!isa<BasicBlock>(V))
2949 return Error(Loc, "expected a basic block");
2950 BB = cast<BasicBlock>(V);
2956 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2957 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2958 /// OptionalAlign OptGC OptionalPrefix
2959 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2960 // Parse the linkage.
2961 LocTy LinkageLoc = Lex.getLoc();
2964 unsigned Visibility;
2965 unsigned DLLStorageClass;
2966 AttrBuilder RetAttrs;
2969 LocTy RetTypeLoc = Lex.getLoc();
2970 if (ParseOptionalLinkage(Linkage) ||
2971 ParseOptionalVisibility(Visibility) ||
2972 ParseOptionalDLLStorageClass(DLLStorageClass) ||
2973 ParseOptionalCallingConv(CC) ||
2974 ParseOptionalReturnAttrs(RetAttrs) ||
2975 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2978 // Verify that the linkage is ok.
2979 switch ((GlobalValue::LinkageTypes)Linkage) {
2980 case GlobalValue::ExternalLinkage:
2981 break; // always ok.
2982 case GlobalValue::ExternalWeakLinkage:
2984 return Error(LinkageLoc, "invalid linkage for function definition");
2986 case GlobalValue::PrivateLinkage:
2987 case GlobalValue::InternalLinkage:
2988 case GlobalValue::AvailableExternallyLinkage:
2989 case GlobalValue::LinkOnceAnyLinkage:
2990 case GlobalValue::LinkOnceODRLinkage:
2991 case GlobalValue::WeakAnyLinkage:
2992 case GlobalValue::WeakODRLinkage:
2994 return Error(LinkageLoc, "invalid linkage for function declaration");
2996 case GlobalValue::AppendingLinkage:
2997 case GlobalValue::CommonLinkage:
2998 return Error(LinkageLoc, "invalid function linkage type");
3001 if (!FunctionType::isValidReturnType(RetType))
3002 return Error(RetTypeLoc, "invalid function return type");
3004 LocTy NameLoc = Lex.getLoc();
3006 std::string FunctionName;
3007 if (Lex.getKind() == lltok::GlobalVar) {
3008 FunctionName = Lex.getStrVal();
3009 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3010 unsigned NameID = Lex.getUIntVal();
3012 if (NameID != NumberedVals.size())
3013 return TokError("function expected to be numbered '%" +
3014 Twine(NumberedVals.size()) + "'");
3016 return TokError("expected function name");
3021 if (Lex.getKind() != lltok::lparen)
3022 return TokError("expected '(' in function argument list");
3024 SmallVector<ArgInfo, 8> ArgList;
3026 AttrBuilder FuncAttrs;
3027 std::vector<unsigned> FwdRefAttrGrps;
3029 std::string Section;
3033 LocTy UnnamedAddrLoc;
3034 Constant *Prefix = 0;
3036 if (ParseArgumentList(ArgList, isVarArg) ||
3037 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3039 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
3041 (EatIfPresent(lltok::kw_section) &&
3042 ParseStringConstant(Section)) ||
3043 ParseOptionalAlignment(Alignment) ||
3044 (EatIfPresent(lltok::kw_gc) &&
3045 ParseStringConstant(GC)) ||
3046 (EatIfPresent(lltok::kw_prefix) &&
3047 ParseGlobalTypeAndValue(Prefix)))
3050 if (FuncAttrs.contains(Attribute::Builtin))
3051 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
3053 // If the alignment was parsed as an attribute, move to the alignment field.
3054 if (FuncAttrs.hasAlignmentAttr()) {
3055 Alignment = FuncAttrs.getAlignment();
3056 FuncAttrs.removeAttribute(Attribute::Alignment);
3059 // Okay, if we got here, the function is syntactically valid. Convert types
3060 // and do semantic checks.
3061 std::vector<Type*> ParamTypeList;
3062 SmallVector<AttributeSet, 8> Attrs;
3064 if (RetAttrs.hasAttributes())
3065 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3066 AttributeSet::ReturnIndex,
3069 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3070 ParamTypeList.push_back(ArgList[i].Ty);
3071 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3072 AttrBuilder B(ArgList[i].Attrs, i + 1);
3073 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3077 if (FuncAttrs.hasAttributes())
3078 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3079 AttributeSet::FunctionIndex,
3082 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3084 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
3085 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3088 FunctionType::get(RetType, ParamTypeList, isVarArg);
3089 PointerType *PFT = PointerType::getUnqual(FT);
3092 if (!FunctionName.empty()) {
3093 // If this was a definition of a forward reference, remove the definition
3094 // from the forward reference table and fill in the forward ref.
3095 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3096 ForwardRefVals.find(FunctionName);
3097 if (FRVI != ForwardRefVals.end()) {
3098 Fn = M->getFunction(FunctionName);
3100 return Error(FRVI->second.second, "invalid forward reference to "
3101 "function as global value!");
3102 if (Fn->getType() != PFT)
3103 return Error(FRVI->second.second, "invalid forward reference to "
3104 "function '" + FunctionName + "' with wrong type!");
3106 ForwardRefVals.erase(FRVI);
3107 } else if ((Fn = M->getFunction(FunctionName))) {
3108 // Reject redefinitions.
3109 return Error(NameLoc, "invalid redefinition of function '" +
3110 FunctionName + "'");
3111 } else if (M->getNamedValue(FunctionName)) {
3112 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
3116 // If this is a definition of a forward referenced function, make sure the
3118 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3119 = ForwardRefValIDs.find(NumberedVals.size());
3120 if (I != ForwardRefValIDs.end()) {
3121 Fn = cast<Function>(I->second.first);
3122 if (Fn->getType() != PFT)
3123 return Error(NameLoc, "type of definition and forward reference of '@" +
3124 Twine(NumberedVals.size()) + "' disagree");
3125 ForwardRefValIDs.erase(I);
3130 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3131 else // Move the forward-reference to the correct spot in the module.
3132 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3134 if (FunctionName.empty())
3135 NumberedVals.push_back(Fn);
3137 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3138 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3139 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
3140 Fn->setCallingConv(CC);
3141 Fn->setAttributes(PAL);
3142 Fn->setUnnamedAddr(UnnamedAddr);
3143 Fn->setAlignment(Alignment);
3144 Fn->setSection(Section);
3145 if (!GC.empty()) Fn->setGC(GC.c_str());
3146 Fn->setPrefixData(Prefix);
3147 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
3149 // Add all of the arguments we parsed to the function.
3150 Function::arg_iterator ArgIt = Fn->arg_begin();
3151 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3152 // If the argument has a name, insert it into the argument symbol table.
3153 if (ArgList[i].Name.empty()) continue;
3155 // Set the name, if it conflicted, it will be auto-renamed.
3156 ArgIt->setName(ArgList[i].Name);
3158 if (ArgIt->getName() != ArgList[i].Name)
3159 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3160 ArgList[i].Name + "'");
3167 /// ParseFunctionBody
3168 /// ::= '{' BasicBlock+ '}'
3170 bool LLParser::ParseFunctionBody(Function &Fn) {
3171 if (Lex.getKind() != lltok::lbrace)
3172 return TokError("expected '{' in function body");
3173 Lex.Lex(); // eat the {.
3175 int FunctionNumber = -1;
3176 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
3178 PerFunctionState PFS(*this, Fn, FunctionNumber);
3180 // We need at least one basic block.
3181 if (Lex.getKind() == lltok::rbrace)
3182 return TokError("function body requires at least one basic block");
3184 while (Lex.getKind() != lltok::rbrace)
3185 if (ParseBasicBlock(PFS)) return true;
3190 // Verify function is ok.
3191 return PFS.FinishFunction();
3195 /// ::= LabelStr? Instruction*
3196 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3197 // If this basic block starts out with a name, remember it.
3199 LocTy NameLoc = Lex.getLoc();
3200 if (Lex.getKind() == lltok::LabelStr) {
3201 Name = Lex.getStrVal();
3205 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3206 if (BB == 0) return true;
3208 std::string NameStr;
3210 // Parse the instructions in this block until we get a terminator.
3213 // This instruction may have three possibilities for a name: a) none
3214 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3215 LocTy NameLoc = Lex.getLoc();
3219 if (Lex.getKind() == lltok::LocalVarID) {
3220 NameID = Lex.getUIntVal();
3222 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3224 } else if (Lex.getKind() == lltok::LocalVar) {
3225 NameStr = Lex.getStrVal();
3227 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3231 switch (ParseInstruction(Inst, BB, PFS)) {
3232 default: llvm_unreachable("Unknown ParseInstruction result!");
3233 case InstError: return true;
3235 BB->getInstList().push_back(Inst);
3237 // With a normal result, we check to see if the instruction is followed by
3238 // a comma and metadata.
3239 if (EatIfPresent(lltok::comma))
3240 if (ParseInstructionMetadata(Inst, &PFS))
3243 case InstExtraComma:
3244 BB->getInstList().push_back(Inst);
3246 // If the instruction parser ate an extra comma at the end of it, it
3247 // *must* be followed by metadata.
3248 if (ParseInstructionMetadata(Inst, &PFS))
3253 // Set the name on the instruction.
3254 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3255 } while (!isa<TerminatorInst>(Inst));
3260 //===----------------------------------------------------------------------===//
3261 // Instruction Parsing.
3262 //===----------------------------------------------------------------------===//
3264 /// ParseInstruction - Parse one of the many different instructions.
3266 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3267 PerFunctionState &PFS) {
3268 lltok::Kind Token = Lex.getKind();
3269 if (Token == lltok::Eof)
3270 return TokError("found end of file when expecting more instructions");
3271 LocTy Loc = Lex.getLoc();
3272 unsigned KeywordVal = Lex.getUIntVal();
3273 Lex.Lex(); // Eat the keyword.
3276 default: return Error(Loc, "expected instruction opcode");
3277 // Terminator Instructions.
3278 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3279 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3280 case lltok::kw_br: return ParseBr(Inst, PFS);
3281 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
3282 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
3283 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3284 case lltok::kw_resume: return ParseResume(Inst, PFS);
3285 // Binary Operators.
3289 case lltok::kw_shl: {
3290 bool NUW = EatIfPresent(lltok::kw_nuw);
3291 bool NSW = EatIfPresent(lltok::kw_nsw);
3292 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3294 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3296 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3297 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3300 case lltok::kw_fadd:
3301 case lltok::kw_fsub:
3302 case lltok::kw_fmul:
3303 case lltok::kw_fdiv:
3304 case lltok::kw_frem: {
3305 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3306 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3310 Inst->setFastMathFlags(FMF);
3314 case lltok::kw_sdiv:
3315 case lltok::kw_udiv:
3316 case lltok::kw_lshr:
3317 case lltok::kw_ashr: {
3318 bool Exact = EatIfPresent(lltok::kw_exact);
3320 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3321 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3325 case lltok::kw_urem:
3326 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3329 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3330 case lltok::kw_icmp:
3331 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3333 case lltok::kw_trunc:
3334 case lltok::kw_zext:
3335 case lltok::kw_sext:
3336 case lltok::kw_fptrunc:
3337 case lltok::kw_fpext:
3338 case lltok::kw_bitcast:
3339 case lltok::kw_addrspacecast:
3340 case lltok::kw_uitofp:
3341 case lltok::kw_sitofp:
3342 case lltok::kw_fptoui:
3343 case lltok::kw_fptosi:
3344 case lltok::kw_inttoptr:
3345 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3347 case lltok::kw_select: return ParseSelect(Inst, PFS);
3348 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3349 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3350 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3351 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3352 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3353 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3354 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3355 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3357 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3358 case lltok::kw_load: return ParseLoad(Inst, PFS);
3359 case lltok::kw_store: return ParseStore(Inst, PFS);
3360 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3361 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3362 case lltok::kw_fence: return ParseFence(Inst, PFS);
3363 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3364 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3365 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3369 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3370 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3371 if (Opc == Instruction::FCmp) {
3372 switch (Lex.getKind()) {
3373 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
3374 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3375 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3376 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3377 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3378 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3379 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3380 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3381 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3382 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3383 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3384 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3385 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3386 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3387 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3388 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3389 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3392 switch (Lex.getKind()) {
3393 default: return TokError("expected icmp predicate (e.g. 'eq')");
3394 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3395 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3396 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3397 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3398 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3399 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3400 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3401 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3402 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3403 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3410 //===----------------------------------------------------------------------===//
3411 // Terminator Instructions.
3412 //===----------------------------------------------------------------------===//
3414 /// ParseRet - Parse a return instruction.
3415 /// ::= 'ret' void (',' !dbg, !1)*
3416 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3417 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3418 PerFunctionState &PFS) {
3419 SMLoc TypeLoc = Lex.getLoc();
3421 if (ParseType(Ty, true /*void allowed*/)) return true;
3423 Type *ResType = PFS.getFunction().getReturnType();
3425 if (Ty->isVoidTy()) {
3426 if (!ResType->isVoidTy())
3427 return Error(TypeLoc, "value doesn't match function result type '" +
3428 getTypeString(ResType) + "'");
3430 Inst = ReturnInst::Create(Context);
3435 if (ParseValue(Ty, RV, PFS)) return true;
3437 if (ResType != RV->getType())
3438 return Error(TypeLoc, "value doesn't match function result type '" +
3439 getTypeString(ResType) + "'");
3441 Inst = ReturnInst::Create(Context, RV);
3447 /// ::= 'br' TypeAndValue
3448 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3449 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3452 BasicBlock *Op1, *Op2;
3453 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3455 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3456 Inst = BranchInst::Create(BB);
3460 if (Op0->getType() != Type::getInt1Ty(Context))
3461 return Error(Loc, "branch condition must have 'i1' type");
3463 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3464 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3465 ParseToken(lltok::comma, "expected ',' after true destination") ||
3466 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3469 Inst = BranchInst::Create(Op1, Op2, Op0);
3475 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3477 /// ::= (TypeAndValue ',' TypeAndValue)*
3478 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3479 LocTy CondLoc, BBLoc;
3481 BasicBlock *DefaultBB;
3482 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3483 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3484 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3485 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3488 if (!Cond->getType()->isIntegerTy())
3489 return Error(CondLoc, "switch condition must have integer type");
3491 // Parse the jump table pairs.
3492 SmallPtrSet<Value*, 32> SeenCases;
3493 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3494 while (Lex.getKind() != lltok::rsquare) {
3498 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3499 ParseToken(lltok::comma, "expected ',' after case value") ||
3500 ParseTypeAndBasicBlock(DestBB, PFS))
3503 if (!SeenCases.insert(Constant))
3504 return Error(CondLoc, "duplicate case value in switch");
3505 if (!isa<ConstantInt>(Constant))
3506 return Error(CondLoc, "case value is not a constant integer");
3508 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3511 Lex.Lex(); // Eat the ']'.
3513 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3514 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3515 SI->addCase(Table[i].first, Table[i].second);
3522 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3523 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3526 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3527 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3528 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3531 if (!Address->getType()->isPointerTy())
3532 return Error(AddrLoc, "indirectbr address must have pointer type");
3534 // Parse the destination list.
3535 SmallVector<BasicBlock*, 16> DestList;
3537 if (Lex.getKind() != lltok::rsquare) {
3539 if (ParseTypeAndBasicBlock(DestBB, PFS))
3541 DestList.push_back(DestBB);
3543 while (EatIfPresent(lltok::comma)) {
3544 if (ParseTypeAndBasicBlock(DestBB, PFS))
3546 DestList.push_back(DestBB);
3550 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3553 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3554 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3555 IBI->addDestination(DestList[i]);
3562 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3563 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3564 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3565 LocTy CallLoc = Lex.getLoc();
3566 AttrBuilder RetAttrs, FnAttrs;
3567 std::vector<unsigned> FwdRefAttrGrps;
3573 SmallVector<ParamInfo, 16> ArgList;
3575 BasicBlock *NormalBB, *UnwindBB;
3576 if (ParseOptionalCallingConv(CC) ||
3577 ParseOptionalReturnAttrs(RetAttrs) ||
3578 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3579 ParseValID(CalleeID) ||
3580 ParseParameterList(ArgList, PFS) ||
3581 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3583 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3584 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3585 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3586 ParseTypeAndBasicBlock(UnwindBB, PFS))
3589 // If RetType is a non-function pointer type, then this is the short syntax
3590 // for the call, which means that RetType is just the return type. Infer the
3591 // rest of the function argument types from the arguments that are present.
3592 PointerType *PFTy = 0;
3593 FunctionType *Ty = 0;
3594 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3595 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3596 // Pull out the types of all of the arguments...
3597 std::vector<Type*> ParamTypes;
3598 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3599 ParamTypes.push_back(ArgList[i].V->getType());
3601 if (!FunctionType::isValidReturnType(RetType))
3602 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3604 Ty = FunctionType::get(RetType, ParamTypes, false);
3605 PFTy = PointerType::getUnqual(Ty);
3608 // Look up the callee.
3610 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3612 // Set up the Attribute for the function.
3613 SmallVector<AttributeSet, 8> Attrs;
3614 if (RetAttrs.hasAttributes())
3615 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3616 AttributeSet::ReturnIndex,
3619 SmallVector<Value*, 8> Args;
3621 // Loop through FunctionType's arguments and ensure they are specified
3622 // correctly. Also, gather any parameter attributes.
3623 FunctionType::param_iterator I = Ty->param_begin();
3624 FunctionType::param_iterator E = Ty->param_end();
3625 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3626 Type *ExpectedTy = 0;
3629 } else if (!Ty->isVarArg()) {
3630 return Error(ArgList[i].Loc, "too many arguments specified");
3633 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3634 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3635 getTypeString(ExpectedTy) + "'");
3636 Args.push_back(ArgList[i].V);
3637 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3638 AttrBuilder B(ArgList[i].Attrs, i + 1);
3639 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3644 return Error(CallLoc, "not enough parameters specified for call");
3646 if (FnAttrs.hasAttributes())
3647 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3648 AttributeSet::FunctionIndex,
3651 // Finish off the Attribute and check them
3652 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3654 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3655 II->setCallingConv(CC);
3656 II->setAttributes(PAL);
3657 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
3663 /// ::= 'resume' TypeAndValue
3664 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3665 Value *Exn; LocTy ExnLoc;
3666 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3669 ResumeInst *RI = ResumeInst::Create(Exn);
3674 //===----------------------------------------------------------------------===//
3675 // Binary Operators.
3676 //===----------------------------------------------------------------------===//
3679 /// ::= ArithmeticOps TypeAndValue ',' Value
3681 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3682 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3683 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3684 unsigned Opc, unsigned OperandType) {
3685 LocTy Loc; Value *LHS, *RHS;
3686 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3687 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3688 ParseValue(LHS->getType(), RHS, PFS))
3692 switch (OperandType) {
3693 default: llvm_unreachable("Unknown operand type!");
3694 case 0: // int or FP.
3695 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3696 LHS->getType()->isFPOrFPVectorTy();
3698 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3699 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3703 return Error(Loc, "invalid operand type for instruction");
3705 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3710 /// ::= ArithmeticOps TypeAndValue ',' Value {
3711 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3713 LocTy Loc; Value *LHS, *RHS;
3714 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3715 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3716 ParseValue(LHS->getType(), RHS, PFS))
3719 if (!LHS->getType()->isIntOrIntVectorTy())
3720 return Error(Loc,"instruction requires integer or integer vector operands");
3722 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3728 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3729 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3730 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3732 // Parse the integer/fp comparison predicate.
3736 if (ParseCmpPredicate(Pred, Opc) ||
3737 ParseTypeAndValue(LHS, Loc, PFS) ||
3738 ParseToken(lltok::comma, "expected ',' after compare value") ||
3739 ParseValue(LHS->getType(), RHS, PFS))
3742 if (Opc == Instruction::FCmp) {
3743 if (!LHS->getType()->isFPOrFPVectorTy())
3744 return Error(Loc, "fcmp requires floating point operands");
3745 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3747 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3748 if (!LHS->getType()->isIntOrIntVectorTy() &&
3749 !LHS->getType()->getScalarType()->isPointerTy())
3750 return Error(Loc, "icmp requires integer operands");
3751 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3756 //===----------------------------------------------------------------------===//
3757 // Other Instructions.
3758 //===----------------------------------------------------------------------===//
3762 /// ::= CastOpc TypeAndValue 'to' Type
3763 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3768 if (ParseTypeAndValue(Op, Loc, PFS) ||
3769 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3773 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3774 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3775 return Error(Loc, "invalid cast opcode for cast from '" +
3776 getTypeString(Op->getType()) + "' to '" +
3777 getTypeString(DestTy) + "'");
3779 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3784 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3785 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3787 Value *Op0, *Op1, *Op2;
3788 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3789 ParseToken(lltok::comma, "expected ',' after select condition") ||
3790 ParseTypeAndValue(Op1, PFS) ||
3791 ParseToken(lltok::comma, "expected ',' after select value") ||
3792 ParseTypeAndValue(Op2, PFS))
3795 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3796 return Error(Loc, Reason);
3798 Inst = SelectInst::Create(Op0, Op1, Op2);
3803 /// ::= 'va_arg' TypeAndValue ',' Type
3804 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3808 if (ParseTypeAndValue(Op, PFS) ||
3809 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3810 ParseType(EltTy, TypeLoc))
3813 if (!EltTy->isFirstClassType())
3814 return Error(TypeLoc, "va_arg requires operand with first class type");
3816 Inst = new VAArgInst(Op, EltTy);
3820 /// ParseExtractElement
3821 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3822 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3825 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3826 ParseToken(lltok::comma, "expected ',' after extract value") ||
3827 ParseTypeAndValue(Op1, PFS))
3830 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3831 return Error(Loc, "invalid extractelement operands");
3833 Inst = ExtractElementInst::Create(Op0, Op1);
3837 /// ParseInsertElement
3838 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3839 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3841 Value *Op0, *Op1, *Op2;
3842 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3843 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3844 ParseTypeAndValue(Op1, PFS) ||
3845 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3846 ParseTypeAndValue(Op2, PFS))
3849 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3850 return Error(Loc, "invalid insertelement operands");
3852 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3856 /// ParseShuffleVector
3857 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3858 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3860 Value *Op0, *Op1, *Op2;
3861 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3862 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3863 ParseTypeAndValue(Op1, PFS) ||
3864 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3865 ParseTypeAndValue(Op2, PFS))
3868 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3869 return Error(Loc, "invalid shufflevector operands");
3871 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3876 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3877 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3878 Type *Ty = 0; LocTy TypeLoc;
3881 if (ParseType(Ty, TypeLoc) ||
3882 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3883 ParseValue(Ty, Op0, PFS) ||
3884 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3885 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3886 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3889 bool AteExtraComma = false;
3890 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3892 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3894 if (!EatIfPresent(lltok::comma))
3897 if (Lex.getKind() == lltok::MetadataVar) {
3898 AteExtraComma = true;
3902 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3903 ParseValue(Ty, Op0, PFS) ||
3904 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3905 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3906 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3910 if (!Ty->isFirstClassType())
3911 return Error(TypeLoc, "phi node must have first class type");
3913 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3914 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3915 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3917 return AteExtraComma ? InstExtraComma : InstNormal;
3921 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3923 /// ::= 'catch' TypeAndValue
3925 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3926 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3927 Type *Ty = 0; LocTy TyLoc;
3928 Value *PersFn; LocTy PersFnLoc;
3930 if (ParseType(Ty, TyLoc) ||
3931 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3932 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3935 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3936 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3938 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3939 LandingPadInst::ClauseType CT;
3940 if (EatIfPresent(lltok::kw_catch))
3941 CT = LandingPadInst::Catch;
3942 else if (EatIfPresent(lltok::kw_filter))
3943 CT = LandingPadInst::Filter;
3945 return TokError("expected 'catch' or 'filter' clause type");
3947 Value *V; LocTy VLoc;
3948 if (ParseTypeAndValue(V, VLoc, PFS)) {
3953 // A 'catch' type expects a non-array constant. A filter clause expects an
3955 if (CT == LandingPadInst::Catch) {
3956 if (isa<ArrayType>(V->getType()))
3957 Error(VLoc, "'catch' clause has an invalid type");
3959 if (!isa<ArrayType>(V->getType()))
3960 Error(VLoc, "'filter' clause has an invalid type");
3971 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3972 /// ParameterList OptionalAttrs
3973 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3975 AttrBuilder RetAttrs, FnAttrs;
3976 std::vector<unsigned> FwdRefAttrGrps;
3982 SmallVector<ParamInfo, 16> ArgList;
3983 LocTy CallLoc = Lex.getLoc();
3985 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3986 ParseOptionalCallingConv(CC) ||
3987 ParseOptionalReturnAttrs(RetAttrs) ||
3988 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3989 ParseValID(CalleeID) ||
3990 ParseParameterList(ArgList, PFS) ||
3991 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3995 // If RetType is a non-function pointer type, then this is the short syntax
3996 // for the call, which means that RetType is just the return type. Infer the
3997 // rest of the function argument types from the arguments that are present.
3998 PointerType *PFTy = 0;
3999 FunctionType *Ty = 0;
4000 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4001 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4002 // Pull out the types of all of the arguments...
4003 std::vector<Type*> ParamTypes;
4004 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4005 ParamTypes.push_back(ArgList[i].V->getType());
4007 if (!FunctionType::isValidReturnType(RetType))
4008 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4010 Ty = FunctionType::get(RetType, ParamTypes, false);
4011 PFTy = PointerType::getUnqual(Ty);
4014 // Look up the callee.
4016 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
4018 // Set up the Attribute for the function.
4019 SmallVector<AttributeSet, 8> Attrs;
4020 if (RetAttrs.hasAttributes())
4021 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4022 AttributeSet::ReturnIndex,
4025 SmallVector<Value*, 8> Args;
4027 // Loop through FunctionType's arguments and ensure they are specified
4028 // correctly. Also, gather any parameter attributes.
4029 FunctionType::param_iterator I = Ty->param_begin();
4030 FunctionType::param_iterator E = Ty->param_end();
4031 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4032 Type *ExpectedTy = 0;
4035 } else if (!Ty->isVarArg()) {
4036 return Error(ArgList[i].Loc, "too many arguments specified");
4039 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4040 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4041 getTypeString(ExpectedTy) + "'");
4042 Args.push_back(ArgList[i].V);
4043 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4044 AttrBuilder B(ArgList[i].Attrs, i + 1);
4045 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4050 return Error(CallLoc, "not enough parameters specified for call");
4052 if (FnAttrs.hasAttributes())
4053 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4054 AttributeSet::FunctionIndex,
4057 // Finish off the Attribute and check them
4058 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4060 CallInst *CI = CallInst::Create(Callee, Args);
4061 CI->setTailCall(isTail);
4062 CI->setCallingConv(CC);
4063 CI->setAttributes(PAL);
4064 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
4069 //===----------------------------------------------------------------------===//
4070 // Memory Instructions.
4071 //===----------------------------------------------------------------------===//
4074 /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
4075 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
4078 unsigned Alignment = 0;
4081 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4083 if (ParseType(Ty)) return true;
4085 bool AteExtraComma = false;
4086 if (EatIfPresent(lltok::comma)) {
4087 if (Lex.getKind() == lltok::kw_align) {
4088 if (ParseOptionalAlignment(Alignment)) return true;
4089 } else if (Lex.getKind() == lltok::MetadataVar) {
4090 AteExtraComma = true;
4092 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4093 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4098 if (Size && !Size->getType()->isIntegerTy())
4099 return Error(SizeLoc, "element count must have integer type");
4101 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4102 AI->setUsedWithInAlloca(IsInAlloca);
4104 return AteExtraComma ? InstExtraComma : InstNormal;
4108 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
4109 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
4110 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4111 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
4112 Value *Val; LocTy Loc;
4113 unsigned Alignment = 0;
4114 bool AteExtraComma = false;
4115 bool isAtomic = false;
4116 AtomicOrdering Ordering = NotAtomic;
4117 SynchronizationScope Scope = CrossThread;
4119 if (Lex.getKind() == lltok::kw_atomic) {
4124 bool isVolatile = false;
4125 if (Lex.getKind() == lltok::kw_volatile) {
4130 if (ParseTypeAndValue(Val, Loc, PFS) ||
4131 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4132 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4135 if (!Val->getType()->isPointerTy() ||
4136 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4137 return Error(Loc, "load operand must be a pointer to a first class type");
4138 if (isAtomic && !Alignment)
4139 return Error(Loc, "atomic load must have explicit non-zero alignment");
4140 if (Ordering == Release || Ordering == AcquireRelease)
4141 return Error(Loc, "atomic load cannot use Release ordering");
4143 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
4144 return AteExtraComma ? InstExtraComma : InstNormal;
4149 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4150 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
4151 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4152 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
4153 Value *Val, *Ptr; LocTy Loc, PtrLoc;
4154 unsigned Alignment = 0;
4155 bool AteExtraComma = false;
4156 bool isAtomic = false;
4157 AtomicOrdering Ordering = NotAtomic;
4158 SynchronizationScope Scope = CrossThread;
4160 if (Lex.getKind() == lltok::kw_atomic) {
4165 bool isVolatile = false;
4166 if (Lex.getKind() == lltok::kw_volatile) {
4171 if (ParseTypeAndValue(Val, Loc, PFS) ||
4172 ParseToken(lltok::comma, "expected ',' after store operand") ||
4173 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4174 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4175 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4178 if (!Ptr->getType()->isPointerTy())
4179 return Error(PtrLoc, "store operand must be a pointer");
4180 if (!Val->getType()->isFirstClassType())
4181 return Error(Loc, "store operand must be a first class value");
4182 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4183 return Error(Loc, "stored value and pointer type do not match");
4184 if (isAtomic && !Alignment)
4185 return Error(Loc, "atomic store must have explicit non-zero alignment");
4186 if (Ordering == Acquire || Ordering == AcquireRelease)
4187 return Error(Loc, "atomic store cannot use Acquire ordering");
4189 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
4190 return AteExtraComma ? InstExtraComma : InstNormal;
4194 /// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
4195 /// 'singlethread'? AtomicOrdering AtomicOrdering
4196 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
4197 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4198 bool AteExtraComma = false;
4199 AtomicOrdering SuccessOrdering = NotAtomic;
4200 AtomicOrdering FailureOrdering = NotAtomic;
4201 SynchronizationScope Scope = CrossThread;
4202 bool isVolatile = false;
4204 if (EatIfPresent(lltok::kw_volatile))
4207 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4208 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4209 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4210 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4211 ParseTypeAndValue(New, NewLoc, PFS) ||
4212 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4213 ParseOrdering(FailureOrdering))
4216 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
4217 return TokError("cmpxchg cannot be unordered");
4218 if (SuccessOrdering < FailureOrdering)
4219 return TokError("cmpxchg must be at least as ordered on success as failure");
4220 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4221 return TokError("cmpxchg failure ordering cannot include release semantics");
4222 if (!Ptr->getType()->isPointerTy())
4223 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4224 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4225 return Error(CmpLoc, "compare value and pointer type do not match");
4226 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4227 return Error(NewLoc, "new value and pointer type do not match");
4228 if (!New->getType()->isIntegerTy())
4229 return Error(NewLoc, "cmpxchg operand must be an integer");
4230 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4231 if (Size < 8 || (Size & (Size - 1)))
4232 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4235 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering,
4236 FailureOrdering, Scope);
4237 CXI->setVolatile(isVolatile);
4239 return AteExtraComma ? InstExtraComma : InstNormal;
4243 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4244 /// 'singlethread'? AtomicOrdering
4245 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
4246 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4247 bool AteExtraComma = false;
4248 AtomicOrdering Ordering = NotAtomic;
4249 SynchronizationScope Scope = CrossThread;
4250 bool isVolatile = false;
4251 AtomicRMWInst::BinOp Operation;
4253 if (EatIfPresent(lltok::kw_volatile))
4256 switch (Lex.getKind()) {
4257 default: return TokError("expected binary operation in atomicrmw");
4258 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4259 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4260 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4261 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4262 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4263 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4264 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4265 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4266 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4267 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4268 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4270 Lex.Lex(); // Eat the operation.
4272 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4273 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4274 ParseTypeAndValue(Val, ValLoc, PFS) ||
4275 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4278 if (Ordering == Unordered)
4279 return TokError("atomicrmw cannot be unordered");
4280 if (!Ptr->getType()->isPointerTy())
4281 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4282 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4283 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4284 if (!Val->getType()->isIntegerTy())
4285 return Error(ValLoc, "atomicrmw operand must be an integer");
4286 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4287 if (Size < 8 || (Size & (Size - 1)))
4288 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4291 AtomicRMWInst *RMWI =
4292 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4293 RMWI->setVolatile(isVolatile);
4295 return AteExtraComma ? InstExtraComma : InstNormal;
4299 /// ::= 'fence' 'singlethread'? AtomicOrdering
4300 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4301 AtomicOrdering Ordering = NotAtomic;
4302 SynchronizationScope Scope = CrossThread;
4303 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4306 if (Ordering == Unordered)
4307 return TokError("fence cannot be unordered");
4308 if (Ordering == Monotonic)
4309 return TokError("fence cannot be monotonic");
4311 Inst = new FenceInst(Context, Ordering, Scope);
4315 /// ParseGetElementPtr
4316 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4317 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4322 bool InBounds = EatIfPresent(lltok::kw_inbounds);
4324 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4326 Type *BaseType = Ptr->getType();
4327 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4328 if (!BasePointerType)
4329 return Error(Loc, "base of getelementptr must be a pointer");
4331 SmallVector<Value*, 16> Indices;
4332 bool AteExtraComma = false;
4333 while (EatIfPresent(lltok::comma)) {
4334 if (Lex.getKind() == lltok::MetadataVar) {
4335 AteExtraComma = true;
4338 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4339 if (!Val->getType()->getScalarType()->isIntegerTy())
4340 return Error(EltLoc, "getelementptr index must be an integer");
4341 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4342 return Error(EltLoc, "getelementptr index type missmatch");
4343 if (Val->getType()->isVectorTy()) {
4344 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4345 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4346 if (ValNumEl != PtrNumEl)
4347 return Error(EltLoc,
4348 "getelementptr vector index has a wrong number of elements");
4350 Indices.push_back(Val);
4353 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4354 return Error(Loc, "base element of getelementptr must be sized");
4356 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
4357 return Error(Loc, "invalid getelementptr indices");
4358 Inst = GetElementPtrInst::Create(Ptr, Indices);
4360 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4361 return AteExtraComma ? InstExtraComma : InstNormal;
4364 /// ParseExtractValue
4365 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
4366 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4367 Value *Val; LocTy Loc;
4368 SmallVector<unsigned, 4> Indices;
4370 if (ParseTypeAndValue(Val, Loc, PFS) ||
4371 ParseIndexList(Indices, AteExtraComma))
4374 if (!Val->getType()->isAggregateType())
4375 return Error(Loc, "extractvalue operand must be aggregate type");
4377 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4378 return Error(Loc, "invalid indices for extractvalue");
4379 Inst = ExtractValueInst::Create(Val, Indices);
4380 return AteExtraComma ? InstExtraComma : InstNormal;
4383 /// ParseInsertValue
4384 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4385 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4386 Value *Val0, *Val1; LocTy Loc0, Loc1;
4387 SmallVector<unsigned, 4> Indices;
4389 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4390 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4391 ParseTypeAndValue(Val1, Loc1, PFS) ||
4392 ParseIndexList(Indices, AteExtraComma))
4395 if (!Val0->getType()->isAggregateType())
4396 return Error(Loc0, "insertvalue operand must be aggregate type");
4398 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4399 return Error(Loc0, "invalid indices for insertvalue");
4400 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4401 return AteExtraComma ? InstExtraComma : InstNormal;
4404 //===----------------------------------------------------------------------===//
4405 // Embedded metadata.
4406 //===----------------------------------------------------------------------===//
4408 /// ParseMDNodeVector
4409 /// ::= Element (',' Element)*
4411 /// ::= 'null' | TypeAndValue
4412 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4413 PerFunctionState *PFS) {
4414 // Check for an empty list.
4415 if (Lex.getKind() == lltok::rbrace)
4419 // Null is a special case since it is typeless.
4420 if (EatIfPresent(lltok::kw_null)) {
4426 if (ParseTypeAndValue(V, PFS)) return true;
4428 } while (EatIfPresent(lltok::comma));