blob: 2725386f8da575f7a07da9f8fee662eb328b0cc4 [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
Manman Renb5d7ff42016-05-25 23:14:48 +0000215 UpgradeModuleFlags(*M);
216
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000217 if (!Slots)
218 return false;
219 // Initialize the slot mapping.
220 // Because by this point we've parsed and validated everything, we can "steal"
221 // the mapping from LLParser as it doesn't need it anymore.
222 Slots->GlobalValues = std::move(NumberedVals);
223 Slots->MetadataNodes = std::move(NumberedMetadata);
Alex Lorenz1de2acd2015-08-21 21:32:39 +0000224 for (const auto &I : NamedTypes)
225 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
226 for (const auto &I : NumberedTypes)
227 Slots->Types.insert(std::make_pair(I.first, I.second.first));
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000228
Chris Lattnerac161bf2009-01-02 07:01:27 +0000229 return false;
230}
231
232//===----------------------------------------------------------------------===//
233// Top-Level Entities
234//===----------------------------------------------------------------------===//
235
236bool LLParser::ParseTopLevelEntities() {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000237 while (1) {
238 switch (Lex.getKind()) {
239 default: return TokError("expected top-level entity");
240 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000241 case lltok::kw_declare: if (ParseDeclare()) return true; break;
242 case lltok::kw_define: if (ParseDefine()) return true; break;
243 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
244 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Teresa Johnson83c517c2016-03-30 18:15:08 +0000245 case lltok::kw_source_filename:
246 if (ParseSourceFileName())
247 return true;
248 break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000249 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000250 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000251 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000252 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000253 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000254 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000255 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000256 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Bill Wendlinga7c38772013-02-09 15:48:49 +0000257 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000258 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
259 case lltok::kw_uselistorder_bb:
260 if (ParseUseListOrderBB()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000261 }
262 }
263}
264
265
266/// toplevelentity
267/// ::= 'module' 'asm' STRINGCONSTANT
268bool LLParser::ParseModuleAsm() {
269 assert(Lex.getKind() == lltok::kw_module);
270 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000271
272 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000273 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
274 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000275
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000276 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000277 return false;
278}
279
280/// toplevelentity
281/// ::= 'target' 'triple' '=' STRINGCONSTANT
282/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
283bool LLParser::ParseTargetDefinition() {
284 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000285 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000286 switch (Lex.Lex()) {
287 default: return TokError("unknown target property");
288 case lltok::kw_triple:
289 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000290 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
291 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000292 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000293 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000294 return false;
295 case lltok::kw_datalayout:
296 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000297 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
298 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000299 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000300 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000301 return false;
302 }
303}
304
Bill Wendling706d3d62012-11-28 08:41:48 +0000305/// toplevelentity
Teresa Johnson83c517c2016-03-30 18:15:08 +0000306/// ::= 'source_filename' '=' STRINGCONSTANT
307bool LLParser::ParseSourceFileName() {
308 assert(Lex.getKind() == lltok::kw_source_filename);
309 std::string Str;
310 Lex.Lex();
311 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
312 ParseStringConstant(Str))
313 return true;
314 M->setSourceFileName(Str);
315 return false;
316}
317
318/// toplevelentity
Bill Wendling706d3d62012-11-28 08:41:48 +0000319/// ::= 'deplibs' '=' '[' ']'
320/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
321/// FIXME: Remove in 4.0. Currently parse, but ignore.
322bool LLParser::ParseDepLibs() {
323 assert(Lex.getKind() == lltok::kw_deplibs);
324 Lex.Lex();
325 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
326 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
327 return true;
328
329 if (EatIfPresent(lltok::rsquare))
330 return false;
331
332 do {
333 std::string Str;
334 if (ParseStringConstant(Str)) return true;
335 } while (EatIfPresent(lltok::comma));
336
337 return ParseToken(lltok::rsquare, "expected ']' at end of list");
338}
339
Dan Gohman466876b2009-08-12 23:32:33 +0000340/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000341/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000342bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000343 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000344 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000345 Lex.Lex(); // eat LocalVarID;
346
347 if (ParseToken(lltok::equal, "expected '=' after name") ||
348 ParseToken(lltok::kw_type, "expected 'type' after '='"))
349 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000350
Craig Topper2617dcc2014-04-15 06:32:26 +0000351 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000352 if (ParseStructDefinition(TypeLoc, "",
353 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000354
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000355 if (!isa<StructType>(Result)) {
356 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
357 if (Entry.first)
358 return Error(TypeLoc, "non-struct types may not be recursive");
359 Entry.first = Result;
360 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000361 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000362
Chris Lattnerac161bf2009-01-02 07:01:27 +0000363 return false;
364}
365
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000366
Chris Lattnerac161bf2009-01-02 07:01:27 +0000367/// toplevelentity
368/// ::= LocalVar '=' 'type' type
369bool LLParser::ParseNamedType() {
370 std::string Name = Lex.getStrVal();
371 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000372 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000373
Chris Lattner3822f632009-01-02 08:05:26 +0000374 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000375 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000376 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000377
Craig Topper2617dcc2014-04-15 06:32:26 +0000378 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000379 if (ParseStructDefinition(NameLoc, Name,
380 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000381
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000382 if (!isa<StructType>(Result)) {
383 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
384 if (Entry.first)
385 return Error(NameLoc, "non-struct types may not be recursive");
386 Entry.first = Result;
387 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000388 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000389
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000390 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000391}
392
393
394/// toplevelentity
395/// ::= 'declare' FunctionHeader
396bool LLParser::ParseDeclare() {
397 assert(Lex.getKind() == lltok::kw_declare);
398 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000399
Chris Lattnerac161bf2009-01-02 07:01:27 +0000400 Function *F;
401 return ParseFunctionHeader(F, false);
402}
403
404/// toplevelentity
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000405/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
Chris Lattnerac161bf2009-01-02 07:01:27 +0000406bool LLParser::ParseDefine() {
407 assert(Lex.getKind() == lltok::kw_define);
408 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000409
Chris Lattnerac161bf2009-01-02 07:01:27 +0000410 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000411 return ParseFunctionHeader(F, true) ||
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000412 ParseOptionalFunctionMetadata(*F) ||
Chris Lattner3822f632009-01-02 08:05:26 +0000413 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000414}
415
Chris Lattner3822f632009-01-02 08:05:26 +0000416/// ParseGlobalType
417/// ::= 'constant'
418/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000419bool LLParser::ParseGlobalType(bool &IsConstant) {
420 if (Lex.getKind() == lltok::kw_constant)
421 IsConstant = true;
422 else if (Lex.getKind() == lltok::kw_global)
423 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000424 else {
425 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000426 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000427 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000428 Lex.Lex();
429 return false;
430}
431
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000432bool LLParser::ParseOptionalUnnamedAddr(
433 GlobalVariable::UnnamedAddr &UnnamedAddr) {
434 if (EatIfPresent(lltok::kw_unnamed_addr))
435 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
436 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
437 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
438 else
439 UnnamedAddr = GlobalValue::UnnamedAddr::None;
440 return false;
441}
442
Dan Gohman466876b2009-08-12 23:32:33 +0000443/// ParseUnnamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000444/// OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000445/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
446/// ... -> global variable
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000447/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000448/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
449/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000450bool LLParser::ParseUnnamedGlobal() {
451 unsigned VarID = NumberedVals.size();
452 std::string Name;
453 LocTy NameLoc = Lex.getLoc();
454
455 // Handle the GlobalID form.
456 if (Lex.getKind() == lltok::GlobalID) {
457 if (Lex.getUIntVal() != VarID)
458 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000459 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000460 Lex.Lex(); // eat GlobalID;
461
462 if (ParseToken(lltok::equal, "expected '=' after name"))
463 return true;
464 }
465
466 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000467 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000468 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000469 GlobalVariable::UnnamedAddr UnnamedAddr;
Rafael Espindola2615c9e2016-05-12 12:37:52 +0000470 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000471 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000472 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000473
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000474 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000475 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000476 DLLStorageClass, TLM, UnnamedAddr);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000477
478 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
479 DLLStorageClass, TLM, UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000480}
481
Chris Lattnerac161bf2009-01-02 07:01:27 +0000482/// ParseNamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000483/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000484/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
485/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000486bool LLParser::ParseNamedGlobal() {
487 assert(Lex.getKind() == lltok::GlobalVar);
488 LocTy NameLoc = Lex.getLoc();
489 std::string Name = Lex.getStrVal();
490 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000491
Chris Lattnerac161bf2009-01-02 07:01:27 +0000492 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000493 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000494 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000495 GlobalVariable::UnnamedAddr UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000496 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
Rafael Espindola2615c9e2016-05-12 12:37:52 +0000497 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000498 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000499 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000500
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000501 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000502 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000503 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000504
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000505 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
506 DLLStorageClass, TLM, UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000507}
508
David Majnemerdad0a642014-06-27 18:19:56 +0000509bool LLParser::parseComdat() {
510 assert(Lex.getKind() == lltok::ComdatVar);
511 std::string Name = Lex.getStrVal();
512 LocTy NameLoc = Lex.getLoc();
513 Lex.Lex();
514
515 if (ParseToken(lltok::equal, "expected '=' here"))
516 return true;
517
518 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
519 return TokError("expected comdat type");
520
521 Comdat::SelectionKind SK;
522 switch (Lex.getKind()) {
523 default:
524 return TokError("unknown selection kind");
525 case lltok::kw_any:
526 SK = Comdat::Any;
527 break;
528 case lltok::kw_exactmatch:
529 SK = Comdat::ExactMatch;
530 break;
531 case lltok::kw_largest:
532 SK = Comdat::Largest;
533 break;
534 case lltok::kw_noduplicates:
535 SK = Comdat::NoDuplicates;
536 break;
537 case lltok::kw_samesize:
538 SK = Comdat::SameSize;
539 break;
540 }
541 Lex.Lex();
542
543 // See if the comdat was forward referenced, if so, use the comdat.
544 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
545 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
546 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
547 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
548
549 Comdat *C;
550 if (I != ComdatSymTab.end())
551 C = &I->second;
552 else
553 C = M->getOrInsertComdat(Name);
554 C->setSelectionKind(SK);
555
556 return false;
557}
558
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000559// MDString:
560// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000561bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000562 std::string Str;
563 if (ParseStringConstant(Str)) return true;
Chris Lattner1797fc72009-12-29 21:53:55 +0000564 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000565 return false;
566}
567
568// MDNode:
569// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000570bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000571 // !{ ..., !42, ... }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000572 LocTy IDLoc = Lex.getLoc();
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000573 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000574 if (ParseUInt32(MID))
575 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000576
Chris Lattner8eff0152010-04-01 05:14:45 +0000577 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000578 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000579 Result = NumberedMetadata[MID];
580 return false;
581 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000582
Chris Lattner8eff0152010-04-01 05:14:45 +0000583 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000584 auto &FwdRef = ForwardRefMDNodes[MID];
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000585 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000586
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000587 Result = FwdRef.first.get();
588 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000589 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000590}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000591
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000592/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000593/// !foo = !{ !1, !2 }
594bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000595 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000596 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000597 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000598
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000599 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000600 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000601 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000602 return true;
603
Dan Gohman2637cc12010-07-21 23:38:33 +0000604 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000605 if (Lex.getKind() != lltok::rbrace)
606 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000607 if (ParseToken(lltok::exclaim, "Expected '!' here"))
608 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000609
Craig Topper2617dcc2014-04-15 06:32:26 +0000610 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000611 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000612 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000613 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000614
Rafael Espindolac7818fb2015-05-26 20:37:36 +0000615 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Patelbe626972009-07-29 00:34:02 +0000616}
617
Devang Patel39e64d42009-07-01 19:21:12 +0000618/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000619/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000620bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000621 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000622 Lex.Lex();
623 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000624
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000625 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000626 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000627 ParseToken(lltok::equal, "expected '=' here"))
628 return true;
629
630 // Detect common error, from old metadata syntax.
631 if (Lex.getKind() == lltok::Type)
632 return TokError("unexpected type in metadata definition");
633
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000634 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000635 if (Lex.getKind() == lltok::MetadataVar) {
636 if (ParseSpecializedMDNode(Init, IsDistinct))
637 return true;
638 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
639 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000640 return true;
641
Chris Lattnerfc58af22009-12-30 04:51:58 +0000642 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000643 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000644 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000645 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000646 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000647
Chris Lattnerfc58af22009-12-30 04:51:58 +0000648 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
649 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000650 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000651 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000652 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000653 }
654
Devang Patel39e64d42009-07-01 19:21:12 +0000655 return false;
656}
657
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000658static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
659 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
660 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
661}
662
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000663/// parseIndirectSymbol:
Rafael Espindola464fe022014-07-30 22:51:54 +0000664/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
665/// OptionalDLLStorageClass OptionalThreadLocal
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000666/// OptionalUnnamedAddr 'alias|ifunc' IndirectSymbol
Rafael Espindola6b238632014-05-16 19:35:39 +0000667///
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000668/// IndirectSymbol
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000669/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000670///
Eric Christopher536f0a92015-05-28 23:07:39 +0000671/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000672///
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000673bool LLParser::parseIndirectSymbol(
674 const std::string &Name, LocTy NameLoc, unsigned L, unsigned Visibility,
675 unsigned DLLStorageClass, GlobalVariable::ThreadLocalMode TLM,
676 GlobalVariable::UnnamedAddr UnnamedAddr) {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000677 bool IsAlias;
678 if (Lex.getKind() == lltok::kw_alias)
679 IsAlias = true;
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000680 else if (Lex.getKind() == lltok::kw_ifunc)
681 IsAlias = false;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000682 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000683 llvm_unreachable("Not an alias or ifunc!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000684 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000685
Rafael Espindola78527052013-10-06 15:10:43 +0000686 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
687
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000688 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000689 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000690
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000691 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000692 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000693 "symbol with local linkage must have default visibility");
694
David Blaikie2f408302015-09-11 03:22:04 +0000695 Type *Ty;
696 LocTy ExplicitTypeLoc = Lex.getLoc();
697 if (ParseType(Ty) ||
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000698 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
David Blaikie2f408302015-09-11 03:22:04 +0000699 return true;
700
Rafael Espindola64c1e182014-06-03 02:41:57 +0000701 Constant *Aliasee;
702 LocTy AliaseeLoc = Lex.getLoc();
703 if (Lex.getKind() != lltok::kw_bitcast &&
704 Lex.getKind() != lltok::kw_getelementptr &&
705 Lex.getKind() != lltok::kw_addrspacecast &&
706 Lex.getKind() != lltok::kw_inttoptr) {
707 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000708 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000709 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000710 // The bitcast dest type is not present, it is implied by the dest type.
711 ValID ID;
712 if (ParseValID(ID))
713 return true;
714 if (ID.Kind != ValID::t_Constant)
715 return Error(AliaseeLoc, "invalid aliasee");
716 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000717 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000718
Rafael Espindola64c1e182014-06-03 02:41:57 +0000719 Type *AliaseeType = Aliasee->getType();
720 auto *PTy = dyn_cast<PointerType>(AliaseeType);
721 if (!PTy)
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000722 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
David Blaikie16a2f3e2015-09-14 18:01:59 +0000723 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000724
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000725 if (IsAlias && Ty != PTy->getElementType())
David Blaikie2f408302015-09-11 03:22:04 +0000726 return Error(
727 ExplicitTypeLoc,
728 "explicit pointee type doesn't match operand's pointee type");
729
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000730 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
731 return Error(
732 ExplicitTypeLoc,
733 "explicit pointee type should be a function type");
734
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000735 GlobalValue *GVal = nullptr;
736
737 // See if the alias was forward referenced, if so, prepare to replace the
738 // forward reference.
739 if (!Name.empty()) {
740 GVal = M->getNamedValue(Name);
741 if (GVal) {
742 if (!ForwardRefVals.erase(Name))
743 return Error(NameLoc, "redefinition of global '@" + Name + "'");
744 }
745 } else {
746 auto I = ForwardRefValIDs.find(NumberedVals.size());
747 if (I != ForwardRefValIDs.end()) {
748 GVal = I->second.first;
749 ForwardRefValIDs.erase(I);
750 }
751 }
752
Chris Lattnerac161bf2009-01-02 07:01:27 +0000753 // Okay, create the alias but do not insert it into the module yet.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000754 std::unique_ptr<GlobalIndirectSymbol> GA;
755 if (IsAlias)
756 GA.reset(GlobalAlias::create(Ty, AddrSpace,
757 (GlobalValue::LinkageTypes)Linkage, Name,
758 Aliasee, /*Parent*/ nullptr));
759 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000760 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
761 (GlobalValue::LinkageTypes)Linkage, Name,
762 Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000763 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000764 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000765 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000766 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000767
Rafael Espindola54fc2982015-06-17 17:53:31 +0000768 if (Name.empty())
769 NumberedVals.push_back(GA.get());
770
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000771 if (GVal) {
772 // Verify that types agree.
773 if (GVal->getType() != GA->getType())
774 return Error(
775 ExplicitTypeLoc,
776 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000777
Chris Lattnerac161bf2009-01-02 07:01:27 +0000778 // If they agree, just RAUW the old value with the alias and remove the
779 // forward ref info.
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000780 GVal->replaceAllUsesWith(GA.get());
781 GVal->eraseFromParent();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000782 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000783
Chris Lattnerac161bf2009-01-02 07:01:27 +0000784 // Insert into the module, we know its name won't collide now.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000785 if (IsAlias)
786 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
787 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000788 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000789 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000790
Rafael Espindolaaa273822014-05-09 21:49:17 +0000791 // The module owns this now
792 GA.release();
793
Chris Lattnerac161bf2009-01-02 07:01:27 +0000794 return false;
795}
796
797/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000798/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000799/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000800/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000801/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000802/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000803/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000804///
Eric Christopher536f0a92015-05-28 23:07:39 +0000805/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000806/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000807///
808bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
809 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000810 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000811 GlobalVariable::ThreadLocalMode TLM,
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000812 GlobalVariable::UnnamedAddr UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000813 if (!isValidVisibilityForLinkage(Visibility, Linkage))
814 return Error(NameLoc,
815 "symbol with local linkage must have default visibility");
816
Chris Lattnerac161bf2009-01-02 07:01:27 +0000817 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000818 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000819 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000820 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000821
Craig Topper2617dcc2014-04-15 06:32:26 +0000822 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000823 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000824 ParseOptionalToken(lltok::kw_externally_initialized,
825 IsExternallyInitialized,
826 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000827 ParseGlobalType(IsConstant) ||
828 ParseType(Ty, TyLoc))
829 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000830
Chris Lattnerac161bf2009-01-02 07:01:27 +0000831 // If the linkage is specified and is external, then no initializer is
832 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000833 Constant *Init = nullptr;
Rafael Espindola4787ba32016-05-11 13:51:39 +0000834 if (!HasLinkage ||
835 !GlobalValue::isValidDeclarationLinkage(
836 (GlobalValue::LinkageTypes)Linkage)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000837 if (ParseGlobalValue(Ty, Init))
838 return true;
839 }
840
David Majnemer49b3d9b2015-02-16 08:41:08 +0000841 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000842 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000843
David Majnemer598bd052014-12-09 05:56:09 +0000844 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000845
846 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000847 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000848 GVal = M->getNamedValue(Name);
849 if (GVal) {
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000850 if (!ForwardRefVals.erase(Name))
Chris Lattnere38317f2009-10-25 23:22:50 +0000851 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000852 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000853 } else {
David Blaikie9ebdc692015-09-21 21:07:50 +0000854 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000855 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000856 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000857 ForwardRefValIDs.erase(I);
858 }
859 }
860
David Majnemer598bd052014-12-09 05:56:09 +0000861 GlobalVariable *GV;
862 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000863 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
864 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000865 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000866 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +0000867 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000868 return Error(TyLoc,
869 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000870
David Majnemer598bd052014-12-09 05:56:09 +0000871 GV = cast<GlobalVariable>(GVal);
872
Chris Lattnerac161bf2009-01-02 07:01:27 +0000873 // Move the forward-reference to the correct spot in the module.
874 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
875 }
876
877 if (Name.empty())
878 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000879
Chris Lattnerac161bf2009-01-02 07:01:27 +0000880 // Set the parsed properties on the global.
881 if (Init)
882 GV->setInitializer(Init);
883 GV->setConstant(IsConstant);
884 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
885 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000886 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000887 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000888 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000889 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000890
Chris Lattnerac161bf2009-01-02 07:01:27 +0000891 // Parse attributes on the global.
892 while (Lex.getKind() == lltok::comma) {
893 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000894
Chris Lattnerac161bf2009-01-02 07:01:27 +0000895 if (Lex.getKind() == lltok::kw_section) {
896 Lex.Lex();
897 GV->setSection(Lex.getStrVal());
898 if (ParseToken(lltok::StringConstant, "expected global section string"))
899 return true;
900 } else if (Lex.getKind() == lltok::kw_align) {
901 unsigned Alignment;
902 if (ParseOptionalAlignment(Alignment)) return true;
903 GV->setAlignment(Alignment);
Peter Collingbournecceae7f2016-05-31 23:01:54 +0000904 } else if (Lex.getKind() == lltok::MetadataVar) {
905 if (ParseGlobalObjectMetadataAttachment(*GV))
906 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000907 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000908 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000909 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000910 return true;
911 if (C)
912 GV->setComdat(C);
913 else
914 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000915 }
916 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000917
Chris Lattnerac161bf2009-01-02 07:01:27 +0000918 return false;
919}
920
Bill Wendling63b88192013-02-06 06:52:58 +0000921/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000922/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000923bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000924 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000925 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000926 Lex.Lex();
927
David Majnemerb39e22b2014-12-09 18:33:57 +0000928 if (Lex.getKind() != lltok::AttrGrpID)
929 return TokError("expected attribute group id");
930
Bill Wendling63b88192013-02-06 06:52:58 +0000931 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000932 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000933 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000934 Lex.Lex();
935
936 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000937 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000938 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000939 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000940 ParseToken(lltok::rbrace, "expected end of attribute group"))
941 return true;
942
Bill Wendlingb32b0412013-02-08 06:32:06 +0000943 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000944 return Error(AttrGrpLoc, "attribute group has no attributes");
945
946 return false;
947}
948
Bill Wendling8b0321d2013-02-08 00:52:31 +0000949/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000950/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000951bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
952 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000953 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000954 bool HaveError = false;
955
956 B.clear();
957
Bill Wendling63b88192013-02-06 06:52:58 +0000958 while (true) {
959 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000960 if (Token == lltok::kw_builtin)
961 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +0000962 switch (Token) {
963 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000964 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +0000965 return Error(Lex.getLoc(), "unterminated attribute group");
966 case lltok::rbrace:
967 // Finished.
968 return false;
969
Bill Wendlingb32b0412013-02-08 06:32:06 +0000970 case lltok::AttrGrpID: {
971 // Allow a function to reference an attribute group:
972 //
973 // define void @foo() #1 { ... }
974 if (inAttrGrp)
975 HaveError |=
976 Error(Lex.getLoc(),
977 "cannot have an attribute group reference in an attribute group");
978
979 unsigned AttrGrpNum = Lex.getUIntVal();
980 if (inAttrGrp) break;
981
982 // Save the reference to the attribute group. We'll fill it in later.
983 FwdRefAttrGrps.push_back(AttrGrpNum);
984 break;
985 }
Bill Wendling63b88192013-02-06 06:52:58 +0000986 // Target-dependent attributes:
987 case lltok::StringConstant: {
Artur Pilipenko17376c42015-08-03 14:31:49 +0000988 if (ParseStringAttribute(B))
Bill Wendling63b88192013-02-06 06:52:58 +0000989 return true;
Bill Wendlingb1ea9802013-02-10 10:12:50 +0000990 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000991 }
992
993 // Target-independent attributes:
994 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +0000995 // As a hack, we allow function alignment to be initially parsed as an
996 // attribute on a function declaration/definition or added to an attribute
997 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +0000998 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000999 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001000 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001001 if (ParseToken(lltok::equal, "expected '=' here") ||
1002 ParseUInt32(Alignment))
1003 return true;
1004 } else {
1005 if (ParseOptionalAlignment(Alignment))
1006 return true;
1007 }
Bill Wendling63b88192013-02-06 06:52:58 +00001008 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001009 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001010 }
1011 case lltok::kw_alignstack: {
1012 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001013 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001014 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001015 if (ParseToken(lltok::equal, "expected '=' here") ||
1016 ParseUInt32(Alignment))
1017 return true;
1018 } else {
1019 if (ParseOptionalStackAlignment(Alignment))
1020 return true;
1021 }
Bill Wendling63b88192013-02-06 06:52:58 +00001022 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001023 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001024 }
George Burgess IV278199f2016-04-12 01:05:35 +00001025 case lltok::kw_allocsize: {
1026 unsigned ElemSizeArg;
1027 Optional<unsigned> NumElemsArg;
1028 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1029 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1030 return true;
1031 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1032 continue;
1033 }
Igor Laevsky39d662f2015-07-11 10:30:36 +00001034 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1035 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1036 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1037 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1038 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001039 case lltok::kw_inaccessiblememonly:
1040 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1041 case lltok::kw_inaccessiblemem_or_argmemonly:
1042 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001043 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1044 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1045 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1046 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1047 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1048 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1049 case lltok::kw_noimplicitfloat:
1050 B.addAttribute(Attribute::NoImplicitFloat); break;
1051 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1052 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1053 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1054 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
James Molloye6f87ca2015-11-06 10:32:53 +00001055 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001056 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1057 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1058 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1059 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1060 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1061 case lltok::kw_returns_twice:
1062 B.addAttribute(Attribute::ReturnsTwice); break;
1063 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1064 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1065 case lltok::kw_sspstrong:
1066 B.addAttribute(Attribute::StackProtectStrong); break;
1067 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1068 case lltok::kw_sanitize_address:
1069 B.addAttribute(Attribute::SanitizeAddress); break;
1070 case lltok::kw_sanitize_thread:
1071 B.addAttribute(Attribute::SanitizeThread); break;
1072 case lltok::kw_sanitize_memory:
1073 B.addAttribute(Attribute::SanitizeMemory); break;
1074 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001075
1076 // Error handling.
1077 case lltok::kw_inreg:
1078 case lltok::kw_signext:
1079 case lltok::kw_zeroext:
1080 HaveError |=
1081 Error(Lex.getLoc(),
1082 "invalid use of attribute on a function");
1083 break;
1084 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001085 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001086 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001087 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001088 case lltok::kw_nest:
1089 case lltok::kw_noalias:
1090 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001091 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001092 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001093 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001094 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001095 case lltok::kw_swiftself:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001096 HaveError |=
1097 Error(Lex.getLoc(),
1098 "invalid use of parameter-only attribute on a function");
1099 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001100 }
1101
1102 Lex.Lex();
1103 }
1104}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001105
1106//===----------------------------------------------------------------------===//
1107// GlobalValue Reference/Resolution Routines.
1108//===----------------------------------------------------------------------===//
1109
Karl Schimpf77729782015-09-03 18:06:44 +00001110static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1111 const std::string &Name) {
1112 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1113 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1114 else
1115 return new GlobalVariable(*M, PTy->getElementType(), false,
1116 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1117 nullptr, GlobalVariable::NotThreadLocal,
1118 PTy->getAddressSpace());
1119}
1120
Chris Lattnerac161bf2009-01-02 07:01:27 +00001121/// GetGlobalVal - Get a value with the specified name or ID, creating a
1122/// forward reference record if needed. This can return null if the value
1123/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001124GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001125 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001126 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001127 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001128 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001129 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001130 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001131
Chris Lattnerac161bf2009-01-02 07:01:27 +00001132 // Look this name up in the normal function symbol table.
1133 GlobalValue *Val =
1134 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001135
Chris Lattnerac161bf2009-01-02 07:01:27 +00001136 // If this is a forward reference for the value, see if we already created a
1137 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001138 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001139 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001140 if (I != ForwardRefVals.end())
1141 Val = I->second.first;
1142 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001143
Chris Lattnerac161bf2009-01-02 07:01:27 +00001144 // If we have the value in the symbol table or fwd-ref table, return it.
1145 if (Val) {
1146 if (Val->getType() == Ty) return Val;
1147 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001148 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001149 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001150 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001151
Chris Lattnerac161bf2009-01-02 07:01:27 +00001152 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001153 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001154 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1155 return FwdVal;
1156}
1157
Chris Lattner229907c2011-07-18 04:54:35 +00001158GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1159 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001160 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001161 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001162 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001163 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001164
Craig Topper2617dcc2014-04-15 06:32:26 +00001165 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001166
Chris Lattnerac161bf2009-01-02 07:01:27 +00001167 // If this is a forward reference for the value, see if we already created a
1168 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001169 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001170 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001171 if (I != ForwardRefValIDs.end())
1172 Val = I->second.first;
1173 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001174
Chris Lattnerac161bf2009-01-02 07:01:27 +00001175 // If we have the value in the symbol table or fwd-ref table, return it.
1176 if (Val) {
1177 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001178 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001179 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001180 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001181 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001182
Chris Lattnerac161bf2009-01-02 07:01:27 +00001183 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001184 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001185 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1186 return FwdVal;
1187}
1188
1189
1190//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001191// Comdat Reference/Resolution Routines.
1192//===----------------------------------------------------------------------===//
1193
1194Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1195 // Look this name up in the comdat symbol table.
1196 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1197 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1198 if (I != ComdatSymTab.end())
1199 return &I->second;
1200
1201 // Otherwise, create a new forward reference for this value and remember it.
1202 Comdat *C = M->getOrInsertComdat(Name);
1203 ForwardRefComdats[Name] = Loc;
1204 return C;
1205}
1206
1207
1208//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001209// Helper Routines.
1210//===----------------------------------------------------------------------===//
1211
1212/// ParseToken - If the current token has the specified kind, eat it and return
1213/// success. Otherwise, emit the specified error and return failure.
1214bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1215 if (Lex.getKind() != T)
1216 return TokError(ErrMsg);
1217 Lex.Lex();
1218 return false;
1219}
1220
Chris Lattner3822f632009-01-02 08:05:26 +00001221/// ParseStringConstant
1222/// ::= StringConstant
1223bool LLParser::ParseStringConstant(std::string &Result) {
1224 if (Lex.getKind() != lltok::StringConstant)
1225 return TokError("expected string constant");
1226 Result = Lex.getStrVal();
1227 Lex.Lex();
1228 return false;
1229}
1230
1231/// ParseUInt32
1232/// ::= uint32
1233bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001234 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1235 return TokError("expected integer");
1236 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1237 if (Val64 != unsigned(Val64))
1238 return TokError("expected 32-bit integer (too large)");
1239 Val = Val64;
1240 Lex.Lex();
1241 return false;
1242}
1243
Hal Finkelb0407ba2014-07-18 15:51:28 +00001244/// ParseUInt64
1245/// ::= uint64
1246bool LLParser::ParseUInt64(uint64_t &Val) {
1247 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1248 return TokError("expected integer");
1249 Val = Lex.getAPSIntVal().getLimitedValue();
1250 Lex.Lex();
1251 return false;
1252}
1253
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001254/// ParseTLSModel
1255/// := 'localdynamic'
1256/// := 'initialexec'
1257/// := 'localexec'
1258bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1259 switch (Lex.getKind()) {
1260 default:
1261 return TokError("expected localdynamic, initialexec or localexec");
1262 case lltok::kw_localdynamic:
1263 TLM = GlobalVariable::LocalDynamicTLSModel;
1264 break;
1265 case lltok::kw_initialexec:
1266 TLM = GlobalVariable::InitialExecTLSModel;
1267 break;
1268 case lltok::kw_localexec:
1269 TLM = GlobalVariable::LocalExecTLSModel;
1270 break;
1271 }
1272
1273 Lex.Lex();
1274 return false;
1275}
1276
1277/// ParseOptionalThreadLocal
1278/// := /*empty*/
1279/// := 'thread_local'
1280/// := 'thread_local' '(' tlsmodel ')'
1281bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1282 TLM = GlobalVariable::NotThreadLocal;
1283 if (!EatIfPresent(lltok::kw_thread_local))
1284 return false;
1285
1286 TLM = GlobalVariable::GeneralDynamicTLSModel;
1287 if (Lex.getKind() == lltok::lparen) {
1288 Lex.Lex();
1289 return ParseTLSModel(TLM) ||
1290 ParseToken(lltok::rparen, "expected ')' after thread local model");
1291 }
1292 return false;
1293}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001294
1295/// ParseOptionalAddrSpace
1296/// := /*empty*/
1297/// := 'addrspace' '(' uint32 ')'
1298bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1299 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001300 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001301 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001302 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001303 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001304 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001305}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001306
Artur Pilipenko17376c42015-08-03 14:31:49 +00001307/// ParseStringAttribute
1308/// := StringConstant
1309/// := StringConstant '=' StringConstant
1310bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1311 std::string Attr = Lex.getStrVal();
1312 Lex.Lex();
1313 std::string Val;
1314 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1315 return true;
1316 B.addAttribute(Attr, Val);
1317 return false;
1318}
1319
Bill Wendling34c2eb22012-12-04 23:40:58 +00001320/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1321bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1322 bool HaveError = false;
1323
1324 B.clear();
1325
1326 while (1) {
1327 lltok::Kind Token = Lex.getKind();
1328 switch (Token) {
1329 default: // End of attributes.
1330 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001331 case lltok::StringConstant: {
1332 if (ParseStringAttribute(B))
1333 return true;
1334 continue;
1335 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001336 case lltok::kw_align: {
1337 unsigned Alignment;
1338 if (ParseOptionalAlignment(Alignment))
1339 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001340 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001341 continue;
1342 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001343 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001344 case lltok::kw_dereferenceable: {
1345 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001346 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001347 return true;
1348 B.addDereferenceableAttr(Bytes);
1349 continue;
1350 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001351 case lltok::kw_dereferenceable_or_null: {
1352 uint64_t Bytes;
1353 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1354 return true;
1355 B.addDereferenceableOrNullAttr(Bytes);
1356 continue;
1357 }
Reid Klecknera534a382013-12-19 02:14:12 +00001358 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001359 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1360 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1361 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1362 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001363 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001364 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1365 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001366 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001367 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1368 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001369 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
Manman Renf46262e2016-03-29 17:37:21 +00001370 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001371 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001372
Stephen Lin7577ed52013-04-20 13:16:13 +00001373 case lltok::kw_alignstack:
1374 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001375 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001376 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001377 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001378 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001379 case lltok::kw_minsize:
1380 case lltok::kw_naked:
1381 case lltok::kw_nobuiltin:
1382 case lltok::kw_noduplicate:
1383 case lltok::kw_noimplicitfloat:
1384 case lltok::kw_noinline:
1385 case lltok::kw_nonlazybind:
1386 case lltok::kw_noredzone:
1387 case lltok::kw_noreturn:
1388 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001389 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001390 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001391 case lltok::kw_returns_twice:
1392 case lltok::kw_sanitize_address:
1393 case lltok::kw_sanitize_memory:
1394 case lltok::kw_sanitize_thread:
1395 case lltok::kw_ssp:
1396 case lltok::kw_sspreq:
1397 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001398 case lltok::kw_safestack:
Stephen Lin7577ed52013-04-20 13:16:13 +00001399 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001400 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1401 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001402 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001403
Bill Wendling34c2eb22012-12-04 23:40:58 +00001404 Lex.Lex();
1405 }
1406}
1407
1408/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1409bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1410 bool HaveError = false;
1411
1412 B.clear();
1413
1414 while (1) {
1415 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001416 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001417 default: // End of attributes.
1418 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001419 case lltok::StringConstant: {
1420 if (ParseStringAttribute(B))
1421 return true;
1422 continue;
1423 }
Hal Finkelb0407ba2014-07-18 15:51:28 +00001424 case lltok::kw_dereferenceable: {
1425 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001426 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001427 return true;
1428 B.addDereferenceableAttr(Bytes);
1429 continue;
1430 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001431 case lltok::kw_dereferenceable_or_null: {
1432 uint64_t Bytes;
1433 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1434 return true;
1435 B.addDereferenceableOrNullAttr(Bytes);
1436 continue;
1437 }
Artur Pilipenko84bc62f2015-09-18 12:33:31 +00001438 case lltok::kw_align: {
1439 unsigned Alignment;
1440 if (ParseOptionalAlignment(Alignment))
1441 return true;
1442 B.addAlignmentAttr(Alignment);
1443 continue;
1444 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001445 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1446 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001447 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001448 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1449 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001450
Bill Wendling34c2eb22012-12-04 23:40:58 +00001451 // Error handling.
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001452 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001453 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001454 case lltok::kw_nest:
1455 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001456 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001457 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001458 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001459 case lltok::kw_swiftself:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001460 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001461 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001462
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001463 case lltok::kw_alignstack:
1464 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001465 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001466 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001467 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001468 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001469 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001470 case lltok::kw_minsize:
1471 case lltok::kw_naked:
1472 case lltok::kw_nobuiltin:
1473 case lltok::kw_noduplicate:
1474 case lltok::kw_noimplicitfloat:
1475 case lltok::kw_noinline:
1476 case lltok::kw_nonlazybind:
1477 case lltok::kw_noredzone:
1478 case lltok::kw_noreturn:
1479 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001480 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001481 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001482 case lltok::kw_returns_twice:
1483 case lltok::kw_sanitize_address:
1484 case lltok::kw_sanitize_memory:
1485 case lltok::kw_sanitize_thread:
1486 case lltok::kw_ssp:
1487 case lltok::kw_sspreq:
1488 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001489 case lltok::kw_safestack:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001490 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001491 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001492 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001493
1494 case lltok::kw_readnone:
1495 case lltok::kw_readonly:
1496 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001497 }
1498
Chris Lattnerac161bf2009-01-02 07:01:27 +00001499 Lex.Lex();
1500 }
1501}
1502
Rafael Espindolac6269912016-05-10 17:16:45 +00001503static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1504 HasLinkage = true;
1505 switch (Kind) {
1506 default:
1507 HasLinkage = false;
1508 return GlobalValue::ExternalLinkage;
1509 case lltok::kw_private:
1510 return GlobalValue::PrivateLinkage;
1511 case lltok::kw_internal:
1512 return GlobalValue::InternalLinkage;
1513 case lltok::kw_weak:
1514 return GlobalValue::WeakAnyLinkage;
1515 case lltok::kw_weak_odr:
1516 return GlobalValue::WeakODRLinkage;
1517 case lltok::kw_linkonce:
1518 return GlobalValue::LinkOnceAnyLinkage;
1519 case lltok::kw_linkonce_odr:
1520 return GlobalValue::LinkOnceODRLinkage;
1521 case lltok::kw_available_externally:
1522 return GlobalValue::AvailableExternallyLinkage;
1523 case lltok::kw_appending:
1524 return GlobalValue::AppendingLinkage;
1525 case lltok::kw_common:
1526 return GlobalValue::CommonLinkage;
1527 case lltok::kw_extern_weak:
1528 return GlobalValue::ExternalWeakLinkage;
1529 case lltok::kw_external:
1530 return GlobalValue::ExternalLinkage;
1531 }
1532}
1533
Chris Lattnerac161bf2009-01-02 07:01:27 +00001534/// ParseOptionalLinkage
1535/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001536/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001537/// ::= 'internal'
1538/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001539/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001540/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001541/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001542/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001543/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001544/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001545/// ::= 'extern_weak'
1546/// ::= 'external'
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001547bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1548 unsigned &Visibility,
1549 unsigned &DLLStorageClass) {
Rafael Espindolac6269912016-05-10 17:16:45 +00001550 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1551 if (HasLinkage)
1552 Lex.Lex();
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001553 ParseOptionalVisibility(Visibility);
1554 ParseOptionalDLLStorageClass(DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001555 return false;
1556}
1557
1558/// ParseOptionalVisibility
1559/// ::= /*empty*/
1560/// ::= 'default'
1561/// ::= 'hidden'
1562/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001563///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001564void LLParser::ParseOptionalVisibility(unsigned &Res) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001565 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001566 default:
1567 Res = GlobalValue::DefaultVisibility;
1568 return;
1569 case lltok::kw_default:
1570 Res = GlobalValue::DefaultVisibility;
1571 break;
1572 case lltok::kw_hidden:
1573 Res = GlobalValue::HiddenVisibility;
1574 break;
1575 case lltok::kw_protected:
1576 Res = GlobalValue::ProtectedVisibility;
1577 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001578 }
1579 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001580}
1581
Nico Rieck7157bb72014-01-14 15:22:47 +00001582/// ParseOptionalDLLStorageClass
1583/// ::= /*empty*/
1584/// ::= 'dllimport'
1585/// ::= 'dllexport'
1586///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001587void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
Nico Rieck7157bb72014-01-14 15:22:47 +00001588 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001589 default:
1590 Res = GlobalValue::DefaultStorageClass;
1591 return;
1592 case lltok::kw_dllimport:
1593 Res = GlobalValue::DLLImportStorageClass;
1594 break;
1595 case lltok::kw_dllexport:
1596 Res = GlobalValue::DLLExportStorageClass;
1597 break;
Nico Rieck7157bb72014-01-14 15:22:47 +00001598 }
1599 Lex.Lex();
Nico Rieck7157bb72014-01-14 15:22:47 +00001600}
1601
Chris Lattnerac161bf2009-01-02 07:01:27 +00001602/// ParseOptionalCallingConv
1603/// ::= /*empty*/
1604/// ::= 'ccc'
1605/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001606/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001607/// ::= 'coldcc'
1608/// ::= 'x86_stdcallcc'
1609/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001610/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001611/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001612/// ::= 'arm_apcscc'
1613/// ::= 'arm_aapcscc'
1614/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001615/// ::= 'msp430_intrcc'
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001616/// ::= 'avr_intrcc'
1617/// ::= 'avr_signalcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001618/// ::= 'ptx_kernel'
1619/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001620/// ::= 'spir_func'
1621/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001622/// ::= 'x86_64_sysvcc'
1623/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001624/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001625/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001626/// ::= 'preserve_mostcc'
1627/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001628/// ::= 'ghccc'
Manman Renf8bdd882016-04-05 22:41:47 +00001629/// ::= 'swiftcc'
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001630/// ::= 'x86_intrcc'
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001631/// ::= 'hhvmcc'
1632/// ::= 'hhvm_ccc'
Manman Ren19c7bbe2015-12-04 17:40:13 +00001633/// ::= 'cxx_fast_tlscc'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001634/// ::= 'amdgpu_vs'
1635/// ::= 'amdgpu_tcs'
1636/// ::= 'amdgpu_tes'
1637/// ::= 'amdgpu_gs'
1638/// ::= 'amdgpu_ps'
1639/// ::= 'amdgpu_cs'
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001640/// ::= 'amdgpu_kernel'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001641/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001642///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001643bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001644 switch (Lex.getKind()) {
1645 default: CC = CallingConv::C; return false;
1646 case lltok::kw_ccc: CC = CallingConv::C; break;
1647 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1648 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1649 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1650 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001651 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001652 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001653 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1654 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1655 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001656 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001657 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1658 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001659 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1660 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001661 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1662 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001663 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001664 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1665 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001666 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001667 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001668 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1669 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001670 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Manman Renf8bdd882016-04-05 22:41:47 +00001671 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001672 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001673 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1674 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
Manman Ren19c7bbe2015-12-04 17:40:13 +00001675 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001676 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
1677 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1678 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1679 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001680 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001681 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001682 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001683 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001684 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001685 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001686
Chris Lattnerac161bf2009-01-02 07:01:27 +00001687 Lex.Lex();
1688 return false;
1689}
1690
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001691/// ParseMetadataAttachment
1692/// ::= !dbg !42
1693bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1694 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1695
1696 std::string Name = Lex.getStrVal();
1697 Kind = M->getMDKindID(Name);
1698 Lex.Lex();
1699
1700 return ParseMDNode(MD);
1701}
1702
Chris Lattner5c427632009-12-30 05:31:19 +00001703/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001704/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001705bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001706 do {
1707 if (Lex.getKind() != lltok::MetadataVar)
1708 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001709
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001710 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001711 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001712 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001713 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001714
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001715 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001716 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001717 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001718
Chris Lattner596760d2009-12-29 21:25:40 +00001719 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001720 } while (EatIfPresent(lltok::comma));
1721 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001722}
1723
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001724/// ParseGlobalObjectMetadataAttachment
1725/// ::= !dbg !57
1726bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1727 unsigned MDK;
1728 MDNode *N;
1729 if (ParseMetadataAttachment(MDK, N))
1730 return true;
1731
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001732 GO.addMetadata(MDK, *N);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001733 return false;
1734}
1735
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001736/// ParseOptionalFunctionMetadata
1737/// ::= (!dbg !57)*
1738bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001739 while (Lex.getKind() == lltok::MetadataVar)
1740 if (ParseGlobalObjectMetadataAttachment(F))
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001741 return true;
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001742 return false;
1743}
1744
Chris Lattnerac161bf2009-01-02 07:01:27 +00001745/// ParseOptionalAlignment
1746/// ::= /* empty */
1747/// ::= 'align' 4
1748bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1749 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001750 if (!EatIfPresent(lltok::kw_align))
1751 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001752 LocTy AlignLoc = Lex.getLoc();
1753 if (ParseUInt32(Alignment)) return true;
1754 if (!isPowerOf2_32(Alignment))
1755 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001756 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001757 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001758 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001759}
1760
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001761/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00001762/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001763/// ::= AttrKind '(' 4 ')'
1764///
1765/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1766bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1767 uint64_t &Bytes) {
1768 assert((AttrKind == lltok::kw_dereferenceable ||
1769 AttrKind == lltok::kw_dereferenceable_or_null) &&
1770 "contract!");
1771
Hal Finkelb0407ba2014-07-18 15:51:28 +00001772 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001773 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001774 return false;
1775 LocTy ParenLoc = Lex.getLoc();
1776 if (!EatIfPresent(lltok::lparen))
1777 return Error(ParenLoc, "expected '('");
1778 LocTy DerefLoc = Lex.getLoc();
1779 if (ParseUInt64(Bytes)) return true;
1780 ParenLoc = Lex.getLoc();
1781 if (!EatIfPresent(lltok::rparen))
1782 return Error(ParenLoc, "expected ')'");
1783 if (!Bytes)
1784 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1785 return false;
1786}
1787
Chris Lattnerb2f39502009-12-30 05:44:30 +00001788/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001789/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001790/// ::= ',' align 4
1791///
1792/// This returns with AteExtraComma set to true if it ate an excess comma at the
1793/// end.
1794bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1795 bool &AteExtraComma) {
1796 AteExtraComma = false;
1797 while (EatIfPresent(lltok::comma)) {
1798 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001799 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001800 AteExtraComma = true;
1801 return false;
1802 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001803
Chris Lattner95b0ff42010-04-23 00:50:50 +00001804 if (Lex.getKind() != lltok::kw_align)
1805 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001806
Chris Lattner95b0ff42010-04-23 00:50:50 +00001807 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001808 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001809
Devang Patelea8a4b92009-09-17 23:04:48 +00001810 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001811}
1812
George Burgess IV278199f2016-04-12 01:05:35 +00001813bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
1814 Optional<unsigned> &HowManyArg) {
1815 Lex.Lex();
1816
1817 auto StartParen = Lex.getLoc();
1818 if (!EatIfPresent(lltok::lparen))
1819 return Error(StartParen, "expected '('");
1820
1821 if (ParseUInt32(BaseSizeArg))
1822 return true;
1823
1824 if (EatIfPresent(lltok::comma)) {
1825 auto HowManyAt = Lex.getLoc();
1826 unsigned HowMany;
1827 if (ParseUInt32(HowMany))
1828 return true;
1829 if (HowMany == BaseSizeArg)
1830 return Error(HowManyAt,
1831 "'allocsize' indices can't refer to the same parameter");
1832 HowManyArg = HowMany;
1833 } else
1834 HowManyArg = None;
1835
1836 auto EndParen = Lex.getLoc();
1837 if (!EatIfPresent(lltok::rparen))
1838 return Error(EndParen, "expected ')'");
1839 return false;
1840}
1841
Eli Friedmanfee02c62011-07-25 23:16:38 +00001842/// ParseScopeAndOrdering
1843/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1844/// else: ::=
1845///
1846/// This sets Scope and Ordering to the parsed values.
1847bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1848 AtomicOrdering &Ordering) {
1849 if (!isAtomic)
1850 return false;
1851
1852 Scope = CrossThread;
1853 if (EatIfPresent(lltok::kw_singlethread))
1854 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001855
1856 return ParseOrdering(Ordering);
1857}
1858
1859/// ParseOrdering
1860/// ::= AtomicOrdering
1861///
1862/// This sets Ordering to the parsed value.
1863bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001864 switch (Lex.getKind()) {
1865 default: return TokError("Expected ordering on atomic instruction");
JF Bastien800f87a2016-04-06 21:19:33 +00001866 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
1867 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
1868 // Not specified yet:
1869 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
1870 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
1871 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
1872 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
1873 case lltok::kw_seq_cst:
1874 Ordering = AtomicOrdering::SequentiallyConsistent;
1875 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00001876 }
1877 Lex.Lex();
1878 return false;
1879}
1880
Charles Davisbe5557e2010-02-12 00:31:15 +00001881/// ParseOptionalStackAlignment
1882/// ::= /* empty */
1883/// ::= 'alignstack' '(' 4 ')'
1884bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1885 Alignment = 0;
1886 if (!EatIfPresent(lltok::kw_alignstack))
1887 return false;
1888 LocTy ParenLoc = Lex.getLoc();
1889 if (!EatIfPresent(lltok::lparen))
1890 return Error(ParenLoc, "expected '('");
1891 LocTy AlignLoc = Lex.getLoc();
1892 if (ParseUInt32(Alignment)) return true;
1893 ParenLoc = Lex.getLoc();
1894 if (!EatIfPresent(lltok::rparen))
1895 return Error(ParenLoc, "expected ')'");
1896 if (!isPowerOf2_32(Alignment))
1897 return Error(AlignLoc, "stack alignment is not a power of two");
1898 return false;
1899}
Devang Patelea8a4b92009-09-17 23:04:48 +00001900
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001901/// ParseIndexList - This parses the index list for an insert/extractvalue
1902/// instruction. This sets AteExtraComma in the case where we eat an extra
1903/// comma at the end of the line and find that it is followed by metadata.
1904/// Clients that don't allow metadata can call the version of this function that
1905/// only takes one argument.
1906///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001907/// ParseIndexList
1908/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001909///
1910bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1911 bool &AteExtraComma) {
1912 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001913
Chris Lattnerac161bf2009-01-02 07:01:27 +00001914 if (Lex.getKind() != lltok::comma)
1915 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001916
Chris Lattner3822f632009-01-02 08:05:26 +00001917 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001918 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00001919 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001920 AteExtraComma = true;
1921 return false;
1922 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001923 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001924 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001925 Indices.push_back(Idx);
1926 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001927
Chris Lattnerac161bf2009-01-02 07:01:27 +00001928 return false;
1929}
1930
1931//===----------------------------------------------------------------------===//
1932// Type Parsing.
1933//===----------------------------------------------------------------------===//
1934
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001935/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001936bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001937 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001938 switch (Lex.getKind()) {
1939 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001940 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001941 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001942 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001943 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001944 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001945 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001946 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001947 // Type ::= StructType
1948 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001949 return true;
1950 break;
1951 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001952 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001953 Lex.Lex(); // eat the lsquare.
1954 if (ParseArrayVectorType(Result, false))
1955 return true;
1956 break;
1957 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001958 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00001959 Lex.Lex();
1960 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001961 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00001962 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001963 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001964 } else if (ParseArrayVectorType(Result, true))
1965 return true;
1966 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001967 case lltok::LocalVar: {
1968 // Type ::= %foo
1969 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001970
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001971 // If the type hasn't been defined yet, create a forward definition and
1972 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001973 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001974 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001975 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001976 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001977 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001978 Lex.Lex();
1979 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001980 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001981
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001982 case lltok::LocalVarID: {
1983 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001984 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001985
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001986 // If the type hasn't been defined yet, create a forward definition and
1987 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001988 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001989 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001990 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001991 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001992 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001993 Lex.Lex();
1994 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001995 }
1996 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001997
1998 // Parse the type suffixes.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001999 while (1) {
2000 switch (Lex.getKind()) {
2001 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002002 default:
2003 if (!AllowVoid && Result->isVoidTy())
2004 return Error(TypeLoc, "void type only allowed for function results");
2005 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002006
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002007 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002008 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002009 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002010 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002011 if (Result->isVoidTy())
2012 return TokError("pointers to void are invalid - use i8* instead");
2013 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002014 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002015 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002016 Lex.Lex();
2017 break;
2018
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002019 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002020 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002021 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002022 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002023 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00002024 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002025 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002026 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002027 unsigned AddrSpace;
2028 if (ParseOptionalAddrSpace(AddrSpace) ||
2029 ParseToken(lltok::star, "expected '*' in address space"))
2030 return true;
2031
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002032 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002033 break;
2034 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002035
Chris Lattnerac161bf2009-01-02 07:01:27 +00002036 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2037 case lltok::lparen:
2038 if (ParseFunctionType(Result))
2039 return true;
2040 break;
2041 }
2042 }
2043}
2044
2045/// ParseParameterList
2046/// ::= '(' ')'
2047/// ::= '(' Arg (',' Arg)* ')'
2048/// Arg
2049/// ::= Type OptionalAttributes Value OptionalAttributes
2050bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00002051 PerFunctionState &PFS, bool IsMustTailCall,
2052 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002053 if (ParseToken(lltok::lparen, "expected '(' in call"))
2054 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002055
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002056 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002057 while (Lex.getKind() != lltok::rparen) {
2058 // If this isn't the first argument, we need a comma.
2059 if (!ArgList.empty() &&
2060 ParseToken(lltok::comma, "expected ',' in argument list"))
2061 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002062
Reid Kleckner83498642014-08-26 00:33:28 +00002063 // Parse an ellipsis if this is a musttail call in a variadic function.
2064 if (Lex.getKind() == lltok::dotdotdot) {
2065 const char *Msg = "unexpected ellipsis in argument list for ";
2066 if (!IsMustTailCall)
2067 return TokError(Twine(Msg) + "non-musttail call");
2068 if (!InVarArgsFunc)
2069 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2070 Lex.Lex(); // Lex the '...', it is purely for readability.
2071 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2072 }
2073
Chris Lattnerac161bf2009-01-02 07:01:27 +00002074 // Parse the argument.
2075 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00002076 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002077 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002078 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00002079 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002080 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00002081
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002082 if (ArgTy->isMetadataTy()) {
2083 if (ParseMetadataAsValue(V, PFS))
2084 return true;
2085 } else {
2086 // Otherwise, handle normal operands.
2087 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2088 return true;
2089 }
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002090 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
2091 AttrIndex++,
2092 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002093 }
2094
Reid Kleckner83498642014-08-26 00:33:28 +00002095 if (IsMustTailCall && InVarArgsFunc)
2096 return TokError("expected '...' at end of argument list for musttail call "
2097 "in varargs function");
2098
Chris Lattnerac161bf2009-01-02 07:01:27 +00002099 Lex.Lex(); // Lex the ')'.
2100 return false;
2101}
2102
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002103/// ParseOptionalOperandBundles
2104/// ::= /*empty*/
2105/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2106///
2107/// OperandBundle
2108/// ::= bundle-tag '(' ')'
2109/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2110///
2111/// bundle-tag ::= String Constant
2112bool LLParser::ParseOptionalOperandBundles(
2113 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2114 LocTy BeginLoc = Lex.getLoc();
2115 if (!EatIfPresent(lltok::lsquare))
2116 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002117
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002118 while (Lex.getKind() != lltok::rsquare) {
2119 // If this isn't the first operand bundle, we need a comma.
2120 if (!BundleList.empty() &&
2121 ParseToken(lltok::comma, "expected ',' in input list"))
2122 return true;
2123
2124 std::string Tag;
2125 if (ParseStringConstant(Tag))
2126 return true;
2127
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002128 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2129 return true;
2130
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002131 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002132 while (Lex.getKind() != lltok::rparen) {
2133 // If this isn't the first input, we need a comma.
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002134 if (!Inputs.empty() &&
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002135 ParseToken(lltok::comma, "expected ',' in input list"))
2136 return true;
2137
2138 Type *Ty = nullptr;
2139 Value *Input = nullptr;
2140 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2141 return true;
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002142 Inputs.push_back(Input);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002143 }
2144
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002145 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2146
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002147 Lex.Lex(); // Lex the ')'.
2148 }
2149
2150 if (BundleList.empty())
2151 return Error(BeginLoc, "operand bundle set must not be empty");
2152
2153 Lex.Lex(); // Lex the ']'.
2154 return false;
2155}
Chris Lattnerac161bf2009-01-02 07:01:27 +00002156
Chris Lattner2ed06b42009-01-05 18:34:07 +00002157/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002158/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00002159/// ::= '(' ArgTypeListI ')'
2160/// ArgTypeListI
2161/// ::= /*empty*/
2162/// ::= '...'
2163/// ::= ArgTypeList ',' '...'
2164/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00002165///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002166bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2167 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00002168 isVarArg = false;
2169 assert(Lex.getKind() == lltok::lparen);
2170 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002171
Chris Lattnerac161bf2009-01-02 07:01:27 +00002172 if (Lex.getKind() == lltok::rparen) {
2173 // empty
2174 } else if (Lex.getKind() == lltok::dotdotdot) {
2175 isVarArg = true;
2176 Lex.Lex();
2177 } else {
2178 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002179 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002180 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002181 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002182
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002183 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002184 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002185
Chris Lattnerfdd87902009-10-05 05:54:46 +00002186 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002187 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002188
Chris Lattnerdef19492011-06-17 06:36:20 +00002189 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002190 Name = Lex.getStrVal();
2191 Lex.Lex();
2192 }
Chris Lattner3822f632009-01-02 08:05:26 +00002193
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002194 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00002195 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002196
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002197 unsigned AttrIndex = 1;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002198 ArgList.emplace_back(TypeLoc, ArgTy, AttributeSet::get(ArgTy->getContext(),
2199 AttrIndex++, Attrs),
2200 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002201
Chris Lattner3822f632009-01-02 08:05:26 +00002202 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002203 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00002204 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002205 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002206 break;
2207 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002208
Chris Lattnerac161bf2009-01-02 07:01:27 +00002209 // Otherwise must be an argument type.
2210 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00002211 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00002212
Chris Lattnerfdd87902009-10-05 05:54:46 +00002213 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002214 return Error(TypeLoc, "argument can not have void type");
2215
Chris Lattnerdef19492011-06-17 06:36:20 +00002216 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002217 Name = Lex.getStrVal();
2218 Lex.Lex();
2219 } else {
2220 Name = "";
2221 }
Chris Lattner3822f632009-01-02 08:05:26 +00002222
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002223 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00002224 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002225
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002226 ArgList.emplace_back(
2227 TypeLoc, ArgTy,
2228 AttributeSet::get(ArgTy->getContext(), AttrIndex++, Attrs),
2229 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002230 }
2231 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002232
Chris Lattner3822f632009-01-02 08:05:26 +00002233 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002234}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002235
Chris Lattnerac161bf2009-01-02 07:01:27 +00002236/// ParseFunctionType
2237/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002238bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002239 assert(Lex.getKind() == lltok::lparen);
2240
Chris Lattnerce473c72009-01-05 08:04:33 +00002241 if (!FunctionType::isValidReturnType(Result))
2242 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002243
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002244 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002245 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002246 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002247 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002248
Chris Lattnerac161bf2009-01-02 07:01:27 +00002249 // Reject names on the arguments lists.
2250 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2251 if (!ArgList[i].Name.empty())
2252 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002253 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00002254 return Error(ArgList[i].Loc,
2255 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002256 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002257
Jay Foadb804a2b2011-07-12 14:06:48 +00002258 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002259 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002260 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002261
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002262 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002263 return false;
2264}
2265
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002266/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2267/// other structs.
2268bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2269 SmallVector<Type*, 8> Elts;
2270 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002271
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002272 Result = StructType::get(Context, Elts, Packed);
2273 return false;
2274}
2275
2276/// ParseStructDefinition - Parse a struct in a 'type' definition.
2277bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2278 std::pair<Type*, LocTy> &Entry,
2279 Type *&ResultTy) {
2280 // If the type was already defined, diagnose the redefinition.
2281 if (Entry.first && !Entry.second.isValid())
2282 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002283
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002284 // If we have opaque, just return without filling in the definition for the
2285 // struct. This counts as a definition as far as the .ll file goes.
2286 if (EatIfPresent(lltok::kw_opaque)) {
2287 // This type is being defined, so clear the location to indicate this.
2288 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002289
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002290 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002291 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002292 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002293 ResultTy = Entry.first;
2294 return false;
2295 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002296
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002297 // If the type starts with '<', then it is either a packed struct or a vector.
2298 bool isPacked = EatIfPresent(lltok::less);
2299
2300 // If we don't have a struct, then we have a random type alias, which we
2301 // accept for compatibility with old files. These types are not allowed to be
2302 // forward referenced and not allowed to be recursive.
2303 if (Lex.getKind() != lltok::lbrace) {
2304 if (Entry.first)
2305 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002306
Craig Topper2617dcc2014-04-15 06:32:26 +00002307 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002308 if (isPacked)
2309 return ParseArrayVectorType(ResultTy, true);
2310 return ParseType(ResultTy);
2311 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002312
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002313 // This type is being defined, so clear the location to indicate this.
2314 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002315
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002316 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002317 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002318 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002319
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002320 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002321
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002322 SmallVector<Type*, 8> Body;
2323 if (ParseStructBody(Body) ||
2324 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2325 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002326
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002327 STy->setBody(Body, isPacked);
2328 ResultTy = STy;
2329 return false;
2330}
2331
2332
Chris Lattnerac161bf2009-01-02 07:01:27 +00002333/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002334/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002335/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002336/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002337/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002338/// ::= '<' '{' Type (',' Type)* '}' '>'
2339bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002340 assert(Lex.getKind() == lltok::lbrace);
2341 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002342
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002343 // Handle the empty struct.
2344 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002345 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002346
Chris Lattnerf880ca22009-03-09 04:49:14 +00002347 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002348 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002349 if (ParseType(Ty)) return true;
2350 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002351
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002352 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002353 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002354
Chris Lattner3822f632009-01-02 08:05:26 +00002355 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002356 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002357 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002358
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002359 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002360 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002361
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002362 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002363 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002364
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002365 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002366}
2367
2368/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2369/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002370/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002371/// ::= '[' APSINTVAL 'x' Types ']'
2372/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002373bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002374 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2375 Lex.getAPSIntVal().getBitWidth() > 64)
2376 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002377
Chris Lattnerac161bf2009-01-02 07:01:27 +00002378 LocTy SizeLoc = Lex.getLoc();
2379 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002380 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002381
Chris Lattner3822f632009-01-02 08:05:26 +00002382 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2383 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002384
2385 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002386 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002387 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002388
Chris Lattner3822f632009-01-02 08:05:26 +00002389 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2390 "expected end of sequential type"))
2391 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002392
Chris Lattnerac161bf2009-01-02 07:01:27 +00002393 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002394 if (Size == 0)
2395 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002396 if ((unsigned)Size != Size)
2397 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002398 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002399 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002400 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002401 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002402 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002403 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002404 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002405 }
2406 return false;
2407}
2408
2409//===----------------------------------------------------------------------===//
2410// Function Semantic Analysis.
2411//===----------------------------------------------------------------------===//
2412
Chris Lattner3432c622009-10-28 03:39:23 +00002413LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2414 int functionNumber)
2415 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002416
2417 // Insert unnamed arguments into the NumberedVals list.
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +00002418 for (Argument &A : F.args())
2419 if (!A.hasName())
2420 NumberedVals.push_back(&A);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002421}
2422
2423LLParser::PerFunctionState::~PerFunctionState() {
2424 // If there were any forward referenced non-basicblock values, delete them.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002425
David Blaikie9ebdc692015-09-21 21:07:50 +00002426 for (const auto &P : ForwardRefVals) {
2427 if (isa<BasicBlock>(P.second.first))
2428 continue;
2429 P.second.first->replaceAllUsesWith(
2430 UndefValue::get(P.second.first->getType()));
2431 delete P.second.first;
2432 }
2433
2434 for (const auto &P : ForwardRefValIDs) {
2435 if (isa<BasicBlock>(P.second.first))
2436 continue;
2437 P.second.first->replaceAllUsesWith(
2438 UndefValue::get(P.second.first->getType()));
2439 delete P.second.first;
2440 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002441}
2442
Chris Lattner3432c622009-10-28 03:39:23 +00002443bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002444 if (!ForwardRefVals.empty())
2445 return P.Error(ForwardRefVals.begin()->second.second,
2446 "use of undefined value '%" + ForwardRefVals.begin()->first +
2447 "'");
2448 if (!ForwardRefValIDs.empty())
2449 return P.Error(ForwardRefValIDs.begin()->second.second,
2450 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002451 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002452 return false;
2453}
2454
2455
2456/// GetVal - Get a value with the specified name or ID, creating a
2457/// forward reference record if needed. This can return null if the value
2458/// exists but does not have the right type.
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002459Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
David Majnemer8a1c45d2015-12-12 05:38:55 +00002460 LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002461 // Look this name up in the normal function symbol table.
2462 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002463
Chris Lattnerac161bf2009-01-02 07:01:27 +00002464 // If this is a forward reference for the value, see if we already created a
2465 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002466 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002467 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002468 if (I != ForwardRefVals.end())
2469 Val = I->second.first;
2470 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002471
Chris Lattnerac161bf2009-01-02 07:01:27 +00002472 // If we have the value in the symbol table or fwd-ref table, return it.
2473 if (Val) {
2474 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002475 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002476 P.Error(Loc, "'%" + Name + "' is not a basic block");
2477 else
2478 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002479 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002480 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002481 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002482
Chris Lattnerac161bf2009-01-02 07:01:27 +00002483 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002484 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002485 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002486 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002487 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002488
Chris Lattnerac161bf2009-01-02 07:01:27 +00002489 // Otherwise, create a new forward reference for this value and remember it.
2490 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002491 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002492 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002493 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002494 FwdVal = new Argument(Ty, Name);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002495 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002496
Chris Lattnerac161bf2009-01-02 07:01:27 +00002497 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2498 return FwdVal;
2499}
2500
David Majnemer8a1c45d2015-12-12 05:38:55 +00002501Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002502 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002503 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002504
Chris Lattnerac161bf2009-01-02 07:01:27 +00002505 // If this is a forward reference for the value, see if we already created a
2506 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002507 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002508 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002509 if (I != ForwardRefValIDs.end())
2510 Val = I->second.first;
2511 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002512
Chris Lattnerac161bf2009-01-02 07:01:27 +00002513 // If we have the value in the symbol table or fwd-ref table, return it.
2514 if (Val) {
2515 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002516 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002517 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002518 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002519 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002520 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002521 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002522 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002523
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002524 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002525 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002526 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002527 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002528
Chris Lattnerac161bf2009-01-02 07:01:27 +00002529 // Otherwise, create a new forward reference for this value and remember it.
2530 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002531 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002532 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002533 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002534 FwdVal = new Argument(Ty);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002535 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002536
Chris Lattnerac161bf2009-01-02 07:01:27 +00002537 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2538 return FwdVal;
2539}
2540
2541/// SetInstName - After an instruction is parsed and inserted into its
2542/// basic block, this installs its name.
2543bool LLParser::PerFunctionState::SetInstName(int NameID,
2544 const std::string &NameStr,
2545 LocTy NameLoc, Instruction *Inst) {
2546 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002547 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002548 if (NameID != -1 || !NameStr.empty())
2549 return P.Error(NameLoc, "instructions returning void cannot have a name");
2550 return false;
2551 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002552
Chris Lattnerac161bf2009-01-02 07:01:27 +00002553 // If this was a numbered instruction, verify that the instruction is the
2554 // expected value and resolve any forward references.
2555 if (NameStr.empty()) {
2556 // If neither a name nor an ID was specified, just use the next ID.
2557 if (NameID == -1)
2558 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002559
Chris Lattnerac161bf2009-01-02 07:01:27 +00002560 if (unsigned(NameID) != NumberedVals.size())
2561 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002562 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002563
David Blaikie9ebdc692015-09-21 21:07:50 +00002564 auto FI = ForwardRefValIDs.find(NameID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002565 if (FI != ForwardRefValIDs.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002566 Value *Sentinel = FI->second.first;
2567 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002568 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002569 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002570
2571 Sentinel->replaceAllUsesWith(Inst);
2572 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002573 ForwardRefValIDs.erase(FI);
2574 }
2575
2576 NumberedVals.push_back(Inst);
2577 return false;
2578 }
2579
2580 // Otherwise, the instruction had a name. Resolve forward refs and set it.
David Blaikie9ebdc692015-09-21 21:07:50 +00002581 auto FI = ForwardRefVals.find(NameStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002582 if (FI != ForwardRefVals.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002583 Value *Sentinel = FI->second.first;
2584 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002585 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002586 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002587
2588 Sentinel->replaceAllUsesWith(Inst);
2589 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002590 ForwardRefVals.erase(FI);
2591 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002592
Chris Lattnerac161bf2009-01-02 07:01:27 +00002593 // Set the name on the instruction.
2594 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002595
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002596 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002597 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002598 NameStr + "'");
2599 return false;
2600}
2601
2602/// GetBB - Get a basic block with the specified name or ID, creating a
2603/// forward reference record if needed.
2604BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2605 LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002606 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2607 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002608}
2609
2610BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002611 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2612 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002613}
2614
2615/// DefineBB - Define the specified basic block, which is either named or
2616/// unnamed. If there is an error, this returns null otherwise it returns
2617/// the block being defined.
2618BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2619 LocTy Loc) {
2620 BasicBlock *BB;
2621 if (Name.empty())
2622 BB = GetBB(NumberedVals.size(), Loc);
2623 else
2624 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002625 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002626
Chris Lattnerac161bf2009-01-02 07:01:27 +00002627 // Move the block to the end of the function. Forward ref'd blocks are
2628 // inserted wherever they happen to be referenced.
2629 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002630
Chris Lattnerac161bf2009-01-02 07:01:27 +00002631 // Remove the block from forward ref sets.
2632 if (Name.empty()) {
2633 ForwardRefValIDs.erase(NumberedVals.size());
2634 NumberedVals.push_back(BB);
2635 } else {
2636 // BB forward references are already in the function symbol table.
2637 ForwardRefVals.erase(Name);
2638 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002639
Chris Lattnerac161bf2009-01-02 07:01:27 +00002640 return BB;
2641}
2642
2643//===----------------------------------------------------------------------===//
2644// Constants.
2645//===----------------------------------------------------------------------===//
2646
2647/// ParseValID - Parse an abstract value that doesn't necessarily have a
2648/// type implied. For example, if we parse "4" we don't know what integer type
2649/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002650/// sanity. PFS is used to convert function-local operands of metadata (since
2651/// metadata operands are not just parsed here but also converted to values).
2652/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002653bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002654 ID.Loc = Lex.getLoc();
2655 switch (Lex.getKind()) {
2656 default: return TokError("expected value token");
2657 case lltok::GlobalID: // @42
2658 ID.UIntVal = Lex.getUIntVal();
2659 ID.Kind = ValID::t_GlobalID;
2660 break;
2661 case lltok::GlobalVar: // @foo
2662 ID.StrVal = Lex.getStrVal();
2663 ID.Kind = ValID::t_GlobalName;
2664 break;
2665 case lltok::LocalVarID: // %42
2666 ID.UIntVal = Lex.getUIntVal();
2667 ID.Kind = ValID::t_LocalID;
2668 break;
2669 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002670 ID.StrVal = Lex.getStrVal();
2671 ID.Kind = ValID::t_LocalName;
2672 break;
2673 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002674 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002675 ID.Kind = ValID::t_APSInt;
2676 break;
2677 case lltok::APFloat:
2678 ID.APFloatVal = Lex.getAPFloatVal();
2679 ID.Kind = ValID::t_APFloat;
2680 break;
2681 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002682 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002683 ID.Kind = ValID::t_Constant;
2684 break;
2685 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002686 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002687 ID.Kind = ValID::t_Constant;
2688 break;
2689 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2690 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2691 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
David Majnemerf0f224d2015-11-11 21:57:16 +00002692 case lltok::kw_none: ID.Kind = ValID::t_None; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002693
Chris Lattnerac161bf2009-01-02 07:01:27 +00002694 case lltok::lbrace: {
2695 // ValID ::= '{' ConstVector '}'
2696 Lex.Lex();
2697 SmallVector<Constant*, 16> Elts;
2698 if (ParseGlobalValueVector(Elts) ||
2699 ParseToken(lltok::rbrace, "expected end of struct constant"))
2700 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002701
David Blaikieadbda4b2015-08-03 20:08:41 +00002702 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002703 ID.UIntVal = Elts.size();
David Blaikieadbda4b2015-08-03 20:08:41 +00002704 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2705 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002706 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002707 return false;
2708 }
2709 case lltok::less: {
2710 // ValID ::= '<' ConstVector '>' --> Vector.
2711 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2712 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002713 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002714
Chris Lattnerac161bf2009-01-02 07:01:27 +00002715 SmallVector<Constant*, 16> Elts;
2716 LocTy FirstEltLoc = Lex.getLoc();
2717 if (ParseGlobalValueVector(Elts) ||
2718 (isPackedStruct &&
2719 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2720 ParseToken(lltok::greater, "expected end of constant"))
2721 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002722
Chris Lattnerac161bf2009-01-02 07:01:27 +00002723 if (isPackedStruct) {
David Blaikieadbda4b2015-08-03 20:08:41 +00002724 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2725 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2726 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002727 ID.UIntVal = Elts.size();
2728 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002729 return false;
2730 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002731
Chris Lattnerac161bf2009-01-02 07:01:27 +00002732 if (Elts.empty())
2733 return Error(ID.Loc, "constant vector must not be empty");
2734
Duncan Sands9dff9be2010-02-15 16:12:20 +00002735 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002736 !Elts[0]->getType()->isFloatingPointTy() &&
2737 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002738 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002739 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002740
Chris Lattnerac161bf2009-01-02 07:01:27 +00002741 // Verify that all the vector elements have the same type.
2742 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2743 if (Elts[i]->getType() != Elts[0]->getType())
2744 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002745 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002746 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002747
Chris Lattner69229312011-02-15 00:14:00 +00002748 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002749 ID.Kind = ValID::t_Constant;
2750 return false;
2751 }
2752 case lltok::lsquare: { // Array Constant
2753 Lex.Lex();
2754 SmallVector<Constant*, 16> Elts;
2755 LocTy FirstEltLoc = Lex.getLoc();
2756 if (ParseGlobalValueVector(Elts) ||
2757 ParseToken(lltok::rsquare, "expected end of array constant"))
2758 return true;
2759
2760 // Handle empty element.
2761 if (Elts.empty()) {
2762 // Use undef instead of an array because it's inconvenient to determine
2763 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002764 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002765 return false;
2766 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002767
Chris Lattnerac161bf2009-01-02 07:01:27 +00002768 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002769 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002770 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002771
Owen Anderson4056ca92009-07-29 22:17:13 +00002772 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002773
Chris Lattnerac161bf2009-01-02 07:01:27 +00002774 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002775 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002776 if (Elts[i]->getType() != Elts[0]->getType())
2777 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002778 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002779 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002780 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002781
Jay Foad83be3612011-06-22 09:24:39 +00002782 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002783 ID.Kind = ValID::t_Constant;
2784 return false;
2785 }
2786 case lltok::kw_c: // c "foo"
2787 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002788 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2789 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002790 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2791 ID.Kind = ValID::t_Constant;
2792 return false;
2793
2794 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002795 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2796 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002797 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002798 Lex.Lex();
2799 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002800 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002801 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002802 ParseStringConstant(ID.StrVal) ||
2803 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002804 ParseToken(lltok::StringConstant, "expected constraint string"))
2805 return true;
2806 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002807 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002808 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002809 ID.Kind = ValID::t_InlineAsm;
2810 return false;
2811 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002812
Chris Lattner3432c622009-10-28 03:39:23 +00002813 case lltok::kw_blockaddress: {
2814 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2815 Lex.Lex();
2816
2817 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002818
Chris Lattner3432c622009-10-28 03:39:23 +00002819 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2820 ParseValID(Fn) ||
2821 ParseToken(lltok::comma, "expected comma in block address expression")||
2822 ParseValID(Label) ||
2823 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2824 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002825
Chris Lattner3432c622009-10-28 03:39:23 +00002826 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2827 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002828 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002829 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002830
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002831 // Try to find the function (but skip it if it's forward-referenced).
2832 GlobalValue *GV = nullptr;
2833 if (Fn.Kind == ValID::t_GlobalID) {
2834 if (Fn.UIntVal < NumberedVals.size())
2835 GV = NumberedVals[Fn.UIntVal];
2836 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2837 GV = M->getNamedValue(Fn.StrVal);
2838 }
2839 Function *F = nullptr;
2840 if (GV) {
2841 // Confirm that it's actually a function with a definition.
2842 if (!isa<Function>(GV))
2843 return Error(Fn.Loc, "expected function name in blockaddress");
2844 F = cast<Function>(GV);
2845 if (F->isDeclaration())
2846 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2847 }
2848
2849 if (!F) {
2850 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00002851 GlobalValue *&FwdRef =
David Blaikie871b4112015-08-03 20:55:00 +00002852 ForwardRefBlockAddresses.insert(std::make_pair(
2853 std::move(Fn),
2854 std::map<ValID, GlobalValue *>()))
David Blaikieb9cc6592015-03-04 01:40:07 +00002855 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2856 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002857 if (!FwdRef)
2858 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2859 GlobalValue::InternalLinkage, nullptr, "");
2860 ID.ConstantVal = FwdRef;
2861 ID.Kind = ValID::t_Constant;
2862 return false;
2863 }
2864
2865 // We found the function; now find the basic block. Don't use PFS, since we
2866 // might be inside a constant expression.
2867 BasicBlock *BB;
2868 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2869 if (Label.Kind == ValID::t_LocalID)
2870 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2871 else
2872 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2873 if (!BB)
2874 return Error(Label.Loc, "referenced value is not a basic block");
2875 } else {
2876 if (Label.Kind == ValID::t_LocalID)
2877 return Error(Label.Loc, "cannot take address of numeric label after "
2878 "the function is defined");
2879 BB = dyn_cast_or_null<BasicBlock>(
2880 F->getValueSymbolTable().lookup(Label.StrVal));
2881 if (!BB)
2882 return Error(Label.Loc, "referenced value is not a basic block");
2883 }
2884
2885 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002886 ID.Kind = ValID::t_Constant;
2887 return false;
2888 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002889
Chris Lattnerac161bf2009-01-02 07:01:27 +00002890 case lltok::kw_trunc:
2891 case lltok::kw_zext:
2892 case lltok::kw_sext:
2893 case lltok::kw_fptrunc:
2894 case lltok::kw_fpext:
2895 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002896 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002897 case lltok::kw_uitofp:
2898 case lltok::kw_sitofp:
2899 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002900 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002901 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002902 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002903 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002904 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002905 Constant *SrcVal;
2906 Lex.Lex();
2907 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2908 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002909 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002910 ParseType(DestTy) ||
2911 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2912 return true;
2913 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2914 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002915 getTypeString(SrcVal->getType()) + "' to '" +
2916 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002917 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002918 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002919 ID.Kind = ValID::t_Constant;
2920 return false;
2921 }
2922 case lltok::kw_extractvalue: {
2923 Lex.Lex();
2924 Constant *Val;
2925 SmallVector<unsigned, 4> Indices;
2926 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2927 ParseGlobalTypeAndValue(Val) ||
2928 ParseIndexList(Indices) ||
2929 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2930 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002931
Chris Lattner392be582010-02-12 20:49:41 +00002932 if (!Val->getType()->isAggregateType())
2933 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002934 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002935 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002936 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002937 ID.Kind = ValID::t_Constant;
2938 return false;
2939 }
2940 case lltok::kw_insertvalue: {
2941 Lex.Lex();
2942 Constant *Val0, *Val1;
2943 SmallVector<unsigned, 4> Indices;
2944 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2945 ParseGlobalTypeAndValue(Val0) ||
2946 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2947 ParseGlobalTypeAndValue(Val1) ||
2948 ParseIndexList(Indices) ||
2949 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2950 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002951 if (!Val0->getType()->isAggregateType())
2952 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00002953 Type *IndexedType =
2954 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2955 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002956 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00002957 if (IndexedType != Val1->getType())
2958 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2959 getTypeString(Val1->getType()) +
2960 "' instead of '" + getTypeString(IndexedType) +
2961 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00002962 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002963 ID.Kind = ValID::t_Constant;
2964 return false;
2965 }
2966 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002967 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002968 unsigned PredVal, Opc = Lex.getUIntVal();
2969 Constant *Val0, *Val1;
2970 Lex.Lex();
2971 if (ParseCmpPredicate(PredVal, Opc) ||
2972 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2973 ParseGlobalTypeAndValue(Val0) ||
2974 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2975 ParseGlobalTypeAndValue(Val1) ||
2976 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2977 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002978
Chris Lattnerac161bf2009-01-02 07:01:27 +00002979 if (Val0->getType() != Val1->getType())
2980 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002981
Chris Lattnerac161bf2009-01-02 07:01:27 +00002982 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002983
Chris Lattnerac161bf2009-01-02 07:01:27 +00002984 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002985 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002986 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002987 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002988 } else {
2989 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002990 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002991 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002992 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002993 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002994 }
2995 ID.Kind = ValID::t_Constant;
2996 return false;
2997 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002998
Chris Lattnerac161bf2009-01-02 07:01:27 +00002999 // Binary Operators.
3000 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00003001 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003002 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00003003 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003004 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00003005 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003006 case lltok::kw_udiv:
3007 case lltok::kw_sdiv:
3008 case lltok::kw_fdiv:
3009 case lltok::kw_urem:
3010 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003011 case lltok::kw_frem:
3012 case lltok::kw_shl:
3013 case lltok::kw_lshr:
3014 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003015 bool NUW = false;
3016 bool NSW = false;
3017 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003018 unsigned Opc = Lex.getUIntVal();
3019 Constant *Val0, *Val1;
3020 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00003021 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00003022 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3023 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003024 if (EatIfPresent(lltok::kw_nuw))
3025 NUW = true;
3026 if (EatIfPresent(lltok::kw_nsw)) {
3027 NSW = true;
3028 if (EatIfPresent(lltok::kw_nuw))
3029 NUW = true;
3030 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00003031 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3032 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003033 if (EatIfPresent(lltok::kw_exact))
3034 Exact = true;
3035 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003036 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3037 ParseGlobalTypeAndValue(Val0) ||
3038 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3039 ParseGlobalTypeAndValue(Val1) ||
3040 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3041 return true;
3042 if (Val0->getType() != Val1->getType())
3043 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003044 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003045 if (NUW)
3046 return Error(ModifierLoc, "nuw only applies to integer operations");
3047 if (NSW)
3048 return Error(ModifierLoc, "nsw only applies to integer operations");
3049 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00003050 // Check that the type is valid for the operator.
3051 switch (Opc) {
3052 case Instruction::Add:
3053 case Instruction::Sub:
3054 case Instruction::Mul:
3055 case Instruction::UDiv:
3056 case Instruction::SDiv:
3057 case Instruction::URem:
3058 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003059 case Instruction::Shl:
3060 case Instruction::AShr:
3061 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00003062 if (!Val0->getType()->isIntOrIntVectorTy())
3063 return Error(ID.Loc, "constexpr requires integer operands");
3064 break;
3065 case Instruction::FAdd:
3066 case Instruction::FSub:
3067 case Instruction::FMul:
3068 case Instruction::FDiv:
3069 case Instruction::FRem:
3070 if (!Val0->getType()->isFPOrFPVectorTy())
3071 return Error(ID.Loc, "constexpr requires fp operands");
3072 break;
3073 default: llvm_unreachable("Unknown binary operator!");
3074 }
Dan Gohman1b849082009-09-07 23:54:19 +00003075 unsigned Flags = 0;
3076 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3077 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00003078 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00003079 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00003080 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003081 ID.Kind = ValID::t_Constant;
3082 return false;
3083 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003084
Chris Lattnerac161bf2009-01-02 07:01:27 +00003085 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00003086 case lltok::kw_and:
3087 case lltok::kw_or:
3088 case lltok::kw_xor: {
3089 unsigned Opc = Lex.getUIntVal();
3090 Constant *Val0, *Val1;
3091 Lex.Lex();
3092 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3093 ParseGlobalTypeAndValue(Val0) ||
3094 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3095 ParseGlobalTypeAndValue(Val1) ||
3096 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3097 return true;
3098 if (Val0->getType() != Val1->getType())
3099 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003100 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003101 return Error(ID.Loc,
3102 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003103 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003104 ID.Kind = ValID::t_Constant;
3105 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003106 }
3107
Chris Lattnerac161bf2009-01-02 07:01:27 +00003108 case lltok::kw_getelementptr:
3109 case lltok::kw_shufflevector:
3110 case lltok::kw_insertelement:
3111 case lltok::kw_extractelement:
3112 case lltok::kw_select: {
3113 unsigned Opc = Lex.getUIntVal();
3114 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00003115 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00003116 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003117 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00003118
Dan Gohman1639c392009-07-27 21:53:46 +00003119 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00003120 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00003121
3122 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3123 return true;
3124
3125 LocTy ExplicitTypeLoc = Lex.getLoc();
3126 if (Opc == Instruction::GetElementPtr) {
3127 if (ParseType(Ty) ||
3128 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3129 return true;
3130 }
3131
3132 if (ParseGlobalValueVector(Elts) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003133 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3134 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003135
Chris Lattnerac161bf2009-01-02 07:01:27 +00003136 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00003137 if (Elts.size() == 0 ||
3138 !Elts[0]->getType()->getScalarType()->isPointerTy())
David Majnemer00303b62015-02-22 23:14:52 +00003139 return Error(ID.Loc, "base of getelementptr must be a pointer");
3140
3141 Type *BaseType = Elts[0]->getType();
3142 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00003143 if (Ty != BasePointerType->getElementType())
3144 return Error(
3145 ExplicitTypeLoc,
3146 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003147
Jay Foaded8db7d2011-07-21 14:31:17 +00003148 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00003149 for (Constant *Val : Indices) {
3150 Type *ValTy = Val->getType();
3151 if (!ValTy->getScalarType()->isIntegerTy())
3152 return Error(ID.Loc, "getelementptr index must be an integer");
3153 if (ValTy->isVectorTy() != BaseType->isVectorTy())
3154 return Error(ID.Loc, "getelementptr index type missmatch");
3155 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00003156 unsigned ValNumEl = ValTy->getVectorNumElements();
3157 unsigned PtrNumEl = BaseType->getVectorNumElements();
David Majnemer00303b62015-02-22 23:14:52 +00003158 if (ValNumEl != PtrNumEl)
3159 return Error(
3160 ID.Loc,
3161 "getelementptr vector index has a wrong number of elements");
3162 }
3163 }
3164
Craig Toppere3dcce92015-08-01 22:20:21 +00003165 SmallPtrSet<Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00003166 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00003167 return Error(ID.Loc, "base element of getelementptr must be sized");
3168
David Blaikie4a2e73b2015-04-02 18:55:32 +00003169 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00003170 return Error(ID.Loc, "invalid getelementptr indices");
David Blaikie4a2e73b2015-04-02 18:55:32 +00003171 ID.ConstantVal =
3172 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003173 } else if (Opc == Instruction::Select) {
3174 if (Elts.size() != 3)
3175 return Error(ID.Loc, "expected three operands to select");
3176 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3177 Elts[2]))
3178 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00003179 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003180 } else if (Opc == Instruction::ShuffleVector) {
3181 if (Elts.size() != 3)
3182 return Error(ID.Loc, "expected three operands to shufflevector");
3183 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3184 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00003185 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003186 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003187 } else if (Opc == Instruction::ExtractElement) {
3188 if (Elts.size() != 2)
3189 return Error(ID.Loc, "expected two operands to extractelement");
3190 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3191 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003192 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003193 } else {
3194 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3195 if (Elts.size() != 3)
3196 return Error(ID.Loc, "expected three operands to insertelement");
3197 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3198 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00003199 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003200 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003201 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003202
Chris Lattnerac161bf2009-01-02 07:01:27 +00003203 ID.Kind = ValID::t_Constant;
3204 return false;
3205 }
3206 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003207
Chris Lattnerac161bf2009-01-02 07:01:27 +00003208 Lex.Lex();
3209 return false;
3210}
3211
3212/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00003213bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003214 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003215 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00003216 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003217 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00003218 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003219 if (V && !(C = dyn_cast<Constant>(V)))
3220 return Error(ID.Loc, "global values must be constants");
3221 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003222}
3223
Victor Hernandez9d75c962010-01-11 22:31:58 +00003224bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003225 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003226 return ParseType(Ty) ||
3227 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003228}
3229
Rafael Espindola83a362c2015-01-06 22:55:16 +00003230bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00003231 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003232
3233 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00003234 if (!EatIfPresent(lltok::kw_comdat))
3235 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003236
3237 if (EatIfPresent(lltok::lparen)) {
3238 if (Lex.getKind() != lltok::ComdatVar)
3239 return TokError("expected comdat variable");
3240 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3241 Lex.Lex();
3242 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3243 return true;
3244 } else {
3245 if (GlobalName.empty())
3246 return TokError("comdat cannot be unnamed");
3247 C = getComdat(GlobalName, KwLoc);
3248 }
3249
David Majnemerdad0a642014-06-27 18:19:56 +00003250 return false;
3251}
3252
Victor Hernandez9d75c962010-01-11 22:31:58 +00003253/// ParseGlobalValueVector
3254/// ::= /*empty*/
3255/// ::= TypeAndValue (',' TypeAndValue)*
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003256bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00003257 // Empty list.
3258 if (Lex.getKind() == lltok::rbrace ||
3259 Lex.getKind() == lltok::rsquare ||
3260 Lex.getKind() == lltok::greater ||
3261 Lex.getKind() == lltok::rparen)
3262 return false;
3263
3264 Constant *C;
3265 if (ParseGlobalTypeAndValue(C)) return true;
3266 Elts.push_back(C);
3267
3268 while (EatIfPresent(lltok::comma)) {
3269 if (ParseGlobalTypeAndValue(C)) return true;
3270 Elts.push_back(C);
3271 }
3272
3273 return false;
3274}
3275
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003276bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003277 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003278 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003279 return true;
3280
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003281 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003282 return false;
3283}
3284
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003285/// MDNode:
3286/// ::= !{ ... }
3287/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003288/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003289bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003290 if (Lex.getKind() == lltok::MetadataVar)
3291 return ParseSpecializedMDNode(N);
3292
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003293 return ParseToken(lltok::exclaim, "expected '!' here") ||
3294 ParseMDNodeTail(N);
3295}
3296
3297bool LLParser::ParseMDNodeTail(MDNode *&N) {
3298 // !{ ... }
3299 if (Lex.getKind() == lltok::lbrace)
3300 return ParseMDTuple(N);
3301
3302 // !42
3303 return ParseMDNodeID(N);
3304}
3305
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003306namespace {
3307
3308/// Structure to represent an optional metadata field.
3309template <class FieldTy> struct MDFieldImpl {
3310 typedef MDFieldImpl ImplTy;
3311 FieldTy Val;
3312 bool Seen;
3313
3314 void assign(FieldTy Val) {
3315 Seen = true;
3316 this->Val = std::move(Val);
3317 }
3318
3319 explicit MDFieldImpl(FieldTy Default)
3320 : Val(std::move(Default)), Seen(false) {}
3321};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003322
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003323struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3324 uint64_t Max;
3325
3326 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3327 : ImplTy(Default), Max(Max) {}
3328};
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003329struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003330 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003331};
3332struct ColumnField : public MDUnsignedField {
3333 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3334};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003335struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003336 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003337 DwarfTagField(dwarf::Tag DefaultTag)
3338 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003339};
Amjad Abouda9bcf162015-12-10 12:56:35 +00003340struct DwarfMacinfoTypeField : public MDUnsignedField {
3341 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3342 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3343 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3344};
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003345struct DwarfAttEncodingField : public MDUnsignedField {
3346 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3347};
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003348struct DwarfVirtualityField : public MDUnsignedField {
3349 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3350};
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003351struct DwarfLangField : public MDUnsignedField {
3352 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3353};
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003354struct DwarfCCField : public MDUnsignedField {
3355 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3356};
Adrian Prantlb939a252016-03-31 23:56:58 +00003357struct EmissionKindField : public MDUnsignedField {
3358 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3359};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003360
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003361struct DIFlagField : public MDUnsignedField {
3362 DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3363};
3364
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003365struct MDSignedField : public MDFieldImpl<int64_t> {
3366 int64_t Min;
3367 int64_t Max;
3368
3369 MDSignedField(int64_t Default = 0)
3370 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3371 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3372 : ImplTy(Default), Min(Min), Max(Max) {}
3373};
3374
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003375struct MDBoolField : public MDFieldImpl<bool> {
3376 MDBoolField(bool Default = false) : ImplTy(Default) {}
3377};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003378struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003379 bool AllowNull;
3380
3381 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003382};
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003383struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3384 MDConstant() : ImplTy(nullptr) {}
3385};
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003386struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003387 bool AllowEmpty;
3388 MDStringField(bool AllowEmpty = true)
3389 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003390};
3391struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3392 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3393};
3394
3395} // end namespace
3396
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003397namespace llvm {
3398
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003399template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003400bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003401 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003402 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3403 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003404
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003405 auto &U = Lex.getAPSIntVal();
3406 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003407 return TokError("value for '" + Name + "' too large, limit is " +
3408 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003409 Result.assign(U.getZExtValue());
3410 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003411 Lex.Lex();
3412 return false;
3413}
3414
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003415template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003416bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3417 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3418}
3419template <>
3420bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3421 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3422}
3423
3424template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003425bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3426 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003427 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003428
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003429 if (Lex.getKind() != lltok::DwarfTag)
3430 return TokError("expected DWARF tag");
3431
3432 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3433 if (Tag == dwarf::DW_TAG_invalid)
3434 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003435 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003436
3437 Result.assign(Tag);
3438 Lex.Lex();
3439 return false;
3440}
3441
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003442template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003443bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003444 DwarfMacinfoTypeField &Result) {
3445 if (Lex.getKind() == lltok::APSInt)
3446 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3447
3448 if (Lex.getKind() != lltok::DwarfMacinfo)
3449 return TokError("expected DWARF macinfo type");
3450
3451 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3452 if (Macinfo == dwarf::DW_MACINFO_invalid)
3453 return TokError(
3454 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3455 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3456
3457 Result.assign(Macinfo);
3458 Lex.Lex();
3459 return false;
3460}
3461
3462template <>
3463bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003464 DwarfVirtualityField &Result) {
3465 if (Lex.getKind() == lltok::APSInt)
3466 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3467
3468 if (Lex.getKind() != lltok::DwarfVirtuality)
3469 return TokError("expected DWARF virtuality code");
3470
3471 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
Peter Collingbournea1f86252016-03-17 23:58:03 +00003472 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003473 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3474 Lex.getStrVal() + "'");
3475 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3476 Result.assign(Virtuality);
3477 Lex.Lex();
3478 return false;
3479}
3480
3481template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003482bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3483 if (Lex.getKind() == lltok::APSInt)
3484 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3485
3486 if (Lex.getKind() != lltok::DwarfLang)
3487 return TokError("expected DWARF language");
3488
3489 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3490 if (!Lang)
3491 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3492 "'");
3493 assert(Lang <= Result.Max && "Expected valid DWARF language");
3494 Result.assign(Lang);
3495 Lex.Lex();
3496 return false;
3497}
3498
3499template <>
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003500bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3501 if (Lex.getKind() == lltok::APSInt)
3502 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3503
3504 if (Lex.getKind() != lltok::DwarfCC)
3505 return TokError("expected DWARF calling convention");
3506
3507 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3508 if (!CC)
3509 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3510 "'");
3511 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
3512 Result.assign(CC);
3513 Lex.Lex();
3514 return false;
3515}
3516
3517template <>
Adrian Prantlb939a252016-03-31 23:56:58 +00003518bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3519 if (Lex.getKind() == lltok::APSInt)
3520 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3521
3522 if (Lex.getKind() != lltok::EmissionKind)
3523 return TokError("expected emission kind");
3524
3525 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3526 if (!Kind)
3527 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3528 "'");
3529 assert(*Kind <= Result.Max && "Expected valid emission kind");
3530 Result.assign(*Kind);
3531 Lex.Lex();
3532 return false;
3533}
3534
3535template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003536bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003537 DwarfAttEncodingField &Result) {
3538 if (Lex.getKind() == lltok::APSInt)
3539 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3540
3541 if (Lex.getKind() != lltok::DwarfAttEncoding)
3542 return TokError("expected DWARF type attribute encoding");
3543
3544 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3545 if (!Encoding)
3546 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3547 Lex.getStrVal() + "'");
3548 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3549 Result.assign(Encoding);
3550 Lex.Lex();
3551 return false;
3552}
3553
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003554/// DIFlagField
3555/// ::= uint32
3556/// ::= DIFlagVector
3557/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3558template <>
3559bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3560 assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3561
3562 // Parser for a single flag.
3563 auto parseFlag = [&](unsigned &Val) {
3564 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3565 return ParseUInt32(Val);
3566
3567 if (Lex.getKind() != lltok::DIFlag)
3568 return TokError("expected debug info flag");
3569
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003570 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003571 if (!Val)
3572 return TokError(Twine("invalid debug info flag flag '") +
3573 Lex.getStrVal() + "'");
3574 Lex.Lex();
3575 return false;
3576 };
3577
3578 // Parse the flags and combine them together.
3579 unsigned Combined = 0;
3580 do {
3581 unsigned Val;
3582 if (parseFlag(Val))
3583 return true;
3584 Combined |= Val;
3585 } while (EatIfPresent(lltok::bar));
3586
3587 Result.assign(Combined);
3588 return false;
3589}
3590
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003591template <>
3592bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003593 MDSignedField &Result) {
3594 if (Lex.getKind() != lltok::APSInt)
3595 return TokError("expected signed integer");
3596
3597 auto &S = Lex.getAPSIntVal();
3598 if (S < Result.Min)
3599 return TokError("value for '" + Name + "' too small, limit is " +
3600 Twine(Result.Min));
3601 if (S > Result.Max)
3602 return TokError("value for '" + Name + "' too large, limit is " +
3603 Twine(Result.Max));
3604 Result.assign(S.getExtValue());
3605 assert(Result.Val >= Result.Min && "Expected value in range");
3606 assert(Result.Val <= Result.Max && "Expected value in range");
3607 Lex.Lex();
3608 return false;
3609}
3610
3611template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003612bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3613 switch (Lex.getKind()) {
3614 default:
3615 return TokError("expected 'true' or 'false'");
3616 case lltok::kw_true:
3617 Result.assign(true);
3618 break;
3619 case lltok::kw_false:
3620 Result.assign(false);
3621 break;
3622 }
3623 Lex.Lex();
3624 return false;
3625}
3626
3627template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003628bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003629 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003630 if (!Result.AllowNull)
3631 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003632 Lex.Lex();
3633 Result.assign(nullptr);
3634 return false;
3635 }
3636
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003637 Metadata *MD;
3638 if (ParseMetadata(MD, nullptr))
3639 return true;
3640
3641 Result.assign(MD);
3642 return false;
3643}
3644
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003645template <>
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003646bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3647 Metadata *MD;
3648 if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3649 return true;
3650
3651 Result.assign(cast<ConstantAsMetadata>(MD));
3652 return false;
3653}
3654
3655template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003656bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003657 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003658 std::string S;
3659 if (ParseStringConstant(S))
3660 return true;
3661
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003662 if (!Result.AllowEmpty && S.empty())
3663 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3664
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003665 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003666 return false;
3667}
3668
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003669template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003670bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3671 SmallVector<Metadata *, 4> MDs;
3672 if (ParseMDNodeVector(MDs))
3673 return true;
3674
3675 Result.assign(std::move(MDs));
3676 return false;
3677}
3678
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003679} // end namespace llvm
3680
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003681template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003682bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003683 do {
3684 if (Lex.getKind() != lltok::LabelStr)
3685 return TokError("expected field label here");
3686
3687 if (parseField())
3688 return true;
3689 } while (EatIfPresent(lltok::comma));
3690
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003691 return false;
3692}
3693
3694template <class ParserTy>
3695bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3696 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3697 Lex.Lex();
3698
3699 if (ParseToken(lltok::lparen, "expected '(' here"))
3700 return true;
3701 if (Lex.getKind() != lltok::rparen)
3702 if (ParseMDFieldsImplBody(parseField))
3703 return true;
3704
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00003705 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003706 return ParseToken(lltok::rparen, "expected ')' here");
3707}
3708
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003709template <class FieldTy>
3710bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3711 if (Result.Seen)
3712 return TokError("field '" + Name + "' cannot be specified more than once");
3713
3714 LocTy Loc = Lex.getLoc();
3715 Lex.Lex();
3716 return ParseMDField(Loc, Name, Result);
3717}
3718
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003719bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3720 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003721
3722#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003723 if (Lex.getStrVal() == #CLASS) \
3724 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003725#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003726
3727 return TokError("expected metadata type");
3728}
3729
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003730#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3731#define NOP_FIELD(NAME, TYPE, INIT)
3732#define REQUIRE_FIELD(NAME, TYPE, INIT) \
3733 if (!NAME.Seen) \
3734 return Error(ClosingLoc, "missing required field '" #NAME "'");
3735#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003736 if (Lex.getStrVal() == #NAME) \
3737 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003738#define PARSE_MD_FIELDS() \
3739 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3740 do { \
3741 LocTy ClosingLoc; \
3742 if (ParseMDFieldsImpl([&]() -> bool { \
3743 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3744 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3745 }, ClosingLoc)) \
3746 return true; \
3747 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3748 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003749#define GET_OR_DISTINCT(CLASS, ARGS) \
3750 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003751
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003752/// ParseDILocationFields:
3753/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3754bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003755#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003756 OPTIONAL(line, LineField, ); \
3757 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003758 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003759 OPTIONAL(inlinedAt, MDField, );
3760 PARSE_MD_FIELDS();
3761#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003762
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00003763 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003764 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003765 return false;
3766}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003767
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003768/// ParseGenericDINode:
3769/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3770bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003771#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003772 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003773 OPTIONAL(header, MDStringField, ); \
3774 OPTIONAL(operands, MDFieldList, );
3775 PARSE_MD_FIELDS();
3776#undef VISIT_MD_FIELDS
3777
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003778 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003779 (Context, tag.Val, header.Val, operands.Val));
3780 return false;
3781}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003782
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003783/// ParseDISubrange:
3784/// ::= !DISubrange(count: 30, lowerBound: 2)
3785bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003786#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith5c9a1772015-02-18 23:17:51 +00003787 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003788 OPTIONAL(lowerBound, MDSignedField, );
3789 PARSE_MD_FIELDS();
3790#undef VISIT_MD_FIELDS
3791
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003792 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003793 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003794}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003795
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003796/// ParseDIEnumerator:
3797/// ::= !DIEnumerator(value: 30, name: "SomeKind")
3798bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003799#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00003800 REQUIRED(name, MDStringField, ); \
3801 REQUIRED(value, MDSignedField, );
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003802 PARSE_MD_FIELDS();
3803#undef VISIT_MD_FIELDS
3804
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003805 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003806 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003807}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003808
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003809/// ParseDIBasicType:
3810/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3811bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003812#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003813 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003814 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003815 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3816 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003817 OPTIONAL(encoding, DwarfAttEncodingField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003818 PARSE_MD_FIELDS();
3819#undef VISIT_MD_FIELDS
3820
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003821 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003822 align.Val, encoding.Val));
3823 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003824}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003825
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003826/// ParseDIDerivedType:
3827/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003828/// line: 7, scope: !1, baseType: !2, size: 32,
3829/// align: 32, offset: 0, flags: 0, extraData: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003830bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003831#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3832 REQUIRED(tag, DwarfTagField, ); \
3833 OPTIONAL(name, MDStringField, ); \
3834 OPTIONAL(file, MDField, ); \
3835 OPTIONAL(line, LineField, ); \
3836 OPTIONAL(scope, MDField, ); \
3837 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003838 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3839 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3840 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003841 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003842 OPTIONAL(extraData, MDField, );
3843 PARSE_MD_FIELDS();
3844#undef VISIT_MD_FIELDS
3845
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003846 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003847 (Context, tag.Val, name.Val, file.Val, line.Val,
3848 scope.Val, baseType.Val, size.Val, align.Val,
3849 offset.Val, flags.Val, extraData.Val));
3850 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003851}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003852
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003853bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003854#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3855 REQUIRED(tag, DwarfTagField, ); \
3856 OPTIONAL(name, MDStringField, ); \
3857 OPTIONAL(file, MDField, ); \
3858 OPTIONAL(line, LineField, ); \
3859 OPTIONAL(scope, MDField, ); \
3860 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003861 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3862 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3863 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003864 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003865 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003866 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003867 OPTIONAL(vtableHolder, MDField, ); \
3868 OPTIONAL(templateParams, MDField, ); \
3869 OPTIONAL(identifier, MDStringField, );
3870 PARSE_MD_FIELDS();
3871#undef VISIT_MD_FIELDS
3872
Duncan P. N. Exon Smith97386022016-04-19 18:00:19 +00003873 // If this has an identifier try to build an ODR type.
3874 if (identifier.Val)
3875 if (auto *CT = DICompositeType::buildODRType(
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00003876 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
3877 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
3878 elements.Val, runtimeLang.Val, vtableHolder.Val,
3879 templateParams.Val)) {
3880 Result = CT;
3881 return false;
3882 }
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00003883
3884 // Create a new node, and save it in the context if it belongs in the type
3885 // map.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003886 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003887 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003888 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3889 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3890 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3891 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003892}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003893
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003894bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003895#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003896 OPTIONAL(flags, DIFlagField, ); \
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003897 OPTIONAL(cc, DwarfCCField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003898 REQUIRED(types, MDField, );
3899 PARSE_MD_FIELDS();
3900#undef VISIT_MD_FIELDS
3901
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003902 Result = GET_OR_DISTINCT(DISubroutineType,
3903 (Context, flags.Val, cc.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003904 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003905}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003906
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003907/// ParseDIFileType:
3908/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir")
3909bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003910#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3911 REQUIRED(filename, MDStringField, ); \
3912 REQUIRED(directory, MDStringField, );
3913 PARSE_MD_FIELDS();
3914#undef VISIT_MD_FIELDS
3915
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003916 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003917 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003918}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003919
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003920/// ParseDICompileUnit:
3921/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003922/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
Adrian Prantlb939a252016-03-31 23:56:58 +00003923/// splitDebugFilename: "abc.debug",
Adrian Prantl75819ae2016-04-15 15:57:41 +00003924/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003925/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003926bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00003927 if (!IsDistinct)
3928 return Lex.Error("missing 'distinct', required for !DICompileUnit");
3929
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003930#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3931 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00003932 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003933 OPTIONAL(producer, MDStringField, ); \
3934 OPTIONAL(isOptimized, MDBoolField, ); \
3935 OPTIONAL(flags, MDStringField, ); \
3936 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
3937 OPTIONAL(splitDebugFilename, MDStringField, ); \
Adrian Prantlb939a252016-03-31 23:56:58 +00003938 OPTIONAL(emissionKind, EmissionKindField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003939 OPTIONAL(enums, MDField, ); \
3940 OPTIONAL(retainedTypes, MDField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003941 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00003942 OPTIONAL(imports, MDField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00003943 OPTIONAL(macros, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00003944 OPTIONAL(dwoId, MDUnsignedField, );
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003945 PARSE_MD_FIELDS();
3946#undef VISIT_MD_FIELDS
3947
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00003948 Result = DICompileUnit::getDistinct(
3949 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
3950 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
Adrian Prantl75819ae2016-04-15 15:57:41 +00003951 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003952 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003953}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003954
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003955/// ParseDISubprogram:
3956/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003957/// file: !1, line: 7, type: !2, isLocal: false,
3958/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003959/// virtuality: DW_VIRTUALTIY_pure_virtual,
3960/// virtualIndex: 10, flags: 11,
Peter Collingbourned4bff302015-11-05 22:03:56 +00003961/// isOptimized: false, templateParams: !4, declaration: !5,
3962/// variables: !6)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003963bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00003964 auto Loc = Lex.getLoc();
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003965#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3966 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00003967 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003968 OPTIONAL(linkageName, MDStringField, ); \
3969 OPTIONAL(file, MDField, ); \
3970 OPTIONAL(line, LineField, ); \
3971 OPTIONAL(type, MDField, ); \
3972 OPTIONAL(isLocal, MDBoolField, ); \
3973 OPTIONAL(isDefinition, MDBoolField, (true)); \
3974 OPTIONAL(scopeLine, LineField, ); \
3975 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003976 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003977 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003978 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003979 OPTIONAL(isOptimized, MDBoolField, ); \
Adrian Prantl75819ae2016-04-15 15:57:41 +00003980 OPTIONAL(unit, MDField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003981 OPTIONAL(templateParams, MDField, ); \
3982 OPTIONAL(declaration, MDField, ); \
3983 OPTIONAL(variables, MDField, );
3984 PARSE_MD_FIELDS();
3985#undef VISIT_MD_FIELDS
3986
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00003987 if (isDefinition.Val && !IsDistinct)
3988 return Lex.Error(
3989 Loc,
3990 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
3991
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003992 Result = GET_OR_DISTINCT(
Adrian Prantl75819ae2016-04-15 15:57:41 +00003993 DISubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
3994 line.Val, type.Val, isLocal.Val, isDefinition.Val,
3995 scopeLine.Val, containingType.Val, virtuality.Val,
3996 virtualIndex.Val, flags.Val, isOptimized.Val, unit.Val,
3997 templateParams.Val, declaration.Val, variables.Val));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003998 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003999}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004000
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004001/// ParseDILexicalBlock:
4002/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4003bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004004#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004005 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004006 OPTIONAL(file, MDField, ); \
4007 OPTIONAL(line, LineField, ); \
4008 OPTIONAL(column, ColumnField, );
4009 PARSE_MD_FIELDS();
4010#undef VISIT_MD_FIELDS
4011
4012 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004013 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004014 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004015}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004016
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004017/// ParseDILexicalBlockFile:
4018/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4019bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004020#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004021 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004022 OPTIONAL(file, MDField, ); \
4023 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4024 PARSE_MD_FIELDS();
4025#undef VISIT_MD_FIELDS
4026
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004027 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004028 (Context, scope.Val, file.Val, discriminator.Val));
4029 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004030}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004031
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004032/// ParseDINamespace:
4033/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4034bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004035#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4036 REQUIRED(scope, MDField, ); \
4037 OPTIONAL(file, MDField, ); \
4038 OPTIONAL(name, MDStringField, ); \
4039 OPTIONAL(line, LineField, );
4040 PARSE_MD_FIELDS();
4041#undef VISIT_MD_FIELDS
4042
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004043 Result = GET_OR_DISTINCT(DINamespace,
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004044 (Context, scope.Val, file.Val, name.Val, line.Val));
4045 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004046}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004047
Amjad Abouda9bcf162015-12-10 12:56:35 +00004048/// ParseDIMacro:
4049/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4050bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4051#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4052 REQUIRED(type, DwarfMacinfoTypeField, ); \
4053 REQUIRED(line, LineField, ); \
4054 REQUIRED(name, MDStringField, ); \
4055 OPTIONAL(value, MDStringField, );
4056 PARSE_MD_FIELDS();
4057#undef VISIT_MD_FIELDS
4058
4059 Result = GET_OR_DISTINCT(DIMacro,
4060 (Context, type.Val, line.Val, name.Val, value.Val));
4061 return false;
4062}
4063
4064/// ParseDIMacroFile:
4065/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4066bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4067#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4068 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
4069 REQUIRED(line, LineField, ); \
4070 REQUIRED(file, MDField, ); \
4071 OPTIONAL(nodes, MDField, );
4072 PARSE_MD_FIELDS();
4073#undef VISIT_MD_FIELDS
4074
4075 Result = GET_OR_DISTINCT(DIMacroFile,
4076 (Context, type.Val, line.Val, file.Val, nodes.Val));
4077 return false;
4078}
4079
4080
Adrian Prantlab1243f2015-06-29 23:03:47 +00004081/// ParseDIModule:
4082/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4083/// includePath: "/usr/include", isysroot: "/")
4084bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4085#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4086 REQUIRED(scope, MDField, ); \
4087 REQUIRED(name, MDStringField, ); \
4088 OPTIONAL(configMacros, MDStringField, ); \
4089 OPTIONAL(includePath, MDStringField, ); \
4090 OPTIONAL(isysroot, MDStringField, );
4091 PARSE_MD_FIELDS();
4092#undef VISIT_MD_FIELDS
4093
4094 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4095 configMacros.Val, includePath.Val, isysroot.Val));
4096 return false;
4097}
4098
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004099/// ParseDITemplateTypeParameter:
4100/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4101bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004102#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004103 OPTIONAL(name, MDStringField, ); \
4104 REQUIRED(type, MDField, );
4105 PARSE_MD_FIELDS();
4106#undef VISIT_MD_FIELDS
4107
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004108 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004109 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004110 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004111}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004112
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004113/// ParseDITemplateValueParameter:
4114/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004115/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004116bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004117#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004118 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004119 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004120 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004121 REQUIRED(value, MDField, );
4122 PARSE_MD_FIELDS();
4123#undef VISIT_MD_FIELDS
4124
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004125 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004126 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004127 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004128}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004129
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004130/// ParseDIGlobalVariable:
4131/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004132/// file: !1, line: 7, type: !2, isLocal: false,
4133/// isDefinition: true, variable: i32* @foo,
4134/// declaration: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004135bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004136#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004137 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004138 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004139 OPTIONAL(linkageName, MDStringField, ); \
4140 OPTIONAL(file, MDField, ); \
4141 OPTIONAL(line, LineField, ); \
4142 OPTIONAL(type, MDField, ); \
4143 OPTIONAL(isLocal, MDBoolField, ); \
4144 OPTIONAL(isDefinition, MDBoolField, (true)); \
4145 OPTIONAL(variable, MDConstant, ); \
4146 OPTIONAL(declaration, MDField, );
4147 PARSE_MD_FIELDS();
4148#undef VISIT_MD_FIELDS
4149
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004150 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004151 (Context, scope.Val, name.Val, linkageName.Val,
4152 file.Val, line.Val, type.Val, isLocal.Val,
4153 isDefinition.Val, variable.Val, declaration.Val));
4154 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004155}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004156
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004157/// ParseDILocalVariable:
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004158/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
4159/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
4160/// ::= !DILocalVariable(scope: !0, name: "foo",
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00004161/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004162bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004163#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004164 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004165 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004166 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004167 OPTIONAL(file, MDField, ); \
4168 OPTIONAL(line, LineField, ); \
4169 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00004170 OPTIONAL(flags, DIFlagField, );
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004171 PARSE_MD_FIELDS();
4172#undef VISIT_MD_FIELDS
4173
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004174 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004175 (Context, scope.Val, name.Val, file.Val, line.Val,
4176 type.Val, arg.Val, flags.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004177 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004178}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004179
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004180/// ParseDIExpression:
4181/// ::= !DIExpression(0, 7, -1)
4182bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004183 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4184 Lex.Lex();
4185
4186 if (ParseToken(lltok::lparen, "expected '(' here"))
4187 return true;
4188
4189 SmallVector<uint64_t, 8> Elements;
4190 if (Lex.getKind() != lltok::rparen)
4191 do {
4192 if (Lex.getKind() == lltok::DwarfOp) {
4193 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4194 Lex.Lex();
4195 Elements.push_back(Op);
4196 continue;
4197 }
4198 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4199 }
4200
4201 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4202 return TokError("expected unsigned integer");
4203
4204 auto &U = Lex.getAPSIntVal();
4205 if (U.ugt(UINT64_MAX))
4206 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4207 Elements.push_back(U.getZExtValue());
4208 Lex.Lex();
4209 } while (EatIfPresent(lltok::comma));
4210
4211 if (ParseToken(lltok::rparen, "expected ')' here"))
4212 return true;
4213
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004214 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004215 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004216}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004217
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004218/// ParseDIObjCProperty:
4219/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004220/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004221bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004222#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004223 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004224 OPTIONAL(file, MDField, ); \
4225 OPTIONAL(line, LineField, ); \
4226 OPTIONAL(setter, MDStringField, ); \
4227 OPTIONAL(getter, MDStringField, ); \
4228 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4229 OPTIONAL(type, MDField, );
4230 PARSE_MD_FIELDS();
4231#undef VISIT_MD_FIELDS
4232
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004233 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004234 (Context, name.Val, file.Val, line.Val, setter.Val,
4235 getter.Val, attributes.Val, type.Val));
4236 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004237}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004238
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004239/// ParseDIImportedEntity:
4240/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004241/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004242bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004243#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4244 REQUIRED(tag, DwarfTagField, ); \
4245 REQUIRED(scope, MDField, ); \
4246 OPTIONAL(entity, MDField, ); \
4247 OPTIONAL(line, LineField, ); \
4248 OPTIONAL(name, MDStringField, );
4249 PARSE_MD_FIELDS();
4250#undef VISIT_MD_FIELDS
4251
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004252 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004253 entity.Val, line.Val, name.Val));
4254 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004255}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004256
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004257#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004258#undef NOP_FIELD
4259#undef REQUIRE_FIELD
4260#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004261
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004262/// ParseMetadataAsValue
4263/// ::= metadata i32 %local
4264/// ::= metadata i32 @global
4265/// ::= metadata i32 7
4266/// ::= metadata !0
4267/// ::= metadata !{...}
4268/// ::= metadata !"string"
4269bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4270 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004271 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004272 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004273 return true;
4274
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004275 V = MetadataAsValue::get(Context, MD);
4276 return false;
4277}
4278
4279/// ParseValueAsMetadata
4280/// ::= i32 %local
4281/// ::= i32 @global
4282/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004283bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4284 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004285 Type *Ty;
4286 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004287 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004288 return true;
4289 if (Ty->isMetadataTy())
4290 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4291
4292 Value *V;
4293 if (ParseValue(Ty, V, PFS))
4294 return true;
4295
4296 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004297 return false;
4298}
4299
4300/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004301/// ::= i32 %local
4302/// ::= i32 @global
4303/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00004304/// ::= !42
4305/// ::= !{...}
4306/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004307/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004308bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004309 if (Lex.getKind() == lltok::MetadataVar) {
4310 MDNode *N;
4311 if (ParseSpecializedMDNode(N))
4312 return true;
4313 MD = N;
4314 return false;
4315 }
4316
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004317 // ValueAsMetadata:
4318 // <type> <value>
4319 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004320 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004321
4322 // '!'.
4323 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4324 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00004325
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004326 // MDString:
4327 // ::= '!' STRINGCONSTANT
4328 if (Lex.getKind() == lltok::StringConstant) {
4329 MDString *S;
4330 if (ParseMDString(S))
4331 return true;
4332 MD = S;
4333 return false;
4334 }
4335
Dan Gohman8939ba332010-07-14 18:26:50 +00004336 // MDNode:
4337 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004338 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004339 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004340 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004341 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004342 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00004343 return false;
4344}
4345
Victor Hernandez9d75c962010-01-11 22:31:58 +00004346
4347//===----------------------------------------------------------------------===//
4348// Function Parsing.
4349//===----------------------------------------------------------------------===//
4350
Chris Lattner229907c2011-07-18 04:54:35 +00004351bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
David Majnemer8a1c45d2015-12-12 05:38:55 +00004352 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00004353 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004354 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004355
Chris Lattnerac161bf2009-01-02 07:01:27 +00004356 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004357 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004358 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004359 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004360 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004361 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004362 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004363 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004364 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004365 case ValID::t_InlineAsm: {
Karl Schimpf44876c52015-09-03 16:18:32 +00004366 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez9d75c962010-01-11 22:31:58 +00004367 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie41ba2b42015-07-27 23:32:19 +00004368 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4369 (ID.UIntVal >> 1) & 1,
4370 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00004371 return false;
4372 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004373 case ValID::t_GlobalName:
4374 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004375 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004376 case ValID::t_GlobalID:
4377 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004378 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004379 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00004380 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004381 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00004382 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00004383 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004384 return false;
4385 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00004386 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004387 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4388 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004389
Dan Gohman518cda42011-12-17 00:04:22 +00004390 // The lexer has no type info, so builds all half, float, and double FP
4391 // constants as double. Fix this here. Long double does not need this.
4392 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004393 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00004394 if (Ty->isHalfTy())
4395 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
4396 &Ignored);
4397 else if (Ty->isFloatTy())
4398 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
4399 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004400 }
Owen Anderson69c464d2009-07-27 20:59:43 +00004401 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004402
Chris Lattner8f57d29e2009-01-05 18:24:23 +00004403 if (V->getType() != Ty)
4404 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004405 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004406
Chris Lattnerac161bf2009-01-02 07:01:27 +00004407 return false;
4408 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00004409 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004410 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004411 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004412 return false;
4413 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00004414 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004415 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00004416 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004417 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004418 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00004419 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00004420 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00004421 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004422 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00004423 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004424 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00004425 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00004426 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004427 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00004428 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004429 return false;
David Majnemerf0f224d2015-11-11 21:57:16 +00004430 case ValID::t_None:
4431 if (!Ty->isTokenTy())
4432 return Error(ID.Loc, "invalid type for none constant");
4433 V = Constant::getNullValue(Ty);
4434 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004435 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00004436 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004437 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00004438
Chris Lattnerac161bf2009-01-02 07:01:27 +00004439 V = ID.ConstantVal;
4440 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004441 case ValID::t_ConstantStruct:
4442 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00004443 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004444 if (ST->getNumElements() != ID.UIntVal)
4445 return Error(ID.Loc,
4446 "initializer with struct type has wrong # elements");
4447 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4448 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004449
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004450 // Verify that the elements are compatible with the structtype.
4451 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4452 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4453 return Error(ID.Loc, "element " + Twine(i) +
4454 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004455
David Blaikieadbda4b2015-08-03 20:08:41 +00004456 V = ConstantStruct::get(
4457 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004458 } else
4459 return Error(ID.Loc, "constant expression type mismatch");
4460 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004461 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00004462 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004463}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004464
Alex Lorenzd2255952015-07-17 22:07:03 +00004465bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4466 C = nullptr;
4467 ValID ID;
4468 auto Loc = Lex.getLoc();
4469 if (ParseValID(ID, /*PFS=*/nullptr))
4470 return true;
4471 switch (ID.Kind) {
4472 case ValID::t_APSInt:
4473 case ValID::t_APFloat:
Alex Lorenzb9a68db2015-09-09 13:44:33 +00004474 case ValID::t_Undef:
Alex Lorenzd2255952015-07-17 22:07:03 +00004475 case ValID::t_Constant:
4476 case ValID::t_ConstantStruct:
4477 case ValID::t_PackedConstantStruct: {
4478 Value *V;
4479 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4480 return true;
4481 assert(isa<Constant>(V) && "Expected a constant value");
4482 C = cast<Constant>(V);
4483 return false;
4484 }
4485 default:
4486 return Error(Loc, "expected a constant value");
4487 }
4488}
4489
David Majnemer8a1c45d2015-12-12 05:38:55 +00004490bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004491 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004492 ValID ID;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004493 return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004494}
4495
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004496bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004497 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004498 return ParseType(Ty) ||
4499 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004500}
4501
Chris Lattner3ed871f2009-10-27 19:13:16 +00004502bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4503 PerFunctionState &PFS) {
4504 Value *V;
4505 Loc = Lex.getLoc();
4506 if (ParseTypeAndValue(V, PFS)) return true;
4507 if (!isa<BasicBlock>(V))
4508 return Error(Loc, "expected a basic block");
4509 BB = cast<BasicBlock>(V);
4510 return false;
4511}
4512
4513
Chris Lattnerac161bf2009-01-02 07:01:27 +00004514/// FunctionHeader
4515/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00004516/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
David Majnemer7fddecc2015-06-17 20:52:32 +00004517/// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00004518bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4519 // Parse the linkage.
4520 LocTy LinkageLoc = Lex.getLoc();
4521 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004522
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00004523 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00004524 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00004525 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004526 unsigned CC;
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004527 bool HasLinkage;
Craig Topper2617dcc2014-04-15 06:32:26 +00004528 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004529 LocTy RetTypeLoc = Lex.getLoc();
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004530 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
4531 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004532 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004533 return true;
4534
4535 // Verify that the linkage is ok.
4536 switch ((GlobalValue::LinkageTypes)Linkage) {
4537 case GlobalValue::ExternalLinkage:
4538 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00004539 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004540 if (isDefine)
4541 return Error(LinkageLoc, "invalid linkage for function definition");
4542 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00004543 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004544 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00004545 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00004546 case GlobalValue::LinkOnceAnyLinkage:
4547 case GlobalValue::LinkOnceODRLinkage:
4548 case GlobalValue::WeakAnyLinkage:
4549 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004550 if (!isDefine)
4551 return Error(LinkageLoc, "invalid linkage for function declaration");
4552 break;
4553 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00004554 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004555 return Error(LinkageLoc, "invalid function linkage type");
4556 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004557
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004558 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4559 return Error(LinkageLoc,
4560 "symbol with local linkage must have default visibility");
4561
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004562 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004563 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004564
Chris Lattnerac161bf2009-01-02 07:01:27 +00004565 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00004566
4567 std::string FunctionName;
4568 if (Lex.getKind() == lltok::GlobalVar) {
4569 FunctionName = Lex.getStrVal();
4570 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4571 unsigned NameID = Lex.getUIntVal();
4572
4573 if (NameID != NumberedVals.size())
4574 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004575 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00004576 } else {
4577 return TokError("expected function name");
4578 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004579
Chris Lattner3822f632009-01-02 08:05:26 +00004580 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004581
Chris Lattner3822f632009-01-02 08:05:26 +00004582 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004583 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004584
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004585 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004586 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00004587 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004588 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004589 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004590 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004591 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00004592 std::string GC;
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004593 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004594 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00004595 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004596 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00004597 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00004598 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00004599
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004600 if (ParseArgumentList(ArgList, isVarArg) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004601 ParseOptionalUnnamedAddr(UnnamedAddr) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004602 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004603 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004604 (EatIfPresent(lltok::kw_section) &&
4605 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00004606 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004607 ParseOptionalAlignment(Alignment) ||
4608 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004609 ParseStringConstant(GC)) ||
4610 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004611 ParseGlobalTypeAndValue(Prefix)) ||
4612 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00004613 ParseGlobalTypeAndValue(Prologue)) ||
4614 (EatIfPresent(lltok::kw_personality) &&
4615 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00004616 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004617
Michael Gottesman41748d72013-06-27 00:25:01 +00004618 if (FuncAttrs.contains(Attribute::Builtin))
4619 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00004620
Chris Lattnerac161bf2009-01-02 07:01:27 +00004621 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00004622 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00004623 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004624 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004625 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004626
Chris Lattnerac161bf2009-01-02 07:01:27 +00004627 // Okay, if we got here, the function is syntactically valid. Convert types
4628 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00004629 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00004630 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004631
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004632 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004633 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4634 AttributeSet::ReturnIndex,
4635 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004636
Chris Lattnerac161bf2009-01-02 07:01:27 +00004637 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004638 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004639 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4640 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004641 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4642 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004643 }
4644
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004645 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004646 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4647 AttributeSet::FunctionIndex,
4648 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004649
Bill Wendlinge94d8432012-12-07 23:16:57 +00004650 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004651
Bill Wendling749a43d2012-12-30 13:50:49 +00004652 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004653 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4654
Chris Lattner229907c2011-07-18 04:54:35 +00004655 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00004656 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00004657 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004658
Craig Topper2617dcc2014-04-15 06:32:26 +00004659 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004660 if (!FunctionName.empty()) {
4661 // If this was a definition of a forward reference, remove the definition
4662 // from the forward reference table and fill in the forward ref.
David Blaikie9ebdc692015-09-21 21:07:50 +00004663 auto FRVI = ForwardRefVals.find(FunctionName);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004664 if (FRVI != ForwardRefVals.end()) {
4665 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00004666 if (!Fn)
4667 return Error(FRVI->second.second, "invalid forward reference to "
4668 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00004669 if (Fn->getType() != PFT)
4670 return Error(FRVI->second.second, "invalid forward reference to "
4671 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004672
Chris Lattnerac161bf2009-01-02 07:01:27 +00004673 ForwardRefVals.erase(FRVI);
4674 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00004675 // Reject redefinitions.
4676 return Error(NameLoc, "invalid redefinition of function '" +
4677 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00004678 } else if (M->getNamedValue(FunctionName)) {
4679 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004680 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004681
Dan Gohman399d6ae2009-08-29 23:37:49 +00004682 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004683 // If this is a definition of a forward referenced function, make sure the
4684 // types agree.
David Blaikie9ebdc692015-09-21 21:07:50 +00004685 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004686 if (I != ForwardRefValIDs.end()) {
4687 Fn = cast<Function>(I->second.first);
4688 if (Fn->getType() != PFT)
4689 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004690 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004691 ForwardRefValIDs.erase(I);
4692 }
4693 }
4694
Craig Topper2617dcc2014-04-15 06:32:26 +00004695 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004696 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4697 else // Move the forward-reference to the correct spot in the module.
4698 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4699
4700 if (FunctionName.empty())
4701 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004702
Chris Lattnerac161bf2009-01-02 07:01:27 +00004703 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4704 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00004705 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004706 Fn->setCallingConv(CC);
4707 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004708 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004709 Fn->setAlignment(Alignment);
4710 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00004711 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00004712 Fn->setPersonalityFn(PersonalityFn);
Benjamin Kramer728f4442016-05-29 10:46:35 +00004713 if (!GC.empty()) Fn->setGC(GC);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004714 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004715 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004716 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004717
Chris Lattnerac161bf2009-01-02 07:01:27 +00004718 // Add all of the arguments we parsed to the function.
4719 Function::arg_iterator ArgIt = Fn->arg_begin();
4720 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4721 // If the argument has a name, insert it into the argument symbol table.
4722 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004723
Chris Lattnerac161bf2009-01-02 07:01:27 +00004724 // Set the name, if it conflicted, it will be auto-renamed.
4725 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004726
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00004727 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004728 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4729 ArgList[i].Name + "'");
4730 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004731
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004732 if (isDefine)
4733 return false;
4734
Robin Morisset039781e2014-08-29 21:53:01 +00004735 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004736 ValID ID;
4737 if (FunctionName.empty()) {
4738 ID.Kind = ValID::t_GlobalID;
4739 ID.UIntVal = NumberedVals.size() - 1;
4740 } else {
4741 ID.Kind = ValID::t_GlobalName;
4742 ID.StrVal = FunctionName;
4743 }
4744 auto Blocks = ForwardRefBlockAddresses.find(ID);
4745 if (Blocks != ForwardRefBlockAddresses.end())
4746 return Error(Blocks->first.Loc,
4747 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004748 return false;
4749}
4750
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004751bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4752 ValID ID;
4753 if (FunctionNumber == -1) {
4754 ID.Kind = ValID::t_GlobalName;
4755 ID.StrVal = F.getName();
4756 } else {
4757 ID.Kind = ValID::t_GlobalID;
4758 ID.UIntVal = FunctionNumber;
4759 }
4760
4761 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4762 if (Blocks == P.ForwardRefBlockAddresses.end())
4763 return false;
4764
4765 for (const auto &I : Blocks->second) {
4766 const ValID &BBID = I.first;
4767 GlobalValue *GV = I.second;
4768
4769 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4770 "Expected local id or name");
4771 BasicBlock *BB;
4772 if (BBID.Kind == ValID::t_LocalName)
4773 BB = GetBB(BBID.StrVal, BBID.Loc);
4774 else
4775 BB = GetBB(BBID.UIntVal, BBID.Loc);
4776 if (!BB)
4777 return P.Error(BBID.Loc, "referenced value is not a basic block");
4778
4779 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4780 GV->eraseFromParent();
4781 }
4782
4783 P.ForwardRefBlockAddresses.erase(Blocks);
4784 return false;
4785}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004786
4787/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004788/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00004789bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00004790 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004791 return TokError("expected '{' in function body");
4792 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004793
Chris Lattner3432c622009-10-28 03:39:23 +00004794 int FunctionNumber = -1;
4795 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004796
Chris Lattner3432c622009-10-28 03:39:23 +00004797 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004798
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004799 // Resolve block addresses and allow basic blocks to be forward-declared
4800 // within this function.
4801 if (PFS.resolveForwardRefBlockAddresses())
4802 return true;
4803 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4804
Chris Lattnerbbddd962010-01-09 19:20:07 +00004805 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004806 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00004807 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004808
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004809 while (Lex.getKind() != lltok::rbrace &&
4810 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004811 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004812
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004813 while (Lex.getKind() != lltok::rbrace)
4814 if (ParseUseListOrder(&PFS))
4815 return true;
4816
Chris Lattnerac161bf2009-01-02 07:01:27 +00004817 // Eat the }.
4818 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004819
Chris Lattnerac161bf2009-01-02 07:01:27 +00004820 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00004821 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004822}
4823
4824/// ParseBasicBlock
4825/// ::= LabelStr? Instruction*
4826bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4827 // If this basic block starts out with a name, remember it.
4828 std::string Name;
4829 LocTy NameLoc = Lex.getLoc();
4830 if (Lex.getKind() == lltok::LabelStr) {
4831 Name = Lex.getStrVal();
4832 Lex.Lex();
4833 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004834
Chris Lattnerac161bf2009-01-02 07:01:27 +00004835 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00004836 if (!BB)
4837 return Error(NameLoc,
4838 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004839
Chris Lattnerac161bf2009-01-02 07:01:27 +00004840 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004841
Chris Lattnerac161bf2009-01-02 07:01:27 +00004842 // Parse the instructions in this block until we get a terminator.
4843 Instruction *Inst;
4844 do {
4845 // This instruction may have three possibilities for a name: a) none
4846 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4847 LocTy NameLoc = Lex.getLoc();
4848 int NameID = -1;
4849 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004850
Chris Lattnerac161bf2009-01-02 07:01:27 +00004851 if (Lex.getKind() == lltok::LocalVarID) {
4852 NameID = Lex.getUIntVal();
4853 Lex.Lex();
4854 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4855 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00004856 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004857 NameStr = Lex.getStrVal();
4858 Lex.Lex();
4859 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4860 return true;
4861 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004862
Chris Lattner77b89dc2009-12-30 05:23:43 +00004863 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00004864 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00004865 case InstError: return true;
4866 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004867 BB->getInstList().push_back(Inst);
4868
Chris Lattner77b89dc2009-12-30 05:23:43 +00004869 // With a normal result, we check to see if the instruction is followed by
4870 // a comma and metadata.
4871 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004872 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004873 return true;
4874 break;
4875 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004876 BB->getInstList().push_back(Inst);
4877
Chris Lattner77b89dc2009-12-30 05:23:43 +00004878 // If the instruction parser ate an extra comma at the end of it, it
4879 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004880 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004881 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004882 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00004883 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004884
Chris Lattnerac161bf2009-01-02 07:01:27 +00004885 // Set the name on the instruction.
4886 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4887 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004888
Chris Lattnerac161bf2009-01-02 07:01:27 +00004889 return false;
4890}
4891
4892//===----------------------------------------------------------------------===//
4893// Instruction Parsing.
4894//===----------------------------------------------------------------------===//
4895
4896/// ParseInstruction - Parse one of the many different instructions.
4897///
Chris Lattner77b89dc2009-12-30 05:23:43 +00004898int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4899 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004900 lltok::Kind Token = Lex.getKind();
4901 if (Token == lltok::Eof)
4902 return TokError("found end of file when expecting more instructions");
4903 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00004904 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004905 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004906
Chris Lattnerac161bf2009-01-02 07:01:27 +00004907 switch (Token) {
4908 default: return Error(Loc, "expected instruction opcode");
4909 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00004910 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004911 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
4912 case lltok::kw_br: return ParseBr(Inst, PFS);
4913 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004914 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004915 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00004916 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer654e1302015-07-31 17:58:14 +00004917 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
4918 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00004919 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
4920 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00004921 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004922 // Binary Operators.
4923 case lltok::kw_add:
4924 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004925 case lltok::kw_mul:
4926 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00004927 bool NUW = EatIfPresent(lltok::kw_nuw);
4928 bool NSW = EatIfPresent(lltok::kw_nsw);
4929 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004930
Chris Lattnera676c0f2011-02-07 16:40:21 +00004931 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004932
Chris Lattnera676c0f2011-02-07 16:40:21 +00004933 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4934 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4935 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004936 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004937 case lltok::kw_fadd:
4938 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00004939 case lltok::kw_fmul:
4940 case lltok::kw_fdiv:
4941 case lltok::kw_frem: {
4942 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4943 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4944 if (Res != 0)
4945 return Res;
4946 if (FMF.any())
4947 Inst->setFastMathFlags(FMF);
4948 return 0;
4949 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004950
Chris Lattner35315d02011-02-06 21:44:57 +00004951 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004952 case lltok::kw_udiv:
4953 case lltok::kw_lshr:
4954 case lltok::kw_ashr: {
4955 bool Exact = EatIfPresent(lltok::kw_exact);
4956
4957 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4958 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4959 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004960 }
4961
Chris Lattnerac161bf2009-01-02 07:01:27 +00004962 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00004963 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004964 case lltok::kw_and:
4965 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00004966 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00004967 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
4968 case lltok::kw_fcmp: {
4969 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4970 int Res = ParseCompare(Inst, PFS, KeywordVal);
4971 if (Res != 0)
4972 return Res;
4973 if (FMF.any())
4974 Inst->setFastMathFlags(FMF);
4975 return 0;
4976 }
4977
Chris Lattnerac161bf2009-01-02 07:01:27 +00004978 // Casts.
4979 case lltok::kw_trunc:
4980 case lltok::kw_zext:
4981 case lltok::kw_sext:
4982 case lltok::kw_fptrunc:
4983 case lltok::kw_fpext:
4984 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004985 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004986 case lltok::kw_uitofp:
4987 case lltok::kw_sitofp:
4988 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004989 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004990 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00004991 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004992 // Other.
4993 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00004994 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004995 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
4996 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
4997 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
4998 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00004999 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00005000 // Call.
5001 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5002 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5003 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00005004 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005005 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00005006 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00005007 case lltok::kw_load: return ParseLoad(Inst, PFS);
5008 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00005009 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5010 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005011 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005012 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5013 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5014 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5015 }
5016}
5017
5018/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5019bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005020 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005021 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005022 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005023 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5024 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5025 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5026 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5027 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5028 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5029 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5030 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5031 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5032 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5033 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5034 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5035 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5036 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5037 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5038 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5039 }
5040 } else {
5041 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005042 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005043 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5044 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5045 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5046 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5047 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5048 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5049 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5050 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5051 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5052 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5053 }
5054 }
5055 Lex.Lex();
5056 return false;
5057}
5058
5059//===----------------------------------------------------------------------===//
5060// Terminator Instructions.
5061//===----------------------------------------------------------------------===//
5062
5063/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00005064/// ::= 'ret' void (',' !dbg, !1)*
5065/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00005066bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005067 PerFunctionState &PFS) {
5068 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00005069 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00005070 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005071
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005072 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005073
Chris Lattnerfdd87902009-10-05 05:54:46 +00005074 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005075 if (!ResType->isVoidTy())
5076 return Error(TypeLoc, "value doesn't match function result type '" +
5077 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005078
Owen Anderson55f1c092009-08-13 21:58:54 +00005079 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005080 return false;
5081 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005082
Chris Lattnerac161bf2009-01-02 07:01:27 +00005083 Value *RV;
5084 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005085
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005086 if (ResType != RV->getType())
5087 return Error(TypeLoc, "value doesn't match function result type '" +
5088 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005089
Owen Anderson55f1c092009-08-13 21:58:54 +00005090 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00005091 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005092}
5093
5094
5095/// ParseBr
5096/// ::= 'br' TypeAndValue
5097/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5098bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5099 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005100 Value *Op0;
5101 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005102 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005103
Chris Lattnerac161bf2009-01-02 07:01:27 +00005104 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5105 Inst = BranchInst::Create(BB);
5106 return false;
5107 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005108
Owen Anderson55f1c092009-08-13 21:58:54 +00005109 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005110 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005111
Chris Lattnerac161bf2009-01-02 07:01:27 +00005112 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005113 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005114 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005115 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005116 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005117
Chris Lattner3ed871f2009-10-27 19:13:16 +00005118 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005119 return false;
5120}
5121
5122/// ParseSwitch
5123/// Instruction
5124/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5125/// JumpTable
5126/// ::= (TypeAndValue ',' TypeAndValue)*
5127bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5128 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005129 Value *Cond;
5130 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005131 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5132 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005133 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005134 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5135 return true;
5136
Duncan Sands19d0b472010-02-16 11:11:14 +00005137 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005138 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005139
Chris Lattnerac161bf2009-01-02 07:01:27 +00005140 // Parse the jump table pairs.
5141 SmallPtrSet<Value*, 32> SeenCases;
5142 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5143 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005144 Value *Constant;
5145 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005146
Chris Lattnerac161bf2009-01-02 07:01:27 +00005147 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5148 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005149 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005150 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005151
David Blaikie70573dc2014-11-19 07:49:26 +00005152 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005153 return Error(CondLoc, "duplicate case value in switch");
5154 if (!isa<ConstantInt>(Constant))
5155 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005156
Chris Lattner3ed871f2009-10-27 19:13:16 +00005157 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00005158 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005159
Chris Lattnerac161bf2009-01-02 07:01:27 +00005160 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005161
Chris Lattner3ed871f2009-10-27 19:13:16 +00005162 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005163 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5164 SI->addCase(Table[i].first, Table[i].second);
5165 Inst = SI;
5166 return false;
5167}
5168
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005169/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00005170/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005171/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5172bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005173 LocTy AddrLoc;
5174 Value *Address;
5175 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005176 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5177 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00005178 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005179
Duncan Sands19d0b472010-02-16 11:11:14 +00005180 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005181 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005182
Chris Lattner3ed871f2009-10-27 19:13:16 +00005183 // Parse the destination list.
5184 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005185
Chris Lattner3ed871f2009-10-27 19:13:16 +00005186 if (Lex.getKind() != lltok::rsquare) {
5187 BasicBlock *DestBB;
5188 if (ParseTypeAndBasicBlock(DestBB, PFS))
5189 return true;
5190 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005191
Chris Lattner3ed871f2009-10-27 19:13:16 +00005192 while (EatIfPresent(lltok::comma)) {
5193 if (ParseTypeAndBasicBlock(DestBB, PFS))
5194 return true;
5195 DestList.push_back(DestBB);
5196 }
5197 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005198
Chris Lattner3ed871f2009-10-27 19:13:16 +00005199 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5200 return true;
5201
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005202 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00005203 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5204 IBI->addDestination(DestList[i]);
5205 Inst = IBI;
5206 return false;
5207}
5208
5209
Chris Lattnerac161bf2009-01-02 07:01:27 +00005210/// ParseInvoke
5211/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5212/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5213bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5214 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00005215 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005216 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00005217 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005218 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005219 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005220 LocTy RetTypeLoc;
5221 ValID CalleeID;
5222 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005223 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005224
Chris Lattner3ed871f2009-10-27 19:13:16 +00005225 BasicBlock *NormalBB, *UnwindBB;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005226 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005227 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005228 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005229 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5230 NoBuiltinLoc) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005231 ParseOptionalOperandBundles(BundleList, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005232 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005233 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005234 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005235 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005236 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005237
Chris Lattnerac161bf2009-01-02 07:01:27 +00005238 // If RetType is a non-function pointer type, then this is the short syntax
5239 // for the call, which means that RetType is just the return type. Infer the
5240 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00005241 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5242 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005243 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005244 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005245 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5246 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005247
Chris Lattnerac161bf2009-01-02 07:01:27 +00005248 if (!FunctionType::isValidReturnType(RetType))
5249 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005250
Owen Anderson4056ca92009-07-29 22:17:13 +00005251 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005252 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005253
David Blaikie41ba2b42015-07-27 23:32:19 +00005254 CalleeID.FTy = Ty;
5255
Chris Lattnerac161bf2009-01-02 07:01:27 +00005256 // Look up the callee.
5257 Value *Callee;
David Blaikie445e3fb2015-04-24 19:32:54 +00005258 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5259 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005260
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005261 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005262 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005263 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005264 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5265 AttributeSet::ReturnIndex,
5266 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005267
Chris Lattnerac161bf2009-01-02 07:01:27 +00005268 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005269
Chris Lattnerac161bf2009-01-02 07:01:27 +00005270 // Loop through FunctionType's arguments and ensure they are specified
5271 // correctly. Also, gather any parameter attributes.
5272 FunctionType::param_iterator I = Ty->param_begin();
5273 FunctionType::param_iterator E = Ty->param_end();
5274 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005275 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005276 if (I != E) {
5277 ExpectedTy = *I++;
5278 } else if (!Ty->isVarArg()) {
5279 return Error(ArgList[i].Loc, "too many arguments specified");
5280 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005281
Chris Lattnerac161bf2009-01-02 07:01:27 +00005282 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5283 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005284 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005285 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005286 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5287 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005288 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5289 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005290 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005291
Chris Lattnerac161bf2009-01-02 07:01:27 +00005292 if (I != E)
5293 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005294
David Majnemer8d22abd2015-02-23 00:01:32 +00005295 if (FnAttrs.hasAttributes()) {
5296 if (FnAttrs.hasAlignmentAttr())
5297 return Error(CallLoc, "invoke instructions may not have an alignment");
5298
Bill Wendlingf5075a42013-01-27 02:24:02 +00005299 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5300 AttributeSet::FunctionIndex,
5301 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005302 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005303
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005304 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005305 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005306
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005307 InvokeInst *II =
5308 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005309 II->setCallingConv(CC);
5310 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005311 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005312 Inst = II;
5313 return false;
5314}
5315
Bill Wendlingf891bf82011-07-31 06:30:59 +00005316/// ParseResume
5317/// ::= 'resume' TypeAndValue
5318bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5319 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005320 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5321 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005322
Bill Wendlingf891bf82011-07-31 06:30:59 +00005323 ResumeInst *RI = ResumeInst::Create(Exn);
5324 Inst = RI;
5325 return false;
5326}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005327
David Majnemer654e1302015-07-31 17:58:14 +00005328bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5329 PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005330 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
David Majnemer654e1302015-07-31 17:58:14 +00005331 return true;
5332
5333 while (Lex.getKind() != lltok::rsquare) {
5334 // If this isn't the first argument, we need a comma.
5335 if (!Args.empty() &&
5336 ParseToken(lltok::comma, "expected ',' in argument list"))
5337 return true;
5338
5339 // Parse the argument.
5340 LocTy ArgLoc;
5341 Type *ArgTy = nullptr;
5342 if (ParseType(ArgTy, ArgLoc))
5343 return true;
5344
5345 Value *V;
5346 if (ArgTy->isMetadataTy()) {
5347 if (ParseMetadataAsValue(V, PFS))
5348 return true;
5349 } else {
5350 if (ParseValue(ArgTy, V, PFS))
5351 return true;
5352 }
5353 Args.push_back(V);
5354 }
5355
5356 Lex.Lex(); // Lex the ']'.
5357 return false;
5358}
5359
5360/// ParseCleanupRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005361/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
David Majnemer654e1302015-07-31 17:58:14 +00005362bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005363 Value *CleanupPad = nullptr;
David Majnemer654e1302015-07-31 17:58:14 +00005364
David Majnemer8a1c45d2015-12-12 05:38:55 +00005365 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5366 return true;
5367
5368 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005369 return true;
David Majnemer654e1302015-07-31 17:58:14 +00005370
5371 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5372 return true;
5373
5374 BasicBlock *UnwindBB = nullptr;
5375 if (Lex.getKind() == lltok::kw_to) {
5376 Lex.Lex();
5377 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5378 return true;
5379 } else {
5380 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5381 return true;
5382 }
5383 }
5384
David Majnemer8a1c45d2015-12-12 05:38:55 +00005385 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
David Majnemer654e1302015-07-31 17:58:14 +00005386 return false;
5387}
5388
5389/// ParseCatchRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005390/// ::= 'catchret' from Parent Value 'to' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005391bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005392 Value *CatchPad = nullptr;
David Majnemer0bc0eef2015-08-15 02:46:08 +00005393
David Majnemer8a1c45d2015-12-12 05:38:55 +00005394 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5395 return true;
5396
5397 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
David Majnemer0bc0eef2015-08-15 02:46:08 +00005398 return true;
5399
David Majnemer0bc0eef2015-08-15 02:46:08 +00005400 BasicBlock *BB;
5401 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5402 ParseTypeAndBasicBlock(BB, PFS))
5403 return true;
5404
David Majnemer8a1c45d2015-12-12 05:38:55 +00005405 Inst = CatchReturnInst::Create(CatchPad, BB);
5406 return false;
5407}
5408
5409/// ParseCatchSwitch
5410/// ::= 'catchswitch' within Parent
5411bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5412 Value *ParentPad;
5413 LocTy BBLoc;
5414
5415 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5416 return true;
5417
5418 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5419 Lex.getKind() != lltok::LocalVarID)
5420 return TokError("expected scope value for catchswitch");
5421
5422 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5423 return true;
5424
5425 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5426 return true;
5427
5428 SmallVector<BasicBlock *, 32> Table;
5429 do {
5430 BasicBlock *DestBB;
5431 if (ParseTypeAndBasicBlock(DestBB, PFS))
5432 return true;
5433 Table.push_back(DestBB);
5434 } while (EatIfPresent(lltok::comma));
5435
5436 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5437 return true;
5438
5439 if (ParseToken(lltok::kw_unwind,
5440 "expected 'unwind' after catchswitch scope"))
5441 return true;
5442
5443 BasicBlock *UnwindBB = nullptr;
5444 if (EatIfPresent(lltok::kw_to)) {
5445 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5446 return true;
5447 } else {
5448 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5449 return true;
5450 }
5451
5452 auto *CatchSwitch =
5453 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5454 for (BasicBlock *DestBB : Table)
5455 CatchSwitch->addHandler(DestBB);
5456 Inst = CatchSwitch;
David Majnemer654e1302015-07-31 17:58:14 +00005457 return false;
5458}
5459
5460/// ParseCatchPad
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005461/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005462bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005463 Value *CatchSwitch = nullptr;
5464
5465 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5466 return true;
5467
5468 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5469 return TokError("expected scope value for catchpad");
5470
5471 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5472 return true;
5473
David Majnemer654e1302015-07-31 17:58:14 +00005474 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005475 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005476 return true;
5477
David Majnemer8a1c45d2015-12-12 05:38:55 +00005478 Inst = CatchPadInst::Create(CatchSwitch, Args);
David Majnemer654e1302015-07-31 17:58:14 +00005479 return false;
5480}
5481
David Majnemer654e1302015-07-31 17:58:14 +00005482/// ParseCleanupPad
David Majnemer8a1c45d2015-12-12 05:38:55 +00005483/// ::= 'cleanuppad' within Parent ParamList
David Majnemer654e1302015-07-31 17:58:14 +00005484bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005485 Value *ParentPad = nullptr;
5486
5487 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5488 return true;
5489
5490 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5491 Lex.getKind() != lltok::LocalVarID)
5492 return TokError("expected scope value for cleanuppad");
5493
5494 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5495 return true;
5496
David Majnemer654e1302015-07-31 17:58:14 +00005497 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005498 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005499 return true;
5500
David Majnemer8a1c45d2015-12-12 05:38:55 +00005501 Inst = CleanupPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00005502 return false;
5503}
5504
Chris Lattnerac161bf2009-01-02 07:01:27 +00005505//===----------------------------------------------------------------------===//
5506// Binary Operators.
5507//===----------------------------------------------------------------------===//
5508
5509/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005510/// ::= ArithmeticOps TypeAndValue ',' Value
5511///
5512/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5513/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00005514bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005515 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005516 LocTy Loc; Value *LHS, *RHS;
5517 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5518 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5519 ParseValue(LHS->getType(), RHS, PFS))
5520 return true;
5521
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005522 bool Valid;
5523 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00005524 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005525 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00005526 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5527 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005528 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00005529 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5530 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005531 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005532
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005533 if (!Valid)
5534 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005535
Chris Lattnerac161bf2009-01-02 07:01:27 +00005536 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5537 return false;
5538}
5539
5540/// ParseLogical
5541/// ::= ArithmeticOps TypeAndValue ',' Value {
5542bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5543 unsigned Opc) {
5544 LocTy Loc; Value *LHS, *RHS;
5545 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5546 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5547 ParseValue(LHS->getType(), RHS, PFS))
5548 return true;
5549
Duncan Sands9dff9be2010-02-15 16:12:20 +00005550 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005551 return Error(Loc,"instruction requires integer or integer vector operands");
5552
5553 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5554 return false;
5555}
5556
5557
5558/// ParseCompare
5559/// ::= 'icmp' IPredicates TypeAndValue ',' Value
5560/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005561bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5562 unsigned Opc) {
5563 // Parse the integer/fp comparison predicate.
5564 LocTy Loc;
5565 unsigned Pred;
5566 Value *LHS, *RHS;
5567 if (ParseCmpPredicate(Pred, Opc) ||
5568 ParseTypeAndValue(LHS, Loc, PFS) ||
5569 ParseToken(lltok::comma, "expected ',' after compare value") ||
5570 ParseValue(LHS->getType(), RHS, PFS))
5571 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005572
Chris Lattnerac161bf2009-01-02 07:01:27 +00005573 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00005574 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005575 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005576 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005577 } else {
5578 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00005579 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00005580 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005581 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005582 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005583 }
5584 return false;
5585}
5586
5587//===----------------------------------------------------------------------===//
5588// Other Instructions.
5589//===----------------------------------------------------------------------===//
5590
5591
5592/// ParseCast
5593/// ::= CastOpc TypeAndValue 'to' Type
5594bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5595 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005596 LocTy Loc;
5597 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005598 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005599 if (ParseTypeAndValue(Op, Loc, PFS) ||
5600 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5601 ParseType(DestTy))
5602 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005603
Chris Lattner89d856e2009-03-01 00:53:13 +00005604 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5605 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005606 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005607 getTypeString(Op->getType()) + "' to '" +
5608 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00005609 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005610 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5611 return false;
5612}
5613
5614/// ParseSelect
5615/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5616bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5617 LocTy Loc;
5618 Value *Op0, *Op1, *Op2;
5619 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5620 ParseToken(lltok::comma, "expected ',' after select condition") ||
5621 ParseTypeAndValue(Op1, PFS) ||
5622 ParseToken(lltok::comma, "expected ',' after select value") ||
5623 ParseTypeAndValue(Op2, PFS))
5624 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005625
Chris Lattnerac161bf2009-01-02 07:01:27 +00005626 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5627 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005628
Chris Lattnerac161bf2009-01-02 07:01:27 +00005629 Inst = SelectInst::Create(Op0, Op1, Op2);
5630 return false;
5631}
5632
Chris Lattnerb55ab542009-01-05 08:18:44 +00005633/// ParseVA_Arg
5634/// ::= 'va_arg' TypeAndValue ',' Type
5635bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005636 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005637 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00005638 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005639 if (ParseTypeAndValue(Op, PFS) ||
5640 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00005641 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005642 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005643
Chris Lattnerb55ab542009-01-05 08:18:44 +00005644 if (!EltTy->isFirstClassType())
5645 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005646
5647 Inst = new VAArgInst(Op, EltTy);
5648 return false;
5649}
5650
5651/// ParseExtractElement
5652/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5653bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5654 LocTy Loc;
5655 Value *Op0, *Op1;
5656 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5657 ParseToken(lltok::comma, "expected ',' after extract value") ||
5658 ParseTypeAndValue(Op1, PFS))
5659 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005660
Chris Lattnerac161bf2009-01-02 07:01:27 +00005661 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5662 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005663
Eric Christopherc9742252009-07-25 02:28:41 +00005664 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005665 return false;
5666}
5667
5668/// ParseInsertElement
5669/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5670bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5671 LocTy Loc;
5672 Value *Op0, *Op1, *Op2;
5673 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5674 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5675 ParseTypeAndValue(Op1, PFS) ||
5676 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5677 ParseTypeAndValue(Op2, PFS))
5678 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005679
Chris Lattnerac161bf2009-01-02 07:01:27 +00005680 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00005681 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005682
Chris Lattnerac161bf2009-01-02 07:01:27 +00005683 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5684 return false;
5685}
5686
5687/// ParseShuffleVector
5688/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5689bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5690 LocTy Loc;
5691 Value *Op0, *Op1, *Op2;
5692 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5693 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5694 ParseTypeAndValue(Op1, PFS) ||
5695 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5696 ParseTypeAndValue(Op2, PFS))
5697 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005698
Chris Lattnerac161bf2009-01-02 07:01:27 +00005699 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00005700 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005701
Chris Lattnerac161bf2009-01-02 07:01:27 +00005702 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5703 return false;
5704}
5705
5706/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00005707/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005708int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005709 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005710 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005711
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005712 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005713 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5714 ParseValue(Ty, Op0, PFS) ||
5715 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005716 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005717 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5718 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005719
Chris Lattnerf4f03422009-12-30 05:27:33 +00005720 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005721 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5722 while (1) {
5723 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005724
Chris Lattner3822f632009-01-02 08:05:26 +00005725 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005726 break;
5727
Chris Lattnerf4f03422009-12-30 05:27:33 +00005728 if (Lex.getKind() == lltok::MetadataVar) {
5729 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00005730 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005731 }
Devang Patel8f842d32009-10-16 18:45:49 +00005732
Chris Lattner3822f632009-01-02 08:05:26 +00005733 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005734 ParseValue(Ty, Op0, PFS) ||
5735 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005736 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005737 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5738 return true;
5739 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005740
Chris Lattnerac161bf2009-01-02 07:01:27 +00005741 if (!Ty->isFirstClassType())
5742 return Error(TypeLoc, "phi node must have first class type");
5743
Jay Foad52131342011-03-30 11:28:46 +00005744 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005745 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5746 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5747 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005748 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005749}
5750
Bill Wendlingfae14752011-08-12 20:24:12 +00005751/// ParseLandingPad
5752/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5753/// Clause
5754/// ::= 'catch' TypeAndValue
5755/// ::= 'filter'
5756/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5757bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005758 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00005759
David Majnemer7fddecc2015-06-17 20:52:32 +00005760 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00005761 return true;
5762
David Majnemer7fddecc2015-06-17 20:52:32 +00005763 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00005764 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5765
5766 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5767 LandingPadInst::ClauseType CT;
5768 if (EatIfPresent(lltok::kw_catch))
5769 CT = LandingPadInst::Catch;
5770 else if (EatIfPresent(lltok::kw_filter))
5771 CT = LandingPadInst::Filter;
5772 else
5773 return TokError("expected 'catch' or 'filter' clause type");
5774
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005775 Value *V;
5776 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00005777 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00005778 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00005779
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00005780 // A 'catch' type expects a non-array constant. A filter clause expects an
5781 // array constant.
5782 if (CT == LandingPadInst::Catch) {
5783 if (isa<ArrayType>(V->getType()))
5784 Error(VLoc, "'catch' clause has an invalid type");
5785 } else {
5786 if (!isa<ArrayType>(V->getType()))
5787 Error(VLoc, "'filter' clause has an invalid type");
5788 }
5789
Owen Andersonf8f259d2015-03-09 07:13:42 +00005790 Constant *CV = dyn_cast<Constant>(V);
5791 if (!CV)
5792 return Error(VLoc, "clause argument must be a constant");
5793 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00005794 }
5795
Owen Andersonf8f259d2015-03-09 07:13:42 +00005796 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00005797 return false;
5798}
5799
Chris Lattnerac161bf2009-01-02 07:01:27 +00005800/// ParseCall
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005801/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
5802/// OptionalAttrs Type Value ParameterList OptionalAttrs
5803/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
5804/// OptionalAttrs Type Value ParameterList OptionalAttrs
5805/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
5806/// OptionalAttrs Type Value ParameterList OptionalAttrs
5807/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
5808/// OptionalAttrs Type Value ParameterList OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +00005809bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00005810 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00005811 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005812 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005813 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005814 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005815 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005816 LocTy RetTypeLoc;
5817 ValID CalleeID;
5818 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005819 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005820 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005821
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005822 if (TCK != CallInst::TCK_None &&
5823 ParseToken(lltok::kw_call,
5824 "expected 'tail call', 'musttail call', or 'notail call'"))
5825 return true;
5826
5827 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5828
5829 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005830 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005831 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00005832 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5833 PFS.getFunction().isVarArg()) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005834 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
5835 ParseOptionalOperandBundles(BundleList, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005836 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005837
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005838 if (FMF.any() && !RetType->isFPOrFPVectorTy())
5839 return Error(CallLoc, "fast-math-flags specified for call without "
5840 "floating-point scalar or vector return type");
5841
Chris Lattnerac161bf2009-01-02 07:01:27 +00005842 // If RetType is a non-function pointer type, then this is the short syntax
5843 // for the call, which means that RetType is just the return type. Infer the
5844 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00005845 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5846 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005847 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005848 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00005849 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5850 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005851
Chris Lattnerac161bf2009-01-02 07:01:27 +00005852 if (!FunctionType::isValidReturnType(RetType))
5853 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005854
Owen Anderson4056ca92009-07-29 22:17:13 +00005855 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005856 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005857
David Blaikie41ba2b42015-07-27 23:32:19 +00005858 CalleeID.FTy = Ty;
5859
Chris Lattnerac161bf2009-01-02 07:01:27 +00005860 // Look up the callee.
5861 Value *Callee;
David Blaikie23af6482015-04-16 23:24:18 +00005862 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5863 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005864
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005865 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005866 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005867 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005868 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5869 AttributeSet::ReturnIndex,
5870 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005871
Chris Lattnerac161bf2009-01-02 07:01:27 +00005872 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005873
Chris Lattnerac161bf2009-01-02 07:01:27 +00005874 // Loop through FunctionType's arguments and ensure they are specified
5875 // correctly. Also, gather any parameter attributes.
5876 FunctionType::param_iterator I = Ty->param_begin();
5877 FunctionType::param_iterator E = Ty->param_end();
5878 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005879 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005880 if (I != E) {
5881 ExpectedTy = *I++;
5882 } else if (!Ty->isVarArg()) {
5883 return Error(ArgList[i].Loc, "too many arguments specified");
5884 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005885
Chris Lattnerac161bf2009-01-02 07:01:27 +00005886 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5887 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005888 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005889 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005890 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5891 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005892 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5893 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005894 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005895
Chris Lattnerac161bf2009-01-02 07:01:27 +00005896 if (I != E)
5897 return Error(CallLoc, "not enough parameters specified for call");
5898
David Majnemer8d22abd2015-02-23 00:01:32 +00005899 if (FnAttrs.hasAttributes()) {
5900 if (FnAttrs.hasAlignmentAttr())
5901 return Error(CallLoc, "call instructions may not have an alignment");
5902
Bill Wendlingf5075a42013-01-27 02:24:02 +00005903 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5904 AttributeSet::FunctionIndex,
5905 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005906 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005907
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005908 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005909 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005910
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005911 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
Reid Kleckner5772b772014-04-24 20:14:34 +00005912 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005913 CI->setCallingConv(CC);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005914 if (FMF.any())
5915 CI->setFastMathFlags(FMF);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005916 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005917 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005918 Inst = CI;
5919 return false;
5920}
5921
5922//===----------------------------------------------------------------------===//
5923// Memory Instructions.
5924//===----------------------------------------------------------------------===//
5925
5926/// ParseAlloc
Manman Ren9bfd0d02016-04-01 21:41:15 +00005927/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
5928/// (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00005929int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005930 Value *Size = nullptr;
David Majnemera3b0eb22015-02-16 08:38:03 +00005931 LocTy SizeLoc, TyLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005932 unsigned Alignment = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00005933 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00005934
5935 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00005936 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
David Majnemerc4ab61c2014-03-09 06:41:58 +00005937
David Majnemera3b0eb22015-02-16 08:38:03 +00005938 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005939
David Majnemera3b0eb22015-02-16 08:38:03 +00005940 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5941 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00005942
Chris Lattnerb2f39502009-12-30 05:44:30 +00005943 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00005944 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00005945 if (Lex.getKind() == lltok::kw_align) {
5946 if (ParseOptionalAlignment(Alignment)) return true;
5947 } else if (Lex.getKind() == lltok::MetadataVar) {
5948 AteExtraComma = true;
5949 } else {
5950 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5951 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5952 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005953 }
5954 }
5955
Dan Gohman2140a742010-05-28 01:14:11 +00005956 if (Size && !Size->getType()->isIntegerTy())
5957 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005958
Reid Kleckner436c42e2014-01-17 23:58:17 +00005959 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5960 AI->setUsedWithInAlloca(IsInAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00005961 AI->setSwiftError(IsSwiftError);
Reid Kleckner436c42e2014-01-17 23:58:17 +00005962 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00005963 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005964}
5965
5966/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00005967/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005968/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00005969/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005970int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005971 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005972 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005973 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005974 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00005975 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedman59b66882011-08-09 23:02:53 +00005976 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005977
5978 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005979 isAtomic = true;
5980 Lex.Lex();
5981 }
5982
Chris Lattnerbc639292011-11-27 06:56:53 +00005983 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005984 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005985 isVolatile = true;
5986 Lex.Lex();
5987 }
5988
David Blaikie15d9a4c2015-04-06 20:59:48 +00005989 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00005990 LocTy ExplicitTypeLoc = Lex.getLoc();
5991 if (ParseType(Ty) ||
5992 ParseToken(lltok::comma, "expected comma after load's type") ||
5993 ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005994 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005995 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5996 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005997
David Blaikie15d9a4c2015-04-06 20:59:48 +00005998 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005999 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00006000 if (isAtomic && !Alignment)
6001 return Error(Loc, "atomic load must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006002 if (Ordering == AtomicOrdering::Release ||
6003 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006004 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006005
David Blaikiea79ac142015-02-27 21:17:42 +00006006 if (Ty != cast<PointerType>(Val->getType())->getElementType())
6007 return Error(ExplicitTypeLoc,
6008 "explicit pointee type doesn't match operand's pointee type");
6009
David Blaikie15d9a4c2015-04-06 20:59:48 +00006010 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006011 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006012}
6013
6014/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00006015
6016/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6017/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00006018/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006019int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006020 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006021 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006022 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006023 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006024 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedman59b66882011-08-09 23:02:53 +00006025 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006026
6027 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006028 isAtomic = true;
6029 Lex.Lex();
6030 }
6031
Chris Lattnerbc639292011-11-27 06:56:53 +00006032 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006033 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006034 isVolatile = true;
6035 Lex.Lex();
6036 }
6037
Chris Lattnerac161bf2009-01-02 07:01:27 +00006038 if (ParseTypeAndValue(Val, Loc, PFS) ||
6039 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006040 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00006041 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006042 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006043 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00006044
Duncan Sands19d0b472010-02-16 11:11:14 +00006045 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006046 return Error(PtrLoc, "store operand must be a pointer");
6047 if (!Val->getType()->isFirstClassType())
6048 return Error(Loc, "store operand must be a first class value");
6049 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6050 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00006051 if (isAtomic && !Alignment)
6052 return Error(Loc, "atomic store must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006053 if (Ordering == AtomicOrdering::Acquire ||
6054 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006055 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006056
Eli Friedman59b66882011-08-09 23:02:53 +00006057 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006058 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006059}
6060
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006061/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00006062/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6063/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00006064int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006065 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6066 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006067 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6068 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006069 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006070 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00006071 bool isWeak = false;
6072
6073 if (EatIfPresent(lltok::kw_weak))
6074 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00006075
6076 if (EatIfPresent(lltok::kw_volatile))
6077 isVolatile = true;
6078
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006079 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6080 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6081 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6082 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6083 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00006084 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
6085 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006086 return true;
6087
JF Bastien800f87a2016-04-06 21:19:33 +00006088 if (SuccessOrdering == AtomicOrdering::Unordered ||
6089 FailureOrdering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006090 return TokError("cmpxchg cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006091 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6092 return TokError("cmpxchg failure argument shall be no stronger than the "
6093 "success argument");
6094 if (FailureOrdering == AtomicOrdering::Release ||
6095 FailureOrdering == AtomicOrdering::AcquireRelease)
6096 return TokError(
6097 "cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006098 if (!Ptr->getType()->isPointerTy())
6099 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6100 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6101 return Error(CmpLoc, "compare value and pointer type do not match");
6102 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6103 return Error(NewLoc, "new value and pointer type do not match");
Philip Reames1960cfd2016-02-19 00:06:41 +00006104 if (!New->getType()->isFirstClassType())
6105 return Error(NewLoc, "cmpxchg operand must be a first class value");
Tim Northover420a2162014-06-13 14:24:07 +00006106 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
6107 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006108 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00006109 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006110 Inst = CXI;
6111 return AteExtraComma ? InstExtraComma : InstNormal;
6112}
6113
6114/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00006115/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6116/// 'singlethread'? AtomicOrdering
6117int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006118 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6119 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006120 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006121 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006122 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006123 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00006124
6125 if (EatIfPresent(lltok::kw_volatile))
6126 isVolatile = true;
6127
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006128 switch (Lex.getKind()) {
6129 default: return TokError("expected binary operation in atomicrmw");
6130 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6131 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6132 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6133 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6134 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6135 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6136 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6137 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6138 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6139 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6140 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6141 }
6142 Lex.Lex(); // Eat the operation.
6143
6144 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6145 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6146 ParseTypeAndValue(Val, ValLoc, PFS) ||
6147 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6148 return true;
6149
JF Bastien800f87a2016-04-06 21:19:33 +00006150 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006151 return TokError("atomicrmw cannot be unordered");
6152 if (!Ptr->getType()->isPointerTy())
6153 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6154 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6155 return Error(ValLoc, "atomicrmw value and pointer type do not match");
6156 if (!Val->getType()->isIntegerTy())
6157 return Error(ValLoc, "atomicrmw operand must be an integer");
6158 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6159 if (Size < 8 || (Size & (Size - 1)))
6160 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6161 " integer");
6162
6163 AtomicRMWInst *RMWI =
6164 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
6165 RMWI->setVolatile(isVolatile);
6166 Inst = RMWI;
6167 return AteExtraComma ? InstExtraComma : InstNormal;
6168}
6169
Eli Friedmanfee02c62011-07-25 23:16:38 +00006170/// ParseFence
6171/// ::= 'fence' 'singlethread'? AtomicOrdering
6172int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
JF Bastien800f87a2016-04-06 21:19:33 +00006173 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedmanfee02c62011-07-25 23:16:38 +00006174 SynchronizationScope Scope = CrossThread;
6175 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6176 return true;
6177
JF Bastien800f87a2016-04-06 21:19:33 +00006178 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006179 return TokError("fence cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006180 if (Ordering == AtomicOrdering::Monotonic)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006181 return TokError("fence cannot be monotonic");
6182
6183 Inst = new FenceInst(Context, Ordering, Scope);
6184 return InstNormal;
6185}
6186
Chris Lattnerac161bf2009-01-02 07:01:27 +00006187/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00006188/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006189int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006190 Value *Ptr = nullptr;
6191 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006192 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00006193
Dan Gohman16cbbe42009-07-29 15:58:36 +00006194 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00006195
David Blaikie79e6c742015-02-27 19:29:02 +00006196 Type *Ty = nullptr;
6197 LocTy ExplicitTypeLoc = Lex.getLoc();
6198 if (ParseType(Ty) ||
6199 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6200 ParseTypeAndValue(Ptr, Loc, PFS))
6201 return true;
6202
Eli Benderskyd9806682013-04-22 17:03:42 +00006203 Type *BaseType = Ptr->getType();
6204 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6205 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006206 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006207
David Blaikie8d757942015-03-09 23:08:44 +00006208 if (Ty != BasePointerType->getElementType())
6209 return Error(ExplicitTypeLoc,
6210 "explicit pointee type doesn't match operand's pointee type");
6211
Chris Lattnerac161bf2009-01-02 07:01:27 +00006212 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006213 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006214 // GEP returns a vector of pointers if at least one of parameters is a vector.
6215 // All vector parameters should have the same vector width.
6216 unsigned GEPWidth = BaseType->isVectorTy() ?
6217 BaseType->getVectorNumElements() : 0;
6218
Chris Lattner3822f632009-01-02 08:05:26 +00006219 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00006220 if (Lex.getKind() == lltok::MetadataVar) {
6221 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00006222 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006223 }
Chris Lattner3822f632009-01-02 08:05:26 +00006224 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006225 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006226 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006227
Nadav Rotem3924cb02011-12-05 06:29:09 +00006228 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006229 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6230 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00006231 return Error(EltLoc,
6232 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006233 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006234 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006235 Indices.push_back(Val);
6236 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006237
Craig Toppere3dcce92015-08-01 22:20:21 +00006238 SmallPtrSet<Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00006239 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00006240 return Error(Loc, "base element of getelementptr must be sized");
6241
David Blaikied33bad32015-04-17 22:32:13 +00006242 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006243 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00006244 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00006245 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00006246 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006247 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006248}
6249
6250/// ParseExtractValue
6251/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006252int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006253 Value *Val; LocTy Loc;
6254 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006255 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006256 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006257 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006258 return true;
6259
Chris Lattner392be582010-02-12 20:49:41 +00006260 if (!Val->getType()->isAggregateType())
6261 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006262
Jay Foad57aa6362011-07-13 10:26:04 +00006263 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006264 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00006265 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006266 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006267}
6268
6269/// ParseInsertValue
6270/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006271int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006272 Value *Val0, *Val1; LocTy Loc0, Loc1;
6273 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006274 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006275 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6276 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6277 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006278 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006279 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006280
Chris Lattner392be582010-02-12 20:49:41 +00006281 if (!Val0->getType()->isAggregateType())
6282 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006283
David Majnemer30074532015-02-11 07:43:58 +00006284 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6285 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006286 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00006287 if (IndexedType != Val1->getType())
6288 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6289 getTypeString(Val1->getType()) + "' instead of '" +
6290 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00006291 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006292 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006293}
Nick Lewycky49f89192009-04-04 07:22:01 +00006294
6295//===----------------------------------------------------------------------===//
6296// Embedded metadata.
6297//===----------------------------------------------------------------------===//
6298
6299/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006300/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006301/// Element
6302/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006303bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00006304 if (ParseToken(lltok::lbrace, "expected '{' here"))
6305 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006306
Dan Gohman1e0213a2010-07-13 19:33:27 +00006307 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006308 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00006309 return false;
6310
Nick Lewycky49f89192009-04-04 07:22:01 +00006311 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006312 // Null is a special case since it is typeless.
6313 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006314 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006315 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006316 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006317
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006318 Metadata *MD;
6319 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006320 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006321 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00006322 } while (EatIfPresent(lltok::comma));
6323
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006324 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00006325}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006326
6327//===----------------------------------------------------------------------===//
6328// Use-list order directives.
6329//===----------------------------------------------------------------------===//
6330bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6331 SMLoc Loc) {
6332 if (V->use_empty())
6333 return Error(Loc, "value has no uses");
6334
6335 unsigned NumUses = 0;
6336 SmallDenseMap<const Use *, unsigned, 16> Order;
6337 for (const Use &U : V->uses()) {
6338 if (++NumUses > Indexes.size())
6339 break;
6340 Order[&U] = Indexes[NumUses - 1];
6341 }
6342 if (NumUses < 2)
6343 return Error(Loc, "value only has one use");
6344 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6345 return Error(Loc, "wrong number of indexes, expected " +
6346 Twine(std::distance(V->use_begin(), V->use_end())));
6347
6348 V->sortUseList([&](const Use &L, const Use &R) {
6349 return Order.lookup(&L) < Order.lookup(&R);
6350 });
6351 return false;
6352}
6353
6354/// ParseUseListOrderIndexes
6355/// ::= '{' uint32 (',' uint32)+ '}'
6356bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6357 SMLoc Loc = Lex.getLoc();
6358 if (ParseToken(lltok::lbrace, "expected '{' here"))
6359 return true;
6360 if (Lex.getKind() == lltok::rbrace)
6361 return Lex.Error("expected non-empty list of uselistorder indexes");
6362
6363 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6364 // indexes should be distinct numbers in the range [0, size-1], and should
6365 // not be in order.
6366 unsigned Offset = 0;
6367 unsigned Max = 0;
6368 bool IsOrdered = true;
6369 assert(Indexes.empty() && "Expected empty order vector");
6370 do {
6371 unsigned Index;
6372 if (ParseUInt32(Index))
6373 return true;
6374
6375 // Update consistency checks.
6376 Offset += Index - Indexes.size();
6377 Max = std::max(Max, Index);
6378 IsOrdered &= Index == Indexes.size();
6379
6380 Indexes.push_back(Index);
6381 } while (EatIfPresent(lltok::comma));
6382
6383 if (ParseToken(lltok::rbrace, "expected '}' here"))
6384 return true;
6385
6386 if (Indexes.size() < 2)
6387 return Error(Loc, "expected >= 2 uselistorder indexes");
6388 if (Offset != 0 || Max >= Indexes.size())
6389 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6390 if (IsOrdered)
6391 return Error(Loc, "expected uselistorder indexes to change the order");
6392
6393 return false;
6394}
6395
6396/// ParseUseListOrder
6397/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6398bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6399 SMLoc Loc = Lex.getLoc();
6400 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6401 return true;
6402
6403 Value *V;
6404 SmallVector<unsigned, 16> Indexes;
6405 if (ParseTypeAndValue(V, PFS) ||
6406 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6407 ParseUseListOrderIndexes(Indexes))
6408 return true;
6409
6410 return sortUseListOrder(V, Indexes, Loc);
6411}
6412
6413/// ParseUseListOrderBB
6414/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6415bool LLParser::ParseUseListOrderBB() {
6416 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6417 SMLoc Loc = Lex.getLoc();
6418 Lex.Lex();
6419
6420 ValID Fn, Label;
6421 SmallVector<unsigned, 16> Indexes;
6422 if (ParseValID(Fn) ||
6423 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6424 ParseValID(Label) ||
6425 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6426 ParseUseListOrderIndexes(Indexes))
6427 return true;
6428
6429 // Check the function.
6430 GlobalValue *GV;
6431 if (Fn.Kind == ValID::t_GlobalName)
6432 GV = M->getNamedValue(Fn.StrVal);
6433 else if (Fn.Kind == ValID::t_GlobalID)
6434 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6435 else
6436 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6437 if (!GV)
6438 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6439 auto *F = dyn_cast<Function>(GV);
6440 if (!F)
6441 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6442 if (F->isDeclaration())
6443 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6444
6445 // Check the basic block.
6446 if (Label.Kind == ValID::t_LocalID)
6447 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6448 if (Label.Kind != ValID::t_LocalName)
6449 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
6450 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
6451 if (!V)
6452 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6453 if (!isa<BasicBlock>(V))
6454 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6455
6456 return sortUseListOrder(V, Indexes, Loc);
6457}