1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the parser class for .ll files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "LLParser.h"
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/IR/AutoUpgrade.h"
17 #include "llvm/IR/CallingConv.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/InlineAsm.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Operator.h"
25 #include "llvm/IR/ValueSymbolTable.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
28 using namespace llvm;
29
getTypeString(Type * T)30 static std::string getTypeString(Type *T) {
31 std::string Result;
32 raw_string_ostream Tmp(Result);
33 Tmp << *T;
34 return Tmp.str();
35 }
36
37 /// Run: module ::= toplevelentity*
Run()38 bool LLParser::Run() {
39 // Prime the lexer.
40 Lex.Lex();
41
42 return ParseTopLevelEntities() ||
43 ValidateEndOfModule();
44 }
45
46 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
47 /// module.
ValidateEndOfModule()48 bool LLParser::ValidateEndOfModule() {
49 // Handle any instruction metadata forward references.
50 if (!ForwardRefInstMetadata.empty()) {
51 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
52 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
53 I != E; ++I) {
54 Instruction *Inst = I->first;
55 const std::vector<MDRef> &MDList = I->second;
56
57 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
58 unsigned SlotNo = MDList[i].MDSlot;
59
60 if (SlotNo >= NumberedMetadata.size() ||
61 NumberedMetadata[SlotNo] == nullptr)
62 return Error(MDList[i].Loc, "use of undefined metadata '!" +
63 Twine(SlotNo) + "'");
64 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
65 }
66 }
67 ForwardRefInstMetadata.clear();
68 }
69
70 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
71 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
72
73 // Handle any function attribute group forward references.
74 for (std::map<Value*, std::vector<unsigned> >::iterator
75 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
76 I != E; ++I) {
77 Value *V = I->first;
78 std::vector<unsigned> &Vec = I->second;
79 AttrBuilder B;
80
81 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
82 VI != VE; ++VI)
83 B.merge(NumberedAttrBuilders[*VI]);
84
85 if (Function *Fn = dyn_cast<Function>(V)) {
86 AttributeSet AS = Fn->getAttributes();
87 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
88 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
89 AS.getFnAttributes());
90
91 FnAttrs.merge(B);
92
93 // If the alignment was parsed as an attribute, move to the alignment
94 // field.
95 if (FnAttrs.hasAlignmentAttr()) {
96 Fn->setAlignment(FnAttrs.getAlignment());
97 FnAttrs.removeAttribute(Attribute::Alignment);
98 }
99
100 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
101 AttributeSet::get(Context,
102 AttributeSet::FunctionIndex,
103 FnAttrs));
104 Fn->setAttributes(AS);
105 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
106 AttributeSet AS = CI->getAttributes();
107 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
108 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
109 AS.getFnAttributes());
110 FnAttrs.merge(B);
111 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
112 AttributeSet::get(Context,
113 AttributeSet::FunctionIndex,
114 FnAttrs));
115 CI->setAttributes(AS);
116 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
117 AttributeSet AS = II->getAttributes();
118 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
119 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
120 AS.getFnAttributes());
121 FnAttrs.merge(B);
122 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
123 AttributeSet::get(Context,
124 AttributeSet::FunctionIndex,
125 FnAttrs));
126 II->setAttributes(AS);
127 } else {
128 llvm_unreachable("invalid object with forward attribute group reference");
129 }
130 }
131
132 // If there are entries in ForwardRefBlockAddresses at this point, they are
133 // references after the function was defined. Resolve those now.
134 while (!ForwardRefBlockAddresses.empty()) {
135 // Okay, we are referencing an already-parsed function, resolve them now.
136 Function *TheFn = nullptr;
137 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
138 if (Fn.Kind == ValID::t_GlobalName)
139 TheFn = M->getFunction(Fn.StrVal);
140 else if (Fn.UIntVal < NumberedVals.size())
141 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
142
143 if (!TheFn)
144 return Error(Fn.Loc, "unknown function referenced by blockaddress");
145
146 // Resolve all these references.
147 if (ResolveForwardRefBlockAddresses(TheFn,
148 ForwardRefBlockAddresses.begin()->second,
149 nullptr))
150 return true;
151
152 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
153 }
154
155 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
156 if (NumberedTypes[i].second.isValid())
157 return Error(NumberedTypes[i].second,
158 "use of undefined type '%" + Twine(i) + "'");
159
160 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
161 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
162 if (I->second.second.isValid())
163 return Error(I->second.second,
164 "use of undefined type named '" + I->getKey() + "'");
165
166 if (!ForwardRefComdats.empty())
167 return Error(ForwardRefComdats.begin()->second,
168 "use of undefined comdat '$" +
169 ForwardRefComdats.begin()->first + "'");
170
171 if (!ForwardRefVals.empty())
172 return Error(ForwardRefVals.begin()->second.second,
173 "use of undefined value '@" + ForwardRefVals.begin()->first +
174 "'");
175
176 if (!ForwardRefValIDs.empty())
177 return Error(ForwardRefValIDs.begin()->second.second,
178 "use of undefined value '@" +
179 Twine(ForwardRefValIDs.begin()->first) + "'");
180
181 if (!ForwardRefMDNodes.empty())
182 return Error(ForwardRefMDNodes.begin()->second.second,
183 "use of undefined metadata '!" +
184 Twine(ForwardRefMDNodes.begin()->first) + "'");
185
186
187 // Look for intrinsic functions and CallInst that need to be upgraded
188 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
189 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
190
191 UpgradeDebugInfo(*M);
192
193 return false;
194 }
195
ResolveForwardRefBlockAddresses(Function * TheFn,std::vector<std::pair<ValID,GlobalValue * >> & Refs,PerFunctionState * PFS)196 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
197 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
198 PerFunctionState *PFS) {
199 // Loop over all the references, resolving them.
200 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
201 BasicBlock *Res;
202 if (PFS) {
203 if (Refs[i].first.Kind == ValID::t_LocalName)
204 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
205 else
206 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
207 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
208 return Error(Refs[i].first.Loc,
209 "cannot take address of numeric label after the function is defined");
210 } else {
211 Res = dyn_cast_or_null<BasicBlock>(
212 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
213 }
214
215 if (!Res)
216 return Error(Refs[i].first.Loc,
217 "referenced value is not a basic block");
218
219 // Get the BlockAddress for this and update references to use it.
220 BlockAddress *BA = BlockAddress::get(TheFn, Res);
221 Refs[i].second->replaceAllUsesWith(BA);
222 Refs[i].second->eraseFromParent();
223 }
224 return false;
225 }
226
227
228 //===----------------------------------------------------------------------===//
229 // Top-Level Entities
230 //===----------------------------------------------------------------------===//
231
ParseTopLevelEntities()232 bool LLParser::ParseTopLevelEntities() {
233 while (1) {
234 switch (Lex.getKind()) {
235 default: return TokError("expected top-level entity");
236 case lltok::Eof: return false;
237 case lltok::kw_declare: if (ParseDeclare()) return true; break;
238 case lltok::kw_define: if (ParseDefine()) return true; break;
239 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
240 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
241 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
242 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
243 case lltok::LocalVar: if (ParseNamedType()) return true; break;
244 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
245 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
246 case lltok::ComdatVar: if (parseComdat()) return true; break;
247 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
248 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
249
250 // The Global variable production with no name can have many different
251 // optional leading prefixes, the production is:
252 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
253 // OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
254 // ('constant'|'global') ...
255 case lltok::kw_private: // OptionalLinkage
256 case lltok::kw_internal: // OptionalLinkage
257 case lltok::kw_linker_private: // Obsolete OptionalLinkage
258 case lltok::kw_linker_private_weak: // Obsolete OptionalLinkage
259 case lltok::kw_weak: // OptionalLinkage
260 case lltok::kw_weak_odr: // OptionalLinkage
261 case lltok::kw_linkonce: // OptionalLinkage
262 case lltok::kw_linkonce_odr: // OptionalLinkage
263 case lltok::kw_appending: // OptionalLinkage
264 case lltok::kw_common: // OptionalLinkage
265 case lltok::kw_extern_weak: // OptionalLinkage
266 case lltok::kw_external: // OptionalLinkage
267 case lltok::kw_default: // OptionalVisibility
268 case lltok::kw_hidden: // OptionalVisibility
269 case lltok::kw_protected: // OptionalVisibility
270 case lltok::kw_dllimport: // OptionalDLLStorageClass
271 case lltok::kw_dllexport: // OptionalDLLStorageClass
272 case lltok::kw_thread_local: // OptionalThreadLocal
273 case lltok::kw_addrspace: // OptionalAddrSpace
274 case lltok::kw_constant: // GlobalType
275 case lltok::kw_global: { // GlobalType
276 unsigned Linkage, Visibility, DLLStorageClass;
277 bool UnnamedAddr;
278 GlobalVariable::ThreadLocalMode TLM;
279 bool HasLinkage;
280 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
281 ParseOptionalVisibility(Visibility) ||
282 ParseOptionalDLLStorageClass(DLLStorageClass) ||
283 ParseOptionalThreadLocal(TLM) ||
284 parseOptionalUnnamedAddr(UnnamedAddr) ||
285 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
286 DLLStorageClass, TLM, UnnamedAddr))
287 return true;
288 break;
289 }
290
291 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
292 }
293 }
294 }
295
296
297 /// toplevelentity
298 /// ::= 'module' 'asm' STRINGCONSTANT
ParseModuleAsm()299 bool LLParser::ParseModuleAsm() {
300 assert(Lex.getKind() == lltok::kw_module);
301 Lex.Lex();
302
303 std::string AsmStr;
304 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
305 ParseStringConstant(AsmStr)) return true;
306
307 M->appendModuleInlineAsm(AsmStr);
308 return false;
309 }
310
311 /// toplevelentity
312 /// ::= 'target' 'triple' '=' STRINGCONSTANT
313 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
ParseTargetDefinition()314 bool LLParser::ParseTargetDefinition() {
315 assert(Lex.getKind() == lltok::kw_target);
316 std::string Str;
317 switch (Lex.Lex()) {
318 default: return TokError("unknown target property");
319 case lltok::kw_triple:
320 Lex.Lex();
321 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
322 ParseStringConstant(Str))
323 return true;
324 M->setTargetTriple(Str);
325 return false;
326 case lltok::kw_datalayout:
327 Lex.Lex();
328 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
329 ParseStringConstant(Str))
330 return true;
331 M->setDataLayout(Str);
332 return false;
333 }
334 }
335
336 /// toplevelentity
337 /// ::= 'deplibs' '=' '[' ']'
338 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
339 /// FIXME: Remove in 4.0. Currently parse, but ignore.
ParseDepLibs()340 bool LLParser::ParseDepLibs() {
341 assert(Lex.getKind() == lltok::kw_deplibs);
342 Lex.Lex();
343 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
344 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
345 return true;
346
347 if (EatIfPresent(lltok::rsquare))
348 return false;
349
350 do {
351 std::string Str;
352 if (ParseStringConstant(Str)) return true;
353 } while (EatIfPresent(lltok::comma));
354
355 return ParseToken(lltok::rsquare, "expected ']' at end of list");
356 }
357
358 /// ParseUnnamedType:
359 /// ::= LocalVarID '=' 'type' type
ParseUnnamedType()360 bool LLParser::ParseUnnamedType() {
361 LocTy TypeLoc = Lex.getLoc();
362 unsigned TypeID = Lex.getUIntVal();
363 Lex.Lex(); // eat LocalVarID;
364
365 if (ParseToken(lltok::equal, "expected '=' after name") ||
366 ParseToken(lltok::kw_type, "expected 'type' after '='"))
367 return true;
368
369 if (TypeID >= NumberedTypes.size())
370 NumberedTypes.resize(TypeID+1);
371
372 Type *Result = nullptr;
373 if (ParseStructDefinition(TypeLoc, "",
374 NumberedTypes[TypeID], Result)) return true;
375
376 if (!isa<StructType>(Result)) {
377 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
378 if (Entry.first)
379 return Error(TypeLoc, "non-struct types may not be recursive");
380 Entry.first = Result;
381 Entry.second = SMLoc();
382 }
383
384 return false;
385 }
386
387
388 /// toplevelentity
389 /// ::= LocalVar '=' 'type' type
ParseNamedType()390 bool LLParser::ParseNamedType() {
391 std::string Name = Lex.getStrVal();
392 LocTy NameLoc = Lex.getLoc();
393 Lex.Lex(); // eat LocalVar.
394
395 if (ParseToken(lltok::equal, "expected '=' after name") ||
396 ParseToken(lltok::kw_type, "expected 'type' after name"))
397 return true;
398
399 Type *Result = nullptr;
400 if (ParseStructDefinition(NameLoc, Name,
401 NamedTypes[Name], Result)) return true;
402
403 if (!isa<StructType>(Result)) {
404 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
405 if (Entry.first)
406 return Error(NameLoc, "non-struct types may not be recursive");
407 Entry.first = Result;
408 Entry.second = SMLoc();
409 }
410
411 return false;
412 }
413
414
415 /// toplevelentity
416 /// ::= 'declare' FunctionHeader
ParseDeclare()417 bool LLParser::ParseDeclare() {
418 assert(Lex.getKind() == lltok::kw_declare);
419 Lex.Lex();
420
421 Function *F;
422 return ParseFunctionHeader(F, false);
423 }
424
425 /// toplevelentity
426 /// ::= 'define' FunctionHeader '{' ...
ParseDefine()427 bool LLParser::ParseDefine() {
428 assert(Lex.getKind() == lltok::kw_define);
429 Lex.Lex();
430
431 Function *F;
432 return ParseFunctionHeader(F, true) ||
433 ParseFunctionBody(*F);
434 }
435
436 /// ParseGlobalType
437 /// ::= 'constant'
438 /// ::= 'global'
ParseGlobalType(bool & IsConstant)439 bool LLParser::ParseGlobalType(bool &IsConstant) {
440 if (Lex.getKind() == lltok::kw_constant)
441 IsConstant = true;
442 else if (Lex.getKind() == lltok::kw_global)
443 IsConstant = false;
444 else {
445 IsConstant = false;
446 return TokError("expected 'global' or 'constant'");
447 }
448 Lex.Lex();
449 return false;
450 }
451
452 /// ParseUnnamedGlobal:
453 /// OptionalVisibility ALIAS ...
454 /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
455 /// ... -> global variable
456 /// GlobalID '=' OptionalVisibility ALIAS ...
457 /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
458 /// ... -> global variable
ParseUnnamedGlobal()459 bool LLParser::ParseUnnamedGlobal() {
460 unsigned VarID = NumberedVals.size();
461 std::string Name;
462 LocTy NameLoc = Lex.getLoc();
463
464 // Handle the GlobalID form.
465 if (Lex.getKind() == lltok::GlobalID) {
466 if (Lex.getUIntVal() != VarID)
467 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
468 Twine(VarID) + "'");
469 Lex.Lex(); // eat GlobalID;
470
471 if (ParseToken(lltok::equal, "expected '=' after name"))
472 return true;
473 }
474
475 bool HasLinkage;
476 unsigned Linkage, Visibility, DLLStorageClass;
477 GlobalVariable::ThreadLocalMode TLM;
478 bool UnnamedAddr;
479 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
480 ParseOptionalVisibility(Visibility) ||
481 ParseOptionalDLLStorageClass(DLLStorageClass) ||
482 ParseOptionalThreadLocal(TLM) ||
483 parseOptionalUnnamedAddr(UnnamedAddr))
484 return true;
485
486 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
487 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
488 DLLStorageClass, TLM, UnnamedAddr);
489 return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass, TLM,
490 UnnamedAddr);
491 }
492
493 /// ParseNamedGlobal:
494 /// GlobalVar '=' OptionalVisibility ALIAS ...
495 /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
496 /// ... -> global variable
ParseNamedGlobal()497 bool LLParser::ParseNamedGlobal() {
498 assert(Lex.getKind() == lltok::GlobalVar);
499 LocTy NameLoc = Lex.getLoc();
500 std::string Name = Lex.getStrVal();
501 Lex.Lex();
502
503 bool HasLinkage;
504 unsigned Linkage, Visibility, DLLStorageClass;
505 GlobalVariable::ThreadLocalMode TLM;
506 bool UnnamedAddr;
507 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
508 ParseOptionalLinkage(Linkage, HasLinkage) ||
509 ParseOptionalVisibility(Visibility) ||
510 ParseOptionalDLLStorageClass(DLLStorageClass) ||
511 ParseOptionalThreadLocal(TLM) ||
512 parseOptionalUnnamedAddr(UnnamedAddr))
513 return true;
514
515 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
516 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
517 DLLStorageClass, TLM, UnnamedAddr);
518 return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass, TLM,
519 UnnamedAddr);
520 }
521
parseComdat()522 bool LLParser::parseComdat() {
523 assert(Lex.getKind() == lltok::ComdatVar);
524 std::string Name = Lex.getStrVal();
525 LocTy NameLoc = Lex.getLoc();
526 Lex.Lex();
527
528 if (ParseToken(lltok::equal, "expected '=' here"))
529 return true;
530
531 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
532 return TokError("expected comdat type");
533
534 Comdat::SelectionKind SK;
535 switch (Lex.getKind()) {
536 default:
537 return TokError("unknown selection kind");
538 case lltok::kw_any:
539 SK = Comdat::Any;
540 break;
541 case lltok::kw_exactmatch:
542 SK = Comdat::ExactMatch;
543 break;
544 case lltok::kw_largest:
545 SK = Comdat::Largest;
546 break;
547 case lltok::kw_noduplicates:
548 SK = Comdat::NoDuplicates;
549 break;
550 case lltok::kw_samesize:
551 SK = Comdat::SameSize;
552 break;
553 }
554 Lex.Lex();
555
556 // See if the comdat was forward referenced, if so, use the comdat.
557 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
558 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
559 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
560 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
561
562 Comdat *C;
563 if (I != ComdatSymTab.end())
564 C = &I->second;
565 else
566 C = M->getOrInsertComdat(Name);
567 C->setSelectionKind(SK);
568
569 return false;
570 }
571
572 // MDString:
573 // ::= '!' STRINGCONSTANT
ParseMDString(MDString * & Result)574 bool LLParser::ParseMDString(MDString *&Result) {
575 std::string Str;
576 if (ParseStringConstant(Str)) return true;
577 llvm::UpgradeMDStringConstant(Str);
578 Result = MDString::get(Context, Str);
579 return false;
580 }
581
582 // MDNode:
583 // ::= '!' MDNodeNumber
584 //
585 /// This version of ParseMDNodeID returns the slot number and null in the case
586 /// of a forward reference.
ParseMDNodeID(MDNode * & Result,unsigned & SlotNo)587 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
588 // !{ ..., !42, ... }
589 if (ParseUInt32(SlotNo)) return true;
590
591 // Check existing MDNode.
592 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != nullptr)
593 Result = NumberedMetadata[SlotNo];
594 else
595 Result = nullptr;
596 return false;
597 }
598
ParseMDNodeID(MDNode * & Result)599 bool LLParser::ParseMDNodeID(MDNode *&Result) {
600 // !{ ..., !42, ... }
601 unsigned MID = 0;
602 if (ParseMDNodeID(Result, MID)) return true;
603
604 // If not a forward reference, just return it now.
605 if (Result) return false;
606
607 // Otherwise, create MDNode forward reference.
608 MDNode *FwdNode = MDNode::getTemporary(Context, None);
609 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
610
611 if (NumberedMetadata.size() <= MID)
612 NumberedMetadata.resize(MID+1);
613 NumberedMetadata[MID] = FwdNode;
614 Result = FwdNode;
615 return false;
616 }
617
618 /// ParseNamedMetadata:
619 /// !foo = !{ !1, !2 }
ParseNamedMetadata()620 bool LLParser::ParseNamedMetadata() {
621 assert(Lex.getKind() == lltok::MetadataVar);
622 std::string Name = Lex.getStrVal();
623 Lex.Lex();
624
625 if (ParseToken(lltok::equal, "expected '=' here") ||
626 ParseToken(lltok::exclaim, "Expected '!' here") ||
627 ParseToken(lltok::lbrace, "Expected '{' here"))
628 return true;
629
630 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
631 if (Lex.getKind() != lltok::rbrace)
632 do {
633 if (ParseToken(lltok::exclaim, "Expected '!' here"))
634 return true;
635
636 MDNode *N = nullptr;
637 if (ParseMDNodeID(N)) return true;
638 NMD->addOperand(N);
639 } while (EatIfPresent(lltok::comma));
640
641 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
642 return true;
643
644 return false;
645 }
646
647 /// ParseStandaloneMetadata:
648 /// !42 = !{...}
ParseStandaloneMetadata()649 bool LLParser::ParseStandaloneMetadata() {
650 assert(Lex.getKind() == lltok::exclaim);
651 Lex.Lex();
652 unsigned MetadataID = 0;
653
654 LocTy TyLoc;
655 Type *Ty = nullptr;
656 SmallVector<Value *, 16> Elts;
657 if (ParseUInt32(MetadataID) ||
658 ParseToken(lltok::equal, "expected '=' here") ||
659 ParseType(Ty, TyLoc) ||
660 ParseToken(lltok::exclaim, "Expected '!' here") ||
661 ParseToken(lltok::lbrace, "Expected '{' here") ||
662 ParseMDNodeVector(Elts, nullptr) ||
663 ParseToken(lltok::rbrace, "expected end of metadata node"))
664 return true;
665
666 MDNode *Init = MDNode::get(Context, Elts);
667
668 // See if this was forward referenced, if so, handle it.
669 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
670 FI = ForwardRefMDNodes.find(MetadataID);
671 if (FI != ForwardRefMDNodes.end()) {
672 MDNode *Temp = FI->second.first;
673 Temp->replaceAllUsesWith(Init);
674 MDNode::deleteTemporary(Temp);
675 ForwardRefMDNodes.erase(FI);
676
677 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
678 } else {
679 if (MetadataID >= NumberedMetadata.size())
680 NumberedMetadata.resize(MetadataID+1);
681
682 if (NumberedMetadata[MetadataID] != nullptr)
683 return TokError("Metadata id is already used");
684 NumberedMetadata[MetadataID] = Init;
685 }
686
687 return false;
688 }
689
isValidVisibilityForLinkage(unsigned V,unsigned L)690 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
691 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
692 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
693 }
694
695 /// ParseAlias:
696 /// ::= GlobalVar '=' OptionalVisibility OptionalDLLStorageClass
697 /// OptionalThreadLocal OptionalUnNammedAddr 'alias'
698 /// OptionalLinkage Aliasee
699 ///
700 /// Aliasee
701 /// ::= TypeAndValue
702 ///
703 /// Everything through OptionalUnNammedAddr has already been parsed.
704 ///
ParseAlias(const std::string & Name,LocTy NameLoc,unsigned Visibility,unsigned DLLStorageClass,GlobalVariable::ThreadLocalMode TLM,bool UnnamedAddr)705 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
706 unsigned Visibility, unsigned DLLStorageClass,
707 GlobalVariable::ThreadLocalMode TLM,
708 bool UnnamedAddr) {
709 assert(Lex.getKind() == lltok::kw_alias);
710 Lex.Lex();
711 LocTy LinkageLoc = Lex.getLoc();
712 unsigned L;
713 if (ParseOptionalLinkage(L))
714 return true;
715
716 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
717
718 if(!GlobalAlias::isValidLinkage(Linkage))
719 return Error(LinkageLoc, "invalid linkage type for alias");
720
721 if (!isValidVisibilityForLinkage(Visibility, L))
722 return Error(LinkageLoc,
723 "symbol with local linkage must have default visibility");
724
725 Constant *Aliasee;
726 LocTy AliaseeLoc = Lex.getLoc();
727 if (Lex.getKind() != lltok::kw_bitcast &&
728 Lex.getKind() != lltok::kw_getelementptr &&
729 Lex.getKind() != lltok::kw_addrspacecast &&
730 Lex.getKind() != lltok::kw_inttoptr) {
731 if (ParseGlobalTypeAndValue(Aliasee))
732 return true;
733 } else {
734 // The bitcast dest type is not present, it is implied by the dest type.
735 ValID ID;
736 if (ParseValID(ID))
737 return true;
738 if (ID.Kind != ValID::t_Constant)
739 return Error(AliaseeLoc, "invalid aliasee");
740 Aliasee = ID.ConstantVal;
741 }
742
743 Type *AliaseeType = Aliasee->getType();
744 auto *PTy = dyn_cast<PointerType>(AliaseeType);
745 if (!PTy)
746 return Error(AliaseeLoc, "An alias must have pointer type");
747 Type *Ty = PTy->getElementType();
748 unsigned AddrSpace = PTy->getAddressSpace();
749
750 // Okay, create the alias but do not insert it into the module yet.
751 std::unique_ptr<GlobalAlias> GA(
752 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
753 Name, Aliasee, /*Parent*/ nullptr));
754 GA->setThreadLocalMode(TLM);
755 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
756 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
757 GA->setUnnamedAddr(UnnamedAddr);
758
759 // See if this value already exists in the symbol table. If so, it is either
760 // a redefinition or a definition of a forward reference.
761 if (GlobalValue *Val = M->getNamedValue(Name)) {
762 // See if this was a redefinition. If so, there is no entry in
763 // ForwardRefVals.
764 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
765 I = ForwardRefVals.find(Name);
766 if (I == ForwardRefVals.end())
767 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
768
769 // Otherwise, this was a definition of forward ref. Verify that types
770 // agree.
771 if (Val->getType() != GA->getType())
772 return Error(NameLoc,
773 "forward reference and definition of alias have different types");
774
775 // If they agree, just RAUW the old value with the alias and remove the
776 // forward ref info.
777 Val->replaceAllUsesWith(GA.get());
778 Val->eraseFromParent();
779 ForwardRefVals.erase(I);
780 }
781
782 // Insert into the module, we know its name won't collide now.
783 M->getAliasList().push_back(GA.get());
784 assert(GA->getName() == Name && "Should not be a name conflict!");
785
786 // The module owns this now
787 GA.release();
788
789 return false;
790 }
791
792 /// ParseGlobal
793 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
794 /// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
795 /// OptionalExternallyInitialized GlobalType Type Const
796 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
797 /// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
798 /// OptionalExternallyInitialized GlobalType Type Const
799 ///
800 /// Everything up to and including OptionalUnNammedAddr has been parsed
801 /// already.
802 ///
ParseGlobal(const std::string & Name,LocTy NameLoc,unsigned Linkage,bool HasLinkage,unsigned Visibility,unsigned DLLStorageClass,GlobalVariable::ThreadLocalMode TLM,bool UnnamedAddr)803 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
804 unsigned Linkage, bool HasLinkage,
805 unsigned Visibility, unsigned DLLStorageClass,
806 GlobalVariable::ThreadLocalMode TLM,
807 bool UnnamedAddr) {
808 if (!isValidVisibilityForLinkage(Visibility, Linkage))
809 return Error(NameLoc,
810 "symbol with local linkage must have default visibility");
811
812 unsigned AddrSpace;
813 bool IsConstant, IsExternallyInitialized;
814 LocTy IsExternallyInitializedLoc;
815 LocTy TyLoc;
816
817 Type *Ty = nullptr;
818 if (ParseOptionalAddrSpace(AddrSpace) ||
819 ParseOptionalToken(lltok::kw_externally_initialized,
820 IsExternallyInitialized,
821 &IsExternallyInitializedLoc) ||
822 ParseGlobalType(IsConstant) ||
823 ParseType(Ty, TyLoc))
824 return true;
825
826 // If the linkage is specified and is external, then no initializer is
827 // present.
828 Constant *Init = nullptr;
829 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
830 Linkage != GlobalValue::ExternalLinkage)) {
831 if (ParseGlobalValue(Ty, Init))
832 return true;
833 }
834
835 if (Ty->isFunctionTy() || Ty->isLabelTy())
836 return Error(TyLoc, "invalid type for global variable");
837
838 GlobalVariable *GV = nullptr;
839
840 // See if the global was forward referenced, if so, use the global.
841 if (!Name.empty()) {
842 if (GlobalValue *GVal = M->getNamedValue(Name)) {
843 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
844 return Error(NameLoc, "redefinition of global '@" + Name + "'");
845 GV = cast<GlobalVariable>(GVal);
846 }
847 } else {
848 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
849 I = ForwardRefValIDs.find(NumberedVals.size());
850 if (I != ForwardRefValIDs.end()) {
851 GV = cast<GlobalVariable>(I->second.first);
852 ForwardRefValIDs.erase(I);
853 }
854 }
855
856 if (!GV) {
857 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
858 Name, nullptr, GlobalVariable::NotThreadLocal,
859 AddrSpace);
860 } else {
861 if (GV->getType()->getElementType() != Ty)
862 return Error(TyLoc,
863 "forward reference and definition of global have different types");
864
865 // Move the forward-reference to the correct spot in the module.
866 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
867 }
868
869 if (Name.empty())
870 NumberedVals.push_back(GV);
871
872 // Set the parsed properties on the global.
873 if (Init)
874 GV->setInitializer(Init);
875 GV->setConstant(IsConstant);
876 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
877 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
878 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
879 GV->setExternallyInitialized(IsExternallyInitialized);
880 GV->setThreadLocalMode(TLM);
881 GV->setUnnamedAddr(UnnamedAddr);
882
883 // Parse attributes on the global.
884 while (Lex.getKind() == lltok::comma) {
885 Lex.Lex();
886
887 if (Lex.getKind() == lltok::kw_section) {
888 Lex.Lex();
889 GV->setSection(Lex.getStrVal());
890 if (ParseToken(lltok::StringConstant, "expected global section string"))
891 return true;
892 } else if (Lex.getKind() == lltok::kw_align) {
893 unsigned Alignment;
894 if (ParseOptionalAlignment(Alignment)) return true;
895 GV->setAlignment(Alignment);
896 } else {
897 Comdat *C;
898 if (parseOptionalComdat(C))
899 return true;
900 if (C)
901 GV->setComdat(C);
902 else
903 return TokError("unknown global variable property!");
904 }
905 }
906
907 return false;
908 }
909
910 /// ParseUnnamedAttrGrp
911 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
ParseUnnamedAttrGrp()912 bool LLParser::ParseUnnamedAttrGrp() {
913 assert(Lex.getKind() == lltok::kw_attributes);
914 LocTy AttrGrpLoc = Lex.getLoc();
915 Lex.Lex();
916
917 assert(Lex.getKind() == lltok::AttrGrpID);
918 unsigned VarID = Lex.getUIntVal();
919 std::vector<unsigned> unused;
920 LocTy BuiltinLoc;
921 Lex.Lex();
922
923 if (ParseToken(lltok::equal, "expected '=' here") ||
924 ParseToken(lltok::lbrace, "expected '{' here") ||
925 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
926 BuiltinLoc) ||
927 ParseToken(lltok::rbrace, "expected end of attribute group"))
928 return true;
929
930 if (!NumberedAttrBuilders[VarID].hasAttributes())
931 return Error(AttrGrpLoc, "attribute group has no attributes");
932
933 return false;
934 }
935
936 /// ParseFnAttributeValuePairs
937 /// ::= <attr> | <attr> '=' <value>
ParseFnAttributeValuePairs(AttrBuilder & B,std::vector<unsigned> & FwdRefAttrGrps,bool inAttrGrp,LocTy & BuiltinLoc)938 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
939 std::vector<unsigned> &FwdRefAttrGrps,
940 bool inAttrGrp, LocTy &BuiltinLoc) {
941 bool HaveError = false;
942
943 B.clear();
944
945 while (true) {
946 lltok::Kind Token = Lex.getKind();
947 if (Token == lltok::kw_builtin)
948 BuiltinLoc = Lex.getLoc();
949 switch (Token) {
950 default:
951 if (!inAttrGrp) return HaveError;
952 return Error(Lex.getLoc(), "unterminated attribute group");
953 case lltok::rbrace:
954 // Finished.
955 return false;
956
957 case lltok::AttrGrpID: {
958 // Allow a function to reference an attribute group:
959 //
960 // define void @foo() #1 { ... }
961 if (inAttrGrp)
962 HaveError |=
963 Error(Lex.getLoc(),
964 "cannot have an attribute group reference in an attribute group");
965
966 unsigned AttrGrpNum = Lex.getUIntVal();
967 if (inAttrGrp) break;
968
969 // Save the reference to the attribute group. We'll fill it in later.
970 FwdRefAttrGrps.push_back(AttrGrpNum);
971 break;
972 }
973 // Target-dependent attributes:
974 case lltok::StringConstant: {
975 std::string Attr = Lex.getStrVal();
976 Lex.Lex();
977 std::string Val;
978 if (EatIfPresent(lltok::equal) &&
979 ParseStringConstant(Val))
980 return true;
981
982 B.addAttribute(Attr, Val);
983 continue;
984 }
985
986 // Target-independent attributes:
987 case lltok::kw_align: {
988 // As a hack, we allow function alignment to be initially parsed as an
989 // attribute on a function declaration/definition or added to an attribute
990 // group and later moved to the alignment field.
991 unsigned Alignment;
992 if (inAttrGrp) {
993 Lex.Lex();
994 if (ParseToken(lltok::equal, "expected '=' here") ||
995 ParseUInt32(Alignment))
996 return true;
997 } else {
998 if (ParseOptionalAlignment(Alignment))
999 return true;
1000 }
1001 B.addAlignmentAttr(Alignment);
1002 continue;
1003 }
1004 case lltok::kw_alignstack: {
1005 unsigned Alignment;
1006 if (inAttrGrp) {
1007 Lex.Lex();
1008 if (ParseToken(lltok::equal, "expected '=' here") ||
1009 ParseUInt32(Alignment))
1010 return true;
1011 } else {
1012 if (ParseOptionalStackAlignment(Alignment))
1013 return true;
1014 }
1015 B.addStackAlignmentAttr(Alignment);
1016 continue;
1017 }
1018 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1019 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1020 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1021 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1022 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1023 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1024 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1025 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1026 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1027 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
1028 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1029 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1030 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1031 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
1032 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1033 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1034 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1035 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1036 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1037 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
1038 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1039 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1040 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
1041 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
1042 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
1043 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
1044 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
1045
1046 // Error handling.
1047 case lltok::kw_inreg:
1048 case lltok::kw_signext:
1049 case lltok::kw_zeroext:
1050 HaveError |=
1051 Error(Lex.getLoc(),
1052 "invalid use of attribute on a function");
1053 break;
1054 case lltok::kw_byval:
1055 case lltok::kw_inalloca:
1056 case lltok::kw_nest:
1057 case lltok::kw_noalias:
1058 case lltok::kw_nocapture:
1059 case lltok::kw_nonnull:
1060 case lltok::kw_returned:
1061 case lltok::kw_sret:
1062 HaveError |=
1063 Error(Lex.getLoc(),
1064 "invalid use of parameter-only attribute on a function");
1065 break;
1066 }
1067
1068 Lex.Lex();
1069 }
1070 }
1071
1072 //===----------------------------------------------------------------------===//
1073 // GlobalValue Reference/Resolution Routines.
1074 //===----------------------------------------------------------------------===//
1075
1076 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1077 /// forward reference record if needed. This can return null if the value
1078 /// exists but does not have the right type.
GetGlobalVal(const std::string & Name,Type * Ty,LocTy Loc)1079 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1080 LocTy Loc) {
1081 PointerType *PTy = dyn_cast<PointerType>(Ty);
1082 if (!PTy) {
1083 Error(Loc, "global variable reference must have pointer type");
1084 return nullptr;
1085 }
1086
1087 // Look this name up in the normal function symbol table.
1088 GlobalValue *Val =
1089 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1090
1091 // If this is a forward reference for the value, see if we already created a
1092 // forward ref record.
1093 if (!Val) {
1094 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1095 I = ForwardRefVals.find(Name);
1096 if (I != ForwardRefVals.end())
1097 Val = I->second.first;
1098 }
1099
1100 // If we have the value in the symbol table or fwd-ref table, return it.
1101 if (Val) {
1102 if (Val->getType() == Ty) return Val;
1103 Error(Loc, "'@" + Name + "' defined with type '" +
1104 getTypeString(Val->getType()) + "'");
1105 return nullptr;
1106 }
1107
1108 // Otherwise, create a new forward reference for this value and remember it.
1109 GlobalValue *FwdVal;
1110 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1111 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1112 else
1113 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1114 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1115 nullptr, GlobalVariable::NotThreadLocal,
1116 PTy->getAddressSpace());
1117
1118 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1119 return FwdVal;
1120 }
1121
GetGlobalVal(unsigned ID,Type * Ty,LocTy Loc)1122 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1123 PointerType *PTy = dyn_cast<PointerType>(Ty);
1124 if (!PTy) {
1125 Error(Loc, "global variable reference must have pointer type");
1126 return nullptr;
1127 }
1128
1129 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1130
1131 // If this is a forward reference for the value, see if we already created a
1132 // forward ref record.
1133 if (!Val) {
1134 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1135 I = ForwardRefValIDs.find(ID);
1136 if (I != ForwardRefValIDs.end())
1137 Val = I->second.first;
1138 }
1139
1140 // If we have the value in the symbol table or fwd-ref table, return it.
1141 if (Val) {
1142 if (Val->getType() == Ty) return Val;
1143 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1144 getTypeString(Val->getType()) + "'");
1145 return nullptr;
1146 }
1147
1148 // Otherwise, create a new forward reference for this value and remember it.
1149 GlobalValue *FwdVal;
1150 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1151 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1152 else
1153 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1154 GlobalValue::ExternalWeakLinkage, nullptr, "");
1155
1156 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1157 return FwdVal;
1158 }
1159
1160
1161 //===----------------------------------------------------------------------===//
1162 // Comdat Reference/Resolution Routines.
1163 //===----------------------------------------------------------------------===//
1164
getComdat(const std::string & Name,LocTy Loc)1165 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1166 // Look this name up in the comdat symbol table.
1167 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1168 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1169 if (I != ComdatSymTab.end())
1170 return &I->second;
1171
1172 // Otherwise, create a new forward reference for this value and remember it.
1173 Comdat *C = M->getOrInsertComdat(Name);
1174 ForwardRefComdats[Name] = Loc;
1175 return C;
1176 }
1177
1178
1179 //===----------------------------------------------------------------------===//
1180 // Helper Routines.
1181 //===----------------------------------------------------------------------===//
1182
1183 /// ParseToken - If the current token has the specified kind, eat it and return
1184 /// success. Otherwise, emit the specified error and return failure.
ParseToken(lltok::Kind T,const char * ErrMsg)1185 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1186 if (Lex.getKind() != T)
1187 return TokError(ErrMsg);
1188 Lex.Lex();
1189 return false;
1190 }
1191
1192 /// ParseStringConstant
1193 /// ::= StringConstant
ParseStringConstant(std::string & Result)1194 bool LLParser::ParseStringConstant(std::string &Result) {
1195 if (Lex.getKind() != lltok::StringConstant)
1196 return TokError("expected string constant");
1197 Result = Lex.getStrVal();
1198 Lex.Lex();
1199 return false;
1200 }
1201
1202 /// ParseUInt32
1203 /// ::= uint32
ParseUInt32(unsigned & Val)1204 bool LLParser::ParseUInt32(unsigned &Val) {
1205 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1206 return TokError("expected integer");
1207 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1208 if (Val64 != unsigned(Val64))
1209 return TokError("expected 32-bit integer (too large)");
1210 Val = Val64;
1211 Lex.Lex();
1212 return false;
1213 }
1214
1215 /// ParseTLSModel
1216 /// := 'localdynamic'
1217 /// := 'initialexec'
1218 /// := 'localexec'
ParseTLSModel(GlobalVariable::ThreadLocalMode & TLM)1219 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1220 switch (Lex.getKind()) {
1221 default:
1222 return TokError("expected localdynamic, initialexec or localexec");
1223 case lltok::kw_localdynamic:
1224 TLM = GlobalVariable::LocalDynamicTLSModel;
1225 break;
1226 case lltok::kw_initialexec:
1227 TLM = GlobalVariable::InitialExecTLSModel;
1228 break;
1229 case lltok::kw_localexec:
1230 TLM = GlobalVariable::LocalExecTLSModel;
1231 break;
1232 }
1233
1234 Lex.Lex();
1235 return false;
1236 }
1237
1238 /// ParseOptionalThreadLocal
1239 /// := /*empty*/
1240 /// := 'thread_local'
1241 /// := 'thread_local' '(' tlsmodel ')'
ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode & TLM)1242 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1243 TLM = GlobalVariable::NotThreadLocal;
1244 if (!EatIfPresent(lltok::kw_thread_local))
1245 return false;
1246
1247 TLM = GlobalVariable::GeneralDynamicTLSModel;
1248 if (Lex.getKind() == lltok::lparen) {
1249 Lex.Lex();
1250 return ParseTLSModel(TLM) ||
1251 ParseToken(lltok::rparen, "expected ')' after thread local model");
1252 }
1253 return false;
1254 }
1255
1256 /// ParseOptionalAddrSpace
1257 /// := /*empty*/
1258 /// := 'addrspace' '(' uint32 ')'
ParseOptionalAddrSpace(unsigned & AddrSpace)1259 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1260 AddrSpace = 0;
1261 if (!EatIfPresent(lltok::kw_addrspace))
1262 return false;
1263 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1264 ParseUInt32(AddrSpace) ||
1265 ParseToken(lltok::rparen, "expected ')' in address space");
1266 }
1267
1268 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
ParseOptionalParamAttrs(AttrBuilder & B)1269 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1270 bool HaveError = false;
1271
1272 B.clear();
1273
1274 while (1) {
1275 lltok::Kind Token = Lex.getKind();
1276 switch (Token) {
1277 default: // End of attributes.
1278 return HaveError;
1279 case lltok::kw_align: {
1280 unsigned Alignment;
1281 if (ParseOptionalAlignment(Alignment))
1282 return true;
1283 B.addAlignmentAttr(Alignment);
1284 continue;
1285 }
1286 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1287 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1288 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1289 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1290 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1291 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1292 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1293 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1294 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1295 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1296 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1297 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1298 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1299
1300 case lltok::kw_alignstack:
1301 case lltok::kw_alwaysinline:
1302 case lltok::kw_builtin:
1303 case lltok::kw_inlinehint:
1304 case lltok::kw_jumptable:
1305 case lltok::kw_minsize:
1306 case lltok::kw_naked:
1307 case lltok::kw_nobuiltin:
1308 case lltok::kw_noduplicate:
1309 case lltok::kw_noimplicitfloat:
1310 case lltok::kw_noinline:
1311 case lltok::kw_nonlazybind:
1312 case lltok::kw_noredzone:
1313 case lltok::kw_noreturn:
1314 case lltok::kw_nounwind:
1315 case lltok::kw_optnone:
1316 case lltok::kw_optsize:
1317 case lltok::kw_returns_twice:
1318 case lltok::kw_sanitize_address:
1319 case lltok::kw_sanitize_memory:
1320 case lltok::kw_sanitize_thread:
1321 case lltok::kw_ssp:
1322 case lltok::kw_sspreq:
1323 case lltok::kw_sspstrong:
1324 case lltok::kw_uwtable:
1325 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1326 break;
1327 }
1328
1329 Lex.Lex();
1330 }
1331 }
1332
1333 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
ParseOptionalReturnAttrs(AttrBuilder & B)1334 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1335 bool HaveError = false;
1336
1337 B.clear();
1338
1339 while (1) {
1340 lltok::Kind Token = Lex.getKind();
1341 switch (Token) {
1342 default: // End of attributes.
1343 return HaveError;
1344 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1345 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1346 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1347 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1348 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1349
1350 // Error handling.
1351 case lltok::kw_align:
1352 case lltok::kw_byval:
1353 case lltok::kw_inalloca:
1354 case lltok::kw_nest:
1355 case lltok::kw_nocapture:
1356 case lltok::kw_returned:
1357 case lltok::kw_sret:
1358 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1359 break;
1360
1361 case lltok::kw_alignstack:
1362 case lltok::kw_alwaysinline:
1363 case lltok::kw_builtin:
1364 case lltok::kw_cold:
1365 case lltok::kw_inlinehint:
1366 case lltok::kw_jumptable:
1367 case lltok::kw_minsize:
1368 case lltok::kw_naked:
1369 case lltok::kw_nobuiltin:
1370 case lltok::kw_noduplicate:
1371 case lltok::kw_noimplicitfloat:
1372 case lltok::kw_noinline:
1373 case lltok::kw_nonlazybind:
1374 case lltok::kw_noredzone:
1375 case lltok::kw_noreturn:
1376 case lltok::kw_nounwind:
1377 case lltok::kw_optnone:
1378 case lltok::kw_optsize:
1379 case lltok::kw_returns_twice:
1380 case lltok::kw_sanitize_address:
1381 case lltok::kw_sanitize_memory:
1382 case lltok::kw_sanitize_thread:
1383 case lltok::kw_ssp:
1384 case lltok::kw_sspreq:
1385 case lltok::kw_sspstrong:
1386 case lltok::kw_uwtable:
1387 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1388 break;
1389
1390 case lltok::kw_readnone:
1391 case lltok::kw_readonly:
1392 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1393 }
1394
1395 Lex.Lex();
1396 }
1397 }
1398
1399 /// ParseOptionalLinkage
1400 /// ::= /*empty*/
1401 /// ::= 'private'
1402 /// ::= 'internal'
1403 /// ::= 'weak'
1404 /// ::= 'weak_odr'
1405 /// ::= 'linkonce'
1406 /// ::= 'linkonce_odr'
1407 /// ::= 'available_externally'
1408 /// ::= 'appending'
1409 /// ::= 'common'
1410 /// ::= 'extern_weak'
1411 /// ::= 'external'
1412 ///
1413 /// Deprecated Values:
1414 /// ::= 'linker_private'
1415 /// ::= 'linker_private_weak'
ParseOptionalLinkage(unsigned & Res,bool & HasLinkage)1416 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1417 HasLinkage = false;
1418 switch (Lex.getKind()) {
1419 default: Res=GlobalValue::ExternalLinkage; return false;
1420 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1421 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1422 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1423 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1424 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1425 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1426 case lltok::kw_available_externally:
1427 Res = GlobalValue::AvailableExternallyLinkage;
1428 break;
1429 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1430 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1431 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1432 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1433
1434 case lltok::kw_linker_private:
1435 case lltok::kw_linker_private_weak:
1436 Lex.Warning("'" + Lex.getStrVal() + "' is deprecated, treating as"
1437 " PrivateLinkage");
1438 Lex.Lex();
1439 // treat linker_private and linker_private_weak as PrivateLinkage
1440 Res = GlobalValue::PrivateLinkage;
1441 return false;
1442 }
1443 Lex.Lex();
1444 HasLinkage = true;
1445 return false;
1446 }
1447
1448 /// ParseOptionalVisibility
1449 /// ::= /*empty*/
1450 /// ::= 'default'
1451 /// ::= 'hidden'
1452 /// ::= 'protected'
1453 ///
ParseOptionalVisibility(unsigned & Res)1454 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1455 switch (Lex.getKind()) {
1456 default: Res = GlobalValue::DefaultVisibility; return false;
1457 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1458 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1459 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1460 }
1461 Lex.Lex();
1462 return false;
1463 }
1464
1465 /// ParseOptionalDLLStorageClass
1466 /// ::= /*empty*/
1467 /// ::= 'dllimport'
1468 /// ::= 'dllexport'
1469 ///
ParseOptionalDLLStorageClass(unsigned & Res)1470 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1471 switch (Lex.getKind()) {
1472 default: Res = GlobalValue::DefaultStorageClass; return false;
1473 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1474 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1475 }
1476 Lex.Lex();
1477 return false;
1478 }
1479
1480 /// ParseOptionalCallingConv
1481 /// ::= /*empty*/
1482 /// ::= 'ccc'
1483 /// ::= 'fastcc'
1484 /// ::= 'kw_intel_ocl_bicc'
1485 /// ::= 'coldcc'
1486 /// ::= 'x86_stdcallcc'
1487 /// ::= 'x86_fastcallcc'
1488 /// ::= 'x86_thiscallcc'
1489 /// ::= 'arm_apcscc'
1490 /// ::= 'arm_aapcscc'
1491 /// ::= 'arm_aapcs_vfpcc'
1492 /// ::= 'msp430_intrcc'
1493 /// ::= 'ptx_kernel'
1494 /// ::= 'ptx_device'
1495 /// ::= 'spir_func'
1496 /// ::= 'spir_kernel'
1497 /// ::= 'x86_64_sysvcc'
1498 /// ::= 'x86_64_win64cc'
1499 /// ::= 'webkit_jscc'
1500 /// ::= 'anyregcc'
1501 /// ::= 'preserve_mostcc'
1502 /// ::= 'preserve_allcc'
1503 /// ::= 'cc' UINT
1504 ///
ParseOptionalCallingConv(CallingConv::ID & CC)1505 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1506 switch (Lex.getKind()) {
1507 default: CC = CallingConv::C; return false;
1508 case lltok::kw_ccc: CC = CallingConv::C; break;
1509 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1510 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1511 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1512 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1513 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1514 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1515 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1516 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1517 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1518 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1519 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1520 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1521 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1522 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1523 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1524 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1525 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1526 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1527 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1528 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1529 case lltok::kw_cc: {
1530 unsigned ArbitraryCC;
1531 Lex.Lex();
1532 if (ParseUInt32(ArbitraryCC))
1533 return true;
1534 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1535 return false;
1536 }
1537 }
1538
1539 Lex.Lex();
1540 return false;
1541 }
1542
1543 /// ParseInstructionMetadata
1544 /// ::= !dbg !42 (',' !dbg !57)*
ParseInstructionMetadata(Instruction * Inst,PerFunctionState * PFS)1545 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1546 PerFunctionState *PFS) {
1547 do {
1548 if (Lex.getKind() != lltok::MetadataVar)
1549 return TokError("expected metadata after comma");
1550
1551 std::string Name = Lex.getStrVal();
1552 unsigned MDK = M->getMDKindID(Name);
1553 Lex.Lex();
1554
1555 MDNode *Node;
1556 SMLoc Loc = Lex.getLoc();
1557
1558 if (ParseToken(lltok::exclaim, "expected '!' here"))
1559 return true;
1560
1561 // This code is similar to that of ParseMetadataValue, however it needs to
1562 // have special-case code for a forward reference; see the comments on
1563 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1564 // at the top level here.
1565 if (Lex.getKind() == lltok::lbrace) {
1566 ValID ID;
1567 if (ParseMetadataListValue(ID, PFS))
1568 return true;
1569 assert(ID.Kind == ValID::t_MDNode);
1570 Inst->setMetadata(MDK, ID.MDNodeVal);
1571 } else {
1572 unsigned NodeID = 0;
1573 if (ParseMDNodeID(Node, NodeID))
1574 return true;
1575 if (Node) {
1576 // If we got the node, add it to the instruction.
1577 Inst->setMetadata(MDK, Node);
1578 } else {
1579 MDRef R = { Loc, MDK, NodeID };
1580 // Otherwise, remember that this should be resolved later.
1581 ForwardRefInstMetadata[Inst].push_back(R);
1582 }
1583 }
1584
1585 if (MDK == LLVMContext::MD_tbaa)
1586 InstsWithTBAATag.push_back(Inst);
1587
1588 // If this is the end of the list, we're done.
1589 } while (EatIfPresent(lltok::comma));
1590 return false;
1591 }
1592
1593 /// ParseOptionalAlignment
1594 /// ::= /* empty */
1595 /// ::= 'align' 4
ParseOptionalAlignment(unsigned & Alignment)1596 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1597 Alignment = 0;
1598 if (!EatIfPresent(lltok::kw_align))
1599 return false;
1600 LocTy AlignLoc = Lex.getLoc();
1601 if (ParseUInt32(Alignment)) return true;
1602 if (!isPowerOf2_32(Alignment))
1603 return Error(AlignLoc, "alignment is not a power of two");
1604 if (Alignment > Value::MaximumAlignment)
1605 return Error(AlignLoc, "huge alignments are not supported yet");
1606 return false;
1607 }
1608
1609 /// ParseOptionalCommaAlign
1610 /// ::=
1611 /// ::= ',' align 4
1612 ///
1613 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1614 /// end.
ParseOptionalCommaAlign(unsigned & Alignment,bool & AteExtraComma)1615 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1616 bool &AteExtraComma) {
1617 AteExtraComma = false;
1618 while (EatIfPresent(lltok::comma)) {
1619 // Metadata at the end is an early exit.
1620 if (Lex.getKind() == lltok::MetadataVar) {
1621 AteExtraComma = true;
1622 return false;
1623 }
1624
1625 if (Lex.getKind() != lltok::kw_align)
1626 return Error(Lex.getLoc(), "expected metadata or 'align'");
1627
1628 if (ParseOptionalAlignment(Alignment)) return true;
1629 }
1630
1631 return false;
1632 }
1633
1634 /// ParseScopeAndOrdering
1635 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1636 /// else: ::=
1637 ///
1638 /// This sets Scope and Ordering to the parsed values.
ParseScopeAndOrdering(bool isAtomic,SynchronizationScope & Scope,AtomicOrdering & Ordering)1639 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1640 AtomicOrdering &Ordering) {
1641 if (!isAtomic)
1642 return false;
1643
1644 Scope = CrossThread;
1645 if (EatIfPresent(lltok::kw_singlethread))
1646 Scope = SingleThread;
1647
1648 return ParseOrdering(Ordering);
1649 }
1650
1651 /// ParseOrdering
1652 /// ::= AtomicOrdering
1653 ///
1654 /// This sets Ordering to the parsed value.
ParseOrdering(AtomicOrdering & Ordering)1655 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1656 switch (Lex.getKind()) {
1657 default: return TokError("Expected ordering on atomic instruction");
1658 case lltok::kw_unordered: Ordering = Unordered; break;
1659 case lltok::kw_monotonic: Ordering = Monotonic; break;
1660 case lltok::kw_acquire: Ordering = Acquire; break;
1661 case lltok::kw_release: Ordering = Release; break;
1662 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1663 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1664 }
1665 Lex.Lex();
1666 return false;
1667 }
1668
1669 /// ParseOptionalStackAlignment
1670 /// ::= /* empty */
1671 /// ::= 'alignstack' '(' 4 ')'
ParseOptionalStackAlignment(unsigned & Alignment)1672 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1673 Alignment = 0;
1674 if (!EatIfPresent(lltok::kw_alignstack))
1675 return false;
1676 LocTy ParenLoc = Lex.getLoc();
1677 if (!EatIfPresent(lltok::lparen))
1678 return Error(ParenLoc, "expected '('");
1679 LocTy AlignLoc = Lex.getLoc();
1680 if (ParseUInt32(Alignment)) return true;
1681 ParenLoc = Lex.getLoc();
1682 if (!EatIfPresent(lltok::rparen))
1683 return Error(ParenLoc, "expected ')'");
1684 if (!isPowerOf2_32(Alignment))
1685 return Error(AlignLoc, "stack alignment is not a power of two");
1686 return false;
1687 }
1688
1689 /// ParseIndexList - This parses the index list for an insert/extractvalue
1690 /// instruction. This sets AteExtraComma in the case where we eat an extra
1691 /// comma at the end of the line and find that it is followed by metadata.
1692 /// Clients that don't allow metadata can call the version of this function that
1693 /// only takes one argument.
1694 ///
1695 /// ParseIndexList
1696 /// ::= (',' uint32)+
1697 ///
ParseIndexList(SmallVectorImpl<unsigned> & Indices,bool & AteExtraComma)1698 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1699 bool &AteExtraComma) {
1700 AteExtraComma = false;
1701
1702 if (Lex.getKind() != lltok::comma)
1703 return TokError("expected ',' as start of index list");
1704
1705 while (EatIfPresent(lltok::comma)) {
1706 if (Lex.getKind() == lltok::MetadataVar) {
1707 AteExtraComma = true;
1708 return false;
1709 }
1710 unsigned Idx = 0;
1711 if (ParseUInt32(Idx)) return true;
1712 Indices.push_back(Idx);
1713 }
1714
1715 return false;
1716 }
1717
1718 //===----------------------------------------------------------------------===//
1719 // Type Parsing.
1720 //===----------------------------------------------------------------------===//
1721
1722 /// ParseType - Parse a type.
ParseType(Type * & Result,bool AllowVoid)1723 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1724 SMLoc TypeLoc = Lex.getLoc();
1725 switch (Lex.getKind()) {
1726 default:
1727 return TokError("expected type");
1728 case lltok::Type:
1729 // Type ::= 'float' | 'void' (etc)
1730 Result = Lex.getTyVal();
1731 Lex.Lex();
1732 break;
1733 case lltok::lbrace:
1734 // Type ::= StructType
1735 if (ParseAnonStructType(Result, false))
1736 return true;
1737 break;
1738 case lltok::lsquare:
1739 // Type ::= '[' ... ']'
1740 Lex.Lex(); // eat the lsquare.
1741 if (ParseArrayVectorType(Result, false))
1742 return true;
1743 break;
1744 case lltok::less: // Either vector or packed struct.
1745 // Type ::= '<' ... '>'
1746 Lex.Lex();
1747 if (Lex.getKind() == lltok::lbrace) {
1748 if (ParseAnonStructType(Result, true) ||
1749 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1750 return true;
1751 } else if (ParseArrayVectorType(Result, true))
1752 return true;
1753 break;
1754 case lltok::LocalVar: {
1755 // Type ::= %foo
1756 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1757
1758 // If the type hasn't been defined yet, create a forward definition and
1759 // remember where that forward def'n was seen (in case it never is defined).
1760 if (!Entry.first) {
1761 Entry.first = StructType::create(Context, Lex.getStrVal());
1762 Entry.second = Lex.getLoc();
1763 }
1764 Result = Entry.first;
1765 Lex.Lex();
1766 break;
1767 }
1768
1769 case lltok::LocalVarID: {
1770 // Type ::= %4
1771 if (Lex.getUIntVal() >= NumberedTypes.size())
1772 NumberedTypes.resize(Lex.getUIntVal()+1);
1773 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1774
1775 // If the type hasn't been defined yet, create a forward definition and
1776 // remember where that forward def'n was seen (in case it never is defined).
1777 if (!Entry.first) {
1778 Entry.first = StructType::create(Context);
1779 Entry.second = Lex.getLoc();
1780 }
1781 Result = Entry.first;
1782 Lex.Lex();
1783 break;
1784 }
1785 }
1786
1787 // Parse the type suffixes.
1788 while (1) {
1789 switch (Lex.getKind()) {
1790 // End of type.
1791 default:
1792 if (!AllowVoid && Result->isVoidTy())
1793 return Error(TypeLoc, "void type only allowed for function results");
1794 return false;
1795
1796 // Type ::= Type '*'
1797 case lltok::star:
1798 if (Result->isLabelTy())
1799 return TokError("basic block pointers are invalid");
1800 if (Result->isVoidTy())
1801 return TokError("pointers to void are invalid - use i8* instead");
1802 if (!PointerType::isValidElementType(Result))
1803 return TokError("pointer to this type is invalid");
1804 Result = PointerType::getUnqual(Result);
1805 Lex.Lex();
1806 break;
1807
1808 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1809 case lltok::kw_addrspace: {
1810 if (Result->isLabelTy())
1811 return TokError("basic block pointers are invalid");
1812 if (Result->isVoidTy())
1813 return TokError("pointers to void are invalid; use i8* instead");
1814 if (!PointerType::isValidElementType(Result))
1815 return TokError("pointer to this type is invalid");
1816 unsigned AddrSpace;
1817 if (ParseOptionalAddrSpace(AddrSpace) ||
1818 ParseToken(lltok::star, "expected '*' in address space"))
1819 return true;
1820
1821 Result = PointerType::get(Result, AddrSpace);
1822 break;
1823 }
1824
1825 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1826 case lltok::lparen:
1827 if (ParseFunctionType(Result))
1828 return true;
1829 break;
1830 }
1831 }
1832 }
1833
1834 /// ParseParameterList
1835 /// ::= '(' ')'
1836 /// ::= '(' Arg (',' Arg)* ')'
1837 /// Arg
1838 /// ::= Type OptionalAttributes Value OptionalAttributes
ParseParameterList(SmallVectorImpl<ParamInfo> & ArgList,PerFunctionState & PFS)1839 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1840 PerFunctionState &PFS) {
1841 if (ParseToken(lltok::lparen, "expected '(' in call"))
1842 return true;
1843
1844 unsigned AttrIndex = 1;
1845 while (Lex.getKind() != lltok::rparen) {
1846 // If this isn't the first argument, we need a comma.
1847 if (!ArgList.empty() &&
1848 ParseToken(lltok::comma, "expected ',' in argument list"))
1849 return true;
1850
1851 // Parse the argument.
1852 LocTy ArgLoc;
1853 Type *ArgTy = nullptr;
1854 AttrBuilder ArgAttrs;
1855 Value *V;
1856 if (ParseType(ArgTy, ArgLoc))
1857 return true;
1858
1859 // Otherwise, handle normal operands.
1860 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1861 return true;
1862 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1863 AttrIndex++,
1864 ArgAttrs)));
1865 }
1866
1867 Lex.Lex(); // Lex the ')'.
1868 return false;
1869 }
1870
1871
1872
1873 /// ParseArgumentList - Parse the argument list for a function type or function
1874 /// prototype.
1875 /// ::= '(' ArgTypeListI ')'
1876 /// ArgTypeListI
1877 /// ::= /*empty*/
1878 /// ::= '...'
1879 /// ::= ArgTypeList ',' '...'
1880 /// ::= ArgType (',' ArgType)*
1881 ///
ParseArgumentList(SmallVectorImpl<ArgInfo> & ArgList,bool & isVarArg)1882 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1883 bool &isVarArg){
1884 isVarArg = false;
1885 assert(Lex.getKind() == lltok::lparen);
1886 Lex.Lex(); // eat the (.
1887
1888 if (Lex.getKind() == lltok::rparen) {
1889 // empty
1890 } else if (Lex.getKind() == lltok::dotdotdot) {
1891 isVarArg = true;
1892 Lex.Lex();
1893 } else {
1894 LocTy TypeLoc = Lex.getLoc();
1895 Type *ArgTy = nullptr;
1896 AttrBuilder Attrs;
1897 std::string Name;
1898
1899 if (ParseType(ArgTy) ||
1900 ParseOptionalParamAttrs(Attrs)) return true;
1901
1902 if (ArgTy->isVoidTy())
1903 return Error(TypeLoc, "argument can not have void type");
1904
1905 if (Lex.getKind() == lltok::LocalVar) {
1906 Name = Lex.getStrVal();
1907 Lex.Lex();
1908 }
1909
1910 if (!FunctionType::isValidArgumentType(ArgTy))
1911 return Error(TypeLoc, "invalid type for function argument");
1912
1913 unsigned AttrIndex = 1;
1914 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1915 AttributeSet::get(ArgTy->getContext(),
1916 AttrIndex++, Attrs), Name));
1917
1918 while (EatIfPresent(lltok::comma)) {
1919 // Handle ... at end of arg list.
1920 if (EatIfPresent(lltok::dotdotdot)) {
1921 isVarArg = true;
1922 break;
1923 }
1924
1925 // Otherwise must be an argument type.
1926 TypeLoc = Lex.getLoc();
1927 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1928
1929 if (ArgTy->isVoidTy())
1930 return Error(TypeLoc, "argument can not have void type");
1931
1932 if (Lex.getKind() == lltok::LocalVar) {
1933 Name = Lex.getStrVal();
1934 Lex.Lex();
1935 } else {
1936 Name = "";
1937 }
1938
1939 if (!ArgTy->isFirstClassType())
1940 return Error(TypeLoc, "invalid type for function argument");
1941
1942 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1943 AttributeSet::get(ArgTy->getContext(),
1944 AttrIndex++, Attrs),
1945 Name));
1946 }
1947 }
1948
1949 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1950 }
1951
1952 /// ParseFunctionType
1953 /// ::= Type ArgumentList OptionalAttrs
ParseFunctionType(Type * & Result)1954 bool LLParser::ParseFunctionType(Type *&Result) {
1955 assert(Lex.getKind() == lltok::lparen);
1956
1957 if (!FunctionType::isValidReturnType(Result))
1958 return TokError("invalid function return type");
1959
1960 SmallVector<ArgInfo, 8> ArgList;
1961 bool isVarArg;
1962 if (ParseArgumentList(ArgList, isVarArg))
1963 return true;
1964
1965 // Reject names on the arguments lists.
1966 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1967 if (!ArgList[i].Name.empty())
1968 return Error(ArgList[i].Loc, "argument name invalid in function type");
1969 if (ArgList[i].Attrs.hasAttributes(i + 1))
1970 return Error(ArgList[i].Loc,
1971 "argument attributes invalid in function type");
1972 }
1973
1974 SmallVector<Type*, 16> ArgListTy;
1975 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1976 ArgListTy.push_back(ArgList[i].Ty);
1977
1978 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1979 return false;
1980 }
1981
1982 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1983 /// other structs.
ParseAnonStructType(Type * & Result,bool Packed)1984 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1985 SmallVector<Type*, 8> Elts;
1986 if (ParseStructBody(Elts)) return true;
1987
1988 Result = StructType::get(Context, Elts, Packed);
1989 return false;
1990 }
1991
1992 /// ParseStructDefinition - Parse a struct in a 'type' definition.
ParseStructDefinition(SMLoc TypeLoc,StringRef Name,std::pair<Type *,LocTy> & Entry,Type * & ResultTy)1993 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1994 std::pair<Type*, LocTy> &Entry,
1995 Type *&ResultTy) {
1996 // If the type was already defined, diagnose the redefinition.
1997 if (Entry.first && !Entry.second.isValid())
1998 return Error(TypeLoc, "redefinition of type");
1999
2000 // If we have opaque, just return without filling in the definition for the
2001 // struct. This counts as a definition as far as the .ll file goes.
2002 if (EatIfPresent(lltok::kw_opaque)) {
2003 // This type is being defined, so clear the location to indicate this.
2004 Entry.second = SMLoc();
2005
2006 // If this type number has never been uttered, create it.
2007 if (!Entry.first)
2008 Entry.first = StructType::create(Context, Name);
2009 ResultTy = Entry.first;
2010 return false;
2011 }
2012
2013 // If the type starts with '<', then it is either a packed struct or a vector.
2014 bool isPacked = EatIfPresent(lltok::less);
2015
2016 // If we don't have a struct, then we have a random type alias, which we
2017 // accept for compatibility with old files. These types are not allowed to be
2018 // forward referenced and not allowed to be recursive.
2019 if (Lex.getKind() != lltok::lbrace) {
2020 if (Entry.first)
2021 return Error(TypeLoc, "forward references to non-struct type");
2022
2023 ResultTy = nullptr;
2024 if (isPacked)
2025 return ParseArrayVectorType(ResultTy, true);
2026 return ParseType(ResultTy);
2027 }
2028
2029 // This type is being defined, so clear the location to indicate this.
2030 Entry.second = SMLoc();
2031
2032 // If this type number has never been uttered, create it.
2033 if (!Entry.first)
2034 Entry.first = StructType::create(Context, Name);
2035
2036 StructType *STy = cast<StructType>(Entry.first);
2037
2038 SmallVector<Type*, 8> Body;
2039 if (ParseStructBody(Body) ||
2040 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2041 return true;
2042
2043 STy->setBody(Body, isPacked);
2044 ResultTy = STy;
2045 return false;
2046 }
2047
2048
2049 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2050 /// StructType
2051 /// ::= '{' '}'
2052 /// ::= '{' Type (',' Type)* '}'
2053 /// ::= '<' '{' '}' '>'
2054 /// ::= '<' '{' Type (',' Type)* '}' '>'
ParseStructBody(SmallVectorImpl<Type * > & Body)2055 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2056 assert(Lex.getKind() == lltok::lbrace);
2057 Lex.Lex(); // Consume the '{'
2058
2059 // Handle the empty struct.
2060 if (EatIfPresent(lltok::rbrace))
2061 return false;
2062
2063 LocTy EltTyLoc = Lex.getLoc();
2064 Type *Ty = nullptr;
2065 if (ParseType(Ty)) return true;
2066 Body.push_back(Ty);
2067
2068 if (!StructType::isValidElementType(Ty))
2069 return Error(EltTyLoc, "invalid element type for struct");
2070
2071 while (EatIfPresent(lltok::comma)) {
2072 EltTyLoc = Lex.getLoc();
2073 if (ParseType(Ty)) return true;
2074
2075 if (!StructType::isValidElementType(Ty))
2076 return Error(EltTyLoc, "invalid element type for struct");
2077
2078 Body.push_back(Ty);
2079 }
2080
2081 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2082 }
2083
2084 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2085 /// token has already been consumed.
2086 /// Type
2087 /// ::= '[' APSINTVAL 'x' Types ']'
2088 /// ::= '<' APSINTVAL 'x' Types '>'
ParseArrayVectorType(Type * & Result,bool isVector)2089 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2090 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2091 Lex.getAPSIntVal().getBitWidth() > 64)
2092 return TokError("expected number in address space");
2093
2094 LocTy SizeLoc = Lex.getLoc();
2095 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2096 Lex.Lex();
2097
2098 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2099 return true;
2100
2101 LocTy TypeLoc = Lex.getLoc();
2102 Type *EltTy = nullptr;
2103 if (ParseType(EltTy)) return true;
2104
2105 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2106 "expected end of sequential type"))
2107 return true;
2108
2109 if (isVector) {
2110 if (Size == 0)
2111 return Error(SizeLoc, "zero element vector is illegal");
2112 if ((unsigned)Size != Size)
2113 return Error(SizeLoc, "size too large for vector");
2114 if (!VectorType::isValidElementType(EltTy))
2115 return Error(TypeLoc, "invalid vector element type");
2116 Result = VectorType::get(EltTy, unsigned(Size));
2117 } else {
2118 if (!ArrayType::isValidElementType(EltTy))
2119 return Error(TypeLoc, "invalid array element type");
2120 Result = ArrayType::get(EltTy, Size);
2121 }
2122 return false;
2123 }
2124
2125 //===----------------------------------------------------------------------===//
2126 // Function Semantic Analysis.
2127 //===----------------------------------------------------------------------===//
2128
PerFunctionState(LLParser & p,Function & f,int functionNumber)2129 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2130 int functionNumber)
2131 : P(p), F(f), FunctionNumber(functionNumber) {
2132
2133 // Insert unnamed arguments into the NumberedVals list.
2134 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2135 AI != E; ++AI)
2136 if (!AI->hasName())
2137 NumberedVals.push_back(AI);
2138 }
2139
~PerFunctionState()2140 LLParser::PerFunctionState::~PerFunctionState() {
2141 // If there were any forward referenced non-basicblock values, delete them.
2142 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2143 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2144 if (!isa<BasicBlock>(I->second.first)) {
2145 I->second.first->replaceAllUsesWith(
2146 UndefValue::get(I->second.first->getType()));
2147 delete I->second.first;
2148 I->second.first = nullptr;
2149 }
2150
2151 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2152 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2153 if (!isa<BasicBlock>(I->second.first)) {
2154 I->second.first->replaceAllUsesWith(
2155 UndefValue::get(I->second.first->getType()));
2156 delete I->second.first;
2157 I->second.first = nullptr;
2158 }
2159 }
2160
FinishFunction()2161 bool LLParser::PerFunctionState::FinishFunction() {
2162 // Check to see if someone took the address of labels in this block.
2163 if (!P.ForwardRefBlockAddresses.empty()) {
2164 ValID FunctionID;
2165 if (!F.getName().empty()) {
2166 FunctionID.Kind = ValID::t_GlobalName;
2167 FunctionID.StrVal = F.getName();
2168 } else {
2169 FunctionID.Kind = ValID::t_GlobalID;
2170 FunctionID.UIntVal = FunctionNumber;
2171 }
2172
2173 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
2174 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
2175 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
2176 // Resolve all these references.
2177 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
2178 return true;
2179
2180 P.ForwardRefBlockAddresses.erase(FRBAI);
2181 }
2182 }
2183
2184 if (!ForwardRefVals.empty())
2185 return P.Error(ForwardRefVals.begin()->second.second,
2186 "use of undefined value '%" + ForwardRefVals.begin()->first +
2187 "'");
2188 if (!ForwardRefValIDs.empty())
2189 return P.Error(ForwardRefValIDs.begin()->second.second,
2190 "use of undefined value '%" +
2191 Twine(ForwardRefValIDs.begin()->first) + "'");
2192 return false;
2193 }
2194
2195
2196 /// GetVal - Get a value with the specified name or ID, creating a
2197 /// forward reference record if needed. This can return null if the value
2198 /// exists but does not have the right type.
GetVal(const std::string & Name,Type * Ty,LocTy Loc)2199 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2200 Type *Ty, LocTy Loc) {
2201 // Look this name up in the normal function symbol table.
2202 Value *Val = F.getValueSymbolTable().lookup(Name);
2203
2204 // If this is a forward reference for the value, see if we already created a
2205 // forward ref record.
2206 if (!Val) {
2207 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2208 I = ForwardRefVals.find(Name);
2209 if (I != ForwardRefVals.end())
2210 Val = I->second.first;
2211 }
2212
2213 // If we have the value in the symbol table or fwd-ref table, return it.
2214 if (Val) {
2215 if (Val->getType() == Ty) return Val;
2216 if (Ty->isLabelTy())
2217 P.Error(Loc, "'%" + Name + "' is not a basic block");
2218 else
2219 P.Error(Loc, "'%" + Name + "' defined with type '" +
2220 getTypeString(Val->getType()) + "'");
2221 return nullptr;
2222 }
2223
2224 // Don't make placeholders with invalid type.
2225 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2226 P.Error(Loc, "invalid use of a non-first-class type");
2227 return nullptr;
2228 }
2229
2230 // Otherwise, create a new forward reference for this value and remember it.
2231 Value *FwdVal;
2232 if (Ty->isLabelTy())
2233 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2234 else
2235 FwdVal = new Argument(Ty, Name);
2236
2237 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2238 return FwdVal;
2239 }
2240
GetVal(unsigned ID,Type * Ty,LocTy Loc)2241 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2242 LocTy Loc) {
2243 // Look this name up in the normal function symbol table.
2244 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2245
2246 // If this is a forward reference for the value, see if we already created a
2247 // forward ref record.
2248 if (!Val) {
2249 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2250 I = ForwardRefValIDs.find(ID);
2251 if (I != ForwardRefValIDs.end())
2252 Val = I->second.first;
2253 }
2254
2255 // If we have the value in the symbol table or fwd-ref table, return it.
2256 if (Val) {
2257 if (Val->getType() == Ty) return Val;
2258 if (Ty->isLabelTy())
2259 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2260 else
2261 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2262 getTypeString(Val->getType()) + "'");
2263 return nullptr;
2264 }
2265
2266 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2267 P.Error(Loc, "invalid use of a non-first-class type");
2268 return nullptr;
2269 }
2270
2271 // Otherwise, create a new forward reference for this value and remember it.
2272 Value *FwdVal;
2273 if (Ty->isLabelTy())
2274 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2275 else
2276 FwdVal = new Argument(Ty);
2277
2278 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2279 return FwdVal;
2280 }
2281
2282 /// SetInstName - After an instruction is parsed and inserted into its
2283 /// basic block, this installs its name.
SetInstName(int NameID,const std::string & NameStr,LocTy NameLoc,Instruction * Inst)2284 bool LLParser::PerFunctionState::SetInstName(int NameID,
2285 const std::string &NameStr,
2286 LocTy NameLoc, Instruction *Inst) {
2287 // If this instruction has void type, it cannot have a name or ID specified.
2288 if (Inst->getType()->isVoidTy()) {
2289 if (NameID != -1 || !NameStr.empty())
2290 return P.Error(NameLoc, "instructions returning void cannot have a name");
2291 return false;
2292 }
2293
2294 // If this was a numbered instruction, verify that the instruction is the
2295 // expected value and resolve any forward references.
2296 if (NameStr.empty()) {
2297 // If neither a name nor an ID was specified, just use the next ID.
2298 if (NameID == -1)
2299 NameID = NumberedVals.size();
2300
2301 if (unsigned(NameID) != NumberedVals.size())
2302 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2303 Twine(NumberedVals.size()) + "'");
2304
2305 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2306 ForwardRefValIDs.find(NameID);
2307 if (FI != ForwardRefValIDs.end()) {
2308 if (FI->second.first->getType() != Inst->getType())
2309 return P.Error(NameLoc, "instruction forward referenced with type '" +
2310 getTypeString(FI->second.first->getType()) + "'");
2311 FI->second.first->replaceAllUsesWith(Inst);
2312 delete FI->second.first;
2313 ForwardRefValIDs.erase(FI);
2314 }
2315
2316 NumberedVals.push_back(Inst);
2317 return false;
2318 }
2319
2320 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2321 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2322 FI = ForwardRefVals.find(NameStr);
2323 if (FI != ForwardRefVals.end()) {
2324 if (FI->second.first->getType() != Inst->getType())
2325 return P.Error(NameLoc, "instruction forward referenced with type '" +
2326 getTypeString(FI->second.first->getType()) + "'");
2327 FI->second.first->replaceAllUsesWith(Inst);
2328 delete FI->second.first;
2329 ForwardRefVals.erase(FI);
2330 }
2331
2332 // Set the name on the instruction.
2333 Inst->setName(NameStr);
2334
2335 if (Inst->getName() != NameStr)
2336 return P.Error(NameLoc, "multiple definition of local value named '" +
2337 NameStr + "'");
2338 return false;
2339 }
2340
2341 /// GetBB - Get a basic block with the specified name or ID, creating a
2342 /// forward reference record if needed.
GetBB(const std::string & Name,LocTy Loc)2343 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2344 LocTy Loc) {
2345 return cast_or_null<BasicBlock>(GetVal(Name,
2346 Type::getLabelTy(F.getContext()), Loc));
2347 }
2348
GetBB(unsigned ID,LocTy Loc)2349 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2350 return cast_or_null<BasicBlock>(GetVal(ID,
2351 Type::getLabelTy(F.getContext()), Loc));
2352 }
2353
2354 /// DefineBB - Define the specified basic block, which is either named or
2355 /// unnamed. If there is an error, this returns null otherwise it returns
2356 /// the block being defined.
DefineBB(const std::string & Name,LocTy Loc)2357 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2358 LocTy Loc) {
2359 BasicBlock *BB;
2360 if (Name.empty())
2361 BB = GetBB(NumberedVals.size(), Loc);
2362 else
2363 BB = GetBB(Name, Loc);
2364 if (!BB) return nullptr; // Already diagnosed error.
2365
2366 // Move the block to the end of the function. Forward ref'd blocks are
2367 // inserted wherever they happen to be referenced.
2368 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2369
2370 // Remove the block from forward ref sets.
2371 if (Name.empty()) {
2372 ForwardRefValIDs.erase(NumberedVals.size());
2373 NumberedVals.push_back(BB);
2374 } else {
2375 // BB forward references are already in the function symbol table.
2376 ForwardRefVals.erase(Name);
2377 }
2378
2379 return BB;
2380 }
2381
2382 //===----------------------------------------------------------------------===//
2383 // Constants.
2384 //===----------------------------------------------------------------------===//
2385
2386 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2387 /// type implied. For example, if we parse "4" we don't know what integer type
2388 /// it has. The value will later be combined with its type and checked for
2389 /// sanity. PFS is used to convert function-local operands of metadata (since
2390 /// metadata operands are not just parsed here but also converted to values).
2391 /// PFS can be null when we are not parsing metadata values inside a function.
ParseValID(ValID & ID,PerFunctionState * PFS)2392 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2393 ID.Loc = Lex.getLoc();
2394 switch (Lex.getKind()) {
2395 default: return TokError("expected value token");
2396 case lltok::GlobalID: // @42
2397 ID.UIntVal = Lex.getUIntVal();
2398 ID.Kind = ValID::t_GlobalID;
2399 break;
2400 case lltok::GlobalVar: // @foo
2401 ID.StrVal = Lex.getStrVal();
2402 ID.Kind = ValID::t_GlobalName;
2403 break;
2404 case lltok::LocalVarID: // %42
2405 ID.UIntVal = Lex.getUIntVal();
2406 ID.Kind = ValID::t_LocalID;
2407 break;
2408 case lltok::LocalVar: // %foo
2409 ID.StrVal = Lex.getStrVal();
2410 ID.Kind = ValID::t_LocalName;
2411 break;
2412 case lltok::exclaim: // !42, !{...}, or !"foo"
2413 return ParseMetadataValue(ID, PFS);
2414 case lltok::APSInt:
2415 ID.APSIntVal = Lex.getAPSIntVal();
2416 ID.Kind = ValID::t_APSInt;
2417 break;
2418 case lltok::APFloat:
2419 ID.APFloatVal = Lex.getAPFloatVal();
2420 ID.Kind = ValID::t_APFloat;
2421 break;
2422 case lltok::kw_true:
2423 ID.ConstantVal = ConstantInt::getTrue(Context);
2424 ID.Kind = ValID::t_Constant;
2425 break;
2426 case lltok::kw_false:
2427 ID.ConstantVal = ConstantInt::getFalse(Context);
2428 ID.Kind = ValID::t_Constant;
2429 break;
2430 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2431 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2432 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2433
2434 case lltok::lbrace: {
2435 // ValID ::= '{' ConstVector '}'
2436 Lex.Lex();
2437 SmallVector<Constant*, 16> Elts;
2438 if (ParseGlobalValueVector(Elts) ||
2439 ParseToken(lltok::rbrace, "expected end of struct constant"))
2440 return true;
2441
2442 ID.ConstantStructElts = new Constant*[Elts.size()];
2443 ID.UIntVal = Elts.size();
2444 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2445 ID.Kind = ValID::t_ConstantStruct;
2446 return false;
2447 }
2448 case lltok::less: {
2449 // ValID ::= '<' ConstVector '>' --> Vector.
2450 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2451 Lex.Lex();
2452 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2453
2454 SmallVector<Constant*, 16> Elts;
2455 LocTy FirstEltLoc = Lex.getLoc();
2456 if (ParseGlobalValueVector(Elts) ||
2457 (isPackedStruct &&
2458 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2459 ParseToken(lltok::greater, "expected end of constant"))
2460 return true;
2461
2462 if (isPackedStruct) {
2463 ID.ConstantStructElts = new Constant*[Elts.size()];
2464 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2465 ID.UIntVal = Elts.size();
2466 ID.Kind = ValID::t_PackedConstantStruct;
2467 return false;
2468 }
2469
2470 if (Elts.empty())
2471 return Error(ID.Loc, "constant vector must not be empty");
2472
2473 if (!Elts[0]->getType()->isIntegerTy() &&
2474 !Elts[0]->getType()->isFloatingPointTy() &&
2475 !Elts[0]->getType()->isPointerTy())
2476 return Error(FirstEltLoc,
2477 "vector elements must have integer, pointer or floating point type");
2478
2479 // Verify that all the vector elements have the same type.
2480 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2481 if (Elts[i]->getType() != Elts[0]->getType())
2482 return Error(FirstEltLoc,
2483 "vector element #" + Twine(i) +
2484 " is not of type '" + getTypeString(Elts[0]->getType()));
2485
2486 ID.ConstantVal = ConstantVector::get(Elts);
2487 ID.Kind = ValID::t_Constant;
2488 return false;
2489 }
2490 case lltok::lsquare: { // Array Constant
2491 Lex.Lex();
2492 SmallVector<Constant*, 16> Elts;
2493 LocTy FirstEltLoc = Lex.getLoc();
2494 if (ParseGlobalValueVector(Elts) ||
2495 ParseToken(lltok::rsquare, "expected end of array constant"))
2496 return true;
2497
2498 // Handle empty element.
2499 if (Elts.empty()) {
2500 // Use undef instead of an array because it's inconvenient to determine
2501 // the element type at this point, there being no elements to examine.
2502 ID.Kind = ValID::t_EmptyArray;
2503 return false;
2504 }
2505
2506 if (!Elts[0]->getType()->isFirstClassType())
2507 return Error(FirstEltLoc, "invalid array element type: " +
2508 getTypeString(Elts[0]->getType()));
2509
2510 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2511
2512 // Verify all elements are correct type!
2513 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2514 if (Elts[i]->getType() != Elts[0]->getType())
2515 return Error(FirstEltLoc,
2516 "array element #" + Twine(i) +
2517 " is not of type '" + getTypeString(Elts[0]->getType()));
2518 }
2519
2520 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2521 ID.Kind = ValID::t_Constant;
2522 return false;
2523 }
2524 case lltok::kw_c: // c "foo"
2525 Lex.Lex();
2526 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2527 false);
2528 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2529 ID.Kind = ValID::t_Constant;
2530 return false;
2531
2532 case lltok::kw_asm: {
2533 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2534 // STRINGCONSTANT
2535 bool HasSideEffect, AlignStack, AsmDialect;
2536 Lex.Lex();
2537 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2538 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2539 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2540 ParseStringConstant(ID.StrVal) ||
2541 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2542 ParseToken(lltok::StringConstant, "expected constraint string"))
2543 return true;
2544 ID.StrVal2 = Lex.getStrVal();
2545 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2546 (unsigned(AsmDialect)<<2);
2547 ID.Kind = ValID::t_InlineAsm;
2548 return false;
2549 }
2550
2551 case lltok::kw_blockaddress: {
2552 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2553 Lex.Lex();
2554
2555 ValID Fn, Label;
2556
2557 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2558 ParseValID(Fn) ||
2559 ParseToken(lltok::comma, "expected comma in block address expression")||
2560 ParseValID(Label) ||
2561 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2562 return true;
2563
2564 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2565 return Error(Fn.Loc, "expected function name in blockaddress");
2566 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2567 return Error(Label.Loc, "expected basic block name in blockaddress");
2568
2569 // Make a global variable as a placeholder for this reference.
2570 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2571 false, GlobalValue::InternalLinkage,
2572 nullptr, "");
2573 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2574 ID.ConstantVal = FwdRef;
2575 ID.Kind = ValID::t_Constant;
2576 return false;
2577 }
2578
2579 case lltok::kw_trunc:
2580 case lltok::kw_zext:
2581 case lltok::kw_sext:
2582 case lltok::kw_fptrunc:
2583 case lltok::kw_fpext:
2584 case lltok::kw_bitcast:
2585 case lltok::kw_addrspacecast:
2586 case lltok::kw_uitofp:
2587 case lltok::kw_sitofp:
2588 case lltok::kw_fptoui:
2589 case lltok::kw_fptosi:
2590 case lltok::kw_inttoptr:
2591 case lltok::kw_ptrtoint: {
2592 unsigned Opc = Lex.getUIntVal();
2593 Type *DestTy = nullptr;
2594 Constant *SrcVal;
2595 Lex.Lex();
2596 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2597 ParseGlobalTypeAndValue(SrcVal) ||
2598 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2599 ParseType(DestTy) ||
2600 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2601 return true;
2602 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2603 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2604 getTypeString(SrcVal->getType()) + "' to '" +
2605 getTypeString(DestTy) + "'");
2606 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2607 SrcVal, DestTy);
2608 ID.Kind = ValID::t_Constant;
2609 return false;
2610 }
2611 case lltok::kw_extractvalue: {
2612 Lex.Lex();
2613 Constant *Val;
2614 SmallVector<unsigned, 4> Indices;
2615 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2616 ParseGlobalTypeAndValue(Val) ||
2617 ParseIndexList(Indices) ||
2618 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2619 return true;
2620
2621 if (!Val->getType()->isAggregateType())
2622 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2623 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2624 return Error(ID.Loc, "invalid indices for extractvalue");
2625 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2626 ID.Kind = ValID::t_Constant;
2627 return false;
2628 }
2629 case lltok::kw_insertvalue: {
2630 Lex.Lex();
2631 Constant *Val0, *Val1;
2632 SmallVector<unsigned, 4> Indices;
2633 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2634 ParseGlobalTypeAndValue(Val0) ||
2635 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2636 ParseGlobalTypeAndValue(Val1) ||
2637 ParseIndexList(Indices) ||
2638 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2639 return true;
2640 if (!Val0->getType()->isAggregateType())
2641 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2642 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2643 return Error(ID.Loc, "invalid indices for insertvalue");
2644 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2645 ID.Kind = ValID::t_Constant;
2646 return false;
2647 }
2648 case lltok::kw_icmp:
2649 case lltok::kw_fcmp: {
2650 unsigned PredVal, Opc = Lex.getUIntVal();
2651 Constant *Val0, *Val1;
2652 Lex.Lex();
2653 if (ParseCmpPredicate(PredVal, Opc) ||
2654 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2655 ParseGlobalTypeAndValue(Val0) ||
2656 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2657 ParseGlobalTypeAndValue(Val1) ||
2658 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2659 return true;
2660
2661 if (Val0->getType() != Val1->getType())
2662 return Error(ID.Loc, "compare operands must have the same type");
2663
2664 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2665
2666 if (Opc == Instruction::FCmp) {
2667 if (!Val0->getType()->isFPOrFPVectorTy())
2668 return Error(ID.Loc, "fcmp requires floating point operands");
2669 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2670 } else {
2671 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2672 if (!Val0->getType()->isIntOrIntVectorTy() &&
2673 !Val0->getType()->getScalarType()->isPointerTy())
2674 return Error(ID.Loc, "icmp requires pointer or integer operands");
2675 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2676 }
2677 ID.Kind = ValID::t_Constant;
2678 return false;
2679 }
2680
2681 // Binary Operators.
2682 case lltok::kw_add:
2683 case lltok::kw_fadd:
2684 case lltok::kw_sub:
2685 case lltok::kw_fsub:
2686 case lltok::kw_mul:
2687 case lltok::kw_fmul:
2688 case lltok::kw_udiv:
2689 case lltok::kw_sdiv:
2690 case lltok::kw_fdiv:
2691 case lltok::kw_urem:
2692 case lltok::kw_srem:
2693 case lltok::kw_frem:
2694 case lltok::kw_shl:
2695 case lltok::kw_lshr:
2696 case lltok::kw_ashr: {
2697 bool NUW = false;
2698 bool NSW = false;
2699 bool Exact = false;
2700 unsigned Opc = Lex.getUIntVal();
2701 Constant *Val0, *Val1;
2702 Lex.Lex();
2703 LocTy ModifierLoc = Lex.getLoc();
2704 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2705 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2706 if (EatIfPresent(lltok::kw_nuw))
2707 NUW = true;
2708 if (EatIfPresent(lltok::kw_nsw)) {
2709 NSW = true;
2710 if (EatIfPresent(lltok::kw_nuw))
2711 NUW = true;
2712 }
2713 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2714 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2715 if (EatIfPresent(lltok::kw_exact))
2716 Exact = true;
2717 }
2718 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2719 ParseGlobalTypeAndValue(Val0) ||
2720 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2721 ParseGlobalTypeAndValue(Val1) ||
2722 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2723 return true;
2724 if (Val0->getType() != Val1->getType())
2725 return Error(ID.Loc, "operands of constexpr must have same type");
2726 if (!Val0->getType()->isIntOrIntVectorTy()) {
2727 if (NUW)
2728 return Error(ModifierLoc, "nuw only applies to integer operations");
2729 if (NSW)
2730 return Error(ModifierLoc, "nsw only applies to integer operations");
2731 }
2732 // Check that the type is valid for the operator.
2733 switch (Opc) {
2734 case Instruction::Add:
2735 case Instruction::Sub:
2736 case Instruction::Mul:
2737 case Instruction::UDiv:
2738 case Instruction::SDiv:
2739 case Instruction::URem:
2740 case Instruction::SRem:
2741 case Instruction::Shl:
2742 case Instruction::AShr:
2743 case Instruction::LShr:
2744 if (!Val0->getType()->isIntOrIntVectorTy())
2745 return Error(ID.Loc, "constexpr requires integer operands");
2746 break;
2747 case Instruction::FAdd:
2748 case Instruction::FSub:
2749 case Instruction::FMul:
2750 case Instruction::FDiv:
2751 case Instruction::FRem:
2752 if (!Val0->getType()->isFPOrFPVectorTy())
2753 return Error(ID.Loc, "constexpr requires fp operands");
2754 break;
2755 default: llvm_unreachable("Unknown binary operator!");
2756 }
2757 unsigned Flags = 0;
2758 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2759 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2760 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2761 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2762 ID.ConstantVal = C;
2763 ID.Kind = ValID::t_Constant;
2764 return false;
2765 }
2766
2767 // Logical Operations
2768 case lltok::kw_and:
2769 case lltok::kw_or:
2770 case lltok::kw_xor: {
2771 unsigned Opc = Lex.getUIntVal();
2772 Constant *Val0, *Val1;
2773 Lex.Lex();
2774 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2775 ParseGlobalTypeAndValue(Val0) ||
2776 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2777 ParseGlobalTypeAndValue(Val1) ||
2778 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2779 return true;
2780 if (Val0->getType() != Val1->getType())
2781 return Error(ID.Loc, "operands of constexpr must have same type");
2782 if (!Val0->getType()->isIntOrIntVectorTy())
2783 return Error(ID.Loc,
2784 "constexpr requires integer or integer vector operands");
2785 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2786 ID.Kind = ValID::t_Constant;
2787 return false;
2788 }
2789
2790 case lltok::kw_getelementptr:
2791 case lltok::kw_shufflevector:
2792 case lltok::kw_insertelement:
2793 case lltok::kw_extractelement:
2794 case lltok::kw_select: {
2795 unsigned Opc = Lex.getUIntVal();
2796 SmallVector<Constant*, 16> Elts;
2797 bool InBounds = false;
2798 Lex.Lex();
2799 if (Opc == Instruction::GetElementPtr)
2800 InBounds = EatIfPresent(lltok::kw_inbounds);
2801 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2802 ParseGlobalValueVector(Elts) ||
2803 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2804 return true;
2805
2806 if (Opc == Instruction::GetElementPtr) {
2807 if (Elts.size() == 0 ||
2808 !Elts[0]->getType()->getScalarType()->isPointerTy())
2809 return Error(ID.Loc, "getelementptr requires pointer operand");
2810
2811 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2812 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2813 return Error(ID.Loc, "invalid indices for getelementptr");
2814 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2815 InBounds);
2816 } else if (Opc == Instruction::Select) {
2817 if (Elts.size() != 3)
2818 return Error(ID.Loc, "expected three operands to select");
2819 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2820 Elts[2]))
2821 return Error(ID.Loc, Reason);
2822 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2823 } else if (Opc == Instruction::ShuffleVector) {
2824 if (Elts.size() != 3)
2825 return Error(ID.Loc, "expected three operands to shufflevector");
2826 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2827 return Error(ID.Loc, "invalid operands to shufflevector");
2828 ID.ConstantVal =
2829 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2830 } else if (Opc == Instruction::ExtractElement) {
2831 if (Elts.size() != 2)
2832 return Error(ID.Loc, "expected two operands to extractelement");
2833 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2834 return Error(ID.Loc, "invalid extractelement operands");
2835 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2836 } else {
2837 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2838 if (Elts.size() != 3)
2839 return Error(ID.Loc, "expected three operands to insertelement");
2840 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2841 return Error(ID.Loc, "invalid insertelement operands");
2842 ID.ConstantVal =
2843 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2844 }
2845
2846 ID.Kind = ValID::t_Constant;
2847 return false;
2848 }
2849 }
2850
2851 Lex.Lex();
2852 return false;
2853 }
2854
2855 /// ParseGlobalValue - Parse a global value with the specified type.
ParseGlobalValue(Type * Ty,Constant * & C)2856 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2857 C = nullptr;
2858 ValID ID;
2859 Value *V = nullptr;
2860 bool Parsed = ParseValID(ID) ||
2861 ConvertValIDToValue(Ty, ID, V, nullptr);
2862 if (V && !(C = dyn_cast<Constant>(V)))
2863 return Error(ID.Loc, "global values must be constants");
2864 return Parsed;
2865 }
2866
ParseGlobalTypeAndValue(Constant * & V)2867 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2868 Type *Ty = nullptr;
2869 return ParseType(Ty) ||
2870 ParseGlobalValue(Ty, V);
2871 }
2872
parseOptionalComdat(Comdat * & C)2873 bool LLParser::parseOptionalComdat(Comdat *&C) {
2874 C = nullptr;
2875 if (!EatIfPresent(lltok::kw_comdat))
2876 return false;
2877 if (Lex.getKind() != lltok::ComdatVar)
2878 return TokError("expected comdat variable");
2879 LocTy Loc = Lex.getLoc();
2880 StringRef Name = Lex.getStrVal();
2881 C = getComdat(Name, Loc);
2882 Lex.Lex();
2883 return false;
2884 }
2885
2886 /// ParseGlobalValueVector
2887 /// ::= /*empty*/
2888 /// ::= TypeAndValue (',' TypeAndValue)*
ParseGlobalValueVector(SmallVectorImpl<Constant * > & Elts)2889 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2890 // Empty list.
2891 if (Lex.getKind() == lltok::rbrace ||
2892 Lex.getKind() == lltok::rsquare ||
2893 Lex.getKind() == lltok::greater ||
2894 Lex.getKind() == lltok::rparen)
2895 return false;
2896
2897 Constant *C;
2898 if (ParseGlobalTypeAndValue(C)) return true;
2899 Elts.push_back(C);
2900
2901 while (EatIfPresent(lltok::comma)) {
2902 if (ParseGlobalTypeAndValue(C)) return true;
2903 Elts.push_back(C);
2904 }
2905
2906 return false;
2907 }
2908
ParseMetadataListValue(ValID & ID,PerFunctionState * PFS)2909 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2910 assert(Lex.getKind() == lltok::lbrace);
2911 Lex.Lex();
2912
2913 SmallVector<Value*, 16> Elts;
2914 if (ParseMDNodeVector(Elts, PFS) ||
2915 ParseToken(lltok::rbrace, "expected end of metadata node"))
2916 return true;
2917
2918 ID.MDNodeVal = MDNode::get(Context, Elts);
2919 ID.Kind = ValID::t_MDNode;
2920 return false;
2921 }
2922
2923 /// ParseMetadataValue
2924 /// ::= !42
2925 /// ::= !{...}
2926 /// ::= !"string"
ParseMetadataValue(ValID & ID,PerFunctionState * PFS)2927 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2928 assert(Lex.getKind() == lltok::exclaim);
2929 Lex.Lex();
2930
2931 // MDNode:
2932 // !{ ... }
2933 if (Lex.getKind() == lltok::lbrace)
2934 return ParseMetadataListValue(ID, PFS);
2935
2936 // Standalone metadata reference
2937 // !42
2938 if (Lex.getKind() == lltok::APSInt) {
2939 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2940 ID.Kind = ValID::t_MDNode;
2941 return false;
2942 }
2943
2944 // MDString:
2945 // ::= '!' STRINGCONSTANT
2946 if (ParseMDString(ID.MDStringVal)) return true;
2947 ID.Kind = ValID::t_MDString;
2948 return false;
2949 }
2950
2951
2952 //===----------------------------------------------------------------------===//
2953 // Function Parsing.
2954 //===----------------------------------------------------------------------===//
2955
ConvertValIDToValue(Type * Ty,ValID & ID,Value * & V,PerFunctionState * PFS)2956 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2957 PerFunctionState *PFS) {
2958 if (Ty->isFunctionTy())
2959 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2960
2961 switch (ID.Kind) {
2962 case ValID::t_LocalID:
2963 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2964 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2965 return V == nullptr;
2966 case ValID::t_LocalName:
2967 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2968 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2969 return V == nullptr;
2970 case ValID::t_InlineAsm: {
2971 PointerType *PTy = dyn_cast<PointerType>(Ty);
2972 FunctionType *FTy =
2973 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
2974 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2975 return Error(ID.Loc, "invalid type for inline asm constraint string");
2976 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
2977 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
2978 return false;
2979 }
2980 case ValID::t_MDNode:
2981 if (!Ty->isMetadataTy())
2982 return Error(ID.Loc, "metadata value must have metadata type");
2983 V = ID.MDNodeVal;
2984 return false;
2985 case ValID::t_MDString:
2986 if (!Ty->isMetadataTy())
2987 return Error(ID.Loc, "metadata value must have metadata type");
2988 V = ID.MDStringVal;
2989 return false;
2990 case ValID::t_GlobalName:
2991 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2992 return V == nullptr;
2993 case ValID::t_GlobalID:
2994 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2995 return V == nullptr;
2996 case ValID::t_APSInt:
2997 if (!Ty->isIntegerTy())
2998 return Error(ID.Loc, "integer constant must have integer type");
2999 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
3000 V = ConstantInt::get(Context, ID.APSIntVal);
3001 return false;
3002 case ValID::t_APFloat:
3003 if (!Ty->isFloatingPointTy() ||
3004 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3005 return Error(ID.Loc, "floating point constant invalid for type");
3006
3007 // The lexer has no type info, so builds all half, float, and double FP
3008 // constants as double. Fix this here. Long double does not need this.
3009 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
3010 bool Ignored;
3011 if (Ty->isHalfTy())
3012 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3013 &Ignored);
3014 else if (Ty->isFloatTy())
3015 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
3016 &Ignored);
3017 }
3018 V = ConstantFP::get(Context, ID.APFloatVal);
3019
3020 if (V->getType() != Ty)
3021 return Error(ID.Loc, "floating point constant does not have type '" +
3022 getTypeString(Ty) + "'");
3023
3024 return false;
3025 case ValID::t_Null:
3026 if (!Ty->isPointerTy())
3027 return Error(ID.Loc, "null must be a pointer type");
3028 V = ConstantPointerNull::get(cast<PointerType>(Ty));
3029 return false;
3030 case ValID::t_Undef:
3031 // FIXME: LabelTy should not be a first-class type.
3032 if (!Ty->isFirstClassType() || Ty->isLabelTy())
3033 return Error(ID.Loc, "invalid type for undef constant");
3034 V = UndefValue::get(Ty);
3035 return false;
3036 case ValID::t_EmptyArray:
3037 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
3038 return Error(ID.Loc, "invalid empty array initializer");
3039 V = UndefValue::get(Ty);
3040 return false;
3041 case ValID::t_Zero:
3042 // FIXME: LabelTy should not be a first-class type.
3043 if (!Ty->isFirstClassType() || Ty->isLabelTy())
3044 return Error(ID.Loc, "invalid type for null constant");
3045 V = Constant::getNullValue(Ty);
3046 return false;
3047 case ValID::t_Constant:
3048 if (ID.ConstantVal->getType() != Ty)
3049 return Error(ID.Loc, "constant expression type mismatch");
3050
3051 V = ID.ConstantVal;
3052 return false;
3053 case ValID::t_ConstantStruct:
3054 case ValID::t_PackedConstantStruct:
3055 if (StructType *ST = dyn_cast<StructType>(Ty)) {
3056 if (ST->getNumElements() != ID.UIntVal)
3057 return Error(ID.Loc,
3058 "initializer with struct type has wrong # elements");
3059 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
3060 return Error(ID.Loc, "packed'ness of initializer and type don't match");
3061
3062 // Verify that the elements are compatible with the structtype.
3063 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
3064 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
3065 return Error(ID.Loc, "element " + Twine(i) +
3066 " of struct initializer doesn't match struct element type");
3067
3068 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
3069 ID.UIntVal));
3070 } else
3071 return Error(ID.Loc, "constant expression type mismatch");
3072 return false;
3073 }
3074 llvm_unreachable("Invalid ValID");
3075 }
3076
ParseValue(Type * Ty,Value * & V,PerFunctionState * PFS)3077 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
3078 V = nullptr;
3079 ValID ID;
3080 return ParseValID(ID, PFS) ||
3081 ConvertValIDToValue(Ty, ID, V, PFS);
3082 }
3083
ParseTypeAndValue(Value * & V,PerFunctionState * PFS)3084 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
3085 Type *Ty = nullptr;
3086 return ParseType(Ty) ||
3087 ParseValue(Ty, V, PFS);
3088 }
3089
ParseTypeAndBasicBlock(BasicBlock * & BB,LocTy & Loc,PerFunctionState & PFS)3090 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
3091 PerFunctionState &PFS) {
3092 Value *V;
3093 Loc = Lex.getLoc();
3094 if (ParseTypeAndValue(V, PFS)) return true;
3095 if (!isa<BasicBlock>(V))
3096 return Error(Loc, "expected a basic block");
3097 BB = cast<BasicBlock>(V);
3098 return false;
3099 }
3100
3101
3102 /// FunctionHeader
3103 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
3104 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
3105 /// OptionalAlign OptGC OptionalPrefix
ParseFunctionHeader(Function * & Fn,bool isDefine)3106 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
3107 // Parse the linkage.
3108 LocTy LinkageLoc = Lex.getLoc();
3109 unsigned Linkage;
3110
3111 unsigned Visibility;
3112 unsigned DLLStorageClass;
3113 AttrBuilder RetAttrs;
3114 CallingConv::ID CC;
3115 Type *RetType = nullptr;
3116 LocTy RetTypeLoc = Lex.getLoc();
3117 if (ParseOptionalLinkage(Linkage) ||
3118 ParseOptionalVisibility(Visibility) ||
3119 ParseOptionalDLLStorageClass(DLLStorageClass) ||
3120 ParseOptionalCallingConv(CC) ||
3121 ParseOptionalReturnAttrs(RetAttrs) ||
3122 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
3123 return true;
3124
3125 // Verify that the linkage is ok.
3126 switch ((GlobalValue::LinkageTypes)Linkage) {
3127 case GlobalValue::ExternalLinkage:
3128 break; // always ok.
3129 case GlobalValue::ExternalWeakLinkage:
3130 if (isDefine)
3131 return Error(LinkageLoc, "invalid linkage for function definition");
3132 break;
3133 case GlobalValue::PrivateLinkage:
3134 case GlobalValue::InternalLinkage:
3135 case GlobalValue::AvailableExternallyLinkage:
3136 case GlobalValue::LinkOnceAnyLinkage:
3137 case GlobalValue::LinkOnceODRLinkage:
3138 case GlobalValue::WeakAnyLinkage:
3139 case GlobalValue::WeakODRLinkage:
3140 if (!isDefine)
3141 return Error(LinkageLoc, "invalid linkage for function declaration");
3142 break;
3143 case GlobalValue::AppendingLinkage:
3144 case GlobalValue::CommonLinkage:
3145 return Error(LinkageLoc, "invalid function linkage type");
3146 }
3147
3148 if (!isValidVisibilityForLinkage(Visibility, Linkage))
3149 return Error(LinkageLoc,
3150 "symbol with local linkage must have default visibility");
3151
3152 if (!FunctionType::isValidReturnType(RetType))
3153 return Error(RetTypeLoc, "invalid function return type");
3154
3155 LocTy NameLoc = Lex.getLoc();
3156
3157 std::string FunctionName;
3158 if (Lex.getKind() == lltok::GlobalVar) {
3159 FunctionName = Lex.getStrVal();
3160 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3161 unsigned NameID = Lex.getUIntVal();
3162
3163 if (NameID != NumberedVals.size())
3164 return TokError("function expected to be numbered '%" +
3165 Twine(NumberedVals.size()) + "'");
3166 } else {
3167 return TokError("expected function name");
3168 }
3169
3170 Lex.Lex();
3171
3172 if (Lex.getKind() != lltok::lparen)
3173 return TokError("expected '(' in function argument list");
3174
3175 SmallVector<ArgInfo, 8> ArgList;
3176 bool isVarArg;
3177 AttrBuilder FuncAttrs;
3178 std::vector<unsigned> FwdRefAttrGrps;
3179 LocTy BuiltinLoc;
3180 std::string Section;
3181 unsigned Alignment;
3182 std::string GC;
3183 bool UnnamedAddr;
3184 LocTy UnnamedAddrLoc;
3185 Constant *Prefix = nullptr;
3186 Comdat *C;
3187
3188 if (ParseArgumentList(ArgList, isVarArg) ||
3189 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3190 &UnnamedAddrLoc) ||
3191 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
3192 BuiltinLoc) ||
3193 (EatIfPresent(lltok::kw_section) &&
3194 ParseStringConstant(Section)) ||
3195 parseOptionalComdat(C) ||
3196 ParseOptionalAlignment(Alignment) ||
3197 (EatIfPresent(lltok::kw_gc) &&
3198 ParseStringConstant(GC)) ||
3199 (EatIfPresent(lltok::kw_prefix) &&
3200 ParseGlobalTypeAndValue(Prefix)))
3201 return true;
3202
3203 if (FuncAttrs.contains(Attribute::Builtin))
3204 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
3205
3206 // If the alignment was parsed as an attribute, move to the alignment field.
3207 if (FuncAttrs.hasAlignmentAttr()) {
3208 Alignment = FuncAttrs.getAlignment();
3209 FuncAttrs.removeAttribute(Attribute::Alignment);
3210 }
3211
3212 // Okay, if we got here, the function is syntactically valid. Convert types
3213 // and do semantic checks.
3214 std::vector<Type*> ParamTypeList;
3215 SmallVector<AttributeSet, 8> Attrs;
3216
3217 if (RetAttrs.hasAttributes())
3218 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3219 AttributeSet::ReturnIndex,
3220 RetAttrs));
3221
3222 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3223 ParamTypeList.push_back(ArgList[i].Ty);
3224 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3225 AttrBuilder B(ArgList[i].Attrs, i + 1);
3226 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3227 }
3228 }
3229
3230 if (FuncAttrs.hasAttributes())
3231 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3232 AttributeSet::FunctionIndex,
3233 FuncAttrs));
3234
3235 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3236
3237 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
3238 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3239
3240 FunctionType *FT =
3241 FunctionType::get(RetType, ParamTypeList, isVarArg);
3242 PointerType *PFT = PointerType::getUnqual(FT);
3243
3244 Fn = nullptr;
3245 if (!FunctionName.empty()) {
3246 // If this was a definition of a forward reference, remove the definition
3247 // from the forward reference table and fill in the forward ref.
3248 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3249 ForwardRefVals.find(FunctionName);
3250 if (FRVI != ForwardRefVals.end()) {
3251 Fn = M->getFunction(FunctionName);
3252 if (!Fn)
3253 return Error(FRVI->second.second, "invalid forward reference to "
3254 "function as global value!");
3255 if (Fn->getType() != PFT)
3256 return Error(FRVI->second.second, "invalid forward reference to "
3257 "function '" + FunctionName + "' with wrong type!");
3258
3259 ForwardRefVals.erase(FRVI);
3260 } else if ((Fn = M->getFunction(FunctionName))) {
3261 // Reject redefinitions.
3262 return Error(NameLoc, "invalid redefinition of function '" +
3263 FunctionName + "'");
3264 } else if (M->getNamedValue(FunctionName)) {
3265 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
3266 }
3267
3268 } else {
3269 // If this is a definition of a forward referenced function, make sure the
3270 // types agree.
3271 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3272 = ForwardRefValIDs.find(NumberedVals.size());
3273 if (I != ForwardRefValIDs.end()) {
3274 Fn = cast<Function>(I->second.first);
3275 if (Fn->getType() != PFT)
3276 return Error(NameLoc, "type of definition and forward reference of '@" +
3277 Twine(NumberedVals.size()) + "' disagree");
3278 ForwardRefValIDs.erase(I);
3279 }
3280 }
3281
3282 if (!Fn)
3283 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3284 else // Move the forward-reference to the correct spot in the module.
3285 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3286
3287 if (FunctionName.empty())
3288 NumberedVals.push_back(Fn);
3289
3290 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3291 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3292 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
3293 Fn->setCallingConv(CC);
3294 Fn->setAttributes(PAL);
3295 Fn->setUnnamedAddr(UnnamedAddr);
3296 Fn->setAlignment(Alignment);
3297 Fn->setSection(Section);
3298 Fn->setComdat(C);
3299 if (!GC.empty()) Fn->setGC(GC.c_str());
3300 Fn->setPrefixData(Prefix);
3301 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
3302
3303 // Add all of the arguments we parsed to the function.
3304 Function::arg_iterator ArgIt = Fn->arg_begin();
3305 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3306 // If the argument has a name, insert it into the argument symbol table.
3307 if (ArgList[i].Name.empty()) continue;
3308
3309 // Set the name, if it conflicted, it will be auto-renamed.
3310 ArgIt->setName(ArgList[i].Name);
3311
3312 if (ArgIt->getName() != ArgList[i].Name)
3313 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3314 ArgList[i].Name + "'");
3315 }
3316
3317 return false;
3318 }
3319
3320
3321 /// ParseFunctionBody
3322 /// ::= '{' BasicBlock+ '}'
3323 ///
ParseFunctionBody(Function & Fn)3324 bool LLParser::ParseFunctionBody(Function &Fn) {
3325 if (Lex.getKind() != lltok::lbrace)
3326 return TokError("expected '{' in function body");
3327 Lex.Lex(); // eat the {.
3328
3329 int FunctionNumber = -1;
3330 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
3331
3332 PerFunctionState PFS(*this, Fn, FunctionNumber);
3333
3334 // We need at least one basic block.
3335 if (Lex.getKind() == lltok::rbrace)
3336 return TokError("function body requires at least one basic block");
3337
3338 while (Lex.getKind() != lltok::rbrace)
3339 if (ParseBasicBlock(PFS)) return true;
3340
3341 // Eat the }.
3342 Lex.Lex();
3343
3344 // Verify function is ok.
3345 return PFS.FinishFunction();
3346 }
3347
3348 /// ParseBasicBlock
3349 /// ::= LabelStr? Instruction*
ParseBasicBlock(PerFunctionState & PFS)3350 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3351 // If this basic block starts out with a name, remember it.
3352 std::string Name;
3353 LocTy NameLoc = Lex.getLoc();
3354 if (Lex.getKind() == lltok::LabelStr) {
3355 Name = Lex.getStrVal();
3356 Lex.Lex();
3357 }
3358
3359 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3360 if (!BB) return true;
3361
3362 std::string NameStr;
3363
3364 // Parse the instructions in this block until we get a terminator.
3365 Instruction *Inst;
3366 do {
3367 // This instruction may have three possibilities for a name: a) none
3368 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3369 LocTy NameLoc = Lex.getLoc();
3370 int NameID = -1;
3371 NameStr = "";
3372
3373 if (Lex.getKind() == lltok::LocalVarID) {
3374 NameID = Lex.getUIntVal();
3375 Lex.Lex();
3376 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3377 return true;
3378 } else if (Lex.getKind() == lltok::LocalVar) {
3379 NameStr = Lex.getStrVal();
3380 Lex.Lex();
3381 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3382 return true;
3383 }
3384
3385 switch (ParseInstruction(Inst, BB, PFS)) {
3386 default: llvm_unreachable("Unknown ParseInstruction result!");
3387 case InstError: return true;
3388 case InstNormal:
3389 BB->getInstList().push_back(Inst);
3390
3391 // With a normal result, we check to see if the instruction is followed by
3392 // a comma and metadata.
3393 if (EatIfPresent(lltok::comma))
3394 if (ParseInstructionMetadata(Inst, &PFS))
3395 return true;
3396 break;
3397 case InstExtraComma:
3398 BB->getInstList().push_back(Inst);
3399
3400 // If the instruction parser ate an extra comma at the end of it, it
3401 // *must* be followed by metadata.
3402 if (ParseInstructionMetadata(Inst, &PFS))
3403 return true;
3404 break;
3405 }
3406
3407 // Set the name on the instruction.
3408 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3409 } while (!isa<TerminatorInst>(Inst));
3410
3411 return false;
3412 }
3413
3414 //===----------------------------------------------------------------------===//
3415 // Instruction Parsing.
3416 //===----------------------------------------------------------------------===//
3417
3418 /// ParseInstruction - Parse one of the many different instructions.
3419 ///
ParseInstruction(Instruction * & Inst,BasicBlock * BB,PerFunctionState & PFS)3420 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3421 PerFunctionState &PFS) {
3422 lltok::Kind Token = Lex.getKind();
3423 if (Token == lltok::Eof)
3424 return TokError("found end of file when expecting more instructions");
3425 LocTy Loc = Lex.getLoc();
3426 unsigned KeywordVal = Lex.getUIntVal();
3427 Lex.Lex(); // Eat the keyword.
3428
3429 switch (Token) {
3430 default: return Error(Loc, "expected instruction opcode");
3431 // Terminator Instructions.
3432 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3433 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3434 case lltok::kw_br: return ParseBr(Inst, PFS);
3435 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
3436 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
3437 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3438 case lltok::kw_resume: return ParseResume(Inst, PFS);
3439 // Binary Operators.
3440 case lltok::kw_add:
3441 case lltok::kw_sub:
3442 case lltok::kw_mul:
3443 case lltok::kw_shl: {
3444 bool NUW = EatIfPresent(lltok::kw_nuw);
3445 bool NSW = EatIfPresent(lltok::kw_nsw);
3446 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3447
3448 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3449
3450 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3451 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3452 return false;
3453 }
3454 case lltok::kw_fadd:
3455 case lltok::kw_fsub:
3456 case lltok::kw_fmul:
3457 case lltok::kw_fdiv:
3458 case lltok::kw_frem: {
3459 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3460 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3461 if (Res != 0)
3462 return Res;
3463 if (FMF.any())
3464 Inst->setFastMathFlags(FMF);
3465 return 0;
3466 }
3467
3468 case lltok::kw_sdiv:
3469 case lltok::kw_udiv:
3470 case lltok::kw_lshr:
3471 case lltok::kw_ashr: {
3472 bool Exact = EatIfPresent(lltok::kw_exact);
3473
3474 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3475 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3476 return false;
3477 }
3478
3479 case lltok::kw_urem:
3480 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3481 case lltok::kw_and:
3482 case lltok::kw_or:
3483 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3484 case lltok::kw_icmp:
3485 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3486 // Casts.
3487 case lltok::kw_trunc:
3488 case lltok::kw_zext:
3489 case lltok::kw_sext:
3490 case lltok::kw_fptrunc:
3491 case lltok::kw_fpext:
3492 case lltok::kw_bitcast:
3493 case lltok::kw_addrspacecast:
3494 case lltok::kw_uitofp:
3495 case lltok::kw_sitofp:
3496 case lltok::kw_fptoui:
3497 case lltok::kw_fptosi:
3498 case lltok::kw_inttoptr:
3499 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3500 // Other.
3501 case lltok::kw_select: return ParseSelect(Inst, PFS);
3502 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3503 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3504 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3505 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3506 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3507 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3508 // Call.
3509 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
3510 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
3511 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
3512 // Memory.
3513 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3514 case lltok::kw_load: return ParseLoad(Inst, PFS);
3515 case lltok::kw_store: return ParseStore(Inst, PFS);
3516 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3517 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3518 case lltok::kw_fence: return ParseFence(Inst, PFS);
3519 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3520 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3521 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3522 }
3523 }
3524
3525 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
ParseCmpPredicate(unsigned & P,unsigned Opc)3526 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3527 if (Opc == Instruction::FCmp) {
3528 switch (Lex.getKind()) {
3529 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
3530 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3531 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3532 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3533 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3534 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3535 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3536 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3537 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3538 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3539 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3540 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3541 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3542 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3543 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3544 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3545 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3546 }
3547 } else {
3548 switch (Lex.getKind()) {
3549 default: return TokError("expected icmp predicate (e.g. 'eq')");
3550 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3551 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3552 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3553 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3554 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3555 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3556 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3557 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3558 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3559 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3560 }
3561 }
3562 Lex.Lex();
3563 return false;
3564 }
3565
3566 //===----------------------------------------------------------------------===//
3567 // Terminator Instructions.
3568 //===----------------------------------------------------------------------===//
3569
3570 /// ParseRet - Parse a return instruction.
3571 /// ::= 'ret' void (',' !dbg, !1)*
3572 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
ParseRet(Instruction * & Inst,BasicBlock * BB,PerFunctionState & PFS)3573 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3574 PerFunctionState &PFS) {
3575 SMLoc TypeLoc = Lex.getLoc();
3576 Type *Ty = nullptr;
3577 if (ParseType(Ty, true /*void allowed*/)) return true;
3578
3579 Type *ResType = PFS.getFunction().getReturnType();
3580
3581 if (Ty->isVoidTy()) {
3582 if (!ResType->isVoidTy())
3583 return Error(TypeLoc, "value doesn't match function result type '" +
3584 getTypeString(ResType) + "'");
3585
3586 Inst = ReturnInst::Create(Context);
3587 return false;
3588 }
3589
3590 Value *RV;
3591 if (ParseValue(Ty, RV, PFS)) return true;
3592
3593 if (ResType != RV->getType())
3594 return Error(TypeLoc, "value doesn't match function result type '" +
3595 getTypeString(ResType) + "'");
3596
3597 Inst = ReturnInst::Create(Context, RV);
3598 return false;
3599 }
3600
3601
3602 /// ParseBr
3603 /// ::= 'br' TypeAndValue
3604 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
ParseBr(Instruction * & Inst,PerFunctionState & PFS)3605 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3606 LocTy Loc, Loc2;
3607 Value *Op0;
3608 BasicBlock *Op1, *Op2;
3609 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3610
3611 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3612 Inst = BranchInst::Create(BB);
3613 return false;
3614 }
3615
3616 if (Op0->getType() != Type::getInt1Ty(Context))
3617 return Error(Loc, "branch condition must have 'i1' type");
3618
3619 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3620 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3621 ParseToken(lltok::comma, "expected ',' after true destination") ||
3622 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3623 return true;
3624
3625 Inst = BranchInst::Create(Op1, Op2, Op0);
3626 return false;
3627 }
3628
3629 /// ParseSwitch
3630 /// Instruction
3631 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3632 /// JumpTable
3633 /// ::= (TypeAndValue ',' TypeAndValue)*
ParseSwitch(Instruction * & Inst,PerFunctionState & PFS)3634 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3635 LocTy CondLoc, BBLoc;
3636 Value *Cond;
3637 BasicBlock *DefaultBB;
3638 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3639 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3640 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3641 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3642 return true;
3643
3644 if (!Cond->getType()->isIntegerTy())
3645 return Error(CondLoc, "switch condition must have integer type");
3646
3647 // Parse the jump table pairs.
3648 SmallPtrSet<Value*, 32> SeenCases;
3649 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3650 while (Lex.getKind() != lltok::rsquare) {
3651 Value *Constant;
3652 BasicBlock *DestBB;
3653
3654 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3655 ParseToken(lltok::comma, "expected ',' after case value") ||
3656 ParseTypeAndBasicBlock(DestBB, PFS))
3657 return true;
3658
3659 if (!SeenCases.insert(Constant))
3660 return Error(CondLoc, "duplicate case value in switch");
3661 if (!isa<ConstantInt>(Constant))
3662 return Error(CondLoc, "case value is not a constant integer");
3663
3664 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3665 }
3666
3667 Lex.Lex(); // Eat the ']'.
3668
3669 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3670 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3671 SI->addCase(Table[i].first, Table[i].second);
3672 Inst = SI;
3673 return false;
3674 }
3675
3676 /// ParseIndirectBr
3677 /// Instruction
3678 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
ParseIndirectBr(Instruction * & Inst,PerFunctionState & PFS)3679 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3680 LocTy AddrLoc;
3681 Value *Address;
3682 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3683 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3684 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3685 return true;
3686
3687 if (!Address->getType()->isPointerTy())
3688 return Error(AddrLoc, "indirectbr address must have pointer type");
3689
3690 // Parse the destination list.
3691 SmallVector<BasicBlock*, 16> DestList;
3692
3693 if (Lex.getKind() != lltok::rsquare) {
3694 BasicBlock *DestBB;
3695 if (ParseTypeAndBasicBlock(DestBB, PFS))
3696 return true;
3697 DestList.push_back(DestBB);
3698
3699 while (EatIfPresent(lltok::comma)) {
3700 if (ParseTypeAndBasicBlock(DestBB, PFS))
3701 return true;
3702 DestList.push_back(DestBB);
3703 }
3704 }
3705
3706 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3707 return true;
3708
3709 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3710 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3711 IBI->addDestination(DestList[i]);
3712 Inst = IBI;
3713 return false;
3714 }
3715
3716
3717 /// ParseInvoke
3718 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3719 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
ParseInvoke(Instruction * & Inst,PerFunctionState & PFS)3720 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3721 LocTy CallLoc = Lex.getLoc();
3722 AttrBuilder RetAttrs, FnAttrs;
3723 std::vector<unsigned> FwdRefAttrGrps;
3724 LocTy NoBuiltinLoc;
3725 CallingConv::ID CC;
3726 Type *RetType = nullptr;
3727 LocTy RetTypeLoc;
3728 ValID CalleeID;
3729 SmallVector<ParamInfo, 16> ArgList;
3730
3731 BasicBlock *NormalBB, *UnwindBB;
3732 if (ParseOptionalCallingConv(CC) ||
3733 ParseOptionalReturnAttrs(RetAttrs) ||
3734 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3735 ParseValID(CalleeID) ||
3736 ParseParameterList(ArgList, PFS) ||
3737 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3738 NoBuiltinLoc) ||
3739 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3740 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3741 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3742 ParseTypeAndBasicBlock(UnwindBB, PFS))
3743 return true;
3744
3745 // If RetType is a non-function pointer type, then this is the short syntax
3746 // for the call, which means that RetType is just the return type. Infer the
3747 // rest of the function argument types from the arguments that are present.
3748 PointerType *PFTy = nullptr;
3749 FunctionType *Ty = nullptr;
3750 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3751 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3752 // Pull out the types of all of the arguments...
3753 std::vector<Type*> ParamTypes;
3754 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3755 ParamTypes.push_back(ArgList[i].V->getType());
3756
3757 if (!FunctionType::isValidReturnType(RetType))
3758 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3759
3760 Ty = FunctionType::get(RetType, ParamTypes, false);
3761 PFTy = PointerType::getUnqual(Ty);
3762 }
3763
3764 // Look up the callee.
3765 Value *Callee;
3766 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3767
3768 // Set up the Attribute for the function.
3769 SmallVector<AttributeSet, 8> Attrs;
3770 if (RetAttrs.hasAttributes())
3771 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3772 AttributeSet::ReturnIndex,
3773 RetAttrs));
3774
3775 SmallVector<Value*, 8> Args;
3776
3777 // Loop through FunctionType's arguments and ensure they are specified
3778 // correctly. Also, gather any parameter attributes.
3779 FunctionType::param_iterator I = Ty->param_begin();
3780 FunctionType::param_iterator E = Ty->param_end();
3781 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3782 Type *ExpectedTy = nullptr;
3783 if (I != E) {
3784 ExpectedTy = *I++;
3785 } else if (!Ty->isVarArg()) {
3786 return Error(ArgList[i].Loc, "too many arguments specified");
3787 }
3788
3789 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3790 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3791 getTypeString(ExpectedTy) + "'");
3792 Args.push_back(ArgList[i].V);
3793 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3794 AttrBuilder B(ArgList[i].Attrs, i + 1);
3795 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3796 }
3797 }
3798
3799 if (I != E)
3800 return Error(CallLoc, "not enough parameters specified for call");
3801
3802 if (FnAttrs.hasAttributes())
3803 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3804 AttributeSet::FunctionIndex,
3805 FnAttrs));
3806
3807 // Finish off the Attribute and check them
3808 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3809
3810 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3811 II->setCallingConv(CC);
3812 II->setAttributes(PAL);
3813 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
3814 Inst = II;
3815 return false;
3816 }
3817
3818 /// ParseResume
3819 /// ::= 'resume' TypeAndValue
ParseResume(Instruction * & Inst,PerFunctionState & PFS)3820 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3821 Value *Exn; LocTy ExnLoc;
3822 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3823 return true;
3824
3825 ResumeInst *RI = ResumeInst::Create(Exn);
3826 Inst = RI;
3827 return false;
3828 }
3829
3830 //===----------------------------------------------------------------------===//
3831 // Binary Operators.
3832 //===----------------------------------------------------------------------===//
3833
3834 /// ParseArithmetic
3835 /// ::= ArithmeticOps TypeAndValue ',' Value
3836 ///
3837 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3838 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
ParseArithmetic(Instruction * & Inst,PerFunctionState & PFS,unsigned Opc,unsigned OperandType)3839 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3840 unsigned Opc, unsigned OperandType) {
3841 LocTy Loc; Value *LHS, *RHS;
3842 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3843 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3844 ParseValue(LHS->getType(), RHS, PFS))
3845 return true;
3846
3847 bool Valid;
3848 switch (OperandType) {
3849 default: llvm_unreachable("Unknown operand type!");
3850 case 0: // int or FP.
3851 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3852 LHS->getType()->isFPOrFPVectorTy();
3853 break;
3854 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3855 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3856 }
3857
3858 if (!Valid)
3859 return Error(Loc, "invalid operand type for instruction");
3860
3861 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3862 return false;
3863 }
3864
3865 /// ParseLogical
3866 /// ::= ArithmeticOps TypeAndValue ',' Value {
ParseLogical(Instruction * & Inst,PerFunctionState & PFS,unsigned Opc)3867 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3868 unsigned Opc) {
3869 LocTy Loc; Value *LHS, *RHS;
3870 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3871 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3872 ParseValue(LHS->getType(), RHS, PFS))
3873 return true;
3874
3875 if (!LHS->getType()->isIntOrIntVectorTy())
3876 return Error(Loc,"instruction requires integer or integer vector operands");
3877
3878 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3879 return false;
3880 }
3881
3882
3883 /// ParseCompare
3884 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3885 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
ParseCompare(Instruction * & Inst,PerFunctionState & PFS,unsigned Opc)3886 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3887 unsigned Opc) {
3888 // Parse the integer/fp comparison predicate.
3889 LocTy Loc;
3890 unsigned Pred;
3891 Value *LHS, *RHS;
3892 if (ParseCmpPredicate(Pred, Opc) ||
3893 ParseTypeAndValue(LHS, Loc, PFS) ||
3894 ParseToken(lltok::comma, "expected ',' after compare value") ||
3895 ParseValue(LHS->getType(), RHS, PFS))
3896 return true;
3897
3898 if (Opc == Instruction::FCmp) {
3899 if (!LHS->getType()->isFPOrFPVectorTy())
3900 return Error(Loc, "fcmp requires floating point operands");
3901 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3902 } else {
3903 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3904 if (!LHS->getType()->isIntOrIntVectorTy() &&
3905 !LHS->getType()->getScalarType()->isPointerTy())
3906 return Error(Loc, "icmp requires integer operands");
3907 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3908 }
3909 return false;
3910 }
3911
3912 //===----------------------------------------------------------------------===//
3913 // Other Instructions.
3914 //===----------------------------------------------------------------------===//
3915
3916
3917 /// ParseCast
3918 /// ::= CastOpc TypeAndValue 'to' Type
ParseCast(Instruction * & Inst,PerFunctionState & PFS,unsigned Opc)3919 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3920 unsigned Opc) {
3921 LocTy Loc;
3922 Value *Op;
3923 Type *DestTy = nullptr;
3924 if (ParseTypeAndValue(Op, Loc, PFS) ||
3925 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3926 ParseType(DestTy))
3927 return true;
3928
3929 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3930 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3931 return Error(Loc, "invalid cast opcode for cast from '" +
3932 getTypeString(Op->getType()) + "' to '" +
3933 getTypeString(DestTy) + "'");
3934 }
3935 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3936 return false;
3937 }
3938
3939 /// ParseSelect
3940 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
ParseSelect(Instruction * & Inst,PerFunctionState & PFS)3941 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3942 LocTy Loc;
3943 Value *Op0, *Op1, *Op2;
3944 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3945 ParseToken(lltok::comma, "expected ',' after select condition") ||
3946 ParseTypeAndValue(Op1, PFS) ||
3947 ParseToken(lltok::comma, "expected ',' after select value") ||
3948 ParseTypeAndValue(Op2, PFS))
3949 return true;
3950
3951 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3952 return Error(Loc, Reason);
3953
3954 Inst = SelectInst::Create(Op0, Op1, Op2);
3955 return false;
3956 }
3957
3958 /// ParseVA_Arg
3959 /// ::= 'va_arg' TypeAndValue ',' Type
ParseVA_Arg(Instruction * & Inst,PerFunctionState & PFS)3960 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3961 Value *Op;
3962 Type *EltTy = nullptr;
3963 LocTy TypeLoc;
3964 if (ParseTypeAndValue(Op, PFS) ||
3965 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3966 ParseType(EltTy, TypeLoc))
3967 return true;
3968
3969 if (!EltTy->isFirstClassType())
3970 return Error(TypeLoc, "va_arg requires operand with first class type");
3971
3972 Inst = new VAArgInst(Op, EltTy);
3973 return false;
3974 }
3975
3976 /// ParseExtractElement
3977 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
ParseExtractElement(Instruction * & Inst,PerFunctionState & PFS)3978 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3979 LocTy Loc;
3980 Value *Op0, *Op1;
3981 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3982 ParseToken(lltok::comma, "expected ',' after extract value") ||
3983 ParseTypeAndValue(Op1, PFS))
3984 return true;
3985
3986 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3987 return Error(Loc, "invalid extractelement operands");
3988
3989 Inst = ExtractElementInst::Create(Op0, Op1);
3990 return false;
3991 }
3992
3993 /// ParseInsertElement
3994 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
ParseInsertElement(Instruction * & Inst,PerFunctionState & PFS)3995 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3996 LocTy Loc;
3997 Value *Op0, *Op1, *Op2;
3998 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3999 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4000 ParseTypeAndValue(Op1, PFS) ||
4001 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4002 ParseTypeAndValue(Op2, PFS))
4003 return true;
4004
4005 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
4006 return Error(Loc, "invalid insertelement operands");
4007
4008 Inst = InsertElementInst::Create(Op0, Op1, Op2);
4009 return false;
4010 }
4011
4012 /// ParseShuffleVector
4013 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
ParseShuffleVector(Instruction * & Inst,PerFunctionState & PFS)4014 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
4015 LocTy Loc;
4016 Value *Op0, *Op1, *Op2;
4017 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4018 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
4019 ParseTypeAndValue(Op1, PFS) ||
4020 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
4021 ParseTypeAndValue(Op2, PFS))
4022 return true;
4023
4024 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
4025 return Error(Loc, "invalid shufflevector operands");
4026
4027 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
4028 return false;
4029 }
4030
4031 /// ParsePHI
4032 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
ParsePHI(Instruction * & Inst,PerFunctionState & PFS)4033 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
4034 Type *Ty = nullptr; LocTy TypeLoc;
4035 Value *Op0, *Op1;
4036
4037 if (ParseType(Ty, TypeLoc) ||
4038 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4039 ParseValue(Ty, Op0, PFS) ||
4040 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4041 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
4042 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4043 return true;
4044
4045 bool AteExtraComma = false;
4046 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
4047 while (1) {
4048 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
4049
4050 if (!EatIfPresent(lltok::comma))
4051 break;
4052
4053 if (Lex.getKind() == lltok::MetadataVar) {
4054 AteExtraComma = true;
4055 break;
4056 }
4057
4058 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4059 ParseValue(Ty, Op0, PFS) ||
4060 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4061 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
4062 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4063 return true;
4064 }
4065
4066 if (!Ty->isFirstClassType())
4067 return Error(TypeLoc, "phi node must have first class type");
4068
4069 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
4070 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
4071 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
4072 Inst = PN;
4073 return AteExtraComma ? InstExtraComma : InstNormal;
4074 }
4075
4076 /// ParseLandingPad
4077 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
4078 /// Clause
4079 /// ::= 'catch' TypeAndValue
4080 /// ::= 'filter'
4081 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
ParseLandingPad(Instruction * & Inst,PerFunctionState & PFS)4082 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
4083 Type *Ty = nullptr; LocTy TyLoc;
4084 Value *PersFn; LocTy PersFnLoc;
4085
4086 if (ParseType(Ty, TyLoc) ||
4087 ParseToken(lltok::kw_personality, "expected 'personality'") ||
4088 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
4089 return true;
4090
4091 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
4092 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
4093
4094 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
4095 LandingPadInst::ClauseType CT;
4096 if (EatIfPresent(lltok::kw_catch))
4097 CT = LandingPadInst::Catch;
4098 else if (EatIfPresent(lltok::kw_filter))
4099 CT = LandingPadInst::Filter;
4100 else
4101 return TokError("expected 'catch' or 'filter' clause type");
4102
4103 Value *V;
4104 LocTy VLoc;
4105 if (ParseTypeAndValue(V, VLoc, PFS)) {
4106 delete LP;
4107 return true;
4108 }
4109
4110 // A 'catch' type expects a non-array constant. A filter clause expects an
4111 // array constant.
4112 if (CT == LandingPadInst::Catch) {
4113 if (isa<ArrayType>(V->getType()))
4114 Error(VLoc, "'catch' clause has an invalid type");
4115 } else {
4116 if (!isa<ArrayType>(V->getType()))
4117 Error(VLoc, "'filter' clause has an invalid type");
4118 }
4119
4120 LP->addClause(cast<Constant>(V));
4121 }
4122
4123 Inst = LP;
4124 return false;
4125 }
4126
4127 /// ParseCall
4128 /// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
4129 /// ParameterList OptionalAttrs
4130 /// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
4131 /// ParameterList OptionalAttrs
4132 /// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
4133 /// ParameterList OptionalAttrs
ParseCall(Instruction * & Inst,PerFunctionState & PFS,CallInst::TailCallKind TCK)4134 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
4135 CallInst::TailCallKind TCK) {
4136 AttrBuilder RetAttrs, FnAttrs;
4137 std::vector<unsigned> FwdRefAttrGrps;
4138 LocTy BuiltinLoc;
4139 CallingConv::ID CC;
4140 Type *RetType = nullptr;
4141 LocTy RetTypeLoc;
4142 ValID CalleeID;
4143 SmallVector<ParamInfo, 16> ArgList;
4144 LocTy CallLoc = Lex.getLoc();
4145
4146 if ((TCK != CallInst::TCK_None &&
4147 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
4148 ParseOptionalCallingConv(CC) ||
4149 ParseOptionalReturnAttrs(RetAttrs) ||
4150 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4151 ParseValID(CalleeID) ||
4152 ParseParameterList(ArgList, PFS) ||
4153 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4154 BuiltinLoc))
4155 return true;
4156
4157 // If RetType is a non-function pointer type, then this is the short syntax
4158 // for the call, which means that RetType is just the return type. Infer the
4159 // rest of the function argument types from the arguments that are present.
4160 PointerType *PFTy = nullptr;
4161 FunctionType *Ty = nullptr;
4162 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4163 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4164 // Pull out the types of all of the arguments...
4165 std::vector<Type*> ParamTypes;
4166 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4167 ParamTypes.push_back(ArgList[i].V->getType());
4168
4169 if (!FunctionType::isValidReturnType(RetType))
4170 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4171
4172 Ty = FunctionType::get(RetType, ParamTypes, false);
4173 PFTy = PointerType::getUnqual(Ty);
4174 }
4175
4176 // Look up the callee.
4177 Value *Callee;
4178 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
4179
4180 // Set up the Attribute for the function.
4181 SmallVector<AttributeSet, 8> Attrs;
4182 if (RetAttrs.hasAttributes())
4183 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4184 AttributeSet::ReturnIndex,
4185 RetAttrs));
4186
4187 SmallVector<Value*, 8> Args;
4188
4189 // Loop through FunctionType's arguments and ensure they are specified
4190 // correctly. Also, gather any parameter attributes.
4191 FunctionType::param_iterator I = Ty->param_begin();
4192 FunctionType::param_iterator E = Ty->param_end();
4193 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4194 Type *ExpectedTy = nullptr;
4195 if (I != E) {
4196 ExpectedTy = *I++;
4197 } else if (!Ty->isVarArg()) {
4198 return Error(ArgList[i].Loc, "too many arguments specified");
4199 }
4200
4201 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4202 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4203 getTypeString(ExpectedTy) + "'");
4204 Args.push_back(ArgList[i].V);
4205 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4206 AttrBuilder B(ArgList[i].Attrs, i + 1);
4207 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4208 }
4209 }
4210
4211 if (I != E)
4212 return Error(CallLoc, "not enough parameters specified for call");
4213
4214 if (FnAttrs.hasAttributes())
4215 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4216 AttributeSet::FunctionIndex,
4217 FnAttrs));
4218
4219 // Finish off the Attribute and check them
4220 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4221
4222 CallInst *CI = CallInst::Create(Callee, Args);
4223 CI->setTailCallKind(TCK);
4224 CI->setCallingConv(CC);
4225 CI->setAttributes(PAL);
4226 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
4227 Inst = CI;
4228 return false;
4229 }
4230
4231 //===----------------------------------------------------------------------===//
4232 // Memory Instructions.
4233 //===----------------------------------------------------------------------===//
4234
4235 /// ParseAlloc
4236 /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
ParseAlloc(Instruction * & Inst,PerFunctionState & PFS)4237 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
4238 Value *Size = nullptr;
4239 LocTy SizeLoc;
4240 unsigned Alignment = 0;
4241 Type *Ty = nullptr;
4242
4243 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4244
4245 if (ParseType(Ty)) return true;
4246
4247 bool AteExtraComma = false;
4248 if (EatIfPresent(lltok::comma)) {
4249 if (Lex.getKind() == lltok::kw_align) {
4250 if (ParseOptionalAlignment(Alignment)) return true;
4251 } else if (Lex.getKind() == lltok::MetadataVar) {
4252 AteExtraComma = true;
4253 } else {
4254 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4255 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4256 return true;
4257 }
4258 }
4259
4260 if (Size && !Size->getType()->isIntegerTy())
4261 return Error(SizeLoc, "element count must have integer type");
4262
4263 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4264 AI->setUsedWithInAlloca(IsInAlloca);
4265 Inst = AI;
4266 return AteExtraComma ? InstExtraComma : InstNormal;
4267 }
4268
4269 /// ParseLoad
4270 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
4271 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
4272 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
ParseLoad(Instruction * & Inst,PerFunctionState & PFS)4273 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
4274 Value *Val; LocTy Loc;
4275 unsigned Alignment = 0;
4276 bool AteExtraComma = false;
4277 bool isAtomic = false;
4278 AtomicOrdering Ordering = NotAtomic;
4279 SynchronizationScope Scope = CrossThread;
4280
4281 if (Lex.getKind() == lltok::kw_atomic) {
4282 isAtomic = true;
4283 Lex.Lex();
4284 }
4285
4286 bool isVolatile = false;
4287 if (Lex.getKind() == lltok::kw_volatile) {
4288 isVolatile = true;
4289 Lex.Lex();
4290 }
4291
4292 if (ParseTypeAndValue(Val, Loc, PFS) ||
4293 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4294 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4295 return true;
4296
4297 if (!Val->getType()->isPointerTy() ||
4298 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4299 return Error(Loc, "load operand must be a pointer to a first class type");
4300 if (isAtomic && !Alignment)
4301 return Error(Loc, "atomic load must have explicit non-zero alignment");
4302 if (Ordering == Release || Ordering == AcquireRelease)
4303 return Error(Loc, "atomic load cannot use Release ordering");
4304
4305 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
4306 return AteExtraComma ? InstExtraComma : InstNormal;
4307 }
4308
4309 /// ParseStore
4310
4311 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4312 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
4313 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
ParseStore(Instruction * & Inst,PerFunctionState & PFS)4314 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
4315 Value *Val, *Ptr; LocTy Loc, PtrLoc;
4316 unsigned Alignment = 0;
4317 bool AteExtraComma = false;
4318 bool isAtomic = false;
4319 AtomicOrdering Ordering = NotAtomic;
4320 SynchronizationScope Scope = CrossThread;
4321
4322 if (Lex.getKind() == lltok::kw_atomic) {
4323 isAtomic = true;
4324 Lex.Lex();
4325 }
4326
4327 bool isVolatile = false;
4328 if (Lex.getKind() == lltok::kw_volatile) {
4329 isVolatile = true;
4330 Lex.Lex();
4331 }
4332
4333 if (ParseTypeAndValue(Val, Loc, PFS) ||
4334 ParseToken(lltok::comma, "expected ',' after store operand") ||
4335 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4336 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4337 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4338 return true;
4339
4340 if (!Ptr->getType()->isPointerTy())
4341 return Error(PtrLoc, "store operand must be a pointer");
4342 if (!Val->getType()->isFirstClassType())
4343 return Error(Loc, "store operand must be a first class value");
4344 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4345 return Error(Loc, "stored value and pointer type do not match");
4346 if (isAtomic && !Alignment)
4347 return Error(Loc, "atomic store must have explicit non-zero alignment");
4348 if (Ordering == Acquire || Ordering == AcquireRelease)
4349 return Error(Loc, "atomic store cannot use Acquire ordering");
4350
4351 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
4352 return AteExtraComma ? InstExtraComma : InstNormal;
4353 }
4354
4355 /// ParseCmpXchg
4356 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
4357 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
ParseCmpXchg(Instruction * & Inst,PerFunctionState & PFS)4358 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
4359 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4360 bool AteExtraComma = false;
4361 AtomicOrdering SuccessOrdering = NotAtomic;
4362 AtomicOrdering FailureOrdering = NotAtomic;
4363 SynchronizationScope Scope = CrossThread;
4364 bool isVolatile = false;
4365 bool isWeak = false;
4366
4367 if (EatIfPresent(lltok::kw_weak))
4368 isWeak = true;
4369
4370 if (EatIfPresent(lltok::kw_volatile))
4371 isVolatile = true;
4372
4373 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4374 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4375 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4376 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4377 ParseTypeAndValue(New, NewLoc, PFS) ||
4378 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4379 ParseOrdering(FailureOrdering))
4380 return true;
4381
4382 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
4383 return TokError("cmpxchg cannot be unordered");
4384 if (SuccessOrdering < FailureOrdering)
4385 return TokError("cmpxchg must be at least as ordered on success as failure");
4386 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4387 return TokError("cmpxchg failure ordering cannot include release semantics");
4388 if (!Ptr->getType()->isPointerTy())
4389 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4390 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4391 return Error(CmpLoc, "compare value and pointer type do not match");
4392 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4393 return Error(NewLoc, "new value and pointer type do not match");
4394 if (!New->getType()->isIntegerTy())
4395 return Error(NewLoc, "cmpxchg operand must be an integer");
4396 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4397 if (Size < 8 || (Size & (Size - 1)))
4398 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4399 " integer");
4400
4401 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
4402 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
4403 CXI->setVolatile(isVolatile);
4404 CXI->setWeak(isWeak);
4405 Inst = CXI;
4406 return AteExtraComma ? InstExtraComma : InstNormal;
4407 }
4408
4409 /// ParseAtomicRMW
4410 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4411 /// 'singlethread'? AtomicOrdering
ParseAtomicRMW(Instruction * & Inst,PerFunctionState & PFS)4412 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
4413 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4414 bool AteExtraComma = false;
4415 AtomicOrdering Ordering = NotAtomic;
4416 SynchronizationScope Scope = CrossThread;
4417 bool isVolatile = false;
4418 AtomicRMWInst::BinOp Operation;
4419
4420 if (EatIfPresent(lltok::kw_volatile))
4421 isVolatile = true;
4422
4423 switch (Lex.getKind()) {
4424 default: return TokError("expected binary operation in atomicrmw");
4425 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4426 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4427 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4428 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4429 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4430 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4431 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4432 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4433 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4434 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4435 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4436 }
4437 Lex.Lex(); // Eat the operation.
4438
4439 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4440 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4441 ParseTypeAndValue(Val, ValLoc, PFS) ||
4442 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4443 return true;
4444
4445 if (Ordering == Unordered)
4446 return TokError("atomicrmw cannot be unordered");
4447 if (!Ptr->getType()->isPointerTy())
4448 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4449 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4450 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4451 if (!Val->getType()->isIntegerTy())
4452 return Error(ValLoc, "atomicrmw operand must be an integer");
4453 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4454 if (Size < 8 || (Size & (Size - 1)))
4455 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4456 " integer");
4457
4458 AtomicRMWInst *RMWI =
4459 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4460 RMWI->setVolatile(isVolatile);
4461 Inst = RMWI;
4462 return AteExtraComma ? InstExtraComma : InstNormal;
4463 }
4464
4465 /// ParseFence
4466 /// ::= 'fence' 'singlethread'? AtomicOrdering
ParseFence(Instruction * & Inst,PerFunctionState & PFS)4467 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4468 AtomicOrdering Ordering = NotAtomic;
4469 SynchronizationScope Scope = CrossThread;
4470 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4471 return true;
4472
4473 if (Ordering == Unordered)
4474 return TokError("fence cannot be unordered");
4475 if (Ordering == Monotonic)
4476 return TokError("fence cannot be monotonic");
4477
4478 Inst = new FenceInst(Context, Ordering, Scope);
4479 return InstNormal;
4480 }
4481
4482 /// ParseGetElementPtr
4483 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
ParseGetElementPtr(Instruction * & Inst,PerFunctionState & PFS)4484 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4485 Value *Ptr = nullptr;
4486 Value *Val = nullptr;
4487 LocTy Loc, EltLoc;
4488
4489 bool InBounds = EatIfPresent(lltok::kw_inbounds);
4490
4491 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4492
4493 Type *BaseType = Ptr->getType();
4494 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4495 if (!BasePointerType)
4496 return Error(Loc, "base of getelementptr must be a pointer");
4497
4498 SmallVector<Value*, 16> Indices;
4499 bool AteExtraComma = false;
4500 while (EatIfPresent(lltok::comma)) {
4501 if (Lex.getKind() == lltok::MetadataVar) {
4502 AteExtraComma = true;
4503 break;
4504 }
4505 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4506 if (!Val->getType()->getScalarType()->isIntegerTy())
4507 return Error(EltLoc, "getelementptr index must be an integer");
4508 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4509 return Error(EltLoc, "getelementptr index type missmatch");
4510 if (Val->getType()->isVectorTy()) {
4511 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4512 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4513 if (ValNumEl != PtrNumEl)
4514 return Error(EltLoc,
4515 "getelementptr vector index has a wrong number of elements");
4516 }
4517 Indices.push_back(Val);
4518 }
4519
4520 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4521 return Error(Loc, "base element of getelementptr must be sized");
4522
4523 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
4524 return Error(Loc, "invalid getelementptr indices");
4525 Inst = GetElementPtrInst::Create(Ptr, Indices);
4526 if (InBounds)
4527 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4528 return AteExtraComma ? InstExtraComma : InstNormal;
4529 }
4530
4531 /// ParseExtractValue
4532 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
ParseExtractValue(Instruction * & Inst,PerFunctionState & PFS)4533 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4534 Value *Val; LocTy Loc;
4535 SmallVector<unsigned, 4> Indices;
4536 bool AteExtraComma;
4537 if (ParseTypeAndValue(Val, Loc, PFS) ||
4538 ParseIndexList(Indices, AteExtraComma))
4539 return true;
4540
4541 if (!Val->getType()->isAggregateType())
4542 return Error(Loc, "extractvalue operand must be aggregate type");
4543
4544 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4545 return Error(Loc, "invalid indices for extractvalue");
4546 Inst = ExtractValueInst::Create(Val, Indices);
4547 return AteExtraComma ? InstExtraComma : InstNormal;
4548 }
4549
4550 /// ParseInsertValue
4551 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
ParseInsertValue(Instruction * & Inst,PerFunctionState & PFS)4552 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4553 Value *Val0, *Val1; LocTy Loc0, Loc1;
4554 SmallVector<unsigned, 4> Indices;
4555 bool AteExtraComma;
4556 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4557 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4558 ParseTypeAndValue(Val1, Loc1, PFS) ||
4559 ParseIndexList(Indices, AteExtraComma))
4560 return true;
4561
4562 if (!Val0->getType()->isAggregateType())
4563 return Error(Loc0, "insertvalue operand must be aggregate type");
4564
4565 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4566 return Error(Loc0, "invalid indices for insertvalue");
4567 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4568 return AteExtraComma ? InstExtraComma : InstNormal;
4569 }
4570
4571 //===----------------------------------------------------------------------===//
4572 // Embedded metadata.
4573 //===----------------------------------------------------------------------===//
4574
4575 /// ParseMDNodeVector
4576 /// ::= Element (',' Element)*
4577 /// Element
4578 /// ::= 'null' | TypeAndValue
ParseMDNodeVector(SmallVectorImpl<Value * > & Elts,PerFunctionState * PFS)4579 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4580 PerFunctionState *PFS) {
4581 // Check for an empty list.
4582 if (Lex.getKind() == lltok::rbrace)
4583 return false;
4584
4585 do {
4586 // Null is a special case since it is typeless.
4587 if (EatIfPresent(lltok::kw_null)) {
4588 Elts.push_back(nullptr);
4589 continue;
4590 }
4591
4592 Value *V = nullptr;
4593 if (ParseTypeAndValue(V, PFS)) return true;
4594 Elts.push_back(V);
4595 } while (EatIfPresent(lltok::comma));
4596
4597 return false;
4598 }
4599