blob: 0d748610742a5aeaad83c8a52fc5f32554ef63c6 [file] [log] [blame]
Chris Lattnerac161bf2009-01-02 07:01:27 +00001//===-- 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"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth91065212014-03-05 10:34:14 +000016#include "llvm/IR/AutoUpgrade.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/CallingConv.h"
18#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000019#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000020#include "llvm/IR/DerivedTypes.h"
21#include "llvm/IR/InlineAsm.h"
22#include "llvm/IR/Instructions.h"
Manman Ren209b17c2013-09-28 00:22:27 +000023#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Module.h"
25#include "llvm/IR/Operator.h"
26#include "llvm/IR/ValueSymbolTable.h"
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +000027#include "llvm/Support/Dwarf.h"
Torok Edwin56d06592009-07-11 20:10:48 +000028#include "llvm/Support/ErrorHandling.h"
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +000029#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerac161bf2009-01-02 07:01:27 +000030#include "llvm/Support/raw_ostream.h"
31using namespace llvm;
32
Chris Lattner229907c2011-07-18 04:54:35 +000033static std::string getTypeString(Type *T) {
Alp Tokere69170a2014-06-26 22:52:05 +000034 std::string Result;
35 raw_string_ostream Tmp(Result);
36 Tmp << *T;
37 return Tmp.str();
Chris Lattner0f214eb2011-06-18 21:18:23 +000038}
39
Chris Lattner3822f632009-01-02 08:05:26 +000040/// Run: module ::= toplevelentity*
Chris Lattnerad6f3352009-01-04 20:44:11 +000041bool LLParser::Run() {
Chris Lattner3822f632009-01-02 08:05:26 +000042 // Prime the lexer.
43 Lex.Lex();
44
Chris Lattnerad6f3352009-01-04 20:44:11 +000045 return ParseTopLevelEntities() ||
46 ValidateEndOfModule();
Chris Lattnerac161bf2009-01-02 07:01:27 +000047}
48
49/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
50/// module.
51bool LLParser::ValidateEndOfModule() {
Manman Ren209b17c2013-09-28 00:22:27 +000052 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
53 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
54
Bill Wendlingb32b0412013-02-08 06:32:06 +000055 // Handle any function attribute group forward references.
56 for (std::map<Value*, std::vector<unsigned> >::iterator
57 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
58 I != E; ++I) {
59 Value *V = I->first;
60 std::vector<unsigned> &Vec = I->second;
61 AttrBuilder B;
62
63 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
64 VI != VE; ++VI)
65 B.merge(NumberedAttrBuilders[*VI]);
66
67 if (Function *Fn = dyn_cast<Function>(V)) {
68 AttributeSet AS = Fn->getAttributes();
69 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
70 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
71 AS.getFnAttributes());
72
73 FnAttrs.merge(B);
74
75 // If the alignment was parsed as an attribute, move to the alignment
76 // field.
77 if (FnAttrs.hasAlignmentAttr()) {
78 Fn->setAlignment(FnAttrs.getAlignment());
79 FnAttrs.removeAttribute(Attribute::Alignment);
80 }
81
82 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
83 AttributeSet::get(Context,
84 AttributeSet::FunctionIndex,
85 FnAttrs));
86 Fn->setAttributes(AS);
87 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
88 AttributeSet AS = CI->getAttributes();
89 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
90 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
91 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +000092 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +000093 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
94 AttributeSet::get(Context,
95 AttributeSet::FunctionIndex,
96 FnAttrs));
97 CI->setAttributes(AS);
98 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
99 AttributeSet AS = II->getAttributes();
100 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
101 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
102 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000103 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000104 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
105 AttributeSet::get(Context,
106 AttributeSet::FunctionIndex,
107 FnAttrs));
108 II->setAttributes(AS);
109 } else {
110 llvm_unreachable("invalid object with forward attribute group reference");
111 }
112 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000113
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000114 // If there are entries in ForwardRefBlockAddresses at this point, the
115 // function was never defined.
116 if (!ForwardRefBlockAddresses.empty())
117 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
118 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000119
David Majnemer19b51052015-02-11 07:43:56 +0000120 for (const auto &NT : NumberedTypes)
121 if (NT.second.second.isValid())
122 return Error(NT.second.second,
123 "use of undefined type '%" + Twine(NT.first) + "'");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000124
125 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
126 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
127 if (I->second.second.isValid())
128 return Error(I->second.second,
129 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000130
David Majnemerdad0a642014-06-27 18:19:56 +0000131 if (!ForwardRefComdats.empty())
132 return Error(ForwardRefComdats.begin()->second,
133 "use of undefined comdat '$" +
134 ForwardRefComdats.begin()->first + "'");
135
Chris Lattnerac161bf2009-01-02 07:01:27 +0000136 if (!ForwardRefVals.empty())
137 return Error(ForwardRefVals.begin()->second.second,
138 "use of undefined value '@" + ForwardRefVals.begin()->first +
139 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000140
Chris Lattnerac161bf2009-01-02 07:01:27 +0000141 if (!ForwardRefValIDs.empty())
142 return Error(ForwardRefValIDs.begin()->second.second,
143 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000144 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000145
Devang Pateld2541152009-07-08 19:23:54 +0000146 if (!ForwardRefMDNodes.empty())
147 return Error(ForwardRefMDNodes.begin()->second.second,
148 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000149 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000150
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000151 // Resolve metadata cycles.
David Majnemer19b51052015-02-11 07:43:56 +0000152 for (auto &N : NumberedMetadata) {
153 if (N.second && !N.second->isResolved())
154 N.second->resolveCycles();
155 }
Devang Pateld2541152009-07-08 19:23:54 +0000156
Chris Lattnerac161bf2009-01-02 07:01:27 +0000157 // Look for intrinsic functions and CallInst that need to be upgraded
158 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
159 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000160
Manman Ren8b4306c2013-12-02 21:29:56 +0000161 UpgradeDebugInfo(*M);
162
Chris Lattnerac161bf2009-01-02 07:01:27 +0000163 return false;
164}
165
166//===----------------------------------------------------------------------===//
167// Top-Level Entities
168//===----------------------------------------------------------------------===//
169
170bool LLParser::ParseTopLevelEntities() {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000171 while (1) {
172 switch (Lex.getKind()) {
173 default: return TokError("expected top-level entity");
174 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000175 case lltok::kw_declare: if (ParseDeclare()) return true; break;
176 case lltok::kw_define: if (ParseDefine()) return true; break;
177 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
178 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000179 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000180 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000181 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000182 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000183 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000184 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000185 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000186 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000187
188 // The Global variable production with no name can have many different
189 // optional leading prefixes, the production is:
Nico Rieck7157bb72014-01-14 15:22:47 +0000190 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
191 // OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
Rafael Espindola45e6c192011-01-08 16:42:36 +0000192 // ('constant'|'global') ...
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000193 case lltok::kw_private: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000194 case lltok::kw_internal: // OptionalLinkage
195 case lltok::kw_weak: // OptionalLinkage
196 case lltok::kw_weak_odr: // OptionalLinkage
197 case lltok::kw_linkonce: // OptionalLinkage
198 case lltok::kw_linkonce_odr: // OptionalLinkage
199 case lltok::kw_appending: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000200 case lltok::kw_common: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000201 case lltok::kw_extern_weak: // OptionalLinkage
Rafael Espindola52b74422014-06-03 20:00:20 +0000202 case lltok::kw_external: // OptionalLinkage
203 case lltok::kw_default: // OptionalVisibility
204 case lltok::kw_hidden: // OptionalVisibility
205 case lltok::kw_protected: // OptionalVisibility
Rafael Espindola63e92fb2014-06-03 20:07:32 +0000206 case lltok::kw_dllimport: // OptionalDLLStorageClass
207 case lltok::kw_dllexport: // OptionalDLLStorageClass
Rafael Espindola52b74422014-06-03 20:00:20 +0000208 case lltok::kw_thread_local: // OptionalThreadLocal
209 case lltok::kw_addrspace: // OptionalAddrSpace
210 case lltok::kw_constant: // GlobalType
211 case lltok::kw_global: { // GlobalType
Nico Rieck7157bb72014-01-14 15:22:47 +0000212 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000213 bool UnnamedAddr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000214 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola52b74422014-06-03 20:00:20 +0000215 bool HasLinkage;
216 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000217 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000218 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000219 ParseOptionalThreadLocal(TLM) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000220 parseOptionalUnnamedAddr(UnnamedAddr) ||
Rafael Espindola52b74422014-06-03 20:00:20 +0000221 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000222 DLLStorageClass, TLM, UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000223 return true;
224 break;
225 }
Bill Wendlinga7c38772013-02-09 15:48:49 +0000226
227 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000228 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
229 case lltok::kw_uselistorder_bb:
230 if (ParseUseListOrderBB()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000231 }
232 }
233}
234
235
236/// toplevelentity
237/// ::= 'module' 'asm' STRINGCONSTANT
238bool LLParser::ParseModuleAsm() {
239 assert(Lex.getKind() == lltok::kw_module);
240 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000241
242 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000243 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
244 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000245
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000246 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000247 return false;
248}
249
250/// toplevelentity
251/// ::= 'target' 'triple' '=' STRINGCONSTANT
252/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
253bool LLParser::ParseTargetDefinition() {
254 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000255 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000256 switch (Lex.Lex()) {
257 default: return TokError("unknown target property");
258 case lltok::kw_triple:
259 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000260 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
261 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000262 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000263 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000264 return false;
265 case lltok::kw_datalayout:
266 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000267 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
268 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000269 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000270 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000271 return false;
272 }
273}
274
Bill Wendling706d3d62012-11-28 08:41:48 +0000275/// toplevelentity
276/// ::= 'deplibs' '=' '[' ']'
277/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
278/// FIXME: Remove in 4.0. Currently parse, but ignore.
279bool LLParser::ParseDepLibs() {
280 assert(Lex.getKind() == lltok::kw_deplibs);
281 Lex.Lex();
282 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
283 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
284 return true;
285
286 if (EatIfPresent(lltok::rsquare))
287 return false;
288
289 do {
290 std::string Str;
291 if (ParseStringConstant(Str)) return true;
292 } while (EatIfPresent(lltok::comma));
293
294 return ParseToken(lltok::rsquare, "expected ']' at end of list");
295}
296
Dan Gohman466876b2009-08-12 23:32:33 +0000297/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000298/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000299bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000300 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000301 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000302 Lex.Lex(); // eat LocalVarID;
303
304 if (ParseToken(lltok::equal, "expected '=' after name") ||
305 ParseToken(lltok::kw_type, "expected 'type' after '='"))
306 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000307
Craig Topper2617dcc2014-04-15 06:32:26 +0000308 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000309 if (ParseStructDefinition(TypeLoc, "",
310 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000311
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000312 if (!isa<StructType>(Result)) {
313 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
314 if (Entry.first)
315 return Error(TypeLoc, "non-struct types may not be recursive");
316 Entry.first = Result;
317 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000318 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000319
Chris Lattnerac161bf2009-01-02 07:01:27 +0000320 return false;
321}
322
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000323
Chris Lattnerac161bf2009-01-02 07:01:27 +0000324/// toplevelentity
325/// ::= LocalVar '=' 'type' type
326bool LLParser::ParseNamedType() {
327 std::string Name = Lex.getStrVal();
328 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000329 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000330
Chris Lattner3822f632009-01-02 08:05:26 +0000331 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000332 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000333 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000334
Craig Topper2617dcc2014-04-15 06:32:26 +0000335 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000336 if (ParseStructDefinition(NameLoc, Name,
337 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000338
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000339 if (!isa<StructType>(Result)) {
340 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
341 if (Entry.first)
342 return Error(NameLoc, "non-struct types may not be recursive");
343 Entry.first = Result;
344 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000345 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000346
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000347 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000348}
349
350
351/// toplevelentity
352/// ::= 'declare' FunctionHeader
353bool LLParser::ParseDeclare() {
354 assert(Lex.getKind() == lltok::kw_declare);
355 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000356
Chris Lattnerac161bf2009-01-02 07:01:27 +0000357 Function *F;
358 return ParseFunctionHeader(F, false);
359}
360
361/// toplevelentity
362/// ::= 'define' FunctionHeader '{' ...
363bool LLParser::ParseDefine() {
364 assert(Lex.getKind() == lltok::kw_define);
365 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000366
Chris Lattnerac161bf2009-01-02 07:01:27 +0000367 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000368 return ParseFunctionHeader(F, true) ||
369 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000370}
371
Chris Lattner3822f632009-01-02 08:05:26 +0000372/// ParseGlobalType
373/// ::= 'constant'
374/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000375bool LLParser::ParseGlobalType(bool &IsConstant) {
376 if (Lex.getKind() == lltok::kw_constant)
377 IsConstant = true;
378 else if (Lex.getKind() == lltok::kw_global)
379 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000380 else {
381 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000382 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000383 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000384 Lex.Lex();
385 return false;
386}
387
Dan Gohman466876b2009-08-12 23:32:33 +0000388/// ParseUnnamedGlobal:
389/// OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000390/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
391/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000392/// GlobalID '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000393/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
394/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000395bool LLParser::ParseUnnamedGlobal() {
396 unsigned VarID = NumberedVals.size();
397 std::string Name;
398 LocTy NameLoc = Lex.getLoc();
399
400 // Handle the GlobalID form.
401 if (Lex.getKind() == lltok::GlobalID) {
402 if (Lex.getUIntVal() != VarID)
403 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000404 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000405 Lex.Lex(); // eat GlobalID;
406
407 if (ParseToken(lltok::equal, "expected '=' after name"))
408 return true;
409 }
410
411 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000412 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000413 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000414 bool UnnamedAddr;
Dan Gohman466876b2009-08-12 23:32:33 +0000415 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000416 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000417 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000418 ParseOptionalThreadLocal(TLM) ||
419 parseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000420 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000421
Rafael Espindola464fe022014-07-30 22:51:54 +0000422 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000423 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000424 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000425 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000426 UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000427}
428
Chris Lattnerac161bf2009-01-02 07:01:27 +0000429/// ParseNamedGlobal:
430/// GlobalVar '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000431/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
432/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000433bool LLParser::ParseNamedGlobal() {
434 assert(Lex.getKind() == lltok::GlobalVar);
435 LocTy NameLoc = Lex.getLoc();
436 std::string Name = Lex.getStrVal();
437 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000438
Chris Lattnerac161bf2009-01-02 07:01:27 +0000439 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000440 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000441 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000442 bool UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000443 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
444 ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000445 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000446 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000447 ParseOptionalThreadLocal(TLM) ||
448 parseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000449 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000450
Rafael Espindola464fe022014-07-30 22:51:54 +0000451 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000452 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000453 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000454
455 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000456 UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000457}
458
David Majnemerdad0a642014-06-27 18:19:56 +0000459bool LLParser::parseComdat() {
460 assert(Lex.getKind() == lltok::ComdatVar);
461 std::string Name = Lex.getStrVal();
462 LocTy NameLoc = Lex.getLoc();
463 Lex.Lex();
464
465 if (ParseToken(lltok::equal, "expected '=' here"))
466 return true;
467
468 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
469 return TokError("expected comdat type");
470
471 Comdat::SelectionKind SK;
472 switch (Lex.getKind()) {
473 default:
474 return TokError("unknown selection kind");
475 case lltok::kw_any:
476 SK = Comdat::Any;
477 break;
478 case lltok::kw_exactmatch:
479 SK = Comdat::ExactMatch;
480 break;
481 case lltok::kw_largest:
482 SK = Comdat::Largest;
483 break;
484 case lltok::kw_noduplicates:
485 SK = Comdat::NoDuplicates;
486 break;
487 case lltok::kw_samesize:
488 SK = Comdat::SameSize;
489 break;
490 }
491 Lex.Lex();
492
493 // See if the comdat was forward referenced, if so, use the comdat.
494 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
495 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
496 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
497 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
498
499 Comdat *C;
500 if (I != ComdatSymTab.end())
501 C = &I->second;
502 else
503 C = M->getOrInsertComdat(Name);
504 C->setSelectionKind(SK);
505
506 return false;
507}
508
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000509// MDString:
510// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000511bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000512 std::string Str;
513 if (ParseStringConstant(Str)) return true;
Eli Bendersky5d5e18d2014-06-25 15:41:00 +0000514 llvm::UpgradeMDStringConstant(Str);
Chris Lattner1797fc72009-12-29 21:53:55 +0000515 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000516 return false;
517}
518
519// MDNode:
520// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000521bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000522 // !{ ..., !42, ... }
523 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000524 if (ParseUInt32(MID))
525 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000526
Chris Lattner8eff0152010-04-01 05:14:45 +0000527 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000528 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000529 Result = NumberedMetadata[MID];
530 return false;
531 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000532
Chris Lattner8eff0152010-04-01 05:14:45 +0000533 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000534 auto &FwdRef = ForwardRefMDNodes[MID];
535 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), Lex.getLoc());
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000536
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000537 Result = FwdRef.first.get();
538 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000539 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000540}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000541
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000542/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000543/// !foo = !{ !1, !2 }
544bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000545 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000546 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000547 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000548
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000549 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000550 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000551 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000552 return true;
553
Dan Gohman2637cc12010-07-21 23:38:33 +0000554 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000555 if (Lex.getKind() != lltok::rbrace)
556 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000557 if (ParseToken(lltok::exclaim, "Expected '!' here"))
558 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000559
Craig Topper2617dcc2014-04-15 06:32:26 +0000560 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000561 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000562 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000563 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000564
565 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
566 return true;
567
Devang Patelbe626972009-07-29 00:34:02 +0000568 return false;
569}
570
Devang Patel39e64d42009-07-01 19:21:12 +0000571/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000572/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000573bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000574 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000575 Lex.Lex();
576 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000577
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000578 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000579 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000580 ParseToken(lltok::equal, "expected '=' here"))
581 return true;
582
583 // Detect common error, from old metadata syntax.
584 if (Lex.getKind() == lltok::Type)
585 return TokError("unexpected type in metadata definition");
586
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000587 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000588 if (Lex.getKind() == lltok::MetadataVar) {
589 if (ParseSpecializedMDNode(Init, IsDistinct))
590 return true;
591 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
592 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000593 return true;
594
Chris Lattnerfc58af22009-12-30 04:51:58 +0000595 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000596 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000597 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000598 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000599 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000600
Chris Lattnerfc58af22009-12-30 04:51:58 +0000601 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
602 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000603 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000604 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000605 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000606 }
607
Devang Patel39e64d42009-07-01 19:21:12 +0000608 return false;
609}
610
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000611static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
612 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
613 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
614}
615
Chris Lattnerac161bf2009-01-02 07:01:27 +0000616/// ParseAlias:
Rafael Espindola464fe022014-07-30 22:51:54 +0000617/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
618/// OptionalDLLStorageClass OptionalThreadLocal
619/// OptionalUnNammedAddr 'alias' Aliasee
Rafael Espindola6b238632014-05-16 19:35:39 +0000620///
Chris Lattnerac161bf2009-01-02 07:01:27 +0000621/// Aliasee
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000622/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000623///
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000624/// Everything through OptionalUnNammedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000625///
Rafael Espindola464fe022014-07-30 22:51:54 +0000626bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000627 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000628 GlobalVariable::ThreadLocalMode TLM,
629 bool UnnamedAddr) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000630 assert(Lex.getKind() == lltok::kw_alias);
631 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000632
Rafael Espindola78527052013-10-06 15:10:43 +0000633 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
634
Rafael Espindolacaa43562013-10-09 16:07:32 +0000635 if(!GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000636 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000637
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000638 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000639 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000640 "symbol with local linkage must have default visibility");
641
Rafael Espindola64c1e182014-06-03 02:41:57 +0000642 Constant *Aliasee;
643 LocTy AliaseeLoc = Lex.getLoc();
644 if (Lex.getKind() != lltok::kw_bitcast &&
645 Lex.getKind() != lltok::kw_getelementptr &&
646 Lex.getKind() != lltok::kw_addrspacecast &&
647 Lex.getKind() != lltok::kw_inttoptr) {
648 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000649 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000650 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000651 // The bitcast dest type is not present, it is implied by the dest type.
652 ValID ID;
653 if (ParseValID(ID))
654 return true;
655 if (ID.Kind != ValID::t_Constant)
656 return Error(AliaseeLoc, "invalid aliasee");
657 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000658 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000659
Rafael Espindola64c1e182014-06-03 02:41:57 +0000660 Type *AliaseeType = Aliasee->getType();
661 auto *PTy = dyn_cast<PointerType>(AliaseeType);
662 if (!PTy)
663 return Error(AliaseeLoc, "An alias must have pointer type");
664 Type *Ty = PTy->getElementType();
665 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000666
667 // Okay, create the alias but do not insert it into the module yet.
Rafael Espindola4fe00942014-05-16 13:34:04 +0000668 std::unique_ptr<GlobalAlias> GA(
Rafael Espindolaf1bedd3742014-05-17 21:29:57 +0000669 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
670 Name, Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000671 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000672 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000673 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000674 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000675
Chris Lattnerac161bf2009-01-02 07:01:27 +0000676 // See if this value already exists in the symbol table. If so, it is either
677 // a redefinition or a definition of a forward reference.
Chris Lattnere38317f2009-10-25 23:22:50 +0000678 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000679 // See if this was a redefinition. If so, there is no entry in
680 // ForwardRefVals.
681 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
682 I = ForwardRefVals.find(Name);
683 if (I == ForwardRefVals.end())
684 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
685
686 // Otherwise, this was a definition of forward ref. Verify that types
687 // agree.
688 if (Val->getType() != GA->getType())
689 return Error(NameLoc,
690 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000691
Chris Lattnerac161bf2009-01-02 07:01:27 +0000692 // If they agree, just RAUW the old value with the alias and remove the
693 // forward ref info.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000694 Val->replaceAllUsesWith(GA.get());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000695 Val->eraseFromParent();
696 ForwardRefVals.erase(I);
697 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000698
Chris Lattnerac161bf2009-01-02 07:01:27 +0000699 // Insert into the module, we know its name won't collide now.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000700 M->getAliasList().push_back(GA.get());
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000701 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000702
Rafael Espindolaaa273822014-05-09 21:49:17 +0000703 // The module owns this now
704 GA.release();
705
Chris Lattnerac161bf2009-01-02 07:01:27 +0000706 return false;
707}
708
709/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000710/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000711/// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000712/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000713/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000714/// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000715/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000716///
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000717/// Everything up to and including OptionalUnNammedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000718/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000719///
720bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
721 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000722 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000723 GlobalVariable::ThreadLocalMode TLM,
724 bool UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000725 if (!isValidVisibilityForLinkage(Visibility, Linkage))
726 return Error(NameLoc,
727 "symbol with local linkage must have default visibility");
728
Chris Lattnerac161bf2009-01-02 07:01:27 +0000729 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000730 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000731 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000732 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000733
Craig Topper2617dcc2014-04-15 06:32:26 +0000734 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000735 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000736 ParseOptionalToken(lltok::kw_externally_initialized,
737 IsExternallyInitialized,
738 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000739 ParseGlobalType(IsConstant) ||
740 ParseType(Ty, TyLoc))
741 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000742
Chris Lattnerac161bf2009-01-02 07:01:27 +0000743 // If the linkage is specified and is external, then no initializer is
744 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000745 Constant *Init = nullptr;
Nico Rieck7157bb72014-01-14 15:22:47 +0000746 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerac161bf2009-01-02 07:01:27 +0000747 Linkage != GlobalValue::ExternalLinkage)) {
748 if (ParseGlobalValue(Ty, Init))
749 return true;
750 }
751
David Majnemer49b3d9b2015-02-16 08:41:08 +0000752 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000753 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000754
David Majnemer598bd052014-12-09 05:56:09 +0000755 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000756
757 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000758 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000759 GVal = M->getNamedValue(Name);
760 if (GVal) {
Chris Lattnere38317f2009-10-25 23:22:50 +0000761 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
762 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000763 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000764 } else {
765 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
766 I = ForwardRefValIDs.find(NumberedVals.size());
767 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000768 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000769 ForwardRefValIDs.erase(I);
770 }
771 }
772
David Majnemer598bd052014-12-09 05:56:09 +0000773 GlobalVariable *GV;
774 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000775 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
776 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000777 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000778 } else {
David Majnemer598bd052014-12-09 05:56:09 +0000779 if (GVal->getType()->getElementType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000780 return Error(TyLoc,
781 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000782
David Majnemer598bd052014-12-09 05:56:09 +0000783 GV = cast<GlobalVariable>(GVal);
784
Chris Lattnerac161bf2009-01-02 07:01:27 +0000785 // Move the forward-reference to the correct spot in the module.
786 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
787 }
788
789 if (Name.empty())
790 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000791
Chris Lattnerac161bf2009-01-02 07:01:27 +0000792 // Set the parsed properties on the global.
793 if (Init)
794 GV->setInitializer(Init);
795 GV->setConstant(IsConstant);
796 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
797 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000798 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000799 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000800 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000801 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000802
Chris Lattnerac161bf2009-01-02 07:01:27 +0000803 // Parse attributes on the global.
804 while (Lex.getKind() == lltok::comma) {
805 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000806
Chris Lattnerac161bf2009-01-02 07:01:27 +0000807 if (Lex.getKind() == lltok::kw_section) {
808 Lex.Lex();
809 GV->setSection(Lex.getStrVal());
810 if (ParseToken(lltok::StringConstant, "expected global section string"))
811 return true;
812 } else if (Lex.getKind() == lltok::kw_align) {
813 unsigned Alignment;
814 if (ParseOptionalAlignment(Alignment)) return true;
815 GV->setAlignment(Alignment);
816 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000817 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000818 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000819 return true;
820 if (C)
821 GV->setComdat(C);
822 else
823 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000824 }
825 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000826
Chris Lattnerac161bf2009-01-02 07:01:27 +0000827 return false;
828}
829
Bill Wendling63b88192013-02-06 06:52:58 +0000830/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000831/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000832bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000833 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000834 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000835 Lex.Lex();
836
David Majnemerb39e22b2014-12-09 18:33:57 +0000837 if (Lex.getKind() != lltok::AttrGrpID)
838 return TokError("expected attribute group id");
839
Bill Wendling63b88192013-02-06 06:52:58 +0000840 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000841 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000842 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000843 Lex.Lex();
844
845 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000846 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000847 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000848 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000849 ParseToken(lltok::rbrace, "expected end of attribute group"))
850 return true;
851
Bill Wendlingb32b0412013-02-08 06:32:06 +0000852 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000853 return Error(AttrGrpLoc, "attribute group has no attributes");
854
855 return false;
856}
857
Bill Wendling8b0321d2013-02-08 00:52:31 +0000858/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000859/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000860bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
861 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000862 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000863 bool HaveError = false;
864
865 B.clear();
866
Bill Wendling63b88192013-02-06 06:52:58 +0000867 while (true) {
868 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000869 if (Token == lltok::kw_builtin)
870 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +0000871 switch (Token) {
872 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000873 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +0000874 return Error(Lex.getLoc(), "unterminated attribute group");
875 case lltok::rbrace:
876 // Finished.
877 return false;
878
Bill Wendlingb32b0412013-02-08 06:32:06 +0000879 case lltok::AttrGrpID: {
880 // Allow a function to reference an attribute group:
881 //
882 // define void @foo() #1 { ... }
883 if (inAttrGrp)
884 HaveError |=
885 Error(Lex.getLoc(),
886 "cannot have an attribute group reference in an attribute group");
887
888 unsigned AttrGrpNum = Lex.getUIntVal();
889 if (inAttrGrp) break;
890
891 // Save the reference to the attribute group. We'll fill it in later.
892 FwdRefAttrGrps.push_back(AttrGrpNum);
893 break;
894 }
Bill Wendling63b88192013-02-06 06:52:58 +0000895 // Target-dependent attributes:
896 case lltok::StringConstant: {
897 std::string Attr = Lex.getStrVal();
898 Lex.Lex();
899 std::string Val;
900 if (EatIfPresent(lltok::equal) &&
901 ParseStringConstant(Val))
902 return true;
903
904 B.addAttribute(Attr, Val);
Bill Wendlingb1ea9802013-02-10 10:12:50 +0000905 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000906 }
907
908 // Target-independent attributes:
909 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +0000910 // As a hack, we allow function alignment to be initially parsed as an
911 // attribute on a function declaration/definition or added to an attribute
912 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +0000913 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000914 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000915 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000916 if (ParseToken(lltok::equal, "expected '=' here") ||
917 ParseUInt32(Alignment))
918 return true;
919 } else {
920 if (ParseOptionalAlignment(Alignment))
921 return true;
922 }
Bill Wendling63b88192013-02-06 06:52:58 +0000923 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000924 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000925 }
926 case lltok::kw_alignstack: {
927 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000928 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000929 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000930 if (ParseToken(lltok::equal, "expected '=' here") ||
931 ParseUInt32(Alignment))
932 return true;
933 } else {
934 if (ParseOptionalStackAlignment(Alignment))
935 return true;
936 }
Bill Wendling63b88192013-02-06 06:52:58 +0000937 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000938 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000939 }
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000940 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
Michael Gottesman41748d72013-06-27 00:25:01 +0000941 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
Diego Novilloc6399532013-05-24 12:26:52 +0000942 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000943 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
Tom Roeder44cb65f2014-06-05 19:29:43 +0000944 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000945 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
946 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
947 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
948 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
949 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
950 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
951 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
952 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
953 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
954 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
Andrea Di Biagio377496b2013-08-23 11:53:55 +0000955 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000956 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
957 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
958 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
959 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
960 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
961 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
962 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
963 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
964 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
965 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
966 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000967
968 // Error handling.
969 case lltok::kw_inreg:
970 case lltok::kw_signext:
971 case lltok::kw_zeroext:
972 HaveError |=
973 Error(Lex.getLoc(),
974 "invalid use of attribute on a function");
975 break;
976 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +0000977 case lltok::kw_dereferenceable:
Reid Klecknera534a382013-12-19 02:14:12 +0000978 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000979 case lltok::kw_nest:
980 case lltok::kw_noalias:
981 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +0000982 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +0000983 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000984 case lltok::kw_sret:
985 HaveError |=
986 Error(Lex.getLoc(),
987 "invalid use of parameter-only attribute on a function");
988 break;
Bill Wendling63b88192013-02-06 06:52:58 +0000989 }
990
991 Lex.Lex();
992 }
993}
Chris Lattnerac161bf2009-01-02 07:01:27 +0000994
995//===----------------------------------------------------------------------===//
996// GlobalValue Reference/Resolution Routines.
997//===----------------------------------------------------------------------===//
998
999/// GetGlobalVal - Get a value with the specified name or ID, creating a
1000/// forward reference record if needed. This can return null if the value
1001/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001002GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001003 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001004 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001005 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001006 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001007 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001008 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001009
Chris Lattnerac161bf2009-01-02 07:01:27 +00001010 // Look this name up in the normal function symbol table.
1011 GlobalValue *Val =
1012 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001013
Chris Lattnerac161bf2009-01-02 07:01:27 +00001014 // If this is a forward reference for the value, see if we already created a
1015 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001016 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001017 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1018 I = ForwardRefVals.find(Name);
1019 if (I != ForwardRefVals.end())
1020 Val = I->second.first;
1021 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001022
Chris Lattnerac161bf2009-01-02 07:01:27 +00001023 // If we have the value in the symbol table or fwd-ref table, return it.
1024 if (Val) {
1025 if (Val->getType() == Ty) return Val;
1026 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001027 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001028 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001029 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001030
Chris Lattnerac161bf2009-01-02 07:01:27 +00001031 // Otherwise, create a new forward reference for this value and remember it.
1032 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001033 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001034 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001035 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001036 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Craig Topper2617dcc2014-04-15 06:32:26 +00001037 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1038 nullptr, GlobalVariable::NotThreadLocal,
Justin Holewinski898a0a02012-11-16 21:03:47 +00001039 PTy->getAddressSpace());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001040
Chris Lattnerac161bf2009-01-02 07:01:27 +00001041 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1042 return FwdVal;
1043}
1044
Chris Lattner229907c2011-07-18 04:54:35 +00001045GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1046 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001047 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001048 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001049 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001050 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001051
Craig Topper2617dcc2014-04-15 06:32:26 +00001052 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001053
Chris Lattnerac161bf2009-01-02 07:01:27 +00001054 // If this is a forward reference for the value, see if we already created a
1055 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001056 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001057 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1058 I = ForwardRefValIDs.find(ID);
1059 if (I != ForwardRefValIDs.end())
1060 Val = I->second.first;
1061 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001062
Chris Lattnerac161bf2009-01-02 07:01:27 +00001063 // If we have the value in the symbol table or fwd-ref table, return it.
1064 if (Val) {
1065 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001066 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001067 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001068 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001069 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001070
Chris Lattnerac161bf2009-01-02 07:01:27 +00001071 // Otherwise, create a new forward reference for this value and remember it.
1072 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001073 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001074 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001075 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001076 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Craig Topper2617dcc2014-04-15 06:32:26 +00001077 GlobalValue::ExternalWeakLinkage, nullptr, "");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001078
Chris Lattnerac161bf2009-01-02 07:01:27 +00001079 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1080 return FwdVal;
1081}
1082
1083
1084//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001085// Comdat Reference/Resolution Routines.
1086//===----------------------------------------------------------------------===//
1087
1088Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1089 // Look this name up in the comdat symbol table.
1090 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1091 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1092 if (I != ComdatSymTab.end())
1093 return &I->second;
1094
1095 // Otherwise, create a new forward reference for this value and remember it.
1096 Comdat *C = M->getOrInsertComdat(Name);
1097 ForwardRefComdats[Name] = Loc;
1098 return C;
1099}
1100
1101
1102//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001103// Helper Routines.
1104//===----------------------------------------------------------------------===//
1105
1106/// ParseToken - If the current token has the specified kind, eat it and return
1107/// success. Otherwise, emit the specified error and return failure.
1108bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1109 if (Lex.getKind() != T)
1110 return TokError(ErrMsg);
1111 Lex.Lex();
1112 return false;
1113}
1114
Chris Lattner3822f632009-01-02 08:05:26 +00001115/// ParseStringConstant
1116/// ::= StringConstant
1117bool LLParser::ParseStringConstant(std::string &Result) {
1118 if (Lex.getKind() != lltok::StringConstant)
1119 return TokError("expected string constant");
1120 Result = Lex.getStrVal();
1121 Lex.Lex();
1122 return false;
1123}
1124
1125/// ParseUInt32
1126/// ::= uint32
1127bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001128 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1129 return TokError("expected integer");
1130 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1131 if (Val64 != unsigned(Val64))
1132 return TokError("expected 32-bit integer (too large)");
1133 Val = Val64;
1134 Lex.Lex();
1135 return false;
1136}
1137
Hal Finkelb0407ba2014-07-18 15:51:28 +00001138/// ParseUInt64
1139/// ::= uint64
1140bool LLParser::ParseUInt64(uint64_t &Val) {
1141 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1142 return TokError("expected integer");
1143 Val = Lex.getAPSIntVal().getLimitedValue();
1144 Lex.Lex();
1145 return false;
1146}
1147
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001148/// ParseTLSModel
1149/// := 'localdynamic'
1150/// := 'initialexec'
1151/// := 'localexec'
1152bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1153 switch (Lex.getKind()) {
1154 default:
1155 return TokError("expected localdynamic, initialexec or localexec");
1156 case lltok::kw_localdynamic:
1157 TLM = GlobalVariable::LocalDynamicTLSModel;
1158 break;
1159 case lltok::kw_initialexec:
1160 TLM = GlobalVariable::InitialExecTLSModel;
1161 break;
1162 case lltok::kw_localexec:
1163 TLM = GlobalVariable::LocalExecTLSModel;
1164 break;
1165 }
1166
1167 Lex.Lex();
1168 return false;
1169}
1170
1171/// ParseOptionalThreadLocal
1172/// := /*empty*/
1173/// := 'thread_local'
1174/// := 'thread_local' '(' tlsmodel ')'
1175bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1176 TLM = GlobalVariable::NotThreadLocal;
1177 if (!EatIfPresent(lltok::kw_thread_local))
1178 return false;
1179
1180 TLM = GlobalVariable::GeneralDynamicTLSModel;
1181 if (Lex.getKind() == lltok::lparen) {
1182 Lex.Lex();
1183 return ParseTLSModel(TLM) ||
1184 ParseToken(lltok::rparen, "expected ')' after thread local model");
1185 }
1186 return false;
1187}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001188
1189/// ParseOptionalAddrSpace
1190/// := /*empty*/
1191/// := 'addrspace' '(' uint32 ')'
1192bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1193 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001194 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001195 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001196 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001197 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001198 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001199}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001200
Bill Wendling34c2eb22012-12-04 23:40:58 +00001201/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1202bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1203 bool HaveError = false;
1204
1205 B.clear();
1206
1207 while (1) {
1208 lltok::Kind Token = Lex.getKind();
1209 switch (Token) {
1210 default: // End of attributes.
1211 return HaveError;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001212 case lltok::kw_align: {
1213 unsigned Alignment;
1214 if (ParseOptionalAlignment(Alignment))
1215 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001216 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001217 continue;
1218 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001219 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001220 case lltok::kw_dereferenceable: {
1221 uint64_t Bytes;
1222 if (ParseOptionalDereferenceableBytes(Bytes))
1223 return true;
1224 B.addDereferenceableAttr(Bytes);
1225 continue;
1226 }
Reid Klecknera534a382013-12-19 02:14:12 +00001227 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001228 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1229 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1230 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1231 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001232 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001233 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1234 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001235 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001236 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1237 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1238 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001239
Stephen Lin7577ed52013-04-20 13:16:13 +00001240 case lltok::kw_alignstack:
1241 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001242 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001243 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001244 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001245 case lltok::kw_minsize:
1246 case lltok::kw_naked:
1247 case lltok::kw_nobuiltin:
1248 case lltok::kw_noduplicate:
1249 case lltok::kw_noimplicitfloat:
1250 case lltok::kw_noinline:
1251 case lltok::kw_nonlazybind:
1252 case lltok::kw_noredzone:
1253 case lltok::kw_noreturn:
1254 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001255 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001256 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001257 case lltok::kw_returns_twice:
1258 case lltok::kw_sanitize_address:
1259 case lltok::kw_sanitize_memory:
1260 case lltok::kw_sanitize_thread:
1261 case lltok::kw_ssp:
1262 case lltok::kw_sspreq:
1263 case lltok::kw_sspstrong:
1264 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001265 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1266 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001267 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001268
Bill Wendling34c2eb22012-12-04 23:40:58 +00001269 Lex.Lex();
1270 }
1271}
1272
1273/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1274bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1275 bool HaveError = false;
1276
1277 B.clear();
1278
1279 while (1) {
1280 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001281 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001282 default: // End of attributes.
1283 return HaveError;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001284 case lltok::kw_dereferenceable: {
1285 uint64_t Bytes;
1286 if (ParseOptionalDereferenceableBytes(Bytes))
1287 return true;
1288 B.addDereferenceableAttr(Bytes);
1289 continue;
1290 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001291 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1292 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001293 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001294 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1295 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001296
Bill Wendling34c2eb22012-12-04 23:40:58 +00001297 // Error handling.
Stephen Lin7577ed52013-04-20 13:16:13 +00001298 case lltok::kw_align:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001299 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001300 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001301 case lltok::kw_nest:
1302 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001303 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001304 case lltok::kw_sret:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001305 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001306 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001307
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001308 case lltok::kw_alignstack:
1309 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001310 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001311 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001312 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001313 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001314 case lltok::kw_minsize:
1315 case lltok::kw_naked:
1316 case lltok::kw_nobuiltin:
1317 case lltok::kw_noduplicate:
1318 case lltok::kw_noimplicitfloat:
1319 case lltok::kw_noinline:
1320 case lltok::kw_nonlazybind:
1321 case lltok::kw_noredzone:
1322 case lltok::kw_noreturn:
1323 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001324 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001325 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001326 case lltok::kw_returns_twice:
1327 case lltok::kw_sanitize_address:
1328 case lltok::kw_sanitize_memory:
1329 case lltok::kw_sanitize_thread:
1330 case lltok::kw_ssp:
1331 case lltok::kw_sspreq:
1332 case lltok::kw_sspstrong:
1333 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001334 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001335 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001336
1337 case lltok::kw_readnone:
1338 case lltok::kw_readonly:
1339 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001340 }
1341
Chris Lattnerac161bf2009-01-02 07:01:27 +00001342 Lex.Lex();
1343 }
1344}
1345
1346/// ParseOptionalLinkage
1347/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001348/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001349/// ::= 'internal'
1350/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001351/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001352/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001353/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001354/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001355/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001356/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001357/// ::= 'extern_weak'
1358/// ::= 'external'
1359bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1360 HasLinkage = false;
1361 switch (Lex.getKind()) {
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001362 default: Res=GlobalValue::ExternalLinkage; return false;
1363 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001364 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1365 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1366 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1367 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1368 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner184f1be2009-04-13 05:44:34 +00001369 case lltok::kw_available_externally:
1370 Res = GlobalValue::AvailableExternallyLinkage;
1371 break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001372 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001373 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001374 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1375 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001376 }
1377 Lex.Lex();
1378 HasLinkage = true;
1379 return false;
1380}
1381
1382/// ParseOptionalVisibility
1383/// ::= /*empty*/
1384/// ::= 'default'
1385/// ::= 'hidden'
1386/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001387///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001388bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1389 switch (Lex.getKind()) {
1390 default: Res = GlobalValue::DefaultVisibility; return false;
1391 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1392 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1393 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1394 }
1395 Lex.Lex();
1396 return false;
1397}
1398
Nico Rieck7157bb72014-01-14 15:22:47 +00001399/// ParseOptionalDLLStorageClass
1400/// ::= /*empty*/
1401/// ::= 'dllimport'
1402/// ::= 'dllexport'
1403///
1404bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1405 switch (Lex.getKind()) {
1406 default: Res = GlobalValue::DefaultStorageClass; return false;
1407 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1408 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1409 }
1410 Lex.Lex();
1411 return false;
1412}
1413
Chris Lattnerac161bf2009-01-02 07:01:27 +00001414/// ParseOptionalCallingConv
1415/// ::= /*empty*/
1416/// ::= 'ccc'
1417/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001418/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001419/// ::= 'coldcc'
1420/// ::= 'x86_stdcallcc'
1421/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001422/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001423/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001424/// ::= 'arm_apcscc'
1425/// ::= 'arm_aapcscc'
1426/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001427/// ::= 'msp430_intrcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001428/// ::= 'ptx_kernel'
1429/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001430/// ::= 'spir_func'
1431/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001432/// ::= 'x86_64_sysvcc'
1433/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001434/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001435/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001436/// ::= 'preserve_mostcc'
1437/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001438/// ::= 'ghccc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001439/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001440///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001441bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001442 switch (Lex.getKind()) {
1443 default: CC = CallingConv::C; return false;
1444 case lltok::kw_ccc: CC = CallingConv::C; break;
1445 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1446 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1447 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1448 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001449 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001450 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001451 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1452 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1453 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001454 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001455 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1456 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001457 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1458 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001459 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001460 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1461 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001462 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001463 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001464 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1465 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001466 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001467 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001468 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001469 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001470 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001471 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001472
Chris Lattnerac161bf2009-01-02 07:01:27 +00001473 Lex.Lex();
1474 return false;
1475}
1476
Chris Lattner5c427632009-12-30 05:31:19 +00001477/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001478/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman338d9a42010-08-24 02:05:17 +00001479bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1480 PerFunctionState *PFS) {
Chris Lattner5c427632009-12-30 05:31:19 +00001481 do {
1482 if (Lex.getKind() != lltok::MetadataVar)
1483 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001484
Chris Lattner596760d2009-12-29 21:25:40 +00001485 std::string Name = Lex.getStrVal();
Benjamin Kramerb3bd0192011-12-06 11:50:26 +00001486 unsigned MDK = M->getMDKindID(Name);
Chris Lattner596760d2009-12-29 21:25:40 +00001487 Lex.Lex();
Chris Lattner8d58f2f2009-10-19 05:31:10 +00001488
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001489 MDNode *N;
1490 if (ParseMDNode(N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001491 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001492
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001493 Inst->setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001494 if (MDK == LLVMContext::MD_tbaa)
1495 InstsWithTBAATag.push_back(Inst);
1496
Chris Lattner596760d2009-12-29 21:25:40 +00001497 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001498 } while (EatIfPresent(lltok::comma));
1499 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001500}
1501
Chris Lattnerac161bf2009-01-02 07:01:27 +00001502/// ParseOptionalAlignment
1503/// ::= /* empty */
1504/// ::= 'align' 4
1505bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1506 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001507 if (!EatIfPresent(lltok::kw_align))
1508 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001509 LocTy AlignLoc = Lex.getLoc();
1510 if (ParseUInt32(Alignment)) return true;
1511 if (!isPowerOf2_32(Alignment))
1512 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001513 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001514 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001515 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001516}
1517
Hal Finkelb0407ba2014-07-18 15:51:28 +00001518/// ParseOptionalDereferenceableBytes
1519/// ::= /* empty */
1520/// ::= 'dereferenceable' '(' 4 ')'
1521bool LLParser::ParseOptionalDereferenceableBytes(uint64_t &Bytes) {
1522 Bytes = 0;
1523 if (!EatIfPresent(lltok::kw_dereferenceable))
1524 return false;
1525 LocTy ParenLoc = Lex.getLoc();
1526 if (!EatIfPresent(lltok::lparen))
1527 return Error(ParenLoc, "expected '('");
1528 LocTy DerefLoc = Lex.getLoc();
1529 if (ParseUInt64(Bytes)) return true;
1530 ParenLoc = Lex.getLoc();
1531 if (!EatIfPresent(lltok::rparen))
1532 return Error(ParenLoc, "expected ')'");
1533 if (!Bytes)
1534 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1535 return false;
1536}
1537
Chris Lattnerb2f39502009-12-30 05:44:30 +00001538/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001539/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001540/// ::= ',' align 4
1541///
1542/// This returns with AteExtraComma set to true if it ate an excess comma at the
1543/// end.
1544bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1545 bool &AteExtraComma) {
1546 AteExtraComma = false;
1547 while (EatIfPresent(lltok::comma)) {
1548 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001549 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001550 AteExtraComma = true;
1551 return false;
1552 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001553
Chris Lattner95b0ff42010-04-23 00:50:50 +00001554 if (Lex.getKind() != lltok::kw_align)
1555 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001556
Chris Lattner95b0ff42010-04-23 00:50:50 +00001557 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001558 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001559
Devang Patelea8a4b92009-09-17 23:04:48 +00001560 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001561}
1562
Eli Friedmanfee02c62011-07-25 23:16:38 +00001563/// ParseScopeAndOrdering
1564/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1565/// else: ::=
1566///
1567/// This sets Scope and Ordering to the parsed values.
1568bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1569 AtomicOrdering &Ordering) {
1570 if (!isAtomic)
1571 return false;
1572
1573 Scope = CrossThread;
1574 if (EatIfPresent(lltok::kw_singlethread))
1575 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001576
1577 return ParseOrdering(Ordering);
1578}
1579
1580/// ParseOrdering
1581/// ::= AtomicOrdering
1582///
1583/// This sets Ordering to the parsed value.
1584bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001585 switch (Lex.getKind()) {
1586 default: return TokError("Expected ordering on atomic instruction");
1587 case lltok::kw_unordered: Ordering = Unordered; break;
1588 case lltok::kw_monotonic: Ordering = Monotonic; break;
1589 case lltok::kw_acquire: Ordering = Acquire; break;
1590 case lltok::kw_release: Ordering = Release; break;
1591 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1592 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1593 }
1594 Lex.Lex();
1595 return false;
1596}
1597
Charles Davisbe5557e2010-02-12 00:31:15 +00001598/// ParseOptionalStackAlignment
1599/// ::= /* empty */
1600/// ::= 'alignstack' '(' 4 ')'
1601bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1602 Alignment = 0;
1603 if (!EatIfPresent(lltok::kw_alignstack))
1604 return false;
1605 LocTy ParenLoc = Lex.getLoc();
1606 if (!EatIfPresent(lltok::lparen))
1607 return Error(ParenLoc, "expected '('");
1608 LocTy AlignLoc = Lex.getLoc();
1609 if (ParseUInt32(Alignment)) return true;
1610 ParenLoc = Lex.getLoc();
1611 if (!EatIfPresent(lltok::rparen))
1612 return Error(ParenLoc, "expected ')'");
1613 if (!isPowerOf2_32(Alignment))
1614 return Error(AlignLoc, "stack alignment is not a power of two");
1615 return false;
1616}
Devang Patelea8a4b92009-09-17 23:04:48 +00001617
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001618/// ParseIndexList - This parses the index list for an insert/extractvalue
1619/// instruction. This sets AteExtraComma in the case where we eat an extra
1620/// comma at the end of the line and find that it is followed by metadata.
1621/// Clients that don't allow metadata can call the version of this function that
1622/// only takes one argument.
1623///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001624/// ParseIndexList
1625/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001626///
1627bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1628 bool &AteExtraComma) {
1629 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001630
Chris Lattnerac161bf2009-01-02 07:01:27 +00001631 if (Lex.getKind() != lltok::comma)
1632 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001633
Chris Lattner3822f632009-01-02 08:05:26 +00001634 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001635 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00001636 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001637 AteExtraComma = true;
1638 return false;
1639 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001640 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001641 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001642 Indices.push_back(Idx);
1643 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001644
Chris Lattnerac161bf2009-01-02 07:01:27 +00001645 return false;
1646}
1647
1648//===----------------------------------------------------------------------===//
1649// Type Parsing.
1650//===----------------------------------------------------------------------===//
1651
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001652/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001653bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001654 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001655 switch (Lex.getKind()) {
1656 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001657 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001658 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001659 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001660 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001661 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001662 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001663 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001664 // Type ::= StructType
1665 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001666 return true;
1667 break;
1668 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001669 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001670 Lex.Lex(); // eat the lsquare.
1671 if (ParseArrayVectorType(Result, false))
1672 return true;
1673 break;
1674 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001675 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00001676 Lex.Lex();
1677 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001678 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00001679 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001680 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001681 } else if (ParseArrayVectorType(Result, true))
1682 return true;
1683 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001684 case lltok::LocalVar: {
1685 // Type ::= %foo
1686 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001687
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001688 // If the type hasn't been defined yet, create a forward definition and
1689 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001690 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001691 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001692 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001693 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001694 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001695 Lex.Lex();
1696 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001697 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001698
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001699 case lltok::LocalVarID: {
1700 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001701 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001702
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001703 // If the type hasn't been defined yet, create a forward definition and
1704 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001705 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001706 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001707 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001708 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001709 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001710 Lex.Lex();
1711 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001712 }
1713 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001714
1715 // Parse the type suffixes.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001716 while (1) {
1717 switch (Lex.getKind()) {
1718 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001719 default:
1720 if (!AllowVoid && Result->isVoidTy())
1721 return Error(TypeLoc, "void type only allowed for function results");
1722 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001723
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001724 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001725 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001726 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001727 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001728 if (Result->isVoidTy())
1729 return TokError("pointers to void are invalid - use i8* instead");
1730 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001731 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001732 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001733 Lex.Lex();
1734 break;
1735
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001736 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001737 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001738 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001739 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001740 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00001741 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001742 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001743 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001744 unsigned AddrSpace;
1745 if (ParseOptionalAddrSpace(AddrSpace) ||
1746 ParseToken(lltok::star, "expected '*' in address space"))
1747 return true;
1748
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001749 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001750 break;
1751 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001752
Chris Lattnerac161bf2009-01-02 07:01:27 +00001753 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1754 case lltok::lparen:
1755 if (ParseFunctionType(Result))
1756 return true;
1757 break;
1758 }
1759 }
1760}
1761
1762/// ParseParameterList
1763/// ::= '(' ')'
1764/// ::= '(' Arg (',' Arg)* ')'
1765/// Arg
1766/// ::= Type OptionalAttributes Value OptionalAttributes
1767bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00001768 PerFunctionState &PFS, bool IsMustTailCall,
1769 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001770 if (ParseToken(lltok::lparen, "expected '(' in call"))
1771 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001772
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001773 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001774 while (Lex.getKind() != lltok::rparen) {
1775 // If this isn't the first argument, we need a comma.
1776 if (!ArgList.empty() &&
1777 ParseToken(lltok::comma, "expected ',' in argument list"))
1778 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001779
Reid Kleckner83498642014-08-26 00:33:28 +00001780 // Parse an ellipsis if this is a musttail call in a variadic function.
1781 if (Lex.getKind() == lltok::dotdotdot) {
1782 const char *Msg = "unexpected ellipsis in argument list for ";
1783 if (!IsMustTailCall)
1784 return TokError(Twine(Msg) + "non-musttail call");
1785 if (!InVarArgsFunc)
1786 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1787 Lex.Lex(); // Lex the '...', it is purely for readability.
1788 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1789 }
1790
Chris Lattnerac161bf2009-01-02 07:01:27 +00001791 // Parse the argument.
1792 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00001793 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001794 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001795 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00001796 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001797 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00001798
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001799 if (ArgTy->isMetadataTy()) {
1800 if (ParseMetadataAsValue(V, PFS))
1801 return true;
1802 } else {
1803 // Otherwise, handle normal operands.
1804 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1805 return true;
1806 }
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001807 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1808 AttrIndex++,
1809 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001810 }
1811
Reid Kleckner83498642014-08-26 00:33:28 +00001812 if (IsMustTailCall && InVarArgsFunc)
1813 return TokError("expected '...' at end of argument list for musttail call "
1814 "in varargs function");
1815
Chris Lattnerac161bf2009-01-02 07:01:27 +00001816 Lex.Lex(); // Lex the ')'.
1817 return false;
1818}
1819
1820
1821
Chris Lattner2ed06b42009-01-05 18:34:07 +00001822/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001823/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001824/// ::= '(' ArgTypeListI ')'
1825/// ArgTypeListI
1826/// ::= /*empty*/
1827/// ::= '...'
1828/// ::= ArgTypeList ',' '...'
1829/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00001830///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001831bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1832 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00001833 isVarArg = false;
1834 assert(Lex.getKind() == lltok::lparen);
1835 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001836
Chris Lattnerac161bf2009-01-02 07:01:27 +00001837 if (Lex.getKind() == lltok::rparen) {
1838 // empty
1839 } else if (Lex.getKind() == lltok::dotdotdot) {
1840 isVarArg = true;
1841 Lex.Lex();
1842 } else {
1843 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00001844 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001845 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001846 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001847
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001848 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00001849 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001850
Chris Lattnerfdd87902009-10-05 05:54:46 +00001851 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001852 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001853
Chris Lattnerdef19492011-06-17 06:36:20 +00001854 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001855 Name = Lex.getStrVal();
1856 Lex.Lex();
1857 }
Chris Lattner3822f632009-01-02 08:05:26 +00001858
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001859 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00001860 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001861
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001862 unsigned AttrIndex = 1;
Bill Wendlingd079a442012-10-15 04:46:55 +00001863 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001864 AttributeSet::get(ArgTy->getContext(),
1865 AttrIndex++, Attrs), Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001866
Chris Lattner3822f632009-01-02 08:05:26 +00001867 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001868 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00001869 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001870 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001871 break;
1872 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001873
Chris Lattnerac161bf2009-01-02 07:01:27 +00001874 // Otherwise must be an argument type.
1875 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00001876 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00001877
Chris Lattnerfdd87902009-10-05 05:54:46 +00001878 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001879 return Error(TypeLoc, "argument can not have void type");
1880
Chris Lattnerdef19492011-06-17 06:36:20 +00001881 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001882 Name = Lex.getStrVal();
1883 Lex.Lex();
1884 } else {
1885 Name = "";
1886 }
Chris Lattner3822f632009-01-02 08:05:26 +00001887
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001888 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00001889 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001890
Bill Wendlingd079a442012-10-15 04:46:55 +00001891 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001892 AttributeSet::get(ArgTy->getContext(),
1893 AttrIndex++, Attrs),
Bill Wendlingd079a442012-10-15 04:46:55 +00001894 Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001895 }
1896 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001897
Chris Lattner3822f632009-01-02 08:05:26 +00001898 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001899}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001900
Chris Lattnerac161bf2009-01-02 07:01:27 +00001901/// ParseFunctionType
1902/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001903bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001904 assert(Lex.getKind() == lltok::lparen);
1905
Chris Lattnerce473c72009-01-05 08:04:33 +00001906 if (!FunctionType::isValidReturnType(Result))
1907 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001908
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001909 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001910 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001911 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001912 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001913
Chris Lattnerac161bf2009-01-02 07:01:27 +00001914 // Reject names on the arguments lists.
1915 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1916 if (!ArgList[i].Name.empty())
1917 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001918 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00001919 return Error(ArgList[i].Loc,
1920 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001921 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001922
Jay Foadb804a2b2011-07-12 14:06:48 +00001923 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001924 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001925 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001926
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001927 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001928 return false;
1929}
1930
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001931/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1932/// other structs.
1933bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1934 SmallVector<Type*, 8> Elts;
1935 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001936
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001937 Result = StructType::get(Context, Elts, Packed);
1938 return false;
1939}
1940
1941/// ParseStructDefinition - Parse a struct in a 'type' definition.
1942bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1943 std::pair<Type*, LocTy> &Entry,
1944 Type *&ResultTy) {
1945 // If the type was already defined, diagnose the redefinition.
1946 if (Entry.first && !Entry.second.isValid())
1947 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001948
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001949 // If we have opaque, just return without filling in the definition for the
1950 // struct. This counts as a definition as far as the .ll file goes.
1951 if (EatIfPresent(lltok::kw_opaque)) {
1952 // This type is being defined, so clear the location to indicate this.
1953 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001954
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001955 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00001956 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00001957 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001958 ResultTy = Entry.first;
1959 return false;
1960 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001961
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001962 // If the type starts with '<', then it is either a packed struct or a vector.
1963 bool isPacked = EatIfPresent(lltok::less);
1964
1965 // If we don't have a struct, then we have a random type alias, which we
1966 // accept for compatibility with old files. These types are not allowed to be
1967 // forward referenced and not allowed to be recursive.
1968 if (Lex.getKind() != lltok::lbrace) {
1969 if (Entry.first)
1970 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001971
Craig Topper2617dcc2014-04-15 06:32:26 +00001972 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001973 if (isPacked)
1974 return ParseArrayVectorType(ResultTy, true);
1975 return ParseType(ResultTy);
1976 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001977
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001978 // This type is being defined, so clear the location to indicate this.
1979 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001980
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001981 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00001982 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00001983 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001984
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001985 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001986
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001987 SmallVector<Type*, 8> Body;
1988 if (ParseStructBody(Body) ||
1989 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1990 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001991
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001992 STy->setBody(Body, isPacked);
1993 ResultTy = STy;
1994 return false;
1995}
1996
1997
Chris Lattnerac161bf2009-01-02 07:01:27 +00001998/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001999/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002000/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002001/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002002/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002003/// ::= '<' '{' Type (',' Type)* '}' '>'
2004bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002005 assert(Lex.getKind() == lltok::lbrace);
2006 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002007
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002008 // Handle the empty struct.
2009 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002010 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002011
Chris Lattnerf880ca22009-03-09 04:49:14 +00002012 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002013 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002014 if (ParseType(Ty)) return true;
2015 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002016
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002017 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002018 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002019
Chris Lattner3822f632009-01-02 08:05:26 +00002020 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002021 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002022 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002023
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002024 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002025 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002026
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002027 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002028 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002029
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002030 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002031}
2032
2033/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2034/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002035/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002036/// ::= '[' APSINTVAL 'x' Types ']'
2037/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002038bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002039 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2040 Lex.getAPSIntVal().getBitWidth() > 64)
2041 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002042
Chris Lattnerac161bf2009-01-02 07:01:27 +00002043 LocTy SizeLoc = Lex.getLoc();
2044 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002045 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002046
Chris Lattner3822f632009-01-02 08:05:26 +00002047 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2048 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002049
2050 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002051 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002052 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002053
Chris Lattner3822f632009-01-02 08:05:26 +00002054 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2055 "expected end of sequential type"))
2056 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002057
Chris Lattnerac161bf2009-01-02 07:01:27 +00002058 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002059 if (Size == 0)
2060 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002061 if ((unsigned)Size != Size)
2062 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002063 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002064 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002065 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002066 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002067 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002068 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002069 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002070 }
2071 return false;
2072}
2073
2074//===----------------------------------------------------------------------===//
2075// Function Semantic Analysis.
2076//===----------------------------------------------------------------------===//
2077
Chris Lattner3432c622009-10-28 03:39:23 +00002078LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2079 int functionNumber)
2080 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002081
2082 // Insert unnamed arguments into the NumberedVals list.
2083 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2084 AI != E; ++AI)
2085 if (!AI->hasName())
2086 NumberedVals.push_back(AI);
2087}
2088
2089LLParser::PerFunctionState::~PerFunctionState() {
2090 // If there were any forward referenced non-basicblock values, delete them.
2091 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2092 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2093 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002094 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002095 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002096 delete I->second.first;
Craig Topper2617dcc2014-04-15 06:32:26 +00002097 I->second.first = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002098 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002099
Chris Lattnerac161bf2009-01-02 07:01:27 +00002100 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2101 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2102 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002103 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002104 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002105 delete I->second.first;
Craig Topper2617dcc2014-04-15 06:32:26 +00002106 I->second.first = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002107 }
2108}
2109
Chris Lattner3432c622009-10-28 03:39:23 +00002110bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002111 if (!ForwardRefVals.empty())
2112 return P.Error(ForwardRefVals.begin()->second.second,
2113 "use of undefined value '%" + ForwardRefVals.begin()->first +
2114 "'");
2115 if (!ForwardRefValIDs.empty())
2116 return P.Error(ForwardRefValIDs.begin()->second.second,
2117 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002118 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002119 return false;
2120}
2121
2122
2123/// GetVal - Get a value with the specified name or ID, creating a
2124/// forward reference record if needed. This can return null if the value
2125/// exists but does not have the right type.
2126Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
Chris Lattner229907c2011-07-18 04:54:35 +00002127 Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002128 // Look this name up in the normal function symbol table.
2129 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002130
Chris Lattnerac161bf2009-01-02 07:01:27 +00002131 // If this is a forward reference for the value, see if we already created a
2132 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002133 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002134 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2135 I = ForwardRefVals.find(Name);
2136 if (I != ForwardRefVals.end())
2137 Val = I->second.first;
2138 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002139
Chris Lattnerac161bf2009-01-02 07:01:27 +00002140 // If we have the value in the symbol table or fwd-ref table, return it.
2141 if (Val) {
2142 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002143 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002144 P.Error(Loc, "'%" + Name + "' is not a basic block");
2145 else
2146 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002147 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002148 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002149 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002150
Chris Lattnerac161bf2009-01-02 07:01:27 +00002151 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002152 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002153 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002154 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002155 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002156
Chris Lattnerac161bf2009-01-02 07:01:27 +00002157 // Otherwise, create a new forward reference for this value and remember it.
2158 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002159 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002160 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002161 else
2162 FwdVal = new Argument(Ty, Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002163
Chris Lattnerac161bf2009-01-02 07:01:27 +00002164 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2165 return FwdVal;
2166}
2167
Chris Lattner229907c2011-07-18 04:54:35 +00002168Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00002169 LocTy Loc) {
2170 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002171 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002172
Chris Lattnerac161bf2009-01-02 07:01:27 +00002173 // If this is a forward reference for the value, see if we already created a
2174 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002175 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002176 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2177 I = ForwardRefValIDs.find(ID);
2178 if (I != ForwardRefValIDs.end())
2179 Val = I->second.first;
2180 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002181
Chris Lattnerac161bf2009-01-02 07:01:27 +00002182 // If we have the value in the symbol table or fwd-ref table, return it.
2183 if (Val) {
2184 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002185 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002186 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002187 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002188 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002189 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002190 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002191 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002192
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002193 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002194 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002195 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002196 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002197
Chris Lattnerac161bf2009-01-02 07:01:27 +00002198 // Otherwise, create a new forward reference for this value and remember it.
2199 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002200 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002201 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002202 else
2203 FwdVal = new Argument(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002204
Chris Lattnerac161bf2009-01-02 07:01:27 +00002205 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2206 return FwdVal;
2207}
2208
2209/// SetInstName - After an instruction is parsed and inserted into its
2210/// basic block, this installs its name.
2211bool LLParser::PerFunctionState::SetInstName(int NameID,
2212 const std::string &NameStr,
2213 LocTy NameLoc, Instruction *Inst) {
2214 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002215 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002216 if (NameID != -1 || !NameStr.empty())
2217 return P.Error(NameLoc, "instructions returning void cannot have a name");
2218 return false;
2219 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002220
Chris Lattnerac161bf2009-01-02 07:01:27 +00002221 // If this was a numbered instruction, verify that the instruction is the
2222 // expected value and resolve any forward references.
2223 if (NameStr.empty()) {
2224 // If neither a name nor an ID was specified, just use the next ID.
2225 if (NameID == -1)
2226 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002227
Chris Lattnerac161bf2009-01-02 07:01:27 +00002228 if (unsigned(NameID) != NumberedVals.size())
2229 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002230 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002231
Chris Lattnerac161bf2009-01-02 07:01:27 +00002232 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2233 ForwardRefValIDs.find(NameID);
2234 if (FI != ForwardRefValIDs.end()) {
2235 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002236 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002237 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002238 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2baa6a32009-09-02 15:02:57 +00002239 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002240 ForwardRefValIDs.erase(FI);
2241 }
2242
2243 NumberedVals.push_back(Inst);
2244 return false;
2245 }
2246
2247 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2248 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2249 FI = ForwardRefVals.find(NameStr);
2250 if (FI != ForwardRefVals.end()) {
2251 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002252 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002253 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002254 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2fcee702009-09-02 14:22:03 +00002255 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002256 ForwardRefVals.erase(FI);
2257 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002258
Chris Lattnerac161bf2009-01-02 07:01:27 +00002259 // Set the name on the instruction.
2260 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002261
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002262 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002263 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002264 NameStr + "'");
2265 return false;
2266}
2267
2268/// GetBB - Get a basic block with the specified name or ID, creating a
2269/// forward reference record if needed.
2270BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2271 LocTy Loc) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002272 return cast_or_null<BasicBlock>(GetVal(Name,
2273 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002274}
2275
2276BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002277 return cast_or_null<BasicBlock>(GetVal(ID,
2278 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002279}
2280
2281/// DefineBB - Define the specified basic block, which is either named or
2282/// unnamed. If there is an error, this returns null otherwise it returns
2283/// the block being defined.
2284BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2285 LocTy Loc) {
2286 BasicBlock *BB;
2287 if (Name.empty())
2288 BB = GetBB(NumberedVals.size(), Loc);
2289 else
2290 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002291 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002292
Chris Lattnerac161bf2009-01-02 07:01:27 +00002293 // Move the block to the end of the function. Forward ref'd blocks are
2294 // inserted wherever they happen to be referenced.
2295 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002296
Chris Lattnerac161bf2009-01-02 07:01:27 +00002297 // Remove the block from forward ref sets.
2298 if (Name.empty()) {
2299 ForwardRefValIDs.erase(NumberedVals.size());
2300 NumberedVals.push_back(BB);
2301 } else {
2302 // BB forward references are already in the function symbol table.
2303 ForwardRefVals.erase(Name);
2304 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002305
Chris Lattnerac161bf2009-01-02 07:01:27 +00002306 return BB;
2307}
2308
2309//===----------------------------------------------------------------------===//
2310// Constants.
2311//===----------------------------------------------------------------------===//
2312
2313/// ParseValID - Parse an abstract value that doesn't necessarily have a
2314/// type implied. For example, if we parse "4" we don't know what integer type
2315/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002316/// sanity. PFS is used to convert function-local operands of metadata (since
2317/// metadata operands are not just parsed here but also converted to values).
2318/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002319bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002320 ID.Loc = Lex.getLoc();
2321 switch (Lex.getKind()) {
2322 default: return TokError("expected value token");
2323 case lltok::GlobalID: // @42
2324 ID.UIntVal = Lex.getUIntVal();
2325 ID.Kind = ValID::t_GlobalID;
2326 break;
2327 case lltok::GlobalVar: // @foo
2328 ID.StrVal = Lex.getStrVal();
2329 ID.Kind = ValID::t_GlobalName;
2330 break;
2331 case lltok::LocalVarID: // %42
2332 ID.UIntVal = Lex.getUIntVal();
2333 ID.Kind = ValID::t_LocalID;
2334 break;
2335 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002336 ID.StrVal = Lex.getStrVal();
2337 ID.Kind = ValID::t_LocalName;
2338 break;
2339 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002340 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002341 ID.Kind = ValID::t_APSInt;
2342 break;
2343 case lltok::APFloat:
2344 ID.APFloatVal = Lex.getAPFloatVal();
2345 ID.Kind = ValID::t_APFloat;
2346 break;
2347 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002348 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002349 ID.Kind = ValID::t_Constant;
2350 break;
2351 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002352 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002353 ID.Kind = ValID::t_Constant;
2354 break;
2355 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2356 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2357 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002358
Chris Lattnerac161bf2009-01-02 07:01:27 +00002359 case lltok::lbrace: {
2360 // ValID ::= '{' ConstVector '}'
2361 Lex.Lex();
2362 SmallVector<Constant*, 16> Elts;
2363 if (ParseGlobalValueVector(Elts) ||
2364 ParseToken(lltok::rbrace, "expected end of struct constant"))
2365 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002366
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002367 ID.ConstantStructElts = new Constant*[Elts.size()];
2368 ID.UIntVal = Elts.size();
2369 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2370 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002371 return false;
2372 }
2373 case lltok::less: {
2374 // ValID ::= '<' ConstVector '>' --> Vector.
2375 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2376 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002377 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002378
Chris Lattnerac161bf2009-01-02 07:01:27 +00002379 SmallVector<Constant*, 16> Elts;
2380 LocTy FirstEltLoc = Lex.getLoc();
2381 if (ParseGlobalValueVector(Elts) ||
2382 (isPackedStruct &&
2383 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2384 ParseToken(lltok::greater, "expected end of constant"))
2385 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002386
Chris Lattnerac161bf2009-01-02 07:01:27 +00002387 if (isPackedStruct) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002388 ID.ConstantStructElts = new Constant*[Elts.size()];
2389 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2390 ID.UIntVal = Elts.size();
2391 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002392 return false;
2393 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002394
Chris Lattnerac161bf2009-01-02 07:01:27 +00002395 if (Elts.empty())
2396 return Error(ID.Loc, "constant vector must not be empty");
2397
Duncan Sands9dff9be2010-02-15 16:12:20 +00002398 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002399 !Elts[0]->getType()->isFloatingPointTy() &&
2400 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002401 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002402 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002403
Chris Lattnerac161bf2009-01-02 07:01:27 +00002404 // Verify that all the vector elements have the same type.
2405 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2406 if (Elts[i]->getType() != Elts[0]->getType())
2407 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002408 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002409 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002410
Chris Lattner69229312011-02-15 00:14:00 +00002411 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002412 ID.Kind = ValID::t_Constant;
2413 return false;
2414 }
2415 case lltok::lsquare: { // Array Constant
2416 Lex.Lex();
2417 SmallVector<Constant*, 16> Elts;
2418 LocTy FirstEltLoc = Lex.getLoc();
2419 if (ParseGlobalValueVector(Elts) ||
2420 ParseToken(lltok::rsquare, "expected end of array constant"))
2421 return true;
2422
2423 // Handle empty element.
2424 if (Elts.empty()) {
2425 // Use undef instead of an array because it's inconvenient to determine
2426 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002427 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002428 return false;
2429 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002430
Chris Lattnerac161bf2009-01-02 07:01:27 +00002431 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002432 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002433 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002434
Owen Anderson4056ca92009-07-29 22:17:13 +00002435 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002436
Chris Lattnerac161bf2009-01-02 07:01:27 +00002437 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002438 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002439 if (Elts[i]->getType() != Elts[0]->getType())
2440 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002441 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002442 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002443 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002444
Jay Foad83be3612011-06-22 09:24:39 +00002445 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002446 ID.Kind = ValID::t_Constant;
2447 return false;
2448 }
2449 case lltok::kw_c: // c "foo"
2450 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002451 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2452 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002453 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2454 ID.Kind = ValID::t_Constant;
2455 return false;
2456
2457 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002458 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2459 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002460 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002461 Lex.Lex();
2462 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002463 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002464 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002465 ParseStringConstant(ID.StrVal) ||
2466 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002467 ParseToken(lltok::StringConstant, "expected constraint string"))
2468 return true;
2469 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002470 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002471 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002472 ID.Kind = ValID::t_InlineAsm;
2473 return false;
2474 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002475
Chris Lattner3432c622009-10-28 03:39:23 +00002476 case lltok::kw_blockaddress: {
2477 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2478 Lex.Lex();
2479
2480 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002481
Chris Lattner3432c622009-10-28 03:39:23 +00002482 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2483 ParseValID(Fn) ||
2484 ParseToken(lltok::comma, "expected comma in block address expression")||
2485 ParseValID(Label) ||
2486 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2487 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002488
Chris Lattner3432c622009-10-28 03:39:23 +00002489 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2490 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002491 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002492 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002493
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002494 // Try to find the function (but skip it if it's forward-referenced).
2495 GlobalValue *GV = nullptr;
2496 if (Fn.Kind == ValID::t_GlobalID) {
2497 if (Fn.UIntVal < NumberedVals.size())
2498 GV = NumberedVals[Fn.UIntVal];
2499 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2500 GV = M->getNamedValue(Fn.StrVal);
2501 }
2502 Function *F = nullptr;
2503 if (GV) {
2504 // Confirm that it's actually a function with a definition.
2505 if (!isa<Function>(GV))
2506 return Error(Fn.Loc, "expected function name in blockaddress");
2507 F = cast<Function>(GV);
2508 if (F->isDeclaration())
2509 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2510 }
2511
2512 if (!F) {
2513 // Make a global variable as a placeholder for this reference.
2514 GlobalValue *&FwdRef = ForwardRefBlockAddresses[Fn][Label];
2515 if (!FwdRef)
2516 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2517 GlobalValue::InternalLinkage, nullptr, "");
2518 ID.ConstantVal = FwdRef;
2519 ID.Kind = ValID::t_Constant;
2520 return false;
2521 }
2522
2523 // We found the function; now find the basic block. Don't use PFS, since we
2524 // might be inside a constant expression.
2525 BasicBlock *BB;
2526 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2527 if (Label.Kind == ValID::t_LocalID)
2528 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2529 else
2530 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2531 if (!BB)
2532 return Error(Label.Loc, "referenced value is not a basic block");
2533 } else {
2534 if (Label.Kind == ValID::t_LocalID)
2535 return Error(Label.Loc, "cannot take address of numeric label after "
2536 "the function is defined");
2537 BB = dyn_cast_or_null<BasicBlock>(
2538 F->getValueSymbolTable().lookup(Label.StrVal));
2539 if (!BB)
2540 return Error(Label.Loc, "referenced value is not a basic block");
2541 }
2542
2543 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002544 ID.Kind = ValID::t_Constant;
2545 return false;
2546 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002547
Chris Lattnerac161bf2009-01-02 07:01:27 +00002548 case lltok::kw_trunc:
2549 case lltok::kw_zext:
2550 case lltok::kw_sext:
2551 case lltok::kw_fptrunc:
2552 case lltok::kw_fpext:
2553 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002554 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002555 case lltok::kw_uitofp:
2556 case lltok::kw_sitofp:
2557 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002558 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002559 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002560 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002561 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002562 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002563 Constant *SrcVal;
2564 Lex.Lex();
2565 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2566 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002567 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002568 ParseType(DestTy) ||
2569 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2570 return true;
2571 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2572 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002573 getTypeString(SrcVal->getType()) + "' to '" +
2574 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002575 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002576 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002577 ID.Kind = ValID::t_Constant;
2578 return false;
2579 }
2580 case lltok::kw_extractvalue: {
2581 Lex.Lex();
2582 Constant *Val;
2583 SmallVector<unsigned, 4> Indices;
2584 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2585 ParseGlobalTypeAndValue(Val) ||
2586 ParseIndexList(Indices) ||
2587 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2588 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002589
Chris Lattner392be582010-02-12 20:49:41 +00002590 if (!Val->getType()->isAggregateType())
2591 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002592 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002593 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002594 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002595 ID.Kind = ValID::t_Constant;
2596 return false;
2597 }
2598 case lltok::kw_insertvalue: {
2599 Lex.Lex();
2600 Constant *Val0, *Val1;
2601 SmallVector<unsigned, 4> Indices;
2602 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2603 ParseGlobalTypeAndValue(Val0) ||
2604 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2605 ParseGlobalTypeAndValue(Val1) ||
2606 ParseIndexList(Indices) ||
2607 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2608 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002609 if (!Val0->getType()->isAggregateType())
2610 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002611 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002612 return Error(ID.Loc, "invalid indices for insertvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002613 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002614 ID.Kind = ValID::t_Constant;
2615 return false;
2616 }
2617 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002618 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002619 unsigned PredVal, Opc = Lex.getUIntVal();
2620 Constant *Val0, *Val1;
2621 Lex.Lex();
2622 if (ParseCmpPredicate(PredVal, Opc) ||
2623 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2624 ParseGlobalTypeAndValue(Val0) ||
2625 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2626 ParseGlobalTypeAndValue(Val1) ||
2627 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2628 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002629
Chris Lattnerac161bf2009-01-02 07:01:27 +00002630 if (Val0->getType() != Val1->getType())
2631 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002632
Chris Lattnerac161bf2009-01-02 07:01:27 +00002633 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002634
Chris Lattnerac161bf2009-01-02 07:01:27 +00002635 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002636 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002637 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002638 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002639 } else {
2640 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002641 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002642 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002643 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002644 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002645 }
2646 ID.Kind = ValID::t_Constant;
2647 return false;
2648 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002649
Chris Lattnerac161bf2009-01-02 07:01:27 +00002650 // Binary Operators.
2651 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00002652 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002653 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00002654 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002655 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00002656 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002657 case lltok::kw_udiv:
2658 case lltok::kw_sdiv:
2659 case lltok::kw_fdiv:
2660 case lltok::kw_urem:
2661 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002662 case lltok::kw_frem:
2663 case lltok::kw_shl:
2664 case lltok::kw_lshr:
2665 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002666 bool NUW = false;
2667 bool NSW = false;
2668 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002669 unsigned Opc = Lex.getUIntVal();
2670 Constant *Val0, *Val1;
2671 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00002672 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00002673 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2674 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002675 if (EatIfPresent(lltok::kw_nuw))
2676 NUW = true;
2677 if (EatIfPresent(lltok::kw_nsw)) {
2678 NSW = true;
2679 if (EatIfPresent(lltok::kw_nuw))
2680 NUW = true;
2681 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00002682 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2683 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002684 if (EatIfPresent(lltok::kw_exact))
2685 Exact = true;
2686 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002687 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2688 ParseGlobalTypeAndValue(Val0) ||
2689 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2690 ParseGlobalTypeAndValue(Val1) ||
2691 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2692 return true;
2693 if (Val0->getType() != Val1->getType())
2694 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002695 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002696 if (NUW)
2697 return Error(ModifierLoc, "nuw only applies to integer operations");
2698 if (NSW)
2699 return Error(ModifierLoc, "nsw only applies to integer operations");
2700 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00002701 // Check that the type is valid for the operator.
2702 switch (Opc) {
2703 case Instruction::Add:
2704 case Instruction::Sub:
2705 case Instruction::Mul:
2706 case Instruction::UDiv:
2707 case Instruction::SDiv:
2708 case Instruction::URem:
2709 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002710 case Instruction::Shl:
2711 case Instruction::AShr:
2712 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00002713 if (!Val0->getType()->isIntOrIntVectorTy())
2714 return Error(ID.Loc, "constexpr requires integer operands");
2715 break;
2716 case Instruction::FAdd:
2717 case Instruction::FSub:
2718 case Instruction::FMul:
2719 case Instruction::FDiv:
2720 case Instruction::FRem:
2721 if (!Val0->getType()->isFPOrFPVectorTy())
2722 return Error(ID.Loc, "constexpr requires fp operands");
2723 break;
2724 default: llvm_unreachable("Unknown binary operator!");
2725 }
Dan Gohman1b849082009-09-07 23:54:19 +00002726 unsigned Flags = 0;
2727 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2728 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002729 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00002730 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00002731 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002732 ID.Kind = ValID::t_Constant;
2733 return false;
2734 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002735
Chris Lattnerac161bf2009-01-02 07:01:27 +00002736 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00002737 case lltok::kw_and:
2738 case lltok::kw_or:
2739 case lltok::kw_xor: {
2740 unsigned Opc = Lex.getUIntVal();
2741 Constant *Val0, *Val1;
2742 Lex.Lex();
2743 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2744 ParseGlobalTypeAndValue(Val0) ||
2745 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2746 ParseGlobalTypeAndValue(Val1) ||
2747 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2748 return true;
2749 if (Val0->getType() != Val1->getType())
2750 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002751 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002752 return Error(ID.Loc,
2753 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002754 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002755 ID.Kind = ValID::t_Constant;
2756 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002757 }
2758
Chris Lattnerac161bf2009-01-02 07:01:27 +00002759 case lltok::kw_getelementptr:
2760 case lltok::kw_shufflevector:
2761 case lltok::kw_insertelement:
2762 case lltok::kw_extractelement:
2763 case lltok::kw_select: {
2764 unsigned Opc = Lex.getUIntVal();
2765 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00002766 bool InBounds = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002767 Lex.Lex();
Dan Gohman1639c392009-07-27 21:53:46 +00002768 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00002769 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002770 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2771 ParseGlobalValueVector(Elts) ||
2772 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2773 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002774
Chris Lattnerac161bf2009-01-02 07:01:27 +00002775 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00002776 if (Elts.size() == 0 ||
2777 !Elts[0]->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002778 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002779
Jay Foaded8db7d2011-07-21 14:31:17 +00002780 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foadd1b78492011-07-25 09:48:08 +00002781 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002782 return Error(ID.Loc, "invalid indices for getelementptr");
Jay Foad2f5fc8c2011-07-21 15:15:37 +00002783 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2784 InBounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002785 } else if (Opc == Instruction::Select) {
2786 if (Elts.size() != 3)
2787 return Error(ID.Loc, "expected three operands to select");
2788 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2789 Elts[2]))
2790 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00002791 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002792 } else if (Opc == Instruction::ShuffleVector) {
2793 if (Elts.size() != 3)
2794 return Error(ID.Loc, "expected three operands to shufflevector");
2795 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2796 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00002797 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002798 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002799 } else if (Opc == Instruction::ExtractElement) {
2800 if (Elts.size() != 2)
2801 return Error(ID.Loc, "expected two operands to extractelement");
2802 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2803 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002804 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002805 } else {
2806 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2807 if (Elts.size() != 3)
2808 return Error(ID.Loc, "expected three operands to insertelement");
2809 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2810 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00002811 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002812 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002813 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002814
Chris Lattnerac161bf2009-01-02 07:01:27 +00002815 ID.Kind = ValID::t_Constant;
2816 return false;
2817 }
2818 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002819
Chris Lattnerac161bf2009-01-02 07:01:27 +00002820 Lex.Lex();
2821 return false;
2822}
2823
2824/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00002825bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002826 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002827 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00002828 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00002829 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00002830 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002831 if (V && !(C = dyn_cast<Constant>(V)))
2832 return Error(ID.Loc, "global values must be constants");
2833 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002834}
2835
Victor Hernandez9d75c962010-01-11 22:31:58 +00002836bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002837 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002838 return ParseType(Ty) ||
2839 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002840}
2841
Rafael Espindola83a362c2015-01-06 22:55:16 +00002842bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00002843 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00002844
2845 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00002846 if (!EatIfPresent(lltok::kw_comdat))
2847 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00002848
2849 if (EatIfPresent(lltok::lparen)) {
2850 if (Lex.getKind() != lltok::ComdatVar)
2851 return TokError("expected comdat variable");
2852 C = getComdat(Lex.getStrVal(), Lex.getLoc());
2853 Lex.Lex();
2854 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
2855 return true;
2856 } else {
2857 if (GlobalName.empty())
2858 return TokError("comdat cannot be unnamed");
2859 C = getComdat(GlobalName, KwLoc);
2860 }
2861
David Majnemerdad0a642014-06-27 18:19:56 +00002862 return false;
2863}
2864
Victor Hernandez9d75c962010-01-11 22:31:58 +00002865/// ParseGlobalValueVector
2866/// ::= /*empty*/
2867/// ::= TypeAndValue (',' TypeAndValue)*
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002868bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00002869 // Empty list.
2870 if (Lex.getKind() == lltok::rbrace ||
2871 Lex.getKind() == lltok::rsquare ||
2872 Lex.getKind() == lltok::greater ||
2873 Lex.getKind() == lltok::rparen)
2874 return false;
2875
2876 Constant *C;
2877 if (ParseGlobalTypeAndValue(C)) return true;
2878 Elts.push_back(C);
2879
2880 while (EatIfPresent(lltok::comma)) {
2881 if (ParseGlobalTypeAndValue(C)) return true;
2882 Elts.push_back(C);
2883 }
2884
2885 return false;
2886}
2887
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00002888bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002889 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002890 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00002891 return true;
2892
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00002893 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00002894 return false;
2895}
2896
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00002897/// MDNode:
2898/// ::= !{ ... }
2899/// ::= !7
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002900/// ::= !MDLocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00002901bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002902 if (Lex.getKind() == lltok::MetadataVar)
2903 return ParseSpecializedMDNode(N);
2904
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00002905 return ParseToken(lltok::exclaim, "expected '!' here") ||
2906 ParseMDNodeTail(N);
2907}
2908
2909bool LLParser::ParseMDNodeTail(MDNode *&N) {
2910 // !{ ... }
2911 if (Lex.getKind() == lltok::lbrace)
2912 return ParseMDTuple(N);
2913
2914 // !42
2915 return ParseMDNodeID(N);
2916}
2917
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00002918namespace {
2919
2920/// Structure to represent an optional metadata field.
2921template <class FieldTy> struct MDFieldImpl {
2922 typedef MDFieldImpl ImplTy;
2923 FieldTy Val;
2924 bool Seen;
2925
2926 void assign(FieldTy Val) {
2927 Seen = true;
2928 this->Val = std::move(Val);
2929 }
2930
2931 explicit MDFieldImpl(FieldTy Default)
2932 : Val(std::move(Default)), Seen(false) {}
2933};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002934
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00002935struct MDUnsignedField : public MDFieldImpl<uint64_t> {
2936 uint64_t Max;
2937
2938 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
2939 : ImplTy(Default), Max(Max) {}
2940};
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00002941struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00002942 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00002943};
2944struct ColumnField : public MDUnsignedField {
2945 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
2946};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00002947struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00002948 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00002949};
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00002950struct DwarfAttEncodingField : public MDUnsignedField {
2951 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
2952};
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00002953struct DwarfVirtualityField : public MDUnsignedField {
2954 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
2955};
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00002956struct DwarfLangField : public MDUnsignedField {
2957 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
2958};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002959
2960struct MDSignedField : public MDFieldImpl<int64_t> {
2961 int64_t Min;
2962 int64_t Max;
2963
2964 MDSignedField(int64_t Default = 0)
2965 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
2966 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
2967 : ImplTy(Default), Min(Min), Max(Max) {}
2968};
2969
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00002970struct MDBoolField : public MDFieldImpl<bool> {
2971 MDBoolField(bool Default = false) : ImplTy(Default) {}
2972};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00002973struct MDField : public MDFieldImpl<Metadata *> {
2974 MDField() : ImplTy(nullptr) {}
2975};
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00002976struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
2977 MDConstant() : ImplTy(nullptr) {}
2978};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00002979struct MDStringField : public MDFieldImpl<std::string> {
2980 MDStringField() : ImplTy(std::string()) {}
2981};
2982struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
2983 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
2984};
2985
2986} // end namespace
2987
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00002988namespace llvm {
2989
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00002990template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002991bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00002992 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002993 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
2994 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002995
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00002996 auto &U = Lex.getAPSIntVal();
2997 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002998 return TokError("value for '" + Name + "' too large, limit is " +
2999 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003000 Result.assign(U.getZExtValue());
3001 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003002 Lex.Lex();
3003 return false;
3004}
3005
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003006template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003007bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3008 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3009}
3010template <>
3011bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3012 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3013}
3014
3015template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003016bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3017 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003018 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003019
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003020 if (Lex.getKind() != lltok::DwarfTag)
3021 return TokError("expected DWARF tag");
3022
3023 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3024 if (Tag == dwarf::DW_TAG_invalid)
3025 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003026 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003027
3028 Result.assign(Tag);
3029 Lex.Lex();
3030 return false;
3031}
3032
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003033template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003034bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3035 DwarfVirtualityField &Result) {
3036 if (Lex.getKind() == lltok::APSInt)
3037 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3038
3039 if (Lex.getKind() != lltok::DwarfVirtuality)
3040 return TokError("expected DWARF virtuality code");
3041
3042 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3043 if (!Virtuality)
3044 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3045 Lex.getStrVal() + "'");
3046 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3047 Result.assign(Virtuality);
3048 Lex.Lex();
3049 return false;
3050}
3051
3052template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003053bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3054 if (Lex.getKind() == lltok::APSInt)
3055 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3056
3057 if (Lex.getKind() != lltok::DwarfLang)
3058 return TokError("expected DWARF language");
3059
3060 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3061 if (!Lang)
3062 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3063 "'");
3064 assert(Lang <= Result.Max && "Expected valid DWARF language");
3065 Result.assign(Lang);
3066 Lex.Lex();
3067 return false;
3068}
3069
3070template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003071bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003072 DwarfAttEncodingField &Result) {
3073 if (Lex.getKind() == lltok::APSInt)
3074 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3075
3076 if (Lex.getKind() != lltok::DwarfAttEncoding)
3077 return TokError("expected DWARF type attribute encoding");
3078
3079 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3080 if (!Encoding)
3081 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3082 Lex.getStrVal() + "'");
3083 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3084 Result.assign(Encoding);
3085 Lex.Lex();
3086 return false;
3087}
3088
3089template <>
3090bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003091 MDSignedField &Result) {
3092 if (Lex.getKind() != lltok::APSInt)
3093 return TokError("expected signed integer");
3094
3095 auto &S = Lex.getAPSIntVal();
3096 if (S < Result.Min)
3097 return TokError("value for '" + Name + "' too small, limit is " +
3098 Twine(Result.Min));
3099 if (S > Result.Max)
3100 return TokError("value for '" + Name + "' too large, limit is " +
3101 Twine(Result.Max));
3102 Result.assign(S.getExtValue());
3103 assert(Result.Val >= Result.Min && "Expected value in range");
3104 assert(Result.Val <= Result.Max && "Expected value in range");
3105 Lex.Lex();
3106 return false;
3107}
3108
3109template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003110bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3111 switch (Lex.getKind()) {
3112 default:
3113 return TokError("expected 'true' or 'false'");
3114 case lltok::kw_true:
3115 Result.assign(true);
3116 break;
3117 case lltok::kw_false:
3118 Result.assign(false);
3119 break;
3120 }
3121 Lex.Lex();
3122 return false;
3123}
3124
3125template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003126bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003127 if (Lex.getKind() == lltok::kw_null) {
3128 Lex.Lex();
3129 Result.assign(nullptr);
3130 return false;
3131 }
3132
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003133 Metadata *MD;
3134 if (ParseMetadata(MD, nullptr))
3135 return true;
3136
3137 Result.assign(MD);
3138 return false;
3139}
3140
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003141template <>
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003142bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3143 Metadata *MD;
3144 if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3145 return true;
3146
3147 Result.assign(cast<ConstantAsMetadata>(MD));
3148 return false;
3149}
3150
3151template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003152bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
3153 std::string S;
3154 if (ParseStringConstant(S))
3155 return true;
3156
3157 Result.assign(std::move(S));
3158 return false;
3159}
3160
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003161template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003162bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3163 SmallVector<Metadata *, 4> MDs;
3164 if (ParseMDNodeVector(MDs))
3165 return true;
3166
3167 Result.assign(std::move(MDs));
3168 return false;
3169}
3170
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003171} // end namespace llvm
3172
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003173template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003174bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003175 do {
3176 if (Lex.getKind() != lltok::LabelStr)
3177 return TokError("expected field label here");
3178
3179 if (parseField())
3180 return true;
3181 } while (EatIfPresent(lltok::comma));
3182
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003183 return false;
3184}
3185
3186template <class ParserTy>
3187bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3188 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3189 Lex.Lex();
3190
3191 if (ParseToken(lltok::lparen, "expected '(' here"))
3192 return true;
3193 if (Lex.getKind() != lltok::rparen)
3194 if (ParseMDFieldsImplBody(parseField))
3195 return true;
3196
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00003197 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003198 return ParseToken(lltok::rparen, "expected ')' here");
3199}
3200
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003201template <class FieldTy>
3202bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3203 if (Result.Seen)
3204 return TokError("field '" + Name + "' cannot be specified more than once");
3205
3206 LocTy Loc = Lex.getLoc();
3207 Lex.Lex();
3208 return ParseMDField(Loc, Name, Result);
3209}
3210
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003211bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3212 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003213
3214#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003215 if (Lex.getStrVal() == #CLASS) \
3216 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003217#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003218
3219 return TokError("expected metadata type");
3220}
3221
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003222#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3223#define NOP_FIELD(NAME, TYPE, INIT)
3224#define REQUIRE_FIELD(NAME, TYPE, INIT) \
3225 if (!NAME.Seen) \
3226 return Error(ClosingLoc, "missing required field '" #NAME "'");
3227#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003228 if (Lex.getStrVal() == #NAME) \
3229 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003230#define PARSE_MD_FIELDS() \
3231 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3232 do { \
3233 LocTy ClosingLoc; \
3234 if (ParseMDFieldsImpl([&]() -> bool { \
3235 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3236 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3237 }, ClosingLoc)) \
3238 return true; \
3239 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3240 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003241#define GET_OR_DISTINCT(CLASS, ARGS) \
3242 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003243
3244/// ParseMDLocationFields:
3245/// ::= !MDLocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3246bool LLParser::ParseMDLocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003247#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003248 OPTIONAL(line, LineField, ); \
3249 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003250 REQUIRED(scope, MDField, ); \
3251 OPTIONAL(inlinedAt, MDField, );
3252 PARSE_MD_FIELDS();
3253#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003254
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003255 auto get = (IsDistinct ? MDLocation::getDistinct : MDLocation::get);
3256 Result = get(Context, line.Val, column.Val, scope.Val, inlinedAt.Val);
3257 return false;
3258}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003259
3260/// ParseGenericDebugNode:
3261/// ::= !GenericDebugNode(tag: 15, header: "...", operands: {...})
3262bool LLParser::ParseGenericDebugNode(MDNode *&Result, bool IsDistinct) {
3263#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003264 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003265 OPTIONAL(header, MDStringField, ); \
3266 OPTIONAL(operands, MDFieldList, );
3267 PARSE_MD_FIELDS();
3268#undef VISIT_MD_FIELDS
3269
3270 Result = GET_OR_DISTINCT(GenericDebugNode,
3271 (Context, tag.Val, header.Val, operands.Val));
3272 return false;
3273}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003274
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003275/// ParseMDSubrange:
3276/// ::= !MDSubrange(count: 30, lowerBound: 2)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003277bool LLParser::ParseMDSubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003278#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith5c9a1772015-02-18 23:17:51 +00003279 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003280 OPTIONAL(lowerBound, MDSignedField, );
3281 PARSE_MD_FIELDS();
3282#undef VISIT_MD_FIELDS
3283
3284 Result = GET_OR_DISTINCT(MDSubrange, (Context, count.Val, lowerBound.Val));
3285 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003286}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003287
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003288/// ParseMDEnumerator:
3289/// ::= !MDEnumerator(value: 30, name: "SomeKind")
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003290bool LLParser::ParseMDEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003291#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00003292 REQUIRED(name, MDStringField, ); \
3293 REQUIRED(value, MDSignedField, );
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003294 PARSE_MD_FIELDS();
3295#undef VISIT_MD_FIELDS
3296
3297 Result = GET_OR_DISTINCT(MDEnumerator, (Context, value.Val, name.Val));
3298 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003299}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003300
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003301/// ParseMDBasicType:
3302/// ::= !MDBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003303bool LLParser::ParseMDBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003304#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3305 REQUIRED(tag, DwarfTagField, ); \
3306 OPTIONAL(name, MDStringField, ); \
3307 OPTIONAL(size, MDUnsignedField, (0, UINT32_MAX)); \
3308 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003309 OPTIONAL(encoding, DwarfAttEncodingField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003310 PARSE_MD_FIELDS();
3311#undef VISIT_MD_FIELDS
3312
3313 Result = GET_OR_DISTINCT(MDBasicType, (Context, tag.Val, name.Val, size.Val,
3314 align.Val, encoding.Val));
3315 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003316}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003317
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003318/// ParseMDDerivedType:
3319/// ::= !MDDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
3320/// line: 7, scope: !1, baseType: !2, size: 32,
3321/// align: 32, offset: 0, flags: 0, extraData: !3)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003322bool LLParser::ParseMDDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003323#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3324 REQUIRED(tag, DwarfTagField, ); \
3325 OPTIONAL(name, MDStringField, ); \
3326 OPTIONAL(file, MDField, ); \
3327 OPTIONAL(line, LineField, ); \
3328 OPTIONAL(scope, MDField, ); \
3329 REQUIRED(baseType, MDField, ); \
3330 OPTIONAL(size, MDUnsignedField, (0, UINT32_MAX)); \
3331 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
3332 OPTIONAL(offset, MDUnsignedField, (0, UINT32_MAX)); \
3333 OPTIONAL(flags, MDUnsignedField, (0, UINT32_MAX)); \
3334 OPTIONAL(extraData, MDField, );
3335 PARSE_MD_FIELDS();
3336#undef VISIT_MD_FIELDS
3337
3338 Result = GET_OR_DISTINCT(MDDerivedType,
3339 (Context, tag.Val, name.Val, file.Val, line.Val,
3340 scope.Val, baseType.Val, size.Val, align.Val,
3341 offset.Val, flags.Val, extraData.Val));
3342 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003343}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003344
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003345bool LLParser::ParseMDCompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003346#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3347 REQUIRED(tag, DwarfTagField, ); \
3348 OPTIONAL(name, MDStringField, ); \
3349 OPTIONAL(file, MDField, ); \
3350 OPTIONAL(line, LineField, ); \
3351 OPTIONAL(scope, MDField, ); \
3352 OPTIONAL(baseType, MDField, ); \
3353 OPTIONAL(size, MDUnsignedField, (0, UINT32_MAX)); \
3354 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
3355 OPTIONAL(offset, MDUnsignedField, (0, UINT32_MAX)); \
3356 OPTIONAL(flags, MDUnsignedField, (0, UINT32_MAX)); \
3357 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003358 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003359 OPTIONAL(vtableHolder, MDField, ); \
3360 OPTIONAL(templateParams, MDField, ); \
3361 OPTIONAL(identifier, MDStringField, );
3362 PARSE_MD_FIELDS();
3363#undef VISIT_MD_FIELDS
3364
3365 Result = GET_OR_DISTINCT(
3366 MDCompositeType,
3367 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3368 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3369 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3370 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003371}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003372
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003373bool LLParser::ParseMDSubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003374#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3375 OPTIONAL(flags, MDUnsignedField, (0, UINT32_MAX)); \
3376 REQUIRED(types, MDField, );
3377 PARSE_MD_FIELDS();
3378#undef VISIT_MD_FIELDS
3379
3380 Result = GET_OR_DISTINCT(MDSubroutineType, (Context, flags.Val, types.Val));
3381 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003382}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003383
3384/// ParseMDFileType:
3385/// ::= !MDFileType(filename: "path/to/file", directory: "/path/to/dir")
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003386bool LLParser::ParseMDFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003387#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3388 REQUIRED(filename, MDStringField, ); \
3389 REQUIRED(directory, MDStringField, );
3390 PARSE_MD_FIELDS();
3391#undef VISIT_MD_FIELDS
3392
3393 Result = GET_OR_DISTINCT(MDFile, (Context, filename.Val, directory.Val));
3394 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003395}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003396
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003397/// ParseMDCompileUnit:
3398/// ::= !MDCompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
3399/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
3400/// splitDebugFilename: "abc.debug", emissionKind: 1,
3401/// enums: !1, retainedTypes: !2, subprograms: !3,
3402/// globals: !4, imports: !5)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003403bool LLParser::ParseMDCompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003404#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3405 REQUIRED(language, DwarfLangField, ); \
3406 REQUIRED(file, MDField, ); \
3407 OPTIONAL(producer, MDStringField, ); \
3408 OPTIONAL(isOptimized, MDBoolField, ); \
3409 OPTIONAL(flags, MDStringField, ); \
3410 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
3411 OPTIONAL(splitDebugFilename, MDStringField, ); \
3412 OPTIONAL(emissionKind, MDUnsignedField, (0, UINT32_MAX)); \
3413 OPTIONAL(enums, MDField, ); \
3414 OPTIONAL(retainedTypes, MDField, ); \
3415 OPTIONAL(subprograms, MDField, ); \
3416 OPTIONAL(globals, MDField, ); \
3417 OPTIONAL(imports, MDField, );
3418 PARSE_MD_FIELDS();
3419#undef VISIT_MD_FIELDS
3420
3421 Result = GET_OR_DISTINCT(MDCompileUnit,
3422 (Context, language.Val, file.Val, producer.Val,
3423 isOptimized.Val, flags.Val, runtimeVersion.Val,
3424 splitDebugFilename.Val, emissionKind.Val, enums.Val,
3425 retainedTypes.Val, subprograms.Val, globals.Val,
3426 imports.Val));
3427 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003428}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003429
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003430/// ParseMDSubprogram:
3431/// ::= !MDSubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
3432/// file: !1, line: 7, type: !2, isLocal: false,
3433/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003434/// virtuality: DW_VIRTUALTIY_pure_virtual,
3435/// virtualIndex: 10, flags: 11,
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003436/// isOptimized: false, function: void ()* @_Z3foov,
3437/// templateParams: !4, declaration: !5, variables: !6)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003438bool LLParser::ParseMDSubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003439#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3440 OPTIONAL(scope, MDField, ); \
3441 REQUIRED(name, MDStringField, ); \
3442 OPTIONAL(linkageName, MDStringField, ); \
3443 OPTIONAL(file, MDField, ); \
3444 OPTIONAL(line, LineField, ); \
3445 OPTIONAL(type, MDField, ); \
3446 OPTIONAL(isLocal, MDBoolField, ); \
3447 OPTIONAL(isDefinition, MDBoolField, (true)); \
3448 OPTIONAL(scopeLine, LineField, ); \
3449 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003450 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003451 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
3452 OPTIONAL(flags, MDUnsignedField, (0, UINT32_MAX)); \
3453 OPTIONAL(isOptimized, MDBoolField, ); \
3454 OPTIONAL(function, MDConstant, ); \
3455 OPTIONAL(templateParams, MDField, ); \
3456 OPTIONAL(declaration, MDField, ); \
3457 OPTIONAL(variables, MDField, );
3458 PARSE_MD_FIELDS();
3459#undef VISIT_MD_FIELDS
3460
3461 Result = GET_OR_DISTINCT(
3462 MDSubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
3463 line.Val, type.Val, isLocal.Val, isDefinition.Val,
3464 scopeLine.Val, containingType.Val, virtuality.Val,
3465 virtualIndex.Val, flags.Val, isOptimized.Val, function.Val,
3466 templateParams.Val, declaration.Val, variables.Val));
3467 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003468}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003469
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003470/// ParseMDLexicalBlock:
3471/// ::= !MDLexicalBlock(scope: !0, file: !2, line: 7, column: 9)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003472bool LLParser::ParseMDLexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003473#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3474 REQUIRED(scope, MDField, ); \
3475 OPTIONAL(file, MDField, ); \
3476 OPTIONAL(line, LineField, ); \
3477 OPTIONAL(column, ColumnField, );
3478 PARSE_MD_FIELDS();
3479#undef VISIT_MD_FIELDS
3480
3481 Result = GET_OR_DISTINCT(
3482 MDLexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
3483 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003484}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003485
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003486/// ParseMDLexicalBlockFile:
3487/// ::= !MDLexicalBlockFile(scope: !0, file: !2, discriminator: 9)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003488bool LLParser::ParseMDLexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003489#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3490 REQUIRED(scope, MDField, ); \
3491 OPTIONAL(file, MDField, ); \
3492 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
3493 PARSE_MD_FIELDS();
3494#undef VISIT_MD_FIELDS
3495
3496 Result = GET_OR_DISTINCT(MDLexicalBlockFile,
3497 (Context, scope.Val, file.Val, discriminator.Val));
3498 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003499}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003500
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003501/// ParseMDNamespace:
3502/// ::= !MDNamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003503bool LLParser::ParseMDNamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003504#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3505 REQUIRED(scope, MDField, ); \
3506 OPTIONAL(file, MDField, ); \
3507 OPTIONAL(name, MDStringField, ); \
3508 OPTIONAL(line, LineField, );
3509 PARSE_MD_FIELDS();
3510#undef VISIT_MD_FIELDS
3511
3512 Result = GET_OR_DISTINCT(MDNamespace,
3513 (Context, scope.Val, file.Val, name.Val, line.Val));
3514 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003515}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003516
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003517/// ParseMDTemplateTypeParameter:
3518/// ::= !MDTemplateTypeParameter(scope: !0, name: "Ty", type: !1)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003519bool LLParser::ParseMDTemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003520#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3521 REQUIRED(scope, MDField, ); \
3522 OPTIONAL(name, MDStringField, ); \
3523 REQUIRED(type, MDField, );
3524 PARSE_MD_FIELDS();
3525#undef VISIT_MD_FIELDS
3526
3527 Result = GET_OR_DISTINCT(MDTemplateTypeParameter,
3528 (Context, scope.Val, name.Val, type.Val));
3529 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003530}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003531
3532/// ParseMDTemplateValueParameter:
3533/// ::= !MDTemplateValueParameter(tag: DW_TAG_template_value_parameter,
3534/// scope: !0, name: "V", type: !1,
3535/// value: i32 7)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003536bool LLParser::ParseMDTemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003537#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3538 REQUIRED(tag, DwarfTagField, ); \
3539 REQUIRED(scope, MDField, ); \
3540 OPTIONAL(name, MDStringField, ); \
3541 REQUIRED(type, MDField, ); \
3542 REQUIRED(value, MDField, );
3543 PARSE_MD_FIELDS();
3544#undef VISIT_MD_FIELDS
3545
3546 Result = GET_OR_DISTINCT(
3547 MDTemplateValueParameter,
3548 (Context, tag.Val, scope.Val, name.Val, type.Val, value.Val));
3549 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003550}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003551
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003552/// ParseMDGlobalVariable:
3553/// ::= !MDGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
3554/// file: !1, line: 7, type: !2, isLocal: false,
3555/// isDefinition: true, variable: i32* @foo,
3556/// declaration: !3)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003557bool LLParser::ParseMDGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003558#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3559 OPTIONAL(scope, MDField, ); \
3560 REQUIRED(name, MDStringField, ); \
3561 OPTIONAL(linkageName, MDStringField, ); \
3562 OPTIONAL(file, MDField, ); \
3563 OPTIONAL(line, LineField, ); \
3564 OPTIONAL(type, MDField, ); \
3565 OPTIONAL(isLocal, MDBoolField, ); \
3566 OPTIONAL(isDefinition, MDBoolField, (true)); \
3567 OPTIONAL(variable, MDConstant, ); \
3568 OPTIONAL(declaration, MDField, );
3569 PARSE_MD_FIELDS();
3570#undef VISIT_MD_FIELDS
3571
3572 Result = GET_OR_DISTINCT(MDGlobalVariable,
3573 (Context, scope.Val, name.Val, linkageName.Val,
3574 file.Val, line.Val, type.Val, isLocal.Val,
3575 isDefinition.Val, variable.Val, declaration.Val));
3576 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003577}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003578
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003579/// ParseMDLocalVariable:
3580/// ::= !MDLocalVariable(tag: DW_TAG_arg_variable, scope: !0, name: "foo",
3581/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
3582/// inlinedAt: !3)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003583bool LLParser::ParseMDLocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003584#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3585 REQUIRED(tag, DwarfTagField, ); \
3586 OPTIONAL(scope, MDField, ); \
3587 OPTIONAL(name, MDStringField, ); \
3588 OPTIONAL(file, MDField, ); \
3589 OPTIONAL(line, LineField, ); \
3590 OPTIONAL(type, MDField, ); \
3591 OPTIONAL(arg, MDUnsignedField, (0, UINT8_MAX)); \
3592 OPTIONAL(flags, MDUnsignedField, (0, UINT32_MAX)); \
3593 OPTIONAL(inlinedAt, MDField, );
3594 PARSE_MD_FIELDS();
3595#undef VISIT_MD_FIELDS
3596
3597 Result = GET_OR_DISTINCT(
3598 MDLocalVariable, (Context, tag.Val, scope.Val, name.Val, file.Val,
3599 line.Val, type.Val, arg.Val, flags.Val, inlinedAt.Val));
3600 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003601}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003602
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00003603/// ParseMDExpression:
3604/// ::= !MDExpression(0, 7, -1)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003605bool LLParser::ParseMDExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00003606 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3607 Lex.Lex();
3608
3609 if (ParseToken(lltok::lparen, "expected '(' here"))
3610 return true;
3611
3612 SmallVector<uint64_t, 8> Elements;
3613 if (Lex.getKind() != lltok::rparen)
3614 do {
3615 if (Lex.getKind() == lltok::DwarfOp) {
3616 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
3617 Lex.Lex();
3618 Elements.push_back(Op);
3619 continue;
3620 }
3621 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
3622 }
3623
3624 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3625 return TokError("expected unsigned integer");
3626
3627 auto &U = Lex.getAPSIntVal();
3628 if (U.ugt(UINT64_MAX))
3629 return TokError("element too large, limit is " + Twine(UINT64_MAX));
3630 Elements.push_back(U.getZExtValue());
3631 Lex.Lex();
3632 } while (EatIfPresent(lltok::comma));
3633
3634 if (ParseToken(lltok::rparen, "expected ')' here"))
3635 return true;
3636
3637 Result = GET_OR_DISTINCT(MDExpression, (Context, Elements));
3638 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003639}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00003640
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003641/// ParseMDObjCProperty:
3642/// ::= !MDObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
3643/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003644bool LLParser::ParseMDObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003645#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3646 REQUIRED(name, MDStringField, ); \
3647 OPTIONAL(file, MDField, ); \
3648 OPTIONAL(line, LineField, ); \
3649 OPTIONAL(setter, MDStringField, ); \
3650 OPTIONAL(getter, MDStringField, ); \
3651 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
3652 OPTIONAL(type, MDField, );
3653 PARSE_MD_FIELDS();
3654#undef VISIT_MD_FIELDS
3655
3656 Result = GET_OR_DISTINCT(MDObjCProperty,
3657 (Context, name.Val, file.Val, line.Val, setter.Val,
3658 getter.Val, attributes.Val, type.Val));
3659 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003660}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003661
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00003662/// ParseMDImportedEntity:
3663/// ::= !MDImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
3664/// line: 7, name: "foo")
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003665bool LLParser::ParseMDImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00003666#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3667 REQUIRED(tag, DwarfTagField, ); \
3668 REQUIRED(scope, MDField, ); \
3669 OPTIONAL(entity, MDField, ); \
3670 OPTIONAL(line, LineField, ); \
3671 OPTIONAL(name, MDStringField, );
3672 PARSE_MD_FIELDS();
3673#undef VISIT_MD_FIELDS
3674
3675 Result = GET_OR_DISTINCT(MDImportedEntity, (Context, tag.Val, scope.Val,
3676 entity.Val, line.Val, name.Val));
3677 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003678}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00003679
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003680#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003681#undef NOP_FIELD
3682#undef REQUIRE_FIELD
3683#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003684
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003685/// ParseMetadataAsValue
3686/// ::= metadata i32 %local
3687/// ::= metadata i32 @global
3688/// ::= metadata i32 7
3689/// ::= metadata !0
3690/// ::= metadata !{...}
3691/// ::= metadata !"string"
3692bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
3693 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003694 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003695 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003696 return true;
3697
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003698 V = MetadataAsValue::get(Context, MD);
3699 return false;
3700}
3701
3702/// ParseValueAsMetadata
3703/// ::= i32 %local
3704/// ::= i32 @global
3705/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003706bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
3707 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003708 Type *Ty;
3709 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003710 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003711 return true;
3712 if (Ty->isMetadataTy())
3713 return Error(Loc, "invalid metadata-value-metadata roundtrip");
3714
3715 Value *V;
3716 if (ParseValue(Ty, V, PFS))
3717 return true;
3718
3719 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003720 return false;
3721}
3722
3723/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003724/// ::= i32 %local
3725/// ::= i32 @global
3726/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00003727/// ::= !42
3728/// ::= !{...}
3729/// ::= !"string"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003730/// ::= !MDLocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003731bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003732 if (Lex.getKind() == lltok::MetadataVar) {
3733 MDNode *N;
3734 if (ParseSpecializedMDNode(N))
3735 return true;
3736 MD = N;
3737 return false;
3738 }
3739
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003740 // ValueAsMetadata:
3741 // <type> <value>
3742 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003743 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003744
3745 // '!'.
3746 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
3747 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00003748
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003749 // MDString:
3750 // ::= '!' STRINGCONSTANT
3751 if (Lex.getKind() == lltok::StringConstant) {
3752 MDString *S;
3753 if (ParseMDString(S))
3754 return true;
3755 MD = S;
3756 return false;
3757 }
3758
Dan Gohman8939ba332010-07-14 18:26:50 +00003759 // MDNode:
3760 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003761 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003762 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003763 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003764 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003765 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00003766 return false;
3767}
3768
Victor Hernandez9d75c962010-01-11 22:31:58 +00003769
3770//===----------------------------------------------------------------------===//
3771// Function Parsing.
3772//===----------------------------------------------------------------------===//
3773
Chris Lattner229907c2011-07-18 04:54:35 +00003774bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Victor Hernandez9d75c962010-01-11 22:31:58 +00003775 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00003776 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003777 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003778
Chris Lattnerac161bf2009-01-02 07:01:27 +00003779 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003780 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00003781 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3782 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003783 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003784 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00003785 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3786 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003787 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003788 case ValID::t_InlineAsm: {
Chris Lattner229907c2011-07-18 04:54:35 +00003789 PointerType *PTy = dyn_cast<PointerType>(Ty);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003790 FunctionType *FTy =
Craig Topper2617dcc2014-04-15 06:32:26 +00003791 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003792 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
3793 return Error(ID.Loc, "invalid type for inline asm constraint string");
Chad Rosierf42fad62012-09-05 00:08:17 +00003794 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
Chad Rosierd8c76102012-09-05 19:00:49 +00003795 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003796 return false;
3797 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003798 case ValID::t_GlobalName:
3799 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003800 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003801 case ValID::t_GlobalID:
3802 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003803 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003804 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00003805 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003806 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00003807 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00003808 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003809 return false;
3810 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00003811 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003812 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3813 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003814
Dan Gohman518cda42011-12-17 00:04:22 +00003815 // The lexer has no type info, so builds all half, float, and double FP
3816 // constants as double. Fix this here. Long double does not need this.
3817 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003818 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00003819 if (Ty->isHalfTy())
3820 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3821 &Ignored);
3822 else if (Ty->isFloatTy())
3823 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
3824 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003825 }
Owen Anderson69c464d2009-07-27 20:59:43 +00003826 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003827
Chris Lattner8f57d29e2009-01-05 18:24:23 +00003828 if (V->getType() != Ty)
3829 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003830 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003831
Chris Lattnerac161bf2009-01-02 07:01:27 +00003832 return false;
3833 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00003834 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003835 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003836 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003837 return false;
3838 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00003839 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003840 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00003841 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003842 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003843 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00003844 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00003845 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00003846 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003847 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00003848 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003849 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00003850 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00003851 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003852 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00003853 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003854 return false;
3855 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00003856 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003857 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00003858
Chris Lattnerac161bf2009-01-02 07:01:27 +00003859 V = ID.ConstantVal;
3860 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003861 case ValID::t_ConstantStruct:
3862 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00003863 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003864 if (ST->getNumElements() != ID.UIntVal)
3865 return Error(ID.Loc,
3866 "initializer with struct type has wrong # elements");
3867 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
3868 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003869
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003870 // Verify that the elements are compatible with the structtype.
3871 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
3872 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
3873 return Error(ID.Loc, "element " + Twine(i) +
3874 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003875
Frits van Bommel717d7ed2011-07-18 12:00:32 +00003876 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
3877 ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003878 } else
3879 return Error(ID.Loc, "constant expression type mismatch");
3880 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003881 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00003882 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003883}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003884
Chris Lattner229907c2011-07-18 04:54:35 +00003885bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003886 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003887 ValID ID;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003888 return ParseValID(ID, PFS) ||
3889 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003890}
3891
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003892bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003893 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003894 return ParseType(Ty) ||
3895 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003896}
3897
Chris Lattner3ed871f2009-10-27 19:13:16 +00003898bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
3899 PerFunctionState &PFS) {
3900 Value *V;
3901 Loc = Lex.getLoc();
3902 if (ParseTypeAndValue(V, PFS)) return true;
3903 if (!isa<BasicBlock>(V))
3904 return Error(Loc, "expected a basic block");
3905 BB = cast<BasicBlock>(V);
3906 return false;
3907}
3908
3909
Chris Lattnerac161bf2009-01-02 07:01:27 +00003910/// FunctionHeader
3911/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00003912/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003913/// OptionalAlign OptGC OptionalPrefix OptionalPrologue
Chris Lattnerac161bf2009-01-02 07:01:27 +00003914bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
3915 // Parse the linkage.
3916 LocTy LinkageLoc = Lex.getLoc();
3917 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003918
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00003919 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00003920 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00003921 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00003922 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00003923 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003924 LocTy RetTypeLoc = Lex.getLoc();
3925 if (ParseOptionalLinkage(Linkage) ||
3926 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +00003927 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003928 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00003929 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00003930 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003931 return true;
3932
3933 // Verify that the linkage is ok.
3934 switch ((GlobalValue::LinkageTypes)Linkage) {
3935 case GlobalValue::ExternalLinkage:
3936 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00003937 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003938 if (isDefine)
3939 return Error(LinkageLoc, "invalid linkage for function definition");
3940 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00003941 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003942 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00003943 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00003944 case GlobalValue::LinkOnceAnyLinkage:
3945 case GlobalValue::LinkOnceODRLinkage:
3946 case GlobalValue::WeakAnyLinkage:
3947 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003948 if (!isDefine)
3949 return Error(LinkageLoc, "invalid linkage for function declaration");
3950 break;
3951 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00003952 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003953 return Error(LinkageLoc, "invalid function linkage type");
3954 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003955
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003956 if (!isValidVisibilityForLinkage(Visibility, Linkage))
3957 return Error(LinkageLoc,
3958 "symbol with local linkage must have default visibility");
3959
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003960 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003961 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003962
Chris Lattnerac161bf2009-01-02 07:01:27 +00003963 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00003964
3965 std::string FunctionName;
3966 if (Lex.getKind() == lltok::GlobalVar) {
3967 FunctionName = Lex.getStrVal();
3968 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3969 unsigned NameID = Lex.getUIntVal();
3970
3971 if (NameID != NumberedVals.size())
3972 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00003973 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00003974 } else {
3975 return TokError("expected function name");
3976 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003977
Chris Lattner3822f632009-01-02 08:05:26 +00003978 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003979
Chris Lattner3822f632009-01-02 08:05:26 +00003980 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003981 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003982
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003983 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003984 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00003985 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00003986 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00003987 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003988 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003989 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00003990 std::string GC;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00003991 bool UnnamedAddr;
3992 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00003993 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003994 Constant *Prologue = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00003995 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00003996
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003997 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola563eb4b2011-01-25 19:09:56 +00003998 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3999 &UnnamedAddrLoc) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004000 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004001 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004002 (EatIfPresent(lltok::kw_section) &&
4003 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00004004 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004005 ParseOptionalAlignment(Alignment) ||
4006 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004007 ParseStringConstant(GC)) ||
4008 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004009 ParseGlobalTypeAndValue(Prefix)) ||
4010 (EatIfPresent(lltok::kw_prologue) &&
4011 ParseGlobalTypeAndValue(Prologue)))
Chris Lattner3822f632009-01-02 08:05:26 +00004012 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004013
Michael Gottesman41748d72013-06-27 00:25:01 +00004014 if (FuncAttrs.contains(Attribute::Builtin))
4015 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00004016
Chris Lattnerac161bf2009-01-02 07:01:27 +00004017 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00004018 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00004019 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004020 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004021 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004022
Chris Lattnerac161bf2009-01-02 07:01:27 +00004023 // Okay, if we got here, the function is syntactically valid. Convert types
4024 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00004025 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00004026 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004027
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004028 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004029 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4030 AttributeSet::ReturnIndex,
4031 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004032
Chris Lattnerac161bf2009-01-02 07:01:27 +00004033 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004034 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004035 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4036 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004037 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4038 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004039 }
4040
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004041 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004042 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4043 AttributeSet::FunctionIndex,
4044 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004045
Bill Wendlinge94d8432012-12-07 23:16:57 +00004046 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004047
Bill Wendling749a43d2012-12-30 13:50:49 +00004048 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004049 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4050
Chris Lattner229907c2011-07-18 04:54:35 +00004051 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00004052 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00004053 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004054
Craig Topper2617dcc2014-04-15 06:32:26 +00004055 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004056 if (!FunctionName.empty()) {
4057 // If this was a definition of a forward reference, remove the definition
4058 // from the forward reference table and fill in the forward ref.
4059 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
4060 ForwardRefVals.find(FunctionName);
4061 if (FRVI != ForwardRefVals.end()) {
4062 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00004063 if (!Fn)
4064 return Error(FRVI->second.second, "invalid forward reference to "
4065 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00004066 if (Fn->getType() != PFT)
4067 return Error(FRVI->second.second, "invalid forward reference to "
4068 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004069
Chris Lattnerac161bf2009-01-02 07:01:27 +00004070 ForwardRefVals.erase(FRVI);
4071 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00004072 // Reject redefinitions.
4073 return Error(NameLoc, "invalid redefinition of function '" +
4074 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00004075 } else if (M->getNamedValue(FunctionName)) {
4076 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004077 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004078
Dan Gohman399d6ae2009-08-29 23:37:49 +00004079 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004080 // If this is a definition of a forward referenced function, make sure the
4081 // types agree.
4082 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
4083 = ForwardRefValIDs.find(NumberedVals.size());
4084 if (I != ForwardRefValIDs.end()) {
4085 Fn = cast<Function>(I->second.first);
4086 if (Fn->getType() != PFT)
4087 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004088 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004089 ForwardRefValIDs.erase(I);
4090 }
4091 }
4092
Craig Topper2617dcc2014-04-15 06:32:26 +00004093 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004094 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4095 else // Move the forward-reference to the correct spot in the module.
4096 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4097
4098 if (FunctionName.empty())
4099 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004100
Chris Lattnerac161bf2009-01-02 07:01:27 +00004101 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4102 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00004103 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004104 Fn->setCallingConv(CC);
4105 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004106 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004107 Fn->setAlignment(Alignment);
4108 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00004109 Fn->setComdat(C);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004110 if (!GC.empty()) Fn->setGC(GC.c_str());
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004111 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004112 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004113 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004114
Chris Lattnerac161bf2009-01-02 07:01:27 +00004115 // Add all of the arguments we parsed to the function.
4116 Function::arg_iterator ArgIt = Fn->arg_begin();
4117 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4118 // If the argument has a name, insert it into the argument symbol table.
4119 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004120
Chris Lattnerac161bf2009-01-02 07:01:27 +00004121 // Set the name, if it conflicted, it will be auto-renamed.
4122 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004123
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00004124 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004125 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4126 ArgList[i].Name + "'");
4127 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004128
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004129 if (isDefine)
4130 return false;
4131
Robin Morisset039781e2014-08-29 21:53:01 +00004132 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004133 ValID ID;
4134 if (FunctionName.empty()) {
4135 ID.Kind = ValID::t_GlobalID;
4136 ID.UIntVal = NumberedVals.size() - 1;
4137 } else {
4138 ID.Kind = ValID::t_GlobalName;
4139 ID.StrVal = FunctionName;
4140 }
4141 auto Blocks = ForwardRefBlockAddresses.find(ID);
4142 if (Blocks != ForwardRefBlockAddresses.end())
4143 return Error(Blocks->first.Loc,
4144 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004145 return false;
4146}
4147
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004148bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4149 ValID ID;
4150 if (FunctionNumber == -1) {
4151 ID.Kind = ValID::t_GlobalName;
4152 ID.StrVal = F.getName();
4153 } else {
4154 ID.Kind = ValID::t_GlobalID;
4155 ID.UIntVal = FunctionNumber;
4156 }
4157
4158 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4159 if (Blocks == P.ForwardRefBlockAddresses.end())
4160 return false;
4161
4162 for (const auto &I : Blocks->second) {
4163 const ValID &BBID = I.first;
4164 GlobalValue *GV = I.second;
4165
4166 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4167 "Expected local id or name");
4168 BasicBlock *BB;
4169 if (BBID.Kind == ValID::t_LocalName)
4170 BB = GetBB(BBID.StrVal, BBID.Loc);
4171 else
4172 BB = GetBB(BBID.UIntVal, BBID.Loc);
4173 if (!BB)
4174 return P.Error(BBID.Loc, "referenced value is not a basic block");
4175
4176 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4177 GV->eraseFromParent();
4178 }
4179
4180 P.ForwardRefBlockAddresses.erase(Blocks);
4181 return false;
4182}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004183
4184/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004185/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00004186bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00004187 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004188 return TokError("expected '{' in function body");
4189 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004190
Chris Lattner3432c622009-10-28 03:39:23 +00004191 int FunctionNumber = -1;
4192 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004193
Chris Lattner3432c622009-10-28 03:39:23 +00004194 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004195
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004196 // Resolve block addresses and allow basic blocks to be forward-declared
4197 // within this function.
4198 if (PFS.resolveForwardRefBlockAddresses())
4199 return true;
4200 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4201
Chris Lattnerbbddd962010-01-09 19:20:07 +00004202 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004203 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00004204 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004205
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004206 while (Lex.getKind() != lltok::rbrace &&
4207 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004208 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004209
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004210 while (Lex.getKind() != lltok::rbrace)
4211 if (ParseUseListOrder(&PFS))
4212 return true;
4213
Chris Lattnerac161bf2009-01-02 07:01:27 +00004214 // Eat the }.
4215 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004216
Chris Lattnerac161bf2009-01-02 07:01:27 +00004217 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00004218 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004219}
4220
4221/// ParseBasicBlock
4222/// ::= LabelStr? Instruction*
4223bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4224 // If this basic block starts out with a name, remember it.
4225 std::string Name;
4226 LocTy NameLoc = Lex.getLoc();
4227 if (Lex.getKind() == lltok::LabelStr) {
4228 Name = Lex.getStrVal();
4229 Lex.Lex();
4230 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004231
Chris Lattnerac161bf2009-01-02 07:01:27 +00004232 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004233 if (!BB) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004234
Chris Lattnerac161bf2009-01-02 07:01:27 +00004235 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004236
Chris Lattnerac161bf2009-01-02 07:01:27 +00004237 // Parse the instructions in this block until we get a terminator.
4238 Instruction *Inst;
4239 do {
4240 // This instruction may have three possibilities for a name: a) none
4241 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4242 LocTy NameLoc = Lex.getLoc();
4243 int NameID = -1;
4244 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004245
Chris Lattnerac161bf2009-01-02 07:01:27 +00004246 if (Lex.getKind() == lltok::LocalVarID) {
4247 NameID = Lex.getUIntVal();
4248 Lex.Lex();
4249 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4250 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00004251 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004252 NameStr = Lex.getStrVal();
4253 Lex.Lex();
4254 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4255 return true;
4256 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004257
Chris Lattner77b89dc2009-12-30 05:23:43 +00004258 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00004259 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00004260 case InstError: return true;
4261 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004262 BB->getInstList().push_back(Inst);
4263
Chris Lattner77b89dc2009-12-30 05:23:43 +00004264 // With a normal result, we check to see if the instruction is followed by
4265 // a comma and metadata.
4266 if (EatIfPresent(lltok::comma))
Dan Gohman338d9a42010-08-24 02:05:17 +00004267 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004268 return true;
4269 break;
4270 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004271 BB->getInstList().push_back(Inst);
4272
Chris Lattner77b89dc2009-12-30 05:23:43 +00004273 // If the instruction parser ate an extra comma at the end of it, it
4274 // *must* be followed by metadata.
Dan Gohman338d9a42010-08-24 02:05:17 +00004275 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004276 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004277 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00004278 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004279
Chris Lattnerac161bf2009-01-02 07:01:27 +00004280 // Set the name on the instruction.
4281 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4282 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004283
Chris Lattnerac161bf2009-01-02 07:01:27 +00004284 return false;
4285}
4286
4287//===----------------------------------------------------------------------===//
4288// Instruction Parsing.
4289//===----------------------------------------------------------------------===//
4290
4291/// ParseInstruction - Parse one of the many different instructions.
4292///
Chris Lattner77b89dc2009-12-30 05:23:43 +00004293int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4294 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004295 lltok::Kind Token = Lex.getKind();
4296 if (Token == lltok::Eof)
4297 return TokError("found end of file when expecting more instructions");
4298 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00004299 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004300 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004301
Chris Lattnerac161bf2009-01-02 07:01:27 +00004302 switch (Token) {
4303 default: return Error(Loc, "expected instruction opcode");
4304 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00004305 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004306 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
4307 case lltok::kw_br: return ParseBr(Inst, PFS);
4308 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004309 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004310 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00004311 case lltok::kw_resume: return ParseResume(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004312 // Binary Operators.
4313 case lltok::kw_add:
4314 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004315 case lltok::kw_mul:
4316 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00004317 bool NUW = EatIfPresent(lltok::kw_nuw);
4318 bool NSW = EatIfPresent(lltok::kw_nsw);
4319 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004320
Chris Lattnera676c0f2011-02-07 16:40:21 +00004321 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004322
Chris Lattnera676c0f2011-02-07 16:40:21 +00004323 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4324 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4325 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004326 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004327 case lltok::kw_fadd:
4328 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00004329 case lltok::kw_fmul:
4330 case lltok::kw_fdiv:
4331 case lltok::kw_frem: {
4332 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4333 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4334 if (Res != 0)
4335 return Res;
4336 if (FMF.any())
4337 Inst->setFastMathFlags(FMF);
4338 return 0;
4339 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004340
Chris Lattner35315d02011-02-06 21:44:57 +00004341 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004342 case lltok::kw_udiv:
4343 case lltok::kw_lshr:
4344 case lltok::kw_ashr: {
4345 bool Exact = EatIfPresent(lltok::kw_exact);
4346
4347 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4348 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4349 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004350 }
4351
Chris Lattnerac161bf2009-01-02 07:01:27 +00004352 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00004353 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004354 case lltok::kw_and:
4355 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00004356 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004357 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004358 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004359 // Casts.
4360 case lltok::kw_trunc:
4361 case lltok::kw_zext:
4362 case lltok::kw_sext:
4363 case lltok::kw_fptrunc:
4364 case lltok::kw_fpext:
4365 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004366 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004367 case lltok::kw_uitofp:
4368 case lltok::kw_sitofp:
4369 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004370 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004371 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00004372 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004373 // Other.
4374 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00004375 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004376 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
4377 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
4378 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
4379 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00004380 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00004381 // Call.
4382 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
4383 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
4384 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004385 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00004386 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00004387 case lltok::kw_load: return ParseLoad(Inst, PFS);
4388 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00004389 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
4390 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00004391 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004392 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
4393 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
4394 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
4395 }
4396}
4397
4398/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
4399bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004400 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004401 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00004402 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004403 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
4404 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
4405 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
4406 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
4407 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
4408 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
4409 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
4410 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
4411 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
4412 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
4413 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
4414 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
4415 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
4416 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
4417 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
4418 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
4419 }
4420 } else {
4421 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00004422 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004423 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
4424 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
4425 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
4426 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
4427 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
4428 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
4429 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
4430 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
4431 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
4432 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
4433 }
4434 }
4435 Lex.Lex();
4436 return false;
4437}
4438
4439//===----------------------------------------------------------------------===//
4440// Terminator Instructions.
4441//===----------------------------------------------------------------------===//
4442
4443/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00004444/// ::= 'ret' void (',' !dbg, !1)*
4445/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00004446bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004447 PerFunctionState &PFS) {
4448 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00004449 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00004450 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004451
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004452 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004453
Chris Lattnerfdd87902009-10-05 05:54:46 +00004454 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004455 if (!ResType->isVoidTy())
4456 return Error(TypeLoc, "value doesn't match function result type '" +
4457 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004458
Owen Anderson55f1c092009-08-13 21:58:54 +00004459 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004460 return false;
4461 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004462
Chris Lattnerac161bf2009-01-02 07:01:27 +00004463 Value *RV;
4464 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004465
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004466 if (ResType != RV->getType())
4467 return Error(TypeLoc, "value doesn't match function result type '" +
4468 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004469
Owen Anderson55f1c092009-08-13 21:58:54 +00004470 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00004471 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004472}
4473
4474
4475/// ParseBr
4476/// ::= 'br' TypeAndValue
4477/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4478bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
4479 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00004480 Value *Op0;
4481 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004482 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004483
Chris Lattnerac161bf2009-01-02 07:01:27 +00004484 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
4485 Inst = BranchInst::Create(BB);
4486 return false;
4487 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004488
Owen Anderson55f1c092009-08-13 21:58:54 +00004489 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004490 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004491
Chris Lattnerac161bf2009-01-02 07:01:27 +00004492 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004493 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004494 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004495 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004496 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004497
Chris Lattner3ed871f2009-10-27 19:13:16 +00004498 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004499 return false;
4500}
4501
4502/// ParseSwitch
4503/// Instruction
4504/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
4505/// JumpTable
4506/// ::= (TypeAndValue ',' TypeAndValue)*
4507bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
4508 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00004509 Value *Cond;
4510 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004511 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
4512 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004513 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004514 ParseToken(lltok::lsquare, "expected '[' with switch table"))
4515 return true;
4516
Duncan Sands19d0b472010-02-16 11:11:14 +00004517 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004518 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004519
Chris Lattnerac161bf2009-01-02 07:01:27 +00004520 // Parse the jump table pairs.
4521 SmallPtrSet<Value*, 32> SeenCases;
4522 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
4523 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00004524 Value *Constant;
4525 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004526
Chris Lattnerac161bf2009-01-02 07:01:27 +00004527 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
4528 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004529 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004530 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004531
David Blaikie70573dc2014-11-19 07:49:26 +00004532 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004533 return Error(CondLoc, "duplicate case value in switch");
4534 if (!isa<ConstantInt>(Constant))
4535 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004536
Chris Lattner3ed871f2009-10-27 19:13:16 +00004537 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004538 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004539
Chris Lattnerac161bf2009-01-02 07:01:27 +00004540 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004541
Chris Lattner3ed871f2009-10-27 19:13:16 +00004542 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004543 for (unsigned i = 0, e = Table.size(); i != e; ++i)
4544 SI->addCase(Table[i].first, Table[i].second);
4545 Inst = SI;
4546 return false;
4547}
4548
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004549/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00004550/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004551/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
4552bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00004553 LocTy AddrLoc;
4554 Value *Address;
4555 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004556 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
4557 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00004558 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004559
Duncan Sands19d0b472010-02-16 11:11:14 +00004560 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004561 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004562
Chris Lattner3ed871f2009-10-27 19:13:16 +00004563 // Parse the destination list.
4564 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004565
Chris Lattner3ed871f2009-10-27 19:13:16 +00004566 if (Lex.getKind() != lltok::rsquare) {
4567 BasicBlock *DestBB;
4568 if (ParseTypeAndBasicBlock(DestBB, PFS))
4569 return true;
4570 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004571
Chris Lattner3ed871f2009-10-27 19:13:16 +00004572 while (EatIfPresent(lltok::comma)) {
4573 if (ParseTypeAndBasicBlock(DestBB, PFS))
4574 return true;
4575 DestList.push_back(DestBB);
4576 }
4577 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004578
Chris Lattner3ed871f2009-10-27 19:13:16 +00004579 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
4580 return true;
4581
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004582 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00004583 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
4584 IBI->addDestination(DestList[i]);
4585 Inst = IBI;
4586 return false;
4587}
4588
4589
Chris Lattnerac161bf2009-01-02 07:01:27 +00004590/// ParseInvoke
4591/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
4592/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
4593bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
4594 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00004595 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004596 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00004597 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004598 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004599 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004600 LocTy RetTypeLoc;
4601 ValID CalleeID;
4602 SmallVector<ParamInfo, 16> ArgList;
4603
Chris Lattner3ed871f2009-10-27 19:13:16 +00004604 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004605 if (ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004606 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004607 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004608 ParseValID(CalleeID) ||
4609 ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004610 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4611 NoBuiltinLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004612 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004613 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004614 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004615 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004616 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004617
Chris Lattnerac161bf2009-01-02 07:01:27 +00004618 // If RetType is a non-function pointer type, then this is the short syntax
4619 // for the call, which means that RetType is just the return type. Infer the
4620 // rest of the function argument types from the arguments that are present.
Craig Topper2617dcc2014-04-15 06:32:26 +00004621 PointerType *PFTy = nullptr;
4622 FunctionType *Ty = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004623 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4624 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4625 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00004626 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004627 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4628 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004629
Chris Lattnerac161bf2009-01-02 07:01:27 +00004630 if (!FunctionType::isValidReturnType(RetType))
4631 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004632
Owen Anderson4056ca92009-07-29 22:17:13 +00004633 Ty = FunctionType::get(RetType, ParamTypes, false);
4634 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004635 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004636
Chris Lattnerac161bf2009-01-02 07:01:27 +00004637 // Look up the callee.
4638 Value *Callee;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004639 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004640
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004641 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00004642 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004643 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004644 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4645 AttributeSet::ReturnIndex,
4646 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004647
Chris Lattnerac161bf2009-01-02 07:01:27 +00004648 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004649
Chris Lattnerac161bf2009-01-02 07:01:27 +00004650 // Loop through FunctionType's arguments and ensure they are specified
4651 // correctly. Also, gather any parameter attributes.
4652 FunctionType::param_iterator I = Ty->param_begin();
4653 FunctionType::param_iterator E = Ty->param_end();
4654 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004655 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004656 if (I != E) {
4657 ExpectedTy = *I++;
4658 } else if (!Ty->isVarArg()) {
4659 return Error(ArgList[i].Loc, "too many arguments specified");
4660 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004661
Chris Lattnerac161bf2009-01-02 07:01:27 +00004662 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4663 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004664 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004665 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004666 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4667 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004668 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4669 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004670 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004671
Chris Lattnerac161bf2009-01-02 07:01:27 +00004672 if (I != E)
4673 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004674
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004675 if (FnAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004676 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4677 AttributeSet::FunctionIndex,
4678 FnAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004679
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004680 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00004681 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004682
Jay Foad5bd375a2011-07-15 08:37:34 +00004683 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004684 II->setCallingConv(CC);
4685 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004686 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004687 Inst = II;
4688 return false;
4689}
4690
Bill Wendlingf891bf82011-07-31 06:30:59 +00004691/// ParseResume
4692/// ::= 'resume' TypeAndValue
4693bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
4694 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00004695 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
4696 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004697
Bill Wendlingf891bf82011-07-31 06:30:59 +00004698 ResumeInst *RI = ResumeInst::Create(Exn);
4699 Inst = RI;
4700 return false;
4701}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004702
4703//===----------------------------------------------------------------------===//
4704// Binary Operators.
4705//===----------------------------------------------------------------------===//
4706
4707/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004708/// ::= ArithmeticOps TypeAndValue ',' Value
4709///
4710/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
4711/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00004712bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004713 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004714 LocTy Loc; Value *LHS, *RHS;
4715 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4716 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
4717 ParseValue(LHS->getType(), RHS, PFS))
4718 return true;
4719
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004720 bool Valid;
4721 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00004722 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004723 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00004724 Valid = LHS->getType()->isIntOrIntVectorTy() ||
4725 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004726 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00004727 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
4728 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004729 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004730
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004731 if (!Valid)
4732 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004733
Chris Lattnerac161bf2009-01-02 07:01:27 +00004734 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4735 return false;
4736}
4737
4738/// ParseLogical
4739/// ::= ArithmeticOps TypeAndValue ',' Value {
4740bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
4741 unsigned Opc) {
4742 LocTy Loc; Value *LHS, *RHS;
4743 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4744 ParseToken(lltok::comma, "expected ',' in logical operation") ||
4745 ParseValue(LHS->getType(), RHS, PFS))
4746 return true;
4747
Duncan Sands9dff9be2010-02-15 16:12:20 +00004748 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004749 return Error(Loc,"instruction requires integer or integer vector operands");
4750
4751 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4752 return false;
4753}
4754
4755
4756/// ParseCompare
4757/// ::= 'icmp' IPredicates TypeAndValue ',' Value
4758/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00004759bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
4760 unsigned Opc) {
4761 // Parse the integer/fp comparison predicate.
4762 LocTy Loc;
4763 unsigned Pred;
4764 Value *LHS, *RHS;
4765 if (ParseCmpPredicate(Pred, Opc) ||
4766 ParseTypeAndValue(LHS, Loc, PFS) ||
4767 ParseToken(lltok::comma, "expected ',' after compare value") ||
4768 ParseValue(LHS->getType(), RHS, PFS))
4769 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004770
Chris Lattnerac161bf2009-01-02 07:01:27 +00004771 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00004772 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004773 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00004774 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004775 } else {
4776 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00004777 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00004778 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004779 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00004780 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004781 }
4782 return false;
4783}
4784
4785//===----------------------------------------------------------------------===//
4786// Other Instructions.
4787//===----------------------------------------------------------------------===//
4788
4789
4790/// ParseCast
4791/// ::= CastOpc TypeAndValue 'to' Type
4792bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
4793 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004794 LocTy Loc;
4795 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00004796 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004797 if (ParseTypeAndValue(Op, Loc, PFS) ||
4798 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
4799 ParseType(DestTy))
4800 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004801
Chris Lattner89d856e2009-03-01 00:53:13 +00004802 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
4803 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004804 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004805 getTypeString(Op->getType()) + "' to '" +
4806 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00004807 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004808 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
4809 return false;
4810}
4811
4812/// ParseSelect
4813/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4814bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
4815 LocTy Loc;
4816 Value *Op0, *Op1, *Op2;
4817 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4818 ParseToken(lltok::comma, "expected ',' after select condition") ||
4819 ParseTypeAndValue(Op1, PFS) ||
4820 ParseToken(lltok::comma, "expected ',' after select value") ||
4821 ParseTypeAndValue(Op2, PFS))
4822 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004823
Chris Lattnerac161bf2009-01-02 07:01:27 +00004824 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
4825 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004826
Chris Lattnerac161bf2009-01-02 07:01:27 +00004827 Inst = SelectInst::Create(Op0, Op1, Op2);
4828 return false;
4829}
4830
Chris Lattnerb55ab542009-01-05 08:18:44 +00004831/// ParseVA_Arg
4832/// ::= 'va_arg' TypeAndValue ',' Type
4833bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004834 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00004835 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00004836 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004837 if (ParseTypeAndValue(Op, PFS) ||
4838 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00004839 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004840 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004841
Chris Lattnerb55ab542009-01-05 08:18:44 +00004842 if (!EltTy->isFirstClassType())
4843 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004844
4845 Inst = new VAArgInst(Op, EltTy);
4846 return false;
4847}
4848
4849/// ParseExtractElement
4850/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
4851bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
4852 LocTy Loc;
4853 Value *Op0, *Op1;
4854 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4855 ParseToken(lltok::comma, "expected ',' after extract value") ||
4856 ParseTypeAndValue(Op1, PFS))
4857 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004858
Chris Lattnerac161bf2009-01-02 07:01:27 +00004859 if (!ExtractElementInst::isValidOperands(Op0, Op1))
4860 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004861
Eric Christopherc9742252009-07-25 02:28:41 +00004862 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004863 return false;
4864}
4865
4866/// ParseInsertElement
4867/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4868bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
4869 LocTy Loc;
4870 Value *Op0, *Op1, *Op2;
4871 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4872 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4873 ParseTypeAndValue(Op1, PFS) ||
4874 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4875 ParseTypeAndValue(Op2, PFS))
4876 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004877
Chris Lattnerac161bf2009-01-02 07:01:27 +00004878 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00004879 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004880
Chris Lattnerac161bf2009-01-02 07:01:27 +00004881 Inst = InsertElementInst::Create(Op0, Op1, Op2);
4882 return false;
4883}
4884
4885/// ParseShuffleVector
4886/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4887bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
4888 LocTy Loc;
4889 Value *Op0, *Op1, *Op2;
4890 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4891 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
4892 ParseTypeAndValue(Op1, PFS) ||
4893 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
4894 ParseTypeAndValue(Op2, PFS))
4895 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004896
Chris Lattnerac161bf2009-01-02 07:01:27 +00004897 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00004898 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004899
Chris Lattnerac161bf2009-01-02 07:01:27 +00004900 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
4901 return false;
4902}
4903
4904/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00004905/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00004906int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004907 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004908 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004909
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004910 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004911 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4912 ParseValue(Ty, Op0, PFS) ||
4913 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00004914 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004915 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4916 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004917
Chris Lattnerf4f03422009-12-30 05:27:33 +00004918 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004919 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
4920 while (1) {
4921 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004922
Chris Lattner3822f632009-01-02 08:05:26 +00004923 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004924 break;
4925
Chris Lattnerf4f03422009-12-30 05:27:33 +00004926 if (Lex.getKind() == lltok::MetadataVar) {
4927 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00004928 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004929 }
Devang Patel8f842d32009-10-16 18:45:49 +00004930
Chris Lattner3822f632009-01-02 08:05:26 +00004931 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004932 ParseValue(Ty, Op0, PFS) ||
4933 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00004934 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004935 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4936 return true;
4937 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004938
Chris Lattnerac161bf2009-01-02 07:01:27 +00004939 if (!Ty->isFirstClassType())
4940 return Error(TypeLoc, "phi node must have first class type");
4941
Jay Foad52131342011-03-30 11:28:46 +00004942 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004943 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
4944 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
4945 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004946 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004947}
4948
Bill Wendlingfae14752011-08-12 20:24:12 +00004949/// ParseLandingPad
4950/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
4951/// Clause
4952/// ::= 'catch' TypeAndValue
4953/// ::= 'filter'
4954/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
4955bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004956 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00004957 Value *PersFn; LocTy PersFnLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00004958
4959 if (ParseType(Ty, TyLoc) ||
4960 ParseToken(lltok::kw_personality, "expected 'personality'") ||
4961 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
4962 return true;
4963
4964 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
4965 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
4966
4967 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
4968 LandingPadInst::ClauseType CT;
4969 if (EatIfPresent(lltok::kw_catch))
4970 CT = LandingPadInst::Catch;
4971 else if (EatIfPresent(lltok::kw_filter))
4972 CT = LandingPadInst::Filter;
4973 else
4974 return TokError("expected 'catch' or 'filter' clause type");
4975
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00004976 Value *V;
4977 LocTy VLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00004978 if (ParseTypeAndValue(V, VLoc, PFS)) {
4979 delete LP;
4980 return true;
4981 }
4982
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00004983 // A 'catch' type expects a non-array constant. A filter clause expects an
4984 // array constant.
4985 if (CT == LandingPadInst::Catch) {
4986 if (isa<ArrayType>(V->getType()))
4987 Error(VLoc, "'catch' clause has an invalid type");
4988 } else {
4989 if (!isa<ArrayType>(V->getType()))
4990 Error(VLoc, "'filter' clause has an invalid type");
4991 }
4992
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00004993 LP->addClause(cast<Constant>(V));
Bill Wendlingfae14752011-08-12 20:24:12 +00004994 }
4995
4996 Inst = LP;
4997 return false;
4998}
4999
Chris Lattnerac161bf2009-01-02 07:01:27 +00005000/// ParseCall
Reid Kleckner5772b772014-04-24 20:14:34 +00005001/// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
5002/// ParameterList OptionalAttrs
5003/// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
5004/// ParameterList OptionalAttrs
5005/// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005006/// ParameterList OptionalAttrs
5007bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00005008 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00005009 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005010 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005011 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005012 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005013 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005014 LocTy RetTypeLoc;
5015 ValID CalleeID;
5016 SmallVector<ParamInfo, 16> ArgList;
5017 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005018
Reid Kleckner5772b772014-04-24 20:14:34 +00005019 if ((TCK != CallInst::TCK_None &&
5020 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005021 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00005022 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005023 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005024 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00005025 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5026 PFS.getFunction().isVarArg()) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005027 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00005028 BuiltinLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005029 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005030
Chris Lattnerac161bf2009-01-02 07:01:27 +00005031 // If RetType is a non-function pointer type, then this is the short syntax
5032 // for the call, which means that RetType is just the return type. Infer the
5033 // rest of the function argument types from the arguments that are present.
Craig Topper2617dcc2014-04-15 06:32:26 +00005034 PointerType *PFTy = nullptr;
5035 FunctionType *Ty = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005036 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
5037 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
5038 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005039 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00005040 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5041 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005042
Chris Lattnerac161bf2009-01-02 07:01:27 +00005043 if (!FunctionType::isValidReturnType(RetType))
5044 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005045
Owen Anderson4056ca92009-07-29 22:17:13 +00005046 Ty = FunctionType::get(RetType, ParamTypes, false);
5047 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005048 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005049
Chris Lattnerac161bf2009-01-02 07:01:27 +00005050 // Look up the callee.
5051 Value *Callee;
Victor Hernandez9d75c962010-01-11 22:31:58 +00005052 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005053
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005054 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005055 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005056 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005057 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5058 AttributeSet::ReturnIndex,
5059 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005060
Chris Lattnerac161bf2009-01-02 07:01:27 +00005061 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005062
Chris Lattnerac161bf2009-01-02 07:01:27 +00005063 // Loop through FunctionType's arguments and ensure they are specified
5064 // correctly. Also, gather any parameter attributes.
5065 FunctionType::param_iterator I = Ty->param_begin();
5066 FunctionType::param_iterator E = Ty->param_end();
5067 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005068 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005069 if (I != E) {
5070 ExpectedTy = *I++;
5071 } else if (!Ty->isVarArg()) {
5072 return Error(ArgList[i].Loc, "too many arguments specified");
5073 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005074
Chris Lattnerac161bf2009-01-02 07:01:27 +00005075 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5076 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005077 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005078 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005079 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5080 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005081 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5082 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005083 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005084
Chris Lattnerac161bf2009-01-02 07:01:27 +00005085 if (I != E)
5086 return Error(CallLoc, "not enough parameters specified for call");
5087
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005088 if (FnAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005089 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5090 AttributeSet::FunctionIndex,
5091 FnAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00005092
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005093 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005094 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005095
Jay Foad5bd375a2011-07-15 08:37:34 +00005096 CallInst *CI = CallInst::Create(Callee, Args);
Reid Kleckner5772b772014-04-24 20:14:34 +00005097 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005098 CI->setCallingConv(CC);
5099 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005100 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005101 Inst = CI;
5102 return false;
5103}
5104
5105//===----------------------------------------------------------------------===//
5106// Memory Instructions.
5107//===----------------------------------------------------------------------===//
5108
5109/// ParseAlloc
David Majnemerc4ab61c2014-03-09 06:41:58 +00005110/// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00005111int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005112 Value *Size = nullptr;
David Majnemera3b0eb22015-02-16 08:38:03 +00005113 LocTy SizeLoc, TyLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005114 unsigned Alignment = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00005115 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00005116
5117 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
5118
David Majnemera3b0eb22015-02-16 08:38:03 +00005119 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005120
David Majnemera3b0eb22015-02-16 08:38:03 +00005121 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5122 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00005123
Chris Lattnerb2f39502009-12-30 05:44:30 +00005124 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00005125 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00005126 if (Lex.getKind() == lltok::kw_align) {
5127 if (ParseOptionalAlignment(Alignment)) return true;
5128 } else if (Lex.getKind() == lltok::MetadataVar) {
5129 AteExtraComma = true;
5130 } else {
5131 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5132 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5133 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005134 }
5135 }
5136
Dan Gohman2140a742010-05-28 01:14:11 +00005137 if (Size && !Size->getType()->isIntegerTy())
5138 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005139
Reid Kleckner436c42e2014-01-17 23:58:17 +00005140 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5141 AI->setUsedWithInAlloca(IsInAlloca);
5142 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00005143 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005144}
5145
5146/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00005147/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005148/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00005149/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005150int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005151 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005152 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005153 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005154 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00005155 AtomicOrdering Ordering = NotAtomic;
5156 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005157
5158 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005159 isAtomic = true;
5160 Lex.Lex();
5161 }
5162
Chris Lattnerbc639292011-11-27 06:56:53 +00005163 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005164 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005165 isVolatile = true;
5166 Lex.Lex();
5167 }
5168
Chris Lattnerb2f39502009-12-30 05:44:30 +00005169 if (ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005170 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005171 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5172 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005173
Duncan Sands19d0b472010-02-16 11:11:14 +00005174 if (!Val->getType()->isPointerTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005175 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
5176 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00005177 if (isAtomic && !Alignment)
5178 return Error(Loc, "atomic load must have explicit non-zero alignment");
5179 if (Ordering == Release || Ordering == AcquireRelease)
5180 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005181
Eli Friedman59b66882011-08-09 23:02:53 +00005182 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00005183 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005184}
5185
5186/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00005187
5188/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
5189/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00005190/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005191int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005192 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005193 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005194 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005195 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00005196 AtomicOrdering Ordering = NotAtomic;
5197 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005198
5199 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005200 isAtomic = true;
5201 Lex.Lex();
5202 }
5203
Chris Lattnerbc639292011-11-27 06:56:53 +00005204 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005205 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005206 isVolatile = true;
5207 Lex.Lex();
5208 }
5209
Chris Lattnerac161bf2009-01-02 07:01:27 +00005210 if (ParseTypeAndValue(Val, Loc, PFS) ||
5211 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005212 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005213 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005214 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005215 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00005216
Duncan Sands19d0b472010-02-16 11:11:14 +00005217 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005218 return Error(PtrLoc, "store operand must be a pointer");
5219 if (!Val->getType()->isFirstClassType())
5220 return Error(Loc, "store operand must be a first class value");
5221 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5222 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00005223 if (isAtomic && !Alignment)
5224 return Error(Loc, "atomic store must have explicit non-zero alignment");
5225 if (Ordering == Acquire || Ordering == AcquireRelease)
5226 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005227
Eli Friedman59b66882011-08-09 23:02:53 +00005228 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00005229 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005230}
5231
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005232/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00005233/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
5234/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00005235int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005236 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
5237 bool AteExtraComma = false;
Tim Northovere94a5182014-03-11 10:48:52 +00005238 AtomicOrdering SuccessOrdering = NotAtomic;
5239 AtomicOrdering FailureOrdering = NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005240 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005241 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00005242 bool isWeak = false;
5243
5244 if (EatIfPresent(lltok::kw_weak))
5245 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00005246
5247 if (EatIfPresent(lltok::kw_volatile))
5248 isVolatile = true;
5249
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005250 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5251 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
5252 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
5253 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
5254 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00005255 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
5256 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005257 return true;
5258
Tim Northovere94a5182014-03-11 10:48:52 +00005259 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005260 return TokError("cmpxchg cannot be unordered");
Tim Northovere94a5182014-03-11 10:48:52 +00005261 if (SuccessOrdering < FailureOrdering)
5262 return TokError("cmpxchg must be at least as ordered on success as failure");
5263 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
5264 return TokError("cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005265 if (!Ptr->getType()->isPointerTy())
5266 return Error(PtrLoc, "cmpxchg operand must be a pointer");
5267 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
5268 return Error(CmpLoc, "compare value and pointer type do not match");
5269 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
5270 return Error(NewLoc, "new value and pointer type do not match");
5271 if (!New->getType()->isIntegerTy())
5272 return Error(NewLoc, "cmpxchg operand must be an integer");
5273 unsigned Size = New->getType()->getPrimitiveSizeInBits();
5274 if (Size < 8 || (Size & (Size - 1)))
5275 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
5276 " integer");
5277
Tim Northover420a2162014-06-13 14:24:07 +00005278 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
5279 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005280 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00005281 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005282 Inst = CXI;
5283 return AteExtraComma ? InstExtraComma : InstNormal;
5284}
5285
5286/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00005287/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
5288/// 'singlethread'? AtomicOrdering
5289int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005290 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
5291 bool AteExtraComma = false;
5292 AtomicOrdering Ordering = NotAtomic;
5293 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005294 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005295 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00005296
5297 if (EatIfPresent(lltok::kw_volatile))
5298 isVolatile = true;
5299
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005300 switch (Lex.getKind()) {
5301 default: return TokError("expected binary operation in atomicrmw");
5302 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
5303 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
5304 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
5305 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
5306 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
5307 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
5308 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
5309 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
5310 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
5311 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
5312 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
5313 }
5314 Lex.Lex(); // Eat the operation.
5315
5316 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5317 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
5318 ParseTypeAndValue(Val, ValLoc, PFS) ||
5319 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5320 return true;
5321
5322 if (Ordering == Unordered)
5323 return TokError("atomicrmw cannot be unordered");
5324 if (!Ptr->getType()->isPointerTy())
5325 return Error(PtrLoc, "atomicrmw operand must be a pointer");
5326 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5327 return Error(ValLoc, "atomicrmw value and pointer type do not match");
5328 if (!Val->getType()->isIntegerTy())
5329 return Error(ValLoc, "atomicrmw operand must be an integer");
5330 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
5331 if (Size < 8 || (Size & (Size - 1)))
5332 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
5333 " integer");
5334
5335 AtomicRMWInst *RMWI =
5336 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
5337 RMWI->setVolatile(isVolatile);
5338 Inst = RMWI;
5339 return AteExtraComma ? InstExtraComma : InstNormal;
5340}
5341
Eli Friedmanfee02c62011-07-25 23:16:38 +00005342/// ParseFence
5343/// ::= 'fence' 'singlethread'? AtomicOrdering
5344int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
5345 AtomicOrdering Ordering = NotAtomic;
5346 SynchronizationScope Scope = CrossThread;
5347 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5348 return true;
5349
5350 if (Ordering == Unordered)
5351 return TokError("fence cannot be unordered");
5352 if (Ordering == Monotonic)
5353 return TokError("fence cannot be monotonic");
5354
5355 Inst = new FenceInst(Context, Ordering, Scope);
5356 return InstNormal;
5357}
5358
Chris Lattnerac161bf2009-01-02 07:01:27 +00005359/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00005360/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005361int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005362 Value *Ptr = nullptr;
5363 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00005364 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00005365
Dan Gohman16cbbe42009-07-29 15:58:36 +00005366 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00005367
Chris Lattner3822f632009-01-02 08:05:26 +00005368 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005369
Eli Benderskyd9806682013-04-22 17:03:42 +00005370 Type *BaseType = Ptr->getType();
5371 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
5372 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005373 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005374
Chris Lattnerac161bf2009-01-02 07:01:27 +00005375 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005376 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00005377 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00005378 if (Lex.getKind() == lltok::MetadataVar) {
5379 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00005380 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005381 }
Chris Lattner3822f632009-01-02 08:05:26 +00005382 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00005383 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005384 return Error(EltLoc, "getelementptr index must be an integer");
Nadav Rotem3924cb02011-12-05 06:29:09 +00005385 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
5386 return Error(EltLoc, "getelementptr index type missmatch");
5387 if (Val->getType()->isVectorTy()) {
5388 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
5389 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
5390 if (ValNumEl != PtrNumEl)
5391 return Error(EltLoc,
5392 "getelementptr vector index has a wrong number of elements");
5393 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005394 Indices.push_back(Val);
5395 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005396
Eli Benderskyd9806682013-04-22 17:03:42 +00005397 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
5398 return Error(Loc, "base element of getelementptr must be sized");
5399
5400 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005401 return Error(Loc, "invalid getelementptr indices");
Jay Foadd1b78492011-07-25 09:48:08 +00005402 Inst = GetElementPtrInst::Create(Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00005403 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00005404 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00005405 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005406}
5407
5408/// ParseExtractValue
5409/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00005410int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005411 Value *Val; LocTy Loc;
5412 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005413 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005414 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00005415 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005416 return true;
5417
Chris Lattner392be582010-02-12 20:49:41 +00005418 if (!Val->getType()->isAggregateType())
5419 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005420
Jay Foad57aa6362011-07-13 10:26:04 +00005421 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005422 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00005423 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00005424 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005425}
5426
5427/// ParseInsertValue
5428/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00005429int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005430 Value *Val0, *Val1; LocTy Loc0, Loc1;
5431 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005432 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005433 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
5434 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
5435 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00005436 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005437 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005438
Chris Lattner392be582010-02-12 20:49:41 +00005439 if (!Val0->getType()->isAggregateType())
5440 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005441
David Majnemer30074532015-02-11 07:43:58 +00005442 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
5443 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005444 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00005445 if (IndexedType != Val1->getType())
5446 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
5447 getTypeString(Val1->getType()) + "' instead of '" +
5448 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00005449 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00005450 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005451}
Nick Lewycky49f89192009-04-04 07:22:01 +00005452
5453//===----------------------------------------------------------------------===//
5454// Embedded metadata.
5455//===----------------------------------------------------------------------===//
5456
5457/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005458/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00005459/// Element
5460/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00005461bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00005462 if (ParseToken(lltok::lbrace, "expected '{' here"))
5463 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005464
Dan Gohman1e0213a2010-07-13 19:33:27 +00005465 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005466 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00005467 return false;
5468
Nick Lewycky49f89192009-04-04 07:22:01 +00005469 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00005470 // Null is a special case since it is typeless.
5471 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005472 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00005473 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00005474 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005475
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00005476 Metadata *MD;
5477 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005478 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00005479 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00005480 } while (EatIfPresent(lltok::comma));
5481
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005482 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00005483}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005484
5485//===----------------------------------------------------------------------===//
5486// Use-list order directives.
5487//===----------------------------------------------------------------------===//
5488bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
5489 SMLoc Loc) {
5490 if (V->use_empty())
5491 return Error(Loc, "value has no uses");
5492
5493 unsigned NumUses = 0;
5494 SmallDenseMap<const Use *, unsigned, 16> Order;
5495 for (const Use &U : V->uses()) {
5496 if (++NumUses > Indexes.size())
5497 break;
5498 Order[&U] = Indexes[NumUses - 1];
5499 }
5500 if (NumUses < 2)
5501 return Error(Loc, "value only has one use");
5502 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
5503 return Error(Loc, "wrong number of indexes, expected " +
5504 Twine(std::distance(V->use_begin(), V->use_end())));
5505
5506 V->sortUseList([&](const Use &L, const Use &R) {
5507 return Order.lookup(&L) < Order.lookup(&R);
5508 });
5509 return false;
5510}
5511
5512/// ParseUseListOrderIndexes
5513/// ::= '{' uint32 (',' uint32)+ '}'
5514bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
5515 SMLoc Loc = Lex.getLoc();
5516 if (ParseToken(lltok::lbrace, "expected '{' here"))
5517 return true;
5518 if (Lex.getKind() == lltok::rbrace)
5519 return Lex.Error("expected non-empty list of uselistorder indexes");
5520
5521 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
5522 // indexes should be distinct numbers in the range [0, size-1], and should
5523 // not be in order.
5524 unsigned Offset = 0;
5525 unsigned Max = 0;
5526 bool IsOrdered = true;
5527 assert(Indexes.empty() && "Expected empty order vector");
5528 do {
5529 unsigned Index;
5530 if (ParseUInt32(Index))
5531 return true;
5532
5533 // Update consistency checks.
5534 Offset += Index - Indexes.size();
5535 Max = std::max(Max, Index);
5536 IsOrdered &= Index == Indexes.size();
5537
5538 Indexes.push_back(Index);
5539 } while (EatIfPresent(lltok::comma));
5540
5541 if (ParseToken(lltok::rbrace, "expected '}' here"))
5542 return true;
5543
5544 if (Indexes.size() < 2)
5545 return Error(Loc, "expected >= 2 uselistorder indexes");
5546 if (Offset != 0 || Max >= Indexes.size())
5547 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
5548 if (IsOrdered)
5549 return Error(Loc, "expected uselistorder indexes to change the order");
5550
5551 return false;
5552}
5553
5554/// ParseUseListOrder
5555/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
5556bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
5557 SMLoc Loc = Lex.getLoc();
5558 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
5559 return true;
5560
5561 Value *V;
5562 SmallVector<unsigned, 16> Indexes;
5563 if (ParseTypeAndValue(V, PFS) ||
5564 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
5565 ParseUseListOrderIndexes(Indexes))
5566 return true;
5567
5568 return sortUseListOrder(V, Indexes, Loc);
5569}
5570
5571/// ParseUseListOrderBB
5572/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
5573bool LLParser::ParseUseListOrderBB() {
5574 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
5575 SMLoc Loc = Lex.getLoc();
5576 Lex.Lex();
5577
5578 ValID Fn, Label;
5579 SmallVector<unsigned, 16> Indexes;
5580 if (ParseValID(Fn) ||
5581 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5582 ParseValID(Label) ||
5583 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5584 ParseUseListOrderIndexes(Indexes))
5585 return true;
5586
5587 // Check the function.
5588 GlobalValue *GV;
5589 if (Fn.Kind == ValID::t_GlobalName)
5590 GV = M->getNamedValue(Fn.StrVal);
5591 else if (Fn.Kind == ValID::t_GlobalID)
5592 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
5593 else
5594 return Error(Fn.Loc, "expected function name in uselistorder_bb");
5595 if (!GV)
5596 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
5597 auto *F = dyn_cast<Function>(GV);
5598 if (!F)
5599 return Error(Fn.Loc, "expected function name in uselistorder_bb");
5600 if (F->isDeclaration())
5601 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
5602
5603 // Check the basic block.
5604 if (Label.Kind == ValID::t_LocalID)
5605 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
5606 if (Label.Kind != ValID::t_LocalName)
5607 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
5608 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
5609 if (!V)
5610 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
5611 if (!isa<BasicBlock>(V))
5612 return Error(Label.Loc, "expected basic block in uselistorder_bb");
5613
5614 return sortUseListOrder(V, Indexes, Loc);
5615}