blob: ea04eb70edecc120e92213680b48f2b20d28ea3b [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;
Dan Gohman466876b2009-08-12 23:32:33 +0000457 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000458 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000459 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000460 ParseOptionalThreadLocal(TLM) ||
461 parseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000462 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000463
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000464 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000465 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000466 DLLStorageClass, TLM, UnnamedAddr);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000467
468 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
469 DLLStorageClass, TLM, UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000470}
471
Chris Lattnerac161bf2009-01-02 07:01:27 +0000472/// ParseNamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000473/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000474/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
475/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000476bool LLParser::ParseNamedGlobal() {
477 assert(Lex.getKind() == lltok::GlobalVar);
478 LocTy NameLoc = Lex.getLoc();
479 std::string Name = Lex.getStrVal();
480 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000481
Chris Lattnerac161bf2009-01-02 07:01:27 +0000482 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000483 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000484 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000485 bool UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000486 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
487 ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000488 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000489 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000490 ParseOptionalThreadLocal(TLM) ||
491 parseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000492 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000493
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000494 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000495 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000496 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000497
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000498 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
499 DLLStorageClass, TLM, UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000500}
501
David Majnemerdad0a642014-06-27 18:19:56 +0000502bool LLParser::parseComdat() {
503 assert(Lex.getKind() == lltok::ComdatVar);
504 std::string Name = Lex.getStrVal();
505 LocTy NameLoc = Lex.getLoc();
506 Lex.Lex();
507
508 if (ParseToken(lltok::equal, "expected '=' here"))
509 return true;
510
511 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
512 return TokError("expected comdat type");
513
514 Comdat::SelectionKind SK;
515 switch (Lex.getKind()) {
516 default:
517 return TokError("unknown selection kind");
518 case lltok::kw_any:
519 SK = Comdat::Any;
520 break;
521 case lltok::kw_exactmatch:
522 SK = Comdat::ExactMatch;
523 break;
524 case lltok::kw_largest:
525 SK = Comdat::Largest;
526 break;
527 case lltok::kw_noduplicates:
528 SK = Comdat::NoDuplicates;
529 break;
530 case lltok::kw_samesize:
531 SK = Comdat::SameSize;
532 break;
533 }
534 Lex.Lex();
535
536 // See if the comdat was forward referenced, if so, use the comdat.
537 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
538 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
539 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
540 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
541
542 Comdat *C;
543 if (I != ComdatSymTab.end())
544 C = &I->second;
545 else
546 C = M->getOrInsertComdat(Name);
547 C->setSelectionKind(SK);
548
549 return false;
550}
551
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000552// MDString:
553// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000554bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000555 std::string Str;
556 if (ParseStringConstant(Str)) return true;
Chris Lattner1797fc72009-12-29 21:53:55 +0000557 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000558 return false;
559}
560
561// MDNode:
562// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000563bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000564 // !{ ..., !42, ... }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000565 LocTy IDLoc = Lex.getLoc();
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000566 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000567 if (ParseUInt32(MID))
568 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000569
Chris Lattner8eff0152010-04-01 05:14:45 +0000570 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000571 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000572 Result = NumberedMetadata[MID];
573 return false;
574 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000575
Chris Lattner8eff0152010-04-01 05:14:45 +0000576 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000577 auto &FwdRef = ForwardRefMDNodes[MID];
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000578 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000579
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000580 Result = FwdRef.first.get();
581 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000582 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000583}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000584
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000585/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000586/// !foo = !{ !1, !2 }
587bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000588 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000589 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000590 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000591
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000592 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000593 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000594 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000595 return true;
596
Dan Gohman2637cc12010-07-21 23:38:33 +0000597 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000598 if (Lex.getKind() != lltok::rbrace)
599 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000600 if (ParseToken(lltok::exclaim, "Expected '!' here"))
601 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000602
Craig Topper2617dcc2014-04-15 06:32:26 +0000603 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000604 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000605 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000606 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000607
Rafael Espindolac7818fb2015-05-26 20:37:36 +0000608 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Patelbe626972009-07-29 00:34:02 +0000609}
610
Devang Patel39e64d42009-07-01 19:21:12 +0000611/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000612/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000613bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000614 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000615 Lex.Lex();
616 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000617
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000618 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000619 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000620 ParseToken(lltok::equal, "expected '=' here"))
621 return true;
622
623 // Detect common error, from old metadata syntax.
624 if (Lex.getKind() == lltok::Type)
625 return TokError("unexpected type in metadata definition");
626
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000627 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000628 if (Lex.getKind() == lltok::MetadataVar) {
629 if (ParseSpecializedMDNode(Init, IsDistinct))
630 return true;
631 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
632 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000633 return true;
634
Chris Lattnerfc58af22009-12-30 04:51:58 +0000635 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000636 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000637 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000638 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000639 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000640
Chris Lattnerfc58af22009-12-30 04:51:58 +0000641 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
642 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000643 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000644 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000645 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000646 }
647
Devang Patel39e64d42009-07-01 19:21:12 +0000648 return false;
649}
650
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000651static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
652 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
653 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
654}
655
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000656/// parseIndirectSymbol:
Rafael Espindola464fe022014-07-30 22:51:54 +0000657/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
658/// OptionalDLLStorageClass OptionalThreadLocal
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000659/// OptionalUnnamedAddr 'alias|ifunc' IndirectSymbol
Rafael Espindola6b238632014-05-16 19:35:39 +0000660///
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000661/// IndirectSymbol
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000662/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000663///
Eric Christopher536f0a92015-05-28 23:07:39 +0000664/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000665///
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000666bool LLParser::parseIndirectSymbol(const std::string &Name, LocTy NameLoc,
667 unsigned L, unsigned Visibility,
668 unsigned DLLStorageClass,
669 GlobalVariable::ThreadLocalMode TLM,
670 bool UnnamedAddr) {
671 bool IsAlias;
672 if (Lex.getKind() == lltok::kw_alias)
673 IsAlias = true;
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000674 else if (Lex.getKind() == lltok::kw_ifunc)
675 IsAlias = false;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000676 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000677 llvm_unreachable("Not an alias or ifunc!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000678 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000679
Rafael Espindola78527052013-10-06 15:10:43 +0000680 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
681
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000682 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000683 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000684
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000685 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000686 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000687 "symbol with local linkage must have default visibility");
688
David Blaikie2f408302015-09-11 03:22:04 +0000689 Type *Ty;
690 LocTy ExplicitTypeLoc = Lex.getLoc();
691 if (ParseType(Ty) ||
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000692 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
David Blaikie2f408302015-09-11 03:22:04 +0000693 return true;
694
Rafael Espindola64c1e182014-06-03 02:41:57 +0000695 Constant *Aliasee;
696 LocTy AliaseeLoc = Lex.getLoc();
697 if (Lex.getKind() != lltok::kw_bitcast &&
698 Lex.getKind() != lltok::kw_getelementptr &&
699 Lex.getKind() != lltok::kw_addrspacecast &&
700 Lex.getKind() != lltok::kw_inttoptr) {
701 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000702 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000703 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000704 // The bitcast dest type is not present, it is implied by the dest type.
705 ValID ID;
706 if (ParseValID(ID))
707 return true;
708 if (ID.Kind != ValID::t_Constant)
709 return Error(AliaseeLoc, "invalid aliasee");
710 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000711 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000712
Rafael Espindola64c1e182014-06-03 02:41:57 +0000713 Type *AliaseeType = Aliasee->getType();
714 auto *PTy = dyn_cast<PointerType>(AliaseeType);
715 if (!PTy)
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000716 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
David Blaikie16a2f3e2015-09-14 18:01:59 +0000717 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000718
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000719 if (IsAlias && Ty != PTy->getElementType())
David Blaikie2f408302015-09-11 03:22:04 +0000720 return Error(
721 ExplicitTypeLoc,
722 "explicit pointee type doesn't match operand's pointee type");
723
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000724 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
725 return Error(
726 ExplicitTypeLoc,
727 "explicit pointee type should be a function type");
728
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000729 GlobalValue *GVal = nullptr;
730
731 // See if the alias was forward referenced, if so, prepare to replace the
732 // forward reference.
733 if (!Name.empty()) {
734 GVal = M->getNamedValue(Name);
735 if (GVal) {
736 if (!ForwardRefVals.erase(Name))
737 return Error(NameLoc, "redefinition of global '@" + Name + "'");
738 }
739 } else {
740 auto I = ForwardRefValIDs.find(NumberedVals.size());
741 if (I != ForwardRefValIDs.end()) {
742 GVal = I->second.first;
743 ForwardRefValIDs.erase(I);
744 }
745 }
746
Chris Lattnerac161bf2009-01-02 07:01:27 +0000747 // Okay, create the alias but do not insert it into the module yet.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000748 std::unique_ptr<GlobalIndirectSymbol> GA;
749 if (IsAlias)
750 GA.reset(GlobalAlias::create(Ty, AddrSpace,
751 (GlobalValue::LinkageTypes)Linkage, Name,
752 Aliasee, /*Parent*/ nullptr));
753 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000754 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
755 (GlobalValue::LinkageTypes)Linkage, Name,
756 Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000757 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000758 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000759 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000760 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000761
Rafael Espindola54fc2982015-06-17 17:53:31 +0000762 if (Name.empty())
763 NumberedVals.push_back(GA.get());
764
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000765 if (GVal) {
766 // Verify that types agree.
767 if (GVal->getType() != GA->getType())
768 return Error(
769 ExplicitTypeLoc,
770 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000771
Chris Lattnerac161bf2009-01-02 07:01:27 +0000772 // If they agree, just RAUW the old value with the alias and remove the
773 // forward ref info.
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000774 GVal->replaceAllUsesWith(GA.get());
775 GVal->eraseFromParent();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000776 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000777
Chris Lattnerac161bf2009-01-02 07:01:27 +0000778 // Insert into the module, we know its name won't collide now.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000779 if (IsAlias)
780 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
781 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000782 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000783 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000784
Rafael Espindolaaa273822014-05-09 21:49:17 +0000785 // The module owns this now
786 GA.release();
787
Chris Lattnerac161bf2009-01-02 07:01:27 +0000788 return false;
789}
790
791/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000792/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000793/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000794/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000795/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000796/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000797/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000798///
Eric Christopher536f0a92015-05-28 23:07:39 +0000799/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000800/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000801///
802bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
803 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000804 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000805 GlobalVariable::ThreadLocalMode TLM,
806 bool UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000807 if (!isValidVisibilityForLinkage(Visibility, Linkage))
808 return Error(NameLoc,
809 "symbol with local linkage must have default visibility");
810
Chris Lattnerac161bf2009-01-02 07:01:27 +0000811 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000812 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000813 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000814 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000815
Craig Topper2617dcc2014-04-15 06:32:26 +0000816 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000817 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000818 ParseOptionalToken(lltok::kw_externally_initialized,
819 IsExternallyInitialized,
820 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000821 ParseGlobalType(IsConstant) ||
822 ParseType(Ty, TyLoc))
823 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000824
Chris Lattnerac161bf2009-01-02 07:01:27 +0000825 // If the linkage is specified and is external, then no initializer is
826 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000827 Constant *Init = nullptr;
Rafael Espindola4787ba32016-05-11 13:51:39 +0000828 if (!HasLinkage ||
829 !GlobalValue::isValidDeclarationLinkage(
830 (GlobalValue::LinkageTypes)Linkage)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000831 if (ParseGlobalValue(Ty, Init))
832 return true;
833 }
834
David Majnemer49b3d9b2015-02-16 08:41:08 +0000835 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000836 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000837
David Majnemer598bd052014-12-09 05:56:09 +0000838 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000839
840 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000841 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000842 GVal = M->getNamedValue(Name);
843 if (GVal) {
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000844 if (!ForwardRefVals.erase(Name))
Chris Lattnere38317f2009-10-25 23:22:50 +0000845 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000846 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000847 } else {
David Blaikie9ebdc692015-09-21 21:07:50 +0000848 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000849 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000850 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000851 ForwardRefValIDs.erase(I);
852 }
853 }
854
David Majnemer598bd052014-12-09 05:56:09 +0000855 GlobalVariable *GV;
856 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000857 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
858 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000859 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000860 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +0000861 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000862 return Error(TyLoc,
863 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000864
David Majnemer598bd052014-12-09 05:56:09 +0000865 GV = cast<GlobalVariable>(GVal);
866
Chris Lattnerac161bf2009-01-02 07:01:27 +0000867 // Move the forward-reference to the correct spot in the module.
868 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
869 }
870
871 if (Name.empty())
872 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000873
Chris Lattnerac161bf2009-01-02 07:01:27 +0000874 // Set the parsed properties on the global.
875 if (Init)
876 GV->setInitializer(Init);
877 GV->setConstant(IsConstant);
878 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
879 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000880 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000881 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000882 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000883 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000884
Chris Lattnerac161bf2009-01-02 07:01:27 +0000885 // Parse attributes on the global.
886 while (Lex.getKind() == lltok::comma) {
887 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000888
Chris Lattnerac161bf2009-01-02 07:01:27 +0000889 if (Lex.getKind() == lltok::kw_section) {
890 Lex.Lex();
891 GV->setSection(Lex.getStrVal());
892 if (ParseToken(lltok::StringConstant, "expected global section string"))
893 return true;
894 } else if (Lex.getKind() == lltok::kw_align) {
895 unsigned Alignment;
896 if (ParseOptionalAlignment(Alignment)) return true;
897 GV->setAlignment(Alignment);
898 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000899 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000900 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000901 return true;
902 if (C)
903 GV->setComdat(C);
904 else
905 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000906 }
907 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000908
Chris Lattnerac161bf2009-01-02 07:01:27 +0000909 return false;
910}
911
Bill Wendling63b88192013-02-06 06:52:58 +0000912/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000913/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000914bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000915 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000916 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000917 Lex.Lex();
918
David Majnemerb39e22b2014-12-09 18:33:57 +0000919 if (Lex.getKind() != lltok::AttrGrpID)
920 return TokError("expected attribute group id");
921
Bill Wendling63b88192013-02-06 06:52:58 +0000922 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000923 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000924 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000925 Lex.Lex();
926
927 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000928 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000929 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000930 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000931 ParseToken(lltok::rbrace, "expected end of attribute group"))
932 return true;
933
Bill Wendlingb32b0412013-02-08 06:32:06 +0000934 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000935 return Error(AttrGrpLoc, "attribute group has no attributes");
936
937 return false;
938}
939
Bill Wendling8b0321d2013-02-08 00:52:31 +0000940/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000941/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000942bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
943 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000944 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000945 bool HaveError = false;
946
947 B.clear();
948
Bill Wendling63b88192013-02-06 06:52:58 +0000949 while (true) {
950 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000951 if (Token == lltok::kw_builtin)
952 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +0000953 switch (Token) {
954 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000955 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +0000956 return Error(Lex.getLoc(), "unterminated attribute group");
957 case lltok::rbrace:
958 // Finished.
959 return false;
960
Bill Wendlingb32b0412013-02-08 06:32:06 +0000961 case lltok::AttrGrpID: {
962 // Allow a function to reference an attribute group:
963 //
964 // define void @foo() #1 { ... }
965 if (inAttrGrp)
966 HaveError |=
967 Error(Lex.getLoc(),
968 "cannot have an attribute group reference in an attribute group");
969
970 unsigned AttrGrpNum = Lex.getUIntVal();
971 if (inAttrGrp) break;
972
973 // Save the reference to the attribute group. We'll fill it in later.
974 FwdRefAttrGrps.push_back(AttrGrpNum);
975 break;
976 }
Bill Wendling63b88192013-02-06 06:52:58 +0000977 // Target-dependent attributes:
978 case lltok::StringConstant: {
Artur Pilipenko17376c42015-08-03 14:31:49 +0000979 if (ParseStringAttribute(B))
Bill Wendling63b88192013-02-06 06:52:58 +0000980 return true;
Bill Wendlingb1ea9802013-02-10 10:12:50 +0000981 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000982 }
983
984 // Target-independent attributes:
985 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +0000986 // As a hack, we allow function alignment to be initially parsed as an
987 // attribute on a function declaration/definition or added to an attribute
988 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +0000989 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000990 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000991 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000992 if (ParseToken(lltok::equal, "expected '=' here") ||
993 ParseUInt32(Alignment))
994 return true;
995 } else {
996 if (ParseOptionalAlignment(Alignment))
997 return true;
998 }
Bill Wendling63b88192013-02-06 06:52:58 +0000999 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001000 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001001 }
1002 case lltok::kw_alignstack: {
1003 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001004 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001005 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001006 if (ParseToken(lltok::equal, "expected '=' here") ||
1007 ParseUInt32(Alignment))
1008 return true;
1009 } else {
1010 if (ParseOptionalStackAlignment(Alignment))
1011 return true;
1012 }
Bill Wendling63b88192013-02-06 06:52:58 +00001013 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001014 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001015 }
George Burgess IV278199f2016-04-12 01:05:35 +00001016 case lltok::kw_allocsize: {
1017 unsigned ElemSizeArg;
1018 Optional<unsigned> NumElemsArg;
1019 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1020 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1021 return true;
1022 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1023 continue;
1024 }
Igor Laevsky39d662f2015-07-11 10:30:36 +00001025 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1026 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1027 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1028 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1029 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001030 case lltok::kw_inaccessiblememonly:
1031 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1032 case lltok::kw_inaccessiblemem_or_argmemonly:
1033 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001034 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1035 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1036 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1037 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1038 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1039 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1040 case lltok::kw_noimplicitfloat:
1041 B.addAttribute(Attribute::NoImplicitFloat); break;
1042 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1043 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1044 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1045 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
James Molloye6f87ca2015-11-06 10:32:53 +00001046 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001047 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1048 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1049 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1050 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1051 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1052 case lltok::kw_returns_twice:
1053 B.addAttribute(Attribute::ReturnsTwice); break;
1054 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1055 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1056 case lltok::kw_sspstrong:
1057 B.addAttribute(Attribute::StackProtectStrong); break;
1058 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1059 case lltok::kw_sanitize_address:
1060 B.addAttribute(Attribute::SanitizeAddress); break;
1061 case lltok::kw_sanitize_thread:
1062 B.addAttribute(Attribute::SanitizeThread); break;
1063 case lltok::kw_sanitize_memory:
1064 B.addAttribute(Attribute::SanitizeMemory); break;
1065 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001066
1067 // Error handling.
1068 case lltok::kw_inreg:
1069 case lltok::kw_signext:
1070 case lltok::kw_zeroext:
1071 HaveError |=
1072 Error(Lex.getLoc(),
1073 "invalid use of attribute on a function");
1074 break;
1075 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001076 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001077 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001078 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001079 case lltok::kw_nest:
1080 case lltok::kw_noalias:
1081 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001082 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001083 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001084 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001085 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001086 case lltok::kw_swiftself:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001087 HaveError |=
1088 Error(Lex.getLoc(),
1089 "invalid use of parameter-only attribute on a function");
1090 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001091 }
1092
1093 Lex.Lex();
1094 }
1095}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001096
1097//===----------------------------------------------------------------------===//
1098// GlobalValue Reference/Resolution Routines.
1099//===----------------------------------------------------------------------===//
1100
Karl Schimpf77729782015-09-03 18:06:44 +00001101static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1102 const std::string &Name) {
1103 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1104 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1105 else
1106 return new GlobalVariable(*M, PTy->getElementType(), false,
1107 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1108 nullptr, GlobalVariable::NotThreadLocal,
1109 PTy->getAddressSpace());
1110}
1111
Chris Lattnerac161bf2009-01-02 07:01:27 +00001112/// GetGlobalVal - Get a value with the specified name or ID, creating a
1113/// forward reference record if needed. This can return null if the value
1114/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001115GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001116 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001117 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001118 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001119 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001120 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001121 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001122
Chris Lattnerac161bf2009-01-02 07:01:27 +00001123 // Look this name up in the normal function symbol table.
1124 GlobalValue *Val =
1125 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001126
Chris Lattnerac161bf2009-01-02 07:01:27 +00001127 // If this is a forward reference for the value, see if we already created a
1128 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001129 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001130 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001131 if (I != ForwardRefVals.end())
1132 Val = I->second.first;
1133 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001134
Chris Lattnerac161bf2009-01-02 07:01:27 +00001135 // If we have the value in the symbol table or fwd-ref table, return it.
1136 if (Val) {
1137 if (Val->getType() == Ty) return Val;
1138 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001139 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001140 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001141 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001142
Chris Lattnerac161bf2009-01-02 07:01:27 +00001143 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001144 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001145 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1146 return FwdVal;
1147}
1148
Chris Lattner229907c2011-07-18 04:54:35 +00001149GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1150 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001151 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001152 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001153 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001154 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001155
Craig Topper2617dcc2014-04-15 06:32:26 +00001156 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001157
Chris Lattnerac161bf2009-01-02 07:01:27 +00001158 // If this is a forward reference for the value, see if we already created a
1159 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001160 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001161 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001162 if (I != ForwardRefValIDs.end())
1163 Val = I->second.first;
1164 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001165
Chris Lattnerac161bf2009-01-02 07:01:27 +00001166 // If we have the value in the symbol table or fwd-ref table, return it.
1167 if (Val) {
1168 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001169 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001170 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001171 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001172 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001173
Chris Lattnerac161bf2009-01-02 07:01:27 +00001174 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001175 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001176 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1177 return FwdVal;
1178}
1179
1180
1181//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001182// Comdat Reference/Resolution Routines.
1183//===----------------------------------------------------------------------===//
1184
1185Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1186 // Look this name up in the comdat symbol table.
1187 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1188 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1189 if (I != ComdatSymTab.end())
1190 return &I->second;
1191
1192 // Otherwise, create a new forward reference for this value and remember it.
1193 Comdat *C = M->getOrInsertComdat(Name);
1194 ForwardRefComdats[Name] = Loc;
1195 return C;
1196}
1197
1198
1199//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001200// Helper Routines.
1201//===----------------------------------------------------------------------===//
1202
1203/// ParseToken - If the current token has the specified kind, eat it and return
1204/// success. Otherwise, emit the specified error and return failure.
1205bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1206 if (Lex.getKind() != T)
1207 return TokError(ErrMsg);
1208 Lex.Lex();
1209 return false;
1210}
1211
Chris Lattner3822f632009-01-02 08:05:26 +00001212/// ParseStringConstant
1213/// ::= StringConstant
1214bool LLParser::ParseStringConstant(std::string &Result) {
1215 if (Lex.getKind() != lltok::StringConstant)
1216 return TokError("expected string constant");
1217 Result = Lex.getStrVal();
1218 Lex.Lex();
1219 return false;
1220}
1221
1222/// ParseUInt32
1223/// ::= uint32
1224bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001225 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1226 return TokError("expected integer");
1227 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1228 if (Val64 != unsigned(Val64))
1229 return TokError("expected 32-bit integer (too large)");
1230 Val = Val64;
1231 Lex.Lex();
1232 return false;
1233}
1234
Hal Finkelb0407ba2014-07-18 15:51:28 +00001235/// ParseUInt64
1236/// ::= uint64
1237bool LLParser::ParseUInt64(uint64_t &Val) {
1238 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1239 return TokError("expected integer");
1240 Val = Lex.getAPSIntVal().getLimitedValue();
1241 Lex.Lex();
1242 return false;
1243}
1244
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001245/// ParseTLSModel
1246/// := 'localdynamic'
1247/// := 'initialexec'
1248/// := 'localexec'
1249bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1250 switch (Lex.getKind()) {
1251 default:
1252 return TokError("expected localdynamic, initialexec or localexec");
1253 case lltok::kw_localdynamic:
1254 TLM = GlobalVariable::LocalDynamicTLSModel;
1255 break;
1256 case lltok::kw_initialexec:
1257 TLM = GlobalVariable::InitialExecTLSModel;
1258 break;
1259 case lltok::kw_localexec:
1260 TLM = GlobalVariable::LocalExecTLSModel;
1261 break;
1262 }
1263
1264 Lex.Lex();
1265 return false;
1266}
1267
1268/// ParseOptionalThreadLocal
1269/// := /*empty*/
1270/// := 'thread_local'
1271/// := 'thread_local' '(' tlsmodel ')'
1272bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1273 TLM = GlobalVariable::NotThreadLocal;
1274 if (!EatIfPresent(lltok::kw_thread_local))
1275 return false;
1276
1277 TLM = GlobalVariable::GeneralDynamicTLSModel;
1278 if (Lex.getKind() == lltok::lparen) {
1279 Lex.Lex();
1280 return ParseTLSModel(TLM) ||
1281 ParseToken(lltok::rparen, "expected ')' after thread local model");
1282 }
1283 return false;
1284}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001285
1286/// ParseOptionalAddrSpace
1287/// := /*empty*/
1288/// := 'addrspace' '(' uint32 ')'
1289bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1290 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001291 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001292 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001293 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001294 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001295 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001296}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001297
Artur Pilipenko17376c42015-08-03 14:31:49 +00001298/// ParseStringAttribute
1299/// := StringConstant
1300/// := StringConstant '=' StringConstant
1301bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1302 std::string Attr = Lex.getStrVal();
1303 Lex.Lex();
1304 std::string Val;
1305 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1306 return true;
1307 B.addAttribute(Attr, Val);
1308 return false;
1309}
1310
Bill Wendling34c2eb22012-12-04 23:40:58 +00001311/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1312bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1313 bool HaveError = false;
1314
1315 B.clear();
1316
1317 while (1) {
1318 lltok::Kind Token = Lex.getKind();
1319 switch (Token) {
1320 default: // End of attributes.
1321 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001322 case lltok::StringConstant: {
1323 if (ParseStringAttribute(B))
1324 return true;
1325 continue;
1326 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001327 case lltok::kw_align: {
1328 unsigned Alignment;
1329 if (ParseOptionalAlignment(Alignment))
1330 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001331 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001332 continue;
1333 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001334 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001335 case lltok::kw_dereferenceable: {
1336 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001337 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001338 return true;
1339 B.addDereferenceableAttr(Bytes);
1340 continue;
1341 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001342 case lltok::kw_dereferenceable_or_null: {
1343 uint64_t Bytes;
1344 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1345 return true;
1346 B.addDereferenceableOrNullAttr(Bytes);
1347 continue;
1348 }
Reid Klecknera534a382013-12-19 02:14:12 +00001349 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001350 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1351 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1352 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1353 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001354 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001355 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1356 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001357 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001358 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1359 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001360 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
Manman Renf46262e2016-03-29 17:37:21 +00001361 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001362 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001363
Stephen Lin7577ed52013-04-20 13:16:13 +00001364 case lltok::kw_alignstack:
1365 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001366 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001367 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001368 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001369 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001370 case lltok::kw_minsize:
1371 case lltok::kw_naked:
1372 case lltok::kw_nobuiltin:
1373 case lltok::kw_noduplicate:
1374 case lltok::kw_noimplicitfloat:
1375 case lltok::kw_noinline:
1376 case lltok::kw_nonlazybind:
1377 case lltok::kw_noredzone:
1378 case lltok::kw_noreturn:
1379 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001380 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001381 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001382 case lltok::kw_returns_twice:
1383 case lltok::kw_sanitize_address:
1384 case lltok::kw_sanitize_memory:
1385 case lltok::kw_sanitize_thread:
1386 case lltok::kw_ssp:
1387 case lltok::kw_sspreq:
1388 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001389 case lltok::kw_safestack:
Stephen Lin7577ed52013-04-20 13:16:13 +00001390 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001391 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1392 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001393 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001394
Bill Wendling34c2eb22012-12-04 23:40:58 +00001395 Lex.Lex();
1396 }
1397}
1398
1399/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1400bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1401 bool HaveError = false;
1402
1403 B.clear();
1404
1405 while (1) {
1406 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001407 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001408 default: // End of attributes.
1409 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001410 case lltok::StringConstant: {
1411 if (ParseStringAttribute(B))
1412 return true;
1413 continue;
1414 }
Hal Finkelb0407ba2014-07-18 15:51:28 +00001415 case lltok::kw_dereferenceable: {
1416 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001417 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001418 return true;
1419 B.addDereferenceableAttr(Bytes);
1420 continue;
1421 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001422 case lltok::kw_dereferenceable_or_null: {
1423 uint64_t Bytes;
1424 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1425 return true;
1426 B.addDereferenceableOrNullAttr(Bytes);
1427 continue;
1428 }
Artur Pilipenko84bc62f2015-09-18 12:33:31 +00001429 case lltok::kw_align: {
1430 unsigned Alignment;
1431 if (ParseOptionalAlignment(Alignment))
1432 return true;
1433 B.addAlignmentAttr(Alignment);
1434 continue;
1435 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001436 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1437 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001438 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001439 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1440 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001441
Bill Wendling34c2eb22012-12-04 23:40:58 +00001442 // Error handling.
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001443 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001444 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001445 case lltok::kw_nest:
1446 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001447 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001448 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001449 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001450 case lltok::kw_swiftself:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001451 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001452 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001453
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001454 case lltok::kw_alignstack:
1455 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001456 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001457 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001458 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001459 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001460 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001461 case lltok::kw_minsize:
1462 case lltok::kw_naked:
1463 case lltok::kw_nobuiltin:
1464 case lltok::kw_noduplicate:
1465 case lltok::kw_noimplicitfloat:
1466 case lltok::kw_noinline:
1467 case lltok::kw_nonlazybind:
1468 case lltok::kw_noredzone:
1469 case lltok::kw_noreturn:
1470 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001471 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001472 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001473 case lltok::kw_returns_twice:
1474 case lltok::kw_sanitize_address:
1475 case lltok::kw_sanitize_memory:
1476 case lltok::kw_sanitize_thread:
1477 case lltok::kw_ssp:
1478 case lltok::kw_sspreq:
1479 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001480 case lltok::kw_safestack:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001481 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001482 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001483 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001484
1485 case lltok::kw_readnone:
1486 case lltok::kw_readonly:
1487 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001488 }
1489
Chris Lattnerac161bf2009-01-02 07:01:27 +00001490 Lex.Lex();
1491 }
1492}
1493
Rafael Espindolac6269912016-05-10 17:16:45 +00001494static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1495 HasLinkage = true;
1496 switch (Kind) {
1497 default:
1498 HasLinkage = false;
1499 return GlobalValue::ExternalLinkage;
1500 case lltok::kw_private:
1501 return GlobalValue::PrivateLinkage;
1502 case lltok::kw_internal:
1503 return GlobalValue::InternalLinkage;
1504 case lltok::kw_weak:
1505 return GlobalValue::WeakAnyLinkage;
1506 case lltok::kw_weak_odr:
1507 return GlobalValue::WeakODRLinkage;
1508 case lltok::kw_linkonce:
1509 return GlobalValue::LinkOnceAnyLinkage;
1510 case lltok::kw_linkonce_odr:
1511 return GlobalValue::LinkOnceODRLinkage;
1512 case lltok::kw_available_externally:
1513 return GlobalValue::AvailableExternallyLinkage;
1514 case lltok::kw_appending:
1515 return GlobalValue::AppendingLinkage;
1516 case lltok::kw_common:
1517 return GlobalValue::CommonLinkage;
1518 case lltok::kw_extern_weak:
1519 return GlobalValue::ExternalWeakLinkage;
1520 case lltok::kw_external:
1521 return GlobalValue::ExternalLinkage;
1522 }
1523}
1524
Chris Lattnerac161bf2009-01-02 07:01:27 +00001525/// ParseOptionalLinkage
1526/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001527/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001528/// ::= 'internal'
1529/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001530/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001531/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001532/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001533/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001534/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001535/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001536/// ::= 'extern_weak'
1537/// ::= 'external'
1538bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
Rafael Espindolac6269912016-05-10 17:16:45 +00001539 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1540 if (HasLinkage)
1541 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001542 return false;
1543}
1544
1545/// ParseOptionalVisibility
1546/// ::= /*empty*/
1547/// ::= 'default'
1548/// ::= 'hidden'
1549/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001550///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001551bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1552 switch (Lex.getKind()) {
1553 default: Res = GlobalValue::DefaultVisibility; return false;
1554 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1555 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1556 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1557 }
1558 Lex.Lex();
1559 return false;
1560}
1561
Nico Rieck7157bb72014-01-14 15:22:47 +00001562/// ParseOptionalDLLStorageClass
1563/// ::= /*empty*/
1564/// ::= 'dllimport'
1565/// ::= 'dllexport'
1566///
1567bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1568 switch (Lex.getKind()) {
1569 default: Res = GlobalValue::DefaultStorageClass; return false;
1570 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1571 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1572 }
1573 Lex.Lex();
1574 return false;
1575}
1576
Chris Lattnerac161bf2009-01-02 07:01:27 +00001577/// ParseOptionalCallingConv
1578/// ::= /*empty*/
1579/// ::= 'ccc'
1580/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001581/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001582/// ::= 'coldcc'
1583/// ::= 'x86_stdcallcc'
1584/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001585/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001586/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001587/// ::= 'arm_apcscc'
1588/// ::= 'arm_aapcscc'
1589/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001590/// ::= 'msp430_intrcc'
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001591/// ::= 'avr_intrcc'
1592/// ::= 'avr_signalcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001593/// ::= 'ptx_kernel'
1594/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001595/// ::= 'spir_func'
1596/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001597/// ::= 'x86_64_sysvcc'
1598/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001599/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001600/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001601/// ::= 'preserve_mostcc'
1602/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001603/// ::= 'ghccc'
Manman Renf8bdd882016-04-05 22:41:47 +00001604/// ::= 'swiftcc'
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001605/// ::= 'x86_intrcc'
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001606/// ::= 'hhvmcc'
1607/// ::= 'hhvm_ccc'
Manman Ren19c7bbe2015-12-04 17:40:13 +00001608/// ::= 'cxx_fast_tlscc'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001609/// ::= 'amdgpu_vs'
1610/// ::= 'amdgpu_tcs'
1611/// ::= 'amdgpu_tes'
1612/// ::= 'amdgpu_gs'
1613/// ::= 'amdgpu_ps'
1614/// ::= 'amdgpu_cs'
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001615/// ::= 'amdgpu_kernel'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001616/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001617///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001618bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001619 switch (Lex.getKind()) {
1620 default: CC = CallingConv::C; return false;
1621 case lltok::kw_ccc: CC = CallingConv::C; break;
1622 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1623 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1624 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1625 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001626 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001627 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001628 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1629 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1630 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001631 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001632 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1633 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001634 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1635 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001636 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1637 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001638 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001639 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1640 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001641 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001642 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001643 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1644 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001645 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Manman Renf8bdd882016-04-05 22:41:47 +00001646 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001647 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001648 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1649 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
Manman Ren19c7bbe2015-12-04 17:40:13 +00001650 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001651 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
1652 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1653 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1654 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001655 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001656 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001657 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001658 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001659 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001660 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001661
Chris Lattnerac161bf2009-01-02 07:01:27 +00001662 Lex.Lex();
1663 return false;
1664}
1665
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001666/// ParseMetadataAttachment
1667/// ::= !dbg !42
1668bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1669 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1670
1671 std::string Name = Lex.getStrVal();
1672 Kind = M->getMDKindID(Name);
1673 Lex.Lex();
1674
1675 return ParseMDNode(MD);
1676}
1677
Chris Lattner5c427632009-12-30 05:31:19 +00001678/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001679/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001680bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001681 do {
1682 if (Lex.getKind() != lltok::MetadataVar)
1683 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001684
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001685 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001686 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001687 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001688 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001689
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001690 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001691 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001692 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001693
Chris Lattner596760d2009-12-29 21:25:40 +00001694 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001695 } while (EatIfPresent(lltok::comma));
1696 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001697}
1698
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001699/// ParseOptionalFunctionMetadata
1700/// ::= (!dbg !57)*
1701bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
1702 while (Lex.getKind() == lltok::MetadataVar) {
1703 unsigned MDK;
1704 MDNode *N;
1705 if (ParseMetadataAttachment(MDK, N))
1706 return true;
1707
1708 F.setMetadata(MDK, N);
1709 }
1710 return false;
1711}
1712
Chris Lattnerac161bf2009-01-02 07:01:27 +00001713/// ParseOptionalAlignment
1714/// ::= /* empty */
1715/// ::= 'align' 4
1716bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1717 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001718 if (!EatIfPresent(lltok::kw_align))
1719 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001720 LocTy AlignLoc = Lex.getLoc();
1721 if (ParseUInt32(Alignment)) return true;
1722 if (!isPowerOf2_32(Alignment))
1723 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001724 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001725 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001726 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001727}
1728
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001729/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00001730/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001731/// ::= AttrKind '(' 4 ')'
1732///
1733/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1734bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1735 uint64_t &Bytes) {
1736 assert((AttrKind == lltok::kw_dereferenceable ||
1737 AttrKind == lltok::kw_dereferenceable_or_null) &&
1738 "contract!");
1739
Hal Finkelb0407ba2014-07-18 15:51:28 +00001740 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001741 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001742 return false;
1743 LocTy ParenLoc = Lex.getLoc();
1744 if (!EatIfPresent(lltok::lparen))
1745 return Error(ParenLoc, "expected '('");
1746 LocTy DerefLoc = Lex.getLoc();
1747 if (ParseUInt64(Bytes)) return true;
1748 ParenLoc = Lex.getLoc();
1749 if (!EatIfPresent(lltok::rparen))
1750 return Error(ParenLoc, "expected ')'");
1751 if (!Bytes)
1752 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1753 return false;
1754}
1755
Chris Lattnerb2f39502009-12-30 05:44:30 +00001756/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001757/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001758/// ::= ',' align 4
1759///
1760/// This returns with AteExtraComma set to true if it ate an excess comma at the
1761/// end.
1762bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1763 bool &AteExtraComma) {
1764 AteExtraComma = false;
1765 while (EatIfPresent(lltok::comma)) {
1766 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001767 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001768 AteExtraComma = true;
1769 return false;
1770 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001771
Chris Lattner95b0ff42010-04-23 00:50:50 +00001772 if (Lex.getKind() != lltok::kw_align)
1773 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001774
Chris Lattner95b0ff42010-04-23 00:50:50 +00001775 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001776 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001777
Devang Patelea8a4b92009-09-17 23:04:48 +00001778 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001779}
1780
George Burgess IV278199f2016-04-12 01:05:35 +00001781bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
1782 Optional<unsigned> &HowManyArg) {
1783 Lex.Lex();
1784
1785 auto StartParen = Lex.getLoc();
1786 if (!EatIfPresent(lltok::lparen))
1787 return Error(StartParen, "expected '('");
1788
1789 if (ParseUInt32(BaseSizeArg))
1790 return true;
1791
1792 if (EatIfPresent(lltok::comma)) {
1793 auto HowManyAt = Lex.getLoc();
1794 unsigned HowMany;
1795 if (ParseUInt32(HowMany))
1796 return true;
1797 if (HowMany == BaseSizeArg)
1798 return Error(HowManyAt,
1799 "'allocsize' indices can't refer to the same parameter");
1800 HowManyArg = HowMany;
1801 } else
1802 HowManyArg = None;
1803
1804 auto EndParen = Lex.getLoc();
1805 if (!EatIfPresent(lltok::rparen))
1806 return Error(EndParen, "expected ')'");
1807 return false;
1808}
1809
Eli Friedmanfee02c62011-07-25 23:16:38 +00001810/// ParseScopeAndOrdering
1811/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1812/// else: ::=
1813///
1814/// This sets Scope and Ordering to the parsed values.
1815bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1816 AtomicOrdering &Ordering) {
1817 if (!isAtomic)
1818 return false;
1819
1820 Scope = CrossThread;
1821 if (EatIfPresent(lltok::kw_singlethread))
1822 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001823
1824 return ParseOrdering(Ordering);
1825}
1826
1827/// ParseOrdering
1828/// ::= AtomicOrdering
1829///
1830/// This sets Ordering to the parsed value.
1831bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001832 switch (Lex.getKind()) {
1833 default: return TokError("Expected ordering on atomic instruction");
JF Bastien800f87a2016-04-06 21:19:33 +00001834 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
1835 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
1836 // Not specified yet:
1837 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
1838 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
1839 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
1840 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
1841 case lltok::kw_seq_cst:
1842 Ordering = AtomicOrdering::SequentiallyConsistent;
1843 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00001844 }
1845 Lex.Lex();
1846 return false;
1847}
1848
Charles Davisbe5557e2010-02-12 00:31:15 +00001849/// ParseOptionalStackAlignment
1850/// ::= /* empty */
1851/// ::= 'alignstack' '(' 4 ')'
1852bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1853 Alignment = 0;
1854 if (!EatIfPresent(lltok::kw_alignstack))
1855 return false;
1856 LocTy ParenLoc = Lex.getLoc();
1857 if (!EatIfPresent(lltok::lparen))
1858 return Error(ParenLoc, "expected '('");
1859 LocTy AlignLoc = Lex.getLoc();
1860 if (ParseUInt32(Alignment)) return true;
1861 ParenLoc = Lex.getLoc();
1862 if (!EatIfPresent(lltok::rparen))
1863 return Error(ParenLoc, "expected ')'");
1864 if (!isPowerOf2_32(Alignment))
1865 return Error(AlignLoc, "stack alignment is not a power of two");
1866 return false;
1867}
Devang Patelea8a4b92009-09-17 23:04:48 +00001868
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001869/// ParseIndexList - This parses the index list for an insert/extractvalue
1870/// instruction. This sets AteExtraComma in the case where we eat an extra
1871/// comma at the end of the line and find that it is followed by metadata.
1872/// Clients that don't allow metadata can call the version of this function that
1873/// only takes one argument.
1874///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001875/// ParseIndexList
1876/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001877///
1878bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1879 bool &AteExtraComma) {
1880 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001881
Chris Lattnerac161bf2009-01-02 07:01:27 +00001882 if (Lex.getKind() != lltok::comma)
1883 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001884
Chris Lattner3822f632009-01-02 08:05:26 +00001885 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001886 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00001887 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001888 AteExtraComma = true;
1889 return false;
1890 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001891 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001892 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001893 Indices.push_back(Idx);
1894 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001895
Chris Lattnerac161bf2009-01-02 07:01:27 +00001896 return false;
1897}
1898
1899//===----------------------------------------------------------------------===//
1900// Type Parsing.
1901//===----------------------------------------------------------------------===//
1902
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001903/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001904bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001905 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001906 switch (Lex.getKind()) {
1907 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001908 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001909 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001910 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001911 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001912 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001913 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001914 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001915 // Type ::= StructType
1916 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001917 return true;
1918 break;
1919 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001920 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001921 Lex.Lex(); // eat the lsquare.
1922 if (ParseArrayVectorType(Result, false))
1923 return true;
1924 break;
1925 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001926 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00001927 Lex.Lex();
1928 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001929 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00001930 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001931 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001932 } else if (ParseArrayVectorType(Result, true))
1933 return true;
1934 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001935 case lltok::LocalVar: {
1936 // Type ::= %foo
1937 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001938
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001939 // If the type hasn't been defined yet, create a forward definition and
1940 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001941 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001942 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001943 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001944 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001945 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001946 Lex.Lex();
1947 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001948 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001949
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001950 case lltok::LocalVarID: {
1951 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001952 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001953
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001954 // If the type hasn't been defined yet, create a forward definition and
1955 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001956 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001957 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001958 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001959 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001960 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001961 Lex.Lex();
1962 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001963 }
1964 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001965
1966 // Parse the type suffixes.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001967 while (1) {
1968 switch (Lex.getKind()) {
1969 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001970 default:
1971 if (!AllowVoid && Result->isVoidTy())
1972 return Error(TypeLoc, "void type only allowed for function results");
1973 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001974
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001975 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001976 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001977 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001978 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001979 if (Result->isVoidTy())
1980 return TokError("pointers to void are invalid - use i8* instead");
1981 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001982 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001983 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001984 Lex.Lex();
1985 break;
1986
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001987 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001988 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001989 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001990 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001991 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00001992 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001993 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001994 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001995 unsigned AddrSpace;
1996 if (ParseOptionalAddrSpace(AddrSpace) ||
1997 ParseToken(lltok::star, "expected '*' in address space"))
1998 return true;
1999
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002000 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002001 break;
2002 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002003
Chris Lattnerac161bf2009-01-02 07:01:27 +00002004 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2005 case lltok::lparen:
2006 if (ParseFunctionType(Result))
2007 return true;
2008 break;
2009 }
2010 }
2011}
2012
2013/// ParseParameterList
2014/// ::= '(' ')'
2015/// ::= '(' Arg (',' Arg)* ')'
2016/// Arg
2017/// ::= Type OptionalAttributes Value OptionalAttributes
2018bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00002019 PerFunctionState &PFS, bool IsMustTailCall,
2020 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002021 if (ParseToken(lltok::lparen, "expected '(' in call"))
2022 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002023
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002024 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002025 while (Lex.getKind() != lltok::rparen) {
2026 // If this isn't the first argument, we need a comma.
2027 if (!ArgList.empty() &&
2028 ParseToken(lltok::comma, "expected ',' in argument list"))
2029 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002030
Reid Kleckner83498642014-08-26 00:33:28 +00002031 // Parse an ellipsis if this is a musttail call in a variadic function.
2032 if (Lex.getKind() == lltok::dotdotdot) {
2033 const char *Msg = "unexpected ellipsis in argument list for ";
2034 if (!IsMustTailCall)
2035 return TokError(Twine(Msg) + "non-musttail call");
2036 if (!InVarArgsFunc)
2037 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2038 Lex.Lex(); // Lex the '...', it is purely for readability.
2039 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2040 }
2041
Chris Lattnerac161bf2009-01-02 07:01:27 +00002042 // Parse the argument.
2043 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00002044 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002045 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002046 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00002047 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002048 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00002049
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002050 if (ArgTy->isMetadataTy()) {
2051 if (ParseMetadataAsValue(V, PFS))
2052 return true;
2053 } else {
2054 // Otherwise, handle normal operands.
2055 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2056 return true;
2057 }
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002058 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
2059 AttrIndex++,
2060 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002061 }
2062
Reid Kleckner83498642014-08-26 00:33:28 +00002063 if (IsMustTailCall && InVarArgsFunc)
2064 return TokError("expected '...' at end of argument list for musttail call "
2065 "in varargs function");
2066
Chris Lattnerac161bf2009-01-02 07:01:27 +00002067 Lex.Lex(); // Lex the ')'.
2068 return false;
2069}
2070
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002071/// ParseOptionalOperandBundles
2072/// ::= /*empty*/
2073/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2074///
2075/// OperandBundle
2076/// ::= bundle-tag '(' ')'
2077/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2078///
2079/// bundle-tag ::= String Constant
2080bool LLParser::ParseOptionalOperandBundles(
2081 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2082 LocTy BeginLoc = Lex.getLoc();
2083 if (!EatIfPresent(lltok::lsquare))
2084 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002085
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002086 while (Lex.getKind() != lltok::rsquare) {
2087 // If this isn't the first operand bundle, we need a comma.
2088 if (!BundleList.empty() &&
2089 ParseToken(lltok::comma, "expected ',' in input list"))
2090 return true;
2091
2092 std::string Tag;
2093 if (ParseStringConstant(Tag))
2094 return true;
2095
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002096 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2097 return true;
2098
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002099 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002100 while (Lex.getKind() != lltok::rparen) {
2101 // If this isn't the first input, we need a comma.
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002102 if (!Inputs.empty() &&
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002103 ParseToken(lltok::comma, "expected ',' in input list"))
2104 return true;
2105
2106 Type *Ty = nullptr;
2107 Value *Input = nullptr;
2108 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2109 return true;
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002110 Inputs.push_back(Input);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002111 }
2112
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002113 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2114
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002115 Lex.Lex(); // Lex the ')'.
2116 }
2117
2118 if (BundleList.empty())
2119 return Error(BeginLoc, "operand bundle set must not be empty");
2120
2121 Lex.Lex(); // Lex the ']'.
2122 return false;
2123}
Chris Lattnerac161bf2009-01-02 07:01:27 +00002124
Chris Lattner2ed06b42009-01-05 18:34:07 +00002125/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002126/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00002127/// ::= '(' ArgTypeListI ')'
2128/// ArgTypeListI
2129/// ::= /*empty*/
2130/// ::= '...'
2131/// ::= ArgTypeList ',' '...'
2132/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00002133///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002134bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2135 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00002136 isVarArg = false;
2137 assert(Lex.getKind() == lltok::lparen);
2138 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002139
Chris Lattnerac161bf2009-01-02 07:01:27 +00002140 if (Lex.getKind() == lltok::rparen) {
2141 // empty
2142 } else if (Lex.getKind() == lltok::dotdotdot) {
2143 isVarArg = true;
2144 Lex.Lex();
2145 } else {
2146 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002147 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002148 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002149 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002150
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002151 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002152 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002153
Chris Lattnerfdd87902009-10-05 05:54:46 +00002154 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002155 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002156
Chris Lattnerdef19492011-06-17 06:36:20 +00002157 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002158 Name = Lex.getStrVal();
2159 Lex.Lex();
2160 }
Chris Lattner3822f632009-01-02 08:05:26 +00002161
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002162 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00002163 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002164
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002165 unsigned AttrIndex = 1;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002166 ArgList.emplace_back(TypeLoc, ArgTy, AttributeSet::get(ArgTy->getContext(),
2167 AttrIndex++, Attrs),
2168 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002169
Chris Lattner3822f632009-01-02 08:05:26 +00002170 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002171 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00002172 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002173 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002174 break;
2175 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002176
Chris Lattnerac161bf2009-01-02 07:01:27 +00002177 // Otherwise must be an argument type.
2178 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00002179 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00002180
Chris Lattnerfdd87902009-10-05 05:54:46 +00002181 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002182 return Error(TypeLoc, "argument can not have void type");
2183
Chris Lattnerdef19492011-06-17 06:36:20 +00002184 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002185 Name = Lex.getStrVal();
2186 Lex.Lex();
2187 } else {
2188 Name = "";
2189 }
Chris Lattner3822f632009-01-02 08:05:26 +00002190
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002191 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00002192 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002193
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002194 ArgList.emplace_back(
2195 TypeLoc, ArgTy,
2196 AttributeSet::get(ArgTy->getContext(), AttrIndex++, Attrs),
2197 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002198 }
2199 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002200
Chris Lattner3822f632009-01-02 08:05:26 +00002201 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002202}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002203
Chris Lattnerac161bf2009-01-02 07:01:27 +00002204/// ParseFunctionType
2205/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002206bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002207 assert(Lex.getKind() == lltok::lparen);
2208
Chris Lattnerce473c72009-01-05 08:04:33 +00002209 if (!FunctionType::isValidReturnType(Result))
2210 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002211
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002212 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002213 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002214 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002215 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002216
Chris Lattnerac161bf2009-01-02 07:01:27 +00002217 // Reject names on the arguments lists.
2218 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2219 if (!ArgList[i].Name.empty())
2220 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002221 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00002222 return Error(ArgList[i].Loc,
2223 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002224 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002225
Jay Foadb804a2b2011-07-12 14:06:48 +00002226 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002227 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002228 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002229
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002230 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002231 return false;
2232}
2233
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002234/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2235/// other structs.
2236bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2237 SmallVector<Type*, 8> Elts;
2238 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002239
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002240 Result = StructType::get(Context, Elts, Packed);
2241 return false;
2242}
2243
2244/// ParseStructDefinition - Parse a struct in a 'type' definition.
2245bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2246 std::pair<Type*, LocTy> &Entry,
2247 Type *&ResultTy) {
2248 // If the type was already defined, diagnose the redefinition.
2249 if (Entry.first && !Entry.second.isValid())
2250 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002251
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002252 // If we have opaque, just return without filling in the definition for the
2253 // struct. This counts as a definition as far as the .ll file goes.
2254 if (EatIfPresent(lltok::kw_opaque)) {
2255 // This type is being defined, so clear the location to indicate this.
2256 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002257
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002258 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002259 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002260 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002261 ResultTy = Entry.first;
2262 return false;
2263 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002264
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002265 // If the type starts with '<', then it is either a packed struct or a vector.
2266 bool isPacked = EatIfPresent(lltok::less);
2267
2268 // If we don't have a struct, then we have a random type alias, which we
2269 // accept for compatibility with old files. These types are not allowed to be
2270 // forward referenced and not allowed to be recursive.
2271 if (Lex.getKind() != lltok::lbrace) {
2272 if (Entry.first)
2273 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002274
Craig Topper2617dcc2014-04-15 06:32:26 +00002275 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002276 if (isPacked)
2277 return ParseArrayVectorType(ResultTy, true);
2278 return ParseType(ResultTy);
2279 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002280
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002281 // This type is being defined, so clear the location to indicate this.
2282 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002283
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002284 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002285 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002286 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002287
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002288 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002289
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002290 SmallVector<Type*, 8> Body;
2291 if (ParseStructBody(Body) ||
2292 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2293 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002294
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002295 STy->setBody(Body, isPacked);
2296 ResultTy = STy;
2297 return false;
2298}
2299
2300
Chris Lattnerac161bf2009-01-02 07:01:27 +00002301/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002302/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002303/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002304/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002305/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002306/// ::= '<' '{' Type (',' Type)* '}' '>'
2307bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002308 assert(Lex.getKind() == lltok::lbrace);
2309 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002310
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002311 // Handle the empty struct.
2312 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002313 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002314
Chris Lattnerf880ca22009-03-09 04:49:14 +00002315 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002316 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002317 if (ParseType(Ty)) return true;
2318 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002319
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002320 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002321 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002322
Chris Lattner3822f632009-01-02 08:05:26 +00002323 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002324 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002325 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002326
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002327 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002328 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002329
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002330 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002331 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002332
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002333 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002334}
2335
2336/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2337/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002338/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002339/// ::= '[' APSINTVAL 'x' Types ']'
2340/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002341bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002342 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2343 Lex.getAPSIntVal().getBitWidth() > 64)
2344 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002345
Chris Lattnerac161bf2009-01-02 07:01:27 +00002346 LocTy SizeLoc = Lex.getLoc();
2347 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002348 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002349
Chris Lattner3822f632009-01-02 08:05:26 +00002350 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2351 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002352
2353 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002354 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002355 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002356
Chris Lattner3822f632009-01-02 08:05:26 +00002357 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2358 "expected end of sequential type"))
2359 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002360
Chris Lattnerac161bf2009-01-02 07:01:27 +00002361 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002362 if (Size == 0)
2363 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002364 if ((unsigned)Size != Size)
2365 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002366 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002367 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002368 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002369 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002370 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002371 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002372 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002373 }
2374 return false;
2375}
2376
2377//===----------------------------------------------------------------------===//
2378// Function Semantic Analysis.
2379//===----------------------------------------------------------------------===//
2380
Chris Lattner3432c622009-10-28 03:39:23 +00002381LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2382 int functionNumber)
2383 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002384
2385 // Insert unnamed arguments into the NumberedVals list.
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +00002386 for (Argument &A : F.args())
2387 if (!A.hasName())
2388 NumberedVals.push_back(&A);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002389}
2390
2391LLParser::PerFunctionState::~PerFunctionState() {
2392 // If there were any forward referenced non-basicblock values, delete them.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002393
David Blaikie9ebdc692015-09-21 21:07:50 +00002394 for (const auto &P : ForwardRefVals) {
2395 if (isa<BasicBlock>(P.second.first))
2396 continue;
2397 P.second.first->replaceAllUsesWith(
2398 UndefValue::get(P.second.first->getType()));
2399 delete P.second.first;
2400 }
2401
2402 for (const auto &P : ForwardRefValIDs) {
2403 if (isa<BasicBlock>(P.second.first))
2404 continue;
2405 P.second.first->replaceAllUsesWith(
2406 UndefValue::get(P.second.first->getType()));
2407 delete P.second.first;
2408 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002409}
2410
Chris Lattner3432c622009-10-28 03:39:23 +00002411bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002412 if (!ForwardRefVals.empty())
2413 return P.Error(ForwardRefVals.begin()->second.second,
2414 "use of undefined value '%" + ForwardRefVals.begin()->first +
2415 "'");
2416 if (!ForwardRefValIDs.empty())
2417 return P.Error(ForwardRefValIDs.begin()->second.second,
2418 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002419 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002420 return false;
2421}
2422
2423
2424/// GetVal - Get a value with the specified name or ID, creating a
2425/// forward reference record if needed. This can return null if the value
2426/// exists but does not have the right type.
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002427Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
David Majnemer8a1c45d2015-12-12 05:38:55 +00002428 LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002429 // Look this name up in the normal function symbol table.
2430 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002431
Chris Lattnerac161bf2009-01-02 07:01:27 +00002432 // If this is a forward reference for the value, see if we already created a
2433 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002434 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002435 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002436 if (I != ForwardRefVals.end())
2437 Val = I->second.first;
2438 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002439
Chris Lattnerac161bf2009-01-02 07:01:27 +00002440 // If we have the value in the symbol table or fwd-ref table, return it.
2441 if (Val) {
2442 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002443 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002444 P.Error(Loc, "'%" + Name + "' is not a basic block");
2445 else
2446 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002447 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002448 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002449 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002450
Chris Lattnerac161bf2009-01-02 07:01:27 +00002451 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002452 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002453 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002454 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002455 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002456
Chris Lattnerac161bf2009-01-02 07:01:27 +00002457 // Otherwise, create a new forward reference for this value and remember it.
2458 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002459 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002460 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002461 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002462 FwdVal = new Argument(Ty, Name);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002463 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002464
Chris Lattnerac161bf2009-01-02 07:01:27 +00002465 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2466 return FwdVal;
2467}
2468
David Majnemer8a1c45d2015-12-12 05:38:55 +00002469Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002470 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002471 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002472
Chris Lattnerac161bf2009-01-02 07:01:27 +00002473 // If this is a forward reference for the value, see if we already created a
2474 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002475 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002476 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002477 if (I != ForwardRefValIDs.end())
2478 Val = I->second.first;
2479 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002480
Chris Lattnerac161bf2009-01-02 07:01:27 +00002481 // If we have the value in the symbol table or fwd-ref table, return it.
2482 if (Val) {
2483 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002484 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002485 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002486 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002487 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002488 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002489 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002490 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002491
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002492 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002493 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002494 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002495 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002496
Chris Lattnerac161bf2009-01-02 07:01:27 +00002497 // Otherwise, create a new forward reference for this value and remember it.
2498 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002499 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002500 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002501 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002502 FwdVal = new Argument(Ty);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002503 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002504
Chris Lattnerac161bf2009-01-02 07:01:27 +00002505 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2506 return FwdVal;
2507}
2508
2509/// SetInstName - After an instruction is parsed and inserted into its
2510/// basic block, this installs its name.
2511bool LLParser::PerFunctionState::SetInstName(int NameID,
2512 const std::string &NameStr,
2513 LocTy NameLoc, Instruction *Inst) {
2514 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002515 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002516 if (NameID != -1 || !NameStr.empty())
2517 return P.Error(NameLoc, "instructions returning void cannot have a name");
2518 return false;
2519 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002520
Chris Lattnerac161bf2009-01-02 07:01:27 +00002521 // If this was a numbered instruction, verify that the instruction is the
2522 // expected value and resolve any forward references.
2523 if (NameStr.empty()) {
2524 // If neither a name nor an ID was specified, just use the next ID.
2525 if (NameID == -1)
2526 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002527
Chris Lattnerac161bf2009-01-02 07:01:27 +00002528 if (unsigned(NameID) != NumberedVals.size())
2529 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002530 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002531
David Blaikie9ebdc692015-09-21 21:07:50 +00002532 auto FI = ForwardRefValIDs.find(NameID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002533 if (FI != ForwardRefValIDs.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002534 Value *Sentinel = FI->second.first;
2535 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002536 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002537 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002538
2539 Sentinel->replaceAllUsesWith(Inst);
2540 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002541 ForwardRefValIDs.erase(FI);
2542 }
2543
2544 NumberedVals.push_back(Inst);
2545 return false;
2546 }
2547
2548 // Otherwise, the instruction had a name. Resolve forward refs and set it.
David Blaikie9ebdc692015-09-21 21:07:50 +00002549 auto FI = ForwardRefVals.find(NameStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002550 if (FI != ForwardRefVals.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002551 Value *Sentinel = FI->second.first;
2552 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002553 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002554 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002555
2556 Sentinel->replaceAllUsesWith(Inst);
2557 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002558 ForwardRefVals.erase(FI);
2559 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002560
Chris Lattnerac161bf2009-01-02 07:01:27 +00002561 // Set the name on the instruction.
2562 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002563
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002564 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002565 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002566 NameStr + "'");
2567 return false;
2568}
2569
2570/// GetBB - Get a basic block with the specified name or ID, creating a
2571/// forward reference record if needed.
2572BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2573 LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002574 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2575 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002576}
2577
2578BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002579 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2580 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002581}
2582
2583/// DefineBB - Define the specified basic block, which is either named or
2584/// unnamed. If there is an error, this returns null otherwise it returns
2585/// the block being defined.
2586BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2587 LocTy Loc) {
2588 BasicBlock *BB;
2589 if (Name.empty())
2590 BB = GetBB(NumberedVals.size(), Loc);
2591 else
2592 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002593 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002594
Chris Lattnerac161bf2009-01-02 07:01:27 +00002595 // Move the block to the end of the function. Forward ref'd blocks are
2596 // inserted wherever they happen to be referenced.
2597 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002598
Chris Lattnerac161bf2009-01-02 07:01:27 +00002599 // Remove the block from forward ref sets.
2600 if (Name.empty()) {
2601 ForwardRefValIDs.erase(NumberedVals.size());
2602 NumberedVals.push_back(BB);
2603 } else {
2604 // BB forward references are already in the function symbol table.
2605 ForwardRefVals.erase(Name);
2606 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002607
Chris Lattnerac161bf2009-01-02 07:01:27 +00002608 return BB;
2609}
2610
2611//===----------------------------------------------------------------------===//
2612// Constants.
2613//===----------------------------------------------------------------------===//
2614
2615/// ParseValID - Parse an abstract value that doesn't necessarily have a
2616/// type implied. For example, if we parse "4" we don't know what integer type
2617/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002618/// sanity. PFS is used to convert function-local operands of metadata (since
2619/// metadata operands are not just parsed here but also converted to values).
2620/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002621bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002622 ID.Loc = Lex.getLoc();
2623 switch (Lex.getKind()) {
2624 default: return TokError("expected value token");
2625 case lltok::GlobalID: // @42
2626 ID.UIntVal = Lex.getUIntVal();
2627 ID.Kind = ValID::t_GlobalID;
2628 break;
2629 case lltok::GlobalVar: // @foo
2630 ID.StrVal = Lex.getStrVal();
2631 ID.Kind = ValID::t_GlobalName;
2632 break;
2633 case lltok::LocalVarID: // %42
2634 ID.UIntVal = Lex.getUIntVal();
2635 ID.Kind = ValID::t_LocalID;
2636 break;
2637 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002638 ID.StrVal = Lex.getStrVal();
2639 ID.Kind = ValID::t_LocalName;
2640 break;
2641 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002642 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002643 ID.Kind = ValID::t_APSInt;
2644 break;
2645 case lltok::APFloat:
2646 ID.APFloatVal = Lex.getAPFloatVal();
2647 ID.Kind = ValID::t_APFloat;
2648 break;
2649 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002650 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002651 ID.Kind = ValID::t_Constant;
2652 break;
2653 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002654 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002655 ID.Kind = ValID::t_Constant;
2656 break;
2657 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2658 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2659 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
David Majnemerf0f224d2015-11-11 21:57:16 +00002660 case lltok::kw_none: ID.Kind = ValID::t_None; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002661
Chris Lattnerac161bf2009-01-02 07:01:27 +00002662 case lltok::lbrace: {
2663 // ValID ::= '{' ConstVector '}'
2664 Lex.Lex();
2665 SmallVector<Constant*, 16> Elts;
2666 if (ParseGlobalValueVector(Elts) ||
2667 ParseToken(lltok::rbrace, "expected end of struct constant"))
2668 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002669
David Blaikieadbda4b2015-08-03 20:08:41 +00002670 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002671 ID.UIntVal = Elts.size();
David Blaikieadbda4b2015-08-03 20:08:41 +00002672 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2673 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002674 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002675 return false;
2676 }
2677 case lltok::less: {
2678 // ValID ::= '<' ConstVector '>' --> Vector.
2679 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2680 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002681 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002682
Chris Lattnerac161bf2009-01-02 07:01:27 +00002683 SmallVector<Constant*, 16> Elts;
2684 LocTy FirstEltLoc = Lex.getLoc();
2685 if (ParseGlobalValueVector(Elts) ||
2686 (isPackedStruct &&
2687 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2688 ParseToken(lltok::greater, "expected end of constant"))
2689 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002690
Chris Lattnerac161bf2009-01-02 07:01:27 +00002691 if (isPackedStruct) {
David Blaikieadbda4b2015-08-03 20:08:41 +00002692 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2693 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2694 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002695 ID.UIntVal = Elts.size();
2696 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002697 return false;
2698 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002699
Chris Lattnerac161bf2009-01-02 07:01:27 +00002700 if (Elts.empty())
2701 return Error(ID.Loc, "constant vector must not be empty");
2702
Duncan Sands9dff9be2010-02-15 16:12:20 +00002703 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002704 !Elts[0]->getType()->isFloatingPointTy() &&
2705 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002706 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002707 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002708
Chris Lattnerac161bf2009-01-02 07:01:27 +00002709 // Verify that all the vector elements have the same type.
2710 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2711 if (Elts[i]->getType() != Elts[0]->getType())
2712 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002713 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002714 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002715
Chris Lattner69229312011-02-15 00:14:00 +00002716 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002717 ID.Kind = ValID::t_Constant;
2718 return false;
2719 }
2720 case lltok::lsquare: { // Array Constant
2721 Lex.Lex();
2722 SmallVector<Constant*, 16> Elts;
2723 LocTy FirstEltLoc = Lex.getLoc();
2724 if (ParseGlobalValueVector(Elts) ||
2725 ParseToken(lltok::rsquare, "expected end of array constant"))
2726 return true;
2727
2728 // Handle empty element.
2729 if (Elts.empty()) {
2730 // Use undef instead of an array because it's inconvenient to determine
2731 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002732 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002733 return false;
2734 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002735
Chris Lattnerac161bf2009-01-02 07:01:27 +00002736 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002737 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002738 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002739
Owen Anderson4056ca92009-07-29 22:17:13 +00002740 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002741
Chris Lattnerac161bf2009-01-02 07:01:27 +00002742 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002743 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002744 if (Elts[i]->getType() != Elts[0]->getType())
2745 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002746 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002747 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002748 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002749
Jay Foad83be3612011-06-22 09:24:39 +00002750 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002751 ID.Kind = ValID::t_Constant;
2752 return false;
2753 }
2754 case lltok::kw_c: // c "foo"
2755 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002756 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2757 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002758 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2759 ID.Kind = ValID::t_Constant;
2760 return false;
2761
2762 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002763 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2764 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002765 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002766 Lex.Lex();
2767 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002768 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002769 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002770 ParseStringConstant(ID.StrVal) ||
2771 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002772 ParseToken(lltok::StringConstant, "expected constraint string"))
2773 return true;
2774 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002775 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002776 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002777 ID.Kind = ValID::t_InlineAsm;
2778 return false;
2779 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002780
Chris Lattner3432c622009-10-28 03:39:23 +00002781 case lltok::kw_blockaddress: {
2782 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2783 Lex.Lex();
2784
2785 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002786
Chris Lattner3432c622009-10-28 03:39:23 +00002787 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2788 ParseValID(Fn) ||
2789 ParseToken(lltok::comma, "expected comma in block address expression")||
2790 ParseValID(Label) ||
2791 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2792 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002793
Chris Lattner3432c622009-10-28 03:39:23 +00002794 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2795 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002796 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002797 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002798
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002799 // Try to find the function (but skip it if it's forward-referenced).
2800 GlobalValue *GV = nullptr;
2801 if (Fn.Kind == ValID::t_GlobalID) {
2802 if (Fn.UIntVal < NumberedVals.size())
2803 GV = NumberedVals[Fn.UIntVal];
2804 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2805 GV = M->getNamedValue(Fn.StrVal);
2806 }
2807 Function *F = nullptr;
2808 if (GV) {
2809 // Confirm that it's actually a function with a definition.
2810 if (!isa<Function>(GV))
2811 return Error(Fn.Loc, "expected function name in blockaddress");
2812 F = cast<Function>(GV);
2813 if (F->isDeclaration())
2814 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2815 }
2816
2817 if (!F) {
2818 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00002819 GlobalValue *&FwdRef =
David Blaikie871b4112015-08-03 20:55:00 +00002820 ForwardRefBlockAddresses.insert(std::make_pair(
2821 std::move(Fn),
2822 std::map<ValID, GlobalValue *>()))
David Blaikieb9cc6592015-03-04 01:40:07 +00002823 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2824 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002825 if (!FwdRef)
2826 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2827 GlobalValue::InternalLinkage, nullptr, "");
2828 ID.ConstantVal = FwdRef;
2829 ID.Kind = ValID::t_Constant;
2830 return false;
2831 }
2832
2833 // We found the function; now find the basic block. Don't use PFS, since we
2834 // might be inside a constant expression.
2835 BasicBlock *BB;
2836 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2837 if (Label.Kind == ValID::t_LocalID)
2838 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2839 else
2840 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2841 if (!BB)
2842 return Error(Label.Loc, "referenced value is not a basic block");
2843 } else {
2844 if (Label.Kind == ValID::t_LocalID)
2845 return Error(Label.Loc, "cannot take address of numeric label after "
2846 "the function is defined");
2847 BB = dyn_cast_or_null<BasicBlock>(
2848 F->getValueSymbolTable().lookup(Label.StrVal));
2849 if (!BB)
2850 return Error(Label.Loc, "referenced value is not a basic block");
2851 }
2852
2853 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002854 ID.Kind = ValID::t_Constant;
2855 return false;
2856 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002857
Chris Lattnerac161bf2009-01-02 07:01:27 +00002858 case lltok::kw_trunc:
2859 case lltok::kw_zext:
2860 case lltok::kw_sext:
2861 case lltok::kw_fptrunc:
2862 case lltok::kw_fpext:
2863 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002864 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002865 case lltok::kw_uitofp:
2866 case lltok::kw_sitofp:
2867 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002868 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002869 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002870 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002871 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002872 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002873 Constant *SrcVal;
2874 Lex.Lex();
2875 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2876 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002877 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002878 ParseType(DestTy) ||
2879 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2880 return true;
2881 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2882 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002883 getTypeString(SrcVal->getType()) + "' to '" +
2884 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002885 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002886 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002887 ID.Kind = ValID::t_Constant;
2888 return false;
2889 }
2890 case lltok::kw_extractvalue: {
2891 Lex.Lex();
2892 Constant *Val;
2893 SmallVector<unsigned, 4> Indices;
2894 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2895 ParseGlobalTypeAndValue(Val) ||
2896 ParseIndexList(Indices) ||
2897 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2898 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002899
Chris Lattner392be582010-02-12 20:49:41 +00002900 if (!Val->getType()->isAggregateType())
2901 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002902 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002903 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002904 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002905 ID.Kind = ValID::t_Constant;
2906 return false;
2907 }
2908 case lltok::kw_insertvalue: {
2909 Lex.Lex();
2910 Constant *Val0, *Val1;
2911 SmallVector<unsigned, 4> Indices;
2912 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2913 ParseGlobalTypeAndValue(Val0) ||
2914 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2915 ParseGlobalTypeAndValue(Val1) ||
2916 ParseIndexList(Indices) ||
2917 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2918 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002919 if (!Val0->getType()->isAggregateType())
2920 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00002921 Type *IndexedType =
2922 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2923 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002924 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00002925 if (IndexedType != Val1->getType())
2926 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2927 getTypeString(Val1->getType()) +
2928 "' instead of '" + getTypeString(IndexedType) +
2929 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00002930 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002931 ID.Kind = ValID::t_Constant;
2932 return false;
2933 }
2934 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002935 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002936 unsigned PredVal, Opc = Lex.getUIntVal();
2937 Constant *Val0, *Val1;
2938 Lex.Lex();
2939 if (ParseCmpPredicate(PredVal, Opc) ||
2940 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2941 ParseGlobalTypeAndValue(Val0) ||
2942 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2943 ParseGlobalTypeAndValue(Val1) ||
2944 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2945 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002946
Chris Lattnerac161bf2009-01-02 07:01:27 +00002947 if (Val0->getType() != Val1->getType())
2948 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002949
Chris Lattnerac161bf2009-01-02 07:01:27 +00002950 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002951
Chris Lattnerac161bf2009-01-02 07:01:27 +00002952 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002953 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002954 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002955 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002956 } else {
2957 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002958 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002959 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002960 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002961 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002962 }
2963 ID.Kind = ValID::t_Constant;
2964 return false;
2965 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002966
Chris Lattnerac161bf2009-01-02 07:01:27 +00002967 // Binary Operators.
2968 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00002969 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002970 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00002971 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002972 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00002973 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002974 case lltok::kw_udiv:
2975 case lltok::kw_sdiv:
2976 case lltok::kw_fdiv:
2977 case lltok::kw_urem:
2978 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002979 case lltok::kw_frem:
2980 case lltok::kw_shl:
2981 case lltok::kw_lshr:
2982 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002983 bool NUW = false;
2984 bool NSW = false;
2985 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002986 unsigned Opc = Lex.getUIntVal();
2987 Constant *Val0, *Val1;
2988 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00002989 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00002990 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2991 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002992 if (EatIfPresent(lltok::kw_nuw))
2993 NUW = true;
2994 if (EatIfPresent(lltok::kw_nsw)) {
2995 NSW = true;
2996 if (EatIfPresent(lltok::kw_nuw))
2997 NUW = true;
2998 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00002999 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3000 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003001 if (EatIfPresent(lltok::kw_exact))
3002 Exact = true;
3003 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003004 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3005 ParseGlobalTypeAndValue(Val0) ||
3006 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3007 ParseGlobalTypeAndValue(Val1) ||
3008 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3009 return true;
3010 if (Val0->getType() != Val1->getType())
3011 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003012 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003013 if (NUW)
3014 return Error(ModifierLoc, "nuw only applies to integer operations");
3015 if (NSW)
3016 return Error(ModifierLoc, "nsw only applies to integer operations");
3017 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00003018 // Check that the type is valid for the operator.
3019 switch (Opc) {
3020 case Instruction::Add:
3021 case Instruction::Sub:
3022 case Instruction::Mul:
3023 case Instruction::UDiv:
3024 case Instruction::SDiv:
3025 case Instruction::URem:
3026 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003027 case Instruction::Shl:
3028 case Instruction::AShr:
3029 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00003030 if (!Val0->getType()->isIntOrIntVectorTy())
3031 return Error(ID.Loc, "constexpr requires integer operands");
3032 break;
3033 case Instruction::FAdd:
3034 case Instruction::FSub:
3035 case Instruction::FMul:
3036 case Instruction::FDiv:
3037 case Instruction::FRem:
3038 if (!Val0->getType()->isFPOrFPVectorTy())
3039 return Error(ID.Loc, "constexpr requires fp operands");
3040 break;
3041 default: llvm_unreachable("Unknown binary operator!");
3042 }
Dan Gohman1b849082009-09-07 23:54:19 +00003043 unsigned Flags = 0;
3044 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3045 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00003046 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00003047 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00003048 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003049 ID.Kind = ValID::t_Constant;
3050 return false;
3051 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003052
Chris Lattnerac161bf2009-01-02 07:01:27 +00003053 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00003054 case lltok::kw_and:
3055 case lltok::kw_or:
3056 case lltok::kw_xor: {
3057 unsigned Opc = Lex.getUIntVal();
3058 Constant *Val0, *Val1;
3059 Lex.Lex();
3060 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3061 ParseGlobalTypeAndValue(Val0) ||
3062 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3063 ParseGlobalTypeAndValue(Val1) ||
3064 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3065 return true;
3066 if (Val0->getType() != Val1->getType())
3067 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003068 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003069 return Error(ID.Loc,
3070 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003071 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003072 ID.Kind = ValID::t_Constant;
3073 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003074 }
3075
Chris Lattnerac161bf2009-01-02 07:01:27 +00003076 case lltok::kw_getelementptr:
3077 case lltok::kw_shufflevector:
3078 case lltok::kw_insertelement:
3079 case lltok::kw_extractelement:
3080 case lltok::kw_select: {
3081 unsigned Opc = Lex.getUIntVal();
3082 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00003083 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00003084 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003085 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00003086
Dan Gohman1639c392009-07-27 21:53:46 +00003087 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00003088 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00003089
3090 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3091 return true;
3092
3093 LocTy ExplicitTypeLoc = Lex.getLoc();
3094 if (Opc == Instruction::GetElementPtr) {
3095 if (ParseType(Ty) ||
3096 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3097 return true;
3098 }
3099
3100 if (ParseGlobalValueVector(Elts) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003101 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3102 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003103
Chris Lattnerac161bf2009-01-02 07:01:27 +00003104 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00003105 if (Elts.size() == 0 ||
3106 !Elts[0]->getType()->getScalarType()->isPointerTy())
David Majnemer00303b62015-02-22 23:14:52 +00003107 return Error(ID.Loc, "base of getelementptr must be a pointer");
3108
3109 Type *BaseType = Elts[0]->getType();
3110 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00003111 if (Ty != BasePointerType->getElementType())
3112 return Error(
3113 ExplicitTypeLoc,
3114 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003115
Jay Foaded8db7d2011-07-21 14:31:17 +00003116 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00003117 for (Constant *Val : Indices) {
3118 Type *ValTy = Val->getType();
3119 if (!ValTy->getScalarType()->isIntegerTy())
3120 return Error(ID.Loc, "getelementptr index must be an integer");
3121 if (ValTy->isVectorTy() != BaseType->isVectorTy())
3122 return Error(ID.Loc, "getelementptr index type missmatch");
3123 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00003124 unsigned ValNumEl = ValTy->getVectorNumElements();
3125 unsigned PtrNumEl = BaseType->getVectorNumElements();
David Majnemer00303b62015-02-22 23:14:52 +00003126 if (ValNumEl != PtrNumEl)
3127 return Error(
3128 ID.Loc,
3129 "getelementptr vector index has a wrong number of elements");
3130 }
3131 }
3132
Craig Toppere3dcce92015-08-01 22:20:21 +00003133 SmallPtrSet<Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00003134 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00003135 return Error(ID.Loc, "base element of getelementptr must be sized");
3136
David Blaikie4a2e73b2015-04-02 18:55:32 +00003137 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00003138 return Error(ID.Loc, "invalid getelementptr indices");
David Blaikie4a2e73b2015-04-02 18:55:32 +00003139 ID.ConstantVal =
3140 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003141 } else if (Opc == Instruction::Select) {
3142 if (Elts.size() != 3)
3143 return Error(ID.Loc, "expected three operands to select");
3144 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3145 Elts[2]))
3146 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00003147 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003148 } else if (Opc == Instruction::ShuffleVector) {
3149 if (Elts.size() != 3)
3150 return Error(ID.Loc, "expected three operands to shufflevector");
3151 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3152 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00003153 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003154 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003155 } else if (Opc == Instruction::ExtractElement) {
3156 if (Elts.size() != 2)
3157 return Error(ID.Loc, "expected two operands to extractelement");
3158 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3159 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003160 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003161 } else {
3162 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3163 if (Elts.size() != 3)
3164 return Error(ID.Loc, "expected three operands to insertelement");
3165 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3166 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00003167 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003168 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003169 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003170
Chris Lattnerac161bf2009-01-02 07:01:27 +00003171 ID.Kind = ValID::t_Constant;
3172 return false;
3173 }
3174 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003175
Chris Lattnerac161bf2009-01-02 07:01:27 +00003176 Lex.Lex();
3177 return false;
3178}
3179
3180/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00003181bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003182 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003183 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00003184 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003185 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00003186 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003187 if (V && !(C = dyn_cast<Constant>(V)))
3188 return Error(ID.Loc, "global values must be constants");
3189 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003190}
3191
Victor Hernandez9d75c962010-01-11 22:31:58 +00003192bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003193 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003194 return ParseType(Ty) ||
3195 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003196}
3197
Rafael Espindola83a362c2015-01-06 22:55:16 +00003198bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00003199 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003200
3201 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00003202 if (!EatIfPresent(lltok::kw_comdat))
3203 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003204
3205 if (EatIfPresent(lltok::lparen)) {
3206 if (Lex.getKind() != lltok::ComdatVar)
3207 return TokError("expected comdat variable");
3208 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3209 Lex.Lex();
3210 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3211 return true;
3212 } else {
3213 if (GlobalName.empty())
3214 return TokError("comdat cannot be unnamed");
3215 C = getComdat(GlobalName, KwLoc);
3216 }
3217
David Majnemerdad0a642014-06-27 18:19:56 +00003218 return false;
3219}
3220
Victor Hernandez9d75c962010-01-11 22:31:58 +00003221/// ParseGlobalValueVector
3222/// ::= /*empty*/
3223/// ::= TypeAndValue (',' TypeAndValue)*
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003224bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00003225 // Empty list.
3226 if (Lex.getKind() == lltok::rbrace ||
3227 Lex.getKind() == lltok::rsquare ||
3228 Lex.getKind() == lltok::greater ||
3229 Lex.getKind() == lltok::rparen)
3230 return false;
3231
3232 Constant *C;
3233 if (ParseGlobalTypeAndValue(C)) return true;
3234 Elts.push_back(C);
3235
3236 while (EatIfPresent(lltok::comma)) {
3237 if (ParseGlobalTypeAndValue(C)) return true;
3238 Elts.push_back(C);
3239 }
3240
3241 return false;
3242}
3243
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003244bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003245 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003246 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003247 return true;
3248
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003249 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003250 return false;
3251}
3252
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003253/// MDNode:
3254/// ::= !{ ... }
3255/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003256/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003257bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003258 if (Lex.getKind() == lltok::MetadataVar)
3259 return ParseSpecializedMDNode(N);
3260
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003261 return ParseToken(lltok::exclaim, "expected '!' here") ||
3262 ParseMDNodeTail(N);
3263}
3264
3265bool LLParser::ParseMDNodeTail(MDNode *&N) {
3266 // !{ ... }
3267 if (Lex.getKind() == lltok::lbrace)
3268 return ParseMDTuple(N);
3269
3270 // !42
3271 return ParseMDNodeID(N);
3272}
3273
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003274namespace {
3275
3276/// Structure to represent an optional metadata field.
3277template <class FieldTy> struct MDFieldImpl {
3278 typedef MDFieldImpl ImplTy;
3279 FieldTy Val;
3280 bool Seen;
3281
3282 void assign(FieldTy Val) {
3283 Seen = true;
3284 this->Val = std::move(Val);
3285 }
3286
3287 explicit MDFieldImpl(FieldTy Default)
3288 : Val(std::move(Default)), Seen(false) {}
3289};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003290
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003291struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3292 uint64_t Max;
3293
3294 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3295 : ImplTy(Default), Max(Max) {}
3296};
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003297struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003298 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003299};
3300struct ColumnField : public MDUnsignedField {
3301 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3302};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003303struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003304 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003305 DwarfTagField(dwarf::Tag DefaultTag)
3306 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003307};
Amjad Abouda9bcf162015-12-10 12:56:35 +00003308struct DwarfMacinfoTypeField : public MDUnsignedField {
3309 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3310 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3311 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3312};
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003313struct DwarfAttEncodingField : public MDUnsignedField {
3314 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3315};
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003316struct DwarfVirtualityField : public MDUnsignedField {
3317 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3318};
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003319struct DwarfLangField : public MDUnsignedField {
3320 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3321};
Adrian Prantlb939a252016-03-31 23:56:58 +00003322struct EmissionKindField : public MDUnsignedField {
3323 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3324};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003325
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003326struct DIFlagField : public MDUnsignedField {
3327 DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3328};
3329
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003330struct MDSignedField : public MDFieldImpl<int64_t> {
3331 int64_t Min;
3332 int64_t Max;
3333
3334 MDSignedField(int64_t Default = 0)
3335 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3336 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3337 : ImplTy(Default), Min(Min), Max(Max) {}
3338};
3339
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003340struct MDBoolField : public MDFieldImpl<bool> {
3341 MDBoolField(bool Default = false) : ImplTy(Default) {}
3342};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003343struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003344 bool AllowNull;
3345
3346 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003347};
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003348struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3349 MDConstant() : ImplTy(nullptr) {}
3350};
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003351struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003352 bool AllowEmpty;
3353 MDStringField(bool AllowEmpty = true)
3354 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003355};
3356struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3357 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3358};
3359
3360} // end namespace
3361
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003362namespace llvm {
3363
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003364template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003365bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003366 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003367 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3368 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003369
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003370 auto &U = Lex.getAPSIntVal();
3371 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003372 return TokError("value for '" + Name + "' too large, limit is " +
3373 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003374 Result.assign(U.getZExtValue());
3375 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003376 Lex.Lex();
3377 return false;
3378}
3379
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003380template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003381bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3382 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3383}
3384template <>
3385bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3386 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3387}
3388
3389template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003390bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3391 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003392 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003393
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003394 if (Lex.getKind() != lltok::DwarfTag)
3395 return TokError("expected DWARF tag");
3396
3397 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3398 if (Tag == dwarf::DW_TAG_invalid)
3399 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003400 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003401
3402 Result.assign(Tag);
3403 Lex.Lex();
3404 return false;
3405}
3406
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003407template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003408bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003409 DwarfMacinfoTypeField &Result) {
3410 if (Lex.getKind() == lltok::APSInt)
3411 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3412
3413 if (Lex.getKind() != lltok::DwarfMacinfo)
3414 return TokError("expected DWARF macinfo type");
3415
3416 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3417 if (Macinfo == dwarf::DW_MACINFO_invalid)
3418 return TokError(
3419 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3420 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3421
3422 Result.assign(Macinfo);
3423 Lex.Lex();
3424 return false;
3425}
3426
3427template <>
3428bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003429 DwarfVirtualityField &Result) {
3430 if (Lex.getKind() == lltok::APSInt)
3431 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3432
3433 if (Lex.getKind() != lltok::DwarfVirtuality)
3434 return TokError("expected DWARF virtuality code");
3435
3436 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
Peter Collingbournea1f86252016-03-17 23:58:03 +00003437 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003438 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3439 Lex.getStrVal() + "'");
3440 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3441 Result.assign(Virtuality);
3442 Lex.Lex();
3443 return false;
3444}
3445
3446template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003447bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3448 if (Lex.getKind() == lltok::APSInt)
3449 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3450
3451 if (Lex.getKind() != lltok::DwarfLang)
3452 return TokError("expected DWARF language");
3453
3454 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3455 if (!Lang)
3456 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3457 "'");
3458 assert(Lang <= Result.Max && "Expected valid DWARF language");
3459 Result.assign(Lang);
3460 Lex.Lex();
3461 return false;
3462}
3463
3464template <>
Adrian Prantlb939a252016-03-31 23:56:58 +00003465bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3466 if (Lex.getKind() == lltok::APSInt)
3467 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3468
3469 if (Lex.getKind() != lltok::EmissionKind)
3470 return TokError("expected emission kind");
3471
3472 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3473 if (!Kind)
3474 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3475 "'");
3476 assert(*Kind <= Result.Max && "Expected valid emission kind");
3477 Result.assign(*Kind);
3478 Lex.Lex();
3479 return false;
3480}
3481
3482template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003483bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003484 DwarfAttEncodingField &Result) {
3485 if (Lex.getKind() == lltok::APSInt)
3486 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3487
3488 if (Lex.getKind() != lltok::DwarfAttEncoding)
3489 return TokError("expected DWARF type attribute encoding");
3490
3491 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3492 if (!Encoding)
3493 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3494 Lex.getStrVal() + "'");
3495 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3496 Result.assign(Encoding);
3497 Lex.Lex();
3498 return false;
3499}
3500
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003501/// DIFlagField
3502/// ::= uint32
3503/// ::= DIFlagVector
3504/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3505template <>
3506bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3507 assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3508
3509 // Parser for a single flag.
3510 auto parseFlag = [&](unsigned &Val) {
3511 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3512 return ParseUInt32(Val);
3513
3514 if (Lex.getKind() != lltok::DIFlag)
3515 return TokError("expected debug info flag");
3516
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003517 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003518 if (!Val)
3519 return TokError(Twine("invalid debug info flag flag '") +
3520 Lex.getStrVal() + "'");
3521 Lex.Lex();
3522 return false;
3523 };
3524
3525 // Parse the flags and combine them together.
3526 unsigned Combined = 0;
3527 do {
3528 unsigned Val;
3529 if (parseFlag(Val))
3530 return true;
3531 Combined |= Val;
3532 } while (EatIfPresent(lltok::bar));
3533
3534 Result.assign(Combined);
3535 return false;
3536}
3537
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003538template <>
3539bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003540 MDSignedField &Result) {
3541 if (Lex.getKind() != lltok::APSInt)
3542 return TokError("expected signed integer");
3543
3544 auto &S = Lex.getAPSIntVal();
3545 if (S < Result.Min)
3546 return TokError("value for '" + Name + "' too small, limit is " +
3547 Twine(Result.Min));
3548 if (S > Result.Max)
3549 return TokError("value for '" + Name + "' too large, limit is " +
3550 Twine(Result.Max));
3551 Result.assign(S.getExtValue());
3552 assert(Result.Val >= Result.Min && "Expected value in range");
3553 assert(Result.Val <= Result.Max && "Expected value in range");
3554 Lex.Lex();
3555 return false;
3556}
3557
3558template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003559bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3560 switch (Lex.getKind()) {
3561 default:
3562 return TokError("expected 'true' or 'false'");
3563 case lltok::kw_true:
3564 Result.assign(true);
3565 break;
3566 case lltok::kw_false:
3567 Result.assign(false);
3568 break;
3569 }
3570 Lex.Lex();
3571 return false;
3572}
3573
3574template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003575bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003576 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003577 if (!Result.AllowNull)
3578 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003579 Lex.Lex();
3580 Result.assign(nullptr);
3581 return false;
3582 }
3583
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003584 Metadata *MD;
3585 if (ParseMetadata(MD, nullptr))
3586 return true;
3587
3588 Result.assign(MD);
3589 return false;
3590}
3591
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003592template <>
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003593bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3594 Metadata *MD;
3595 if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3596 return true;
3597
3598 Result.assign(cast<ConstantAsMetadata>(MD));
3599 return false;
3600}
3601
3602template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003603bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003604 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003605 std::string S;
3606 if (ParseStringConstant(S))
3607 return true;
3608
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003609 if (!Result.AllowEmpty && S.empty())
3610 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3611
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003612 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003613 return false;
3614}
3615
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003616template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003617bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3618 SmallVector<Metadata *, 4> MDs;
3619 if (ParseMDNodeVector(MDs))
3620 return true;
3621
3622 Result.assign(std::move(MDs));
3623 return false;
3624}
3625
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003626} // end namespace llvm
3627
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003628template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003629bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003630 do {
3631 if (Lex.getKind() != lltok::LabelStr)
3632 return TokError("expected field label here");
3633
3634 if (parseField())
3635 return true;
3636 } while (EatIfPresent(lltok::comma));
3637
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003638 return false;
3639}
3640
3641template <class ParserTy>
3642bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3643 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3644 Lex.Lex();
3645
3646 if (ParseToken(lltok::lparen, "expected '(' here"))
3647 return true;
3648 if (Lex.getKind() != lltok::rparen)
3649 if (ParseMDFieldsImplBody(parseField))
3650 return true;
3651
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00003652 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003653 return ParseToken(lltok::rparen, "expected ')' here");
3654}
3655
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003656template <class FieldTy>
3657bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3658 if (Result.Seen)
3659 return TokError("field '" + Name + "' cannot be specified more than once");
3660
3661 LocTy Loc = Lex.getLoc();
3662 Lex.Lex();
3663 return ParseMDField(Loc, Name, Result);
3664}
3665
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003666bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3667 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003668
3669#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003670 if (Lex.getStrVal() == #CLASS) \
3671 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003672#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003673
3674 return TokError("expected metadata type");
3675}
3676
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003677#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3678#define NOP_FIELD(NAME, TYPE, INIT)
3679#define REQUIRE_FIELD(NAME, TYPE, INIT) \
3680 if (!NAME.Seen) \
3681 return Error(ClosingLoc, "missing required field '" #NAME "'");
3682#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003683 if (Lex.getStrVal() == #NAME) \
3684 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003685#define PARSE_MD_FIELDS() \
3686 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3687 do { \
3688 LocTy ClosingLoc; \
3689 if (ParseMDFieldsImpl([&]() -> bool { \
3690 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3691 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3692 }, ClosingLoc)) \
3693 return true; \
3694 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3695 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003696#define GET_OR_DISTINCT(CLASS, ARGS) \
3697 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003698
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003699/// ParseDILocationFields:
3700/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3701bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003702#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003703 OPTIONAL(line, LineField, ); \
3704 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003705 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003706 OPTIONAL(inlinedAt, MDField, );
3707 PARSE_MD_FIELDS();
3708#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003709
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00003710 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003711 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003712 return false;
3713}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003714
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003715/// ParseGenericDINode:
3716/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3717bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003718#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003719 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003720 OPTIONAL(header, MDStringField, ); \
3721 OPTIONAL(operands, MDFieldList, );
3722 PARSE_MD_FIELDS();
3723#undef VISIT_MD_FIELDS
3724
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003725 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003726 (Context, tag.Val, header.Val, operands.Val));
3727 return false;
3728}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003729
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003730/// ParseDISubrange:
3731/// ::= !DISubrange(count: 30, lowerBound: 2)
3732bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003733#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith5c9a1772015-02-18 23:17:51 +00003734 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003735 OPTIONAL(lowerBound, MDSignedField, );
3736 PARSE_MD_FIELDS();
3737#undef VISIT_MD_FIELDS
3738
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003739 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003740 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003741}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003742
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003743/// ParseDIEnumerator:
3744/// ::= !DIEnumerator(value: 30, name: "SomeKind")
3745bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003746#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00003747 REQUIRED(name, MDStringField, ); \
3748 REQUIRED(value, MDSignedField, );
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003749 PARSE_MD_FIELDS();
3750#undef VISIT_MD_FIELDS
3751
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003752 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003753 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003754}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003755
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003756/// ParseDIBasicType:
3757/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3758bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003759#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003760 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003761 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003762 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3763 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003764 OPTIONAL(encoding, DwarfAttEncodingField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003765 PARSE_MD_FIELDS();
3766#undef VISIT_MD_FIELDS
3767
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003768 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003769 align.Val, encoding.Val));
3770 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003771}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003772
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003773/// ParseDIDerivedType:
3774/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003775/// line: 7, scope: !1, baseType: !2, size: 32,
3776/// align: 32, offset: 0, flags: 0, extraData: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003777bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003778#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3779 REQUIRED(tag, DwarfTagField, ); \
3780 OPTIONAL(name, MDStringField, ); \
3781 OPTIONAL(file, MDField, ); \
3782 OPTIONAL(line, LineField, ); \
3783 OPTIONAL(scope, MDField, ); \
3784 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003785 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3786 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3787 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003788 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003789 OPTIONAL(extraData, MDField, );
3790 PARSE_MD_FIELDS();
3791#undef VISIT_MD_FIELDS
3792
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003793 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003794 (Context, tag.Val, name.Val, file.Val, line.Val,
3795 scope.Val, baseType.Val, size.Val, align.Val,
3796 offset.Val, flags.Val, extraData.Val));
3797 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003798}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003799
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003800bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003801#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3802 REQUIRED(tag, DwarfTagField, ); \
3803 OPTIONAL(name, MDStringField, ); \
3804 OPTIONAL(file, MDField, ); \
3805 OPTIONAL(line, LineField, ); \
3806 OPTIONAL(scope, MDField, ); \
3807 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003808 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3809 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3810 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003811 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003812 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003813 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003814 OPTIONAL(vtableHolder, MDField, ); \
3815 OPTIONAL(templateParams, MDField, ); \
3816 OPTIONAL(identifier, MDStringField, );
3817 PARSE_MD_FIELDS();
3818#undef VISIT_MD_FIELDS
3819
Duncan P. N. Exon Smith97386022016-04-19 18:00:19 +00003820 // If this has an identifier try to build an ODR type.
3821 if (identifier.Val)
3822 if (auto *CT = DICompositeType::buildODRType(
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00003823 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
3824 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
3825 elements.Val, runtimeLang.Val, vtableHolder.Val,
3826 templateParams.Val)) {
3827 Result = CT;
3828 return false;
3829 }
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00003830
3831 // Create a new node, and save it in the context if it belongs in the type
3832 // map.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003833 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003834 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003835 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3836 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3837 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3838 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003839}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003840
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003841bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003842#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003843 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003844 REQUIRED(types, MDField, );
3845 PARSE_MD_FIELDS();
3846#undef VISIT_MD_FIELDS
3847
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003848 Result = GET_OR_DISTINCT(DISubroutineType, (Context, flags.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003849 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003850}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003851
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003852/// ParseDIFileType:
3853/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir")
3854bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003855#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3856 REQUIRED(filename, MDStringField, ); \
3857 REQUIRED(directory, MDStringField, );
3858 PARSE_MD_FIELDS();
3859#undef VISIT_MD_FIELDS
3860
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003861 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003862 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003863}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003864
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003865/// ParseDICompileUnit:
3866/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003867/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
Adrian Prantlb939a252016-03-31 23:56:58 +00003868/// splitDebugFilename: "abc.debug",
Adrian Prantl75819ae2016-04-15 15:57:41 +00003869/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003870/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003871bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00003872 if (!IsDistinct)
3873 return Lex.Error("missing 'distinct', required for !DICompileUnit");
3874
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003875#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3876 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00003877 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003878 OPTIONAL(producer, MDStringField, ); \
3879 OPTIONAL(isOptimized, MDBoolField, ); \
3880 OPTIONAL(flags, MDStringField, ); \
3881 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
3882 OPTIONAL(splitDebugFilename, MDStringField, ); \
Adrian Prantlb939a252016-03-31 23:56:58 +00003883 OPTIONAL(emissionKind, EmissionKindField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003884 OPTIONAL(enums, MDField, ); \
3885 OPTIONAL(retainedTypes, MDField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003886 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00003887 OPTIONAL(imports, MDField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00003888 OPTIONAL(macros, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00003889 OPTIONAL(dwoId, MDUnsignedField, );
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003890 PARSE_MD_FIELDS();
3891#undef VISIT_MD_FIELDS
3892
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00003893 Result = DICompileUnit::getDistinct(
3894 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
3895 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
Adrian Prantl75819ae2016-04-15 15:57:41 +00003896 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003897 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003898}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003899
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003900/// ParseDISubprogram:
3901/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003902/// file: !1, line: 7, type: !2, isLocal: false,
3903/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003904/// virtuality: DW_VIRTUALTIY_pure_virtual,
3905/// virtualIndex: 10, flags: 11,
Peter Collingbourned4bff302015-11-05 22:03:56 +00003906/// isOptimized: false, templateParams: !4, declaration: !5,
3907/// variables: !6)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003908bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00003909 auto Loc = Lex.getLoc();
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003910#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3911 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00003912 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003913 OPTIONAL(linkageName, MDStringField, ); \
3914 OPTIONAL(file, MDField, ); \
3915 OPTIONAL(line, LineField, ); \
3916 OPTIONAL(type, MDField, ); \
3917 OPTIONAL(isLocal, MDBoolField, ); \
3918 OPTIONAL(isDefinition, MDBoolField, (true)); \
3919 OPTIONAL(scopeLine, LineField, ); \
3920 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003921 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003922 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003923 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003924 OPTIONAL(isOptimized, MDBoolField, ); \
Adrian Prantl75819ae2016-04-15 15:57:41 +00003925 OPTIONAL(unit, MDField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003926 OPTIONAL(templateParams, MDField, ); \
3927 OPTIONAL(declaration, MDField, ); \
3928 OPTIONAL(variables, MDField, );
3929 PARSE_MD_FIELDS();
3930#undef VISIT_MD_FIELDS
3931
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00003932 if (isDefinition.Val && !IsDistinct)
3933 return Lex.Error(
3934 Loc,
3935 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
3936
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003937 Result = GET_OR_DISTINCT(
Adrian Prantl75819ae2016-04-15 15:57:41 +00003938 DISubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
3939 line.Val, type.Val, isLocal.Val, isDefinition.Val,
3940 scopeLine.Val, containingType.Val, virtuality.Val,
3941 virtualIndex.Val, flags.Val, isOptimized.Val, unit.Val,
3942 templateParams.Val, declaration.Val, variables.Val));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003943 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003944}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003945
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003946/// ParseDILexicalBlock:
3947/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
3948bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003949#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00003950 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003951 OPTIONAL(file, MDField, ); \
3952 OPTIONAL(line, LineField, ); \
3953 OPTIONAL(column, ColumnField, );
3954 PARSE_MD_FIELDS();
3955#undef VISIT_MD_FIELDS
3956
3957 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003958 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003959 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003960}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003961
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003962/// ParseDILexicalBlockFile:
3963/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
3964bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003965#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00003966 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003967 OPTIONAL(file, MDField, ); \
3968 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
3969 PARSE_MD_FIELDS();
3970#undef VISIT_MD_FIELDS
3971
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003972 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003973 (Context, scope.Val, file.Val, discriminator.Val));
3974 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003975}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003976
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003977/// ParseDINamespace:
3978/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
3979bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003980#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3981 REQUIRED(scope, MDField, ); \
3982 OPTIONAL(file, MDField, ); \
3983 OPTIONAL(name, MDStringField, ); \
3984 OPTIONAL(line, LineField, );
3985 PARSE_MD_FIELDS();
3986#undef VISIT_MD_FIELDS
3987
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003988 Result = GET_OR_DISTINCT(DINamespace,
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003989 (Context, scope.Val, file.Val, name.Val, line.Val));
3990 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003991}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003992
Amjad Abouda9bcf162015-12-10 12:56:35 +00003993/// ParseDIMacro:
3994/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
3995bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
3996#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3997 REQUIRED(type, DwarfMacinfoTypeField, ); \
3998 REQUIRED(line, LineField, ); \
3999 REQUIRED(name, MDStringField, ); \
4000 OPTIONAL(value, MDStringField, );
4001 PARSE_MD_FIELDS();
4002#undef VISIT_MD_FIELDS
4003
4004 Result = GET_OR_DISTINCT(DIMacro,
4005 (Context, type.Val, line.Val, name.Val, value.Val));
4006 return false;
4007}
4008
4009/// ParseDIMacroFile:
4010/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4011bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4012#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4013 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
4014 REQUIRED(line, LineField, ); \
4015 REQUIRED(file, MDField, ); \
4016 OPTIONAL(nodes, MDField, );
4017 PARSE_MD_FIELDS();
4018#undef VISIT_MD_FIELDS
4019
4020 Result = GET_OR_DISTINCT(DIMacroFile,
4021 (Context, type.Val, line.Val, file.Val, nodes.Val));
4022 return false;
4023}
4024
4025
Adrian Prantlab1243f2015-06-29 23:03:47 +00004026/// ParseDIModule:
4027/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4028/// includePath: "/usr/include", isysroot: "/")
4029bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4030#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4031 REQUIRED(scope, MDField, ); \
4032 REQUIRED(name, MDStringField, ); \
4033 OPTIONAL(configMacros, MDStringField, ); \
4034 OPTIONAL(includePath, MDStringField, ); \
4035 OPTIONAL(isysroot, MDStringField, );
4036 PARSE_MD_FIELDS();
4037#undef VISIT_MD_FIELDS
4038
4039 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4040 configMacros.Val, includePath.Val, isysroot.Val));
4041 return false;
4042}
4043
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004044/// ParseDITemplateTypeParameter:
4045/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4046bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004047#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004048 OPTIONAL(name, MDStringField, ); \
4049 REQUIRED(type, MDField, );
4050 PARSE_MD_FIELDS();
4051#undef VISIT_MD_FIELDS
4052
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004053 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004054 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004055 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004056}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004057
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004058/// ParseDITemplateValueParameter:
4059/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004060/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004061bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004062#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004063 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004064 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004065 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004066 REQUIRED(value, MDField, );
4067 PARSE_MD_FIELDS();
4068#undef VISIT_MD_FIELDS
4069
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004070 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004071 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004072 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004073}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004074
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004075/// ParseDIGlobalVariable:
4076/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004077/// file: !1, line: 7, type: !2, isLocal: false,
4078/// isDefinition: true, variable: i32* @foo,
4079/// declaration: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004080bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004081#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004082 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004083 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004084 OPTIONAL(linkageName, MDStringField, ); \
4085 OPTIONAL(file, MDField, ); \
4086 OPTIONAL(line, LineField, ); \
4087 OPTIONAL(type, MDField, ); \
4088 OPTIONAL(isLocal, MDBoolField, ); \
4089 OPTIONAL(isDefinition, MDBoolField, (true)); \
4090 OPTIONAL(variable, MDConstant, ); \
4091 OPTIONAL(declaration, MDField, );
4092 PARSE_MD_FIELDS();
4093#undef VISIT_MD_FIELDS
4094
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004095 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004096 (Context, scope.Val, name.Val, linkageName.Val,
4097 file.Val, line.Val, type.Val, isLocal.Val,
4098 isDefinition.Val, variable.Val, declaration.Val));
4099 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004100}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004101
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004102/// ParseDILocalVariable:
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004103/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
4104/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
4105/// ::= !DILocalVariable(scope: !0, name: "foo",
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00004106/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004107bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004108#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004109 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004110 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004111 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004112 OPTIONAL(file, MDField, ); \
4113 OPTIONAL(line, LineField, ); \
4114 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00004115 OPTIONAL(flags, DIFlagField, );
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004116 PARSE_MD_FIELDS();
4117#undef VISIT_MD_FIELDS
4118
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004119 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004120 (Context, scope.Val, name.Val, file.Val, line.Val,
4121 type.Val, arg.Val, flags.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004122 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004123}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004124
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004125/// ParseDIExpression:
4126/// ::= !DIExpression(0, 7, -1)
4127bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004128 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4129 Lex.Lex();
4130
4131 if (ParseToken(lltok::lparen, "expected '(' here"))
4132 return true;
4133
4134 SmallVector<uint64_t, 8> Elements;
4135 if (Lex.getKind() != lltok::rparen)
4136 do {
4137 if (Lex.getKind() == lltok::DwarfOp) {
4138 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4139 Lex.Lex();
4140 Elements.push_back(Op);
4141 continue;
4142 }
4143 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4144 }
4145
4146 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4147 return TokError("expected unsigned integer");
4148
4149 auto &U = Lex.getAPSIntVal();
4150 if (U.ugt(UINT64_MAX))
4151 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4152 Elements.push_back(U.getZExtValue());
4153 Lex.Lex();
4154 } while (EatIfPresent(lltok::comma));
4155
4156 if (ParseToken(lltok::rparen, "expected ')' here"))
4157 return true;
4158
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004159 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004160 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004161}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004162
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004163/// ParseDIObjCProperty:
4164/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004165/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004166bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004167#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004168 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004169 OPTIONAL(file, MDField, ); \
4170 OPTIONAL(line, LineField, ); \
4171 OPTIONAL(setter, MDStringField, ); \
4172 OPTIONAL(getter, MDStringField, ); \
4173 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4174 OPTIONAL(type, MDField, );
4175 PARSE_MD_FIELDS();
4176#undef VISIT_MD_FIELDS
4177
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004178 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004179 (Context, name.Val, file.Val, line.Val, setter.Val,
4180 getter.Val, attributes.Val, type.Val));
4181 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004182}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004183
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004184/// ParseDIImportedEntity:
4185/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004186/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004187bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004188#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4189 REQUIRED(tag, DwarfTagField, ); \
4190 REQUIRED(scope, MDField, ); \
4191 OPTIONAL(entity, MDField, ); \
4192 OPTIONAL(line, LineField, ); \
4193 OPTIONAL(name, MDStringField, );
4194 PARSE_MD_FIELDS();
4195#undef VISIT_MD_FIELDS
4196
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004197 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004198 entity.Val, line.Val, name.Val));
4199 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004200}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004201
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004202#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004203#undef NOP_FIELD
4204#undef REQUIRE_FIELD
4205#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004206
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004207/// ParseMetadataAsValue
4208/// ::= metadata i32 %local
4209/// ::= metadata i32 @global
4210/// ::= metadata i32 7
4211/// ::= metadata !0
4212/// ::= metadata !{...}
4213/// ::= metadata !"string"
4214bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4215 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004216 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004217 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004218 return true;
4219
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004220 V = MetadataAsValue::get(Context, MD);
4221 return false;
4222}
4223
4224/// ParseValueAsMetadata
4225/// ::= i32 %local
4226/// ::= i32 @global
4227/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004228bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4229 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004230 Type *Ty;
4231 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004232 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004233 return true;
4234 if (Ty->isMetadataTy())
4235 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4236
4237 Value *V;
4238 if (ParseValue(Ty, V, PFS))
4239 return true;
4240
4241 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004242 return false;
4243}
4244
4245/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004246/// ::= i32 %local
4247/// ::= i32 @global
4248/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00004249/// ::= !42
4250/// ::= !{...}
4251/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004252/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004253bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004254 if (Lex.getKind() == lltok::MetadataVar) {
4255 MDNode *N;
4256 if (ParseSpecializedMDNode(N))
4257 return true;
4258 MD = N;
4259 return false;
4260 }
4261
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004262 // ValueAsMetadata:
4263 // <type> <value>
4264 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004265 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004266
4267 // '!'.
4268 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4269 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00004270
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004271 // MDString:
4272 // ::= '!' STRINGCONSTANT
4273 if (Lex.getKind() == lltok::StringConstant) {
4274 MDString *S;
4275 if (ParseMDString(S))
4276 return true;
4277 MD = S;
4278 return false;
4279 }
4280
Dan Gohman8939ba332010-07-14 18:26:50 +00004281 // MDNode:
4282 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004283 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004284 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004285 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004286 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004287 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00004288 return false;
4289}
4290
Victor Hernandez9d75c962010-01-11 22:31:58 +00004291
4292//===----------------------------------------------------------------------===//
4293// Function Parsing.
4294//===----------------------------------------------------------------------===//
4295
Chris Lattner229907c2011-07-18 04:54:35 +00004296bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
David Majnemer8a1c45d2015-12-12 05:38:55 +00004297 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00004298 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004299 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004300
Chris Lattnerac161bf2009-01-02 07:01:27 +00004301 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004302 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004303 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004304 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004305 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004306 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004307 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004308 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004309 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004310 case ValID::t_InlineAsm: {
Karl Schimpf44876c52015-09-03 16:18:32 +00004311 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez9d75c962010-01-11 22:31:58 +00004312 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie41ba2b42015-07-27 23:32:19 +00004313 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4314 (ID.UIntVal >> 1) & 1,
4315 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00004316 return false;
4317 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004318 case ValID::t_GlobalName:
4319 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004320 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004321 case ValID::t_GlobalID:
4322 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004323 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004324 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00004325 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004326 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00004327 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00004328 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004329 return false;
4330 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00004331 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004332 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4333 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004334
Dan Gohman518cda42011-12-17 00:04:22 +00004335 // The lexer has no type info, so builds all half, float, and double FP
4336 // constants as double. Fix this here. Long double does not need this.
4337 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004338 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00004339 if (Ty->isHalfTy())
4340 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
4341 &Ignored);
4342 else if (Ty->isFloatTy())
4343 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
4344 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004345 }
Owen Anderson69c464d2009-07-27 20:59:43 +00004346 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004347
Chris Lattner8f57d29e2009-01-05 18:24:23 +00004348 if (V->getType() != Ty)
4349 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004350 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004351
Chris Lattnerac161bf2009-01-02 07:01:27 +00004352 return false;
4353 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00004354 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004355 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004356 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004357 return false;
4358 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00004359 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004360 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00004361 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004362 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004363 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00004364 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00004365 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00004366 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004367 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00004368 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004369 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00004370 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00004371 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004372 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00004373 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004374 return false;
David Majnemerf0f224d2015-11-11 21:57:16 +00004375 case ValID::t_None:
4376 if (!Ty->isTokenTy())
4377 return Error(ID.Loc, "invalid type for none constant");
4378 V = Constant::getNullValue(Ty);
4379 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004380 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00004381 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004382 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00004383
Chris Lattnerac161bf2009-01-02 07:01:27 +00004384 V = ID.ConstantVal;
4385 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004386 case ValID::t_ConstantStruct:
4387 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00004388 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004389 if (ST->getNumElements() != ID.UIntVal)
4390 return Error(ID.Loc,
4391 "initializer with struct type has wrong # elements");
4392 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4393 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004394
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004395 // Verify that the elements are compatible with the structtype.
4396 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4397 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4398 return Error(ID.Loc, "element " + Twine(i) +
4399 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004400
David Blaikieadbda4b2015-08-03 20:08:41 +00004401 V = ConstantStruct::get(
4402 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004403 } else
4404 return Error(ID.Loc, "constant expression type mismatch");
4405 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004406 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00004407 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004408}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004409
Alex Lorenzd2255952015-07-17 22:07:03 +00004410bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4411 C = nullptr;
4412 ValID ID;
4413 auto Loc = Lex.getLoc();
4414 if (ParseValID(ID, /*PFS=*/nullptr))
4415 return true;
4416 switch (ID.Kind) {
4417 case ValID::t_APSInt:
4418 case ValID::t_APFloat:
Alex Lorenzb9a68db2015-09-09 13:44:33 +00004419 case ValID::t_Undef:
Alex Lorenzd2255952015-07-17 22:07:03 +00004420 case ValID::t_Constant:
4421 case ValID::t_ConstantStruct:
4422 case ValID::t_PackedConstantStruct: {
4423 Value *V;
4424 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4425 return true;
4426 assert(isa<Constant>(V) && "Expected a constant value");
4427 C = cast<Constant>(V);
4428 return false;
4429 }
4430 default:
4431 return Error(Loc, "expected a constant value");
4432 }
4433}
4434
David Majnemer8a1c45d2015-12-12 05:38:55 +00004435bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004436 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004437 ValID ID;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004438 return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004439}
4440
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004441bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004442 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004443 return ParseType(Ty) ||
4444 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004445}
4446
Chris Lattner3ed871f2009-10-27 19:13:16 +00004447bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4448 PerFunctionState &PFS) {
4449 Value *V;
4450 Loc = Lex.getLoc();
4451 if (ParseTypeAndValue(V, PFS)) return true;
4452 if (!isa<BasicBlock>(V))
4453 return Error(Loc, "expected a basic block");
4454 BB = cast<BasicBlock>(V);
4455 return false;
4456}
4457
4458
Chris Lattnerac161bf2009-01-02 07:01:27 +00004459/// FunctionHeader
4460/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00004461/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
David Majnemer7fddecc2015-06-17 20:52:32 +00004462/// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00004463bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4464 // Parse the linkage.
4465 LocTy LinkageLoc = Lex.getLoc();
4466 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004467
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00004468 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00004469 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00004470 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004471 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004472 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004473 LocTy RetTypeLoc = Lex.getLoc();
4474 if (ParseOptionalLinkage(Linkage) ||
4475 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +00004476 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004477 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004478 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004479 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004480 return true;
4481
4482 // Verify that the linkage is ok.
4483 switch ((GlobalValue::LinkageTypes)Linkage) {
4484 case GlobalValue::ExternalLinkage:
4485 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00004486 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004487 if (isDefine)
4488 return Error(LinkageLoc, "invalid linkage for function definition");
4489 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00004490 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004491 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00004492 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00004493 case GlobalValue::LinkOnceAnyLinkage:
4494 case GlobalValue::LinkOnceODRLinkage:
4495 case GlobalValue::WeakAnyLinkage:
4496 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004497 if (!isDefine)
4498 return Error(LinkageLoc, "invalid linkage for function declaration");
4499 break;
4500 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00004501 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004502 return Error(LinkageLoc, "invalid function linkage type");
4503 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004504
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004505 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4506 return Error(LinkageLoc,
4507 "symbol with local linkage must have default visibility");
4508
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004509 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004510 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004511
Chris Lattnerac161bf2009-01-02 07:01:27 +00004512 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00004513
4514 std::string FunctionName;
4515 if (Lex.getKind() == lltok::GlobalVar) {
4516 FunctionName = Lex.getStrVal();
4517 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4518 unsigned NameID = Lex.getUIntVal();
4519
4520 if (NameID != NumberedVals.size())
4521 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004522 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00004523 } else {
4524 return TokError("expected function name");
4525 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004526
Chris Lattner3822f632009-01-02 08:05:26 +00004527 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004528
Chris Lattner3822f632009-01-02 08:05:26 +00004529 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004530 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004531
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004532 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004533 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00004534 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004535 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004536 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004537 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004538 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00004539 std::string GC;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004540 bool UnnamedAddr;
4541 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00004542 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004543 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00004544 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00004545 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00004546
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004547 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004548 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
4549 &UnnamedAddrLoc) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004550 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004551 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004552 (EatIfPresent(lltok::kw_section) &&
4553 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00004554 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004555 ParseOptionalAlignment(Alignment) ||
4556 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004557 ParseStringConstant(GC)) ||
4558 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004559 ParseGlobalTypeAndValue(Prefix)) ||
4560 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00004561 ParseGlobalTypeAndValue(Prologue)) ||
4562 (EatIfPresent(lltok::kw_personality) &&
4563 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00004564 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004565
Michael Gottesman41748d72013-06-27 00:25:01 +00004566 if (FuncAttrs.contains(Attribute::Builtin))
4567 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00004568
Chris Lattnerac161bf2009-01-02 07:01:27 +00004569 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00004570 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00004571 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004572 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004573 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004574
Chris Lattnerac161bf2009-01-02 07:01:27 +00004575 // Okay, if we got here, the function is syntactically valid. Convert types
4576 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00004577 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00004578 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004579
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004580 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004581 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4582 AttributeSet::ReturnIndex,
4583 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004584
Chris Lattnerac161bf2009-01-02 07:01:27 +00004585 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004586 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004587 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4588 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004589 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4590 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004591 }
4592
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004593 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004594 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4595 AttributeSet::FunctionIndex,
4596 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004597
Bill Wendlinge94d8432012-12-07 23:16:57 +00004598 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004599
Bill Wendling749a43d2012-12-30 13:50:49 +00004600 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004601 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4602
Chris Lattner229907c2011-07-18 04:54:35 +00004603 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00004604 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00004605 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004606
Craig Topper2617dcc2014-04-15 06:32:26 +00004607 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004608 if (!FunctionName.empty()) {
4609 // If this was a definition of a forward reference, remove the definition
4610 // from the forward reference table and fill in the forward ref.
David Blaikie9ebdc692015-09-21 21:07:50 +00004611 auto FRVI = ForwardRefVals.find(FunctionName);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004612 if (FRVI != ForwardRefVals.end()) {
4613 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00004614 if (!Fn)
4615 return Error(FRVI->second.second, "invalid forward reference to "
4616 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00004617 if (Fn->getType() != PFT)
4618 return Error(FRVI->second.second, "invalid forward reference to "
4619 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004620
Chris Lattnerac161bf2009-01-02 07:01:27 +00004621 ForwardRefVals.erase(FRVI);
4622 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00004623 // Reject redefinitions.
4624 return Error(NameLoc, "invalid redefinition of function '" +
4625 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00004626 } else if (M->getNamedValue(FunctionName)) {
4627 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004628 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004629
Dan Gohman399d6ae2009-08-29 23:37:49 +00004630 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004631 // If this is a definition of a forward referenced function, make sure the
4632 // types agree.
David Blaikie9ebdc692015-09-21 21:07:50 +00004633 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004634 if (I != ForwardRefValIDs.end()) {
4635 Fn = cast<Function>(I->second.first);
4636 if (Fn->getType() != PFT)
4637 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004638 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004639 ForwardRefValIDs.erase(I);
4640 }
4641 }
4642
Craig Topper2617dcc2014-04-15 06:32:26 +00004643 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004644 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4645 else // Move the forward-reference to the correct spot in the module.
4646 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4647
4648 if (FunctionName.empty())
4649 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004650
Chris Lattnerac161bf2009-01-02 07:01:27 +00004651 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4652 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00004653 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004654 Fn->setCallingConv(CC);
4655 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004656 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004657 Fn->setAlignment(Alignment);
4658 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00004659 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00004660 Fn->setPersonalityFn(PersonalityFn);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004661 if (!GC.empty()) Fn->setGC(GC.c_str());
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004662 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004663 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004664 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004665
Chris Lattnerac161bf2009-01-02 07:01:27 +00004666 // Add all of the arguments we parsed to the function.
4667 Function::arg_iterator ArgIt = Fn->arg_begin();
4668 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4669 // If the argument has a name, insert it into the argument symbol table.
4670 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004671
Chris Lattnerac161bf2009-01-02 07:01:27 +00004672 // Set the name, if it conflicted, it will be auto-renamed.
4673 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004674
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00004675 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004676 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4677 ArgList[i].Name + "'");
4678 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004679
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004680 if (isDefine)
4681 return false;
4682
Robin Morisset039781e2014-08-29 21:53:01 +00004683 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004684 ValID ID;
4685 if (FunctionName.empty()) {
4686 ID.Kind = ValID::t_GlobalID;
4687 ID.UIntVal = NumberedVals.size() - 1;
4688 } else {
4689 ID.Kind = ValID::t_GlobalName;
4690 ID.StrVal = FunctionName;
4691 }
4692 auto Blocks = ForwardRefBlockAddresses.find(ID);
4693 if (Blocks != ForwardRefBlockAddresses.end())
4694 return Error(Blocks->first.Loc,
4695 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004696 return false;
4697}
4698
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004699bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4700 ValID ID;
4701 if (FunctionNumber == -1) {
4702 ID.Kind = ValID::t_GlobalName;
4703 ID.StrVal = F.getName();
4704 } else {
4705 ID.Kind = ValID::t_GlobalID;
4706 ID.UIntVal = FunctionNumber;
4707 }
4708
4709 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4710 if (Blocks == P.ForwardRefBlockAddresses.end())
4711 return false;
4712
4713 for (const auto &I : Blocks->second) {
4714 const ValID &BBID = I.first;
4715 GlobalValue *GV = I.second;
4716
4717 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4718 "Expected local id or name");
4719 BasicBlock *BB;
4720 if (BBID.Kind == ValID::t_LocalName)
4721 BB = GetBB(BBID.StrVal, BBID.Loc);
4722 else
4723 BB = GetBB(BBID.UIntVal, BBID.Loc);
4724 if (!BB)
4725 return P.Error(BBID.Loc, "referenced value is not a basic block");
4726
4727 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4728 GV->eraseFromParent();
4729 }
4730
4731 P.ForwardRefBlockAddresses.erase(Blocks);
4732 return false;
4733}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004734
4735/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004736/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00004737bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00004738 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004739 return TokError("expected '{' in function body");
4740 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004741
Chris Lattner3432c622009-10-28 03:39:23 +00004742 int FunctionNumber = -1;
4743 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004744
Chris Lattner3432c622009-10-28 03:39:23 +00004745 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004746
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004747 // Resolve block addresses and allow basic blocks to be forward-declared
4748 // within this function.
4749 if (PFS.resolveForwardRefBlockAddresses())
4750 return true;
4751 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4752
Chris Lattnerbbddd962010-01-09 19:20:07 +00004753 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004754 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00004755 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004756
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004757 while (Lex.getKind() != lltok::rbrace &&
4758 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004759 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004760
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004761 while (Lex.getKind() != lltok::rbrace)
4762 if (ParseUseListOrder(&PFS))
4763 return true;
4764
Chris Lattnerac161bf2009-01-02 07:01:27 +00004765 // Eat the }.
4766 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004767
Chris Lattnerac161bf2009-01-02 07:01:27 +00004768 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00004769 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004770}
4771
4772/// ParseBasicBlock
4773/// ::= LabelStr? Instruction*
4774bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4775 // If this basic block starts out with a name, remember it.
4776 std::string Name;
4777 LocTy NameLoc = Lex.getLoc();
4778 if (Lex.getKind() == lltok::LabelStr) {
4779 Name = Lex.getStrVal();
4780 Lex.Lex();
4781 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004782
Chris Lattnerac161bf2009-01-02 07:01:27 +00004783 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00004784 if (!BB)
4785 return Error(NameLoc,
4786 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004787
Chris Lattnerac161bf2009-01-02 07:01:27 +00004788 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004789
Chris Lattnerac161bf2009-01-02 07:01:27 +00004790 // Parse the instructions in this block until we get a terminator.
4791 Instruction *Inst;
4792 do {
4793 // This instruction may have three possibilities for a name: a) none
4794 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4795 LocTy NameLoc = Lex.getLoc();
4796 int NameID = -1;
4797 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004798
Chris Lattnerac161bf2009-01-02 07:01:27 +00004799 if (Lex.getKind() == lltok::LocalVarID) {
4800 NameID = Lex.getUIntVal();
4801 Lex.Lex();
4802 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4803 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00004804 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004805 NameStr = Lex.getStrVal();
4806 Lex.Lex();
4807 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4808 return true;
4809 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004810
Chris Lattner77b89dc2009-12-30 05:23:43 +00004811 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00004812 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00004813 case InstError: return true;
4814 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004815 BB->getInstList().push_back(Inst);
4816
Chris Lattner77b89dc2009-12-30 05:23:43 +00004817 // With a normal result, we check to see if the instruction is followed by
4818 // a comma and metadata.
4819 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004820 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004821 return true;
4822 break;
4823 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004824 BB->getInstList().push_back(Inst);
4825
Chris Lattner77b89dc2009-12-30 05:23:43 +00004826 // If the instruction parser ate an extra comma at the end of it, it
4827 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004828 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004829 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004830 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00004831 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004832
Chris Lattnerac161bf2009-01-02 07:01:27 +00004833 // Set the name on the instruction.
4834 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4835 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004836
Chris Lattnerac161bf2009-01-02 07:01:27 +00004837 return false;
4838}
4839
4840//===----------------------------------------------------------------------===//
4841// Instruction Parsing.
4842//===----------------------------------------------------------------------===//
4843
4844/// ParseInstruction - Parse one of the many different instructions.
4845///
Chris Lattner77b89dc2009-12-30 05:23:43 +00004846int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4847 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004848 lltok::Kind Token = Lex.getKind();
4849 if (Token == lltok::Eof)
4850 return TokError("found end of file when expecting more instructions");
4851 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00004852 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004853 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004854
Chris Lattnerac161bf2009-01-02 07:01:27 +00004855 switch (Token) {
4856 default: return Error(Loc, "expected instruction opcode");
4857 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00004858 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004859 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
4860 case lltok::kw_br: return ParseBr(Inst, PFS);
4861 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004862 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004863 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00004864 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer654e1302015-07-31 17:58:14 +00004865 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
4866 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00004867 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
4868 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00004869 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004870 // Binary Operators.
4871 case lltok::kw_add:
4872 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004873 case lltok::kw_mul:
4874 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00004875 bool NUW = EatIfPresent(lltok::kw_nuw);
4876 bool NSW = EatIfPresent(lltok::kw_nsw);
4877 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004878
Chris Lattnera676c0f2011-02-07 16:40:21 +00004879 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004880
Chris Lattnera676c0f2011-02-07 16:40:21 +00004881 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4882 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4883 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004884 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004885 case lltok::kw_fadd:
4886 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00004887 case lltok::kw_fmul:
4888 case lltok::kw_fdiv:
4889 case lltok::kw_frem: {
4890 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4891 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4892 if (Res != 0)
4893 return Res;
4894 if (FMF.any())
4895 Inst->setFastMathFlags(FMF);
4896 return 0;
4897 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004898
Chris Lattner35315d02011-02-06 21:44:57 +00004899 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004900 case lltok::kw_udiv:
4901 case lltok::kw_lshr:
4902 case lltok::kw_ashr: {
4903 bool Exact = EatIfPresent(lltok::kw_exact);
4904
4905 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4906 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4907 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004908 }
4909
Chris Lattnerac161bf2009-01-02 07:01:27 +00004910 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00004911 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004912 case lltok::kw_and:
4913 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00004914 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00004915 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
4916 case lltok::kw_fcmp: {
4917 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4918 int Res = ParseCompare(Inst, PFS, KeywordVal);
4919 if (Res != 0)
4920 return Res;
4921 if (FMF.any())
4922 Inst->setFastMathFlags(FMF);
4923 return 0;
4924 }
4925
Chris Lattnerac161bf2009-01-02 07:01:27 +00004926 // Casts.
4927 case lltok::kw_trunc:
4928 case lltok::kw_zext:
4929 case lltok::kw_sext:
4930 case lltok::kw_fptrunc:
4931 case lltok::kw_fpext:
4932 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004933 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004934 case lltok::kw_uitofp:
4935 case lltok::kw_sitofp:
4936 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004937 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004938 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00004939 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004940 // Other.
4941 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00004942 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004943 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
4944 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
4945 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
4946 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00004947 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00004948 // Call.
4949 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
4950 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
4951 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00004952 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004953 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00004954 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00004955 case lltok::kw_load: return ParseLoad(Inst, PFS);
4956 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00004957 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
4958 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00004959 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004960 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
4961 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
4962 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
4963 }
4964}
4965
4966/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
4967bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004968 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004969 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00004970 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004971 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
4972 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
4973 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
4974 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
4975 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
4976 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
4977 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
4978 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
4979 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
4980 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
4981 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
4982 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
4983 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
4984 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
4985 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
4986 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
4987 }
4988 } else {
4989 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00004990 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004991 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
4992 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
4993 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
4994 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
4995 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
4996 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
4997 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
4998 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
4999 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5000 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5001 }
5002 }
5003 Lex.Lex();
5004 return false;
5005}
5006
5007//===----------------------------------------------------------------------===//
5008// Terminator Instructions.
5009//===----------------------------------------------------------------------===//
5010
5011/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00005012/// ::= 'ret' void (',' !dbg, !1)*
5013/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00005014bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005015 PerFunctionState &PFS) {
5016 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00005017 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00005018 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005019
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005020 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005021
Chris Lattnerfdd87902009-10-05 05:54:46 +00005022 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005023 if (!ResType->isVoidTy())
5024 return Error(TypeLoc, "value doesn't match function result type '" +
5025 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005026
Owen Anderson55f1c092009-08-13 21:58:54 +00005027 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005028 return false;
5029 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005030
Chris Lattnerac161bf2009-01-02 07:01:27 +00005031 Value *RV;
5032 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005033
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005034 if (ResType != RV->getType())
5035 return Error(TypeLoc, "value doesn't match function result type '" +
5036 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005037
Owen Anderson55f1c092009-08-13 21:58:54 +00005038 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00005039 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005040}
5041
5042
5043/// ParseBr
5044/// ::= 'br' TypeAndValue
5045/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5046bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5047 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005048 Value *Op0;
5049 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005050 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005051
Chris Lattnerac161bf2009-01-02 07:01:27 +00005052 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5053 Inst = BranchInst::Create(BB);
5054 return false;
5055 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005056
Owen Anderson55f1c092009-08-13 21:58:54 +00005057 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005058 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005059
Chris Lattnerac161bf2009-01-02 07:01:27 +00005060 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005061 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005062 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005063 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005064 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005065
Chris Lattner3ed871f2009-10-27 19:13:16 +00005066 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005067 return false;
5068}
5069
5070/// ParseSwitch
5071/// Instruction
5072/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5073/// JumpTable
5074/// ::= (TypeAndValue ',' TypeAndValue)*
5075bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5076 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005077 Value *Cond;
5078 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005079 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5080 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005081 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005082 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5083 return true;
5084
Duncan Sands19d0b472010-02-16 11:11:14 +00005085 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005086 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005087
Chris Lattnerac161bf2009-01-02 07:01:27 +00005088 // Parse the jump table pairs.
5089 SmallPtrSet<Value*, 32> SeenCases;
5090 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5091 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005092 Value *Constant;
5093 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005094
Chris Lattnerac161bf2009-01-02 07:01:27 +00005095 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5096 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005097 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005098 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005099
David Blaikie70573dc2014-11-19 07:49:26 +00005100 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005101 return Error(CondLoc, "duplicate case value in switch");
5102 if (!isa<ConstantInt>(Constant))
5103 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005104
Chris Lattner3ed871f2009-10-27 19:13:16 +00005105 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00005106 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005107
Chris Lattnerac161bf2009-01-02 07:01:27 +00005108 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005109
Chris Lattner3ed871f2009-10-27 19:13:16 +00005110 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005111 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5112 SI->addCase(Table[i].first, Table[i].second);
5113 Inst = SI;
5114 return false;
5115}
5116
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005117/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00005118/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005119/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5120bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005121 LocTy AddrLoc;
5122 Value *Address;
5123 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005124 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5125 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00005126 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005127
Duncan Sands19d0b472010-02-16 11:11:14 +00005128 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005129 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005130
Chris Lattner3ed871f2009-10-27 19:13:16 +00005131 // Parse the destination list.
5132 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005133
Chris Lattner3ed871f2009-10-27 19:13:16 +00005134 if (Lex.getKind() != lltok::rsquare) {
5135 BasicBlock *DestBB;
5136 if (ParseTypeAndBasicBlock(DestBB, PFS))
5137 return true;
5138 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005139
Chris Lattner3ed871f2009-10-27 19:13:16 +00005140 while (EatIfPresent(lltok::comma)) {
5141 if (ParseTypeAndBasicBlock(DestBB, PFS))
5142 return true;
5143 DestList.push_back(DestBB);
5144 }
5145 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005146
Chris Lattner3ed871f2009-10-27 19:13:16 +00005147 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5148 return true;
5149
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005150 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00005151 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5152 IBI->addDestination(DestList[i]);
5153 Inst = IBI;
5154 return false;
5155}
5156
5157
Chris Lattnerac161bf2009-01-02 07:01:27 +00005158/// ParseInvoke
5159/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5160/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5161bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5162 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00005163 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005164 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00005165 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005166 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005167 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005168 LocTy RetTypeLoc;
5169 ValID CalleeID;
5170 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005171 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005172
Chris Lattner3ed871f2009-10-27 19:13:16 +00005173 BasicBlock *NormalBB, *UnwindBB;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005174 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005175 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005176 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005177 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5178 NoBuiltinLoc) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005179 ParseOptionalOperandBundles(BundleList, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005180 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005181 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005182 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005183 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005184 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005185
Chris Lattnerac161bf2009-01-02 07:01:27 +00005186 // If RetType is a non-function pointer type, then this is the short syntax
5187 // for the call, which means that RetType is just the return type. Infer the
5188 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00005189 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5190 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005191 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005192 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005193 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5194 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005195
Chris Lattnerac161bf2009-01-02 07:01:27 +00005196 if (!FunctionType::isValidReturnType(RetType))
5197 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005198
Owen Anderson4056ca92009-07-29 22:17:13 +00005199 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005200 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005201
David Blaikie41ba2b42015-07-27 23:32:19 +00005202 CalleeID.FTy = Ty;
5203
Chris Lattnerac161bf2009-01-02 07:01:27 +00005204 // Look up the callee.
5205 Value *Callee;
David Blaikie445e3fb2015-04-24 19:32:54 +00005206 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5207 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005208
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005209 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005210 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005211 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005212 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5213 AttributeSet::ReturnIndex,
5214 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005215
Chris Lattnerac161bf2009-01-02 07:01:27 +00005216 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005217
Chris Lattnerac161bf2009-01-02 07:01:27 +00005218 // Loop through FunctionType's arguments and ensure they are specified
5219 // correctly. Also, gather any parameter attributes.
5220 FunctionType::param_iterator I = Ty->param_begin();
5221 FunctionType::param_iterator E = Ty->param_end();
5222 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005223 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005224 if (I != E) {
5225 ExpectedTy = *I++;
5226 } else if (!Ty->isVarArg()) {
5227 return Error(ArgList[i].Loc, "too many arguments specified");
5228 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005229
Chris Lattnerac161bf2009-01-02 07:01:27 +00005230 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5231 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005232 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005233 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005234 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5235 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005236 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5237 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005238 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005239
Chris Lattnerac161bf2009-01-02 07:01:27 +00005240 if (I != E)
5241 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005242
David Majnemer8d22abd2015-02-23 00:01:32 +00005243 if (FnAttrs.hasAttributes()) {
5244 if (FnAttrs.hasAlignmentAttr())
5245 return Error(CallLoc, "invoke instructions may not have an alignment");
5246
Bill Wendlingf5075a42013-01-27 02:24:02 +00005247 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5248 AttributeSet::FunctionIndex,
5249 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005250 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005251
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005252 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005253 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005254
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005255 InvokeInst *II =
5256 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005257 II->setCallingConv(CC);
5258 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005259 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005260 Inst = II;
5261 return false;
5262}
5263
Bill Wendlingf891bf82011-07-31 06:30:59 +00005264/// ParseResume
5265/// ::= 'resume' TypeAndValue
5266bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5267 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005268 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5269 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005270
Bill Wendlingf891bf82011-07-31 06:30:59 +00005271 ResumeInst *RI = ResumeInst::Create(Exn);
5272 Inst = RI;
5273 return false;
5274}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005275
David Majnemer654e1302015-07-31 17:58:14 +00005276bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5277 PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005278 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
David Majnemer654e1302015-07-31 17:58:14 +00005279 return true;
5280
5281 while (Lex.getKind() != lltok::rsquare) {
5282 // If this isn't the first argument, we need a comma.
5283 if (!Args.empty() &&
5284 ParseToken(lltok::comma, "expected ',' in argument list"))
5285 return true;
5286
5287 // Parse the argument.
5288 LocTy ArgLoc;
5289 Type *ArgTy = nullptr;
5290 if (ParseType(ArgTy, ArgLoc))
5291 return true;
5292
5293 Value *V;
5294 if (ArgTy->isMetadataTy()) {
5295 if (ParseMetadataAsValue(V, PFS))
5296 return true;
5297 } else {
5298 if (ParseValue(ArgTy, V, PFS))
5299 return true;
5300 }
5301 Args.push_back(V);
5302 }
5303
5304 Lex.Lex(); // Lex the ']'.
5305 return false;
5306}
5307
5308/// ParseCleanupRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005309/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
David Majnemer654e1302015-07-31 17:58:14 +00005310bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005311 Value *CleanupPad = nullptr;
David Majnemer654e1302015-07-31 17:58:14 +00005312
David Majnemer8a1c45d2015-12-12 05:38:55 +00005313 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5314 return true;
5315
5316 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005317 return true;
David Majnemer654e1302015-07-31 17:58:14 +00005318
5319 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5320 return true;
5321
5322 BasicBlock *UnwindBB = nullptr;
5323 if (Lex.getKind() == lltok::kw_to) {
5324 Lex.Lex();
5325 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5326 return true;
5327 } else {
5328 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5329 return true;
5330 }
5331 }
5332
David Majnemer8a1c45d2015-12-12 05:38:55 +00005333 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
David Majnemer654e1302015-07-31 17:58:14 +00005334 return false;
5335}
5336
5337/// ParseCatchRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005338/// ::= 'catchret' from Parent Value 'to' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005339bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005340 Value *CatchPad = nullptr;
David Majnemer0bc0eef2015-08-15 02:46:08 +00005341
David Majnemer8a1c45d2015-12-12 05:38:55 +00005342 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5343 return true;
5344
5345 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
David Majnemer0bc0eef2015-08-15 02:46:08 +00005346 return true;
5347
David Majnemer0bc0eef2015-08-15 02:46:08 +00005348 BasicBlock *BB;
5349 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5350 ParseTypeAndBasicBlock(BB, PFS))
5351 return true;
5352
David Majnemer8a1c45d2015-12-12 05:38:55 +00005353 Inst = CatchReturnInst::Create(CatchPad, BB);
5354 return false;
5355}
5356
5357/// ParseCatchSwitch
5358/// ::= 'catchswitch' within Parent
5359bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5360 Value *ParentPad;
5361 LocTy BBLoc;
5362
5363 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5364 return true;
5365
5366 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5367 Lex.getKind() != lltok::LocalVarID)
5368 return TokError("expected scope value for catchswitch");
5369
5370 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5371 return true;
5372
5373 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5374 return true;
5375
5376 SmallVector<BasicBlock *, 32> Table;
5377 do {
5378 BasicBlock *DestBB;
5379 if (ParseTypeAndBasicBlock(DestBB, PFS))
5380 return true;
5381 Table.push_back(DestBB);
5382 } while (EatIfPresent(lltok::comma));
5383
5384 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5385 return true;
5386
5387 if (ParseToken(lltok::kw_unwind,
5388 "expected 'unwind' after catchswitch scope"))
5389 return true;
5390
5391 BasicBlock *UnwindBB = nullptr;
5392 if (EatIfPresent(lltok::kw_to)) {
5393 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5394 return true;
5395 } else {
5396 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5397 return true;
5398 }
5399
5400 auto *CatchSwitch =
5401 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5402 for (BasicBlock *DestBB : Table)
5403 CatchSwitch->addHandler(DestBB);
5404 Inst = CatchSwitch;
David Majnemer654e1302015-07-31 17:58:14 +00005405 return false;
5406}
5407
5408/// ParseCatchPad
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005409/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005410bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005411 Value *CatchSwitch = nullptr;
5412
5413 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5414 return true;
5415
5416 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5417 return TokError("expected scope value for catchpad");
5418
5419 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5420 return true;
5421
David Majnemer654e1302015-07-31 17:58:14 +00005422 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005423 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005424 return true;
5425
David Majnemer8a1c45d2015-12-12 05:38:55 +00005426 Inst = CatchPadInst::Create(CatchSwitch, Args);
David Majnemer654e1302015-07-31 17:58:14 +00005427 return false;
5428}
5429
David Majnemer654e1302015-07-31 17:58:14 +00005430/// ParseCleanupPad
David Majnemer8a1c45d2015-12-12 05:38:55 +00005431/// ::= 'cleanuppad' within Parent ParamList
David Majnemer654e1302015-07-31 17:58:14 +00005432bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005433 Value *ParentPad = nullptr;
5434
5435 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5436 return true;
5437
5438 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5439 Lex.getKind() != lltok::LocalVarID)
5440 return TokError("expected scope value for cleanuppad");
5441
5442 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5443 return true;
5444
David Majnemer654e1302015-07-31 17:58:14 +00005445 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005446 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005447 return true;
5448
David Majnemer8a1c45d2015-12-12 05:38:55 +00005449 Inst = CleanupPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00005450 return false;
5451}
5452
Chris Lattnerac161bf2009-01-02 07:01:27 +00005453//===----------------------------------------------------------------------===//
5454// Binary Operators.
5455//===----------------------------------------------------------------------===//
5456
5457/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005458/// ::= ArithmeticOps TypeAndValue ',' Value
5459///
5460/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5461/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00005462bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005463 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005464 LocTy Loc; Value *LHS, *RHS;
5465 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5466 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5467 ParseValue(LHS->getType(), RHS, PFS))
5468 return true;
5469
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005470 bool Valid;
5471 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00005472 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005473 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00005474 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5475 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005476 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00005477 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5478 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005479 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005480
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005481 if (!Valid)
5482 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005483
Chris Lattnerac161bf2009-01-02 07:01:27 +00005484 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5485 return false;
5486}
5487
5488/// ParseLogical
5489/// ::= ArithmeticOps TypeAndValue ',' Value {
5490bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5491 unsigned Opc) {
5492 LocTy Loc; Value *LHS, *RHS;
5493 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5494 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5495 ParseValue(LHS->getType(), RHS, PFS))
5496 return true;
5497
Duncan Sands9dff9be2010-02-15 16:12:20 +00005498 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005499 return Error(Loc,"instruction requires integer or integer vector operands");
5500
5501 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5502 return false;
5503}
5504
5505
5506/// ParseCompare
5507/// ::= 'icmp' IPredicates TypeAndValue ',' Value
5508/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005509bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5510 unsigned Opc) {
5511 // Parse the integer/fp comparison predicate.
5512 LocTy Loc;
5513 unsigned Pred;
5514 Value *LHS, *RHS;
5515 if (ParseCmpPredicate(Pred, Opc) ||
5516 ParseTypeAndValue(LHS, Loc, PFS) ||
5517 ParseToken(lltok::comma, "expected ',' after compare value") ||
5518 ParseValue(LHS->getType(), RHS, PFS))
5519 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005520
Chris Lattnerac161bf2009-01-02 07:01:27 +00005521 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00005522 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005523 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005524 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005525 } else {
5526 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00005527 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00005528 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005529 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005530 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005531 }
5532 return false;
5533}
5534
5535//===----------------------------------------------------------------------===//
5536// Other Instructions.
5537//===----------------------------------------------------------------------===//
5538
5539
5540/// ParseCast
5541/// ::= CastOpc TypeAndValue 'to' Type
5542bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5543 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005544 LocTy Loc;
5545 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005546 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005547 if (ParseTypeAndValue(Op, Loc, PFS) ||
5548 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5549 ParseType(DestTy))
5550 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005551
Chris Lattner89d856e2009-03-01 00:53:13 +00005552 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5553 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005554 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005555 getTypeString(Op->getType()) + "' to '" +
5556 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00005557 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005558 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5559 return false;
5560}
5561
5562/// ParseSelect
5563/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5564bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5565 LocTy Loc;
5566 Value *Op0, *Op1, *Op2;
5567 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5568 ParseToken(lltok::comma, "expected ',' after select condition") ||
5569 ParseTypeAndValue(Op1, PFS) ||
5570 ParseToken(lltok::comma, "expected ',' after select value") ||
5571 ParseTypeAndValue(Op2, PFS))
5572 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005573
Chris Lattnerac161bf2009-01-02 07:01:27 +00005574 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5575 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005576
Chris Lattnerac161bf2009-01-02 07:01:27 +00005577 Inst = SelectInst::Create(Op0, Op1, Op2);
5578 return false;
5579}
5580
Chris Lattnerb55ab542009-01-05 08:18:44 +00005581/// ParseVA_Arg
5582/// ::= 'va_arg' TypeAndValue ',' Type
5583bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005584 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005585 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00005586 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005587 if (ParseTypeAndValue(Op, PFS) ||
5588 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00005589 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005590 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005591
Chris Lattnerb55ab542009-01-05 08:18:44 +00005592 if (!EltTy->isFirstClassType())
5593 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005594
5595 Inst = new VAArgInst(Op, EltTy);
5596 return false;
5597}
5598
5599/// ParseExtractElement
5600/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5601bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5602 LocTy Loc;
5603 Value *Op0, *Op1;
5604 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5605 ParseToken(lltok::comma, "expected ',' after extract value") ||
5606 ParseTypeAndValue(Op1, PFS))
5607 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005608
Chris Lattnerac161bf2009-01-02 07:01:27 +00005609 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5610 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005611
Eric Christopherc9742252009-07-25 02:28:41 +00005612 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005613 return false;
5614}
5615
5616/// ParseInsertElement
5617/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5618bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5619 LocTy Loc;
5620 Value *Op0, *Op1, *Op2;
5621 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5622 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5623 ParseTypeAndValue(Op1, PFS) ||
5624 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5625 ParseTypeAndValue(Op2, PFS))
5626 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005627
Chris Lattnerac161bf2009-01-02 07:01:27 +00005628 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00005629 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005630
Chris Lattnerac161bf2009-01-02 07:01:27 +00005631 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5632 return false;
5633}
5634
5635/// ParseShuffleVector
5636/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5637bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5638 LocTy Loc;
5639 Value *Op0, *Op1, *Op2;
5640 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5641 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5642 ParseTypeAndValue(Op1, PFS) ||
5643 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5644 ParseTypeAndValue(Op2, PFS))
5645 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005646
Chris Lattnerac161bf2009-01-02 07:01:27 +00005647 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00005648 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005649
Chris Lattnerac161bf2009-01-02 07:01:27 +00005650 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5651 return false;
5652}
5653
5654/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00005655/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005656int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005657 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005658 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005659
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005660 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005661 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5662 ParseValue(Ty, Op0, PFS) ||
5663 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005664 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005665 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5666 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005667
Chris Lattnerf4f03422009-12-30 05:27:33 +00005668 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005669 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5670 while (1) {
5671 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005672
Chris Lattner3822f632009-01-02 08:05:26 +00005673 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005674 break;
5675
Chris Lattnerf4f03422009-12-30 05:27:33 +00005676 if (Lex.getKind() == lltok::MetadataVar) {
5677 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00005678 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005679 }
Devang Patel8f842d32009-10-16 18:45:49 +00005680
Chris Lattner3822f632009-01-02 08:05:26 +00005681 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005682 ParseValue(Ty, Op0, PFS) ||
5683 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005684 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005685 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5686 return true;
5687 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005688
Chris Lattnerac161bf2009-01-02 07:01:27 +00005689 if (!Ty->isFirstClassType())
5690 return Error(TypeLoc, "phi node must have first class type");
5691
Jay Foad52131342011-03-30 11:28:46 +00005692 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005693 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5694 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5695 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005696 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005697}
5698
Bill Wendlingfae14752011-08-12 20:24:12 +00005699/// ParseLandingPad
5700/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5701/// Clause
5702/// ::= 'catch' TypeAndValue
5703/// ::= 'filter'
5704/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5705bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005706 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00005707
David Majnemer7fddecc2015-06-17 20:52:32 +00005708 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00005709 return true;
5710
David Majnemer7fddecc2015-06-17 20:52:32 +00005711 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00005712 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5713
5714 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5715 LandingPadInst::ClauseType CT;
5716 if (EatIfPresent(lltok::kw_catch))
5717 CT = LandingPadInst::Catch;
5718 else if (EatIfPresent(lltok::kw_filter))
5719 CT = LandingPadInst::Filter;
5720 else
5721 return TokError("expected 'catch' or 'filter' clause type");
5722
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005723 Value *V;
5724 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00005725 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00005726 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00005727
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00005728 // A 'catch' type expects a non-array constant. A filter clause expects an
5729 // array constant.
5730 if (CT == LandingPadInst::Catch) {
5731 if (isa<ArrayType>(V->getType()))
5732 Error(VLoc, "'catch' clause has an invalid type");
5733 } else {
5734 if (!isa<ArrayType>(V->getType()))
5735 Error(VLoc, "'filter' clause has an invalid type");
5736 }
5737
Owen Andersonf8f259d2015-03-09 07:13:42 +00005738 Constant *CV = dyn_cast<Constant>(V);
5739 if (!CV)
5740 return Error(VLoc, "clause argument must be a constant");
5741 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00005742 }
5743
Owen Andersonf8f259d2015-03-09 07:13:42 +00005744 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00005745 return false;
5746}
5747
Chris Lattnerac161bf2009-01-02 07:01:27 +00005748/// ParseCall
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005749/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
5750/// OptionalAttrs Type Value ParameterList OptionalAttrs
5751/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
5752/// OptionalAttrs Type Value ParameterList OptionalAttrs
5753/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
5754/// OptionalAttrs Type Value ParameterList OptionalAttrs
5755/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
5756/// OptionalAttrs Type Value ParameterList OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +00005757bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00005758 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00005759 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005760 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005761 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005762 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005763 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005764 LocTy RetTypeLoc;
5765 ValID CalleeID;
5766 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005767 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005768 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005769
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005770 if (TCK != CallInst::TCK_None &&
5771 ParseToken(lltok::kw_call,
5772 "expected 'tail call', 'musttail call', or 'notail call'"))
5773 return true;
5774
5775 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5776
5777 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005778 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005779 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00005780 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5781 PFS.getFunction().isVarArg()) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005782 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
5783 ParseOptionalOperandBundles(BundleList, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005784 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005785
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005786 if (FMF.any() && !RetType->isFPOrFPVectorTy())
5787 return Error(CallLoc, "fast-math-flags specified for call without "
5788 "floating-point scalar or vector return type");
5789
Chris Lattnerac161bf2009-01-02 07:01:27 +00005790 // If RetType is a non-function pointer type, then this is the short syntax
5791 // for the call, which means that RetType is just the return type. Infer the
5792 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00005793 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5794 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005795 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005796 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00005797 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5798 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005799
Chris Lattnerac161bf2009-01-02 07:01:27 +00005800 if (!FunctionType::isValidReturnType(RetType))
5801 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005802
Owen Anderson4056ca92009-07-29 22:17:13 +00005803 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005804 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005805
David Blaikie41ba2b42015-07-27 23:32:19 +00005806 CalleeID.FTy = Ty;
5807
Chris Lattnerac161bf2009-01-02 07:01:27 +00005808 // Look up the callee.
5809 Value *Callee;
David Blaikie23af6482015-04-16 23:24:18 +00005810 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5811 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005812
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005813 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005814 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005815 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005816 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5817 AttributeSet::ReturnIndex,
5818 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005819
Chris Lattnerac161bf2009-01-02 07:01:27 +00005820 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005821
Chris Lattnerac161bf2009-01-02 07:01:27 +00005822 // Loop through FunctionType's arguments and ensure they are specified
5823 // correctly. Also, gather any parameter attributes.
5824 FunctionType::param_iterator I = Ty->param_begin();
5825 FunctionType::param_iterator E = Ty->param_end();
5826 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005827 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005828 if (I != E) {
5829 ExpectedTy = *I++;
5830 } else if (!Ty->isVarArg()) {
5831 return Error(ArgList[i].Loc, "too many arguments specified");
5832 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005833
Chris Lattnerac161bf2009-01-02 07:01:27 +00005834 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5835 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005836 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005837 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005838 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5839 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005840 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5841 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005842 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005843
Chris Lattnerac161bf2009-01-02 07:01:27 +00005844 if (I != E)
5845 return Error(CallLoc, "not enough parameters specified for call");
5846
David Majnemer8d22abd2015-02-23 00:01:32 +00005847 if (FnAttrs.hasAttributes()) {
5848 if (FnAttrs.hasAlignmentAttr())
5849 return Error(CallLoc, "call instructions may not have an alignment");
5850
Bill Wendlingf5075a42013-01-27 02:24:02 +00005851 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5852 AttributeSet::FunctionIndex,
5853 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005854 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005855
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005856 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005857 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005858
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005859 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
Reid Kleckner5772b772014-04-24 20:14:34 +00005860 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005861 CI->setCallingConv(CC);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005862 if (FMF.any())
5863 CI->setFastMathFlags(FMF);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005864 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005865 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005866 Inst = CI;
5867 return false;
5868}
5869
5870//===----------------------------------------------------------------------===//
5871// Memory Instructions.
5872//===----------------------------------------------------------------------===//
5873
5874/// ParseAlloc
Manman Ren9bfd0d02016-04-01 21:41:15 +00005875/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
5876/// (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00005877int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005878 Value *Size = nullptr;
David Majnemera3b0eb22015-02-16 08:38:03 +00005879 LocTy SizeLoc, TyLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005880 unsigned Alignment = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00005881 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00005882
5883 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00005884 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
David Majnemerc4ab61c2014-03-09 06:41:58 +00005885
David Majnemera3b0eb22015-02-16 08:38:03 +00005886 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005887
David Majnemera3b0eb22015-02-16 08:38:03 +00005888 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5889 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00005890
Chris Lattnerb2f39502009-12-30 05:44:30 +00005891 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00005892 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00005893 if (Lex.getKind() == lltok::kw_align) {
5894 if (ParseOptionalAlignment(Alignment)) return true;
5895 } else if (Lex.getKind() == lltok::MetadataVar) {
5896 AteExtraComma = true;
5897 } else {
5898 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5899 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5900 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005901 }
5902 }
5903
Dan Gohman2140a742010-05-28 01:14:11 +00005904 if (Size && !Size->getType()->isIntegerTy())
5905 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005906
Reid Kleckner436c42e2014-01-17 23:58:17 +00005907 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5908 AI->setUsedWithInAlloca(IsInAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00005909 AI->setSwiftError(IsSwiftError);
Reid Kleckner436c42e2014-01-17 23:58:17 +00005910 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00005911 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005912}
5913
5914/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00005915/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005916/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00005917/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005918int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005919 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005920 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005921 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005922 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00005923 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedman59b66882011-08-09 23:02:53 +00005924 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005925
5926 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005927 isAtomic = true;
5928 Lex.Lex();
5929 }
5930
Chris Lattnerbc639292011-11-27 06:56:53 +00005931 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005932 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005933 isVolatile = true;
5934 Lex.Lex();
5935 }
5936
David Blaikie15d9a4c2015-04-06 20:59:48 +00005937 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00005938 LocTy ExplicitTypeLoc = Lex.getLoc();
5939 if (ParseType(Ty) ||
5940 ParseToken(lltok::comma, "expected comma after load's type") ||
5941 ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005942 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005943 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5944 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005945
David Blaikie15d9a4c2015-04-06 20:59:48 +00005946 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005947 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00005948 if (isAtomic && !Alignment)
5949 return Error(Loc, "atomic load must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00005950 if (Ordering == AtomicOrdering::Release ||
5951 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00005952 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005953
David Blaikiea79ac142015-02-27 21:17:42 +00005954 if (Ty != cast<PointerType>(Val->getType())->getElementType())
5955 return Error(ExplicitTypeLoc,
5956 "explicit pointee type doesn't match operand's pointee type");
5957
David Blaikie15d9a4c2015-04-06 20:59:48 +00005958 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00005959 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005960}
5961
5962/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00005963
5964/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
5965/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00005966/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005967int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005968 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005969 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005970 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005971 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00005972 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedman59b66882011-08-09 23:02:53 +00005973 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005974
5975 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005976 isAtomic = true;
5977 Lex.Lex();
5978 }
5979
Chris Lattnerbc639292011-11-27 06:56:53 +00005980 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005981 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005982 isVolatile = true;
5983 Lex.Lex();
5984 }
5985
Chris Lattnerac161bf2009-01-02 07:01:27 +00005986 if (ParseTypeAndValue(Val, Loc, PFS) ||
5987 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005988 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005989 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005990 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005991 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00005992
Duncan Sands19d0b472010-02-16 11:11:14 +00005993 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005994 return Error(PtrLoc, "store operand must be a pointer");
5995 if (!Val->getType()->isFirstClassType())
5996 return Error(Loc, "store operand must be a first class value");
5997 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5998 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00005999 if (isAtomic && !Alignment)
6000 return Error(Loc, "atomic store must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006001 if (Ordering == AtomicOrdering::Acquire ||
6002 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006003 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006004
Eli Friedman59b66882011-08-09 23:02:53 +00006005 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006006 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006007}
6008
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006009/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00006010/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6011/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00006012int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006013 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6014 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006015 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6016 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006017 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006018 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00006019 bool isWeak = false;
6020
6021 if (EatIfPresent(lltok::kw_weak))
6022 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00006023
6024 if (EatIfPresent(lltok::kw_volatile))
6025 isVolatile = true;
6026
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006027 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6028 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6029 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6030 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6031 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00006032 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
6033 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006034 return true;
6035
JF Bastien800f87a2016-04-06 21:19:33 +00006036 if (SuccessOrdering == AtomicOrdering::Unordered ||
6037 FailureOrdering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006038 return TokError("cmpxchg cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006039 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6040 return TokError("cmpxchg failure argument shall be no stronger than the "
6041 "success argument");
6042 if (FailureOrdering == AtomicOrdering::Release ||
6043 FailureOrdering == AtomicOrdering::AcquireRelease)
6044 return TokError(
6045 "cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006046 if (!Ptr->getType()->isPointerTy())
6047 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6048 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6049 return Error(CmpLoc, "compare value and pointer type do not match");
6050 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6051 return Error(NewLoc, "new value and pointer type do not match");
Philip Reames1960cfd2016-02-19 00:06:41 +00006052 if (!New->getType()->isFirstClassType())
6053 return Error(NewLoc, "cmpxchg operand must be a first class value");
Tim Northover420a2162014-06-13 14:24:07 +00006054 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
6055 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006056 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00006057 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006058 Inst = CXI;
6059 return AteExtraComma ? InstExtraComma : InstNormal;
6060}
6061
6062/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00006063/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6064/// 'singlethread'? AtomicOrdering
6065int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006066 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6067 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006068 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006069 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006070 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006071 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00006072
6073 if (EatIfPresent(lltok::kw_volatile))
6074 isVolatile = true;
6075
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006076 switch (Lex.getKind()) {
6077 default: return TokError("expected binary operation in atomicrmw");
6078 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6079 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6080 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6081 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6082 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6083 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6084 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6085 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6086 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6087 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6088 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6089 }
6090 Lex.Lex(); // Eat the operation.
6091
6092 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6093 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6094 ParseTypeAndValue(Val, ValLoc, PFS) ||
6095 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6096 return true;
6097
JF Bastien800f87a2016-04-06 21:19:33 +00006098 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006099 return TokError("atomicrmw cannot be unordered");
6100 if (!Ptr->getType()->isPointerTy())
6101 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6102 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6103 return Error(ValLoc, "atomicrmw value and pointer type do not match");
6104 if (!Val->getType()->isIntegerTy())
6105 return Error(ValLoc, "atomicrmw operand must be an integer");
6106 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6107 if (Size < 8 || (Size & (Size - 1)))
6108 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6109 " integer");
6110
6111 AtomicRMWInst *RMWI =
6112 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
6113 RMWI->setVolatile(isVolatile);
6114 Inst = RMWI;
6115 return AteExtraComma ? InstExtraComma : InstNormal;
6116}
6117
Eli Friedmanfee02c62011-07-25 23:16:38 +00006118/// ParseFence
6119/// ::= 'fence' 'singlethread'? AtomicOrdering
6120int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
JF Bastien800f87a2016-04-06 21:19:33 +00006121 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedmanfee02c62011-07-25 23:16:38 +00006122 SynchronizationScope Scope = CrossThread;
6123 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6124 return true;
6125
JF Bastien800f87a2016-04-06 21:19:33 +00006126 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006127 return TokError("fence cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006128 if (Ordering == AtomicOrdering::Monotonic)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006129 return TokError("fence cannot be monotonic");
6130
6131 Inst = new FenceInst(Context, Ordering, Scope);
6132 return InstNormal;
6133}
6134
Chris Lattnerac161bf2009-01-02 07:01:27 +00006135/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00006136/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006137int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006138 Value *Ptr = nullptr;
6139 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006140 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00006141
Dan Gohman16cbbe42009-07-29 15:58:36 +00006142 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00006143
David Blaikie79e6c742015-02-27 19:29:02 +00006144 Type *Ty = nullptr;
6145 LocTy ExplicitTypeLoc = Lex.getLoc();
6146 if (ParseType(Ty) ||
6147 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6148 ParseTypeAndValue(Ptr, Loc, PFS))
6149 return true;
6150
Eli Benderskyd9806682013-04-22 17:03:42 +00006151 Type *BaseType = Ptr->getType();
6152 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6153 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006154 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006155
David Blaikie8d757942015-03-09 23:08:44 +00006156 if (Ty != BasePointerType->getElementType())
6157 return Error(ExplicitTypeLoc,
6158 "explicit pointee type doesn't match operand's pointee type");
6159
Chris Lattnerac161bf2009-01-02 07:01:27 +00006160 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006161 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006162 // GEP returns a vector of pointers if at least one of parameters is a vector.
6163 // All vector parameters should have the same vector width.
6164 unsigned GEPWidth = BaseType->isVectorTy() ?
6165 BaseType->getVectorNumElements() : 0;
6166
Chris Lattner3822f632009-01-02 08:05:26 +00006167 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00006168 if (Lex.getKind() == lltok::MetadataVar) {
6169 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00006170 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006171 }
Chris Lattner3822f632009-01-02 08:05:26 +00006172 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006173 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006174 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006175
Nadav Rotem3924cb02011-12-05 06:29:09 +00006176 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006177 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6178 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00006179 return Error(EltLoc,
6180 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006181 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006182 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006183 Indices.push_back(Val);
6184 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006185
Craig Toppere3dcce92015-08-01 22:20:21 +00006186 SmallPtrSet<Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00006187 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00006188 return Error(Loc, "base element of getelementptr must be sized");
6189
David Blaikied33bad32015-04-17 22:32:13 +00006190 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006191 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00006192 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00006193 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00006194 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006195 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006196}
6197
6198/// ParseExtractValue
6199/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006200int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006201 Value *Val; LocTy Loc;
6202 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006203 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006204 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006205 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006206 return true;
6207
Chris Lattner392be582010-02-12 20:49:41 +00006208 if (!Val->getType()->isAggregateType())
6209 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006210
Jay Foad57aa6362011-07-13 10:26:04 +00006211 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006212 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00006213 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006214 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006215}
6216
6217/// ParseInsertValue
6218/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006219int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006220 Value *Val0, *Val1; LocTy Loc0, Loc1;
6221 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006222 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006223 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6224 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6225 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006226 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006227 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006228
Chris Lattner392be582010-02-12 20:49:41 +00006229 if (!Val0->getType()->isAggregateType())
6230 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006231
David Majnemer30074532015-02-11 07:43:58 +00006232 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6233 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006234 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00006235 if (IndexedType != Val1->getType())
6236 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6237 getTypeString(Val1->getType()) + "' instead of '" +
6238 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00006239 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006240 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006241}
Nick Lewycky49f89192009-04-04 07:22:01 +00006242
6243//===----------------------------------------------------------------------===//
6244// Embedded metadata.
6245//===----------------------------------------------------------------------===//
6246
6247/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006248/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006249/// Element
6250/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006251bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00006252 if (ParseToken(lltok::lbrace, "expected '{' here"))
6253 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006254
Dan Gohman1e0213a2010-07-13 19:33:27 +00006255 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006256 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00006257 return false;
6258
Nick Lewycky49f89192009-04-04 07:22:01 +00006259 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006260 // Null is a special case since it is typeless.
6261 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006262 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006263 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006264 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006265
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006266 Metadata *MD;
6267 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006268 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006269 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00006270 } while (EatIfPresent(lltok::comma));
6271
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006272 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00006273}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006274
6275//===----------------------------------------------------------------------===//
6276// Use-list order directives.
6277//===----------------------------------------------------------------------===//
6278bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6279 SMLoc Loc) {
6280 if (V->use_empty())
6281 return Error(Loc, "value has no uses");
6282
6283 unsigned NumUses = 0;
6284 SmallDenseMap<const Use *, unsigned, 16> Order;
6285 for (const Use &U : V->uses()) {
6286 if (++NumUses > Indexes.size())
6287 break;
6288 Order[&U] = Indexes[NumUses - 1];
6289 }
6290 if (NumUses < 2)
6291 return Error(Loc, "value only has one use");
6292 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6293 return Error(Loc, "wrong number of indexes, expected " +
6294 Twine(std::distance(V->use_begin(), V->use_end())));
6295
6296 V->sortUseList([&](const Use &L, const Use &R) {
6297 return Order.lookup(&L) < Order.lookup(&R);
6298 });
6299 return false;
6300}
6301
6302/// ParseUseListOrderIndexes
6303/// ::= '{' uint32 (',' uint32)+ '}'
6304bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6305 SMLoc Loc = Lex.getLoc();
6306 if (ParseToken(lltok::lbrace, "expected '{' here"))
6307 return true;
6308 if (Lex.getKind() == lltok::rbrace)
6309 return Lex.Error("expected non-empty list of uselistorder indexes");
6310
6311 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6312 // indexes should be distinct numbers in the range [0, size-1], and should
6313 // not be in order.
6314 unsigned Offset = 0;
6315 unsigned Max = 0;
6316 bool IsOrdered = true;
6317 assert(Indexes.empty() && "Expected empty order vector");
6318 do {
6319 unsigned Index;
6320 if (ParseUInt32(Index))
6321 return true;
6322
6323 // Update consistency checks.
6324 Offset += Index - Indexes.size();
6325 Max = std::max(Max, Index);
6326 IsOrdered &= Index == Indexes.size();
6327
6328 Indexes.push_back(Index);
6329 } while (EatIfPresent(lltok::comma));
6330
6331 if (ParseToken(lltok::rbrace, "expected '}' here"))
6332 return true;
6333
6334 if (Indexes.size() < 2)
6335 return Error(Loc, "expected >= 2 uselistorder indexes");
6336 if (Offset != 0 || Max >= Indexes.size())
6337 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6338 if (IsOrdered)
6339 return Error(Loc, "expected uselistorder indexes to change the order");
6340
6341 return false;
6342}
6343
6344/// ParseUseListOrder
6345/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6346bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6347 SMLoc Loc = Lex.getLoc();
6348 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6349 return true;
6350
6351 Value *V;
6352 SmallVector<unsigned, 16> Indexes;
6353 if (ParseTypeAndValue(V, PFS) ||
6354 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6355 ParseUseListOrderIndexes(Indexes))
6356 return true;
6357
6358 return sortUseListOrder(V, Indexes, Loc);
6359}
6360
6361/// ParseUseListOrderBB
6362/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6363bool LLParser::ParseUseListOrderBB() {
6364 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6365 SMLoc Loc = Lex.getLoc();
6366 Lex.Lex();
6367
6368 ValID Fn, Label;
6369 SmallVector<unsigned, 16> Indexes;
6370 if (ParseValID(Fn) ||
6371 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6372 ParseValID(Label) ||
6373 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6374 ParseUseListOrderIndexes(Indexes))
6375 return true;
6376
6377 // Check the function.
6378 GlobalValue *GV;
6379 if (Fn.Kind == ValID::t_GlobalName)
6380 GV = M->getNamedValue(Fn.StrVal);
6381 else if (Fn.Kind == ValID::t_GlobalID)
6382 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6383 else
6384 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6385 if (!GV)
6386 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6387 auto *F = dyn_cast<Function>(GV);
6388 if (!F)
6389 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6390 if (F->isDeclaration())
6391 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6392
6393 // Check the basic block.
6394 if (Label.Kind == ValID::t_LocalID)
6395 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6396 if (Label.Kind != ValID::t_LocalName)
6397 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
6398 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
6399 if (!V)
6400 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6401 if (!isa<BasicBlock>(V))
6402 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6403
6404 return sortUseListOrder(V, Indexes, Loc);
6405}