blob: 56667bdead45d4202819373104a787463f350d9f [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"
David Blaikieadbda4b2015-08-03 20:08:41 +000016#include "llvm/ADT/STLExtras.h"
George Burgess IV278199f2016-04-12 01:05:35 +000017#include "llvm/ADT/StringExtras.h"
Alex Lorenz8955f7d2015-06-23 17:10:10 +000018#include "llvm/AsmParser/SlotMapping.h"
Chandler Carruth91065212014-03-05 10:34:14 +000019#include "llvm/IR/AutoUpgrade.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000020#include "llvm/IR/CallingConv.h"
21#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +000022#include "llvm/IR/DebugInfo.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000023#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/DerivedTypes.h"
25#include "llvm/IR/InlineAsm.h"
26#include "llvm/IR/Instructions.h"
Manman Ren209b17c2013-09-28 00:22:27 +000027#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Module.h"
29#include "llvm/IR/Operator.h"
30#include "llvm/IR/ValueSymbolTable.h"
Philip Reames1960cfd2016-02-19 00:06:41 +000031#include "llvm/Support/Debug.h"
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +000032#include "llvm/Support/Dwarf.h"
Torok Edwin56d06592009-07-11 20:10:48 +000033#include "llvm/Support/ErrorHandling.h"
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +000034#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerac161bf2009-01-02 07:01:27 +000035#include "llvm/Support/raw_ostream.h"
36using namespace llvm;
37
Chris Lattner229907c2011-07-18 04:54:35 +000038static std::string getTypeString(Type *T) {
Alp Tokere69170a2014-06-26 22:52:05 +000039 std::string Result;
40 raw_string_ostream Tmp(Result);
41 Tmp << *T;
42 return Tmp.str();
Chris Lattner0f214eb2011-06-18 21:18:23 +000043}
44
Chris Lattner3822f632009-01-02 08:05:26 +000045/// Run: module ::= toplevelentity*
Chris Lattnerad6f3352009-01-04 20:44:11 +000046bool LLParser::Run() {
Chris Lattner3822f632009-01-02 08:05:26 +000047 // Prime the lexer.
48 Lex.Lex();
49
Mehdi Amini50af49f2016-04-02 03:46:17 +000050 if (Context.shouldDiscardValueNames())
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000051 return Error(
52 Lex.getLoc(),
53 "Can't read textual IR with a Context that discards named Values");
54
Chris Lattnerad6f3352009-01-04 20:44:11 +000055 return ParseTopLevelEntities() ||
56 ValidateEndOfModule();
Chris Lattnerac161bf2009-01-02 07:01:27 +000057}
58
Alex Lorenz1de2acd2015-08-21 21:32:39 +000059bool LLParser::parseStandaloneConstantValue(Constant *&C,
60 const SlotMapping *Slots) {
61 restoreParsingState(Slots);
Alex Lorenzd2255952015-07-17 22:07:03 +000062 Lex.Lex();
63
64 Type *Ty = nullptr;
65 if (ParseType(Ty) || parseConstantValue(Ty, C))
66 return true;
67 if (Lex.getKind() != lltok::Eof)
68 return Error(Lex.getLoc(), "expected end of string");
69 return false;
70}
71
Quentin Colombetdafed5d2016-03-08 00:37:07 +000072bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
73 const SlotMapping *Slots) {
Quentin Colombet81e72b42016-03-07 22:09:05 +000074 restoreParsingState(Slots);
75 Lex.Lex();
76
Quentin Colombetdafed5d2016-03-08 00:37:07 +000077 Read = 0;
78 SMLoc Start = Lex.getLoc();
Quentin Colombet81e72b42016-03-07 22:09:05 +000079 Ty = nullptr;
80 if (ParseType(Ty))
81 return true;
Quentin Colombetdafed5d2016-03-08 00:37:07 +000082 SMLoc End = Lex.getLoc();
83 Read = End.getPointer() - Start.getPointer();
84
Quentin Colombet81e72b42016-03-07 22:09:05 +000085 return false;
86}
87
Alex Lorenz1de2acd2015-08-21 21:32:39 +000088void LLParser::restoreParsingState(const SlotMapping *Slots) {
89 if (!Slots)
90 return;
91 NumberedVals = Slots->GlobalValues;
92 NumberedMetadata = Slots->MetadataNodes;
93 for (const auto &I : Slots->NamedTypes)
94 NamedTypes.insert(
95 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
96 for (const auto &I : Slots->Types)
97 NumberedTypes.insert(
98 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
99}
100
Chris Lattnerac161bf2009-01-02 07:01:27 +0000101/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
102/// module.
103bool LLParser::ValidateEndOfModule() {
Bill Wendlingb32b0412013-02-08 06:32:06 +0000104 // Handle any function attribute group forward references.
105 for (std::map<Value*, std::vector<unsigned> >::iterator
106 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
107 I != E; ++I) {
108 Value *V = I->first;
109 std::vector<unsigned> &Vec = I->second;
110 AttrBuilder B;
111
112 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
113 VI != VE; ++VI)
114 B.merge(NumberedAttrBuilders[*VI]);
115
116 if (Function *Fn = dyn_cast<Function>(V)) {
117 AttributeSet AS = Fn->getAttributes();
118 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
119 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
120 AS.getFnAttributes());
121
122 FnAttrs.merge(B);
123
124 // If the alignment was parsed as an attribute, move to the alignment
125 // field.
126 if (FnAttrs.hasAlignmentAttr()) {
127 Fn->setAlignment(FnAttrs.getAlignment());
128 FnAttrs.removeAttribute(Attribute::Alignment);
129 }
130
131 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
132 AttributeSet::get(Context,
133 AttributeSet::FunctionIndex,
134 FnAttrs));
135 Fn->setAttributes(AS);
136 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
137 AttributeSet AS = CI->getAttributes();
138 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
139 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
140 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000141 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000142 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
143 AttributeSet::get(Context,
144 AttributeSet::FunctionIndex,
145 FnAttrs));
146 CI->setAttributes(AS);
147 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
148 AttributeSet AS = II->getAttributes();
149 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
150 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
151 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000152 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000153 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
154 AttributeSet::get(Context,
155 AttributeSet::FunctionIndex,
156 FnAttrs));
157 II->setAttributes(AS);
158 } else {
159 llvm_unreachable("invalid object with forward attribute group reference");
160 }
161 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000162
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000163 // If there are entries in ForwardRefBlockAddresses at this point, the
164 // function was never defined.
165 if (!ForwardRefBlockAddresses.empty())
166 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
167 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000168
David Majnemer19b51052015-02-11 07:43:56 +0000169 for (const auto &NT : NumberedTypes)
170 if (NT.second.second.isValid())
171 return Error(NT.second.second,
172 "use of undefined type '%" + Twine(NT.first) + "'");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000173
174 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
175 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
176 if (I->second.second.isValid())
177 return Error(I->second.second,
178 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000179
David Majnemerdad0a642014-06-27 18:19:56 +0000180 if (!ForwardRefComdats.empty())
181 return Error(ForwardRefComdats.begin()->second,
182 "use of undefined comdat '$" +
183 ForwardRefComdats.begin()->first + "'");
184
Chris Lattnerac161bf2009-01-02 07:01:27 +0000185 if (!ForwardRefVals.empty())
186 return Error(ForwardRefVals.begin()->second.second,
187 "use of undefined value '@" + ForwardRefVals.begin()->first +
188 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000189
Chris Lattnerac161bf2009-01-02 07:01:27 +0000190 if (!ForwardRefValIDs.empty())
191 return Error(ForwardRefValIDs.begin()->second.second,
192 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000193 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000194
Devang Pateld2541152009-07-08 19:23:54 +0000195 if (!ForwardRefMDNodes.empty())
196 return Error(ForwardRefMDNodes.begin()->second.second,
197 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000198 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000199
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000200 // Resolve metadata cycles.
David Majnemer19b51052015-02-11 07:43:56 +0000201 for (auto &N : NumberedMetadata) {
202 if (N.second && !N.second->isResolved())
203 N.second->resolveCycles();
204 }
Devang Pateld2541152009-07-08 19:23:54 +0000205
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000206 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
207 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
208
Chris Lattnerac161bf2009-01-02 07:01:27 +0000209 // Look for intrinsic functions and CallInst that need to be upgraded
210 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +0000211 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000212
Manman Ren8b4306c2013-12-02 21:29:56 +0000213 UpgradeDebugInfo(*M);
214
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000215 if (!Slots)
216 return false;
217 // Initialize the slot mapping.
218 // Because by this point we've parsed and validated everything, we can "steal"
219 // the mapping from LLParser as it doesn't need it anymore.
220 Slots->GlobalValues = std::move(NumberedVals);
221 Slots->MetadataNodes = std::move(NumberedMetadata);
Alex Lorenz1de2acd2015-08-21 21:32:39 +0000222 for (const auto &I : NamedTypes)
223 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
224 for (const auto &I : NumberedTypes)
225 Slots->Types.insert(std::make_pair(I.first, I.second.first));
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000226
Chris Lattnerac161bf2009-01-02 07:01:27 +0000227 return false;
228}
229
230//===----------------------------------------------------------------------===//
231// Top-Level Entities
232//===----------------------------------------------------------------------===//
233
234bool LLParser::ParseTopLevelEntities() {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000235 while (1) {
236 switch (Lex.getKind()) {
237 default: return TokError("expected top-level entity");
238 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000239 case lltok::kw_declare: if (ParseDeclare()) return true; break;
240 case lltok::kw_define: if (ParseDefine()) return true; break;
241 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
242 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Teresa Johnson83c517c2016-03-30 18:15:08 +0000243 case lltok::kw_source_filename:
244 if (ParseSourceFileName())
245 return true;
246 break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000247 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000248 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000249 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000250 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000251 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000252 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000253 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000254 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Bill Wendlinga7c38772013-02-09 15:48:49 +0000255 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000256 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
257 case lltok::kw_uselistorder_bb:
258 if (ParseUseListOrderBB()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000259 }
260 }
261}
262
263
264/// toplevelentity
265/// ::= 'module' 'asm' STRINGCONSTANT
266bool LLParser::ParseModuleAsm() {
267 assert(Lex.getKind() == lltok::kw_module);
268 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000269
270 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000271 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
272 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000273
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000274 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000275 return false;
276}
277
278/// toplevelentity
279/// ::= 'target' 'triple' '=' STRINGCONSTANT
280/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
281bool LLParser::ParseTargetDefinition() {
282 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000283 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000284 switch (Lex.Lex()) {
285 default: return TokError("unknown target property");
286 case lltok::kw_triple:
287 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000288 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
289 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000290 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000291 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000292 return false;
293 case lltok::kw_datalayout:
294 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000295 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
296 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000297 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000298 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000299 return false;
300 }
301}
302
Bill Wendling706d3d62012-11-28 08:41:48 +0000303/// toplevelentity
Teresa Johnson83c517c2016-03-30 18:15:08 +0000304/// ::= 'source_filename' '=' STRINGCONSTANT
305bool LLParser::ParseSourceFileName() {
306 assert(Lex.getKind() == lltok::kw_source_filename);
307 std::string Str;
308 Lex.Lex();
309 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
310 ParseStringConstant(Str))
311 return true;
312 M->setSourceFileName(Str);
313 return false;
314}
315
316/// toplevelentity
Bill Wendling706d3d62012-11-28 08:41:48 +0000317/// ::= 'deplibs' '=' '[' ']'
318/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
319/// FIXME: Remove in 4.0. Currently parse, but ignore.
320bool LLParser::ParseDepLibs() {
321 assert(Lex.getKind() == lltok::kw_deplibs);
322 Lex.Lex();
323 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
324 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
325 return true;
326
327 if (EatIfPresent(lltok::rsquare))
328 return false;
329
330 do {
331 std::string Str;
332 if (ParseStringConstant(Str)) return true;
333 } while (EatIfPresent(lltok::comma));
334
335 return ParseToken(lltok::rsquare, "expected ']' at end of list");
336}
337
Dan Gohman466876b2009-08-12 23:32:33 +0000338/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000339/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000340bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000341 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000342 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000343 Lex.Lex(); // eat LocalVarID;
344
345 if (ParseToken(lltok::equal, "expected '=' after name") ||
346 ParseToken(lltok::kw_type, "expected 'type' after '='"))
347 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000348
Craig Topper2617dcc2014-04-15 06:32:26 +0000349 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000350 if (ParseStructDefinition(TypeLoc, "",
351 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000352
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000353 if (!isa<StructType>(Result)) {
354 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
355 if (Entry.first)
356 return Error(TypeLoc, "non-struct types may not be recursive");
357 Entry.first = Result;
358 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000359 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000360
Chris Lattnerac161bf2009-01-02 07:01:27 +0000361 return false;
362}
363
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000364
Chris Lattnerac161bf2009-01-02 07:01:27 +0000365/// toplevelentity
366/// ::= LocalVar '=' 'type' type
367bool LLParser::ParseNamedType() {
368 std::string Name = Lex.getStrVal();
369 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000370 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000371
Chris Lattner3822f632009-01-02 08:05:26 +0000372 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000373 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000374 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000375
Craig Topper2617dcc2014-04-15 06:32:26 +0000376 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000377 if (ParseStructDefinition(NameLoc, Name,
378 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000379
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000380 if (!isa<StructType>(Result)) {
381 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
382 if (Entry.first)
383 return Error(NameLoc, "non-struct types may not be recursive");
384 Entry.first = Result;
385 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000386 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000387
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000388 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000389}
390
391
392/// toplevelentity
393/// ::= 'declare' FunctionHeader
394bool LLParser::ParseDeclare() {
395 assert(Lex.getKind() == lltok::kw_declare);
396 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000397
Chris Lattnerac161bf2009-01-02 07:01:27 +0000398 Function *F;
399 return ParseFunctionHeader(F, false);
400}
401
402/// toplevelentity
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000403/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
Chris Lattnerac161bf2009-01-02 07:01:27 +0000404bool LLParser::ParseDefine() {
405 assert(Lex.getKind() == lltok::kw_define);
406 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000407
Chris Lattnerac161bf2009-01-02 07:01:27 +0000408 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000409 return ParseFunctionHeader(F, true) ||
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000410 ParseOptionalFunctionMetadata(*F) ||
Chris Lattner3822f632009-01-02 08:05:26 +0000411 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000412}
413
Chris Lattner3822f632009-01-02 08:05:26 +0000414/// ParseGlobalType
415/// ::= 'constant'
416/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000417bool LLParser::ParseGlobalType(bool &IsConstant) {
418 if (Lex.getKind() == lltok::kw_constant)
419 IsConstant = true;
420 else if (Lex.getKind() == lltok::kw_global)
421 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000422 else {
423 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000424 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000425 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000426 Lex.Lex();
427 return false;
428}
429
Dan Gohman466876b2009-08-12 23:32:33 +0000430/// ParseUnnamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000431/// OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000432/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
433/// ... -> global variable
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000434/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000435/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
436/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000437bool LLParser::ParseUnnamedGlobal() {
438 unsigned VarID = NumberedVals.size();
439 std::string Name;
440 LocTy NameLoc = Lex.getLoc();
441
442 // Handle the GlobalID form.
443 if (Lex.getKind() == lltok::GlobalID) {
444 if (Lex.getUIntVal() != VarID)
445 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000446 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000447 Lex.Lex(); // eat GlobalID;
448
449 if (ParseToken(lltok::equal, "expected '=' after name"))
450 return true;
451 }
452
453 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000454 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000455 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000456 bool UnnamedAddr;
Rafael Espindola2615c9e2016-05-12 12:37:52 +0000457 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
458 ParseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000459 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000460
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000461 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000462 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000463 DLLStorageClass, TLM, UnnamedAddr);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000464
465 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
466 DLLStorageClass, TLM, UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000467}
468
Chris Lattnerac161bf2009-01-02 07:01:27 +0000469/// ParseNamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000470/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000471/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
472/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000473bool LLParser::ParseNamedGlobal() {
474 assert(Lex.getKind() == lltok::GlobalVar);
475 LocTy NameLoc = Lex.getLoc();
476 std::string Name = Lex.getStrVal();
477 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000478
Chris Lattnerac161bf2009-01-02 07:01:27 +0000479 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000480 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000481 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000482 bool UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000483 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
Rafael Espindola2615c9e2016-05-12 12:37:52 +0000484 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
485 ParseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000486 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000487
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000488 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000489 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000490 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000491
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000492 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
493 DLLStorageClass, TLM, UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000494}
495
David Majnemerdad0a642014-06-27 18:19:56 +0000496bool LLParser::parseComdat() {
497 assert(Lex.getKind() == lltok::ComdatVar);
498 std::string Name = Lex.getStrVal();
499 LocTy NameLoc = Lex.getLoc();
500 Lex.Lex();
501
502 if (ParseToken(lltok::equal, "expected '=' here"))
503 return true;
504
505 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
506 return TokError("expected comdat type");
507
508 Comdat::SelectionKind SK;
509 switch (Lex.getKind()) {
510 default:
511 return TokError("unknown selection kind");
512 case lltok::kw_any:
513 SK = Comdat::Any;
514 break;
515 case lltok::kw_exactmatch:
516 SK = Comdat::ExactMatch;
517 break;
518 case lltok::kw_largest:
519 SK = Comdat::Largest;
520 break;
521 case lltok::kw_noduplicates:
522 SK = Comdat::NoDuplicates;
523 break;
524 case lltok::kw_samesize:
525 SK = Comdat::SameSize;
526 break;
527 }
528 Lex.Lex();
529
530 // See if the comdat was forward referenced, if so, use the comdat.
531 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
532 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
533 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
534 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
535
536 Comdat *C;
537 if (I != ComdatSymTab.end())
538 C = &I->second;
539 else
540 C = M->getOrInsertComdat(Name);
541 C->setSelectionKind(SK);
542
543 return false;
544}
545
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000546// MDString:
547// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000548bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000549 std::string Str;
550 if (ParseStringConstant(Str)) return true;
Chris Lattner1797fc72009-12-29 21:53:55 +0000551 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000552 return false;
553}
554
555// MDNode:
556// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000557bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000558 // !{ ..., !42, ... }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000559 LocTy IDLoc = Lex.getLoc();
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000560 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000561 if (ParseUInt32(MID))
562 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000563
Chris Lattner8eff0152010-04-01 05:14:45 +0000564 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000565 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000566 Result = NumberedMetadata[MID];
567 return false;
568 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000569
Chris Lattner8eff0152010-04-01 05:14:45 +0000570 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000571 auto &FwdRef = ForwardRefMDNodes[MID];
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000572 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000573
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000574 Result = FwdRef.first.get();
575 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000576 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000577}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000578
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000579/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000580/// !foo = !{ !1, !2 }
581bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000582 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000583 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000584 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000585
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000586 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000587 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000588 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000589 return true;
590
Dan Gohman2637cc12010-07-21 23:38:33 +0000591 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000592 if (Lex.getKind() != lltok::rbrace)
593 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000594 if (ParseToken(lltok::exclaim, "Expected '!' here"))
595 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000596
Craig Topper2617dcc2014-04-15 06:32:26 +0000597 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000598 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000599 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000600 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000601
Rafael Espindolac7818fb2015-05-26 20:37:36 +0000602 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Patelbe626972009-07-29 00:34:02 +0000603}
604
Devang Patel39e64d42009-07-01 19:21:12 +0000605/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000606/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000607bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000608 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000609 Lex.Lex();
610 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000611
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000612 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000613 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000614 ParseToken(lltok::equal, "expected '=' here"))
615 return true;
616
617 // Detect common error, from old metadata syntax.
618 if (Lex.getKind() == lltok::Type)
619 return TokError("unexpected type in metadata definition");
620
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000621 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000622 if (Lex.getKind() == lltok::MetadataVar) {
623 if (ParseSpecializedMDNode(Init, IsDistinct))
624 return true;
625 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
626 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000627 return true;
628
Chris Lattnerfc58af22009-12-30 04:51:58 +0000629 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000630 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000631 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000632 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000633 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000634
Chris Lattnerfc58af22009-12-30 04:51:58 +0000635 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
636 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000637 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000638 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000639 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000640 }
641
Devang Patel39e64d42009-07-01 19:21:12 +0000642 return false;
643}
644
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000645static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
646 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
647 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
648}
649
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000650/// parseIndirectSymbol:
Rafael Espindola464fe022014-07-30 22:51:54 +0000651/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
652/// OptionalDLLStorageClass OptionalThreadLocal
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000653/// OptionalUnnamedAddr 'alias|ifunc' IndirectSymbol
Rafael Espindola6b238632014-05-16 19:35:39 +0000654///
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000655/// IndirectSymbol
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000656/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000657///
Eric Christopher536f0a92015-05-28 23:07:39 +0000658/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000659///
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000660bool LLParser::parseIndirectSymbol(const std::string &Name, LocTy NameLoc,
661 unsigned L, unsigned Visibility,
662 unsigned DLLStorageClass,
663 GlobalVariable::ThreadLocalMode TLM,
664 bool UnnamedAddr) {
665 bool IsAlias;
666 if (Lex.getKind() == lltok::kw_alias)
667 IsAlias = true;
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000668 else if (Lex.getKind() == lltok::kw_ifunc)
669 IsAlias = false;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000670 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000671 llvm_unreachable("Not an alias or ifunc!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000672 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000673
Rafael Espindola78527052013-10-06 15:10:43 +0000674 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
675
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000676 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000677 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000678
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000679 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000680 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000681 "symbol with local linkage must have default visibility");
682
David Blaikie2f408302015-09-11 03:22:04 +0000683 Type *Ty;
684 LocTy ExplicitTypeLoc = Lex.getLoc();
685 if (ParseType(Ty) ||
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000686 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
David Blaikie2f408302015-09-11 03:22:04 +0000687 return true;
688
Rafael Espindola64c1e182014-06-03 02:41:57 +0000689 Constant *Aliasee;
690 LocTy AliaseeLoc = Lex.getLoc();
691 if (Lex.getKind() != lltok::kw_bitcast &&
692 Lex.getKind() != lltok::kw_getelementptr &&
693 Lex.getKind() != lltok::kw_addrspacecast &&
694 Lex.getKind() != lltok::kw_inttoptr) {
695 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000696 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000697 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000698 // The bitcast dest type is not present, it is implied by the dest type.
699 ValID ID;
700 if (ParseValID(ID))
701 return true;
702 if (ID.Kind != ValID::t_Constant)
703 return Error(AliaseeLoc, "invalid aliasee");
704 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000705 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000706
Rafael Espindola64c1e182014-06-03 02:41:57 +0000707 Type *AliaseeType = Aliasee->getType();
708 auto *PTy = dyn_cast<PointerType>(AliaseeType);
709 if (!PTy)
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000710 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
David Blaikie16a2f3e2015-09-14 18:01:59 +0000711 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000712
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000713 if (IsAlias && Ty != PTy->getElementType())
David Blaikie2f408302015-09-11 03:22:04 +0000714 return Error(
715 ExplicitTypeLoc,
716 "explicit pointee type doesn't match operand's pointee type");
717
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000718 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
719 return Error(
720 ExplicitTypeLoc,
721 "explicit pointee type should be a function type");
722
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000723 GlobalValue *GVal = nullptr;
724
725 // See if the alias was forward referenced, if so, prepare to replace the
726 // forward reference.
727 if (!Name.empty()) {
728 GVal = M->getNamedValue(Name);
729 if (GVal) {
730 if (!ForwardRefVals.erase(Name))
731 return Error(NameLoc, "redefinition of global '@" + Name + "'");
732 }
733 } else {
734 auto I = ForwardRefValIDs.find(NumberedVals.size());
735 if (I != ForwardRefValIDs.end()) {
736 GVal = I->second.first;
737 ForwardRefValIDs.erase(I);
738 }
739 }
740
Chris Lattnerac161bf2009-01-02 07:01:27 +0000741 // Okay, create the alias but do not insert it into the module yet.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000742 std::unique_ptr<GlobalIndirectSymbol> GA;
743 if (IsAlias)
744 GA.reset(GlobalAlias::create(Ty, AddrSpace,
745 (GlobalValue::LinkageTypes)Linkage, Name,
746 Aliasee, /*Parent*/ nullptr));
747 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000748 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
749 (GlobalValue::LinkageTypes)Linkage, Name,
750 Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000751 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000752 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000753 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000754 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000755
Rafael Espindola54fc2982015-06-17 17:53:31 +0000756 if (Name.empty())
757 NumberedVals.push_back(GA.get());
758
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000759 if (GVal) {
760 // Verify that types agree.
761 if (GVal->getType() != GA->getType())
762 return Error(
763 ExplicitTypeLoc,
764 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000765
Chris Lattnerac161bf2009-01-02 07:01:27 +0000766 // If they agree, just RAUW the old value with the alias and remove the
767 // forward ref info.
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000768 GVal->replaceAllUsesWith(GA.get());
769 GVal->eraseFromParent();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000770 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000771
Chris Lattnerac161bf2009-01-02 07:01:27 +0000772 // Insert into the module, we know its name won't collide now.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000773 if (IsAlias)
774 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
775 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000776 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000777 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000778
Rafael Espindolaaa273822014-05-09 21:49:17 +0000779 // The module owns this now
780 GA.release();
781
Chris Lattnerac161bf2009-01-02 07:01:27 +0000782 return false;
783}
784
785/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000786/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000787/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000788/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000789/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000790/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000791/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000792///
Eric Christopher536f0a92015-05-28 23:07:39 +0000793/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000794/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000795///
796bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
797 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000798 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000799 GlobalVariable::ThreadLocalMode TLM,
800 bool UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000801 if (!isValidVisibilityForLinkage(Visibility, Linkage))
802 return Error(NameLoc,
803 "symbol with local linkage must have default visibility");
804
Chris Lattnerac161bf2009-01-02 07:01:27 +0000805 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000806 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000807 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000808 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000809
Craig Topper2617dcc2014-04-15 06:32:26 +0000810 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000811 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000812 ParseOptionalToken(lltok::kw_externally_initialized,
813 IsExternallyInitialized,
814 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000815 ParseGlobalType(IsConstant) ||
816 ParseType(Ty, TyLoc))
817 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000818
Chris Lattnerac161bf2009-01-02 07:01:27 +0000819 // If the linkage is specified and is external, then no initializer is
820 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000821 Constant *Init = nullptr;
Rafael Espindola4787ba32016-05-11 13:51:39 +0000822 if (!HasLinkage ||
823 !GlobalValue::isValidDeclarationLinkage(
824 (GlobalValue::LinkageTypes)Linkage)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000825 if (ParseGlobalValue(Ty, Init))
826 return true;
827 }
828
David Majnemer49b3d9b2015-02-16 08:41:08 +0000829 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000830 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000831
David Majnemer598bd052014-12-09 05:56:09 +0000832 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000833
834 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000835 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000836 GVal = M->getNamedValue(Name);
837 if (GVal) {
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000838 if (!ForwardRefVals.erase(Name))
Chris Lattnere38317f2009-10-25 23:22:50 +0000839 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000840 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000841 } else {
David Blaikie9ebdc692015-09-21 21:07:50 +0000842 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000843 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000844 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000845 ForwardRefValIDs.erase(I);
846 }
847 }
848
David Majnemer598bd052014-12-09 05:56:09 +0000849 GlobalVariable *GV;
850 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000851 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
852 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000853 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000854 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +0000855 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000856 return Error(TyLoc,
857 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000858
David Majnemer598bd052014-12-09 05:56:09 +0000859 GV = cast<GlobalVariable>(GVal);
860
Chris Lattnerac161bf2009-01-02 07:01:27 +0000861 // Move the forward-reference to the correct spot in the module.
862 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
863 }
864
865 if (Name.empty())
866 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000867
Chris Lattnerac161bf2009-01-02 07:01:27 +0000868 // Set the parsed properties on the global.
869 if (Init)
870 GV->setInitializer(Init);
871 GV->setConstant(IsConstant);
872 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
873 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000874 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000875 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000876 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000877 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000878
Chris Lattnerac161bf2009-01-02 07:01:27 +0000879 // Parse attributes on the global.
880 while (Lex.getKind() == lltok::comma) {
881 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000882
Chris Lattnerac161bf2009-01-02 07:01:27 +0000883 if (Lex.getKind() == lltok::kw_section) {
884 Lex.Lex();
885 GV->setSection(Lex.getStrVal());
886 if (ParseToken(lltok::StringConstant, "expected global section string"))
887 return true;
888 } else if (Lex.getKind() == lltok::kw_align) {
889 unsigned Alignment;
890 if (ParseOptionalAlignment(Alignment)) return true;
891 GV->setAlignment(Alignment);
892 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000893 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000894 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000895 return true;
896 if (C)
897 GV->setComdat(C);
898 else
899 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000900 }
901 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000902
Chris Lattnerac161bf2009-01-02 07:01:27 +0000903 return false;
904}
905
Bill Wendling63b88192013-02-06 06:52:58 +0000906/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000907/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000908bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000909 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000910 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000911 Lex.Lex();
912
David Majnemerb39e22b2014-12-09 18:33:57 +0000913 if (Lex.getKind() != lltok::AttrGrpID)
914 return TokError("expected attribute group id");
915
Bill Wendling63b88192013-02-06 06:52:58 +0000916 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000917 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000918 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000919 Lex.Lex();
920
921 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000922 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000923 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000924 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000925 ParseToken(lltok::rbrace, "expected end of attribute group"))
926 return true;
927
Bill Wendlingb32b0412013-02-08 06:32:06 +0000928 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000929 return Error(AttrGrpLoc, "attribute group has no attributes");
930
931 return false;
932}
933
Bill Wendling8b0321d2013-02-08 00:52:31 +0000934/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000935/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000936bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
937 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000938 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000939 bool HaveError = false;
940
941 B.clear();
942
Bill Wendling63b88192013-02-06 06:52:58 +0000943 while (true) {
944 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000945 if (Token == lltok::kw_builtin)
946 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +0000947 switch (Token) {
948 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000949 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +0000950 return Error(Lex.getLoc(), "unterminated attribute group");
951 case lltok::rbrace:
952 // Finished.
953 return false;
954
Bill Wendlingb32b0412013-02-08 06:32:06 +0000955 case lltok::AttrGrpID: {
956 // Allow a function to reference an attribute group:
957 //
958 // define void @foo() #1 { ... }
959 if (inAttrGrp)
960 HaveError |=
961 Error(Lex.getLoc(),
962 "cannot have an attribute group reference in an attribute group");
963
964 unsigned AttrGrpNum = Lex.getUIntVal();
965 if (inAttrGrp) break;
966
967 // Save the reference to the attribute group. We'll fill it in later.
968 FwdRefAttrGrps.push_back(AttrGrpNum);
969 break;
970 }
Bill Wendling63b88192013-02-06 06:52:58 +0000971 // Target-dependent attributes:
972 case lltok::StringConstant: {
Artur Pilipenko17376c42015-08-03 14:31:49 +0000973 if (ParseStringAttribute(B))
Bill Wendling63b88192013-02-06 06:52:58 +0000974 return true;
Bill Wendlingb1ea9802013-02-10 10:12:50 +0000975 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000976 }
977
978 // Target-independent attributes:
979 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +0000980 // As a hack, we allow function alignment to be initially parsed as an
981 // attribute on a function declaration/definition or added to an attribute
982 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +0000983 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000984 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000985 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000986 if (ParseToken(lltok::equal, "expected '=' here") ||
987 ParseUInt32(Alignment))
988 return true;
989 } else {
990 if (ParseOptionalAlignment(Alignment))
991 return true;
992 }
Bill Wendling63b88192013-02-06 06:52:58 +0000993 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000994 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000995 }
996 case lltok::kw_alignstack: {
997 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000998 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000999 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001000 if (ParseToken(lltok::equal, "expected '=' here") ||
1001 ParseUInt32(Alignment))
1002 return true;
1003 } else {
1004 if (ParseOptionalStackAlignment(Alignment))
1005 return true;
1006 }
Bill Wendling63b88192013-02-06 06:52:58 +00001007 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001008 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001009 }
George Burgess IV278199f2016-04-12 01:05:35 +00001010 case lltok::kw_allocsize: {
1011 unsigned ElemSizeArg;
1012 Optional<unsigned> NumElemsArg;
1013 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1014 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1015 return true;
1016 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1017 continue;
1018 }
Igor Laevsky39d662f2015-07-11 10:30:36 +00001019 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1020 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1021 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1022 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1023 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001024 case lltok::kw_inaccessiblememonly:
1025 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1026 case lltok::kw_inaccessiblemem_or_argmemonly:
1027 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001028 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1029 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1030 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1031 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1032 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1033 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1034 case lltok::kw_noimplicitfloat:
1035 B.addAttribute(Attribute::NoImplicitFloat); break;
1036 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1037 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1038 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1039 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
James Molloye6f87ca2015-11-06 10:32:53 +00001040 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001041 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1042 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1043 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1044 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1045 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1046 case lltok::kw_returns_twice:
1047 B.addAttribute(Attribute::ReturnsTwice); break;
1048 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1049 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1050 case lltok::kw_sspstrong:
1051 B.addAttribute(Attribute::StackProtectStrong); break;
1052 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1053 case lltok::kw_sanitize_address:
1054 B.addAttribute(Attribute::SanitizeAddress); break;
1055 case lltok::kw_sanitize_thread:
1056 B.addAttribute(Attribute::SanitizeThread); break;
1057 case lltok::kw_sanitize_memory:
1058 B.addAttribute(Attribute::SanitizeMemory); break;
1059 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001060
1061 // Error handling.
1062 case lltok::kw_inreg:
1063 case lltok::kw_signext:
1064 case lltok::kw_zeroext:
1065 HaveError |=
1066 Error(Lex.getLoc(),
1067 "invalid use of attribute on a function");
1068 break;
1069 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001070 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001071 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001072 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001073 case lltok::kw_nest:
1074 case lltok::kw_noalias:
1075 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001076 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001077 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001078 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001079 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001080 case lltok::kw_swiftself:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001081 HaveError |=
1082 Error(Lex.getLoc(),
1083 "invalid use of parameter-only attribute on a function");
1084 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001085 }
1086
1087 Lex.Lex();
1088 }
1089}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001090
1091//===----------------------------------------------------------------------===//
1092// GlobalValue Reference/Resolution Routines.
1093//===----------------------------------------------------------------------===//
1094
Karl Schimpf77729782015-09-03 18:06:44 +00001095static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1096 const std::string &Name) {
1097 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1098 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1099 else
1100 return new GlobalVariable(*M, PTy->getElementType(), false,
1101 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1102 nullptr, GlobalVariable::NotThreadLocal,
1103 PTy->getAddressSpace());
1104}
1105
Chris Lattnerac161bf2009-01-02 07:01:27 +00001106/// GetGlobalVal - Get a value with the specified name or ID, creating a
1107/// forward reference record if needed. This can return null if the value
1108/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001109GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001110 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001111 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001112 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001113 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001114 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001115 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001116
Chris Lattnerac161bf2009-01-02 07:01:27 +00001117 // Look this name up in the normal function symbol table.
1118 GlobalValue *Val =
1119 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001120
Chris Lattnerac161bf2009-01-02 07:01:27 +00001121 // If this is a forward reference for the value, see if we already created a
1122 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001123 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001124 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001125 if (I != ForwardRefVals.end())
1126 Val = I->second.first;
1127 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001128
Chris Lattnerac161bf2009-01-02 07:01:27 +00001129 // If we have the value in the symbol table or fwd-ref table, return it.
1130 if (Val) {
1131 if (Val->getType() == Ty) return Val;
1132 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001133 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001134 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001135 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001136
Chris Lattnerac161bf2009-01-02 07:01:27 +00001137 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001138 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001139 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1140 return FwdVal;
1141}
1142
Chris Lattner229907c2011-07-18 04:54:35 +00001143GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1144 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001145 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001146 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001147 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001148 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001149
Craig Topper2617dcc2014-04-15 06:32:26 +00001150 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001151
Chris Lattnerac161bf2009-01-02 07:01:27 +00001152 // If this is a forward reference for the value, see if we already created a
1153 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001154 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001155 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001156 if (I != ForwardRefValIDs.end())
1157 Val = I->second.first;
1158 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001159
Chris Lattnerac161bf2009-01-02 07:01:27 +00001160 // If we have the value in the symbol table or fwd-ref table, return it.
1161 if (Val) {
1162 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001163 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001164 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001165 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001166 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001167
Chris Lattnerac161bf2009-01-02 07:01:27 +00001168 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001169 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001170 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1171 return FwdVal;
1172}
1173
1174
1175//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001176// Comdat Reference/Resolution Routines.
1177//===----------------------------------------------------------------------===//
1178
1179Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1180 // Look this name up in the comdat symbol table.
1181 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1182 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1183 if (I != ComdatSymTab.end())
1184 return &I->second;
1185
1186 // Otherwise, create a new forward reference for this value and remember it.
1187 Comdat *C = M->getOrInsertComdat(Name);
1188 ForwardRefComdats[Name] = Loc;
1189 return C;
1190}
1191
1192
1193//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001194// Helper Routines.
1195//===----------------------------------------------------------------------===//
1196
1197/// ParseToken - If the current token has the specified kind, eat it and return
1198/// success. Otherwise, emit the specified error and return failure.
1199bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1200 if (Lex.getKind() != T)
1201 return TokError(ErrMsg);
1202 Lex.Lex();
1203 return false;
1204}
1205
Chris Lattner3822f632009-01-02 08:05:26 +00001206/// ParseStringConstant
1207/// ::= StringConstant
1208bool LLParser::ParseStringConstant(std::string &Result) {
1209 if (Lex.getKind() != lltok::StringConstant)
1210 return TokError("expected string constant");
1211 Result = Lex.getStrVal();
1212 Lex.Lex();
1213 return false;
1214}
1215
1216/// ParseUInt32
1217/// ::= uint32
1218bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001219 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1220 return TokError("expected integer");
1221 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1222 if (Val64 != unsigned(Val64))
1223 return TokError("expected 32-bit integer (too large)");
1224 Val = Val64;
1225 Lex.Lex();
1226 return false;
1227}
1228
Hal Finkelb0407ba2014-07-18 15:51:28 +00001229/// ParseUInt64
1230/// ::= uint64
1231bool LLParser::ParseUInt64(uint64_t &Val) {
1232 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1233 return TokError("expected integer");
1234 Val = Lex.getAPSIntVal().getLimitedValue();
1235 Lex.Lex();
1236 return false;
1237}
1238
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001239/// ParseTLSModel
1240/// := 'localdynamic'
1241/// := 'initialexec'
1242/// := 'localexec'
1243bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1244 switch (Lex.getKind()) {
1245 default:
1246 return TokError("expected localdynamic, initialexec or localexec");
1247 case lltok::kw_localdynamic:
1248 TLM = GlobalVariable::LocalDynamicTLSModel;
1249 break;
1250 case lltok::kw_initialexec:
1251 TLM = GlobalVariable::InitialExecTLSModel;
1252 break;
1253 case lltok::kw_localexec:
1254 TLM = GlobalVariable::LocalExecTLSModel;
1255 break;
1256 }
1257
1258 Lex.Lex();
1259 return false;
1260}
1261
1262/// ParseOptionalThreadLocal
1263/// := /*empty*/
1264/// := 'thread_local'
1265/// := 'thread_local' '(' tlsmodel ')'
1266bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1267 TLM = GlobalVariable::NotThreadLocal;
1268 if (!EatIfPresent(lltok::kw_thread_local))
1269 return false;
1270
1271 TLM = GlobalVariable::GeneralDynamicTLSModel;
1272 if (Lex.getKind() == lltok::lparen) {
1273 Lex.Lex();
1274 return ParseTLSModel(TLM) ||
1275 ParseToken(lltok::rparen, "expected ')' after thread local model");
1276 }
1277 return false;
1278}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001279
1280/// ParseOptionalAddrSpace
1281/// := /*empty*/
1282/// := 'addrspace' '(' uint32 ')'
1283bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1284 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001285 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001286 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001287 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001288 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001289 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001290}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001291
Artur Pilipenko17376c42015-08-03 14:31:49 +00001292/// ParseStringAttribute
1293/// := StringConstant
1294/// := StringConstant '=' StringConstant
1295bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1296 std::string Attr = Lex.getStrVal();
1297 Lex.Lex();
1298 std::string Val;
1299 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1300 return true;
1301 B.addAttribute(Attr, Val);
1302 return false;
1303}
1304
Bill Wendling34c2eb22012-12-04 23:40:58 +00001305/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1306bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1307 bool HaveError = false;
1308
1309 B.clear();
1310
1311 while (1) {
1312 lltok::Kind Token = Lex.getKind();
1313 switch (Token) {
1314 default: // End of attributes.
1315 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001316 case lltok::StringConstant: {
1317 if (ParseStringAttribute(B))
1318 return true;
1319 continue;
1320 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001321 case lltok::kw_align: {
1322 unsigned Alignment;
1323 if (ParseOptionalAlignment(Alignment))
1324 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001325 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001326 continue;
1327 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001328 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001329 case lltok::kw_dereferenceable: {
1330 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001331 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001332 return true;
1333 B.addDereferenceableAttr(Bytes);
1334 continue;
1335 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001336 case lltok::kw_dereferenceable_or_null: {
1337 uint64_t Bytes;
1338 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1339 return true;
1340 B.addDereferenceableOrNullAttr(Bytes);
1341 continue;
1342 }
Reid Klecknera534a382013-12-19 02:14:12 +00001343 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001344 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1345 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1346 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1347 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001348 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001349 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1350 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001351 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001352 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1353 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001354 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
Manman Renf46262e2016-03-29 17:37:21 +00001355 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001356 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001357
Stephen Lin7577ed52013-04-20 13:16:13 +00001358 case lltok::kw_alignstack:
1359 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001360 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001361 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001362 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001363 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001364 case lltok::kw_minsize:
1365 case lltok::kw_naked:
1366 case lltok::kw_nobuiltin:
1367 case lltok::kw_noduplicate:
1368 case lltok::kw_noimplicitfloat:
1369 case lltok::kw_noinline:
1370 case lltok::kw_nonlazybind:
1371 case lltok::kw_noredzone:
1372 case lltok::kw_noreturn:
1373 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001374 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001375 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001376 case lltok::kw_returns_twice:
1377 case lltok::kw_sanitize_address:
1378 case lltok::kw_sanitize_memory:
1379 case lltok::kw_sanitize_thread:
1380 case lltok::kw_ssp:
1381 case lltok::kw_sspreq:
1382 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001383 case lltok::kw_safestack:
Stephen Lin7577ed52013-04-20 13:16:13 +00001384 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001385 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1386 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001387 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001388
Bill Wendling34c2eb22012-12-04 23:40:58 +00001389 Lex.Lex();
1390 }
1391}
1392
1393/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1394bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1395 bool HaveError = false;
1396
1397 B.clear();
1398
1399 while (1) {
1400 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001401 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001402 default: // End of attributes.
1403 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001404 case lltok::StringConstant: {
1405 if (ParseStringAttribute(B))
1406 return true;
1407 continue;
1408 }
Hal Finkelb0407ba2014-07-18 15:51:28 +00001409 case lltok::kw_dereferenceable: {
1410 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001411 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001412 return true;
1413 B.addDereferenceableAttr(Bytes);
1414 continue;
1415 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001416 case lltok::kw_dereferenceable_or_null: {
1417 uint64_t Bytes;
1418 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1419 return true;
1420 B.addDereferenceableOrNullAttr(Bytes);
1421 continue;
1422 }
Artur Pilipenko84bc62f2015-09-18 12:33:31 +00001423 case lltok::kw_align: {
1424 unsigned Alignment;
1425 if (ParseOptionalAlignment(Alignment))
1426 return true;
1427 B.addAlignmentAttr(Alignment);
1428 continue;
1429 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001430 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1431 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001432 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001433 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1434 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001435
Bill Wendling34c2eb22012-12-04 23:40:58 +00001436 // Error handling.
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001437 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001438 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001439 case lltok::kw_nest:
1440 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001441 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001442 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001443 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001444 case lltok::kw_swiftself:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001445 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001446 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001447
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001448 case lltok::kw_alignstack:
1449 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001450 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001451 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001452 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001453 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001454 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001455 case lltok::kw_minsize:
1456 case lltok::kw_naked:
1457 case lltok::kw_nobuiltin:
1458 case lltok::kw_noduplicate:
1459 case lltok::kw_noimplicitfloat:
1460 case lltok::kw_noinline:
1461 case lltok::kw_nonlazybind:
1462 case lltok::kw_noredzone:
1463 case lltok::kw_noreturn:
1464 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001465 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001466 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001467 case lltok::kw_returns_twice:
1468 case lltok::kw_sanitize_address:
1469 case lltok::kw_sanitize_memory:
1470 case lltok::kw_sanitize_thread:
1471 case lltok::kw_ssp:
1472 case lltok::kw_sspreq:
1473 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001474 case lltok::kw_safestack:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001475 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001476 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001477 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001478
1479 case lltok::kw_readnone:
1480 case lltok::kw_readonly:
1481 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001482 }
1483
Chris Lattnerac161bf2009-01-02 07:01:27 +00001484 Lex.Lex();
1485 }
1486}
1487
Rafael Espindolac6269912016-05-10 17:16:45 +00001488static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1489 HasLinkage = true;
1490 switch (Kind) {
1491 default:
1492 HasLinkage = false;
1493 return GlobalValue::ExternalLinkage;
1494 case lltok::kw_private:
1495 return GlobalValue::PrivateLinkage;
1496 case lltok::kw_internal:
1497 return GlobalValue::InternalLinkage;
1498 case lltok::kw_weak:
1499 return GlobalValue::WeakAnyLinkage;
1500 case lltok::kw_weak_odr:
1501 return GlobalValue::WeakODRLinkage;
1502 case lltok::kw_linkonce:
1503 return GlobalValue::LinkOnceAnyLinkage;
1504 case lltok::kw_linkonce_odr:
1505 return GlobalValue::LinkOnceODRLinkage;
1506 case lltok::kw_available_externally:
1507 return GlobalValue::AvailableExternallyLinkage;
1508 case lltok::kw_appending:
1509 return GlobalValue::AppendingLinkage;
1510 case lltok::kw_common:
1511 return GlobalValue::CommonLinkage;
1512 case lltok::kw_extern_weak:
1513 return GlobalValue::ExternalWeakLinkage;
1514 case lltok::kw_external:
1515 return GlobalValue::ExternalLinkage;
1516 }
1517}
1518
Chris Lattnerac161bf2009-01-02 07:01:27 +00001519/// ParseOptionalLinkage
1520/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001521/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001522/// ::= 'internal'
1523/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001524/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001525/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001526/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001527/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001528/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001529/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001530/// ::= 'extern_weak'
1531/// ::= 'external'
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001532bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1533 unsigned &Visibility,
1534 unsigned &DLLStorageClass) {
Rafael Espindolac6269912016-05-10 17:16:45 +00001535 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1536 if (HasLinkage)
1537 Lex.Lex();
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001538 ParseOptionalVisibility(Visibility);
1539 ParseOptionalDLLStorageClass(DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001540 return false;
1541}
1542
1543/// ParseOptionalVisibility
1544/// ::= /*empty*/
1545/// ::= 'default'
1546/// ::= 'hidden'
1547/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001548///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001549void LLParser::ParseOptionalVisibility(unsigned &Res) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001550 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001551 default:
1552 Res = GlobalValue::DefaultVisibility;
1553 return;
1554 case lltok::kw_default:
1555 Res = GlobalValue::DefaultVisibility;
1556 break;
1557 case lltok::kw_hidden:
1558 Res = GlobalValue::HiddenVisibility;
1559 break;
1560 case lltok::kw_protected:
1561 Res = GlobalValue::ProtectedVisibility;
1562 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001563 }
1564 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001565}
1566
Nico Rieck7157bb72014-01-14 15:22:47 +00001567/// ParseOptionalDLLStorageClass
1568/// ::= /*empty*/
1569/// ::= 'dllimport'
1570/// ::= 'dllexport'
1571///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001572void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
Nico Rieck7157bb72014-01-14 15:22:47 +00001573 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001574 default:
1575 Res = GlobalValue::DefaultStorageClass;
1576 return;
1577 case lltok::kw_dllimport:
1578 Res = GlobalValue::DLLImportStorageClass;
1579 break;
1580 case lltok::kw_dllexport:
1581 Res = GlobalValue::DLLExportStorageClass;
1582 break;
Nico Rieck7157bb72014-01-14 15:22:47 +00001583 }
1584 Lex.Lex();
Nico Rieck7157bb72014-01-14 15:22:47 +00001585}
1586
Chris Lattnerac161bf2009-01-02 07:01:27 +00001587/// ParseOptionalCallingConv
1588/// ::= /*empty*/
1589/// ::= 'ccc'
1590/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001591/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001592/// ::= 'coldcc'
1593/// ::= 'x86_stdcallcc'
1594/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001595/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001596/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001597/// ::= 'arm_apcscc'
1598/// ::= 'arm_aapcscc'
1599/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001600/// ::= 'msp430_intrcc'
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001601/// ::= 'avr_intrcc'
1602/// ::= 'avr_signalcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001603/// ::= 'ptx_kernel'
1604/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001605/// ::= 'spir_func'
1606/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001607/// ::= 'x86_64_sysvcc'
1608/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001609/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001610/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001611/// ::= 'preserve_mostcc'
1612/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001613/// ::= 'ghccc'
Manman Renf8bdd882016-04-05 22:41:47 +00001614/// ::= 'swiftcc'
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001615/// ::= 'x86_intrcc'
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001616/// ::= 'hhvmcc'
1617/// ::= 'hhvm_ccc'
Manman Ren19c7bbe2015-12-04 17:40:13 +00001618/// ::= 'cxx_fast_tlscc'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001619/// ::= 'amdgpu_vs'
1620/// ::= 'amdgpu_tcs'
1621/// ::= 'amdgpu_tes'
1622/// ::= 'amdgpu_gs'
1623/// ::= 'amdgpu_ps'
1624/// ::= 'amdgpu_cs'
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001625/// ::= 'amdgpu_kernel'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001626/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001627///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001628bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001629 switch (Lex.getKind()) {
1630 default: CC = CallingConv::C; return false;
1631 case lltok::kw_ccc: CC = CallingConv::C; break;
1632 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1633 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1634 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1635 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001636 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001637 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001638 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1639 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1640 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001641 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001642 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1643 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001644 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1645 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001646 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1647 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001648 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001649 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1650 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001651 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001652 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001653 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1654 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001655 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Manman Renf8bdd882016-04-05 22:41:47 +00001656 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001657 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001658 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1659 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
Manman Ren19c7bbe2015-12-04 17:40:13 +00001660 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001661 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
1662 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1663 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1664 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001665 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001666 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001667 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001668 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001669 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001670 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001671
Chris Lattnerac161bf2009-01-02 07:01:27 +00001672 Lex.Lex();
1673 return false;
1674}
1675
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001676/// ParseMetadataAttachment
1677/// ::= !dbg !42
1678bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1679 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1680
1681 std::string Name = Lex.getStrVal();
1682 Kind = M->getMDKindID(Name);
1683 Lex.Lex();
1684
1685 return ParseMDNode(MD);
1686}
1687
Chris Lattner5c427632009-12-30 05:31:19 +00001688/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001689/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001690bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001691 do {
1692 if (Lex.getKind() != lltok::MetadataVar)
1693 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001694
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001695 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001696 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001697 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001698 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001699
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001700 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001701 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001702 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001703
Chris Lattner596760d2009-12-29 21:25:40 +00001704 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001705 } while (EatIfPresent(lltok::comma));
1706 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001707}
1708
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001709/// ParseOptionalFunctionMetadata
1710/// ::= (!dbg !57)*
1711bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
1712 while (Lex.getKind() == lltok::MetadataVar) {
1713 unsigned MDK;
1714 MDNode *N;
1715 if (ParseMetadataAttachment(MDK, N))
1716 return true;
1717
1718 F.setMetadata(MDK, N);
1719 }
1720 return false;
1721}
1722
Chris Lattnerac161bf2009-01-02 07:01:27 +00001723/// ParseOptionalAlignment
1724/// ::= /* empty */
1725/// ::= 'align' 4
1726bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1727 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001728 if (!EatIfPresent(lltok::kw_align))
1729 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001730 LocTy AlignLoc = Lex.getLoc();
1731 if (ParseUInt32(Alignment)) return true;
1732 if (!isPowerOf2_32(Alignment))
1733 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001734 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001735 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001736 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001737}
1738
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001739/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00001740/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001741/// ::= AttrKind '(' 4 ')'
1742///
1743/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1744bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1745 uint64_t &Bytes) {
1746 assert((AttrKind == lltok::kw_dereferenceable ||
1747 AttrKind == lltok::kw_dereferenceable_or_null) &&
1748 "contract!");
1749
Hal Finkelb0407ba2014-07-18 15:51:28 +00001750 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001751 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001752 return false;
1753 LocTy ParenLoc = Lex.getLoc();
1754 if (!EatIfPresent(lltok::lparen))
1755 return Error(ParenLoc, "expected '('");
1756 LocTy DerefLoc = Lex.getLoc();
1757 if (ParseUInt64(Bytes)) return true;
1758 ParenLoc = Lex.getLoc();
1759 if (!EatIfPresent(lltok::rparen))
1760 return Error(ParenLoc, "expected ')'");
1761 if (!Bytes)
1762 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1763 return false;
1764}
1765
Chris Lattnerb2f39502009-12-30 05:44:30 +00001766/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001767/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001768/// ::= ',' align 4
1769///
1770/// This returns with AteExtraComma set to true if it ate an excess comma at the
1771/// end.
1772bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1773 bool &AteExtraComma) {
1774 AteExtraComma = false;
1775 while (EatIfPresent(lltok::comma)) {
1776 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001777 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001778 AteExtraComma = true;
1779 return false;
1780 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001781
Chris Lattner95b0ff42010-04-23 00:50:50 +00001782 if (Lex.getKind() != lltok::kw_align)
1783 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001784
Chris Lattner95b0ff42010-04-23 00:50:50 +00001785 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001786 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001787
Devang Patelea8a4b92009-09-17 23:04:48 +00001788 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001789}
1790
George Burgess IV278199f2016-04-12 01:05:35 +00001791bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
1792 Optional<unsigned> &HowManyArg) {
1793 Lex.Lex();
1794
1795 auto StartParen = Lex.getLoc();
1796 if (!EatIfPresent(lltok::lparen))
1797 return Error(StartParen, "expected '('");
1798
1799 if (ParseUInt32(BaseSizeArg))
1800 return true;
1801
1802 if (EatIfPresent(lltok::comma)) {
1803 auto HowManyAt = Lex.getLoc();
1804 unsigned HowMany;
1805 if (ParseUInt32(HowMany))
1806 return true;
1807 if (HowMany == BaseSizeArg)
1808 return Error(HowManyAt,
1809 "'allocsize' indices can't refer to the same parameter");
1810 HowManyArg = HowMany;
1811 } else
1812 HowManyArg = None;
1813
1814 auto EndParen = Lex.getLoc();
1815 if (!EatIfPresent(lltok::rparen))
1816 return Error(EndParen, "expected ')'");
1817 return false;
1818}
1819
Eli Friedmanfee02c62011-07-25 23:16:38 +00001820/// ParseScopeAndOrdering
1821/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1822/// else: ::=
1823///
1824/// This sets Scope and Ordering to the parsed values.
1825bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1826 AtomicOrdering &Ordering) {
1827 if (!isAtomic)
1828 return false;
1829
1830 Scope = CrossThread;
1831 if (EatIfPresent(lltok::kw_singlethread))
1832 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001833
1834 return ParseOrdering(Ordering);
1835}
1836
1837/// ParseOrdering
1838/// ::= AtomicOrdering
1839///
1840/// This sets Ordering to the parsed value.
1841bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001842 switch (Lex.getKind()) {
1843 default: return TokError("Expected ordering on atomic instruction");
JF Bastien800f87a2016-04-06 21:19:33 +00001844 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
1845 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
1846 // Not specified yet:
1847 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
1848 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
1849 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
1850 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
1851 case lltok::kw_seq_cst:
1852 Ordering = AtomicOrdering::SequentiallyConsistent;
1853 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00001854 }
1855 Lex.Lex();
1856 return false;
1857}
1858
Charles Davisbe5557e2010-02-12 00:31:15 +00001859/// ParseOptionalStackAlignment
1860/// ::= /* empty */
1861/// ::= 'alignstack' '(' 4 ')'
1862bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1863 Alignment = 0;
1864 if (!EatIfPresent(lltok::kw_alignstack))
1865 return false;
1866 LocTy ParenLoc = Lex.getLoc();
1867 if (!EatIfPresent(lltok::lparen))
1868 return Error(ParenLoc, "expected '('");
1869 LocTy AlignLoc = Lex.getLoc();
1870 if (ParseUInt32(Alignment)) return true;
1871 ParenLoc = Lex.getLoc();
1872 if (!EatIfPresent(lltok::rparen))
1873 return Error(ParenLoc, "expected ')'");
1874 if (!isPowerOf2_32(Alignment))
1875 return Error(AlignLoc, "stack alignment is not a power of two");
1876 return false;
1877}
Devang Patelea8a4b92009-09-17 23:04:48 +00001878
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001879/// ParseIndexList - This parses the index list for an insert/extractvalue
1880/// instruction. This sets AteExtraComma in the case where we eat an extra
1881/// comma at the end of the line and find that it is followed by metadata.
1882/// Clients that don't allow metadata can call the version of this function that
1883/// only takes one argument.
1884///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001885/// ParseIndexList
1886/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001887///
1888bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1889 bool &AteExtraComma) {
1890 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001891
Chris Lattnerac161bf2009-01-02 07:01:27 +00001892 if (Lex.getKind() != lltok::comma)
1893 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001894
Chris Lattner3822f632009-01-02 08:05:26 +00001895 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001896 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00001897 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001898 AteExtraComma = true;
1899 return false;
1900 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001901 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001902 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001903 Indices.push_back(Idx);
1904 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001905
Chris Lattnerac161bf2009-01-02 07:01:27 +00001906 return false;
1907}
1908
1909//===----------------------------------------------------------------------===//
1910// Type Parsing.
1911//===----------------------------------------------------------------------===//
1912
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001913/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001914bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001915 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001916 switch (Lex.getKind()) {
1917 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001918 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001919 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001920 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001921 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001922 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001923 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001924 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001925 // Type ::= StructType
1926 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001927 return true;
1928 break;
1929 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001930 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001931 Lex.Lex(); // eat the lsquare.
1932 if (ParseArrayVectorType(Result, false))
1933 return true;
1934 break;
1935 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001936 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00001937 Lex.Lex();
1938 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001939 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00001940 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001941 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001942 } else if (ParseArrayVectorType(Result, true))
1943 return true;
1944 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001945 case lltok::LocalVar: {
1946 // Type ::= %foo
1947 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001948
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001949 // If the type hasn't been defined yet, create a forward definition and
1950 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001951 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001952 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001953 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001954 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001955 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001956 Lex.Lex();
1957 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001958 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001959
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001960 case lltok::LocalVarID: {
1961 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001962 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001963
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001964 // If the type hasn't been defined yet, create a forward definition and
1965 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001966 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001967 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001968 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001969 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001970 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001971 Lex.Lex();
1972 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001973 }
1974 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001975
1976 // Parse the type suffixes.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001977 while (1) {
1978 switch (Lex.getKind()) {
1979 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001980 default:
1981 if (!AllowVoid && Result->isVoidTy())
1982 return Error(TypeLoc, "void type only allowed for function results");
1983 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001984
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001985 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001986 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001987 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001988 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001989 if (Result->isVoidTy())
1990 return TokError("pointers to void are invalid - use i8* instead");
1991 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001992 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001993 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001994 Lex.Lex();
1995 break;
1996
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001997 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001998 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001999 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002000 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002001 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00002002 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002003 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002004 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002005 unsigned AddrSpace;
2006 if (ParseOptionalAddrSpace(AddrSpace) ||
2007 ParseToken(lltok::star, "expected '*' in address space"))
2008 return true;
2009
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002010 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002011 break;
2012 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002013
Chris Lattnerac161bf2009-01-02 07:01:27 +00002014 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2015 case lltok::lparen:
2016 if (ParseFunctionType(Result))
2017 return true;
2018 break;
2019 }
2020 }
2021}
2022
2023/// ParseParameterList
2024/// ::= '(' ')'
2025/// ::= '(' Arg (',' Arg)* ')'
2026/// Arg
2027/// ::= Type OptionalAttributes Value OptionalAttributes
2028bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00002029 PerFunctionState &PFS, bool IsMustTailCall,
2030 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002031 if (ParseToken(lltok::lparen, "expected '(' in call"))
2032 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002033
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002034 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002035 while (Lex.getKind() != lltok::rparen) {
2036 // If this isn't the first argument, we need a comma.
2037 if (!ArgList.empty() &&
2038 ParseToken(lltok::comma, "expected ',' in argument list"))
2039 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002040
Reid Kleckner83498642014-08-26 00:33:28 +00002041 // Parse an ellipsis if this is a musttail call in a variadic function.
2042 if (Lex.getKind() == lltok::dotdotdot) {
2043 const char *Msg = "unexpected ellipsis in argument list for ";
2044 if (!IsMustTailCall)
2045 return TokError(Twine(Msg) + "non-musttail call");
2046 if (!InVarArgsFunc)
2047 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2048 Lex.Lex(); // Lex the '...', it is purely for readability.
2049 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2050 }
2051
Chris Lattnerac161bf2009-01-02 07:01:27 +00002052 // Parse the argument.
2053 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00002054 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002055 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002056 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00002057 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002058 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00002059
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002060 if (ArgTy->isMetadataTy()) {
2061 if (ParseMetadataAsValue(V, PFS))
2062 return true;
2063 } else {
2064 // Otherwise, handle normal operands.
2065 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2066 return true;
2067 }
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002068 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
2069 AttrIndex++,
2070 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002071 }
2072
Reid Kleckner83498642014-08-26 00:33:28 +00002073 if (IsMustTailCall && InVarArgsFunc)
2074 return TokError("expected '...' at end of argument list for musttail call "
2075 "in varargs function");
2076
Chris Lattnerac161bf2009-01-02 07:01:27 +00002077 Lex.Lex(); // Lex the ')'.
2078 return false;
2079}
2080
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002081/// ParseOptionalOperandBundles
2082/// ::= /*empty*/
2083/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2084///
2085/// OperandBundle
2086/// ::= bundle-tag '(' ')'
2087/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2088///
2089/// bundle-tag ::= String Constant
2090bool LLParser::ParseOptionalOperandBundles(
2091 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2092 LocTy BeginLoc = Lex.getLoc();
2093 if (!EatIfPresent(lltok::lsquare))
2094 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002095
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002096 while (Lex.getKind() != lltok::rsquare) {
2097 // If this isn't the first operand bundle, we need a comma.
2098 if (!BundleList.empty() &&
2099 ParseToken(lltok::comma, "expected ',' in input list"))
2100 return true;
2101
2102 std::string Tag;
2103 if (ParseStringConstant(Tag))
2104 return true;
2105
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002106 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2107 return true;
2108
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002109 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002110 while (Lex.getKind() != lltok::rparen) {
2111 // If this isn't the first input, we need a comma.
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002112 if (!Inputs.empty() &&
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002113 ParseToken(lltok::comma, "expected ',' in input list"))
2114 return true;
2115
2116 Type *Ty = nullptr;
2117 Value *Input = nullptr;
2118 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2119 return true;
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002120 Inputs.push_back(Input);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002121 }
2122
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002123 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2124
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002125 Lex.Lex(); // Lex the ')'.
2126 }
2127
2128 if (BundleList.empty())
2129 return Error(BeginLoc, "operand bundle set must not be empty");
2130
2131 Lex.Lex(); // Lex the ']'.
2132 return false;
2133}
Chris Lattnerac161bf2009-01-02 07:01:27 +00002134
Chris Lattner2ed06b42009-01-05 18:34:07 +00002135/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002136/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00002137/// ::= '(' ArgTypeListI ')'
2138/// ArgTypeListI
2139/// ::= /*empty*/
2140/// ::= '...'
2141/// ::= ArgTypeList ',' '...'
2142/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00002143///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002144bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2145 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00002146 isVarArg = false;
2147 assert(Lex.getKind() == lltok::lparen);
2148 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002149
Chris Lattnerac161bf2009-01-02 07:01:27 +00002150 if (Lex.getKind() == lltok::rparen) {
2151 // empty
2152 } else if (Lex.getKind() == lltok::dotdotdot) {
2153 isVarArg = true;
2154 Lex.Lex();
2155 } else {
2156 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002157 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002158 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002159 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002160
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002161 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002162 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002163
Chris Lattnerfdd87902009-10-05 05:54:46 +00002164 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002165 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002166
Chris Lattnerdef19492011-06-17 06:36:20 +00002167 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002168 Name = Lex.getStrVal();
2169 Lex.Lex();
2170 }
Chris Lattner3822f632009-01-02 08:05:26 +00002171
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002172 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00002173 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002174
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002175 unsigned AttrIndex = 1;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002176 ArgList.emplace_back(TypeLoc, ArgTy, AttributeSet::get(ArgTy->getContext(),
2177 AttrIndex++, Attrs),
2178 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002179
Chris Lattner3822f632009-01-02 08:05:26 +00002180 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002181 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00002182 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002183 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002184 break;
2185 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002186
Chris Lattnerac161bf2009-01-02 07:01:27 +00002187 // Otherwise must be an argument type.
2188 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00002189 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00002190
Chris Lattnerfdd87902009-10-05 05:54:46 +00002191 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002192 return Error(TypeLoc, "argument can not have void type");
2193
Chris Lattnerdef19492011-06-17 06:36:20 +00002194 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002195 Name = Lex.getStrVal();
2196 Lex.Lex();
2197 } else {
2198 Name = "";
2199 }
Chris Lattner3822f632009-01-02 08:05:26 +00002200
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002201 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00002202 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002203
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002204 ArgList.emplace_back(
2205 TypeLoc, ArgTy,
2206 AttributeSet::get(ArgTy->getContext(), AttrIndex++, Attrs),
2207 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002208 }
2209 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002210
Chris Lattner3822f632009-01-02 08:05:26 +00002211 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002212}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002213
Chris Lattnerac161bf2009-01-02 07:01:27 +00002214/// ParseFunctionType
2215/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002216bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002217 assert(Lex.getKind() == lltok::lparen);
2218
Chris Lattnerce473c72009-01-05 08:04:33 +00002219 if (!FunctionType::isValidReturnType(Result))
2220 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002221
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002222 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002223 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002224 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002225 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002226
Chris Lattnerac161bf2009-01-02 07:01:27 +00002227 // Reject names on the arguments lists.
2228 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2229 if (!ArgList[i].Name.empty())
2230 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002231 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00002232 return Error(ArgList[i].Loc,
2233 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002234 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002235
Jay Foadb804a2b2011-07-12 14:06:48 +00002236 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002237 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002238 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002239
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002240 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002241 return false;
2242}
2243
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002244/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2245/// other structs.
2246bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2247 SmallVector<Type*, 8> Elts;
2248 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002249
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002250 Result = StructType::get(Context, Elts, Packed);
2251 return false;
2252}
2253
2254/// ParseStructDefinition - Parse a struct in a 'type' definition.
2255bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2256 std::pair<Type*, LocTy> &Entry,
2257 Type *&ResultTy) {
2258 // If the type was already defined, diagnose the redefinition.
2259 if (Entry.first && !Entry.second.isValid())
2260 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002261
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002262 // If we have opaque, just return without filling in the definition for the
2263 // struct. This counts as a definition as far as the .ll file goes.
2264 if (EatIfPresent(lltok::kw_opaque)) {
2265 // This type is being defined, so clear the location to indicate this.
2266 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002267
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002268 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002269 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002270 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002271 ResultTy = Entry.first;
2272 return false;
2273 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002274
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002275 // If the type starts with '<', then it is either a packed struct or a vector.
2276 bool isPacked = EatIfPresent(lltok::less);
2277
2278 // If we don't have a struct, then we have a random type alias, which we
2279 // accept for compatibility with old files. These types are not allowed to be
2280 // forward referenced and not allowed to be recursive.
2281 if (Lex.getKind() != lltok::lbrace) {
2282 if (Entry.first)
2283 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002284
Craig Topper2617dcc2014-04-15 06:32:26 +00002285 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002286 if (isPacked)
2287 return ParseArrayVectorType(ResultTy, true);
2288 return ParseType(ResultTy);
2289 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002290
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002291 // This type is being defined, so clear the location to indicate this.
2292 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002293
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002294 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002295 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002296 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002297
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002298 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002299
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002300 SmallVector<Type*, 8> Body;
2301 if (ParseStructBody(Body) ||
2302 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2303 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002304
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002305 STy->setBody(Body, isPacked);
2306 ResultTy = STy;
2307 return false;
2308}
2309
2310
Chris Lattnerac161bf2009-01-02 07:01:27 +00002311/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002312/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002313/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002314/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002315/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002316/// ::= '<' '{' Type (',' Type)* '}' '>'
2317bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002318 assert(Lex.getKind() == lltok::lbrace);
2319 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002320
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002321 // Handle the empty struct.
2322 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002323 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002324
Chris Lattnerf880ca22009-03-09 04:49:14 +00002325 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002326 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002327 if (ParseType(Ty)) return true;
2328 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002329
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002330 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002331 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002332
Chris Lattner3822f632009-01-02 08:05:26 +00002333 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002334 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002335 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002336
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002337 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002338 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002339
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002340 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002341 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002342
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002343 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002344}
2345
2346/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2347/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002348/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002349/// ::= '[' APSINTVAL 'x' Types ']'
2350/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002351bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002352 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2353 Lex.getAPSIntVal().getBitWidth() > 64)
2354 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002355
Chris Lattnerac161bf2009-01-02 07:01:27 +00002356 LocTy SizeLoc = Lex.getLoc();
2357 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002358 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002359
Chris Lattner3822f632009-01-02 08:05:26 +00002360 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2361 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002362
2363 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002364 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002365 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002366
Chris Lattner3822f632009-01-02 08:05:26 +00002367 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2368 "expected end of sequential type"))
2369 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002370
Chris Lattnerac161bf2009-01-02 07:01:27 +00002371 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002372 if (Size == 0)
2373 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002374 if ((unsigned)Size != Size)
2375 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002376 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002377 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002378 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002379 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002380 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002381 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002382 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002383 }
2384 return false;
2385}
2386
2387//===----------------------------------------------------------------------===//
2388// Function Semantic Analysis.
2389//===----------------------------------------------------------------------===//
2390
Chris Lattner3432c622009-10-28 03:39:23 +00002391LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2392 int functionNumber)
2393 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002394
2395 // Insert unnamed arguments into the NumberedVals list.
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +00002396 for (Argument &A : F.args())
2397 if (!A.hasName())
2398 NumberedVals.push_back(&A);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002399}
2400
2401LLParser::PerFunctionState::~PerFunctionState() {
2402 // If there were any forward referenced non-basicblock values, delete them.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002403
David Blaikie9ebdc692015-09-21 21:07:50 +00002404 for (const auto &P : ForwardRefVals) {
2405 if (isa<BasicBlock>(P.second.first))
2406 continue;
2407 P.second.first->replaceAllUsesWith(
2408 UndefValue::get(P.second.first->getType()));
2409 delete P.second.first;
2410 }
2411
2412 for (const auto &P : ForwardRefValIDs) {
2413 if (isa<BasicBlock>(P.second.first))
2414 continue;
2415 P.second.first->replaceAllUsesWith(
2416 UndefValue::get(P.second.first->getType()));
2417 delete P.second.first;
2418 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002419}
2420
Chris Lattner3432c622009-10-28 03:39:23 +00002421bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002422 if (!ForwardRefVals.empty())
2423 return P.Error(ForwardRefVals.begin()->second.second,
2424 "use of undefined value '%" + ForwardRefVals.begin()->first +
2425 "'");
2426 if (!ForwardRefValIDs.empty())
2427 return P.Error(ForwardRefValIDs.begin()->second.second,
2428 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002429 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002430 return false;
2431}
2432
2433
2434/// GetVal - Get a value with the specified name or ID, creating a
2435/// forward reference record if needed. This can return null if the value
2436/// exists but does not have the right type.
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002437Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
David Majnemer8a1c45d2015-12-12 05:38:55 +00002438 LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002439 // Look this name up in the normal function symbol table.
2440 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002441
Chris Lattnerac161bf2009-01-02 07:01:27 +00002442 // If this is a forward reference for the value, see if we already created a
2443 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002444 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002445 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002446 if (I != ForwardRefVals.end())
2447 Val = I->second.first;
2448 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002449
Chris Lattnerac161bf2009-01-02 07:01:27 +00002450 // If we have the value in the symbol table or fwd-ref table, return it.
2451 if (Val) {
2452 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002453 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002454 P.Error(Loc, "'%" + Name + "' is not a basic block");
2455 else
2456 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002457 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002458 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002459 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002460
Chris Lattnerac161bf2009-01-02 07:01:27 +00002461 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002462 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002463 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002464 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002465 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002466
Chris Lattnerac161bf2009-01-02 07:01:27 +00002467 // Otherwise, create a new forward reference for this value and remember it.
2468 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002469 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002470 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002471 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002472 FwdVal = new Argument(Ty, Name);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002473 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002474
Chris Lattnerac161bf2009-01-02 07:01:27 +00002475 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2476 return FwdVal;
2477}
2478
David Majnemer8a1c45d2015-12-12 05:38:55 +00002479Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002480 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002481 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002482
Chris Lattnerac161bf2009-01-02 07:01:27 +00002483 // If this is a forward reference for the value, see if we already created a
2484 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002485 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002486 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002487 if (I != ForwardRefValIDs.end())
2488 Val = I->second.first;
2489 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002490
Chris Lattnerac161bf2009-01-02 07:01:27 +00002491 // If we have the value in the symbol table or fwd-ref table, return it.
2492 if (Val) {
2493 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002494 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002495 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002496 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002497 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002498 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002499 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002500 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002501
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002502 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002503 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002504 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002505 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002506
Chris Lattnerac161bf2009-01-02 07:01:27 +00002507 // Otherwise, create a new forward reference for this value and remember it.
2508 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002509 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002510 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002511 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002512 FwdVal = new Argument(Ty);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002513 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002514
Chris Lattnerac161bf2009-01-02 07:01:27 +00002515 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2516 return FwdVal;
2517}
2518
2519/// SetInstName - After an instruction is parsed and inserted into its
2520/// basic block, this installs its name.
2521bool LLParser::PerFunctionState::SetInstName(int NameID,
2522 const std::string &NameStr,
2523 LocTy NameLoc, Instruction *Inst) {
2524 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002525 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002526 if (NameID != -1 || !NameStr.empty())
2527 return P.Error(NameLoc, "instructions returning void cannot have a name");
2528 return false;
2529 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002530
Chris Lattnerac161bf2009-01-02 07:01:27 +00002531 // If this was a numbered instruction, verify that the instruction is the
2532 // expected value and resolve any forward references.
2533 if (NameStr.empty()) {
2534 // If neither a name nor an ID was specified, just use the next ID.
2535 if (NameID == -1)
2536 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002537
Chris Lattnerac161bf2009-01-02 07:01:27 +00002538 if (unsigned(NameID) != NumberedVals.size())
2539 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002540 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002541
David Blaikie9ebdc692015-09-21 21:07:50 +00002542 auto FI = ForwardRefValIDs.find(NameID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002543 if (FI != ForwardRefValIDs.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002544 Value *Sentinel = FI->second.first;
2545 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002546 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002547 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002548
2549 Sentinel->replaceAllUsesWith(Inst);
2550 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002551 ForwardRefValIDs.erase(FI);
2552 }
2553
2554 NumberedVals.push_back(Inst);
2555 return false;
2556 }
2557
2558 // Otherwise, the instruction had a name. Resolve forward refs and set it.
David Blaikie9ebdc692015-09-21 21:07:50 +00002559 auto FI = ForwardRefVals.find(NameStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002560 if (FI != ForwardRefVals.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002561 Value *Sentinel = FI->second.first;
2562 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002563 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002564 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002565
2566 Sentinel->replaceAllUsesWith(Inst);
2567 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002568 ForwardRefVals.erase(FI);
2569 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002570
Chris Lattnerac161bf2009-01-02 07:01:27 +00002571 // Set the name on the instruction.
2572 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002573
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002574 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002575 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002576 NameStr + "'");
2577 return false;
2578}
2579
2580/// GetBB - Get a basic block with the specified name or ID, creating a
2581/// forward reference record if needed.
2582BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2583 LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002584 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2585 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002586}
2587
2588BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002589 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2590 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002591}
2592
2593/// DefineBB - Define the specified basic block, which is either named or
2594/// unnamed. If there is an error, this returns null otherwise it returns
2595/// the block being defined.
2596BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2597 LocTy Loc) {
2598 BasicBlock *BB;
2599 if (Name.empty())
2600 BB = GetBB(NumberedVals.size(), Loc);
2601 else
2602 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002603 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002604
Chris Lattnerac161bf2009-01-02 07:01:27 +00002605 // Move the block to the end of the function. Forward ref'd blocks are
2606 // inserted wherever they happen to be referenced.
2607 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002608
Chris Lattnerac161bf2009-01-02 07:01:27 +00002609 // Remove the block from forward ref sets.
2610 if (Name.empty()) {
2611 ForwardRefValIDs.erase(NumberedVals.size());
2612 NumberedVals.push_back(BB);
2613 } else {
2614 // BB forward references are already in the function symbol table.
2615 ForwardRefVals.erase(Name);
2616 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002617
Chris Lattnerac161bf2009-01-02 07:01:27 +00002618 return BB;
2619}
2620
2621//===----------------------------------------------------------------------===//
2622// Constants.
2623//===----------------------------------------------------------------------===//
2624
2625/// ParseValID - Parse an abstract value that doesn't necessarily have a
2626/// type implied. For example, if we parse "4" we don't know what integer type
2627/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002628/// sanity. PFS is used to convert function-local operands of metadata (since
2629/// metadata operands are not just parsed here but also converted to values).
2630/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002631bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002632 ID.Loc = Lex.getLoc();
2633 switch (Lex.getKind()) {
2634 default: return TokError("expected value token");
2635 case lltok::GlobalID: // @42
2636 ID.UIntVal = Lex.getUIntVal();
2637 ID.Kind = ValID::t_GlobalID;
2638 break;
2639 case lltok::GlobalVar: // @foo
2640 ID.StrVal = Lex.getStrVal();
2641 ID.Kind = ValID::t_GlobalName;
2642 break;
2643 case lltok::LocalVarID: // %42
2644 ID.UIntVal = Lex.getUIntVal();
2645 ID.Kind = ValID::t_LocalID;
2646 break;
2647 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002648 ID.StrVal = Lex.getStrVal();
2649 ID.Kind = ValID::t_LocalName;
2650 break;
2651 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002652 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002653 ID.Kind = ValID::t_APSInt;
2654 break;
2655 case lltok::APFloat:
2656 ID.APFloatVal = Lex.getAPFloatVal();
2657 ID.Kind = ValID::t_APFloat;
2658 break;
2659 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002660 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002661 ID.Kind = ValID::t_Constant;
2662 break;
2663 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002664 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002665 ID.Kind = ValID::t_Constant;
2666 break;
2667 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2668 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2669 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
David Majnemerf0f224d2015-11-11 21:57:16 +00002670 case lltok::kw_none: ID.Kind = ValID::t_None; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002671
Chris Lattnerac161bf2009-01-02 07:01:27 +00002672 case lltok::lbrace: {
2673 // ValID ::= '{' ConstVector '}'
2674 Lex.Lex();
2675 SmallVector<Constant*, 16> Elts;
2676 if (ParseGlobalValueVector(Elts) ||
2677 ParseToken(lltok::rbrace, "expected end of struct constant"))
2678 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002679
David Blaikieadbda4b2015-08-03 20:08:41 +00002680 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002681 ID.UIntVal = Elts.size();
David Blaikieadbda4b2015-08-03 20:08:41 +00002682 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2683 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002684 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002685 return false;
2686 }
2687 case lltok::less: {
2688 // ValID ::= '<' ConstVector '>' --> Vector.
2689 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2690 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002691 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002692
Chris Lattnerac161bf2009-01-02 07:01:27 +00002693 SmallVector<Constant*, 16> Elts;
2694 LocTy FirstEltLoc = Lex.getLoc();
2695 if (ParseGlobalValueVector(Elts) ||
2696 (isPackedStruct &&
2697 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2698 ParseToken(lltok::greater, "expected end of constant"))
2699 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002700
Chris Lattnerac161bf2009-01-02 07:01:27 +00002701 if (isPackedStruct) {
David Blaikieadbda4b2015-08-03 20:08:41 +00002702 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2703 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2704 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002705 ID.UIntVal = Elts.size();
2706 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002707 return false;
2708 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002709
Chris Lattnerac161bf2009-01-02 07:01:27 +00002710 if (Elts.empty())
2711 return Error(ID.Loc, "constant vector must not be empty");
2712
Duncan Sands9dff9be2010-02-15 16:12:20 +00002713 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002714 !Elts[0]->getType()->isFloatingPointTy() &&
2715 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002716 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002717 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002718
Chris Lattnerac161bf2009-01-02 07:01:27 +00002719 // Verify that all the vector elements have the same type.
2720 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2721 if (Elts[i]->getType() != Elts[0]->getType())
2722 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002723 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002724 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002725
Chris Lattner69229312011-02-15 00:14:00 +00002726 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002727 ID.Kind = ValID::t_Constant;
2728 return false;
2729 }
2730 case lltok::lsquare: { // Array Constant
2731 Lex.Lex();
2732 SmallVector<Constant*, 16> Elts;
2733 LocTy FirstEltLoc = Lex.getLoc();
2734 if (ParseGlobalValueVector(Elts) ||
2735 ParseToken(lltok::rsquare, "expected end of array constant"))
2736 return true;
2737
2738 // Handle empty element.
2739 if (Elts.empty()) {
2740 // Use undef instead of an array because it's inconvenient to determine
2741 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002742 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002743 return false;
2744 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002745
Chris Lattnerac161bf2009-01-02 07:01:27 +00002746 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002747 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002748 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002749
Owen Anderson4056ca92009-07-29 22:17:13 +00002750 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002751
Chris Lattnerac161bf2009-01-02 07:01:27 +00002752 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002753 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002754 if (Elts[i]->getType() != Elts[0]->getType())
2755 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002756 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002757 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002758 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002759
Jay Foad83be3612011-06-22 09:24:39 +00002760 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002761 ID.Kind = ValID::t_Constant;
2762 return false;
2763 }
2764 case lltok::kw_c: // c "foo"
2765 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002766 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2767 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002768 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2769 ID.Kind = ValID::t_Constant;
2770 return false;
2771
2772 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002773 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2774 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002775 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002776 Lex.Lex();
2777 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002778 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002779 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002780 ParseStringConstant(ID.StrVal) ||
2781 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002782 ParseToken(lltok::StringConstant, "expected constraint string"))
2783 return true;
2784 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002785 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002786 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002787 ID.Kind = ValID::t_InlineAsm;
2788 return false;
2789 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002790
Chris Lattner3432c622009-10-28 03:39:23 +00002791 case lltok::kw_blockaddress: {
2792 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2793 Lex.Lex();
2794
2795 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002796
Chris Lattner3432c622009-10-28 03:39:23 +00002797 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2798 ParseValID(Fn) ||
2799 ParseToken(lltok::comma, "expected comma in block address expression")||
2800 ParseValID(Label) ||
2801 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2802 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002803
Chris Lattner3432c622009-10-28 03:39:23 +00002804 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2805 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002806 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002807 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002808
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002809 // Try to find the function (but skip it if it's forward-referenced).
2810 GlobalValue *GV = nullptr;
2811 if (Fn.Kind == ValID::t_GlobalID) {
2812 if (Fn.UIntVal < NumberedVals.size())
2813 GV = NumberedVals[Fn.UIntVal];
2814 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2815 GV = M->getNamedValue(Fn.StrVal);
2816 }
2817 Function *F = nullptr;
2818 if (GV) {
2819 // Confirm that it's actually a function with a definition.
2820 if (!isa<Function>(GV))
2821 return Error(Fn.Loc, "expected function name in blockaddress");
2822 F = cast<Function>(GV);
2823 if (F->isDeclaration())
2824 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2825 }
2826
2827 if (!F) {
2828 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00002829 GlobalValue *&FwdRef =
David Blaikie871b4112015-08-03 20:55:00 +00002830 ForwardRefBlockAddresses.insert(std::make_pair(
2831 std::move(Fn),
2832 std::map<ValID, GlobalValue *>()))
David Blaikieb9cc6592015-03-04 01:40:07 +00002833 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2834 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002835 if (!FwdRef)
2836 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2837 GlobalValue::InternalLinkage, nullptr, "");
2838 ID.ConstantVal = FwdRef;
2839 ID.Kind = ValID::t_Constant;
2840 return false;
2841 }
2842
2843 // We found the function; now find the basic block. Don't use PFS, since we
2844 // might be inside a constant expression.
2845 BasicBlock *BB;
2846 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2847 if (Label.Kind == ValID::t_LocalID)
2848 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2849 else
2850 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2851 if (!BB)
2852 return Error(Label.Loc, "referenced value is not a basic block");
2853 } else {
2854 if (Label.Kind == ValID::t_LocalID)
2855 return Error(Label.Loc, "cannot take address of numeric label after "
2856 "the function is defined");
2857 BB = dyn_cast_or_null<BasicBlock>(
2858 F->getValueSymbolTable().lookup(Label.StrVal));
2859 if (!BB)
2860 return Error(Label.Loc, "referenced value is not a basic block");
2861 }
2862
2863 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002864 ID.Kind = ValID::t_Constant;
2865 return false;
2866 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002867
Chris Lattnerac161bf2009-01-02 07:01:27 +00002868 case lltok::kw_trunc:
2869 case lltok::kw_zext:
2870 case lltok::kw_sext:
2871 case lltok::kw_fptrunc:
2872 case lltok::kw_fpext:
2873 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002874 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002875 case lltok::kw_uitofp:
2876 case lltok::kw_sitofp:
2877 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002878 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002879 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002880 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002881 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002882 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002883 Constant *SrcVal;
2884 Lex.Lex();
2885 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2886 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002887 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002888 ParseType(DestTy) ||
2889 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2890 return true;
2891 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2892 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002893 getTypeString(SrcVal->getType()) + "' to '" +
2894 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002895 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002896 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002897 ID.Kind = ValID::t_Constant;
2898 return false;
2899 }
2900 case lltok::kw_extractvalue: {
2901 Lex.Lex();
2902 Constant *Val;
2903 SmallVector<unsigned, 4> Indices;
2904 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2905 ParseGlobalTypeAndValue(Val) ||
2906 ParseIndexList(Indices) ||
2907 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2908 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002909
Chris Lattner392be582010-02-12 20:49:41 +00002910 if (!Val->getType()->isAggregateType())
2911 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002912 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002913 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002914 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002915 ID.Kind = ValID::t_Constant;
2916 return false;
2917 }
2918 case lltok::kw_insertvalue: {
2919 Lex.Lex();
2920 Constant *Val0, *Val1;
2921 SmallVector<unsigned, 4> Indices;
2922 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2923 ParseGlobalTypeAndValue(Val0) ||
2924 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2925 ParseGlobalTypeAndValue(Val1) ||
2926 ParseIndexList(Indices) ||
2927 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2928 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002929 if (!Val0->getType()->isAggregateType())
2930 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00002931 Type *IndexedType =
2932 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2933 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002934 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00002935 if (IndexedType != Val1->getType())
2936 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2937 getTypeString(Val1->getType()) +
2938 "' instead of '" + getTypeString(IndexedType) +
2939 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00002940 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002941 ID.Kind = ValID::t_Constant;
2942 return false;
2943 }
2944 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002945 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002946 unsigned PredVal, Opc = Lex.getUIntVal();
2947 Constant *Val0, *Val1;
2948 Lex.Lex();
2949 if (ParseCmpPredicate(PredVal, Opc) ||
2950 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2951 ParseGlobalTypeAndValue(Val0) ||
2952 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2953 ParseGlobalTypeAndValue(Val1) ||
2954 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2955 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002956
Chris Lattnerac161bf2009-01-02 07:01:27 +00002957 if (Val0->getType() != Val1->getType())
2958 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002959
Chris Lattnerac161bf2009-01-02 07:01:27 +00002960 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002961
Chris Lattnerac161bf2009-01-02 07:01:27 +00002962 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002963 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002964 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002965 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002966 } else {
2967 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002968 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002969 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002970 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002971 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002972 }
2973 ID.Kind = ValID::t_Constant;
2974 return false;
2975 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002976
Chris Lattnerac161bf2009-01-02 07:01:27 +00002977 // Binary Operators.
2978 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00002979 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002980 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00002981 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002982 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00002983 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002984 case lltok::kw_udiv:
2985 case lltok::kw_sdiv:
2986 case lltok::kw_fdiv:
2987 case lltok::kw_urem:
2988 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002989 case lltok::kw_frem:
2990 case lltok::kw_shl:
2991 case lltok::kw_lshr:
2992 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002993 bool NUW = false;
2994 bool NSW = false;
2995 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002996 unsigned Opc = Lex.getUIntVal();
2997 Constant *Val0, *Val1;
2998 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00002999 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00003000 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3001 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003002 if (EatIfPresent(lltok::kw_nuw))
3003 NUW = true;
3004 if (EatIfPresent(lltok::kw_nsw)) {
3005 NSW = true;
3006 if (EatIfPresent(lltok::kw_nuw))
3007 NUW = true;
3008 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00003009 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3010 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003011 if (EatIfPresent(lltok::kw_exact))
3012 Exact = true;
3013 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003014 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3015 ParseGlobalTypeAndValue(Val0) ||
3016 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3017 ParseGlobalTypeAndValue(Val1) ||
3018 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3019 return true;
3020 if (Val0->getType() != Val1->getType())
3021 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003022 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003023 if (NUW)
3024 return Error(ModifierLoc, "nuw only applies to integer operations");
3025 if (NSW)
3026 return Error(ModifierLoc, "nsw only applies to integer operations");
3027 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00003028 // Check that the type is valid for the operator.
3029 switch (Opc) {
3030 case Instruction::Add:
3031 case Instruction::Sub:
3032 case Instruction::Mul:
3033 case Instruction::UDiv:
3034 case Instruction::SDiv:
3035 case Instruction::URem:
3036 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003037 case Instruction::Shl:
3038 case Instruction::AShr:
3039 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00003040 if (!Val0->getType()->isIntOrIntVectorTy())
3041 return Error(ID.Loc, "constexpr requires integer operands");
3042 break;
3043 case Instruction::FAdd:
3044 case Instruction::FSub:
3045 case Instruction::FMul:
3046 case Instruction::FDiv:
3047 case Instruction::FRem:
3048 if (!Val0->getType()->isFPOrFPVectorTy())
3049 return Error(ID.Loc, "constexpr requires fp operands");
3050 break;
3051 default: llvm_unreachable("Unknown binary operator!");
3052 }
Dan Gohman1b849082009-09-07 23:54:19 +00003053 unsigned Flags = 0;
3054 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3055 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00003056 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00003057 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00003058 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003059 ID.Kind = ValID::t_Constant;
3060 return false;
3061 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003062
Chris Lattnerac161bf2009-01-02 07:01:27 +00003063 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00003064 case lltok::kw_and:
3065 case lltok::kw_or:
3066 case lltok::kw_xor: {
3067 unsigned Opc = Lex.getUIntVal();
3068 Constant *Val0, *Val1;
3069 Lex.Lex();
3070 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3071 ParseGlobalTypeAndValue(Val0) ||
3072 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3073 ParseGlobalTypeAndValue(Val1) ||
3074 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3075 return true;
3076 if (Val0->getType() != Val1->getType())
3077 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003078 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003079 return Error(ID.Loc,
3080 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003081 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003082 ID.Kind = ValID::t_Constant;
3083 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003084 }
3085
Chris Lattnerac161bf2009-01-02 07:01:27 +00003086 case lltok::kw_getelementptr:
3087 case lltok::kw_shufflevector:
3088 case lltok::kw_insertelement:
3089 case lltok::kw_extractelement:
3090 case lltok::kw_select: {
3091 unsigned Opc = Lex.getUIntVal();
3092 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00003093 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00003094 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003095 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00003096
Dan Gohman1639c392009-07-27 21:53:46 +00003097 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00003098 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00003099
3100 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3101 return true;
3102
3103 LocTy ExplicitTypeLoc = Lex.getLoc();
3104 if (Opc == Instruction::GetElementPtr) {
3105 if (ParseType(Ty) ||
3106 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3107 return true;
3108 }
3109
3110 if (ParseGlobalValueVector(Elts) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003111 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3112 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003113
Chris Lattnerac161bf2009-01-02 07:01:27 +00003114 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00003115 if (Elts.size() == 0 ||
3116 !Elts[0]->getType()->getScalarType()->isPointerTy())
David Majnemer00303b62015-02-22 23:14:52 +00003117 return Error(ID.Loc, "base of getelementptr must be a pointer");
3118
3119 Type *BaseType = Elts[0]->getType();
3120 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00003121 if (Ty != BasePointerType->getElementType())
3122 return Error(
3123 ExplicitTypeLoc,
3124 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003125
Jay Foaded8db7d2011-07-21 14:31:17 +00003126 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00003127 for (Constant *Val : Indices) {
3128 Type *ValTy = Val->getType();
3129 if (!ValTy->getScalarType()->isIntegerTy())
3130 return Error(ID.Loc, "getelementptr index must be an integer");
3131 if (ValTy->isVectorTy() != BaseType->isVectorTy())
3132 return Error(ID.Loc, "getelementptr index type missmatch");
3133 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00003134 unsigned ValNumEl = ValTy->getVectorNumElements();
3135 unsigned PtrNumEl = BaseType->getVectorNumElements();
David Majnemer00303b62015-02-22 23:14:52 +00003136 if (ValNumEl != PtrNumEl)
3137 return Error(
3138 ID.Loc,
3139 "getelementptr vector index has a wrong number of elements");
3140 }
3141 }
3142
Craig Toppere3dcce92015-08-01 22:20:21 +00003143 SmallPtrSet<Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00003144 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00003145 return Error(ID.Loc, "base element of getelementptr must be sized");
3146
David Blaikie4a2e73b2015-04-02 18:55:32 +00003147 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00003148 return Error(ID.Loc, "invalid getelementptr indices");
David Blaikie4a2e73b2015-04-02 18:55:32 +00003149 ID.ConstantVal =
3150 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003151 } else if (Opc == Instruction::Select) {
3152 if (Elts.size() != 3)
3153 return Error(ID.Loc, "expected three operands to select");
3154 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3155 Elts[2]))
3156 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00003157 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003158 } else if (Opc == Instruction::ShuffleVector) {
3159 if (Elts.size() != 3)
3160 return Error(ID.Loc, "expected three operands to shufflevector");
3161 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3162 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00003163 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003164 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003165 } else if (Opc == Instruction::ExtractElement) {
3166 if (Elts.size() != 2)
3167 return Error(ID.Loc, "expected two operands to extractelement");
3168 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3169 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003170 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003171 } else {
3172 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3173 if (Elts.size() != 3)
3174 return Error(ID.Loc, "expected three operands to insertelement");
3175 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3176 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00003177 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003178 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003179 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003180
Chris Lattnerac161bf2009-01-02 07:01:27 +00003181 ID.Kind = ValID::t_Constant;
3182 return false;
3183 }
3184 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003185
Chris Lattnerac161bf2009-01-02 07:01:27 +00003186 Lex.Lex();
3187 return false;
3188}
3189
3190/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00003191bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003192 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003193 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00003194 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003195 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00003196 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003197 if (V && !(C = dyn_cast<Constant>(V)))
3198 return Error(ID.Loc, "global values must be constants");
3199 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003200}
3201
Victor Hernandez9d75c962010-01-11 22:31:58 +00003202bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003203 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003204 return ParseType(Ty) ||
3205 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003206}
3207
Rafael Espindola83a362c2015-01-06 22:55:16 +00003208bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00003209 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003210
3211 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00003212 if (!EatIfPresent(lltok::kw_comdat))
3213 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003214
3215 if (EatIfPresent(lltok::lparen)) {
3216 if (Lex.getKind() != lltok::ComdatVar)
3217 return TokError("expected comdat variable");
3218 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3219 Lex.Lex();
3220 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3221 return true;
3222 } else {
3223 if (GlobalName.empty())
3224 return TokError("comdat cannot be unnamed");
3225 C = getComdat(GlobalName, KwLoc);
3226 }
3227
David Majnemerdad0a642014-06-27 18:19:56 +00003228 return false;
3229}
3230
Victor Hernandez9d75c962010-01-11 22:31:58 +00003231/// ParseGlobalValueVector
3232/// ::= /*empty*/
3233/// ::= TypeAndValue (',' TypeAndValue)*
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003234bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00003235 // Empty list.
3236 if (Lex.getKind() == lltok::rbrace ||
3237 Lex.getKind() == lltok::rsquare ||
3238 Lex.getKind() == lltok::greater ||
3239 Lex.getKind() == lltok::rparen)
3240 return false;
3241
3242 Constant *C;
3243 if (ParseGlobalTypeAndValue(C)) return true;
3244 Elts.push_back(C);
3245
3246 while (EatIfPresent(lltok::comma)) {
3247 if (ParseGlobalTypeAndValue(C)) return true;
3248 Elts.push_back(C);
3249 }
3250
3251 return false;
3252}
3253
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003254bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003255 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003256 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003257 return true;
3258
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003259 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003260 return false;
3261}
3262
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003263/// MDNode:
3264/// ::= !{ ... }
3265/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003266/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003267bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003268 if (Lex.getKind() == lltok::MetadataVar)
3269 return ParseSpecializedMDNode(N);
3270
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003271 return ParseToken(lltok::exclaim, "expected '!' here") ||
3272 ParseMDNodeTail(N);
3273}
3274
3275bool LLParser::ParseMDNodeTail(MDNode *&N) {
3276 // !{ ... }
3277 if (Lex.getKind() == lltok::lbrace)
3278 return ParseMDTuple(N);
3279
3280 // !42
3281 return ParseMDNodeID(N);
3282}
3283
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003284namespace {
3285
3286/// Structure to represent an optional metadata field.
3287template <class FieldTy> struct MDFieldImpl {
3288 typedef MDFieldImpl ImplTy;
3289 FieldTy Val;
3290 bool Seen;
3291
3292 void assign(FieldTy Val) {
3293 Seen = true;
3294 this->Val = std::move(Val);
3295 }
3296
3297 explicit MDFieldImpl(FieldTy Default)
3298 : Val(std::move(Default)), Seen(false) {}
3299};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003300
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003301struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3302 uint64_t Max;
3303
3304 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3305 : ImplTy(Default), Max(Max) {}
3306};
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003307struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003308 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003309};
3310struct ColumnField : public MDUnsignedField {
3311 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3312};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003313struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003314 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003315 DwarfTagField(dwarf::Tag DefaultTag)
3316 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003317};
Amjad Abouda9bcf162015-12-10 12:56:35 +00003318struct DwarfMacinfoTypeField : public MDUnsignedField {
3319 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3320 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3321 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3322};
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003323struct DwarfAttEncodingField : public MDUnsignedField {
3324 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3325};
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003326struct DwarfVirtualityField : public MDUnsignedField {
3327 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3328};
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003329struct DwarfLangField : public MDUnsignedField {
3330 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3331};
Adrian Prantlb939a252016-03-31 23:56:58 +00003332struct EmissionKindField : public MDUnsignedField {
3333 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3334};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003335
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003336struct DIFlagField : public MDUnsignedField {
3337 DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3338};
3339
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003340struct MDSignedField : public MDFieldImpl<int64_t> {
3341 int64_t Min;
3342 int64_t Max;
3343
3344 MDSignedField(int64_t Default = 0)
3345 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3346 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3347 : ImplTy(Default), Min(Min), Max(Max) {}
3348};
3349
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003350struct MDBoolField : public MDFieldImpl<bool> {
3351 MDBoolField(bool Default = false) : ImplTy(Default) {}
3352};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003353struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003354 bool AllowNull;
3355
3356 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003357};
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003358struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3359 MDConstant() : ImplTy(nullptr) {}
3360};
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003361struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003362 bool AllowEmpty;
3363 MDStringField(bool AllowEmpty = true)
3364 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003365};
3366struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3367 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3368};
3369
3370} // end namespace
3371
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003372namespace llvm {
3373
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003374template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003375bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003376 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003377 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3378 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003379
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003380 auto &U = Lex.getAPSIntVal();
3381 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003382 return TokError("value for '" + Name + "' too large, limit is " +
3383 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003384 Result.assign(U.getZExtValue());
3385 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003386 Lex.Lex();
3387 return false;
3388}
3389
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003390template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003391bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3392 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3393}
3394template <>
3395bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3396 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3397}
3398
3399template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003400bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3401 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003402 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003403
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003404 if (Lex.getKind() != lltok::DwarfTag)
3405 return TokError("expected DWARF tag");
3406
3407 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3408 if (Tag == dwarf::DW_TAG_invalid)
3409 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003410 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003411
3412 Result.assign(Tag);
3413 Lex.Lex();
3414 return false;
3415}
3416
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003417template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003418bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003419 DwarfMacinfoTypeField &Result) {
3420 if (Lex.getKind() == lltok::APSInt)
3421 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3422
3423 if (Lex.getKind() != lltok::DwarfMacinfo)
3424 return TokError("expected DWARF macinfo type");
3425
3426 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3427 if (Macinfo == dwarf::DW_MACINFO_invalid)
3428 return TokError(
3429 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3430 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3431
3432 Result.assign(Macinfo);
3433 Lex.Lex();
3434 return false;
3435}
3436
3437template <>
3438bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003439 DwarfVirtualityField &Result) {
3440 if (Lex.getKind() == lltok::APSInt)
3441 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3442
3443 if (Lex.getKind() != lltok::DwarfVirtuality)
3444 return TokError("expected DWARF virtuality code");
3445
3446 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
Peter Collingbournea1f86252016-03-17 23:58:03 +00003447 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003448 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3449 Lex.getStrVal() + "'");
3450 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3451 Result.assign(Virtuality);
3452 Lex.Lex();
3453 return false;
3454}
3455
3456template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003457bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3458 if (Lex.getKind() == lltok::APSInt)
3459 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3460
3461 if (Lex.getKind() != lltok::DwarfLang)
3462 return TokError("expected DWARF language");
3463
3464 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3465 if (!Lang)
3466 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3467 "'");
3468 assert(Lang <= Result.Max && "Expected valid DWARF language");
3469 Result.assign(Lang);
3470 Lex.Lex();
3471 return false;
3472}
3473
3474template <>
Adrian Prantlb939a252016-03-31 23:56:58 +00003475bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3476 if (Lex.getKind() == lltok::APSInt)
3477 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3478
3479 if (Lex.getKind() != lltok::EmissionKind)
3480 return TokError("expected emission kind");
3481
3482 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3483 if (!Kind)
3484 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3485 "'");
3486 assert(*Kind <= Result.Max && "Expected valid emission kind");
3487 Result.assign(*Kind);
3488 Lex.Lex();
3489 return false;
3490}
3491
3492template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003493bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003494 DwarfAttEncodingField &Result) {
3495 if (Lex.getKind() == lltok::APSInt)
3496 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3497
3498 if (Lex.getKind() != lltok::DwarfAttEncoding)
3499 return TokError("expected DWARF type attribute encoding");
3500
3501 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3502 if (!Encoding)
3503 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3504 Lex.getStrVal() + "'");
3505 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3506 Result.assign(Encoding);
3507 Lex.Lex();
3508 return false;
3509}
3510
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003511/// DIFlagField
3512/// ::= uint32
3513/// ::= DIFlagVector
3514/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3515template <>
3516bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3517 assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3518
3519 // Parser for a single flag.
3520 auto parseFlag = [&](unsigned &Val) {
3521 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3522 return ParseUInt32(Val);
3523
3524 if (Lex.getKind() != lltok::DIFlag)
3525 return TokError("expected debug info flag");
3526
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003527 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003528 if (!Val)
3529 return TokError(Twine("invalid debug info flag flag '") +
3530 Lex.getStrVal() + "'");
3531 Lex.Lex();
3532 return false;
3533 };
3534
3535 // Parse the flags and combine them together.
3536 unsigned Combined = 0;
3537 do {
3538 unsigned Val;
3539 if (parseFlag(Val))
3540 return true;
3541 Combined |= Val;
3542 } while (EatIfPresent(lltok::bar));
3543
3544 Result.assign(Combined);
3545 return false;
3546}
3547
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003548template <>
3549bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003550 MDSignedField &Result) {
3551 if (Lex.getKind() != lltok::APSInt)
3552 return TokError("expected signed integer");
3553
3554 auto &S = Lex.getAPSIntVal();
3555 if (S < Result.Min)
3556 return TokError("value for '" + Name + "' too small, limit is " +
3557 Twine(Result.Min));
3558 if (S > Result.Max)
3559 return TokError("value for '" + Name + "' too large, limit is " +
3560 Twine(Result.Max));
3561 Result.assign(S.getExtValue());
3562 assert(Result.Val >= Result.Min && "Expected value in range");
3563 assert(Result.Val <= Result.Max && "Expected value in range");
3564 Lex.Lex();
3565 return false;
3566}
3567
3568template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003569bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3570 switch (Lex.getKind()) {
3571 default:
3572 return TokError("expected 'true' or 'false'");
3573 case lltok::kw_true:
3574 Result.assign(true);
3575 break;
3576 case lltok::kw_false:
3577 Result.assign(false);
3578 break;
3579 }
3580 Lex.Lex();
3581 return false;
3582}
3583
3584template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003585bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003586 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003587 if (!Result.AllowNull)
3588 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003589 Lex.Lex();
3590 Result.assign(nullptr);
3591 return false;
3592 }
3593
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003594 Metadata *MD;
3595 if (ParseMetadata(MD, nullptr))
3596 return true;
3597
3598 Result.assign(MD);
3599 return false;
3600}
3601
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003602template <>
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003603bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3604 Metadata *MD;
3605 if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3606 return true;
3607
3608 Result.assign(cast<ConstantAsMetadata>(MD));
3609 return false;
3610}
3611
3612template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003613bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003614 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003615 std::string S;
3616 if (ParseStringConstant(S))
3617 return true;
3618
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003619 if (!Result.AllowEmpty && S.empty())
3620 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3621
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003622 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003623 return false;
3624}
3625
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003626template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003627bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3628 SmallVector<Metadata *, 4> MDs;
3629 if (ParseMDNodeVector(MDs))
3630 return true;
3631
3632 Result.assign(std::move(MDs));
3633 return false;
3634}
3635
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003636} // end namespace llvm
3637
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003638template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003639bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003640 do {
3641 if (Lex.getKind() != lltok::LabelStr)
3642 return TokError("expected field label here");
3643
3644 if (parseField())
3645 return true;
3646 } while (EatIfPresent(lltok::comma));
3647
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003648 return false;
3649}
3650
3651template <class ParserTy>
3652bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3653 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3654 Lex.Lex();
3655
3656 if (ParseToken(lltok::lparen, "expected '(' here"))
3657 return true;
3658 if (Lex.getKind() != lltok::rparen)
3659 if (ParseMDFieldsImplBody(parseField))
3660 return true;
3661
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00003662 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003663 return ParseToken(lltok::rparen, "expected ')' here");
3664}
3665
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003666template <class FieldTy>
3667bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3668 if (Result.Seen)
3669 return TokError("field '" + Name + "' cannot be specified more than once");
3670
3671 LocTy Loc = Lex.getLoc();
3672 Lex.Lex();
3673 return ParseMDField(Loc, Name, Result);
3674}
3675
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003676bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3677 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003678
3679#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003680 if (Lex.getStrVal() == #CLASS) \
3681 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003682#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003683
3684 return TokError("expected metadata type");
3685}
3686
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003687#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3688#define NOP_FIELD(NAME, TYPE, INIT)
3689#define REQUIRE_FIELD(NAME, TYPE, INIT) \
3690 if (!NAME.Seen) \
3691 return Error(ClosingLoc, "missing required field '" #NAME "'");
3692#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003693 if (Lex.getStrVal() == #NAME) \
3694 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003695#define PARSE_MD_FIELDS() \
3696 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3697 do { \
3698 LocTy ClosingLoc; \
3699 if (ParseMDFieldsImpl([&]() -> bool { \
3700 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3701 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3702 }, ClosingLoc)) \
3703 return true; \
3704 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3705 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003706#define GET_OR_DISTINCT(CLASS, ARGS) \
3707 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003708
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003709/// ParseDILocationFields:
3710/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3711bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003712#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003713 OPTIONAL(line, LineField, ); \
3714 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003715 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003716 OPTIONAL(inlinedAt, MDField, );
3717 PARSE_MD_FIELDS();
3718#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003719
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00003720 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003721 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003722 return false;
3723}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003724
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003725/// ParseGenericDINode:
3726/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3727bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003728#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003729 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003730 OPTIONAL(header, MDStringField, ); \
3731 OPTIONAL(operands, MDFieldList, );
3732 PARSE_MD_FIELDS();
3733#undef VISIT_MD_FIELDS
3734
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003735 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003736 (Context, tag.Val, header.Val, operands.Val));
3737 return false;
3738}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003739
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003740/// ParseDISubrange:
3741/// ::= !DISubrange(count: 30, lowerBound: 2)
3742bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003743#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith5c9a1772015-02-18 23:17:51 +00003744 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003745 OPTIONAL(lowerBound, MDSignedField, );
3746 PARSE_MD_FIELDS();
3747#undef VISIT_MD_FIELDS
3748
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003749 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003750 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003751}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003752
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003753/// ParseDIEnumerator:
3754/// ::= !DIEnumerator(value: 30, name: "SomeKind")
3755bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003756#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00003757 REQUIRED(name, MDStringField, ); \
3758 REQUIRED(value, MDSignedField, );
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003759 PARSE_MD_FIELDS();
3760#undef VISIT_MD_FIELDS
3761
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003762 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003763 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003764}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003765
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003766/// ParseDIBasicType:
3767/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3768bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003769#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003770 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003771 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003772 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3773 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003774 OPTIONAL(encoding, DwarfAttEncodingField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003775 PARSE_MD_FIELDS();
3776#undef VISIT_MD_FIELDS
3777
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003778 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003779 align.Val, encoding.Val));
3780 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003781}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003782
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003783/// ParseDIDerivedType:
3784/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003785/// line: 7, scope: !1, baseType: !2, size: 32,
3786/// align: 32, offset: 0, flags: 0, extraData: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003787bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003788#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3789 REQUIRED(tag, DwarfTagField, ); \
3790 OPTIONAL(name, MDStringField, ); \
3791 OPTIONAL(file, MDField, ); \
3792 OPTIONAL(line, LineField, ); \
3793 OPTIONAL(scope, MDField, ); \
3794 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003795 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3796 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3797 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003798 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003799 OPTIONAL(extraData, MDField, );
3800 PARSE_MD_FIELDS();
3801#undef VISIT_MD_FIELDS
3802
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003803 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003804 (Context, tag.Val, name.Val, file.Val, line.Val,
3805 scope.Val, baseType.Val, size.Val, align.Val,
3806 offset.Val, flags.Val, extraData.Val));
3807 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003808}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003809
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003810bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003811#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3812 REQUIRED(tag, DwarfTagField, ); \
3813 OPTIONAL(name, MDStringField, ); \
3814 OPTIONAL(file, MDField, ); \
3815 OPTIONAL(line, LineField, ); \
3816 OPTIONAL(scope, MDField, ); \
3817 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003818 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3819 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3820 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003821 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003822 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003823 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003824 OPTIONAL(vtableHolder, MDField, ); \
3825 OPTIONAL(templateParams, MDField, ); \
3826 OPTIONAL(identifier, MDStringField, );
3827 PARSE_MD_FIELDS();
3828#undef VISIT_MD_FIELDS
3829
Duncan P. N. Exon Smith97386022016-04-19 18:00:19 +00003830 // If this has an identifier try to build an ODR type.
3831 if (identifier.Val)
3832 if (auto *CT = DICompositeType::buildODRType(
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00003833 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
3834 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
3835 elements.Val, runtimeLang.Val, vtableHolder.Val,
3836 templateParams.Val)) {
3837 Result = CT;
3838 return false;
3839 }
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00003840
3841 // Create a new node, and save it in the context if it belongs in the type
3842 // map.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003843 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003844 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003845 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3846 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3847 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3848 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003849}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003850
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003851bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003852#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003853 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003854 REQUIRED(types, MDField, );
3855 PARSE_MD_FIELDS();
3856#undef VISIT_MD_FIELDS
3857
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003858 Result = GET_OR_DISTINCT(DISubroutineType, (Context, flags.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003859 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003860}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003861
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003862/// ParseDIFileType:
3863/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir")
3864bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003865#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3866 REQUIRED(filename, MDStringField, ); \
3867 REQUIRED(directory, MDStringField, );
3868 PARSE_MD_FIELDS();
3869#undef VISIT_MD_FIELDS
3870
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003871 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003872 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003873}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003874
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003875/// ParseDICompileUnit:
3876/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003877/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
Adrian Prantlb939a252016-03-31 23:56:58 +00003878/// splitDebugFilename: "abc.debug",
Adrian Prantl75819ae2016-04-15 15:57:41 +00003879/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003880/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003881bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00003882 if (!IsDistinct)
3883 return Lex.Error("missing 'distinct', required for !DICompileUnit");
3884
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003885#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3886 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00003887 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003888 OPTIONAL(producer, MDStringField, ); \
3889 OPTIONAL(isOptimized, MDBoolField, ); \
3890 OPTIONAL(flags, MDStringField, ); \
3891 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
3892 OPTIONAL(splitDebugFilename, MDStringField, ); \
Adrian Prantlb939a252016-03-31 23:56:58 +00003893 OPTIONAL(emissionKind, EmissionKindField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003894 OPTIONAL(enums, MDField, ); \
3895 OPTIONAL(retainedTypes, MDField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003896 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00003897 OPTIONAL(imports, MDField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00003898 OPTIONAL(macros, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00003899 OPTIONAL(dwoId, MDUnsignedField, );
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003900 PARSE_MD_FIELDS();
3901#undef VISIT_MD_FIELDS
3902
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00003903 Result = DICompileUnit::getDistinct(
3904 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
3905 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
Adrian Prantl75819ae2016-04-15 15:57:41 +00003906 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003907 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003908}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003909
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003910/// ParseDISubprogram:
3911/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003912/// file: !1, line: 7, type: !2, isLocal: false,
3913/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003914/// virtuality: DW_VIRTUALTIY_pure_virtual,
3915/// virtualIndex: 10, flags: 11,
Peter Collingbourned4bff302015-11-05 22:03:56 +00003916/// isOptimized: false, templateParams: !4, declaration: !5,
3917/// variables: !6)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003918bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00003919 auto Loc = Lex.getLoc();
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003920#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3921 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00003922 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003923 OPTIONAL(linkageName, MDStringField, ); \
3924 OPTIONAL(file, MDField, ); \
3925 OPTIONAL(line, LineField, ); \
3926 OPTIONAL(type, MDField, ); \
3927 OPTIONAL(isLocal, MDBoolField, ); \
3928 OPTIONAL(isDefinition, MDBoolField, (true)); \
3929 OPTIONAL(scopeLine, LineField, ); \
3930 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003931 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003932 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003933 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003934 OPTIONAL(isOptimized, MDBoolField, ); \
Adrian Prantl75819ae2016-04-15 15:57:41 +00003935 OPTIONAL(unit, MDField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003936 OPTIONAL(templateParams, MDField, ); \
3937 OPTIONAL(declaration, MDField, ); \
3938 OPTIONAL(variables, MDField, );
3939 PARSE_MD_FIELDS();
3940#undef VISIT_MD_FIELDS
3941
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00003942 if (isDefinition.Val && !IsDistinct)
3943 return Lex.Error(
3944 Loc,
3945 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
3946
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003947 Result = GET_OR_DISTINCT(
Adrian Prantl75819ae2016-04-15 15:57:41 +00003948 DISubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
3949 line.Val, type.Val, isLocal.Val, isDefinition.Val,
3950 scopeLine.Val, containingType.Val, virtuality.Val,
3951 virtualIndex.Val, flags.Val, isOptimized.Val, unit.Val,
3952 templateParams.Val, declaration.Val, variables.Val));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003953 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003954}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003955
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003956/// ParseDILexicalBlock:
3957/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
3958bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003959#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00003960 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003961 OPTIONAL(file, MDField, ); \
3962 OPTIONAL(line, LineField, ); \
3963 OPTIONAL(column, ColumnField, );
3964 PARSE_MD_FIELDS();
3965#undef VISIT_MD_FIELDS
3966
3967 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003968 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003969 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003970}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003971
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003972/// ParseDILexicalBlockFile:
3973/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
3974bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003975#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00003976 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003977 OPTIONAL(file, MDField, ); \
3978 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
3979 PARSE_MD_FIELDS();
3980#undef VISIT_MD_FIELDS
3981
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003982 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003983 (Context, scope.Val, file.Val, discriminator.Val));
3984 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003985}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003986
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003987/// ParseDINamespace:
3988/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
3989bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003990#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3991 REQUIRED(scope, MDField, ); \
3992 OPTIONAL(file, MDField, ); \
3993 OPTIONAL(name, MDStringField, ); \
3994 OPTIONAL(line, LineField, );
3995 PARSE_MD_FIELDS();
3996#undef VISIT_MD_FIELDS
3997
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003998 Result = GET_OR_DISTINCT(DINamespace,
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003999 (Context, scope.Val, file.Val, name.Val, line.Val));
4000 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004001}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004002
Amjad Abouda9bcf162015-12-10 12:56:35 +00004003/// ParseDIMacro:
4004/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4005bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4006#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4007 REQUIRED(type, DwarfMacinfoTypeField, ); \
4008 REQUIRED(line, LineField, ); \
4009 REQUIRED(name, MDStringField, ); \
4010 OPTIONAL(value, MDStringField, );
4011 PARSE_MD_FIELDS();
4012#undef VISIT_MD_FIELDS
4013
4014 Result = GET_OR_DISTINCT(DIMacro,
4015 (Context, type.Val, line.Val, name.Val, value.Val));
4016 return false;
4017}
4018
4019/// ParseDIMacroFile:
4020/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4021bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4022#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4023 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
4024 REQUIRED(line, LineField, ); \
4025 REQUIRED(file, MDField, ); \
4026 OPTIONAL(nodes, MDField, );
4027 PARSE_MD_FIELDS();
4028#undef VISIT_MD_FIELDS
4029
4030 Result = GET_OR_DISTINCT(DIMacroFile,
4031 (Context, type.Val, line.Val, file.Val, nodes.Val));
4032 return false;
4033}
4034
4035
Adrian Prantlab1243f2015-06-29 23:03:47 +00004036/// ParseDIModule:
4037/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4038/// includePath: "/usr/include", isysroot: "/")
4039bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4040#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4041 REQUIRED(scope, MDField, ); \
4042 REQUIRED(name, MDStringField, ); \
4043 OPTIONAL(configMacros, MDStringField, ); \
4044 OPTIONAL(includePath, MDStringField, ); \
4045 OPTIONAL(isysroot, MDStringField, );
4046 PARSE_MD_FIELDS();
4047#undef VISIT_MD_FIELDS
4048
4049 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4050 configMacros.Val, includePath.Val, isysroot.Val));
4051 return false;
4052}
4053
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004054/// ParseDITemplateTypeParameter:
4055/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4056bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004057#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004058 OPTIONAL(name, MDStringField, ); \
4059 REQUIRED(type, MDField, );
4060 PARSE_MD_FIELDS();
4061#undef VISIT_MD_FIELDS
4062
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004063 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004064 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004065 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004066}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004067
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004068/// ParseDITemplateValueParameter:
4069/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004070/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004071bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004072#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004073 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004074 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004075 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004076 REQUIRED(value, MDField, );
4077 PARSE_MD_FIELDS();
4078#undef VISIT_MD_FIELDS
4079
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004080 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004081 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004082 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004083}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004084
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004085/// ParseDIGlobalVariable:
4086/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004087/// file: !1, line: 7, type: !2, isLocal: false,
4088/// isDefinition: true, variable: i32* @foo,
4089/// declaration: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004090bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004091#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004092 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004093 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004094 OPTIONAL(linkageName, MDStringField, ); \
4095 OPTIONAL(file, MDField, ); \
4096 OPTIONAL(line, LineField, ); \
4097 OPTIONAL(type, MDField, ); \
4098 OPTIONAL(isLocal, MDBoolField, ); \
4099 OPTIONAL(isDefinition, MDBoolField, (true)); \
4100 OPTIONAL(variable, MDConstant, ); \
4101 OPTIONAL(declaration, MDField, );
4102 PARSE_MD_FIELDS();
4103#undef VISIT_MD_FIELDS
4104
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004105 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004106 (Context, scope.Val, name.Val, linkageName.Val,
4107 file.Val, line.Val, type.Val, isLocal.Val,
4108 isDefinition.Val, variable.Val, declaration.Val));
4109 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004110}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004111
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004112/// ParseDILocalVariable:
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004113/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
4114/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
4115/// ::= !DILocalVariable(scope: !0, name: "foo",
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00004116/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004117bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004118#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004119 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004120 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004121 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004122 OPTIONAL(file, MDField, ); \
4123 OPTIONAL(line, LineField, ); \
4124 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00004125 OPTIONAL(flags, DIFlagField, );
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004126 PARSE_MD_FIELDS();
4127#undef VISIT_MD_FIELDS
4128
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004129 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004130 (Context, scope.Val, name.Val, file.Val, line.Val,
4131 type.Val, arg.Val, flags.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004132 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004133}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004134
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004135/// ParseDIExpression:
4136/// ::= !DIExpression(0, 7, -1)
4137bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004138 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4139 Lex.Lex();
4140
4141 if (ParseToken(lltok::lparen, "expected '(' here"))
4142 return true;
4143
4144 SmallVector<uint64_t, 8> Elements;
4145 if (Lex.getKind() != lltok::rparen)
4146 do {
4147 if (Lex.getKind() == lltok::DwarfOp) {
4148 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4149 Lex.Lex();
4150 Elements.push_back(Op);
4151 continue;
4152 }
4153 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4154 }
4155
4156 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4157 return TokError("expected unsigned integer");
4158
4159 auto &U = Lex.getAPSIntVal();
4160 if (U.ugt(UINT64_MAX))
4161 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4162 Elements.push_back(U.getZExtValue());
4163 Lex.Lex();
4164 } while (EatIfPresent(lltok::comma));
4165
4166 if (ParseToken(lltok::rparen, "expected ')' here"))
4167 return true;
4168
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004169 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004170 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004171}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004172
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004173/// ParseDIObjCProperty:
4174/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004175/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004176bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004177#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004178 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004179 OPTIONAL(file, MDField, ); \
4180 OPTIONAL(line, LineField, ); \
4181 OPTIONAL(setter, MDStringField, ); \
4182 OPTIONAL(getter, MDStringField, ); \
4183 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4184 OPTIONAL(type, MDField, );
4185 PARSE_MD_FIELDS();
4186#undef VISIT_MD_FIELDS
4187
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004188 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004189 (Context, name.Val, file.Val, line.Val, setter.Val,
4190 getter.Val, attributes.Val, type.Val));
4191 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004192}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004193
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004194/// ParseDIImportedEntity:
4195/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004196/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004197bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004198#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4199 REQUIRED(tag, DwarfTagField, ); \
4200 REQUIRED(scope, MDField, ); \
4201 OPTIONAL(entity, MDField, ); \
4202 OPTIONAL(line, LineField, ); \
4203 OPTIONAL(name, MDStringField, );
4204 PARSE_MD_FIELDS();
4205#undef VISIT_MD_FIELDS
4206
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004207 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004208 entity.Val, line.Val, name.Val));
4209 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004210}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004211
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004212#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004213#undef NOP_FIELD
4214#undef REQUIRE_FIELD
4215#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004216
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004217/// ParseMetadataAsValue
4218/// ::= metadata i32 %local
4219/// ::= metadata i32 @global
4220/// ::= metadata i32 7
4221/// ::= metadata !0
4222/// ::= metadata !{...}
4223/// ::= metadata !"string"
4224bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4225 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004226 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004227 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004228 return true;
4229
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004230 V = MetadataAsValue::get(Context, MD);
4231 return false;
4232}
4233
4234/// ParseValueAsMetadata
4235/// ::= i32 %local
4236/// ::= i32 @global
4237/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004238bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4239 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004240 Type *Ty;
4241 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004242 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004243 return true;
4244 if (Ty->isMetadataTy())
4245 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4246
4247 Value *V;
4248 if (ParseValue(Ty, V, PFS))
4249 return true;
4250
4251 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004252 return false;
4253}
4254
4255/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004256/// ::= i32 %local
4257/// ::= i32 @global
4258/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00004259/// ::= !42
4260/// ::= !{...}
4261/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004262/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004263bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004264 if (Lex.getKind() == lltok::MetadataVar) {
4265 MDNode *N;
4266 if (ParseSpecializedMDNode(N))
4267 return true;
4268 MD = N;
4269 return false;
4270 }
4271
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004272 // ValueAsMetadata:
4273 // <type> <value>
4274 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004275 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004276
4277 // '!'.
4278 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4279 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00004280
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004281 // MDString:
4282 // ::= '!' STRINGCONSTANT
4283 if (Lex.getKind() == lltok::StringConstant) {
4284 MDString *S;
4285 if (ParseMDString(S))
4286 return true;
4287 MD = S;
4288 return false;
4289 }
4290
Dan Gohman8939ba332010-07-14 18:26:50 +00004291 // MDNode:
4292 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004293 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004294 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004295 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004296 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004297 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00004298 return false;
4299}
4300
Victor Hernandez9d75c962010-01-11 22:31:58 +00004301
4302//===----------------------------------------------------------------------===//
4303// Function Parsing.
4304//===----------------------------------------------------------------------===//
4305
Chris Lattner229907c2011-07-18 04:54:35 +00004306bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
David Majnemer8a1c45d2015-12-12 05:38:55 +00004307 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00004308 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004309 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004310
Chris Lattnerac161bf2009-01-02 07:01:27 +00004311 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004312 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004313 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004314 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004315 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004316 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004317 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004318 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004319 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004320 case ValID::t_InlineAsm: {
Karl Schimpf44876c52015-09-03 16:18:32 +00004321 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez9d75c962010-01-11 22:31:58 +00004322 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie41ba2b42015-07-27 23:32:19 +00004323 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4324 (ID.UIntVal >> 1) & 1,
4325 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00004326 return false;
4327 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004328 case ValID::t_GlobalName:
4329 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004330 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004331 case ValID::t_GlobalID:
4332 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004333 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004334 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00004335 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004336 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00004337 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00004338 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004339 return false;
4340 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00004341 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004342 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4343 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004344
Dan Gohman518cda42011-12-17 00:04:22 +00004345 // The lexer has no type info, so builds all half, float, and double FP
4346 // constants as double. Fix this here. Long double does not need this.
4347 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004348 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00004349 if (Ty->isHalfTy())
4350 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
4351 &Ignored);
4352 else if (Ty->isFloatTy())
4353 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
4354 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004355 }
Owen Anderson69c464d2009-07-27 20:59:43 +00004356 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004357
Chris Lattner8f57d29e2009-01-05 18:24:23 +00004358 if (V->getType() != Ty)
4359 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004360 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004361
Chris Lattnerac161bf2009-01-02 07:01:27 +00004362 return false;
4363 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00004364 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004365 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004366 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004367 return false;
4368 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00004369 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004370 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00004371 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004372 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004373 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00004374 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00004375 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00004376 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004377 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00004378 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004379 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00004380 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00004381 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004382 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00004383 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004384 return false;
David Majnemerf0f224d2015-11-11 21:57:16 +00004385 case ValID::t_None:
4386 if (!Ty->isTokenTy())
4387 return Error(ID.Loc, "invalid type for none constant");
4388 V = Constant::getNullValue(Ty);
4389 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004390 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00004391 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004392 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00004393
Chris Lattnerac161bf2009-01-02 07:01:27 +00004394 V = ID.ConstantVal;
4395 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004396 case ValID::t_ConstantStruct:
4397 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00004398 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004399 if (ST->getNumElements() != ID.UIntVal)
4400 return Error(ID.Loc,
4401 "initializer with struct type has wrong # elements");
4402 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4403 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004404
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004405 // Verify that the elements are compatible with the structtype.
4406 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4407 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4408 return Error(ID.Loc, "element " + Twine(i) +
4409 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004410
David Blaikieadbda4b2015-08-03 20:08:41 +00004411 V = ConstantStruct::get(
4412 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004413 } else
4414 return Error(ID.Loc, "constant expression type mismatch");
4415 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004416 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00004417 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004418}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004419
Alex Lorenzd2255952015-07-17 22:07:03 +00004420bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4421 C = nullptr;
4422 ValID ID;
4423 auto Loc = Lex.getLoc();
4424 if (ParseValID(ID, /*PFS=*/nullptr))
4425 return true;
4426 switch (ID.Kind) {
4427 case ValID::t_APSInt:
4428 case ValID::t_APFloat:
Alex Lorenzb9a68db2015-09-09 13:44:33 +00004429 case ValID::t_Undef:
Alex Lorenzd2255952015-07-17 22:07:03 +00004430 case ValID::t_Constant:
4431 case ValID::t_ConstantStruct:
4432 case ValID::t_PackedConstantStruct: {
4433 Value *V;
4434 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4435 return true;
4436 assert(isa<Constant>(V) && "Expected a constant value");
4437 C = cast<Constant>(V);
4438 return false;
4439 }
4440 default:
4441 return Error(Loc, "expected a constant value");
4442 }
4443}
4444
David Majnemer8a1c45d2015-12-12 05:38:55 +00004445bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004446 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004447 ValID ID;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004448 return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004449}
4450
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004451bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004452 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004453 return ParseType(Ty) ||
4454 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004455}
4456
Chris Lattner3ed871f2009-10-27 19:13:16 +00004457bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4458 PerFunctionState &PFS) {
4459 Value *V;
4460 Loc = Lex.getLoc();
4461 if (ParseTypeAndValue(V, PFS)) return true;
4462 if (!isa<BasicBlock>(V))
4463 return Error(Loc, "expected a basic block");
4464 BB = cast<BasicBlock>(V);
4465 return false;
4466}
4467
4468
Chris Lattnerac161bf2009-01-02 07:01:27 +00004469/// FunctionHeader
4470/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00004471/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
David Majnemer7fddecc2015-06-17 20:52:32 +00004472/// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00004473bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4474 // Parse the linkage.
4475 LocTy LinkageLoc = Lex.getLoc();
4476 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004477
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00004478 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00004479 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00004480 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004481 unsigned CC;
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004482 bool HasLinkage;
Craig Topper2617dcc2014-04-15 06:32:26 +00004483 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004484 LocTy RetTypeLoc = Lex.getLoc();
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004485 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
4486 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004487 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004488 return true;
4489
4490 // Verify that the linkage is ok.
4491 switch ((GlobalValue::LinkageTypes)Linkage) {
4492 case GlobalValue::ExternalLinkage:
4493 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00004494 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004495 if (isDefine)
4496 return Error(LinkageLoc, "invalid linkage for function definition");
4497 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00004498 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004499 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00004500 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00004501 case GlobalValue::LinkOnceAnyLinkage:
4502 case GlobalValue::LinkOnceODRLinkage:
4503 case GlobalValue::WeakAnyLinkage:
4504 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004505 if (!isDefine)
4506 return Error(LinkageLoc, "invalid linkage for function declaration");
4507 break;
4508 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00004509 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004510 return Error(LinkageLoc, "invalid function linkage type");
4511 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004512
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004513 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4514 return Error(LinkageLoc,
4515 "symbol with local linkage must have default visibility");
4516
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004517 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004518 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004519
Chris Lattnerac161bf2009-01-02 07:01:27 +00004520 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00004521
4522 std::string FunctionName;
4523 if (Lex.getKind() == lltok::GlobalVar) {
4524 FunctionName = Lex.getStrVal();
4525 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4526 unsigned NameID = Lex.getUIntVal();
4527
4528 if (NameID != NumberedVals.size())
4529 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004530 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00004531 } else {
4532 return TokError("expected function name");
4533 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004534
Chris Lattner3822f632009-01-02 08:05:26 +00004535 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004536
Chris Lattner3822f632009-01-02 08:05:26 +00004537 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004538 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004539
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004540 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004541 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00004542 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004543 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004544 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004545 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004546 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00004547 std::string GC;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004548 bool UnnamedAddr;
4549 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00004550 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004551 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00004552 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00004553 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00004554
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004555 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004556 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
4557 &UnnamedAddrLoc) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004558 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004559 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004560 (EatIfPresent(lltok::kw_section) &&
4561 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00004562 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004563 ParseOptionalAlignment(Alignment) ||
4564 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004565 ParseStringConstant(GC)) ||
4566 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004567 ParseGlobalTypeAndValue(Prefix)) ||
4568 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00004569 ParseGlobalTypeAndValue(Prologue)) ||
4570 (EatIfPresent(lltok::kw_personality) &&
4571 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00004572 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004573
Michael Gottesman41748d72013-06-27 00:25:01 +00004574 if (FuncAttrs.contains(Attribute::Builtin))
4575 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00004576
Chris Lattnerac161bf2009-01-02 07:01:27 +00004577 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00004578 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00004579 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004580 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004581 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004582
Chris Lattnerac161bf2009-01-02 07:01:27 +00004583 // Okay, if we got here, the function is syntactically valid. Convert types
4584 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00004585 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00004586 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004587
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004588 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004589 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4590 AttributeSet::ReturnIndex,
4591 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004592
Chris Lattnerac161bf2009-01-02 07:01:27 +00004593 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004594 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004595 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4596 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004597 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4598 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004599 }
4600
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004601 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004602 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4603 AttributeSet::FunctionIndex,
4604 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004605
Bill Wendlinge94d8432012-12-07 23:16:57 +00004606 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004607
Bill Wendling749a43d2012-12-30 13:50:49 +00004608 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004609 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4610
Chris Lattner229907c2011-07-18 04:54:35 +00004611 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00004612 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00004613 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004614
Craig Topper2617dcc2014-04-15 06:32:26 +00004615 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004616 if (!FunctionName.empty()) {
4617 // If this was a definition of a forward reference, remove the definition
4618 // from the forward reference table and fill in the forward ref.
David Blaikie9ebdc692015-09-21 21:07:50 +00004619 auto FRVI = ForwardRefVals.find(FunctionName);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004620 if (FRVI != ForwardRefVals.end()) {
4621 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00004622 if (!Fn)
4623 return Error(FRVI->second.second, "invalid forward reference to "
4624 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00004625 if (Fn->getType() != PFT)
4626 return Error(FRVI->second.second, "invalid forward reference to "
4627 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004628
Chris Lattnerac161bf2009-01-02 07:01:27 +00004629 ForwardRefVals.erase(FRVI);
4630 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00004631 // Reject redefinitions.
4632 return Error(NameLoc, "invalid redefinition of function '" +
4633 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00004634 } else if (M->getNamedValue(FunctionName)) {
4635 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004636 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004637
Dan Gohman399d6ae2009-08-29 23:37:49 +00004638 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004639 // If this is a definition of a forward referenced function, make sure the
4640 // types agree.
David Blaikie9ebdc692015-09-21 21:07:50 +00004641 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004642 if (I != ForwardRefValIDs.end()) {
4643 Fn = cast<Function>(I->second.first);
4644 if (Fn->getType() != PFT)
4645 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004646 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004647 ForwardRefValIDs.erase(I);
4648 }
4649 }
4650
Craig Topper2617dcc2014-04-15 06:32:26 +00004651 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004652 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4653 else // Move the forward-reference to the correct spot in the module.
4654 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4655
4656 if (FunctionName.empty())
4657 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004658
Chris Lattnerac161bf2009-01-02 07:01:27 +00004659 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4660 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00004661 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004662 Fn->setCallingConv(CC);
4663 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004664 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004665 Fn->setAlignment(Alignment);
4666 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00004667 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00004668 Fn->setPersonalityFn(PersonalityFn);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004669 if (!GC.empty()) Fn->setGC(GC.c_str());
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004670 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004671 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004672 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004673
Chris Lattnerac161bf2009-01-02 07:01:27 +00004674 // Add all of the arguments we parsed to the function.
4675 Function::arg_iterator ArgIt = Fn->arg_begin();
4676 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4677 // If the argument has a name, insert it into the argument symbol table.
4678 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004679
Chris Lattnerac161bf2009-01-02 07:01:27 +00004680 // Set the name, if it conflicted, it will be auto-renamed.
4681 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004682
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00004683 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004684 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4685 ArgList[i].Name + "'");
4686 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004687
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004688 if (isDefine)
4689 return false;
4690
Robin Morisset039781e2014-08-29 21:53:01 +00004691 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004692 ValID ID;
4693 if (FunctionName.empty()) {
4694 ID.Kind = ValID::t_GlobalID;
4695 ID.UIntVal = NumberedVals.size() - 1;
4696 } else {
4697 ID.Kind = ValID::t_GlobalName;
4698 ID.StrVal = FunctionName;
4699 }
4700 auto Blocks = ForwardRefBlockAddresses.find(ID);
4701 if (Blocks != ForwardRefBlockAddresses.end())
4702 return Error(Blocks->first.Loc,
4703 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004704 return false;
4705}
4706
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004707bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4708 ValID ID;
4709 if (FunctionNumber == -1) {
4710 ID.Kind = ValID::t_GlobalName;
4711 ID.StrVal = F.getName();
4712 } else {
4713 ID.Kind = ValID::t_GlobalID;
4714 ID.UIntVal = FunctionNumber;
4715 }
4716
4717 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4718 if (Blocks == P.ForwardRefBlockAddresses.end())
4719 return false;
4720
4721 for (const auto &I : Blocks->second) {
4722 const ValID &BBID = I.first;
4723 GlobalValue *GV = I.second;
4724
4725 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4726 "Expected local id or name");
4727 BasicBlock *BB;
4728 if (BBID.Kind == ValID::t_LocalName)
4729 BB = GetBB(BBID.StrVal, BBID.Loc);
4730 else
4731 BB = GetBB(BBID.UIntVal, BBID.Loc);
4732 if (!BB)
4733 return P.Error(BBID.Loc, "referenced value is not a basic block");
4734
4735 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4736 GV->eraseFromParent();
4737 }
4738
4739 P.ForwardRefBlockAddresses.erase(Blocks);
4740 return false;
4741}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004742
4743/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004744/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00004745bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00004746 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004747 return TokError("expected '{' in function body");
4748 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004749
Chris Lattner3432c622009-10-28 03:39:23 +00004750 int FunctionNumber = -1;
4751 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004752
Chris Lattner3432c622009-10-28 03:39:23 +00004753 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004754
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004755 // Resolve block addresses and allow basic blocks to be forward-declared
4756 // within this function.
4757 if (PFS.resolveForwardRefBlockAddresses())
4758 return true;
4759 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4760
Chris Lattnerbbddd962010-01-09 19:20:07 +00004761 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004762 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00004763 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004764
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004765 while (Lex.getKind() != lltok::rbrace &&
4766 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004767 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004768
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004769 while (Lex.getKind() != lltok::rbrace)
4770 if (ParseUseListOrder(&PFS))
4771 return true;
4772
Chris Lattnerac161bf2009-01-02 07:01:27 +00004773 // Eat the }.
4774 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004775
Chris Lattnerac161bf2009-01-02 07:01:27 +00004776 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00004777 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004778}
4779
4780/// ParseBasicBlock
4781/// ::= LabelStr? Instruction*
4782bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4783 // If this basic block starts out with a name, remember it.
4784 std::string Name;
4785 LocTy NameLoc = Lex.getLoc();
4786 if (Lex.getKind() == lltok::LabelStr) {
4787 Name = Lex.getStrVal();
4788 Lex.Lex();
4789 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004790
Chris Lattnerac161bf2009-01-02 07:01:27 +00004791 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00004792 if (!BB)
4793 return Error(NameLoc,
4794 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004795
Chris Lattnerac161bf2009-01-02 07:01:27 +00004796 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004797
Chris Lattnerac161bf2009-01-02 07:01:27 +00004798 // Parse the instructions in this block until we get a terminator.
4799 Instruction *Inst;
4800 do {
4801 // This instruction may have three possibilities for a name: a) none
4802 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4803 LocTy NameLoc = Lex.getLoc();
4804 int NameID = -1;
4805 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004806
Chris Lattnerac161bf2009-01-02 07:01:27 +00004807 if (Lex.getKind() == lltok::LocalVarID) {
4808 NameID = Lex.getUIntVal();
4809 Lex.Lex();
4810 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4811 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00004812 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004813 NameStr = Lex.getStrVal();
4814 Lex.Lex();
4815 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4816 return true;
4817 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004818
Chris Lattner77b89dc2009-12-30 05:23:43 +00004819 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00004820 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00004821 case InstError: return true;
4822 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004823 BB->getInstList().push_back(Inst);
4824
Chris Lattner77b89dc2009-12-30 05:23:43 +00004825 // With a normal result, we check to see if the instruction is followed by
4826 // a comma and metadata.
4827 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004828 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004829 return true;
4830 break;
4831 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004832 BB->getInstList().push_back(Inst);
4833
Chris Lattner77b89dc2009-12-30 05:23:43 +00004834 // If the instruction parser ate an extra comma at the end of it, it
4835 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004836 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004837 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004838 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00004839 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004840
Chris Lattnerac161bf2009-01-02 07:01:27 +00004841 // Set the name on the instruction.
4842 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4843 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004844
Chris Lattnerac161bf2009-01-02 07:01:27 +00004845 return false;
4846}
4847
4848//===----------------------------------------------------------------------===//
4849// Instruction Parsing.
4850//===----------------------------------------------------------------------===//
4851
4852/// ParseInstruction - Parse one of the many different instructions.
4853///
Chris Lattner77b89dc2009-12-30 05:23:43 +00004854int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4855 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004856 lltok::Kind Token = Lex.getKind();
4857 if (Token == lltok::Eof)
4858 return TokError("found end of file when expecting more instructions");
4859 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00004860 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004861 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004862
Chris Lattnerac161bf2009-01-02 07:01:27 +00004863 switch (Token) {
4864 default: return Error(Loc, "expected instruction opcode");
4865 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00004866 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004867 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
4868 case lltok::kw_br: return ParseBr(Inst, PFS);
4869 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004870 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004871 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00004872 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer654e1302015-07-31 17:58:14 +00004873 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
4874 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00004875 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
4876 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00004877 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004878 // Binary Operators.
4879 case lltok::kw_add:
4880 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004881 case lltok::kw_mul:
4882 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00004883 bool NUW = EatIfPresent(lltok::kw_nuw);
4884 bool NSW = EatIfPresent(lltok::kw_nsw);
4885 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004886
Chris Lattnera676c0f2011-02-07 16:40:21 +00004887 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004888
Chris Lattnera676c0f2011-02-07 16:40:21 +00004889 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4890 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4891 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004892 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004893 case lltok::kw_fadd:
4894 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00004895 case lltok::kw_fmul:
4896 case lltok::kw_fdiv:
4897 case lltok::kw_frem: {
4898 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4899 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4900 if (Res != 0)
4901 return Res;
4902 if (FMF.any())
4903 Inst->setFastMathFlags(FMF);
4904 return 0;
4905 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004906
Chris Lattner35315d02011-02-06 21:44:57 +00004907 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004908 case lltok::kw_udiv:
4909 case lltok::kw_lshr:
4910 case lltok::kw_ashr: {
4911 bool Exact = EatIfPresent(lltok::kw_exact);
4912
4913 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4914 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4915 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004916 }
4917
Chris Lattnerac161bf2009-01-02 07:01:27 +00004918 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00004919 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004920 case lltok::kw_and:
4921 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00004922 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00004923 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
4924 case lltok::kw_fcmp: {
4925 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4926 int Res = ParseCompare(Inst, PFS, KeywordVal);
4927 if (Res != 0)
4928 return Res;
4929 if (FMF.any())
4930 Inst->setFastMathFlags(FMF);
4931 return 0;
4932 }
4933
Chris Lattnerac161bf2009-01-02 07:01:27 +00004934 // Casts.
4935 case lltok::kw_trunc:
4936 case lltok::kw_zext:
4937 case lltok::kw_sext:
4938 case lltok::kw_fptrunc:
4939 case lltok::kw_fpext:
4940 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004941 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004942 case lltok::kw_uitofp:
4943 case lltok::kw_sitofp:
4944 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004945 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004946 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00004947 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004948 // Other.
4949 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00004950 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004951 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
4952 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
4953 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
4954 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00004955 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00004956 // Call.
4957 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
4958 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
4959 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00004960 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004961 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00004962 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00004963 case lltok::kw_load: return ParseLoad(Inst, PFS);
4964 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00004965 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
4966 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00004967 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004968 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
4969 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
4970 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
4971 }
4972}
4973
4974/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
4975bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004976 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004977 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00004978 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004979 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
4980 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
4981 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
4982 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
4983 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
4984 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
4985 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
4986 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
4987 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
4988 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
4989 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
4990 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
4991 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
4992 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
4993 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
4994 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
4995 }
4996 } else {
4997 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00004998 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004999 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5000 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5001 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5002 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5003 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5004 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5005 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5006 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5007 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5008 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5009 }
5010 }
5011 Lex.Lex();
5012 return false;
5013}
5014
5015//===----------------------------------------------------------------------===//
5016// Terminator Instructions.
5017//===----------------------------------------------------------------------===//
5018
5019/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00005020/// ::= 'ret' void (',' !dbg, !1)*
5021/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00005022bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005023 PerFunctionState &PFS) {
5024 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00005025 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00005026 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005027
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005028 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005029
Chris Lattnerfdd87902009-10-05 05:54:46 +00005030 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005031 if (!ResType->isVoidTy())
5032 return Error(TypeLoc, "value doesn't match function result type '" +
5033 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005034
Owen Anderson55f1c092009-08-13 21:58:54 +00005035 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005036 return false;
5037 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005038
Chris Lattnerac161bf2009-01-02 07:01:27 +00005039 Value *RV;
5040 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005041
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005042 if (ResType != RV->getType())
5043 return Error(TypeLoc, "value doesn't match function result type '" +
5044 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005045
Owen Anderson55f1c092009-08-13 21:58:54 +00005046 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00005047 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005048}
5049
5050
5051/// ParseBr
5052/// ::= 'br' TypeAndValue
5053/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5054bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5055 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005056 Value *Op0;
5057 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005058 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005059
Chris Lattnerac161bf2009-01-02 07:01:27 +00005060 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5061 Inst = BranchInst::Create(BB);
5062 return false;
5063 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005064
Owen Anderson55f1c092009-08-13 21:58:54 +00005065 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005066 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005067
Chris Lattnerac161bf2009-01-02 07:01:27 +00005068 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005069 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005070 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005071 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005072 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005073
Chris Lattner3ed871f2009-10-27 19:13:16 +00005074 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005075 return false;
5076}
5077
5078/// ParseSwitch
5079/// Instruction
5080/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5081/// JumpTable
5082/// ::= (TypeAndValue ',' TypeAndValue)*
5083bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5084 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005085 Value *Cond;
5086 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005087 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5088 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005089 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005090 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5091 return true;
5092
Duncan Sands19d0b472010-02-16 11:11:14 +00005093 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005094 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005095
Chris Lattnerac161bf2009-01-02 07:01:27 +00005096 // Parse the jump table pairs.
5097 SmallPtrSet<Value*, 32> SeenCases;
5098 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5099 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005100 Value *Constant;
5101 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005102
Chris Lattnerac161bf2009-01-02 07:01:27 +00005103 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5104 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005105 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005106 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005107
David Blaikie70573dc2014-11-19 07:49:26 +00005108 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005109 return Error(CondLoc, "duplicate case value in switch");
5110 if (!isa<ConstantInt>(Constant))
5111 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005112
Chris Lattner3ed871f2009-10-27 19:13:16 +00005113 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00005114 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005115
Chris Lattnerac161bf2009-01-02 07:01:27 +00005116 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005117
Chris Lattner3ed871f2009-10-27 19:13:16 +00005118 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005119 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5120 SI->addCase(Table[i].first, Table[i].second);
5121 Inst = SI;
5122 return false;
5123}
5124
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005125/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00005126/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005127/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5128bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005129 LocTy AddrLoc;
5130 Value *Address;
5131 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005132 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5133 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00005134 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005135
Duncan Sands19d0b472010-02-16 11:11:14 +00005136 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005137 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005138
Chris Lattner3ed871f2009-10-27 19:13:16 +00005139 // Parse the destination list.
5140 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005141
Chris Lattner3ed871f2009-10-27 19:13:16 +00005142 if (Lex.getKind() != lltok::rsquare) {
5143 BasicBlock *DestBB;
5144 if (ParseTypeAndBasicBlock(DestBB, PFS))
5145 return true;
5146 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005147
Chris Lattner3ed871f2009-10-27 19:13:16 +00005148 while (EatIfPresent(lltok::comma)) {
5149 if (ParseTypeAndBasicBlock(DestBB, PFS))
5150 return true;
5151 DestList.push_back(DestBB);
5152 }
5153 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005154
Chris Lattner3ed871f2009-10-27 19:13:16 +00005155 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5156 return true;
5157
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005158 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00005159 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5160 IBI->addDestination(DestList[i]);
5161 Inst = IBI;
5162 return false;
5163}
5164
5165
Chris Lattnerac161bf2009-01-02 07:01:27 +00005166/// ParseInvoke
5167/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5168/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5169bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5170 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00005171 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005172 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00005173 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005174 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005175 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005176 LocTy RetTypeLoc;
5177 ValID CalleeID;
5178 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005179 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005180
Chris Lattner3ed871f2009-10-27 19:13:16 +00005181 BasicBlock *NormalBB, *UnwindBB;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005182 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005183 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005184 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005185 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5186 NoBuiltinLoc) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005187 ParseOptionalOperandBundles(BundleList, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005188 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005189 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005190 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005191 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005192 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005193
Chris Lattnerac161bf2009-01-02 07:01:27 +00005194 // If RetType is a non-function pointer type, then this is the short syntax
5195 // for the call, which means that RetType is just the return type. Infer the
5196 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00005197 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5198 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005199 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005200 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005201 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5202 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005203
Chris Lattnerac161bf2009-01-02 07:01:27 +00005204 if (!FunctionType::isValidReturnType(RetType))
5205 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005206
Owen Anderson4056ca92009-07-29 22:17:13 +00005207 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005208 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005209
David Blaikie41ba2b42015-07-27 23:32:19 +00005210 CalleeID.FTy = Ty;
5211
Chris Lattnerac161bf2009-01-02 07:01:27 +00005212 // Look up the callee.
5213 Value *Callee;
David Blaikie445e3fb2015-04-24 19:32:54 +00005214 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5215 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005216
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005217 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005218 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005219 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005220 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5221 AttributeSet::ReturnIndex,
5222 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005223
Chris Lattnerac161bf2009-01-02 07:01:27 +00005224 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005225
Chris Lattnerac161bf2009-01-02 07:01:27 +00005226 // Loop through FunctionType's arguments and ensure they are specified
5227 // correctly. Also, gather any parameter attributes.
5228 FunctionType::param_iterator I = Ty->param_begin();
5229 FunctionType::param_iterator E = Ty->param_end();
5230 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005231 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005232 if (I != E) {
5233 ExpectedTy = *I++;
5234 } else if (!Ty->isVarArg()) {
5235 return Error(ArgList[i].Loc, "too many arguments specified");
5236 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005237
Chris Lattnerac161bf2009-01-02 07:01:27 +00005238 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5239 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005240 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005241 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005242 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5243 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005244 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5245 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005246 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005247
Chris Lattnerac161bf2009-01-02 07:01:27 +00005248 if (I != E)
5249 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005250
David Majnemer8d22abd2015-02-23 00:01:32 +00005251 if (FnAttrs.hasAttributes()) {
5252 if (FnAttrs.hasAlignmentAttr())
5253 return Error(CallLoc, "invoke instructions may not have an alignment");
5254
Bill Wendlingf5075a42013-01-27 02:24:02 +00005255 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5256 AttributeSet::FunctionIndex,
5257 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005258 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005259
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005260 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005261 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005262
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005263 InvokeInst *II =
5264 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005265 II->setCallingConv(CC);
5266 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005267 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005268 Inst = II;
5269 return false;
5270}
5271
Bill Wendlingf891bf82011-07-31 06:30:59 +00005272/// ParseResume
5273/// ::= 'resume' TypeAndValue
5274bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5275 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005276 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5277 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005278
Bill Wendlingf891bf82011-07-31 06:30:59 +00005279 ResumeInst *RI = ResumeInst::Create(Exn);
5280 Inst = RI;
5281 return false;
5282}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005283
David Majnemer654e1302015-07-31 17:58:14 +00005284bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5285 PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005286 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
David Majnemer654e1302015-07-31 17:58:14 +00005287 return true;
5288
5289 while (Lex.getKind() != lltok::rsquare) {
5290 // If this isn't the first argument, we need a comma.
5291 if (!Args.empty() &&
5292 ParseToken(lltok::comma, "expected ',' in argument list"))
5293 return true;
5294
5295 // Parse the argument.
5296 LocTy ArgLoc;
5297 Type *ArgTy = nullptr;
5298 if (ParseType(ArgTy, ArgLoc))
5299 return true;
5300
5301 Value *V;
5302 if (ArgTy->isMetadataTy()) {
5303 if (ParseMetadataAsValue(V, PFS))
5304 return true;
5305 } else {
5306 if (ParseValue(ArgTy, V, PFS))
5307 return true;
5308 }
5309 Args.push_back(V);
5310 }
5311
5312 Lex.Lex(); // Lex the ']'.
5313 return false;
5314}
5315
5316/// ParseCleanupRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005317/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
David Majnemer654e1302015-07-31 17:58:14 +00005318bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005319 Value *CleanupPad = nullptr;
David Majnemer654e1302015-07-31 17:58:14 +00005320
David Majnemer8a1c45d2015-12-12 05:38:55 +00005321 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5322 return true;
5323
5324 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005325 return true;
David Majnemer654e1302015-07-31 17:58:14 +00005326
5327 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5328 return true;
5329
5330 BasicBlock *UnwindBB = nullptr;
5331 if (Lex.getKind() == lltok::kw_to) {
5332 Lex.Lex();
5333 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5334 return true;
5335 } else {
5336 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5337 return true;
5338 }
5339 }
5340
David Majnemer8a1c45d2015-12-12 05:38:55 +00005341 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
David Majnemer654e1302015-07-31 17:58:14 +00005342 return false;
5343}
5344
5345/// ParseCatchRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005346/// ::= 'catchret' from Parent Value 'to' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005347bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005348 Value *CatchPad = nullptr;
David Majnemer0bc0eef2015-08-15 02:46:08 +00005349
David Majnemer8a1c45d2015-12-12 05:38:55 +00005350 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5351 return true;
5352
5353 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
David Majnemer0bc0eef2015-08-15 02:46:08 +00005354 return true;
5355
David Majnemer0bc0eef2015-08-15 02:46:08 +00005356 BasicBlock *BB;
5357 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5358 ParseTypeAndBasicBlock(BB, PFS))
5359 return true;
5360
David Majnemer8a1c45d2015-12-12 05:38:55 +00005361 Inst = CatchReturnInst::Create(CatchPad, BB);
5362 return false;
5363}
5364
5365/// ParseCatchSwitch
5366/// ::= 'catchswitch' within Parent
5367bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5368 Value *ParentPad;
5369 LocTy BBLoc;
5370
5371 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5372 return true;
5373
5374 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5375 Lex.getKind() != lltok::LocalVarID)
5376 return TokError("expected scope value for catchswitch");
5377
5378 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5379 return true;
5380
5381 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5382 return true;
5383
5384 SmallVector<BasicBlock *, 32> Table;
5385 do {
5386 BasicBlock *DestBB;
5387 if (ParseTypeAndBasicBlock(DestBB, PFS))
5388 return true;
5389 Table.push_back(DestBB);
5390 } while (EatIfPresent(lltok::comma));
5391
5392 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5393 return true;
5394
5395 if (ParseToken(lltok::kw_unwind,
5396 "expected 'unwind' after catchswitch scope"))
5397 return true;
5398
5399 BasicBlock *UnwindBB = nullptr;
5400 if (EatIfPresent(lltok::kw_to)) {
5401 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5402 return true;
5403 } else {
5404 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5405 return true;
5406 }
5407
5408 auto *CatchSwitch =
5409 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5410 for (BasicBlock *DestBB : Table)
5411 CatchSwitch->addHandler(DestBB);
5412 Inst = CatchSwitch;
David Majnemer654e1302015-07-31 17:58:14 +00005413 return false;
5414}
5415
5416/// ParseCatchPad
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005417/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005418bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005419 Value *CatchSwitch = nullptr;
5420
5421 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5422 return true;
5423
5424 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5425 return TokError("expected scope value for catchpad");
5426
5427 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5428 return true;
5429
David Majnemer654e1302015-07-31 17:58:14 +00005430 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005431 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005432 return true;
5433
David Majnemer8a1c45d2015-12-12 05:38:55 +00005434 Inst = CatchPadInst::Create(CatchSwitch, Args);
David Majnemer654e1302015-07-31 17:58:14 +00005435 return false;
5436}
5437
David Majnemer654e1302015-07-31 17:58:14 +00005438/// ParseCleanupPad
David Majnemer8a1c45d2015-12-12 05:38:55 +00005439/// ::= 'cleanuppad' within Parent ParamList
David Majnemer654e1302015-07-31 17:58:14 +00005440bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005441 Value *ParentPad = nullptr;
5442
5443 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5444 return true;
5445
5446 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5447 Lex.getKind() != lltok::LocalVarID)
5448 return TokError("expected scope value for cleanuppad");
5449
5450 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5451 return true;
5452
David Majnemer654e1302015-07-31 17:58:14 +00005453 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005454 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005455 return true;
5456
David Majnemer8a1c45d2015-12-12 05:38:55 +00005457 Inst = CleanupPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00005458 return false;
5459}
5460
Chris Lattnerac161bf2009-01-02 07:01:27 +00005461//===----------------------------------------------------------------------===//
5462// Binary Operators.
5463//===----------------------------------------------------------------------===//
5464
5465/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005466/// ::= ArithmeticOps TypeAndValue ',' Value
5467///
5468/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5469/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00005470bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005471 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005472 LocTy Loc; Value *LHS, *RHS;
5473 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5474 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5475 ParseValue(LHS->getType(), RHS, PFS))
5476 return true;
5477
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005478 bool Valid;
5479 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00005480 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005481 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00005482 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5483 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005484 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00005485 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5486 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005487 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005488
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005489 if (!Valid)
5490 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005491
Chris Lattnerac161bf2009-01-02 07:01:27 +00005492 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5493 return false;
5494}
5495
5496/// ParseLogical
5497/// ::= ArithmeticOps TypeAndValue ',' Value {
5498bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5499 unsigned Opc) {
5500 LocTy Loc; Value *LHS, *RHS;
5501 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5502 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5503 ParseValue(LHS->getType(), RHS, PFS))
5504 return true;
5505
Duncan Sands9dff9be2010-02-15 16:12:20 +00005506 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005507 return Error(Loc,"instruction requires integer or integer vector operands");
5508
5509 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5510 return false;
5511}
5512
5513
5514/// ParseCompare
5515/// ::= 'icmp' IPredicates TypeAndValue ',' Value
5516/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005517bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5518 unsigned Opc) {
5519 // Parse the integer/fp comparison predicate.
5520 LocTy Loc;
5521 unsigned Pred;
5522 Value *LHS, *RHS;
5523 if (ParseCmpPredicate(Pred, Opc) ||
5524 ParseTypeAndValue(LHS, Loc, PFS) ||
5525 ParseToken(lltok::comma, "expected ',' after compare value") ||
5526 ParseValue(LHS->getType(), RHS, PFS))
5527 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005528
Chris Lattnerac161bf2009-01-02 07:01:27 +00005529 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00005530 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005531 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005532 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005533 } else {
5534 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00005535 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00005536 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005537 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005538 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005539 }
5540 return false;
5541}
5542
5543//===----------------------------------------------------------------------===//
5544// Other Instructions.
5545//===----------------------------------------------------------------------===//
5546
5547
5548/// ParseCast
5549/// ::= CastOpc TypeAndValue 'to' Type
5550bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5551 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005552 LocTy Loc;
5553 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005554 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005555 if (ParseTypeAndValue(Op, Loc, PFS) ||
5556 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5557 ParseType(DestTy))
5558 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005559
Chris Lattner89d856e2009-03-01 00:53:13 +00005560 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5561 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005562 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005563 getTypeString(Op->getType()) + "' to '" +
5564 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00005565 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005566 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5567 return false;
5568}
5569
5570/// ParseSelect
5571/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5572bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5573 LocTy Loc;
5574 Value *Op0, *Op1, *Op2;
5575 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5576 ParseToken(lltok::comma, "expected ',' after select condition") ||
5577 ParseTypeAndValue(Op1, PFS) ||
5578 ParseToken(lltok::comma, "expected ',' after select value") ||
5579 ParseTypeAndValue(Op2, PFS))
5580 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005581
Chris Lattnerac161bf2009-01-02 07:01:27 +00005582 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5583 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005584
Chris Lattnerac161bf2009-01-02 07:01:27 +00005585 Inst = SelectInst::Create(Op0, Op1, Op2);
5586 return false;
5587}
5588
Chris Lattnerb55ab542009-01-05 08:18:44 +00005589/// ParseVA_Arg
5590/// ::= 'va_arg' TypeAndValue ',' Type
5591bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005592 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005593 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00005594 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005595 if (ParseTypeAndValue(Op, PFS) ||
5596 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00005597 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005598 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005599
Chris Lattnerb55ab542009-01-05 08:18:44 +00005600 if (!EltTy->isFirstClassType())
5601 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005602
5603 Inst = new VAArgInst(Op, EltTy);
5604 return false;
5605}
5606
5607/// ParseExtractElement
5608/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5609bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5610 LocTy Loc;
5611 Value *Op0, *Op1;
5612 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5613 ParseToken(lltok::comma, "expected ',' after extract value") ||
5614 ParseTypeAndValue(Op1, PFS))
5615 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005616
Chris Lattnerac161bf2009-01-02 07:01:27 +00005617 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5618 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005619
Eric Christopherc9742252009-07-25 02:28:41 +00005620 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005621 return false;
5622}
5623
5624/// ParseInsertElement
5625/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5626bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5627 LocTy Loc;
5628 Value *Op0, *Op1, *Op2;
5629 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5630 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5631 ParseTypeAndValue(Op1, PFS) ||
5632 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5633 ParseTypeAndValue(Op2, PFS))
5634 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005635
Chris Lattnerac161bf2009-01-02 07:01:27 +00005636 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00005637 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005638
Chris Lattnerac161bf2009-01-02 07:01:27 +00005639 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5640 return false;
5641}
5642
5643/// ParseShuffleVector
5644/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5645bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5646 LocTy Loc;
5647 Value *Op0, *Op1, *Op2;
5648 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5649 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5650 ParseTypeAndValue(Op1, PFS) ||
5651 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5652 ParseTypeAndValue(Op2, PFS))
5653 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005654
Chris Lattnerac161bf2009-01-02 07:01:27 +00005655 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00005656 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005657
Chris Lattnerac161bf2009-01-02 07:01:27 +00005658 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5659 return false;
5660}
5661
5662/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00005663/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005664int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005665 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005666 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005667
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005668 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005669 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5670 ParseValue(Ty, Op0, PFS) ||
5671 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005672 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005673 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5674 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005675
Chris Lattnerf4f03422009-12-30 05:27:33 +00005676 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005677 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5678 while (1) {
5679 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005680
Chris Lattner3822f632009-01-02 08:05:26 +00005681 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005682 break;
5683
Chris Lattnerf4f03422009-12-30 05:27:33 +00005684 if (Lex.getKind() == lltok::MetadataVar) {
5685 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00005686 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005687 }
Devang Patel8f842d32009-10-16 18:45:49 +00005688
Chris Lattner3822f632009-01-02 08:05:26 +00005689 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005690 ParseValue(Ty, Op0, PFS) ||
5691 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005692 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005693 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5694 return true;
5695 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005696
Chris Lattnerac161bf2009-01-02 07:01:27 +00005697 if (!Ty->isFirstClassType())
5698 return Error(TypeLoc, "phi node must have first class type");
5699
Jay Foad52131342011-03-30 11:28:46 +00005700 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005701 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5702 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5703 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005704 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005705}
5706
Bill Wendlingfae14752011-08-12 20:24:12 +00005707/// ParseLandingPad
5708/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5709/// Clause
5710/// ::= 'catch' TypeAndValue
5711/// ::= 'filter'
5712/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5713bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005714 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00005715
David Majnemer7fddecc2015-06-17 20:52:32 +00005716 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00005717 return true;
5718
David Majnemer7fddecc2015-06-17 20:52:32 +00005719 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00005720 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5721
5722 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5723 LandingPadInst::ClauseType CT;
5724 if (EatIfPresent(lltok::kw_catch))
5725 CT = LandingPadInst::Catch;
5726 else if (EatIfPresent(lltok::kw_filter))
5727 CT = LandingPadInst::Filter;
5728 else
5729 return TokError("expected 'catch' or 'filter' clause type");
5730
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005731 Value *V;
5732 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00005733 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00005734 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00005735
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00005736 // A 'catch' type expects a non-array constant. A filter clause expects an
5737 // array constant.
5738 if (CT == LandingPadInst::Catch) {
5739 if (isa<ArrayType>(V->getType()))
5740 Error(VLoc, "'catch' clause has an invalid type");
5741 } else {
5742 if (!isa<ArrayType>(V->getType()))
5743 Error(VLoc, "'filter' clause has an invalid type");
5744 }
5745
Owen Andersonf8f259d2015-03-09 07:13:42 +00005746 Constant *CV = dyn_cast<Constant>(V);
5747 if (!CV)
5748 return Error(VLoc, "clause argument must be a constant");
5749 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00005750 }
5751
Owen Andersonf8f259d2015-03-09 07:13:42 +00005752 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00005753 return false;
5754}
5755
Chris Lattnerac161bf2009-01-02 07:01:27 +00005756/// ParseCall
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005757/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
5758/// OptionalAttrs Type Value ParameterList OptionalAttrs
5759/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
5760/// OptionalAttrs Type Value ParameterList OptionalAttrs
5761/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
5762/// OptionalAttrs Type Value ParameterList OptionalAttrs
5763/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
5764/// OptionalAttrs Type Value ParameterList OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +00005765bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00005766 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00005767 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005768 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005769 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005770 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005771 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005772 LocTy RetTypeLoc;
5773 ValID CalleeID;
5774 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005775 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005776 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005777
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005778 if (TCK != CallInst::TCK_None &&
5779 ParseToken(lltok::kw_call,
5780 "expected 'tail call', 'musttail call', or 'notail call'"))
5781 return true;
5782
5783 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5784
5785 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005786 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005787 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00005788 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5789 PFS.getFunction().isVarArg()) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005790 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
5791 ParseOptionalOperandBundles(BundleList, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005792 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005793
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005794 if (FMF.any() && !RetType->isFPOrFPVectorTy())
5795 return Error(CallLoc, "fast-math-flags specified for call without "
5796 "floating-point scalar or vector return type");
5797
Chris Lattnerac161bf2009-01-02 07:01:27 +00005798 // If RetType is a non-function pointer type, then this is the short syntax
5799 // for the call, which means that RetType is just the return type. Infer the
5800 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00005801 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5802 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005803 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005804 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00005805 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5806 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005807
Chris Lattnerac161bf2009-01-02 07:01:27 +00005808 if (!FunctionType::isValidReturnType(RetType))
5809 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005810
Owen Anderson4056ca92009-07-29 22:17:13 +00005811 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005812 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005813
David Blaikie41ba2b42015-07-27 23:32:19 +00005814 CalleeID.FTy = Ty;
5815
Chris Lattnerac161bf2009-01-02 07:01:27 +00005816 // Look up the callee.
5817 Value *Callee;
David Blaikie23af6482015-04-16 23:24:18 +00005818 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5819 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005820
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005821 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005822 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005823 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005824 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5825 AttributeSet::ReturnIndex,
5826 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005827
Chris Lattnerac161bf2009-01-02 07:01:27 +00005828 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005829
Chris Lattnerac161bf2009-01-02 07:01:27 +00005830 // Loop through FunctionType's arguments and ensure they are specified
5831 // correctly. Also, gather any parameter attributes.
5832 FunctionType::param_iterator I = Ty->param_begin();
5833 FunctionType::param_iterator E = Ty->param_end();
5834 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005835 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005836 if (I != E) {
5837 ExpectedTy = *I++;
5838 } else if (!Ty->isVarArg()) {
5839 return Error(ArgList[i].Loc, "too many arguments specified");
5840 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005841
Chris Lattnerac161bf2009-01-02 07:01:27 +00005842 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5843 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005844 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005845 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005846 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5847 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005848 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5849 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005850 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005851
Chris Lattnerac161bf2009-01-02 07:01:27 +00005852 if (I != E)
5853 return Error(CallLoc, "not enough parameters specified for call");
5854
David Majnemer8d22abd2015-02-23 00:01:32 +00005855 if (FnAttrs.hasAttributes()) {
5856 if (FnAttrs.hasAlignmentAttr())
5857 return Error(CallLoc, "call instructions may not have an alignment");
5858
Bill Wendlingf5075a42013-01-27 02:24:02 +00005859 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5860 AttributeSet::FunctionIndex,
5861 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005862 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005863
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005864 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005865 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005866
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005867 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
Reid Kleckner5772b772014-04-24 20:14:34 +00005868 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005869 CI->setCallingConv(CC);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005870 if (FMF.any())
5871 CI->setFastMathFlags(FMF);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005872 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005873 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005874 Inst = CI;
5875 return false;
5876}
5877
5878//===----------------------------------------------------------------------===//
5879// Memory Instructions.
5880//===----------------------------------------------------------------------===//
5881
5882/// ParseAlloc
Manman Ren9bfd0d02016-04-01 21:41:15 +00005883/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
5884/// (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00005885int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005886 Value *Size = nullptr;
David Majnemera3b0eb22015-02-16 08:38:03 +00005887 LocTy SizeLoc, TyLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005888 unsigned Alignment = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00005889 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00005890
5891 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00005892 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
David Majnemerc4ab61c2014-03-09 06:41:58 +00005893
David Majnemera3b0eb22015-02-16 08:38:03 +00005894 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005895
David Majnemera3b0eb22015-02-16 08:38:03 +00005896 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5897 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00005898
Chris Lattnerb2f39502009-12-30 05:44:30 +00005899 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00005900 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00005901 if (Lex.getKind() == lltok::kw_align) {
5902 if (ParseOptionalAlignment(Alignment)) return true;
5903 } else if (Lex.getKind() == lltok::MetadataVar) {
5904 AteExtraComma = true;
5905 } else {
5906 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5907 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5908 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005909 }
5910 }
5911
Dan Gohman2140a742010-05-28 01:14:11 +00005912 if (Size && !Size->getType()->isIntegerTy())
5913 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005914
Reid Kleckner436c42e2014-01-17 23:58:17 +00005915 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5916 AI->setUsedWithInAlloca(IsInAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00005917 AI->setSwiftError(IsSwiftError);
Reid Kleckner436c42e2014-01-17 23:58:17 +00005918 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00005919 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005920}
5921
5922/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00005923/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005924/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00005925/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005926int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005927 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005928 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005929 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005930 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00005931 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedman59b66882011-08-09 23:02:53 +00005932 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005933
5934 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005935 isAtomic = true;
5936 Lex.Lex();
5937 }
5938
Chris Lattnerbc639292011-11-27 06:56:53 +00005939 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005940 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005941 isVolatile = true;
5942 Lex.Lex();
5943 }
5944
David Blaikie15d9a4c2015-04-06 20:59:48 +00005945 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00005946 LocTy ExplicitTypeLoc = Lex.getLoc();
5947 if (ParseType(Ty) ||
5948 ParseToken(lltok::comma, "expected comma after load's type") ||
5949 ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005950 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005951 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5952 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005953
David Blaikie15d9a4c2015-04-06 20:59:48 +00005954 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005955 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00005956 if (isAtomic && !Alignment)
5957 return Error(Loc, "atomic load must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00005958 if (Ordering == AtomicOrdering::Release ||
5959 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00005960 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005961
David Blaikiea79ac142015-02-27 21:17:42 +00005962 if (Ty != cast<PointerType>(Val->getType())->getElementType())
5963 return Error(ExplicitTypeLoc,
5964 "explicit pointee type doesn't match operand's pointee type");
5965
David Blaikie15d9a4c2015-04-06 20:59:48 +00005966 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00005967 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005968}
5969
5970/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00005971
5972/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
5973/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00005974/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005975int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005976 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005977 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005978 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005979 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00005980 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedman59b66882011-08-09 23:02:53 +00005981 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005982
5983 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005984 isAtomic = true;
5985 Lex.Lex();
5986 }
5987
Chris Lattnerbc639292011-11-27 06:56:53 +00005988 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005989 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005990 isVolatile = true;
5991 Lex.Lex();
5992 }
5993
Chris Lattnerac161bf2009-01-02 07:01:27 +00005994 if (ParseTypeAndValue(Val, Loc, PFS) ||
5995 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005996 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005997 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005998 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005999 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00006000
Duncan Sands19d0b472010-02-16 11:11:14 +00006001 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006002 return Error(PtrLoc, "store operand must be a pointer");
6003 if (!Val->getType()->isFirstClassType())
6004 return Error(Loc, "store operand must be a first class value");
6005 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6006 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00006007 if (isAtomic && !Alignment)
6008 return Error(Loc, "atomic store must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006009 if (Ordering == AtomicOrdering::Acquire ||
6010 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006011 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006012
Eli Friedman59b66882011-08-09 23:02:53 +00006013 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006014 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006015}
6016
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006017/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00006018/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6019/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00006020int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006021 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6022 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006023 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6024 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006025 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006026 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00006027 bool isWeak = false;
6028
6029 if (EatIfPresent(lltok::kw_weak))
6030 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00006031
6032 if (EatIfPresent(lltok::kw_volatile))
6033 isVolatile = true;
6034
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006035 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6036 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6037 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6038 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6039 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00006040 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
6041 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006042 return true;
6043
JF Bastien800f87a2016-04-06 21:19:33 +00006044 if (SuccessOrdering == AtomicOrdering::Unordered ||
6045 FailureOrdering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006046 return TokError("cmpxchg cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006047 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6048 return TokError("cmpxchg failure argument shall be no stronger than the "
6049 "success argument");
6050 if (FailureOrdering == AtomicOrdering::Release ||
6051 FailureOrdering == AtomicOrdering::AcquireRelease)
6052 return TokError(
6053 "cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006054 if (!Ptr->getType()->isPointerTy())
6055 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6056 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6057 return Error(CmpLoc, "compare value and pointer type do not match");
6058 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6059 return Error(NewLoc, "new value and pointer type do not match");
Philip Reames1960cfd2016-02-19 00:06:41 +00006060 if (!New->getType()->isFirstClassType())
6061 return Error(NewLoc, "cmpxchg operand must be a first class value");
Tim Northover420a2162014-06-13 14:24:07 +00006062 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
6063 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006064 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00006065 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006066 Inst = CXI;
6067 return AteExtraComma ? InstExtraComma : InstNormal;
6068}
6069
6070/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00006071/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6072/// 'singlethread'? AtomicOrdering
6073int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006074 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6075 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006076 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006077 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006078 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006079 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00006080
6081 if (EatIfPresent(lltok::kw_volatile))
6082 isVolatile = true;
6083
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006084 switch (Lex.getKind()) {
6085 default: return TokError("expected binary operation in atomicrmw");
6086 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6087 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6088 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6089 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6090 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6091 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6092 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6093 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6094 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6095 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6096 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6097 }
6098 Lex.Lex(); // Eat the operation.
6099
6100 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6101 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6102 ParseTypeAndValue(Val, ValLoc, PFS) ||
6103 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6104 return true;
6105
JF Bastien800f87a2016-04-06 21:19:33 +00006106 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006107 return TokError("atomicrmw cannot be unordered");
6108 if (!Ptr->getType()->isPointerTy())
6109 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6110 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6111 return Error(ValLoc, "atomicrmw value and pointer type do not match");
6112 if (!Val->getType()->isIntegerTy())
6113 return Error(ValLoc, "atomicrmw operand must be an integer");
6114 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6115 if (Size < 8 || (Size & (Size - 1)))
6116 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6117 " integer");
6118
6119 AtomicRMWInst *RMWI =
6120 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
6121 RMWI->setVolatile(isVolatile);
6122 Inst = RMWI;
6123 return AteExtraComma ? InstExtraComma : InstNormal;
6124}
6125
Eli Friedmanfee02c62011-07-25 23:16:38 +00006126/// ParseFence
6127/// ::= 'fence' 'singlethread'? AtomicOrdering
6128int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
JF Bastien800f87a2016-04-06 21:19:33 +00006129 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedmanfee02c62011-07-25 23:16:38 +00006130 SynchronizationScope Scope = CrossThread;
6131 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6132 return true;
6133
JF Bastien800f87a2016-04-06 21:19:33 +00006134 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006135 return TokError("fence cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006136 if (Ordering == AtomicOrdering::Monotonic)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006137 return TokError("fence cannot be monotonic");
6138
6139 Inst = new FenceInst(Context, Ordering, Scope);
6140 return InstNormal;
6141}
6142
Chris Lattnerac161bf2009-01-02 07:01:27 +00006143/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00006144/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006145int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006146 Value *Ptr = nullptr;
6147 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006148 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00006149
Dan Gohman16cbbe42009-07-29 15:58:36 +00006150 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00006151
David Blaikie79e6c742015-02-27 19:29:02 +00006152 Type *Ty = nullptr;
6153 LocTy ExplicitTypeLoc = Lex.getLoc();
6154 if (ParseType(Ty) ||
6155 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6156 ParseTypeAndValue(Ptr, Loc, PFS))
6157 return true;
6158
Eli Benderskyd9806682013-04-22 17:03:42 +00006159 Type *BaseType = Ptr->getType();
6160 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6161 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006162 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006163
David Blaikie8d757942015-03-09 23:08:44 +00006164 if (Ty != BasePointerType->getElementType())
6165 return Error(ExplicitTypeLoc,
6166 "explicit pointee type doesn't match operand's pointee type");
6167
Chris Lattnerac161bf2009-01-02 07:01:27 +00006168 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006169 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006170 // GEP returns a vector of pointers if at least one of parameters is a vector.
6171 // All vector parameters should have the same vector width.
6172 unsigned GEPWidth = BaseType->isVectorTy() ?
6173 BaseType->getVectorNumElements() : 0;
6174
Chris Lattner3822f632009-01-02 08:05:26 +00006175 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00006176 if (Lex.getKind() == lltok::MetadataVar) {
6177 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00006178 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006179 }
Chris Lattner3822f632009-01-02 08:05:26 +00006180 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006181 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006182 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006183
Nadav Rotem3924cb02011-12-05 06:29:09 +00006184 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006185 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6186 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00006187 return Error(EltLoc,
6188 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006189 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006190 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006191 Indices.push_back(Val);
6192 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006193
Craig Toppere3dcce92015-08-01 22:20:21 +00006194 SmallPtrSet<Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00006195 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00006196 return Error(Loc, "base element of getelementptr must be sized");
6197
David Blaikied33bad32015-04-17 22:32:13 +00006198 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006199 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00006200 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00006201 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00006202 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006203 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006204}
6205
6206/// ParseExtractValue
6207/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006208int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006209 Value *Val; LocTy Loc;
6210 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006211 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006212 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006213 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006214 return true;
6215
Chris Lattner392be582010-02-12 20:49:41 +00006216 if (!Val->getType()->isAggregateType())
6217 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006218
Jay Foad57aa6362011-07-13 10:26:04 +00006219 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006220 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00006221 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006222 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006223}
6224
6225/// ParseInsertValue
6226/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006227int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006228 Value *Val0, *Val1; LocTy Loc0, Loc1;
6229 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006230 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006231 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6232 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6233 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006234 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006235 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006236
Chris Lattner392be582010-02-12 20:49:41 +00006237 if (!Val0->getType()->isAggregateType())
6238 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006239
David Majnemer30074532015-02-11 07:43:58 +00006240 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6241 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006242 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00006243 if (IndexedType != Val1->getType())
6244 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6245 getTypeString(Val1->getType()) + "' instead of '" +
6246 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00006247 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006248 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006249}
Nick Lewycky49f89192009-04-04 07:22:01 +00006250
6251//===----------------------------------------------------------------------===//
6252// Embedded metadata.
6253//===----------------------------------------------------------------------===//
6254
6255/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006256/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006257/// Element
6258/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006259bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00006260 if (ParseToken(lltok::lbrace, "expected '{' here"))
6261 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006262
Dan Gohman1e0213a2010-07-13 19:33:27 +00006263 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006264 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00006265 return false;
6266
Nick Lewycky49f89192009-04-04 07:22:01 +00006267 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006268 // Null is a special case since it is typeless.
6269 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006270 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006271 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006272 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006273
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006274 Metadata *MD;
6275 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006276 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006277 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00006278 } while (EatIfPresent(lltok::comma));
6279
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006280 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00006281}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006282
6283//===----------------------------------------------------------------------===//
6284// Use-list order directives.
6285//===----------------------------------------------------------------------===//
6286bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6287 SMLoc Loc) {
6288 if (V->use_empty())
6289 return Error(Loc, "value has no uses");
6290
6291 unsigned NumUses = 0;
6292 SmallDenseMap<const Use *, unsigned, 16> Order;
6293 for (const Use &U : V->uses()) {
6294 if (++NumUses > Indexes.size())
6295 break;
6296 Order[&U] = Indexes[NumUses - 1];
6297 }
6298 if (NumUses < 2)
6299 return Error(Loc, "value only has one use");
6300 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6301 return Error(Loc, "wrong number of indexes, expected " +
6302 Twine(std::distance(V->use_begin(), V->use_end())));
6303
6304 V->sortUseList([&](const Use &L, const Use &R) {
6305 return Order.lookup(&L) < Order.lookup(&R);
6306 });
6307 return false;
6308}
6309
6310/// ParseUseListOrderIndexes
6311/// ::= '{' uint32 (',' uint32)+ '}'
6312bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6313 SMLoc Loc = Lex.getLoc();
6314 if (ParseToken(lltok::lbrace, "expected '{' here"))
6315 return true;
6316 if (Lex.getKind() == lltok::rbrace)
6317 return Lex.Error("expected non-empty list of uselistorder indexes");
6318
6319 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6320 // indexes should be distinct numbers in the range [0, size-1], and should
6321 // not be in order.
6322 unsigned Offset = 0;
6323 unsigned Max = 0;
6324 bool IsOrdered = true;
6325 assert(Indexes.empty() && "Expected empty order vector");
6326 do {
6327 unsigned Index;
6328 if (ParseUInt32(Index))
6329 return true;
6330
6331 // Update consistency checks.
6332 Offset += Index - Indexes.size();
6333 Max = std::max(Max, Index);
6334 IsOrdered &= Index == Indexes.size();
6335
6336 Indexes.push_back(Index);
6337 } while (EatIfPresent(lltok::comma));
6338
6339 if (ParseToken(lltok::rbrace, "expected '}' here"))
6340 return true;
6341
6342 if (Indexes.size() < 2)
6343 return Error(Loc, "expected >= 2 uselistorder indexes");
6344 if (Offset != 0 || Max >= Indexes.size())
6345 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6346 if (IsOrdered)
6347 return Error(Loc, "expected uselistorder indexes to change the order");
6348
6349 return false;
6350}
6351
6352/// ParseUseListOrder
6353/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6354bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6355 SMLoc Loc = Lex.getLoc();
6356 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6357 return true;
6358
6359 Value *V;
6360 SmallVector<unsigned, 16> Indexes;
6361 if (ParseTypeAndValue(V, PFS) ||
6362 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6363 ParseUseListOrderIndexes(Indexes))
6364 return true;
6365
6366 return sortUseListOrder(V, Indexes, Loc);
6367}
6368
6369/// ParseUseListOrderBB
6370/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6371bool LLParser::ParseUseListOrderBB() {
6372 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6373 SMLoc Loc = Lex.getLoc();
6374 Lex.Lex();
6375
6376 ValID Fn, Label;
6377 SmallVector<unsigned, 16> Indexes;
6378 if (ParseValID(Fn) ||
6379 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6380 ParseValID(Label) ||
6381 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6382 ParseUseListOrderIndexes(Indexes))
6383 return true;
6384
6385 // Check the function.
6386 GlobalValue *GV;
6387 if (Fn.Kind == ValID::t_GlobalName)
6388 GV = M->getNamedValue(Fn.StrVal);
6389 else if (Fn.Kind == ValID::t_GlobalID)
6390 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6391 else
6392 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6393 if (!GV)
6394 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6395 auto *F = dyn_cast<Function>(GV);
6396 if (!F)
6397 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6398 if (F->isDeclaration())
6399 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6400
6401 // Check the basic block.
6402 if (Label.Kind == ValID::t_LocalID)
6403 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6404 if (Label.Kind != ValID::t_LocalName)
6405 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
6406 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
6407 if (!V)
6408 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6409 if (!isa<BasicBlock>(V))
6410 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6411
6412 return sortUseListOrder(V, Indexes, Loc);
6413}