1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the parser class for .ll files.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/AutoUpgrade.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Metadata.h"
23 #include "llvm/Module.h"
24 #include "llvm/Operator.h"
25 #include "llvm/ValueSymbolTable.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
33 /// ValID - Represents a reference of a definition of some sort with no type.
34 /// There are several cases where we have to parse the value but where the
35 /// type can depend on later context. This may either be a numeric reference
36 /// or a symbolic (%var) reference. This is just a discriminated union.
39 t_LocalID, t_GlobalID, // ID in UIntVal.
40 t_LocalName, t_GlobalName, // Name in StrVal.
41 t_APSInt, t_APFloat, // Value in APSIntVal/APFloatVal.
42 t_Null, t_Undef, t_Zero, // No value.
43 t_EmptyArray, // No value: []
44 t_Constant, // Value in ConstantVal.
45 t_InlineAsm, // Value in StrVal/StrVal2/UIntVal.
46 t_Metadata // Value in MetadataVal.
51 std::string StrVal, StrVal2;
54 Constant *ConstantVal;
55 MetadataBase *MetadataVal;
56 ValID() : APFloatVal(0.0) {}
60 /// Run: module ::= toplevelentity*
61 bool LLParser::Run() {
65 return ParseTopLevelEntities() ||
66 ValidateEndOfModule();
69 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
71 bool LLParser::ValidateEndOfModule() {
72 // Update auto-upgraded malloc calls from "autoupgrade_malloc" to "malloc".
73 // FIXME: Remove in LLVM 3.0.
75 MallocF->setName("malloc");
76 // If setName() does not set the name to "malloc", then there is already a
77 // declaration of "malloc". In that case, iterate over all calls to MallocF
78 // and get them to call the declared "malloc" instead.
79 if (MallocF->getName() != "malloc") {
80 Function* realMallocF = M->getFunction("malloc");
81 for (User::use_iterator UI = MallocF->use_begin(), UE= MallocF->use_end();
85 if (CallInst *Call = dyn_cast<CallInst>(user))
86 Call->setCalledFunction(realMallocF);
88 if (!realMallocF->doesNotAlias(0)) realMallocF->setDoesNotAlias(0);
89 MallocF->eraseFromParent();
94 if (!ForwardRefTypes.empty())
95 return Error(ForwardRefTypes.begin()->second.second,
96 "use of undefined type named '" +
97 ForwardRefTypes.begin()->first + "'");
98 if (!ForwardRefTypeIDs.empty())
99 return Error(ForwardRefTypeIDs.begin()->second.second,
100 "use of undefined type '%" +
101 utostr(ForwardRefTypeIDs.begin()->first) + "'");
103 if (!ForwardRefVals.empty())
104 return Error(ForwardRefVals.begin()->second.second,
105 "use of undefined value '@" + ForwardRefVals.begin()->first +
108 if (!ForwardRefValIDs.empty())
109 return Error(ForwardRefValIDs.begin()->second.second,
110 "use of undefined value '@" +
111 utostr(ForwardRefValIDs.begin()->first) + "'");
113 if (!ForwardRefMDNodes.empty())
114 return Error(ForwardRefMDNodes.begin()->second.second,
115 "use of undefined metadata '!" +
116 utostr(ForwardRefMDNodes.begin()->first) + "'");
119 // Look for intrinsic functions and CallInst that need to be upgraded
120 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
121 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
123 // Check debug info intrinsics.
124 CheckDebugInfoIntrinsics(M);
128 //===----------------------------------------------------------------------===//
129 // Top-Level Entities
130 //===----------------------------------------------------------------------===//
132 bool LLParser::ParseTopLevelEntities() {
134 switch (Lex.getKind()) {
135 default: return TokError("expected top-level entity");
136 case lltok::Eof: return false;
137 //case lltok::kw_define:
138 case lltok::kw_declare: if (ParseDeclare()) return true; break;
139 case lltok::kw_define: if (ParseDefine()) return true; break;
140 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
141 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
142 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
143 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
144 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
145 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
146 case lltok::LocalVar: if (ParseNamedType()) return true; break;
147 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
148 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
149 case lltok::Metadata: if (ParseStandaloneMetadata()) return true; break;
150 case lltok::NamedOrCustomMD: if (ParseNamedMetadata()) return true; break;
152 // The Global variable production with no name can have many different
153 // optional leading prefixes, the production is:
154 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
155 // OptionalAddrSpace ('constant'|'global') ...
156 case lltok::kw_private : // OptionalLinkage
157 case lltok::kw_linker_private: // OptionalLinkage
158 case lltok::kw_internal: // OptionalLinkage
159 case lltok::kw_weak: // OptionalLinkage
160 case lltok::kw_weak_odr: // OptionalLinkage
161 case lltok::kw_linkonce: // OptionalLinkage
162 case lltok::kw_linkonce_odr: // OptionalLinkage
163 case lltok::kw_appending: // OptionalLinkage
164 case lltok::kw_dllexport: // OptionalLinkage
165 case lltok::kw_common: // OptionalLinkage
166 case lltok::kw_dllimport: // OptionalLinkage
167 case lltok::kw_extern_weak: // OptionalLinkage
168 case lltok::kw_external: { // OptionalLinkage
169 unsigned Linkage, Visibility;
170 if (ParseOptionalLinkage(Linkage) ||
171 ParseOptionalVisibility(Visibility) ||
172 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
176 case lltok::kw_default: // OptionalVisibility
177 case lltok::kw_hidden: // OptionalVisibility
178 case lltok::kw_protected: { // OptionalVisibility
180 if (ParseOptionalVisibility(Visibility) ||
181 ParseGlobal("", SMLoc(), 0, false, Visibility))
186 case lltok::kw_thread_local: // OptionalThreadLocal
187 case lltok::kw_addrspace: // OptionalAddrSpace
188 case lltok::kw_constant: // GlobalType
189 case lltok::kw_global: // GlobalType
190 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
198 /// ::= 'module' 'asm' STRINGCONSTANT
199 bool LLParser::ParseModuleAsm() {
200 assert(Lex.getKind() == lltok::kw_module);
204 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
205 ParseStringConstant(AsmStr)) return true;
207 const std::string &AsmSoFar = M->getModuleInlineAsm();
208 if (AsmSoFar.empty())
209 M->setModuleInlineAsm(AsmStr);
211 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
216 /// ::= 'target' 'triple' '=' STRINGCONSTANT
217 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
218 bool LLParser::ParseTargetDefinition() {
219 assert(Lex.getKind() == lltok::kw_target);
222 default: return TokError("unknown target property");
223 case lltok::kw_triple:
225 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
226 ParseStringConstant(Str))
228 M->setTargetTriple(Str);
230 case lltok::kw_datalayout:
232 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
233 ParseStringConstant(Str))
235 M->setDataLayout(Str);
241 /// ::= 'deplibs' '=' '[' ']'
242 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
243 bool LLParser::ParseDepLibs() {
244 assert(Lex.getKind() == lltok::kw_deplibs);
246 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
247 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
250 if (EatIfPresent(lltok::rsquare))
254 if (ParseStringConstant(Str)) return true;
257 while (EatIfPresent(lltok::comma)) {
258 if (ParseStringConstant(Str)) return true;
262 return ParseToken(lltok::rsquare, "expected ']' at end of list");
265 /// ParseUnnamedType:
267 /// ::= LocalVarID '=' 'type' type
268 bool LLParser::ParseUnnamedType() {
269 unsigned TypeID = NumberedTypes.size();
271 // Handle the LocalVarID form.
272 if (Lex.getKind() == lltok::LocalVarID) {
273 if (Lex.getUIntVal() != TypeID)
274 return Error(Lex.getLoc(), "type expected to be numbered '%" +
275 utostr(TypeID) + "'");
276 Lex.Lex(); // eat LocalVarID;
278 if (ParseToken(lltok::equal, "expected '=' after name"))
282 assert(Lex.getKind() == lltok::kw_type);
283 LocTy TypeLoc = Lex.getLoc();
284 Lex.Lex(); // eat kw_type
286 PATypeHolder Ty(Type::getVoidTy(Context));
287 if (ParseType(Ty)) return true;
289 // See if this type was previously referenced.
290 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
291 FI = ForwardRefTypeIDs.find(TypeID);
292 if (FI != ForwardRefTypeIDs.end()) {
293 if (FI->second.first.get() == Ty)
294 return Error(TypeLoc, "self referential type is invalid");
296 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
297 Ty = FI->second.first.get();
298 ForwardRefTypeIDs.erase(FI);
301 NumberedTypes.push_back(Ty);
307 /// ::= LocalVar '=' 'type' type
308 bool LLParser::ParseNamedType() {
309 std::string Name = Lex.getStrVal();
310 LocTy NameLoc = Lex.getLoc();
311 Lex.Lex(); // eat LocalVar.
313 PATypeHolder Ty(Type::getVoidTy(Context));
315 if (ParseToken(lltok::equal, "expected '=' after name") ||
316 ParseToken(lltok::kw_type, "expected 'type' after name") ||
320 // Set the type name, checking for conflicts as we do so.
321 bool AlreadyExists = M->addTypeName(Name, Ty);
322 if (!AlreadyExists) return false;
324 // See if this type is a forward reference. We need to eagerly resolve
325 // types to allow recursive type redefinitions below.
326 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
327 FI = ForwardRefTypes.find(Name);
328 if (FI != ForwardRefTypes.end()) {
329 if (FI->second.first.get() == Ty)
330 return Error(NameLoc, "self referential type is invalid");
332 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
333 Ty = FI->second.first.get();
334 ForwardRefTypes.erase(FI);
337 // Inserting a name that is already defined, get the existing name.
338 const Type *Existing = M->getTypeByName(Name);
339 assert(Existing && "Conflict but no matching type?!");
341 // Otherwise, this is an attempt to redefine a type. That's okay if
342 // the redefinition is identical to the original.
343 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
344 if (Existing == Ty) return false;
346 // Any other kind of (non-equivalent) redefinition is an error.
347 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
348 Ty->getDescription() + "'");
353 /// ::= 'declare' FunctionHeader
354 bool LLParser::ParseDeclare() {
355 assert(Lex.getKind() == lltok::kw_declare);
359 return ParseFunctionHeader(F, false);
363 /// ::= 'define' FunctionHeader '{' ...
364 bool LLParser::ParseDefine() {
365 assert(Lex.getKind() == lltok::kw_define);
369 return ParseFunctionHeader(F, true) ||
370 ParseFunctionBody(*F);
376 bool LLParser::ParseGlobalType(bool &IsConstant) {
377 if (Lex.getKind() == lltok::kw_constant)
379 else if (Lex.getKind() == lltok::kw_global)
383 return TokError("expected 'global' or 'constant'");
389 /// ParseUnnamedGlobal:
390 /// OptionalVisibility ALIAS ...
391 /// OptionalLinkage OptionalVisibility ... -> global variable
392 /// GlobalID '=' OptionalVisibility ALIAS ...
393 /// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
394 bool LLParser::ParseUnnamedGlobal() {
395 unsigned VarID = NumberedVals.size();
397 LocTy NameLoc = Lex.getLoc();
399 // Handle the GlobalID form.
400 if (Lex.getKind() == lltok::GlobalID) {
401 if (Lex.getUIntVal() != VarID)
402 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
403 utostr(VarID) + "'");
404 Lex.Lex(); // eat GlobalID;
406 if (ParseToken(lltok::equal, "expected '=' after name"))
411 unsigned Linkage, Visibility;
412 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
413 ParseOptionalVisibility(Visibility))
416 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
417 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
418 return ParseAlias(Name, NameLoc, Visibility);
421 /// ParseNamedGlobal:
422 /// GlobalVar '=' OptionalVisibility ALIAS ...
423 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
424 bool LLParser::ParseNamedGlobal() {
425 assert(Lex.getKind() == lltok::GlobalVar);
426 LocTy NameLoc = Lex.getLoc();
427 std::string Name = Lex.getStrVal();
431 unsigned Linkage, Visibility;
432 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
433 ParseOptionalLinkage(Linkage, HasLinkage) ||
434 ParseOptionalVisibility(Visibility))
437 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
438 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
439 return ParseAlias(Name, NameLoc, Visibility);
443 // ::= '!' STRINGCONSTANT
444 bool LLParser::ParseMDString(MetadataBase *&MDS) {
446 if (ParseStringConstant(Str)) return true;
447 MDS = MDString::get(Context, Str);
452 // ::= '!' MDNodeNumber
453 bool LLParser::ParseMDNode(MetadataBase *&Node) {
454 // !{ ..., !42, ... }
456 if (ParseUInt32(MID)) return true;
458 // Check existing MDNode.
459 std::map<unsigned, MetadataBase *>::iterator I = MetadataCache.find(MID);
460 if (I != MetadataCache.end()) {
465 // Check known forward references.
466 std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
467 FI = ForwardRefMDNodes.find(MID);
468 if (FI != ForwardRefMDNodes.end()) {
469 Node = FI->second.first;
473 // Create MDNode forward reference
474 SmallVector<Value *, 1> Elts;
475 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
476 Elts.push_back(MDString::get(Context, FwdRefName));
477 MDNode *FwdNode = MDNode::get(Context, Elts.data(), Elts.size());
478 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
483 ///ParseNamedMetadata:
484 /// !foo = !{ !1, !2 }
485 bool LLParser::ParseNamedMetadata() {
486 assert(Lex.getKind() == lltok::NamedOrCustomMD);
488 std::string Name = Lex.getStrVal();
490 if (ParseToken(lltok::equal, "expected '=' here"))
493 if (Lex.getKind() != lltok::Metadata)
494 return TokError("Expected '!' here");
497 if (Lex.getKind() != lltok::lbrace)
498 return TokError("Expected '{' here");
500 SmallVector<MetadataBase *, 8> Elts;
502 if (Lex.getKind() != lltok::Metadata)
503 return TokError("Expected '!' here");
506 if (ParseMDNode(N)) return true;
508 } while (EatIfPresent(lltok::comma));
510 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
513 NamedMDNode::Create(Context, Name, Elts.data(), Elts.size(), M);
517 /// ParseStandaloneMetadata:
519 bool LLParser::ParseStandaloneMetadata() {
520 assert(Lex.getKind() == lltok::Metadata);
522 unsigned MetadataID = 0;
523 if (ParseUInt32(MetadataID))
525 if (MetadataCache.find(MetadataID) != MetadataCache.end())
526 return TokError("Metadata id is already used");
527 if (ParseToken(lltok::equal, "expected '=' here"))
531 PATypeHolder Ty(Type::getVoidTy(Context));
532 if (ParseType(Ty, TyLoc))
535 if (Lex.getKind() != lltok::Metadata)
536 return TokError("Expected metadata here");
539 if (Lex.getKind() != lltok::lbrace)
540 return TokError("Expected '{' here");
542 SmallVector<Value *, 16> Elts;
543 if (ParseMDNodeVector(Elts)
544 || ParseToken(lltok::rbrace, "expected end of metadata node"))
547 MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
548 MetadataCache[MetadataID] = Init;
549 std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
550 FI = ForwardRefMDNodes.find(MetadataID);
551 if (FI != ForwardRefMDNodes.end()) {
552 MDNode *FwdNode = cast<MDNode>(FI->second.first);
553 FwdNode->replaceAllUsesWith(Init);
554 ForwardRefMDNodes.erase(FI);
561 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
564 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
565 /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
567 /// Everything through visibility has already been parsed.
569 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
570 unsigned Visibility) {
571 assert(Lex.getKind() == lltok::kw_alias);
574 LocTy LinkageLoc = Lex.getLoc();
575 if (ParseOptionalLinkage(Linkage))
578 if (Linkage != GlobalValue::ExternalLinkage &&
579 Linkage != GlobalValue::WeakAnyLinkage &&
580 Linkage != GlobalValue::WeakODRLinkage &&
581 Linkage != GlobalValue::InternalLinkage &&
582 Linkage != GlobalValue::PrivateLinkage &&
583 Linkage != GlobalValue::LinkerPrivateLinkage)
584 return Error(LinkageLoc, "invalid linkage type for alias");
587 LocTy AliaseeLoc = Lex.getLoc();
588 if (Lex.getKind() != lltok::kw_bitcast &&
589 Lex.getKind() != lltok::kw_getelementptr) {
590 if (ParseGlobalTypeAndValue(Aliasee)) return true;
592 // The bitcast dest type is not present, it is implied by the dest type.
594 if (ParseValID(ID)) return true;
595 if (ID.Kind != ValID::t_Constant)
596 return Error(AliaseeLoc, "invalid aliasee");
597 Aliasee = ID.ConstantVal;
600 if (!isa<PointerType>(Aliasee->getType()))
601 return Error(AliaseeLoc, "alias must have pointer type");
603 // Okay, create the alias but do not insert it into the module yet.
604 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
605 (GlobalValue::LinkageTypes)Linkage, Name,
607 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
609 // See if this value already exists in the symbol table. If so, it is either
610 // a redefinition or a definition of a forward reference.
611 if (GlobalValue *Val =
612 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
613 // See if this was a redefinition. If so, there is no entry in
615 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
616 I = ForwardRefVals.find(Name);
617 if (I == ForwardRefVals.end())
618 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
620 // Otherwise, this was a definition of forward ref. Verify that types
622 if (Val->getType() != GA->getType())
623 return Error(NameLoc,
624 "forward reference and definition of alias have different types");
626 // If they agree, just RAUW the old value with the alias and remove the
628 Val->replaceAllUsesWith(GA);
629 Val->eraseFromParent();
630 ForwardRefVals.erase(I);
633 // Insert into the module, we know its name won't collide now.
634 M->getAliasList().push_back(GA);
635 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
641 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
642 /// OptionalAddrSpace GlobalType Type Const
643 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
644 /// OptionalAddrSpace GlobalType Type Const
646 /// Everything through visibility has been parsed already.
648 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
649 unsigned Linkage, bool HasLinkage,
650 unsigned Visibility) {
652 bool ThreadLocal, IsConstant;
655 PATypeHolder Ty(Type::getVoidTy(Context));
656 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
657 ParseOptionalAddrSpace(AddrSpace) ||
658 ParseGlobalType(IsConstant) ||
659 ParseType(Ty, TyLoc))
662 // If the linkage is specified and is external, then no initializer is
665 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
666 Linkage != GlobalValue::ExternalWeakLinkage &&
667 Linkage != GlobalValue::ExternalLinkage)) {
668 if (ParseGlobalValue(Ty, Init))
672 if (isa<FunctionType>(Ty) || Ty->isLabelTy())
673 return Error(TyLoc, "invalid type for global variable");
675 GlobalVariable *GV = 0;
677 // See if the global was forward referenced, if so, use the global.
679 if ((GV = M->getGlobalVariable(Name, true)) &&
680 !ForwardRefVals.erase(Name))
681 return Error(NameLoc, "redefinition of global '@" + Name + "'");
683 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
684 I = ForwardRefValIDs.find(NumberedVals.size());
685 if (I != ForwardRefValIDs.end()) {
686 GV = cast<GlobalVariable>(I->second.first);
687 ForwardRefValIDs.erase(I);
692 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
693 Name, 0, false, AddrSpace);
695 if (GV->getType()->getElementType() != Ty)
697 "forward reference and definition of global have different types");
699 // Move the forward-reference to the correct spot in the module.
700 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
704 NumberedVals.push_back(GV);
706 // Set the parsed properties on the global.
708 GV->setInitializer(Init);
709 GV->setConstant(IsConstant);
710 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
711 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
712 GV->setThreadLocal(ThreadLocal);
714 // Parse attributes on the global.
715 while (Lex.getKind() == lltok::comma) {
718 if (Lex.getKind() == lltok::kw_section) {
720 GV->setSection(Lex.getStrVal());
721 if (ParseToken(lltok::StringConstant, "expected global section string"))
723 } else if (Lex.getKind() == lltok::kw_align) {
725 if (ParseOptionalAlignment(Alignment)) return true;
726 GV->setAlignment(Alignment);
728 TokError("unknown global variable property!");
736 //===----------------------------------------------------------------------===//
737 // GlobalValue Reference/Resolution Routines.
738 //===----------------------------------------------------------------------===//
740 /// GetGlobalVal - Get a value with the specified name or ID, creating a
741 /// forward reference record if needed. This can return null if the value
742 /// exists but does not have the right type.
743 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
745 const PointerType *PTy = dyn_cast<PointerType>(Ty);
747 Error(Loc, "global variable reference must have pointer type");
751 // Look this name up in the normal function symbol table.
753 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
755 // If this is a forward reference for the value, see if we already created a
756 // forward ref record.
758 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
759 I = ForwardRefVals.find(Name);
760 if (I != ForwardRefVals.end())
761 Val = I->second.first;
764 // If we have the value in the symbol table or fwd-ref table, return it.
766 if (Val->getType() == Ty) return Val;
767 Error(Loc, "'@" + Name + "' defined with type '" +
768 Val->getType()->getDescription() + "'");
772 // Otherwise, create a new forward reference for this value and remember it.
774 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
775 // Function types can return opaque but functions can't.
776 if (isa<OpaqueType>(FT->getReturnType())) {
777 Error(Loc, "function may not return opaque type");
781 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
783 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
784 GlobalValue::ExternalWeakLinkage, 0, Name);
787 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
791 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
792 const PointerType *PTy = dyn_cast<PointerType>(Ty);
794 Error(Loc, "global variable reference must have pointer type");
798 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
800 // If this is a forward reference for the value, see if we already created a
801 // forward ref record.
803 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
804 I = ForwardRefValIDs.find(ID);
805 if (I != ForwardRefValIDs.end())
806 Val = I->second.first;
809 // If we have the value in the symbol table or fwd-ref table, return it.
811 if (Val->getType() == Ty) return Val;
812 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
813 Val->getType()->getDescription() + "'");
817 // Otherwise, create a new forward reference for this value and remember it.
819 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
820 // Function types can return opaque but functions can't.
821 if (isa<OpaqueType>(FT->getReturnType())) {
822 Error(Loc, "function may not return opaque type");
825 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
827 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
828 GlobalValue::ExternalWeakLinkage, 0, "");
831 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
836 //===----------------------------------------------------------------------===//
838 //===----------------------------------------------------------------------===//
840 /// ParseToken - If the current token has the specified kind, eat it and return
841 /// success. Otherwise, emit the specified error and return failure.
842 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
843 if (Lex.getKind() != T)
844 return TokError(ErrMsg);
849 /// ParseStringConstant
850 /// ::= StringConstant
851 bool LLParser::ParseStringConstant(std::string &Result) {
852 if (Lex.getKind() != lltok::StringConstant)
853 return TokError("expected string constant");
854 Result = Lex.getStrVal();
861 bool LLParser::ParseUInt32(unsigned &Val) {
862 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
863 return TokError("expected integer");
864 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
865 if (Val64 != unsigned(Val64))
866 return TokError("expected 32-bit integer (too large)");
873 /// ParseOptionalAddrSpace
875 /// := 'addrspace' '(' uint32 ')'
876 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
878 if (!EatIfPresent(lltok::kw_addrspace))
880 return ParseToken(lltok::lparen, "expected '(' in address space") ||
881 ParseUInt32(AddrSpace) ||
882 ParseToken(lltok::rparen, "expected ')' in address space");
885 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
886 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
887 /// 2: function attr.
888 /// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
889 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
890 Attrs = Attribute::None;
891 LocTy AttrLoc = Lex.getLoc();
894 switch (Lex.getKind()) {
897 // Treat these as signext/zeroext if they occur in the argument list after
898 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
899 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
901 // FIXME: REMOVE THIS IN LLVM 3.0
903 if (Lex.getKind() == lltok::kw_sext)
904 Attrs |= Attribute::SExt;
906 Attrs |= Attribute::ZExt;
910 default: // End of attributes.
911 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
912 return Error(AttrLoc, "invalid use of function-only attribute");
914 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
915 return Error(AttrLoc, "invalid use of parameter-only attribute");
918 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
919 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
920 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
921 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
922 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
923 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
924 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
925 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
927 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
928 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
929 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
930 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
931 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
932 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
933 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
934 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
935 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
936 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
937 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
938 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
939 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
941 case lltok::kw_align: {
943 if (ParseOptionalAlignment(Alignment))
945 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
953 /// ParseOptionalLinkage
956 /// ::= 'linker_private'
961 /// ::= 'linkonce_odr'
966 /// ::= 'extern_weak'
968 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
970 switch (Lex.getKind()) {
971 default: Res=GlobalValue::ExternalLinkage; return false;
972 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
973 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
974 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
975 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
976 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
977 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
978 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
979 case lltok::kw_available_externally:
980 Res = GlobalValue::AvailableExternallyLinkage;
982 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
983 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
984 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
985 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
986 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
987 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
994 /// ParseOptionalVisibility
1000 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1001 switch (Lex.getKind()) {
1002 default: Res = GlobalValue::DefaultVisibility; return false;
1003 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1004 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1005 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1011 /// ParseOptionalCallingConv
1016 /// ::= 'x86_stdcallcc'
1017 /// ::= 'x86_fastcallcc'
1018 /// ::= 'arm_apcscc'
1019 /// ::= 'arm_aapcscc'
1020 /// ::= 'arm_aapcs_vfpcc'
1023 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1024 switch (Lex.getKind()) {
1025 default: CC = CallingConv::C; return false;
1026 case lltok::kw_ccc: CC = CallingConv::C; break;
1027 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1028 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1029 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1030 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1031 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1032 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1033 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1034 case lltok::kw_cc: {
1035 unsigned ArbitraryCC;
1037 if (ParseUInt32(ArbitraryCC)) {
1040 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1050 /// ParseOptionalCustomMetadata
1053 bool LLParser::ParseOptionalCustomMetadata() {
1054 if (Lex.getKind() != lltok::NamedOrCustomMD)
1057 std::string Name = Lex.getStrVal();
1060 if (Lex.getKind() != lltok::Metadata)
1061 return TokError("Expected '!' here");
1065 if (ParseMDNode(Node)) return true;
1067 MetadataContext &TheMetadata = M->getContext().getMetadata();
1068 unsigned MDK = TheMetadata.getMDKind(Name.c_str());
1070 MDK = TheMetadata.registerMDKind(Name.c_str());
1071 MDsOnInst.push_back(std::make_pair(MDK, cast<MDNode>(Node)));
1076 /// ParseOptionalAlignment
1079 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1081 if (!EatIfPresent(lltok::kw_align))
1083 LocTy AlignLoc = Lex.getLoc();
1084 if (ParseUInt32(Alignment)) return true;
1085 if (!isPowerOf2_32(Alignment))
1086 return Error(AlignLoc, "alignment is not a power of two");
1090 /// ParseOptionalInfo
1091 /// ::= OptionalInfo (',' OptionalInfo)+
1092 bool LLParser::ParseOptionalInfo(unsigned &Alignment) {
1094 // FIXME: Handle customized metadata info attached with an instruction.
1096 if (Lex.getKind() == lltok::NamedOrCustomMD) {
1097 if (ParseOptionalCustomMetadata()) return true;
1098 } else if (Lex.getKind() == lltok::kw_align) {
1099 if (ParseOptionalAlignment(Alignment)) return true;
1102 } while (EatIfPresent(lltok::comma));
1109 /// ::= (',' uint32)+
1110 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
1111 if (Lex.getKind() != lltok::comma)
1112 return TokError("expected ',' as start of index list");
1114 while (EatIfPresent(lltok::comma)) {
1116 if (ParseUInt32(Idx)) return true;
1117 Indices.push_back(Idx);
1123 //===----------------------------------------------------------------------===//
1125 //===----------------------------------------------------------------------===//
1127 /// ParseType - Parse and resolve a full type.
1128 bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1129 LocTy TypeLoc = Lex.getLoc();
1130 if (ParseTypeRec(Result)) return true;
1132 // Verify no unresolved uprefs.
1133 if (!UpRefs.empty())
1134 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
1136 if (!AllowVoid && Result.get()->isVoidTy())
1137 return Error(TypeLoc, "void type only allowed for function results");
1142 /// HandleUpRefs - Every time we finish a new layer of types, this function is
1143 /// called. It loops through the UpRefs vector, which is a list of the
1144 /// currently active types. For each type, if the up-reference is contained in
1145 /// the newly completed type, we decrement the level count. When the level
1146 /// count reaches zero, the up-referenced type is the type that is passed in:
1147 /// thus we can complete the cycle.
1149 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1150 // If Ty isn't abstract, or if there are no up-references in it, then there is
1151 // nothing to resolve here.
1152 if (!ty->isAbstract() || UpRefs.empty()) return ty;
1154 PATypeHolder Ty(ty);
1156 errs() << "Type '" << Ty->getDescription()
1157 << "' newly formed. Resolving upreferences.\n"
1158 << UpRefs.size() << " upreferences active!\n";
1161 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1162 // to zero), we resolve them all together before we resolve them to Ty. At
1163 // the end of the loop, if there is anything to resolve to Ty, it will be in
1165 OpaqueType *TypeToResolve = 0;
1167 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1168 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1170 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1171 UpRefs[i].LastContainedTy) != Ty->subtype_end();
1174 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1175 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1176 << (ContainsType ? "true" : "false")
1177 << " level=" << UpRefs[i].NestingLevel << "\n";
1182 // Decrement level of upreference
1183 unsigned Level = --UpRefs[i].NestingLevel;
1184 UpRefs[i].LastContainedTy = Ty;
1186 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1191 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1194 TypeToResolve = UpRefs[i].UpRefTy;
1196 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1197 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1198 --i; // Do not skip the next element.
1202 TypeToResolve->refineAbstractTypeTo(Ty);
1208 /// ParseTypeRec - The recursive function used to process the internal
1209 /// implementation details of types.
1210 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1211 switch (Lex.getKind()) {
1213 return TokError("expected type");
1215 // TypeRec ::= 'float' | 'void' (etc)
1216 Result = Lex.getTyVal();
1219 case lltok::kw_opaque:
1220 // TypeRec ::= 'opaque'
1221 Result = OpaqueType::get(Context);
1225 // TypeRec ::= '{' ... '}'
1226 if (ParseStructType(Result, false))
1229 case lltok::lsquare:
1230 // TypeRec ::= '[' ... ']'
1231 Lex.Lex(); // eat the lsquare.
1232 if (ParseArrayVectorType(Result, false))
1235 case lltok::less: // Either vector or packed struct.
1236 // TypeRec ::= '<' ... '>'
1238 if (Lex.getKind() == lltok::lbrace) {
1239 if (ParseStructType(Result, true) ||
1240 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1242 } else if (ParseArrayVectorType(Result, true))
1245 case lltok::LocalVar:
1246 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1248 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1251 Result = OpaqueType::get(Context);
1252 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1253 std::make_pair(Result,
1255 M->addTypeName(Lex.getStrVal(), Result.get());
1260 case lltok::LocalVarID:
1262 if (Lex.getUIntVal() < NumberedTypes.size())
1263 Result = NumberedTypes[Lex.getUIntVal()];
1265 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1266 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1267 if (I != ForwardRefTypeIDs.end())
1268 Result = I->second.first;
1270 Result = OpaqueType::get(Context);
1271 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1272 std::make_pair(Result,
1278 case lltok::backslash: {
1279 // TypeRec ::= '\' 4
1282 if (ParseUInt32(Val)) return true;
1283 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
1284 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1290 // Parse the type suffixes.
1292 switch (Lex.getKind()) {
1294 default: return false;
1296 // TypeRec ::= TypeRec '*'
1298 if (Result.get()->isLabelTy())
1299 return TokError("basic block pointers are invalid");
1300 if (Result.get()->isVoidTy())
1301 return TokError("pointers to void are invalid; use i8* instead");
1302 if (!PointerType::isValidElementType(Result.get()))
1303 return TokError("pointer to this type is invalid");
1304 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1308 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1309 case lltok::kw_addrspace: {
1310 if (Result.get()->isLabelTy())
1311 return TokError("basic block pointers are invalid");
1312 if (Result.get()->isVoidTy())
1313 return TokError("pointers to void are invalid; use i8* instead");
1314 if (!PointerType::isValidElementType(Result.get()))
1315 return TokError("pointer to this type is invalid");
1317 if (ParseOptionalAddrSpace(AddrSpace) ||
1318 ParseToken(lltok::star, "expected '*' in address space"))
1321 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1325 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1327 if (ParseFunctionType(Result))
1334 /// ParseParameterList
1336 /// ::= '(' Arg (',' Arg)* ')'
1338 /// ::= Type OptionalAttributes Value OptionalAttributes
1339 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1340 PerFunctionState &PFS) {
1341 if (ParseToken(lltok::lparen, "expected '(' in call"))
1344 while (Lex.getKind() != lltok::rparen) {
1345 // If this isn't the first argument, we need a comma.
1346 if (!ArgList.empty() &&
1347 ParseToken(lltok::comma, "expected ',' in argument list"))
1350 // Parse the argument.
1352 PATypeHolder ArgTy(Type::getVoidTy(Context));
1353 unsigned ArgAttrs1, ArgAttrs2;
1355 if (ParseType(ArgTy, ArgLoc) ||
1356 ParseOptionalAttrs(ArgAttrs1, 0) ||
1357 ParseValue(ArgTy, V, PFS) ||
1358 // FIXME: Should not allow attributes after the argument, remove this in
1360 ParseOptionalAttrs(ArgAttrs2, 3))
1362 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1365 Lex.Lex(); // Lex the ')'.
1371 /// ParseArgumentList - Parse the argument list for a function type or function
1372 /// prototype. If 'inType' is true then we are parsing a FunctionType.
1373 /// ::= '(' ArgTypeListI ')'
1377 /// ::= ArgTypeList ',' '...'
1378 /// ::= ArgType (',' ArgType)*
1380 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1381 bool &isVarArg, bool inType) {
1383 assert(Lex.getKind() == lltok::lparen);
1384 Lex.Lex(); // eat the (.
1386 if (Lex.getKind() == lltok::rparen) {
1388 } else if (Lex.getKind() == lltok::dotdotdot) {
1392 LocTy TypeLoc = Lex.getLoc();
1393 PATypeHolder ArgTy(Type::getVoidTy(Context));
1397 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1398 // types (such as a function returning a pointer to itself). If parsing a
1399 // function prototype, we require fully resolved types.
1400 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1401 ParseOptionalAttrs(Attrs, 0)) return true;
1403 if (ArgTy->isVoidTy())
1404 return Error(TypeLoc, "argument can not have void type");
1406 if (Lex.getKind() == lltok::LocalVar ||
1407 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1408 Name = Lex.getStrVal();
1412 if (!FunctionType::isValidArgumentType(ArgTy))
1413 return Error(TypeLoc, "invalid type for function argument");
1415 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1417 while (EatIfPresent(lltok::comma)) {
1418 // Handle ... at end of arg list.
1419 if (EatIfPresent(lltok::dotdotdot)) {
1424 // Otherwise must be an argument type.
1425 TypeLoc = Lex.getLoc();
1426 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1427 ParseOptionalAttrs(Attrs, 0)) return true;
1429 if (ArgTy->isVoidTy())
1430 return Error(TypeLoc, "argument can not have void type");
1432 if (Lex.getKind() == lltok::LocalVar ||
1433 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1434 Name = Lex.getStrVal();
1440 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1441 return Error(TypeLoc, "invalid type for function argument");
1443 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1447 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1450 /// ParseFunctionType
1451 /// ::= Type ArgumentList OptionalAttrs
1452 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1453 assert(Lex.getKind() == lltok::lparen);
1455 if (!FunctionType::isValidReturnType(Result))
1456 return TokError("invalid function return type");
1458 std::vector<ArgInfo> ArgList;
1461 if (ParseArgumentList(ArgList, isVarArg, true) ||
1462 // FIXME: Allow, but ignore attributes on function types!
1463 // FIXME: Remove in LLVM 3.0
1464 ParseOptionalAttrs(Attrs, 2))
1467 // Reject names on the arguments lists.
1468 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1469 if (!ArgList[i].Name.empty())
1470 return Error(ArgList[i].Loc, "argument name invalid in function type");
1471 if (!ArgList[i].Attrs != 0) {
1472 // Allow but ignore attributes on function types; this permits
1474 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1478 std::vector<const Type*> ArgListTy;
1479 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1480 ArgListTy.push_back(ArgList[i].Type);
1482 Result = HandleUpRefs(FunctionType::get(Result.get(),
1483 ArgListTy, isVarArg));
1487 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1490 /// ::= '{' TypeRec (',' TypeRec)* '}'
1491 /// ::= '<' '{' '}' '>'
1492 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1493 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1494 assert(Lex.getKind() == lltok::lbrace);
1495 Lex.Lex(); // Consume the '{'
1497 if (EatIfPresent(lltok::rbrace)) {
1498 Result = StructType::get(Context, Packed);
1502 std::vector<PATypeHolder> ParamsList;
1503 LocTy EltTyLoc = Lex.getLoc();
1504 if (ParseTypeRec(Result)) return true;
1505 ParamsList.push_back(Result);
1507 if (Result->isVoidTy())
1508 return Error(EltTyLoc, "struct element can not have void type");
1509 if (!StructType::isValidElementType(Result))
1510 return Error(EltTyLoc, "invalid element type for struct");
1512 while (EatIfPresent(lltok::comma)) {
1513 EltTyLoc = Lex.getLoc();
1514 if (ParseTypeRec(Result)) return true;
1516 if (Result->isVoidTy())
1517 return Error(EltTyLoc, "struct element can not have void type");
1518 if (!StructType::isValidElementType(Result))
1519 return Error(EltTyLoc, "invalid element type for struct");
1521 ParamsList.push_back(Result);
1524 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1527 std::vector<const Type*> ParamsListTy;
1528 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1529 ParamsListTy.push_back(ParamsList[i].get());
1530 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
1534 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1535 /// token has already been consumed.
1537 /// ::= '[' APSINTVAL 'x' Types ']'
1538 /// ::= '<' APSINTVAL 'x' Types '>'
1539 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1540 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1541 Lex.getAPSIntVal().getBitWidth() > 64)
1542 return TokError("expected number in address space");
1544 LocTy SizeLoc = Lex.getLoc();
1545 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1548 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1551 LocTy TypeLoc = Lex.getLoc();
1552 PATypeHolder EltTy(Type::getVoidTy(Context));
1553 if (ParseTypeRec(EltTy)) return true;
1555 if (EltTy->isVoidTy())
1556 return Error(TypeLoc, "array and vector element type cannot be void");
1558 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1559 "expected end of sequential type"))
1564 return Error(SizeLoc, "zero element vector is illegal");
1565 if ((unsigned)Size != Size)
1566 return Error(SizeLoc, "size too large for vector");
1567 if (!VectorType::isValidElementType(EltTy))
1568 return Error(TypeLoc, "vector element type must be fp or integer");
1569 Result = VectorType::get(EltTy, unsigned(Size));
1571 if (!ArrayType::isValidElementType(EltTy))
1572 return Error(TypeLoc, "invalid array element type");
1573 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1578 //===----------------------------------------------------------------------===//
1579 // Function Semantic Analysis.
1580 //===----------------------------------------------------------------------===//
1582 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1585 // Insert unnamed arguments into the NumberedVals list.
1586 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1589 NumberedVals.push_back(AI);
1592 LLParser::PerFunctionState::~PerFunctionState() {
1593 // If there were any forward referenced non-basicblock values, delete them.
1594 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1595 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1596 if (!isa<BasicBlock>(I->second.first)) {
1597 I->second.first->replaceAllUsesWith(
1598 UndefValue::get(I->second.first->getType()));
1599 delete I->second.first;
1600 I->second.first = 0;
1603 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1604 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1605 if (!isa<BasicBlock>(I->second.first)) {
1606 I->second.first->replaceAllUsesWith(
1607 UndefValue::get(I->second.first->getType()));
1608 delete I->second.first;
1609 I->second.first = 0;
1613 bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1614 if (!ForwardRefVals.empty())
1615 return P.Error(ForwardRefVals.begin()->second.second,
1616 "use of undefined value '%" + ForwardRefVals.begin()->first +
1618 if (!ForwardRefValIDs.empty())
1619 return P.Error(ForwardRefValIDs.begin()->second.second,
1620 "use of undefined value '%" +
1621 utostr(ForwardRefValIDs.begin()->first) + "'");
1626 /// GetVal - Get a value with the specified name or ID, creating a
1627 /// forward reference record if needed. This can return null if the value
1628 /// exists but does not have the right type.
1629 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1630 const Type *Ty, LocTy Loc) {
1631 // Look this name up in the normal function symbol table.
1632 Value *Val = F.getValueSymbolTable().lookup(Name);
1634 // If this is a forward reference for the value, see if we already created a
1635 // forward ref record.
1637 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1638 I = ForwardRefVals.find(Name);
1639 if (I != ForwardRefVals.end())
1640 Val = I->second.first;
1643 // If we have the value in the symbol table or fwd-ref table, return it.
1645 if (Val->getType() == Ty) return Val;
1646 if (Ty->isLabelTy())
1647 P.Error(Loc, "'%" + Name + "' is not a basic block");
1649 P.Error(Loc, "'%" + Name + "' defined with type '" +
1650 Val->getType()->getDescription() + "'");
1654 // Don't make placeholders with invalid type.
1655 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1656 Ty != Type::getLabelTy(F.getContext())) {
1657 P.Error(Loc, "invalid use of a non-first-class type");
1661 // Otherwise, create a new forward reference for this value and remember it.
1663 if (Ty->isLabelTy())
1664 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
1666 FwdVal = new Argument(Ty, Name);
1668 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1672 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1674 // Look this name up in the normal function symbol table.
1675 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1677 // If this is a forward reference for the value, see if we already created a
1678 // forward ref record.
1680 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1681 I = ForwardRefValIDs.find(ID);
1682 if (I != ForwardRefValIDs.end())
1683 Val = I->second.first;
1686 // If we have the value in the symbol table or fwd-ref table, return it.
1688 if (Val->getType() == Ty) return Val;
1689 if (Ty->isLabelTy())
1690 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1692 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1693 Val->getType()->getDescription() + "'");
1697 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1698 Ty != Type::getLabelTy(F.getContext())) {
1699 P.Error(Loc, "invalid use of a non-first-class type");
1703 // Otherwise, create a new forward reference for this value and remember it.
1705 if (Ty->isLabelTy())
1706 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
1708 FwdVal = new Argument(Ty);
1710 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1714 /// SetInstName - After an instruction is parsed and inserted into its
1715 /// basic block, this installs its name.
1716 bool LLParser::PerFunctionState::SetInstName(int NameID,
1717 const std::string &NameStr,
1718 LocTy NameLoc, Instruction *Inst) {
1719 // If this instruction has void type, it cannot have a name or ID specified.
1720 if (Inst->getType()->isVoidTy()) {
1721 if (NameID != -1 || !NameStr.empty())
1722 return P.Error(NameLoc, "instructions returning void cannot have a name");
1726 // If this was a numbered instruction, verify that the instruction is the
1727 // expected value and resolve any forward references.
1728 if (NameStr.empty()) {
1729 // If neither a name nor an ID was specified, just use the next ID.
1731 NameID = NumberedVals.size();
1733 if (unsigned(NameID) != NumberedVals.size())
1734 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1735 utostr(NumberedVals.size()) + "'");
1737 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1738 ForwardRefValIDs.find(NameID);
1739 if (FI != ForwardRefValIDs.end()) {
1740 if (FI->second.first->getType() != Inst->getType())
1741 return P.Error(NameLoc, "instruction forward referenced with type '" +
1742 FI->second.first->getType()->getDescription() + "'");
1743 FI->second.first->replaceAllUsesWith(Inst);
1744 delete FI->second.first;
1745 ForwardRefValIDs.erase(FI);
1748 NumberedVals.push_back(Inst);
1752 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1753 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1754 FI = ForwardRefVals.find(NameStr);
1755 if (FI != ForwardRefVals.end()) {
1756 if (FI->second.first->getType() != Inst->getType())
1757 return P.Error(NameLoc, "instruction forward referenced with type '" +
1758 FI->second.first->getType()->getDescription() + "'");
1759 FI->second.first->replaceAllUsesWith(Inst);
1760 delete FI->second.first;
1761 ForwardRefVals.erase(FI);
1764 // Set the name on the instruction.
1765 Inst->setName(NameStr);
1767 if (Inst->getNameStr() != NameStr)
1768 return P.Error(NameLoc, "multiple definition of local value named '" +
1773 /// GetBB - Get a basic block with the specified name or ID, creating a
1774 /// forward reference record if needed.
1775 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1777 return cast_or_null<BasicBlock>(GetVal(Name,
1778 Type::getLabelTy(F.getContext()), Loc));
1781 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1782 return cast_or_null<BasicBlock>(GetVal(ID,
1783 Type::getLabelTy(F.getContext()), Loc));
1786 /// DefineBB - Define the specified basic block, which is either named or
1787 /// unnamed. If there is an error, this returns null otherwise it returns
1788 /// the block being defined.
1789 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1793 BB = GetBB(NumberedVals.size(), Loc);
1795 BB = GetBB(Name, Loc);
1796 if (BB == 0) return 0; // Already diagnosed error.
1798 // Move the block to the end of the function. Forward ref'd blocks are
1799 // inserted wherever they happen to be referenced.
1800 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1802 // Remove the block from forward ref sets.
1804 ForwardRefValIDs.erase(NumberedVals.size());
1805 NumberedVals.push_back(BB);
1807 // BB forward references are already in the function symbol table.
1808 ForwardRefVals.erase(Name);
1814 //===----------------------------------------------------------------------===//
1816 //===----------------------------------------------------------------------===//
1818 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1819 /// type implied. For example, if we parse "4" we don't know what integer type
1820 /// it has. The value will later be combined with its type and checked for
1822 bool LLParser::ParseValID(ValID &ID) {
1823 ID.Loc = Lex.getLoc();
1824 switch (Lex.getKind()) {
1825 default: return TokError("expected value token");
1826 case lltok::GlobalID: // @42
1827 ID.UIntVal = Lex.getUIntVal();
1828 ID.Kind = ValID::t_GlobalID;
1830 case lltok::GlobalVar: // @foo
1831 ID.StrVal = Lex.getStrVal();
1832 ID.Kind = ValID::t_GlobalName;
1834 case lltok::LocalVarID: // %42
1835 ID.UIntVal = Lex.getUIntVal();
1836 ID.Kind = ValID::t_LocalID;
1838 case lltok::LocalVar: // %foo
1839 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1840 ID.StrVal = Lex.getStrVal();
1841 ID.Kind = ValID::t_LocalName;
1843 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
1844 ID.Kind = ValID::t_Metadata;
1846 if (Lex.getKind() == lltok::lbrace) {
1847 SmallVector<Value*, 16> Elts;
1848 if (ParseMDNodeVector(Elts) ||
1849 ParseToken(lltok::rbrace, "expected end of metadata node"))
1852 ID.MetadataVal = MDNode::get(Context, Elts.data(), Elts.size());
1856 // Standalone metadata reference
1857 // !{ ..., !42, ... }
1858 if (!ParseMDNode(ID.MetadataVal))
1862 // ::= '!' STRINGCONSTANT
1863 if (ParseMDString(ID.MetadataVal)) return true;
1864 ID.Kind = ValID::t_Metadata;
1868 ID.APSIntVal = Lex.getAPSIntVal();
1869 ID.Kind = ValID::t_APSInt;
1871 case lltok::APFloat:
1872 ID.APFloatVal = Lex.getAPFloatVal();
1873 ID.Kind = ValID::t_APFloat;
1875 case lltok::kw_true:
1876 ID.ConstantVal = ConstantInt::getTrue(Context);
1877 ID.Kind = ValID::t_Constant;
1879 case lltok::kw_false:
1880 ID.ConstantVal = ConstantInt::getFalse(Context);
1881 ID.Kind = ValID::t_Constant;
1883 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1884 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1885 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1887 case lltok::lbrace: {
1888 // ValID ::= '{' ConstVector '}'
1890 SmallVector<Constant*, 16> Elts;
1891 if (ParseGlobalValueVector(Elts) ||
1892 ParseToken(lltok::rbrace, "expected end of struct constant"))
1895 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
1896 Elts.size(), false);
1897 ID.Kind = ValID::t_Constant;
1901 // ValID ::= '<' ConstVector '>' --> Vector.
1902 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1904 bool isPackedStruct = EatIfPresent(lltok::lbrace);
1906 SmallVector<Constant*, 16> Elts;
1907 LocTy FirstEltLoc = Lex.getLoc();
1908 if (ParseGlobalValueVector(Elts) ||
1910 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1911 ParseToken(lltok::greater, "expected end of constant"))
1914 if (isPackedStruct) {
1916 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
1917 ID.Kind = ValID::t_Constant;
1922 return Error(ID.Loc, "constant vector must not be empty");
1924 if (!Elts[0]->getType()->isInteger() &&
1925 !Elts[0]->getType()->isFloatingPoint())
1926 return Error(FirstEltLoc,
1927 "vector elements must have integer or floating point type");
1929 // Verify that all the vector elements have the same type.
1930 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1931 if (Elts[i]->getType() != Elts[0]->getType())
1932 return Error(FirstEltLoc,
1933 "vector element #" + utostr(i) +
1934 " is not of type '" + Elts[0]->getType()->getDescription());
1936 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
1937 ID.Kind = ValID::t_Constant;
1940 case lltok::lsquare: { // Array Constant
1942 SmallVector<Constant*, 16> Elts;
1943 LocTy FirstEltLoc = Lex.getLoc();
1944 if (ParseGlobalValueVector(Elts) ||
1945 ParseToken(lltok::rsquare, "expected end of array constant"))
1948 // Handle empty element.
1950 // Use undef instead of an array because it's inconvenient to determine
1951 // the element type at this point, there being no elements to examine.
1952 ID.Kind = ValID::t_EmptyArray;
1956 if (!Elts[0]->getType()->isFirstClassType())
1957 return Error(FirstEltLoc, "invalid array element type: " +
1958 Elts[0]->getType()->getDescription());
1960 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
1962 // Verify all elements are correct type!
1963 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
1964 if (Elts[i]->getType() != Elts[0]->getType())
1965 return Error(FirstEltLoc,
1966 "array element #" + utostr(i) +
1967 " is not of type '" +Elts[0]->getType()->getDescription());
1970 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
1971 ID.Kind = ValID::t_Constant;
1974 case lltok::kw_c: // c "foo"
1976 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
1977 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1978 ID.Kind = ValID::t_Constant;
1981 case lltok::kw_asm: {
1982 // ValID ::= 'asm' SideEffect? MsAsm? STRINGCONSTANT ',' STRINGCONSTANT
1983 bool HasSideEffect, MsAsm;
1985 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
1986 ParseOptionalToken(lltok::kw_msasm, MsAsm) ||
1987 ParseStringConstant(ID.StrVal) ||
1988 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
1989 ParseToken(lltok::StringConstant, "expected constraint string"))
1991 ID.StrVal2 = Lex.getStrVal();
1992 ID.UIntVal = HasSideEffect | ((unsigned)MsAsm<<1);
1993 ID.Kind = ValID::t_InlineAsm;
1997 case lltok::kw_trunc:
1998 case lltok::kw_zext:
1999 case lltok::kw_sext:
2000 case lltok::kw_fptrunc:
2001 case lltok::kw_fpext:
2002 case lltok::kw_bitcast:
2003 case lltok::kw_uitofp:
2004 case lltok::kw_sitofp:
2005 case lltok::kw_fptoui:
2006 case lltok::kw_fptosi:
2007 case lltok::kw_inttoptr:
2008 case lltok::kw_ptrtoint: {
2009 unsigned Opc = Lex.getUIntVal();
2010 PATypeHolder DestTy(Type::getVoidTy(Context));
2013 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2014 ParseGlobalTypeAndValue(SrcVal) ||
2015 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2016 ParseType(DestTy) ||
2017 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2019 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2020 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2021 SrcVal->getType()->getDescription() + "' to '" +
2022 DestTy->getDescription() + "'");
2023 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2025 ID.Kind = ValID::t_Constant;
2028 case lltok::kw_extractvalue: {
2031 SmallVector<unsigned, 4> Indices;
2032 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2033 ParseGlobalTypeAndValue(Val) ||
2034 ParseIndexList(Indices) ||
2035 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2037 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
2038 return Error(ID.Loc, "extractvalue operand must be array or struct");
2039 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2041 return Error(ID.Loc, "invalid indices for extractvalue");
2043 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
2044 ID.Kind = ValID::t_Constant;
2047 case lltok::kw_insertvalue: {
2049 Constant *Val0, *Val1;
2050 SmallVector<unsigned, 4> Indices;
2051 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2052 ParseGlobalTypeAndValue(Val0) ||
2053 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2054 ParseGlobalTypeAndValue(Val1) ||
2055 ParseIndexList(Indices) ||
2056 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2058 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
2059 return Error(ID.Loc, "extractvalue operand must be array or struct");
2060 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2062 return Error(ID.Loc, "invalid indices for insertvalue");
2063 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
2064 Indices.data(), Indices.size());
2065 ID.Kind = ValID::t_Constant;
2068 case lltok::kw_icmp:
2069 case lltok::kw_fcmp: {
2070 unsigned PredVal, Opc = Lex.getUIntVal();
2071 Constant *Val0, *Val1;
2073 if (ParseCmpPredicate(PredVal, Opc) ||
2074 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2075 ParseGlobalTypeAndValue(Val0) ||
2076 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2077 ParseGlobalTypeAndValue(Val1) ||
2078 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2081 if (Val0->getType() != Val1->getType())
2082 return Error(ID.Loc, "compare operands must have the same type");
2084 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2086 if (Opc == Instruction::FCmp) {
2087 if (!Val0->getType()->isFPOrFPVector())
2088 return Error(ID.Loc, "fcmp requires floating point operands");
2089 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2091 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2092 if (!Val0->getType()->isIntOrIntVector() &&
2093 !isa<PointerType>(Val0->getType()))
2094 return Error(ID.Loc, "icmp requires pointer or integer operands");
2095 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2097 ID.Kind = ValID::t_Constant;
2101 // Binary Operators.
2103 case lltok::kw_fadd:
2105 case lltok::kw_fsub:
2107 case lltok::kw_fmul:
2108 case lltok::kw_udiv:
2109 case lltok::kw_sdiv:
2110 case lltok::kw_fdiv:
2111 case lltok::kw_urem:
2112 case lltok::kw_srem:
2113 case lltok::kw_frem: {
2117 unsigned Opc = Lex.getUIntVal();
2118 Constant *Val0, *Val1;
2120 LocTy ModifierLoc = Lex.getLoc();
2121 if (Opc == Instruction::Add ||
2122 Opc == Instruction::Sub ||
2123 Opc == Instruction::Mul) {
2124 if (EatIfPresent(lltok::kw_nuw))
2126 if (EatIfPresent(lltok::kw_nsw)) {
2128 if (EatIfPresent(lltok::kw_nuw))
2131 } else if (Opc == Instruction::SDiv) {
2132 if (EatIfPresent(lltok::kw_exact))
2135 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2136 ParseGlobalTypeAndValue(Val0) ||
2137 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2138 ParseGlobalTypeAndValue(Val1) ||
2139 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2141 if (Val0->getType() != Val1->getType())
2142 return Error(ID.Loc, "operands of constexpr must have same type");
2143 if (!Val0->getType()->isIntOrIntVector()) {
2145 return Error(ModifierLoc, "nuw only applies to integer operations");
2147 return Error(ModifierLoc, "nsw only applies to integer operations");
2149 // API compatibility: Accept either integer or floating-point types with
2150 // add, sub, and mul.
2151 if (!Val0->getType()->isIntOrIntVector() &&
2152 !Val0->getType()->isFPOrFPVector())
2153 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
2155 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2156 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2157 if (Exact) Flags |= SDivOperator::IsExact;
2158 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2160 ID.Kind = ValID::t_Constant;
2164 // Logical Operations
2166 case lltok::kw_lshr:
2167 case lltok::kw_ashr:
2170 case lltok::kw_xor: {
2171 unsigned Opc = Lex.getUIntVal();
2172 Constant *Val0, *Val1;
2174 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2175 ParseGlobalTypeAndValue(Val0) ||
2176 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2177 ParseGlobalTypeAndValue(Val1) ||
2178 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2180 if (Val0->getType() != Val1->getType())
2181 return Error(ID.Loc, "operands of constexpr must have same type");
2182 if (!Val0->getType()->isIntOrIntVector())
2183 return Error(ID.Loc,
2184 "constexpr requires integer or integer vector operands");
2185 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2186 ID.Kind = ValID::t_Constant;
2190 case lltok::kw_getelementptr:
2191 case lltok::kw_shufflevector:
2192 case lltok::kw_insertelement:
2193 case lltok::kw_extractelement:
2194 case lltok::kw_select: {
2195 unsigned Opc = Lex.getUIntVal();
2196 SmallVector<Constant*, 16> Elts;
2197 bool InBounds = false;
2199 if (Opc == Instruction::GetElementPtr)
2200 InBounds = EatIfPresent(lltok::kw_inbounds);
2201 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2202 ParseGlobalValueVector(Elts) ||
2203 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2206 if (Opc == Instruction::GetElementPtr) {
2207 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
2208 return Error(ID.Loc, "getelementptr requires pointer operand");
2210 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
2211 (Value**)(Elts.data() + 1),
2213 return Error(ID.Loc, "invalid indices for getelementptr");
2214 ID.ConstantVal = InBounds ?
2215 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2218 ConstantExpr::getGetElementPtr(Elts[0],
2219 Elts.data() + 1, Elts.size() - 1);
2220 } else if (Opc == Instruction::Select) {
2221 if (Elts.size() != 3)
2222 return Error(ID.Loc, "expected three operands to select");
2223 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2225 return Error(ID.Loc, Reason);
2226 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2227 } else if (Opc == Instruction::ShuffleVector) {
2228 if (Elts.size() != 3)
2229 return Error(ID.Loc, "expected three operands to shufflevector");
2230 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2231 return Error(ID.Loc, "invalid operands to shufflevector");
2233 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2234 } else if (Opc == Instruction::ExtractElement) {
2235 if (Elts.size() != 2)
2236 return Error(ID.Loc, "expected two operands to extractelement");
2237 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2238 return Error(ID.Loc, "invalid extractelement operands");
2239 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2241 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2242 if (Elts.size() != 3)
2243 return Error(ID.Loc, "expected three operands to insertelement");
2244 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2245 return Error(ID.Loc, "invalid insertelement operands");
2247 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2250 ID.Kind = ValID::t_Constant;
2259 /// ParseGlobalValue - Parse a global value with the specified type.
2260 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2263 return ParseValID(ID) ||
2264 ConvertGlobalValIDToValue(Ty, ID, V);
2267 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2269 bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2271 if (isa<FunctionType>(Ty))
2272 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2275 default: llvm_unreachable("Unknown ValID!");
2276 case ValID::t_Metadata:
2277 return Error(ID.Loc, "invalid use of metadata");
2278 case ValID::t_LocalID:
2279 case ValID::t_LocalName:
2280 return Error(ID.Loc, "invalid use of function-local name");
2281 case ValID::t_InlineAsm:
2282 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2283 case ValID::t_GlobalName:
2284 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2286 case ValID::t_GlobalID:
2287 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2289 case ValID::t_APSInt:
2290 if (!isa<IntegerType>(Ty))
2291 return Error(ID.Loc, "integer constant must have integer type");
2292 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2293 V = ConstantInt::get(Context, ID.APSIntVal);
2295 case ValID::t_APFloat:
2296 if (!Ty->isFloatingPoint() ||
2297 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2298 return Error(ID.Loc, "floating point constant invalid for type");
2300 // The lexer has no type info, so builds all float and double FP constants
2301 // as double. Fix this here. Long double does not need this.
2302 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2305 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2308 V = ConstantFP::get(Context, ID.APFloatVal);
2310 if (V->getType() != Ty)
2311 return Error(ID.Loc, "floating point constant does not have type '" +
2312 Ty->getDescription() + "'");
2316 if (!isa<PointerType>(Ty))
2317 return Error(ID.Loc, "null must be a pointer type");
2318 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2320 case ValID::t_Undef:
2321 // FIXME: LabelTy should not be a first-class type.
2322 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
2323 !isa<OpaqueType>(Ty))
2324 return Error(ID.Loc, "invalid type for undef constant");
2325 V = UndefValue::get(Ty);
2327 case ValID::t_EmptyArray:
2328 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2329 return Error(ID.Loc, "invalid empty array initializer");
2330 V = UndefValue::get(Ty);
2333 // FIXME: LabelTy should not be a first-class type.
2334 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2335 return Error(ID.Loc, "invalid type for null constant");
2336 V = Constant::getNullValue(Ty);
2338 case ValID::t_Constant:
2339 if (ID.ConstantVal->getType() != Ty)
2340 return Error(ID.Loc, "constant expression type mismatch");
2346 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2347 PATypeHolder Type(Type::getVoidTy(Context));
2348 return ParseType(Type) ||
2349 ParseGlobalValue(Type, V);
2352 /// ParseGlobalValueVector
2354 /// ::= TypeAndValue (',' TypeAndValue)*
2355 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2357 if (Lex.getKind() == lltok::rbrace ||
2358 Lex.getKind() == lltok::rsquare ||
2359 Lex.getKind() == lltok::greater ||
2360 Lex.getKind() == lltok::rparen)
2364 if (ParseGlobalTypeAndValue(C)) return true;
2367 while (EatIfPresent(lltok::comma)) {
2368 if (ParseGlobalTypeAndValue(C)) return true;
2376 //===----------------------------------------------------------------------===//
2377 // Function Parsing.
2378 //===----------------------------------------------------------------------===//
2380 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2381 PerFunctionState &PFS) {
2382 if (ID.Kind == ValID::t_LocalID)
2383 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2384 else if (ID.Kind == ValID::t_LocalName)
2385 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
2386 else if (ID.Kind == ValID::t_InlineAsm) {
2387 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2388 const FunctionType *FTy =
2389 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2390 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2391 return Error(ID.Loc, "invalid type for inline asm constraint string");
2392 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2394 } else if (ID.Kind == ValID::t_Metadata) {
2398 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2406 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2409 return ParseValID(ID) ||
2410 ConvertValIDToValue(Ty, ID, V, PFS);
2413 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2414 PATypeHolder T(Type::getVoidTy(Context));
2415 return ParseType(T) ||
2416 ParseValue(T, V, PFS);
2420 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2421 /// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2422 /// OptionalAlign OptGC
2423 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2424 // Parse the linkage.
2425 LocTy LinkageLoc = Lex.getLoc();
2428 unsigned Visibility, RetAttrs;
2430 PATypeHolder RetType(Type::getVoidTy(Context));
2431 LocTy RetTypeLoc = Lex.getLoc();
2432 if (ParseOptionalLinkage(Linkage) ||
2433 ParseOptionalVisibility(Visibility) ||
2434 ParseOptionalCallingConv(CC) ||
2435 ParseOptionalAttrs(RetAttrs, 1) ||
2436 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2439 // Verify that the linkage is ok.
2440 switch ((GlobalValue::LinkageTypes)Linkage) {
2441 case GlobalValue::ExternalLinkage:
2442 break; // always ok.
2443 case GlobalValue::DLLImportLinkage:
2444 case GlobalValue::ExternalWeakLinkage:
2446 return Error(LinkageLoc, "invalid linkage for function definition");
2448 case GlobalValue::PrivateLinkage:
2449 case GlobalValue::LinkerPrivateLinkage:
2450 case GlobalValue::InternalLinkage:
2451 case GlobalValue::AvailableExternallyLinkage:
2452 case GlobalValue::LinkOnceAnyLinkage:
2453 case GlobalValue::LinkOnceODRLinkage:
2454 case GlobalValue::WeakAnyLinkage:
2455 case GlobalValue::WeakODRLinkage:
2456 case GlobalValue::DLLExportLinkage:
2458 return Error(LinkageLoc, "invalid linkage for function declaration");
2460 case GlobalValue::AppendingLinkage:
2461 case GlobalValue::GhostLinkage:
2462 case GlobalValue::CommonLinkage:
2463 return Error(LinkageLoc, "invalid function linkage type");
2466 if (!FunctionType::isValidReturnType(RetType) ||
2467 isa<OpaqueType>(RetType))
2468 return Error(RetTypeLoc, "invalid function return type");
2470 LocTy NameLoc = Lex.getLoc();
2472 std::string FunctionName;
2473 if (Lex.getKind() == lltok::GlobalVar) {
2474 FunctionName = Lex.getStrVal();
2475 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2476 unsigned NameID = Lex.getUIntVal();
2478 if (NameID != NumberedVals.size())
2479 return TokError("function expected to be numbered '%" +
2480 utostr(NumberedVals.size()) + "'");
2482 return TokError("expected function name");
2487 if (Lex.getKind() != lltok::lparen)
2488 return TokError("expected '(' in function argument list");
2490 std::vector<ArgInfo> ArgList;
2493 std::string Section;
2497 if (ParseArgumentList(ArgList, isVarArg, false) ||
2498 ParseOptionalAttrs(FuncAttrs, 2) ||
2499 (EatIfPresent(lltok::kw_section) &&
2500 ParseStringConstant(Section)) ||
2501 ParseOptionalAlignment(Alignment) ||
2502 (EatIfPresent(lltok::kw_gc) &&
2503 ParseStringConstant(GC)))
2506 // If the alignment was parsed as an attribute, move to the alignment field.
2507 if (FuncAttrs & Attribute::Alignment) {
2508 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2509 FuncAttrs &= ~Attribute::Alignment;
2512 // Okay, if we got here, the function is syntactically valid. Convert types
2513 // and do semantic checks.
2514 std::vector<const Type*> ParamTypeList;
2515 SmallVector<AttributeWithIndex, 8> Attrs;
2516 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2518 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2519 if (FuncAttrs & ObsoleteFuncAttrs) {
2520 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2521 FuncAttrs &= ~ObsoleteFuncAttrs;
2524 if (RetAttrs != Attribute::None)
2525 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2527 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2528 ParamTypeList.push_back(ArgList[i].Type);
2529 if (ArgList[i].Attrs != Attribute::None)
2530 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2533 if (FuncAttrs != Attribute::None)
2534 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2536 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2538 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2539 RetType != Type::getVoidTy(Context))
2540 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2542 const FunctionType *FT =
2543 FunctionType::get(RetType, ParamTypeList, isVarArg);
2544 const PointerType *PFT = PointerType::getUnqual(FT);
2547 if (!FunctionName.empty()) {
2548 // If this was a definition of a forward reference, remove the definition
2549 // from the forward reference table and fill in the forward ref.
2550 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2551 ForwardRefVals.find(FunctionName);
2552 if (FRVI != ForwardRefVals.end()) {
2553 Fn = M->getFunction(FunctionName);
2554 ForwardRefVals.erase(FRVI);
2555 } else if ((Fn = M->getFunction(FunctionName))) {
2556 // If this function already exists in the symbol table, then it is
2557 // multiply defined. We accept a few cases for old backwards compat.
2558 // FIXME: Remove this stuff for LLVM 3.0.
2559 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2560 (!Fn->isDeclaration() && isDefine)) {
2561 // If the redefinition has different type or different attributes,
2562 // reject it. If both have bodies, reject it.
2563 return Error(NameLoc, "invalid redefinition of function '" +
2564 FunctionName + "'");
2565 } else if (Fn->isDeclaration()) {
2566 // Make sure to strip off any argument names so we can't get conflicts.
2567 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2574 // If this is a definition of a forward referenced function, make sure the
2576 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2577 = ForwardRefValIDs.find(NumberedVals.size());
2578 if (I != ForwardRefValIDs.end()) {
2579 Fn = cast<Function>(I->second.first);
2580 if (Fn->getType() != PFT)
2581 return Error(NameLoc, "type of definition and forward reference of '@" +
2582 utostr(NumberedVals.size()) +"' disagree");
2583 ForwardRefValIDs.erase(I);
2588 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2589 else // Move the forward-reference to the correct spot in the module.
2590 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2592 if (FunctionName.empty())
2593 NumberedVals.push_back(Fn);
2595 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2596 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2597 Fn->setCallingConv(CC);
2598 Fn->setAttributes(PAL);
2599 Fn->setAlignment(Alignment);
2600 Fn->setSection(Section);
2601 if (!GC.empty()) Fn->setGC(GC.c_str());
2603 // Add all of the arguments we parsed to the function.
2604 Function::arg_iterator ArgIt = Fn->arg_begin();
2605 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2606 // If the argument has a name, insert it into the argument symbol table.
2607 if (ArgList[i].Name.empty()) continue;
2609 // Set the name, if it conflicted, it will be auto-renamed.
2610 ArgIt->setName(ArgList[i].Name);
2612 if (ArgIt->getNameStr() != ArgList[i].Name)
2613 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2614 ArgList[i].Name + "'");
2621 /// ParseFunctionBody
2622 /// ::= '{' BasicBlock+ '}'
2623 /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2625 bool LLParser::ParseFunctionBody(Function &Fn) {
2626 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2627 return TokError("expected '{' in function body");
2628 Lex.Lex(); // eat the {.
2630 PerFunctionState PFS(*this, Fn);
2632 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2633 if (ParseBasicBlock(PFS)) return true;
2638 // Verify function is ok.
2639 return PFS.VerifyFunctionComplete();
2643 /// ::= LabelStr? Instruction*
2644 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2645 // If this basic block starts out with a name, remember it.
2647 LocTy NameLoc = Lex.getLoc();
2648 if (Lex.getKind() == lltok::LabelStr) {
2649 Name = Lex.getStrVal();
2653 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2654 if (BB == 0) return true;
2656 std::string NameStr;
2658 // Parse the instructions in this block until we get a terminator.
2661 // This instruction may have three possibilities for a name: a) none
2662 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2663 LocTy NameLoc = Lex.getLoc();
2667 if (Lex.getKind() == lltok::LocalVarID) {
2668 NameID = Lex.getUIntVal();
2670 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2672 } else if (Lex.getKind() == lltok::LocalVar ||
2673 // FIXME: REMOVE IN LLVM 3.0
2674 Lex.getKind() == lltok::StringConstant) {
2675 NameStr = Lex.getStrVal();
2677 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2681 if (ParseInstruction(Inst, BB, PFS)) return true;
2682 if (EatIfPresent(lltok::comma))
2683 ParseOptionalCustomMetadata();
2685 // Set metadata attached with this instruction.
2686 MetadataContext &TheMetadata = M->getContext().getMetadata();
2687 for (SmallVector<std::pair<unsigned, MDNode *>, 2>::iterator
2688 MDI = MDsOnInst.begin(), MDE = MDsOnInst.end(); MDI != MDE; ++MDI)
2689 TheMetadata.addMD(MDI->first, MDI->second, Inst);
2692 BB->getInstList().push_back(Inst);
2694 // Set the name on the instruction.
2695 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2696 } while (!isa<TerminatorInst>(Inst));
2701 //===----------------------------------------------------------------------===//
2702 // Instruction Parsing.
2703 //===----------------------------------------------------------------------===//
2705 /// ParseInstruction - Parse one of the many different instructions.
2707 bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2708 PerFunctionState &PFS) {
2709 lltok::Kind Token = Lex.getKind();
2710 if (Token == lltok::Eof)
2711 return TokError("found end of file when expecting more instructions");
2712 LocTy Loc = Lex.getLoc();
2713 unsigned KeywordVal = Lex.getUIntVal();
2714 Lex.Lex(); // Eat the keyword.
2717 default: return Error(Loc, "expected instruction opcode");
2718 // Terminator Instructions.
2719 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2720 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
2721 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2722 case lltok::kw_br: return ParseBr(Inst, PFS);
2723 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2724 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2725 // Binary Operators.
2728 case lltok::kw_mul: {
2731 LocTy ModifierLoc = Lex.getLoc();
2732 if (EatIfPresent(lltok::kw_nuw))
2734 if (EatIfPresent(lltok::kw_nsw)) {
2736 if (EatIfPresent(lltok::kw_nuw))
2739 // API compatibility: Accept either integer or floating-point types.
2740 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
2742 if (!Inst->getType()->isIntOrIntVector()) {
2744 return Error(ModifierLoc, "nuw only applies to integer operations");
2746 return Error(ModifierLoc, "nsw only applies to integer operations");
2749 cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
2751 cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
2755 case lltok::kw_fadd:
2756 case lltok::kw_fsub:
2757 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2759 case lltok::kw_sdiv: {
2761 if (EatIfPresent(lltok::kw_exact))
2763 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2766 cast<BinaryOperator>(Inst)->setIsExact(true);
2770 case lltok::kw_udiv:
2771 case lltok::kw_urem:
2772 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2773 case lltok::kw_fdiv:
2774 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2776 case lltok::kw_lshr:
2777 case lltok::kw_ashr:
2780 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
2781 case lltok::kw_icmp:
2782 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
2784 case lltok::kw_trunc:
2785 case lltok::kw_zext:
2786 case lltok::kw_sext:
2787 case lltok::kw_fptrunc:
2788 case lltok::kw_fpext:
2789 case lltok::kw_bitcast:
2790 case lltok::kw_uitofp:
2791 case lltok::kw_sitofp:
2792 case lltok::kw_fptoui:
2793 case lltok::kw_fptosi:
2794 case lltok::kw_inttoptr:
2795 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
2797 case lltok::kw_select: return ParseSelect(Inst, PFS);
2798 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
2799 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2800 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2801 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2802 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2803 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2804 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2806 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
2807 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, BB, false);
2808 case lltok::kw_free: return ParseFree(Inst, PFS);
2809 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2810 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2811 case lltok::kw_volatile:
2812 if (EatIfPresent(lltok::kw_load))
2813 return ParseLoad(Inst, PFS, true);
2814 else if (EatIfPresent(lltok::kw_store))
2815 return ParseStore(Inst, PFS, true);
2817 return TokError("expected 'load' or 'store'");
2818 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2819 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2820 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2821 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2825 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2826 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2827 if (Opc == Instruction::FCmp) {
2828 switch (Lex.getKind()) {
2829 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2830 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2831 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2832 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2833 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2834 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2835 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2836 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2837 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2838 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2839 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2840 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2841 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2842 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2843 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2844 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2845 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2848 switch (Lex.getKind()) {
2849 default: TokError("expected icmp predicate (e.g. 'eq')");
2850 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2851 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2852 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2853 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2854 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2855 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2856 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2857 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2858 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2859 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2866 //===----------------------------------------------------------------------===//
2867 // Terminator Instructions.
2868 //===----------------------------------------------------------------------===//
2870 /// ParseRet - Parse a return instruction.
2871 /// ::= 'ret' void (',' !dbg, !1)
2872 /// ::= 'ret' TypeAndValue (',' !dbg, !1)
2873 /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)
2874 /// [[obsolete: LLVM 3.0]]
2875 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2876 PerFunctionState &PFS) {
2877 PATypeHolder Ty(Type::getVoidTy(Context));
2878 if (ParseType(Ty, true /*void allowed*/)) return true;
2880 if (Ty->isVoidTy()) {
2881 Inst = ReturnInst::Create(Context);
2886 if (ParseValue(Ty, RV, PFS)) return true;
2888 if (EatIfPresent(lltok::comma)) {
2889 // Parse optional custom metadata, e.g. !dbg
2890 if (Lex.getKind() == lltok::NamedOrCustomMD) {
2891 if (ParseOptionalCustomMetadata()) return true;
2893 // The normal case is one return value.
2894 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2895 // of 'ret {i32,i32} {i32 1, i32 2}'
2896 SmallVector<Value*, 8> RVs;
2900 // If optional custom metadata, e.g. !dbg is seen then this is the
2902 if (Lex.getKind() == lltok::NamedOrCustomMD)
2904 if (ParseTypeAndValue(RV, PFS)) return true;
2906 } while (EatIfPresent(lltok::comma));
2908 RV = UndefValue::get(PFS.getFunction().getReturnType());
2909 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2910 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2911 BB->getInstList().push_back(I);
2917 Inst = ReturnInst::Create(Context, RV);
2923 /// ::= 'br' TypeAndValue
2924 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2925 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2927 Value *Op0, *Op1, *Op2;
2928 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2930 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2931 Inst = BranchInst::Create(BB);
2935 if (Op0->getType() != Type::getInt1Ty(Context))
2936 return Error(Loc, "branch condition must have 'i1' type");
2938 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2939 ParseTypeAndValue(Op1, Loc, PFS) ||
2940 ParseToken(lltok::comma, "expected ',' after true destination") ||
2941 ParseTypeAndValue(Op2, Loc2, PFS))
2944 if (!isa<BasicBlock>(Op1))
2945 return Error(Loc, "true destination of branch must be a basic block");
2946 if (!isa<BasicBlock>(Op2))
2947 return Error(Loc2, "true destination of branch must be a basic block");
2949 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2955 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2957 /// ::= (TypeAndValue ',' TypeAndValue)*
2958 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2959 LocTy CondLoc, BBLoc;
2960 Value *Cond, *DefaultBB;
2961 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2962 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2963 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2964 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2967 if (!isa<IntegerType>(Cond->getType()))
2968 return Error(CondLoc, "switch condition must have integer type");
2969 if (!isa<BasicBlock>(DefaultBB))
2970 return Error(BBLoc, "default destination must be a basic block");
2972 // Parse the jump table pairs.
2973 SmallPtrSet<Value*, 32> SeenCases;
2974 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2975 while (Lex.getKind() != lltok::rsquare) {
2976 Value *Constant, *DestBB;
2978 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2979 ParseToken(lltok::comma, "expected ',' after case value") ||
2980 ParseTypeAndValue(DestBB, BBLoc, PFS))
2983 if (!SeenCases.insert(Constant))
2984 return Error(CondLoc, "duplicate case value in switch");
2985 if (!isa<ConstantInt>(Constant))
2986 return Error(CondLoc, "case value is not a constant integer");
2987 if (!isa<BasicBlock>(DestBB))
2988 return Error(BBLoc, "case destination is not a basic block");
2990 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2991 cast<BasicBlock>(DestBB)));
2994 Lex.Lex(); // Eat the ']'.
2996 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2998 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2999 SI->addCase(Table[i].first, Table[i].second);
3005 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3006 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3007 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3008 LocTy CallLoc = Lex.getLoc();
3009 unsigned RetAttrs, FnAttrs;
3011 PATypeHolder RetType(Type::getVoidTy(Context));
3014 SmallVector<ParamInfo, 16> ArgList;
3016 Value *NormalBB, *UnwindBB;
3017 if (ParseOptionalCallingConv(CC) ||
3018 ParseOptionalAttrs(RetAttrs, 1) ||
3019 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3020 ParseValID(CalleeID) ||
3021 ParseParameterList(ArgList, PFS) ||
3022 ParseOptionalAttrs(FnAttrs, 2) ||
3023 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3024 ParseTypeAndValue(NormalBB, PFS) ||
3025 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3026 ParseTypeAndValue(UnwindBB, PFS))
3029 if (!isa<BasicBlock>(NormalBB))
3030 return Error(CallLoc, "normal destination is not a basic block");
3031 if (!isa<BasicBlock>(UnwindBB))
3032 return Error(CallLoc, "unwind destination is not a basic block");
3034 // If RetType is a non-function pointer type, then this is the short syntax
3035 // for the call, which means that RetType is just the return type. Infer the
3036 // rest of the function argument types from the arguments that are present.
3037 const PointerType *PFTy = 0;
3038 const FunctionType *Ty = 0;
3039 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3040 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3041 // Pull out the types of all of the arguments...
3042 std::vector<const Type*> ParamTypes;
3043 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3044 ParamTypes.push_back(ArgList[i].V->getType());
3046 if (!FunctionType::isValidReturnType(RetType))
3047 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3049 Ty = FunctionType::get(RetType, ParamTypes, false);
3050 PFTy = PointerType::getUnqual(Ty);
3053 // Look up the callee.
3055 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3057 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3058 // function attributes.
3059 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3060 if (FnAttrs & ObsoleteFuncAttrs) {
3061 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3062 FnAttrs &= ~ObsoleteFuncAttrs;
3065 // Set up the Attributes for the function.
3066 SmallVector<AttributeWithIndex, 8> Attrs;
3067 if (RetAttrs != Attribute::None)
3068 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3070 SmallVector<Value*, 8> Args;
3072 // Loop through FunctionType's arguments and ensure they are specified
3073 // correctly. Also, gather any parameter attributes.
3074 FunctionType::param_iterator I = Ty->param_begin();
3075 FunctionType::param_iterator E = Ty->param_end();
3076 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3077 const Type *ExpectedTy = 0;
3080 } else if (!Ty->isVarArg()) {
3081 return Error(ArgList[i].Loc, "too many arguments specified");
3084 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3085 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3086 ExpectedTy->getDescription() + "'");
3087 Args.push_back(ArgList[i].V);
3088 if (ArgList[i].Attrs != Attribute::None)
3089 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3093 return Error(CallLoc, "not enough parameters specified for call");
3095 if (FnAttrs != Attribute::None)
3096 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3098 // Finish off the Attributes and check them
3099 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3101 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
3102 cast<BasicBlock>(UnwindBB),
3103 Args.begin(), Args.end());
3104 II->setCallingConv(CC);
3105 II->setAttributes(PAL);
3112 //===----------------------------------------------------------------------===//
3113 // Binary Operators.
3114 //===----------------------------------------------------------------------===//
3117 /// ::= ArithmeticOps TypeAndValue ',' Value
3119 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3120 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3121 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3122 unsigned Opc, unsigned OperandType) {
3123 LocTy Loc; Value *LHS, *RHS;
3124 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3125 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3126 ParseValue(LHS->getType(), RHS, PFS))
3130 switch (OperandType) {
3131 default: llvm_unreachable("Unknown operand type!");
3132 case 0: // int or FP.
3133 Valid = LHS->getType()->isIntOrIntVector() ||
3134 LHS->getType()->isFPOrFPVector();
3136 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
3137 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
3141 return Error(Loc, "invalid operand type for instruction");
3143 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3148 /// ::= ArithmeticOps TypeAndValue ',' Value {
3149 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3151 LocTy Loc; Value *LHS, *RHS;
3152 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3153 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3154 ParseValue(LHS->getType(), RHS, PFS))
3157 if (!LHS->getType()->isIntOrIntVector())
3158 return Error(Loc,"instruction requires integer or integer vector operands");
3160 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3166 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3167 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3168 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3170 // Parse the integer/fp comparison predicate.
3174 if (ParseCmpPredicate(Pred, Opc) ||
3175 ParseTypeAndValue(LHS, Loc, PFS) ||
3176 ParseToken(lltok::comma, "expected ',' after compare value") ||
3177 ParseValue(LHS->getType(), RHS, PFS))
3180 if (Opc == Instruction::FCmp) {
3181 if (!LHS->getType()->isFPOrFPVector())
3182 return Error(Loc, "fcmp requires floating point operands");
3183 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3185 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3186 if (!LHS->getType()->isIntOrIntVector() &&
3187 !isa<PointerType>(LHS->getType()))
3188 return Error(Loc, "icmp requires integer operands");
3189 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3194 //===----------------------------------------------------------------------===//
3195 // Other Instructions.
3196 //===----------------------------------------------------------------------===//
3200 /// ::= CastOpc TypeAndValue 'to' Type
3201 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3203 LocTy Loc; Value *Op;
3204 PATypeHolder DestTy(Type::getVoidTy(Context));
3205 if (ParseTypeAndValue(Op, Loc, PFS) ||
3206 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3210 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3211 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3212 return Error(Loc, "invalid cast opcode for cast from '" +
3213 Op->getType()->getDescription() + "' to '" +
3214 DestTy->getDescription() + "'");
3216 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3221 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3222 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3224 Value *Op0, *Op1, *Op2;
3225 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3226 ParseToken(lltok::comma, "expected ',' after select condition") ||
3227 ParseTypeAndValue(Op1, PFS) ||
3228 ParseToken(lltok::comma, "expected ',' after select value") ||
3229 ParseTypeAndValue(Op2, PFS))
3232 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3233 return Error(Loc, Reason);
3235 Inst = SelectInst::Create(Op0, Op1, Op2);
3240 /// ::= 'va_arg' TypeAndValue ',' Type
3241 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3243 PATypeHolder EltTy(Type::getVoidTy(Context));
3245 if (ParseTypeAndValue(Op, PFS) ||
3246 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3247 ParseType(EltTy, TypeLoc))
3250 if (!EltTy->isFirstClassType())
3251 return Error(TypeLoc, "va_arg requires operand with first class type");
3253 Inst = new VAArgInst(Op, EltTy);
3257 /// ParseExtractElement
3258 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3259 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3262 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3263 ParseToken(lltok::comma, "expected ',' after extract value") ||
3264 ParseTypeAndValue(Op1, PFS))
3267 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3268 return Error(Loc, "invalid extractelement operands");
3270 Inst = ExtractElementInst::Create(Op0, Op1);
3274 /// ParseInsertElement
3275 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3276 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3278 Value *Op0, *Op1, *Op2;
3279 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3280 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3281 ParseTypeAndValue(Op1, PFS) ||
3282 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3283 ParseTypeAndValue(Op2, PFS))
3286 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3287 return Error(Loc, "invalid insertelement operands");
3289 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3293 /// ParseShuffleVector
3294 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3295 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3297 Value *Op0, *Op1, *Op2;
3298 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3299 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3300 ParseTypeAndValue(Op1, PFS) ||
3301 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3302 ParseTypeAndValue(Op2, PFS))
3305 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3306 return Error(Loc, "invalid extractelement operands");
3308 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3313 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3314 bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3315 PATypeHolder Ty(Type::getVoidTy(Context));
3317 LocTy TypeLoc = Lex.getLoc();
3319 if (ParseType(Ty) ||
3320 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3321 ParseValue(Ty, Op0, PFS) ||
3322 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3323 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3324 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3327 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3329 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3331 if (!EatIfPresent(lltok::comma))
3334 if (Lex.getKind() == lltok::NamedOrCustomMD)
3337 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3338 ParseValue(Ty, Op0, PFS) ||
3339 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3340 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3341 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3345 if (Lex.getKind() == lltok::NamedOrCustomMD)
3346 if (ParseOptionalCustomMetadata()) return true;
3348 if (!Ty->isFirstClassType())
3349 return Error(TypeLoc, "phi node must have first class type");
3351 PHINode *PN = PHINode::Create(Ty);
3352 PN->reserveOperandSpace(PHIVals.size());
3353 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3354 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3360 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3361 /// ParameterList OptionalAttrs
3362 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3364 unsigned RetAttrs, FnAttrs;
3366 PATypeHolder RetType(Type::getVoidTy(Context));
3369 SmallVector<ParamInfo, 16> ArgList;
3370 LocTy CallLoc = Lex.getLoc();
3372 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3373 ParseOptionalCallingConv(CC) ||
3374 ParseOptionalAttrs(RetAttrs, 1) ||
3375 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3376 ParseValID(CalleeID) ||
3377 ParseParameterList(ArgList, PFS) ||
3378 ParseOptionalAttrs(FnAttrs, 2))
3381 // If RetType is a non-function pointer type, then this is the short syntax
3382 // for the call, which means that RetType is just the return type. Infer the
3383 // rest of the function argument types from the arguments that are present.
3384 const PointerType *PFTy = 0;
3385 const FunctionType *Ty = 0;
3386 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3387 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3388 // Pull out the types of all of the arguments...
3389 std::vector<const Type*> ParamTypes;
3390 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3391 ParamTypes.push_back(ArgList[i].V->getType());
3393 if (!FunctionType::isValidReturnType(RetType))
3394 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3396 Ty = FunctionType::get(RetType, ParamTypes, false);
3397 PFTy = PointerType::getUnqual(Ty);
3400 // Look up the callee.
3402 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3404 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3405 // function attributes.
3406 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3407 if (FnAttrs & ObsoleteFuncAttrs) {
3408 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3409 FnAttrs &= ~ObsoleteFuncAttrs;
3412 // Set up the Attributes for the function.
3413 SmallVector<AttributeWithIndex, 8> Attrs;
3414 if (RetAttrs != Attribute::None)
3415 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3417 SmallVector<Value*, 8> Args;
3419 // Loop through FunctionType's arguments and ensure they are specified
3420 // correctly. Also, gather any parameter attributes.
3421 FunctionType::param_iterator I = Ty->param_begin();
3422 FunctionType::param_iterator E = Ty->param_end();
3423 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3424 const Type *ExpectedTy = 0;
3427 } else if (!Ty->isVarArg()) {
3428 return Error(ArgList[i].Loc, "too many arguments specified");
3431 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3432 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3433 ExpectedTy->getDescription() + "'");
3434 Args.push_back(ArgList[i].V);
3435 if (ArgList[i].Attrs != Attribute::None)
3436 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3440 return Error(CallLoc, "not enough parameters specified for call");
3442 if (FnAttrs != Attribute::None)
3443 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3445 // Finish off the Attributes and check them
3446 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3448 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3449 CI->setTailCall(isTail);
3450 CI->setCallingConv(CC);
3451 CI->setAttributes(PAL);
3456 //===----------------------------------------------------------------------===//
3457 // Memory Instructions.
3458 //===----------------------------------------------------------------------===//
3461 /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3462 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
3463 bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3464 BasicBlock* BB, bool isAlloca) {
3465 PATypeHolder Ty(Type::getVoidTy(Context));
3468 unsigned Alignment = 0;
3469 if (ParseType(Ty)) return true;
3471 if (EatIfPresent(lltok::comma)) {
3472 if (Lex.getKind() == lltok::kw_align
3473 || Lex.getKind() == lltok::NamedOrCustomMD) {
3474 if (ParseOptionalInfo(Alignment)) return true;
3476 if (ParseTypeAndValue(Size, SizeLoc, PFS)) return true;
3477 if (EatIfPresent(lltok::comma))
3478 if (ParseOptionalInfo(Alignment)) return true;
3482 if (Size && Size->getType() != Type::getInt32Ty(Context))
3483 return Error(SizeLoc, "element count must be i32");
3486 Inst = new AllocaInst(Ty, Size, Alignment);
3488 // Autoupgrade old malloc instruction to malloc call.
3489 const Type* IntPtrTy = Type::getInt32Ty(Context);
3490 const Type* Int8PtrTy = PointerType::getUnqual(Type::getInt8Ty(Context));
3492 // Prototype malloc as "void *autoupgrade_malloc(int32)".
3493 MallocF = cast<Function>(M->getOrInsertFunction("autoupgrade_malloc",
3494 Int8PtrTy, IntPtrTy, NULL));
3495 // "autoupgrade_malloc" updated to "malloc" in ValidateEndOfModule().
3497 Inst = cast<Instruction>(CallInst::CreateMalloc(BB, IntPtrTy, Ty,
3504 /// ::= 'free' TypeAndValue
3505 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3506 Value *Val; LocTy Loc;
3507 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3508 if (!isa<PointerType>(Val->getType()))
3509 return Error(Loc, "operand to free must be a pointer");
3510 Inst = new FreeInst(Val);
3515 /// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
3516 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3518 Value *Val; LocTy Loc;
3519 unsigned Alignment = 0;
3520 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3522 if (EatIfPresent(lltok::comma))
3523 if (ParseOptionalInfo(Alignment)) return true;
3525 if (!isa<PointerType>(Val->getType()) ||
3526 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3527 return Error(Loc, "load operand must be a pointer to a first class type");
3529 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3534 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3535 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3537 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3538 unsigned Alignment = 0;
3539 if (ParseTypeAndValue(Val, Loc, PFS) ||
3540 ParseToken(lltok::comma, "expected ',' after store operand") ||
3541 ParseTypeAndValue(Ptr, PtrLoc, PFS))
3544 if (EatIfPresent(lltok::comma))
3545 if (ParseOptionalInfo(Alignment)) return true;
3547 if (!isa<PointerType>(Ptr->getType()))
3548 return Error(PtrLoc, "store operand must be a pointer");
3549 if (!Val->getType()->isFirstClassType())
3550 return Error(Loc, "store operand must be a first class value");
3551 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3552 return Error(Loc, "stored value and pointer type do not match");
3554 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3559 /// ::= 'getresult' TypeAndValue ',' i32
3560 /// FIXME: Remove support for getresult in LLVM 3.0
3561 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3562 Value *Val; LocTy ValLoc, EltLoc;
3564 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3565 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3566 ParseUInt32(Element, EltLoc))
3569 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3570 return Error(ValLoc, "getresult inst requires an aggregate operand");
3571 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3572 return Error(EltLoc, "invalid getresult index for value");
3573 Inst = ExtractValueInst::Create(Val, Element);
3577 /// ParseGetElementPtr
3578 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
3579 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3580 Value *Ptr, *Val; LocTy Loc, EltLoc;
3582 bool InBounds = EatIfPresent(lltok::kw_inbounds);
3584 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3586 if (!isa<PointerType>(Ptr->getType()))
3587 return Error(Loc, "base of getelementptr must be a pointer");
3589 SmallVector<Value*, 16> Indices;
3590 while (EatIfPresent(lltok::comma)) {
3591 if (Lex.getKind() == lltok::NamedOrCustomMD)
3593 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3594 if (!isa<IntegerType>(Val->getType()))
3595 return Error(EltLoc, "getelementptr index must be an integer");
3596 Indices.push_back(Val);
3598 if (Lex.getKind() == lltok::NamedOrCustomMD)
3599 if (ParseOptionalCustomMetadata()) return true;
3601 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3602 Indices.begin(), Indices.end()))
3603 return Error(Loc, "invalid getelementptr indices");
3604 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3606 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
3610 /// ParseExtractValue
3611 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3612 bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3613 Value *Val; LocTy Loc;
3614 SmallVector<unsigned, 4> Indices;
3615 if (ParseTypeAndValue(Val, Loc, PFS) ||
3616 ParseIndexList(Indices))
3619 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3620 return Error(Loc, "extractvalue operand must be array or struct");
3622 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3624 return Error(Loc, "invalid indices for extractvalue");
3625 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3629 /// ParseInsertValue
3630 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3631 bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3632 Value *Val0, *Val1; LocTy Loc0, Loc1;
3633 SmallVector<unsigned, 4> Indices;
3634 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3635 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3636 ParseTypeAndValue(Val1, Loc1, PFS) ||
3637 ParseIndexList(Indices))
3640 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3641 return Error(Loc0, "extractvalue operand must be array or struct");
3643 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3645 return Error(Loc0, "invalid indices for insertvalue");
3646 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3650 //===----------------------------------------------------------------------===//
3651 // Embedded metadata.
3652 //===----------------------------------------------------------------------===//
3654 /// ParseMDNodeVector
3655 /// ::= Element (',' Element)*
3657 /// ::= 'null' | TypeAndValue
3658 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
3659 assert(Lex.getKind() == lltok::lbrace);
3663 if (Lex.getKind() == lltok::kw_null) {
3667 PATypeHolder Ty(Type::getVoidTy(Context));
3668 if (ParseType(Ty)) return true;
3669 if (Lex.getKind() == lltok::Metadata) {
3671 MetadataBase *Node = 0;
3672 if (!ParseMDNode(Node))
3675 MetadataBase *MDS = 0;
3676 if (ParseMDString(MDS)) return true;
3681 if (ParseGlobalValue(Ty, C)) return true;
3686 } while (EatIfPresent(lltok::comma));