blob: ee634505581e81ab3fb7cfebc759b64ad0d2d20c [file] [log] [blame]
Chris Lattnerdf986172009-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"
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +000015#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/None.h"
17#include "llvm/ADT/Optional.h"
David Blaikieafb53792015-08-03 20:08:41 +000018#include "llvm/ADT/STLExtras.h"
Chandler Carruthe3e43d92017-06-06 11:49:48 +000019#include "llvm/ADT/SmallPtrSet.h"
Alex Lorenzd31dc692015-06-23 17:10:10 +000020#include "llvm/AsmParser/SlotMapping.h"
Zachary Turner19ca2b02017-06-07 03:48:56 +000021#include "llvm/BinaryFormat/Dwarf.h"
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +000022#include "llvm/IR/Argument.h"
Chandler Carruthf8aca1d2014-03-05 10:34:14 +000023#include "llvm/IR/AutoUpgrade.h"
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +000024#include "llvm/IR/BasicBlock.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000025#include "llvm/IR/CallingConv.h"
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +000026#include "llvm/IR/Comdat.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000027#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smithca8d3bf2015-02-02 18:53:21 +000028#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000029#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +000030#include "llvm/IR/Function.h"
31#include "llvm/IR/GlobalIFunc.h"
32#include "llvm/IR/GlobalObject.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000033#include "llvm/IR/InlineAsm.h"
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +000034#include "llvm/IR/Instruction.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000035#include "llvm/IR/Instructions.h"
Artur Pilipenko140d9e62016-06-24 15:10:29 +000036#include "llvm/IR/Intrinsics.h"
Manman Ren804f0342013-09-28 00:22:27 +000037#include "llvm/IR/LLVMContext.h"
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +000038#include "llvm/IR/Metadata.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000039#include "llvm/IR/Module.h"
40#include "llvm/IR/Operator.h"
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +000041#include "llvm/IR/Type.h"
42#include "llvm/IR/Value.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000043#include "llvm/IR/ValueSymbolTable.h"
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +000044#include "llvm/Support/Casting.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000045#include "llvm/Support/ErrorHandling.h"
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +000046#include "llvm/Support/MathExtras.h"
Duncan P. N. Exon Smith16589782014-08-19 00:13:19 +000047#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000048#include "llvm/Support/raw_ostream.h"
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +000049#include <algorithm>
50#include <cassert>
51#include <cstring>
52#include <iterator>
53#include <vector>
54
Chris Lattnerdf986172009-01-02 07:01:27 +000055using namespace llvm;
56
Chris Lattnerdb125cf2011-07-18 04:54:35 +000057static std::string getTypeString(Type *T) {
Alp Toker8dd8d5c2014-06-26 22:52:05 +000058 std::string Result;
59 raw_string_ostream Tmp(Result);
60 Tmp << *T;
61 return Tmp.str();
Chris Lattner0cd0d882011-06-18 21:18:23 +000062}
63
Chris Lattner3ed88ef2009-01-02 08:05:26 +000064/// Run: module ::= toplevelentity*
Chris Lattnerad7d1e22009-01-04 20:44:11 +000065bool LLParser::Run() {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000066 // Prime the lexer.
67 Lex.Lex();
68
Mehdi Amini64a77d02016-04-02 03:46:17 +000069 if (Context.shouldDiscardValueNames())
Mehdi Amini2de99272016-03-10 01:28:54 +000070 return Error(
71 Lex.getLoc(),
72 "Can't read textual IR with a Context that discards named Values");
73
Teresa Johnsonc6dda902018-06-26 13:56:49 +000074 return ParseTopLevelEntities() || ValidateEndOfModule() ||
75 ValidateEndOfIndex();
Chris Lattnerdf986172009-01-02 07:01:27 +000076}
77
Alex Lorenz0e998762015-08-21 21:32:39 +000078bool LLParser::parseStandaloneConstantValue(Constant *&C,
79 const SlotMapping *Slots) {
80 restoreParsingState(Slots);
Alex Lorenz4b50ecb2015-07-17 22:07:03 +000081 Lex.Lex();
82
83 Type *Ty = nullptr;
84 if (ParseType(Ty) || parseConstantValue(Ty, C))
85 return true;
86 if (Lex.getKind() != lltok::Eof)
87 return Error(Lex.getLoc(), "expected end of string");
88 return false;
89}
90
Quentin Colombetcbd4dbb2016-03-08 00:37:07 +000091bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
92 const SlotMapping *Slots) {
Quentin Colombet2ba03232016-03-07 22:09:05 +000093 restoreParsingState(Slots);
94 Lex.Lex();
95
Quentin Colombetcbd4dbb2016-03-08 00:37:07 +000096 Read = 0;
97 SMLoc Start = Lex.getLoc();
Quentin Colombet2ba03232016-03-07 22:09:05 +000098 Ty = nullptr;
99 if (ParseType(Ty))
100 return true;
Quentin Colombetcbd4dbb2016-03-08 00:37:07 +0000101 SMLoc End = Lex.getLoc();
102 Read = End.getPointer() - Start.getPointer();
103
Quentin Colombet2ba03232016-03-07 22:09:05 +0000104 return false;
105}
106
Alex Lorenz0e998762015-08-21 21:32:39 +0000107void LLParser::restoreParsingState(const SlotMapping *Slots) {
108 if (!Slots)
109 return;
110 NumberedVals = Slots->GlobalValues;
111 NumberedMetadata = Slots->MetadataNodes;
112 for (const auto &I : Slots->NamedTypes)
113 NamedTypes.insert(
114 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
115 for (const auto &I : Slots->Types)
116 NumberedTypes.insert(
117 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
118}
119
Chris Lattnerdf986172009-01-02 07:01:27 +0000120/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
121/// module.
122bool LLParser::ValidateEndOfModule() {
Teresa Johnsonc6dda902018-06-26 13:56:49 +0000123 if (!M)
124 return false;
Bill Wendlingbaad55c2013-02-08 06:32:06 +0000125 // Handle any function attribute group forward references.
Saleem Abdulrasoolad04ba22016-12-27 18:35:22 +0000126 for (const auto &RAG : ForwardRefAttrGroups) {
127 Value *V = RAG.first;
128 const std::vector<unsigned> &Attrs = RAG.second;
Bill Wendlingbaad55c2013-02-08 06:32:06 +0000129 AttrBuilder B;
130
Saleem Abdulrasoolad04ba22016-12-27 18:35:22 +0000131 for (const auto &Attr : Attrs)
132 B.merge(NumberedAttrBuilders[Attr]);
Bill Wendlingbaad55c2013-02-08 06:32:06 +0000133
134 if (Function *Fn = dyn_cast<Function>(V)) {
Reid Kleckner67077702017-03-21 16:57:19 +0000135 AttributeList AS = Fn->getAttributes();
Reid Kleckner7dde8e82017-04-10 23:31:05 +0000136 AttrBuilder FnAttrs(AS.getFnAttributes());
137 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendlingbaad55c2013-02-08 06:32:06 +0000138
139 FnAttrs.merge(B);
140
141 // If the alignment was parsed as an attribute, move to the alignment
142 // field.
143 if (FnAttrs.hasAlignmentAttr()) {
144 Fn->setAlignment(FnAttrs.getAlignment());
145 FnAttrs.removeAttribute(Attribute::Alignment);
146 }
147
Reid Klecknerd6b4b102017-04-19 17:28:52 +0000148 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
149 AttributeSet::get(Context, FnAttrs));
Bill Wendlingbaad55c2013-02-08 06:32:06 +0000150 Fn->setAttributes(AS);
151 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
Reid Kleckner67077702017-03-21 16:57:19 +0000152 AttributeList AS = CI->getAttributes();
Reid Kleckner7dde8e82017-04-10 23:31:05 +0000153 AttrBuilder FnAttrs(AS.getFnAttributes());
154 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendlingf5467622013-02-12 10:13:06 +0000155 FnAttrs.merge(B);
Reid Klecknerd6b4b102017-04-19 17:28:52 +0000156 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
157 AttributeSet::get(Context, FnAttrs));
Bill Wendlingbaad55c2013-02-08 06:32:06 +0000158 CI->setAttributes(AS);
159 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
Reid Kleckner67077702017-03-21 16:57:19 +0000160 AttributeList AS = II->getAttributes();
Reid Kleckner7dde8e82017-04-10 23:31:05 +0000161 AttrBuilder FnAttrs(AS.getFnAttributes());
162 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendlingf5467622013-02-12 10:13:06 +0000163 FnAttrs.merge(B);
Reid Klecknerd6b4b102017-04-19 17:28:52 +0000164 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
165 AttributeSet::get(Context, FnAttrs));
Bill Wendlingbaad55c2013-02-08 06:32:06 +0000166 II->setAttributes(AS);
Javed Absara8ddcaa2017-05-11 12:28:08 +0000167 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
168 AttrBuilder Attrs(GV->getAttributes());
169 Attrs.merge(B);
170 GV->setAttributes(AttributeSet::get(Context,Attrs));
Bill Wendlingbaad55c2013-02-08 06:32:06 +0000171 } else {
172 llvm_unreachable("invalid object with forward attribute group reference");
173 }
174 }
Michael Ilseman407a6162012-11-15 22:34:00 +0000175
Duncan P. N. Exon Smith16589782014-08-19 00:13:19 +0000176 // If there are entries in ForwardRefBlockAddresses at this point, the
177 // function was never defined.
178 if (!ForwardRefBlockAddresses.empty())
179 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
180 "expected function name in blockaddress");
Michael Ilseman407a6162012-11-15 22:34:00 +0000181
David Majnemer4762c0b2015-02-11 07:43:56 +0000182 for (const auto &NT : NumberedTypes)
183 if (NT.second.second.isValid())
184 return Error(NT.second.second,
185 "use of undefined type '%" + Twine(NT.first) + "'");
Chris Lattner1afcace2011-07-09 17:41:24 +0000186
187 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
188 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
189 if (I->second.second.isValid())
190 return Error(I->second.second,
191 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000192
David Majnemerc8a11692014-06-27 18:19:56 +0000193 if (!ForwardRefComdats.empty())
194 return Error(ForwardRefComdats.begin()->second,
195 "use of undefined comdat '$" +
196 ForwardRefComdats.begin()->first + "'");
197
Chris Lattnerdf986172009-01-02 07:01:27 +0000198 if (!ForwardRefVals.empty())
199 return Error(ForwardRefVals.begin()->second.second,
200 "use of undefined value '@" + ForwardRefVals.begin()->first +
201 "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000202
Chris Lattnerdf986172009-01-02 07:01:27 +0000203 if (!ForwardRefValIDs.empty())
204 return Error(ForwardRefValIDs.begin()->second.second,
205 "use of undefined value '@" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000206 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000207
Devang Patel1c7eea62009-07-08 19:23:54 +0000208 if (!ForwardRefMDNodes.empty())
209 return Error(ForwardRefMDNodes.begin()->second.second,
210 "use of undefined metadata '!" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000211 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000212
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000213 // Resolve metadata cycles.
David Majnemer4762c0b2015-02-11 07:43:56 +0000214 for (auto &N : NumberedMetadata) {
215 if (N.second && !N.second->isResolved())
216 N.second->resolveCycles();
217 }
Devang Patel1c7eea62009-07-08 19:23:54 +0000218
Mehdi Aminia3648252016-09-14 22:29:59 +0000219 for (auto *Inst : InstsWithTBAATag) {
220 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
221 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
222 auto *UpgradedMD = UpgradeTBAANode(*MD);
223 if (MD != UpgradedMD)
224 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
225 }
Duncan P. N. Exon Smith13d5c582016-04-06 02:06:40 +0000226
Chris Lattnerdf986172009-01-02 07:01:27 +0000227 // Look for intrinsic functions and CallInst that need to be upgraded
228 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
Duncan P. N. Exon Smith090db022015-10-20 01:12:49 +0000229 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
Daniel Dunbara279bc32009-09-20 02:20:51 +0000230
Artur Pilipenko140d9e62016-06-24 15:10:29 +0000231 // Some types could be renamed during loading if several modules are
232 // loaded in the same LLVMContext (LTO scenario). In this case we should
233 // remangle intrinsics names as well.
234 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
235 Function *F = &*FI++;
236 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
237 F->replaceAllUsesWith(Remangled.getValue());
238 F->eraseFromParent();
239 }
240 }
241
Adrian Prantl733fe2f2017-10-02 18:31:29 +0000242 if (UpgradeDebugInfo)
243 llvm::UpgradeDebugInfo(*M);
Manman Ren7d318bd2013-12-02 21:29:56 +0000244
Manman Renb9f73592016-05-25 23:14:48 +0000245 UpgradeModuleFlags(*M);
Saleem Abdulrasoolfe63ecd2017-10-06 18:06:59 +0000246 UpgradeSectionAttributes(*M);
Manman Renb9f73592016-05-25 23:14:48 +0000247
Alex Lorenzd31dc692015-06-23 17:10:10 +0000248 if (!Slots)
249 return false;
250 // Initialize the slot mapping.
251 // Because by this point we've parsed and validated everything, we can "steal"
252 // the mapping from LLParser as it doesn't need it anymore.
253 Slots->GlobalValues = std::move(NumberedVals);
254 Slots->MetadataNodes = std::move(NumberedMetadata);
Alex Lorenz0e998762015-08-21 21:32:39 +0000255 for (const auto &I : NamedTypes)
256 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
257 for (const auto &I : NumberedTypes)
258 Slots->Types.insert(std::make_pair(I.first, I.second.first));
Alex Lorenzd31dc692015-06-23 17:10:10 +0000259
Chris Lattnerdf986172009-01-02 07:01:27 +0000260 return false;
261}
262
Teresa Johnsonc6dda902018-06-26 13:56:49 +0000263/// Do final validity and sanity checks at the end of the index.
264bool LLParser::ValidateEndOfIndex() {
265 if (!Index)
266 return false;
267
268 if (!ForwardRefValueInfos.empty())
269 return Error(ForwardRefValueInfos.begin()->second.front().second,
270 "use of undefined summary '^" +
271 Twine(ForwardRefValueInfos.begin()->first) + "'");
272
273 if (!ForwardRefAliasees.empty())
274 return Error(ForwardRefAliasees.begin()->second.front().second,
275 "use of undefined summary '^" +
276 Twine(ForwardRefAliasees.begin()->first) + "'");
277
278 if (!ForwardRefTypeIds.empty())
279 return Error(ForwardRefTypeIds.begin()->second.front().second,
280 "use of undefined type id summary '^" +
281 Twine(ForwardRefTypeIds.begin()->first) + "'");
282
283 return false;
284}
285
Chris Lattnerdf986172009-01-02 07:01:27 +0000286//===----------------------------------------------------------------------===//
287// Top-Level Entities
288//===----------------------------------------------------------------------===//
289
290bool LLParser::ParseTopLevelEntities() {
Teresa Johnsonc6dda902018-06-26 13:56:49 +0000291 // If there is no Module, then parse just the summary index entries.
292 if (!M) {
293 while (true) {
294 switch (Lex.getKind()) {
295 case lltok::Eof:
296 return false;
297 case lltok::SummaryID:
298 if (ParseSummaryEntry())
299 return true;
300 break;
301 case lltok::kw_source_filename:
302 if (ParseSourceFileName())
303 return true;
304 break;
305 default:
306 // Skip everything else
307 Lex.Lex();
308 }
309 }
310 }
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +0000311 while (true) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000312 switch (Lex.getKind()) {
313 default: return TokError("expected top-level entity");
314 case lltok::Eof: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000315 case lltok::kw_declare: if (ParseDeclare()) return true; break;
316 case lltok::kw_define: if (ParseDefine()) return true; break;
317 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
318 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Teresa Johnson2dec5fc2016-03-30 18:15:08 +0000319 case lltok::kw_source_filename:
320 if (ParseSourceFileName())
321 return true;
322 break;
Bill Wendling3defc0b2012-11-28 08:41:48 +0000323 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000324 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000325 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000326 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000327 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerc8a11692014-06-27 18:19:56 +0000328 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattnere434d272009-12-30 04:56:59 +0000329 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Teresa Johnsona9a21472018-05-26 02:34:13 +0000330 case lltok::SummaryID:
331 if (ParseSummaryEntry())
332 return true;
333 break;
Bill Wendling95ce4c22013-02-06 06:52:58 +0000334 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Bill Wendling0b778662013-02-09 15:48:49 +0000335 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith78388182014-08-19 21:30:15 +0000336 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
337 case lltok::kw_uselistorder_bb:
Davide Italianofb0de922016-08-26 18:05:03 +0000338 if (ParseUseListOrderBB())
339 return true;
340 break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000341 }
342 }
343}
344
Chris Lattnerdf986172009-01-02 07:01:27 +0000345/// toplevelentity
346/// ::= 'module' 'asm' STRINGCONSTANT
347bool LLParser::ParseModuleAsm() {
348 assert(Lex.getKind() == lltok::kw_module);
349 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000350
351 std::string AsmStr;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000352 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
353 ParseStringConstant(AsmStr)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000354
Rafael Espindola38c4e532011-03-02 04:14:42 +0000355 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000356 return false;
357}
358
359/// toplevelentity
360/// ::= 'target' 'triple' '=' STRINGCONSTANT
361/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
362bool LLParser::ParseTargetDefinition() {
363 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000364 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000365 switch (Lex.Lex()) {
366 default: return TokError("unknown target property");
367 case lltok::kw_triple:
368 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000369 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
370 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000371 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000372 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000373 return false;
374 case lltok::kw_datalayout:
375 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000376 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
377 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000378 return true;
Yaxun Liu7c2d0492018-01-30 22:32:39 +0000379 if (DataLayoutStr.empty())
380 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000381 return false;
382 }
383}
384
Bill Wendling3defc0b2012-11-28 08:41:48 +0000385/// toplevelentity
Teresa Johnson2dec5fc2016-03-30 18:15:08 +0000386/// ::= 'source_filename' '=' STRINGCONSTANT
387bool LLParser::ParseSourceFileName() {
388 assert(Lex.getKind() == lltok::kw_source_filename);
Teresa Johnson2dec5fc2016-03-30 18:15:08 +0000389 Lex.Lex();
390 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
Teresa Johnsonc6dda902018-06-26 13:56:49 +0000391 ParseStringConstant(SourceFileName))
Teresa Johnson2dec5fc2016-03-30 18:15:08 +0000392 return true;
Teresa Johnsonc6dda902018-06-26 13:56:49 +0000393 if (M)
394 M->setSourceFileName(SourceFileName);
Teresa Johnson2dec5fc2016-03-30 18:15:08 +0000395 return false;
396}
397
398/// toplevelentity
Bill Wendling3defc0b2012-11-28 08:41:48 +0000399/// ::= 'deplibs' '=' '[' ']'
400/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
401/// FIXME: Remove in 4.0. Currently parse, but ignore.
402bool LLParser::ParseDepLibs() {
403 assert(Lex.getKind() == lltok::kw_deplibs);
404 Lex.Lex();
405 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
406 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
407 return true;
408
409 if (EatIfPresent(lltok::rsquare))
410 return false;
411
412 do {
413 std::string Str;
414 if (ParseStringConstant(Str)) return true;
415 } while (EatIfPresent(lltok::comma));
416
417 return ParseToken(lltok::rsquare, "expected ']' at end of list");
418}
419
Dan Gohman3845e502009-08-12 23:32:33 +0000420/// ParseUnnamedType:
Dan Gohman3845e502009-08-12 23:32:33 +0000421/// ::= LocalVarID '=' 'type' type
Chris Lattnerdf986172009-01-02 07:01:27 +0000422bool LLParser::ParseUnnamedType() {
Chris Lattneredcaca82011-06-18 23:51:31 +0000423 LocTy TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +0000424 unsigned TypeID = Lex.getUIntVal();
Chris Lattnera53616d2011-06-19 00:03:46 +0000425 Lex.Lex(); // eat LocalVarID;
426
427 if (ParseToken(lltok::equal, "expected '=' after name") ||
428 ParseToken(lltok::kw_type, "expected 'type' after '='"))
429 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000430
Craig Topper0b6cb712014-04-15 06:32:26 +0000431 Type *Result = nullptr;
Chris Lattner1afcace2011-07-09 17:41:24 +0000432 if (ParseStructDefinition(TypeLoc, "",
433 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman407a6162012-11-15 22:34:00 +0000434
Chris Lattner1afcace2011-07-09 17:41:24 +0000435 if (!isa<StructType>(Result)) {
436 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
437 if (Entry.first)
438 return Error(TypeLoc, "non-struct types may not be recursive");
439 Entry.first = Result;
440 Entry.second = SMLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +0000441 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000442
Chris Lattnerdf986172009-01-02 07:01:27 +0000443 return false;
444}
445
446/// toplevelentity
447/// ::= LocalVar '=' 'type' type
448bool LLParser::ParseNamedType() {
449 std::string Name = Lex.getStrVal();
450 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000451 Lex.Lex(); // eat LocalVar.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000452
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000453 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattner1afcace2011-07-09 17:41:24 +0000454 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000455 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +0000456
Craig Topper0b6cb712014-04-15 06:32:26 +0000457 Type *Result = nullptr;
Chris Lattner1afcace2011-07-09 17:41:24 +0000458 if (ParseStructDefinition(NameLoc, Name,
459 NamedTypes[Name], Result)) return true;
Michael Ilseman407a6162012-11-15 22:34:00 +0000460
Chris Lattner1afcace2011-07-09 17:41:24 +0000461 if (!isa<StructType>(Result)) {
462 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
463 if (Entry.first)
464 return Error(NameLoc, "non-struct types may not be recursive");
465 Entry.first = Result;
466 Entry.second = SMLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +0000467 }
Michael Ilseman407a6162012-11-15 22:34:00 +0000468
Chris Lattner1afcace2011-07-09 17:41:24 +0000469 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000470}
471
Chris Lattnerdf986172009-01-02 07:01:27 +0000472/// toplevelentity
473/// ::= 'declare' FunctionHeader
474bool LLParser::ParseDeclare() {
475 assert(Lex.getKind() == lltok::kw_declare);
476 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000477
Peter Collingbourne99e2e272016-06-21 23:42:48 +0000478 std::vector<std::pair<unsigned, MDNode *>> MDs;
479 while (Lex.getKind() == lltok::MetadataVar) {
480 unsigned MDK;
481 MDNode *N;
482 if (ParseMetadataAttachment(MDK, N))
483 return true;
484 MDs.push_back({MDK, N});
485 }
486
Chris Lattnerdf986172009-01-02 07:01:27 +0000487 Function *F;
Peter Collingbourne99e2e272016-06-21 23:42:48 +0000488 if (ParseFunctionHeader(F, false))
489 return true;
490 for (auto &MD : MDs)
491 F->addMetadata(MD.first, *MD.second);
492 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000493}
494
495/// toplevelentity
Duncan P. N. Exon Smithae321142015-04-24 22:04:41 +0000496/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
Chris Lattnerdf986172009-01-02 07:01:27 +0000497bool LLParser::ParseDefine() {
498 assert(Lex.getKind() == lltok::kw_define);
499 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000500
Chris Lattnerdf986172009-01-02 07:01:27 +0000501 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000502 return ParseFunctionHeader(F, true) ||
Duncan P. N. Exon Smithae321142015-04-24 22:04:41 +0000503 ParseOptionalFunctionMetadata(*F) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000504 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000505}
506
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000507/// ParseGlobalType
508/// ::= 'constant'
509/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000510bool LLParser::ParseGlobalType(bool &IsConstant) {
511 if (Lex.getKind() == lltok::kw_constant)
512 IsConstant = true;
513 else if (Lex.getKind() == lltok::kw_global)
514 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000515 else {
516 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000517 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000518 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000519 Lex.Lex();
520 return false;
521}
522
Peter Collingbourne63b34cd2016-06-14 21:01:22 +0000523bool LLParser::ParseOptionalUnnamedAddr(
524 GlobalVariable::UnnamedAddr &UnnamedAddr) {
525 if (EatIfPresent(lltok::kw_unnamed_addr))
526 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
527 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
528 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
529 else
530 UnnamedAddr = GlobalValue::UnnamedAddr::None;
531 return false;
532}
533
Dan Gohman3845e502009-08-12 23:32:33 +0000534/// ParseUnnamedGlobal:
Dmitry Polukhinba492232016-04-07 12:32:19 +0000535/// OptionalVisibility (ALIAS | IFUNC) ...
Sean Fertile509132b2017-10-26 15:00:26 +0000536/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
537/// OptionalDLLStorageClass
Nico Rieck38f68c52014-01-14 15:22:47 +0000538/// ... -> global variable
Dmitry Polukhinba492232016-04-07 12:32:19 +0000539/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
Sean Fertile509132b2017-10-26 15:00:26 +0000540/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
541/// OptionalDLLStorageClass
Nico Rieck38f68c52014-01-14 15:22:47 +0000542/// ... -> global variable
Dan Gohman3845e502009-08-12 23:32:33 +0000543bool LLParser::ParseUnnamedGlobal() {
544 unsigned VarID = NumberedVals.size();
545 std::string Name;
546 LocTy NameLoc = Lex.getLoc();
547
548 // Handle the GlobalID form.
549 if (Lex.getKind() == lltok::GlobalID) {
550 if (Lex.getUIntVal() != VarID)
551 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000552 Twine(VarID) + "'");
Dan Gohman3845e502009-08-12 23:32:33 +0000553 Lex.Lex(); // eat GlobalID;
554
555 if (ParseToken(lltok::equal, "expected '=' after name"))
556 return true;
557 }
558
559 bool HasLinkage;
Nico Rieck38f68c52014-01-14 15:22:47 +0000560 unsigned Linkage, Visibility, DLLStorageClass;
Sean Fertile509132b2017-10-26 15:00:26 +0000561 bool DSOLocal;
Rafael Espindola665d42a2014-05-28 18:15:43 +0000562 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne63b34cd2016-06-14 21:01:22 +0000563 GlobalVariable::UnnamedAddr UnnamedAddr;
Sean Fertile509132b2017-10-26 15:00:26 +0000564 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
565 DSOLocal) ||
Peter Collingbourne63b34cd2016-06-14 21:01:22 +0000566 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman3845e502009-08-12 23:32:33 +0000567 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000568
Dmitry Polukhinba492232016-04-07 12:32:19 +0000569 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck38f68c52014-01-14 15:22:47 +0000570 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Sean Fertile509132b2017-10-26 15:00:26 +0000571 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Dmitry Polukhin51a06a22016-04-05 08:47:51 +0000572
573 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
Sean Fertile509132b2017-10-26 15:00:26 +0000574 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Dan Gohman3845e502009-08-12 23:32:33 +0000575}
576
Chris Lattnerdf986172009-01-02 07:01:27 +0000577/// ParseNamedGlobal:
Dmitry Polukhinba492232016-04-07 12:32:19 +0000578/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
Sean Fertile509132b2017-10-26 15:00:26 +0000579/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
580/// OptionalVisibility OptionalDLLStorageClass
Nico Rieck38f68c52014-01-14 15:22:47 +0000581/// ... -> global variable
Chris Lattnerdf986172009-01-02 07:01:27 +0000582bool LLParser::ParseNamedGlobal() {
583 assert(Lex.getKind() == lltok::GlobalVar);
584 LocTy NameLoc = Lex.getLoc();
585 std::string Name = Lex.getStrVal();
586 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000587
Chris Lattnerdf986172009-01-02 07:01:27 +0000588 bool HasLinkage;
Nico Rieck38f68c52014-01-14 15:22:47 +0000589 unsigned Linkage, Visibility, DLLStorageClass;
Sean Fertile509132b2017-10-26 15:00:26 +0000590 bool DSOLocal;
Rafael Espindola665d42a2014-05-28 18:15:43 +0000591 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne63b34cd2016-06-14 21:01:22 +0000592 GlobalVariable::UnnamedAddr UnnamedAddr;
Chris Lattnerdf986172009-01-02 07:01:27 +0000593 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
Sean Fertile509132b2017-10-26 15:00:26 +0000594 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
595 DSOLocal) ||
Peter Collingbourne63b34cd2016-06-14 21:01:22 +0000596 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerdf986172009-01-02 07:01:27 +0000597 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000598
Dmitry Polukhinba492232016-04-07 12:32:19 +0000599 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck38f68c52014-01-14 15:22:47 +0000600 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Sean Fertile509132b2017-10-26 15:00:26 +0000601 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Rafael Espindolad5712052014-07-30 22:51:54 +0000602
Dmitry Polukhin51a06a22016-04-05 08:47:51 +0000603 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
Sean Fertile509132b2017-10-26 15:00:26 +0000604 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000605}
606
David Majnemerc8a11692014-06-27 18:19:56 +0000607bool LLParser::parseComdat() {
608 assert(Lex.getKind() == lltok::ComdatVar);
609 std::string Name = Lex.getStrVal();
610 LocTy NameLoc = Lex.getLoc();
611 Lex.Lex();
612
613 if (ParseToken(lltok::equal, "expected '=' here"))
614 return true;
615
616 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
617 return TokError("expected comdat type");
618
619 Comdat::SelectionKind SK;
620 switch (Lex.getKind()) {
621 default:
622 return TokError("unknown selection kind");
623 case lltok::kw_any:
624 SK = Comdat::Any;
625 break;
626 case lltok::kw_exactmatch:
627 SK = Comdat::ExactMatch;
628 break;
629 case lltok::kw_largest:
630 SK = Comdat::Largest;
631 break;
632 case lltok::kw_noduplicates:
633 SK = Comdat::NoDuplicates;
634 break;
635 case lltok::kw_samesize:
636 SK = Comdat::SameSize;
637 break;
638 }
639 Lex.Lex();
640
641 // See if the comdat was forward referenced, if so, use the comdat.
642 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
643 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
644 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
645 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
646
647 Comdat *C;
648 if (I != ComdatSymTab.end())
649 C = &I->second;
650 else
651 C = M->getOrInsertComdat(Name);
652 C->setSelectionKind(SK);
653
654 return false;
655}
656
Devang Patel256be962009-07-20 19:00:08 +0000657// MDString:
658// ::= '!' STRINGCONSTANT
Chris Lattner442ffa12009-12-29 21:53:55 +0000659bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000660 std::string Str;
661 if (ParseStringConstant(Str)) return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000662 Result = MDString::get(Context, Str);
Devang Patel256be962009-07-20 19:00:08 +0000663 return false;
664}
665
666// MDNode:
667// ::= '!' MDNodeNumber
Chris Lattner4a72efc2009-12-30 04:15:23 +0000668bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000669 // !{ ..., !42, ... }
Duncan P. N. Exon Smith13d5c582016-04-06 02:06:40 +0000670 LocTy IDLoc = Lex.getLoc();
Devang Patel256be962009-07-20 19:00:08 +0000671 unsigned MID = 0;
Duncan P. N. Exon Smith023f8e42015-01-12 21:14:38 +0000672 if (ParseUInt32(MID))
673 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000674
Chris Lattner449c3102010-04-01 05:14:45 +0000675 // If not a forward reference, just return it now.
David Majnemer4762c0b2015-02-11 07:43:56 +0000676 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smith023f8e42015-01-12 21:14:38 +0000677 Result = NumberedMetadata[MID];
678 return false;
679 }
Devang Patel256be962009-07-20 19:00:08 +0000680
Chris Lattner449c3102010-04-01 05:14:45 +0000681 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smithf9eaea72015-01-19 21:30:18 +0000682 auto &FwdRef = ForwardRefMDNodes[MID];
Duncan P. N. Exon Smith13d5c582016-04-06 02:06:40 +0000683 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
Michael Ilseman407a6162012-11-15 22:34:00 +0000684
Duncan P. N. Exon Smithf9eaea72015-01-19 21:30:18 +0000685 Result = FwdRef.first.get();
686 NumberedMetadata[MID].reset(Result);
Devang Patel256be962009-07-20 19:00:08 +0000687 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000688}
Devang Patel256be962009-07-20 19:00:08 +0000689
Chris Lattner84d03b12009-12-29 22:35:39 +0000690/// ParseNamedMetadata:
Devang Pateleff2ab62009-07-29 00:34:02 +0000691/// !foo = !{ !1, !2 }
692bool LLParser::ParseNamedMetadata() {
Chris Lattner1d928312009-12-30 05:02:06 +0000693 assert(Lex.getKind() == lltok::MetadataVar);
Devang Pateleff2ab62009-07-29 00:34:02 +0000694 std::string Name = Lex.getStrVal();
Chris Lattner1d928312009-12-30 05:02:06 +0000695 Lex.Lex();
Devang Pateleff2ab62009-07-29 00:34:02 +0000696
Chris Lattner84d03b12009-12-29 22:35:39 +0000697 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattnere434d272009-12-30 04:56:59 +0000698 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner84d03b12009-12-29 22:35:39 +0000699 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Pateleff2ab62009-07-29 00:34:02 +0000700 return true;
701
Dan Gohman17aa92c2010-07-21 23:38:33 +0000702 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000703 if (Lex.getKind() != lltok::rbrace)
704 do {
Craig Topper0b6cb712014-04-15 06:32:26 +0000705 MDNode *N = nullptr;
Reid Klecknera5b2af02017-08-23 20:31:27 +0000706 // Parse DIExpressions inline as a special case. They are still MDNodes,
707 // so they can still appear in named metadata. Remove this logic if they
708 // become plain Metadata.
709 if (Lex.getKind() == lltok::MetadataVar &&
710 Lex.getStrVal() == "DIExpression") {
711 if (ParseDIExpression(N, /*IsDistinct=*/false))
712 return true;
713 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
714 ParseMDNodeID(N)) {
715 return true;
716 }
Dan Gohman17aa92c2010-07-21 23:38:33 +0000717 NMD->addOperand(N);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000718 } while (EatIfPresent(lltok::comma));
Devang Pateleff2ab62009-07-29 00:34:02 +0000719
Rafael Espindola8a7b4ea2015-05-26 20:37:36 +0000720 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Pateleff2ab62009-07-29 00:34:02 +0000721}
722
Devang Patel923078c2009-07-01 19:21:12 +0000723/// ParseStandaloneMetadata:
Daniel Dunbara279bc32009-09-20 02:20:51 +0000724/// !42 = !{...}
Devang Patel923078c2009-07-01 19:21:12 +0000725bool LLParser::ParseStandaloneMetadata() {
Chris Lattnere434d272009-12-30 04:56:59 +0000726 assert(Lex.getKind() == lltok::exclaim);
Devang Patel923078c2009-07-01 19:21:12 +0000727 Lex.Lex();
728 unsigned MetadataID = 0;
Devang Patel923078c2009-07-01 19:21:12 +0000729
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000730 MDNode *Init;
Chris Lattner3f5132a2009-12-29 22:40:21 +0000731 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smith1ef70ff2014-12-15 19:07:53 +0000732 ParseToken(lltok::equal, "expected '=' here"))
733 return true;
734
735 // Detect common error, from old metadata syntax.
736 if (Lex.getKind() == lltok::Type)
737 return TokError("unexpected type in metadata definition");
738
Duncan P. N. Exon Smithf416d722015-01-08 22:38:29 +0000739 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith3b0fe4e2015-01-13 21:10:44 +0000740 if (Lex.getKind() == lltok::MetadataVar) {
741 if (ParseSpecializedMDNode(Init, IsDistinct))
742 return true;
743 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
744 ParseMDTuple(Init, IsDistinct))
Devang Patel104cf9e2009-07-23 01:07:34 +0000745 return true;
746
Chris Lattner0834e6a2009-12-30 04:51:58 +0000747 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000748 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Patel1c7eea62009-07-08 19:23:54 +0000749 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smithf9eaea72015-01-19 21:30:18 +0000750 FI->second.first->replaceAllUsesWith(Init);
Devang Patel1c7eea62009-07-08 19:23:54 +0000751 ForwardRefMDNodes.erase(FI);
Michael Ilseman407a6162012-11-15 22:34:00 +0000752
Chris Lattner0834e6a2009-12-30 04:51:58 +0000753 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
754 } else {
David Majnemer4762c0b2015-02-11 07:43:56 +0000755 if (NumberedMetadata.count(MetadataID))
Chris Lattner0834e6a2009-12-30 04:51:58 +0000756 return TokError("Metadata id is already used");
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000757 NumberedMetadata[MetadataID].reset(Init);
Devang Patel1c7eea62009-07-08 19:23:54 +0000758 }
759
Devang Patel923078c2009-07-01 19:21:12 +0000760 return false;
761}
762
Teresa Johnsona9a21472018-05-26 02:34:13 +0000763// Skips a single module summary entry.
764bool LLParser::SkipModuleSummaryEntry() {
765 // Each module summary entry consists of a tag for the entry
766 // type, followed by a colon, then the fields surrounded by nested sets of
767 // parentheses. The "tag:" looks like a Label. Once parsing support is
768 // in place we will look for the tokens corresponding to the expected tags.
Teresa Johnsonc6dda902018-06-26 13:56:49 +0000769 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
770 Lex.getKind() != lltok::kw_typeid)
771 return TokError(
772 "Expected 'gv', 'module', or 'typeid' at the start of summary entry");
773 Lex.Lex();
774 if (ParseToken(lltok::colon, "expected ':' at start of summary entry") ||
Teresa Johnsona9a21472018-05-26 02:34:13 +0000775 ParseToken(lltok::lparen, "expected '(' at start of summary entry"))
776 return true;
777 // Now walk through the parenthesized entry, until the number of open
778 // parentheses goes back down to 0 (the first '(' was parsed above).
779 unsigned NumOpenParen = 1;
780 do {
781 switch (Lex.getKind()) {
782 case lltok::lparen:
783 NumOpenParen++;
784 break;
785 case lltok::rparen:
786 NumOpenParen--;
787 break;
788 case lltok::Eof:
789 return TokError("found end of file while parsing summary entry");
790 default:
791 // Skip everything in between parentheses.
792 break;
793 }
794 Lex.Lex();
795 } while (NumOpenParen > 0);
796 return false;
797}
798
Teresa Johnsonc6dda902018-06-26 13:56:49 +0000799/// SummaryEntry
800/// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
Teresa Johnsona9a21472018-05-26 02:34:13 +0000801bool LLParser::ParseSummaryEntry() {
802 assert(Lex.getKind() == lltok::SummaryID);
Teresa Johnsonc6dda902018-06-26 13:56:49 +0000803 unsigned SummaryID = Lex.getUIntVal();
804
805 // For summary entries, colons should be treated as distinct tokens,
806 // not an indication of the end of a label token.
807 Lex.setIgnoreColonInIdentifiers(true);
Teresa Johnsona9a21472018-05-26 02:34:13 +0000808
809 Lex.Lex();
810 if (ParseToken(lltok::equal, "expected '=' here"))
811 return true;
812
Teresa Johnsonc6dda902018-06-26 13:56:49 +0000813 // If we don't have an index object, skip the summary entry.
814 if (!Index)
815 return SkipModuleSummaryEntry();
816
817 switch (Lex.getKind()) {
818 case lltok::kw_gv:
819 return ParseGVEntry(SummaryID);
820 case lltok::kw_module:
821 return ParseModuleEntry(SummaryID);
822 case lltok::kw_typeid:
823 return ParseTypeIdEntry(SummaryID);
824 break;
825 default:
826 return Error(Lex.getLoc(), "unexpected summary kind");
827 }
828 Lex.setIgnoreColonInIdentifiers(false);
Teresa Johnsona9a21472018-05-26 02:34:13 +0000829 return false;
830}
831
Duncan P. N. Exon Smith76c17d32014-05-07 22:57:20 +0000832static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
833 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
834 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
835}
836
Rafael Espindola1e1801c2018-01-11 22:15:05 +0000837// If there was an explicit dso_local, update GV. In the absence of an explicit
838// dso_local we keep the default value.
839static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
840 if (DSOLocal)
841 GV.setDSOLocal(true);
842}
843
Dmitry Polukhin51a06a22016-04-05 08:47:51 +0000844/// parseIndirectSymbol:
Fangrui Songaf7b1832018-07-30 19:41:25 +0000845/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
Sean Fertile509132b2017-10-26 15:00:26 +0000846/// OptionalVisibility OptionalDLLStorageClass
847/// OptionalThreadLocal OptionalUnnamedAddr
848// 'alias|ifunc' IndirectSymbol
Rafael Espindola27c076a2014-05-16 19:35:39 +0000849///
Dmitry Polukhin51a06a22016-04-05 08:47:51 +0000850/// IndirectSymbol
Chris Lattner040f7582009-04-25 21:26:00 +0000851/// ::= TypeAndValue
Chris Lattnerdf986172009-01-02 07:01:27 +0000852///
Eric Christopher7984aa92015-05-28 23:07:39 +0000853/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerdf986172009-01-02 07:01:27 +0000854///
Sean Fertile509132b2017-10-26 15:00:26 +0000855bool LLParser::parseIndirectSymbol(const std::string &Name, LocTy NameLoc,
856 unsigned L, unsigned Visibility,
857 unsigned DLLStorageClass, bool DSOLocal,
858 GlobalVariable::ThreadLocalMode TLM,
859 GlobalVariable::UnnamedAddr UnnamedAddr) {
Dmitry Polukhin51a06a22016-04-05 08:47:51 +0000860 bool IsAlias;
861 if (Lex.getKind() == lltok::kw_alias)
862 IsAlias = true;
Dmitry Polukhinba492232016-04-07 12:32:19 +0000863 else if (Lex.getKind() == lltok::kw_ifunc)
864 IsAlias = false;
Dmitry Polukhin51a06a22016-04-05 08:47:51 +0000865 else
Dmitry Polukhinba492232016-04-07 12:32:19 +0000866 llvm_unreachable("Not an alias or ifunc!");
Chris Lattnerdf986172009-01-02 07:01:27 +0000867 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +0000868
Rafael Espindola2def1792013-10-06 15:10:43 +0000869 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
870
Dmitry Polukhin51a06a22016-04-05 08:47:51 +0000871 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
Rafael Espindolad5712052014-07-30 22:51:54 +0000872 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000873
Duncan P. N. Exon Smith76c17d32014-05-07 22:57:20 +0000874 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindolad5712052014-07-30 22:51:54 +0000875 return Error(NameLoc,
Duncan P. N. Exon Smith76c17d32014-05-07 22:57:20 +0000876 "symbol with local linkage must have default visibility");
877
David Blaikie21f77df2015-09-11 03:22:04 +0000878 Type *Ty;
879 LocTy ExplicitTypeLoc = Lex.getLoc();
880 if (ParseType(Ty) ||
Dmitry Polukhinba492232016-04-07 12:32:19 +0000881 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
David Blaikie21f77df2015-09-11 03:22:04 +0000882 return true;
883
Rafael Espindola2d21b252014-06-03 02:41:57 +0000884 Constant *Aliasee;
885 LocTy AliaseeLoc = Lex.getLoc();
886 if (Lex.getKind() != lltok::kw_bitcast &&
887 Lex.getKind() != lltok::kw_getelementptr &&
888 Lex.getKind() != lltok::kw_addrspacecast &&
889 Lex.getKind() != lltok::kw_inttoptr) {
890 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola27c076a2014-05-16 19:35:39 +0000891 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000892 } else {
Rafael Espindola2d21b252014-06-03 02:41:57 +0000893 // The bitcast dest type is not present, it is implied by the dest type.
894 ValID ID;
895 if (ParseValID(ID))
896 return true;
897 if (ID.Kind != ValID::t_Constant)
898 return Error(AliaseeLoc, "invalid aliasee");
899 Aliasee = ID.ConstantVal;
Chris Lattnerdf986172009-01-02 07:01:27 +0000900 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000901
Rafael Espindola2d21b252014-06-03 02:41:57 +0000902 Type *AliaseeType = Aliasee->getType();
903 auto *PTy = dyn_cast<PointerType>(AliaseeType);
904 if (!PTy)
Dmitry Polukhinba492232016-04-07 12:32:19 +0000905 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
David Blaikie2d353482015-09-14 18:01:59 +0000906 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerdf986172009-01-02 07:01:27 +0000907
Dmitry Polukhin51a06a22016-04-05 08:47:51 +0000908 if (IsAlias && Ty != PTy->getElementType())
David Blaikie21f77df2015-09-11 03:22:04 +0000909 return Error(
910 ExplicitTypeLoc,
911 "explicit pointee type doesn't match operand's pointee type");
912
Dmitry Polukhin51a06a22016-04-05 08:47:51 +0000913 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
914 return Error(
915 ExplicitTypeLoc,
916 "explicit pointee type should be a function type");
917
Peter Collingbourne834f85c2015-11-25 02:54:07 +0000918 GlobalValue *GVal = nullptr;
919
920 // See if the alias was forward referenced, if so, prepare to replace the
921 // forward reference.
922 if (!Name.empty()) {
923 GVal = M->getNamedValue(Name);
924 if (GVal) {
925 if (!ForwardRefVals.erase(Name))
926 return Error(NameLoc, "redefinition of global '@" + Name + "'");
927 }
928 } else {
929 auto I = ForwardRefValIDs.find(NumberedVals.size());
930 if (I != ForwardRefValIDs.end()) {
931 GVal = I->second.first;
932 ForwardRefValIDs.erase(I);
933 }
934 }
935
Chris Lattnerdf986172009-01-02 07:01:27 +0000936 // Okay, create the alias but do not insert it into the module yet.
Dmitry Polukhin51a06a22016-04-05 08:47:51 +0000937 std::unique_ptr<GlobalIndirectSymbol> GA;
938 if (IsAlias)
939 GA.reset(GlobalAlias::create(Ty, AddrSpace,
940 (GlobalValue::LinkageTypes)Linkage, Name,
941 Aliasee, /*Parent*/ nullptr));
942 else
Dmitry Polukhinba492232016-04-07 12:32:19 +0000943 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
944 (GlobalValue::LinkageTypes)Linkage, Name,
945 Aliasee, /*Parent*/ nullptr));
Rafael Espindola665d42a2014-05-28 18:15:43 +0000946 GA->setThreadLocalMode(TLM);
Chris Lattnerdf986172009-01-02 07:01:27 +0000947 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck38f68c52014-01-14 15:22:47 +0000948 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola6fd1b8e2014-06-06 01:20:28 +0000949 GA->setUnnamedAddr(UnnamedAddr);
Rafael Espindola1e1801c2018-01-11 22:15:05 +0000950 maybeSetDSOLocal(DSOLocal, *GA);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000951
Rafael Espindola43e53492015-06-17 17:53:31 +0000952 if (Name.empty())
953 NumberedVals.push_back(GA.get());
954
Peter Collingbourne834f85c2015-11-25 02:54:07 +0000955 if (GVal) {
956 // Verify that types agree.
957 if (GVal->getType() != GA->getType())
958 return Error(
959 ExplicitTypeLoc,
960 "forward reference and definition of alias have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000961
Chris Lattnerdf986172009-01-02 07:01:27 +0000962 // If they agree, just RAUW the old value with the alias and remove the
963 // forward ref info.
Peter Collingbourne834f85c2015-11-25 02:54:07 +0000964 GVal->replaceAllUsesWith(GA.get());
965 GVal->eraseFromParent();
Chris Lattnerdf986172009-01-02 07:01:27 +0000966 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000967
Chris Lattnerdf986172009-01-02 07:01:27 +0000968 // Insert into the module, we know its name won't collide now.
Dmitry Polukhin51a06a22016-04-05 08:47:51 +0000969 if (IsAlias)
970 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
971 else
Dmitry Polukhinba492232016-04-07 12:32:19 +0000972 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
Benjamin Krameraf812352010-10-16 11:28:23 +0000973 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000974
Rafael Espindola1acea2d2014-05-09 21:49:17 +0000975 // The module owns this now
976 GA.release();
977
Chris Lattnerdf986172009-01-02 07:01:27 +0000978 return false;
979}
980
981/// ParseGlobal
Sean Fertile509132b2017-10-26 15:00:26 +0000982/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
983/// OptionalVisibility OptionalDLLStorageClass
Eric Christopher7984aa92015-05-28 23:07:39 +0000984/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Javed Absara8ddcaa2017-05-11 12:28:08 +0000985/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
Sean Fertile509132b2017-10-26 15:00:26 +0000986/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
987/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
988/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
989/// Const OptionalAttrs
Chris Lattnerdf986172009-01-02 07:01:27 +0000990///
Eric Christopher7984aa92015-05-28 23:07:39 +0000991/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemer39a09d22014-03-09 06:41:58 +0000992/// already.
Chris Lattnerdf986172009-01-02 07:01:27 +0000993///
994bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
995 unsigned Linkage, bool HasLinkage,
Rafael Espindola665d42a2014-05-28 18:15:43 +0000996 unsigned Visibility, unsigned DLLStorageClass,
Sean Fertile509132b2017-10-26 15:00:26 +0000997 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
Peter Collingbourne63b34cd2016-06-14 21:01:22 +0000998 GlobalVariable::UnnamedAddr UnnamedAddr) {
Duncan P. N. Exon Smith76c17d32014-05-07 22:57:20 +0000999 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1000 return Error(NameLoc,
1001 "symbol with local linkage must have default visibility");
1002
Chris Lattnerdf986172009-01-02 07:01:27 +00001003 unsigned AddrSpace;
Rafael Espindola6fd1b8e2014-06-06 01:20:28 +00001004 bool IsConstant, IsExternallyInitialized;
Michael Gottesmana2de37c2013-02-05 05:57:38 +00001005 LocTy IsExternallyInitializedLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00001006 LocTy TyLoc;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001007
Craig Topper0b6cb712014-04-15 06:32:26 +00001008 Type *Ty = nullptr;
Rafael Espindola665d42a2014-05-28 18:15:43 +00001009 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesmana2de37c2013-02-05 05:57:38 +00001010 ParseOptionalToken(lltok::kw_externally_initialized,
1011 IsExternallyInitialized,
1012 &IsExternallyInitializedLoc) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001013 ParseGlobalType(IsConstant) ||
1014 ParseType(Ty, TyLoc))
1015 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001016
Chris Lattnerdf986172009-01-02 07:01:27 +00001017 // If the linkage is specified and is external, then no initializer is
1018 // present.
Craig Topper0b6cb712014-04-15 06:32:26 +00001019 Constant *Init = nullptr;
Rafael Espindola06d92082016-05-11 13:51:39 +00001020 if (!HasLinkage ||
1021 !GlobalValue::isValidDeclarationLinkage(
1022 (GlobalValue::LinkageTypes)Linkage)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001023 if (ParseGlobalValue(Ty, Init))
1024 return true;
1025 }
1026
David Majnemer40d10632015-02-16 08:41:08 +00001027 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattner4a2f1122009-02-08 20:00:15 +00001028 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001029
David Majnemer2959baf2014-12-09 05:56:09 +00001030 GlobalValue *GVal = nullptr;
Chris Lattnerdf986172009-01-02 07:01:27 +00001031
1032 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad87d2009-02-02 07:24:28 +00001033 if (!Name.empty()) {
David Majnemer2959baf2014-12-09 05:56:09 +00001034 GVal = M->getNamedValue(Name);
1035 if (GVal) {
Peter Collingbourne834f85c2015-11-25 02:54:07 +00001036 if (!ForwardRefVals.erase(Name))
Chris Lattner1d871c52009-10-25 23:22:50 +00001037 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattner1d871c52009-10-25 23:22:50 +00001038 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001039 } else {
David Blaikie6030b442015-09-21 21:07:50 +00001040 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001041 if (I != ForwardRefValIDs.end()) {
David Majnemer2959baf2014-12-09 05:56:09 +00001042 GVal = I->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001043 ForwardRefValIDs.erase(I);
1044 }
1045 }
1046
David Majnemer2959baf2014-12-09 05:56:09 +00001047 GlobalVariable *GV;
1048 if (!GVal) {
Craig Topper0b6cb712014-04-15 06:32:26 +00001049 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
1050 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgce718ff2012-06-23 11:37:03 +00001051 AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +00001052 } else {
David Blaikie7c001da2015-05-13 22:55:01 +00001053 if (GVal->getValueType() != Ty)
Chris Lattnerdf986172009-01-02 07:01:27 +00001054 return Error(TyLoc,
1055 "forward reference and definition of global have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001056
David Majnemer2959baf2014-12-09 05:56:09 +00001057 GV = cast<GlobalVariable>(GVal);
1058
Chris Lattnerdf986172009-01-02 07:01:27 +00001059 // Move the forward-reference to the correct spot in the module.
1060 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
1061 }
1062
1063 if (Name.empty())
1064 NumberedVals.push_back(GV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001065
Chris Lattnerdf986172009-01-02 07:01:27 +00001066 // Set the parsed properties on the global.
1067 if (Init)
1068 GV->setInitializer(Init);
1069 GV->setConstant(IsConstant);
1070 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
Rafael Espindola1e1801c2018-01-11 22:15:05 +00001071 maybeSetDSOLocal(DSOLocal, *GV);
Chris Lattnerdf986172009-01-02 07:01:27 +00001072 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck38f68c52014-01-14 15:22:47 +00001073 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesmana2de37c2013-02-05 05:57:38 +00001074 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgce718ff2012-06-23 11:37:03 +00001075 GV->setThreadLocalMode(TLM);
Rafael Espindolabea46262011-01-08 16:42:36 +00001076 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001077
Chris Lattnerdf986172009-01-02 07:01:27 +00001078 // Parse attributes on the global.
1079 while (Lex.getKind() == lltok::comma) {
1080 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001081
Chris Lattnerdf986172009-01-02 07:01:27 +00001082 if (Lex.getKind() == lltok::kw_section) {
1083 Lex.Lex();
1084 GV->setSection(Lex.getStrVal());
1085 if (ParseToken(lltok::StringConstant, "expected global section string"))
1086 return true;
1087 } else if (Lex.getKind() == lltok::kw_align) {
1088 unsigned Alignment;
1089 if (ParseOptionalAlignment(Alignment)) return true;
1090 GV->setAlignment(Alignment);
Peter Collingbourne6aef9f92016-05-31 23:01:54 +00001091 } else if (Lex.getKind() == lltok::MetadataVar) {
1092 if (ParseGlobalObjectMetadataAttachment(*GV))
1093 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001094 } else {
David Majnemerc8a11692014-06-27 18:19:56 +00001095 Comdat *C;
Rafael Espindolaf907a262015-01-06 22:55:16 +00001096 if (parseOptionalComdat(Name, C))
David Majnemerc8a11692014-06-27 18:19:56 +00001097 return true;
1098 if (C)
1099 GV->setComdat(C);
1100 else
1101 return TokError("unknown global variable property!");
Chris Lattnerdf986172009-01-02 07:01:27 +00001102 }
1103 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001104
Javed Absara8ddcaa2017-05-11 12:28:08 +00001105 AttrBuilder Attrs;
1106 LocTy BuiltinLoc;
1107 std::vector<unsigned> FwdRefAttrGrps;
1108 if (ParseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1109 return true;
1110 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1111 GV->setAttributes(AttributeSet::get(Context, Attrs));
1112 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1113 }
1114
Chris Lattnerdf986172009-01-02 07:01:27 +00001115 return false;
1116}
1117
Bill Wendling95ce4c22013-02-06 06:52:58 +00001118/// ParseUnnamedAttrGrp
Bill Wendling0b778662013-02-09 15:48:49 +00001119/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling95ce4c22013-02-06 06:52:58 +00001120bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendling0b778662013-02-09 15:48:49 +00001121 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling95ce4c22013-02-06 06:52:58 +00001122 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendling0b778662013-02-09 15:48:49 +00001123 Lex.Lex();
1124
David Majnemerdb7b69e2014-12-09 18:33:57 +00001125 if (Lex.getKind() != lltok::AttrGrpID)
1126 return TokError("expected attribute group id");
1127
Bill Wendling95ce4c22013-02-06 06:52:58 +00001128 unsigned VarID = Lex.getUIntVal();
Bill Wendlingbaad55c2013-02-08 06:32:06 +00001129 std::vector<unsigned> unused;
Michael Gottesman2253a2f2013-06-27 00:25:01 +00001130 LocTy BuiltinLoc;
Bill Wendling95ce4c22013-02-06 06:52:58 +00001131 Lex.Lex();
1132
1133 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling95ce4c22013-02-06 06:52:58 +00001134 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling143d4642013-02-22 00:12:35 +00001135 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman2253a2f2013-06-27 00:25:01 +00001136 BuiltinLoc) ||
Bill Wendling95ce4c22013-02-06 06:52:58 +00001137 ParseToken(lltok::rbrace, "expected end of attribute group"))
1138 return true;
1139
Bill Wendlingbaad55c2013-02-08 06:32:06 +00001140 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling95ce4c22013-02-06 06:52:58 +00001141 return Error(AttrGrpLoc, "attribute group has no attributes");
1142
1143 return false;
1144}
1145
Bill Wendlingea007fa2013-02-08 00:52:31 +00001146/// ParseFnAttributeValuePairs
Bill Wendling95ce4c22013-02-06 06:52:58 +00001147/// ::= <attr> | <attr> '=' <value>
Bill Wendlingbaad55c2013-02-08 06:32:06 +00001148bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
1149 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman2253a2f2013-06-27 00:25:01 +00001150 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendlingea007fa2013-02-08 00:52:31 +00001151 bool HaveError = false;
1152
1153 B.clear();
1154
Bill Wendling95ce4c22013-02-06 06:52:58 +00001155 while (true) {
1156 lltok::Kind Token = Lex.getKind();
Michael Gottesman2253a2f2013-06-27 00:25:01 +00001157 if (Token == lltok::kw_builtin)
1158 BuiltinLoc = Lex.getLoc();
Bill Wendling95ce4c22013-02-06 06:52:58 +00001159 switch (Token) {
1160 default:
Bill Wendlingea007fa2013-02-08 00:52:31 +00001161 if (!inAttrGrp) return HaveError;
Bill Wendling95ce4c22013-02-06 06:52:58 +00001162 return Error(Lex.getLoc(), "unterminated attribute group");
1163 case lltok::rbrace:
1164 // Finished.
1165 return false;
1166
Bill Wendlingbaad55c2013-02-08 06:32:06 +00001167 case lltok::AttrGrpID: {
1168 // Allow a function to reference an attribute group:
1169 //
1170 // define void @foo() #1 { ... }
1171 if (inAttrGrp)
1172 HaveError |=
1173 Error(Lex.getLoc(),
1174 "cannot have an attribute group reference in an attribute group");
1175
1176 unsigned AttrGrpNum = Lex.getUIntVal();
1177 if (inAttrGrp) break;
1178
1179 // Save the reference to the attribute group. We'll fill it in later.
1180 FwdRefAttrGrps.push_back(AttrGrpNum);
1181 break;
1182 }
Bill Wendling95ce4c22013-02-06 06:52:58 +00001183 // Target-dependent attributes:
1184 case lltok::StringConstant: {
Artur Pilipenko9987cb62015-08-03 14:31:49 +00001185 if (ParseStringAttribute(B))
Bill Wendling95ce4c22013-02-06 06:52:58 +00001186 return true;
Bill Wendling0f742202013-02-10 10:12:50 +00001187 continue;
Bill Wendling95ce4c22013-02-06 06:52:58 +00001188 }
1189
1190 // Target-independent attributes:
1191 case lltok::kw_align: {
Bill Wendlingc0b4b672013-04-18 18:30:16 +00001192 // As a hack, we allow function alignment to be initially parsed as an
1193 // attribute on a function declaration/definition or added to an attribute
1194 // group and later moved to the alignment field.
Bill Wendling95ce4c22013-02-06 06:52:58 +00001195 unsigned Alignment;
Bill Wendlingea007fa2013-02-08 00:52:31 +00001196 if (inAttrGrp) {
Bill Wendling3f87d232013-02-10 23:15:51 +00001197 Lex.Lex();
Bill Wendlingea007fa2013-02-08 00:52:31 +00001198 if (ParseToken(lltok::equal, "expected '=' here") ||
1199 ParseUInt32(Alignment))
1200 return true;
1201 } else {
1202 if (ParseOptionalAlignment(Alignment))
1203 return true;
1204 }
Bill Wendling95ce4c22013-02-06 06:52:58 +00001205 B.addAlignmentAttr(Alignment);
Bill Wendlingea007fa2013-02-08 00:52:31 +00001206 continue;
Bill Wendling95ce4c22013-02-06 06:52:58 +00001207 }
1208 case lltok::kw_alignstack: {
1209 unsigned Alignment;
Bill Wendlingea007fa2013-02-08 00:52:31 +00001210 if (inAttrGrp) {
Bill Wendling3f87d232013-02-10 23:15:51 +00001211 Lex.Lex();
Bill Wendlingea007fa2013-02-08 00:52:31 +00001212 if (ParseToken(lltok::equal, "expected '=' here") ||
1213 ParseUInt32(Alignment))
1214 return true;
1215 } else {
1216 if (ParseOptionalStackAlignment(Alignment))
1217 return true;
1218 }
Bill Wendling95ce4c22013-02-06 06:52:58 +00001219 B.addStackAlignmentAttr(Alignment);
Bill Wendlingea007fa2013-02-08 00:52:31 +00001220 continue;
Bill Wendling95ce4c22013-02-06 06:52:58 +00001221 }
George Burgess IV274105b2016-04-12 01:05:35 +00001222 case lltok::kw_allocsize: {
1223 unsigned ElemSizeArg;
1224 Optional<unsigned> NumElemsArg;
1225 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1226 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1227 return true;
1228 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1229 continue;
1230 }
Igor Laevsky6690dbf2015-07-11 10:30:36 +00001231 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1232 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1233 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1234 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1235 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
Vaivaswatha Nagarajee7970e2015-12-16 16:16:19 +00001236 case lltok::kw_inaccessiblememonly:
1237 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1238 case lltok::kw_inaccessiblemem_or_argmemonly:
1239 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
Igor Laevsky6690dbf2015-07-11 10:30:36 +00001240 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1241 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1242 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1243 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1244 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1245 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1246 case lltok::kw_noimplicitfloat:
1247 B.addAttribute(Attribute::NoImplicitFloat); break;
1248 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1249 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1250 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1251 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
Oren Ben Simhon10c992c2018-03-17 13:29:46 +00001252 case lltok::kw_nocf_check: B.addAttribute(Attribute::NoCfCheck); break;
James Molloyd0019322015-11-06 10:32:53 +00001253 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
Igor Laevsky6690dbf2015-07-11 10:30:36 +00001254 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
Matt Morehouse7d085b62018-03-22 17:07:51 +00001255 case lltok::kw_optforfuzzing:
1256 B.addAttribute(Attribute::OptForFuzzing); break;
Igor Laevsky6690dbf2015-07-11 10:30:36 +00001257 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1258 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1259 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1260 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1261 case lltok::kw_returns_twice:
1262 B.addAttribute(Attribute::ReturnsTwice); break;
Matt Arsenaultea376da2017-04-28 20:25:27 +00001263 case lltok::kw_speculatable: B.addAttribute(Attribute::Speculatable); break;
Igor Laevsky6690dbf2015-07-11 10:30:36 +00001264 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1265 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1266 case lltok::kw_sspstrong:
1267 B.addAttribute(Attribute::StackProtectStrong); break;
1268 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
Vlad Tsyrklevich45013b22018-04-03 20:10:40 +00001269 case lltok::kw_shadowcallstack:
1270 B.addAttribute(Attribute::ShadowCallStack); break;
Igor Laevsky6690dbf2015-07-11 10:30:36 +00001271 case lltok::kw_sanitize_address:
1272 B.addAttribute(Attribute::SanitizeAddress); break;
Evgeniy Stepanovd47b5b32017-12-09 00:21:41 +00001273 case lltok::kw_sanitize_hwaddress:
1274 B.addAttribute(Attribute::SanitizeHWAddress); break;
Igor Laevsky6690dbf2015-07-11 10:30:36 +00001275 case lltok::kw_sanitize_thread:
1276 B.addAttribute(Attribute::SanitizeThread); break;
1277 case lltok::kw_sanitize_memory:
1278 B.addAttribute(Attribute::SanitizeMemory); break;
Chandler Carruthd2b1fb12018-09-04 12:38:00 +00001279 case lltok::kw_speculative_load_hardening:
1280 B.addAttribute(Attribute::SpeculativeLoadHardening);
1281 break;
Andrew Kaylor68d0bd12017-08-14 21:15:13 +00001282 case lltok::kw_strictfp: B.addAttribute(Attribute::StrictFP); break;
Igor Laevsky6690dbf2015-07-11 10:30:36 +00001283 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Nicolai Haehnleb07f5402016-07-04 08:01:29 +00001284 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendlingea007fa2013-02-08 00:52:31 +00001285
1286 // Error handling.
1287 case lltok::kw_inreg:
1288 case lltok::kw_signext:
1289 case lltok::kw_zeroext:
1290 HaveError |=
1291 Error(Lex.getLoc(),
1292 "invalid use of attribute on a function");
1293 break;
1294 case lltok::kw_byval:
Hal Finkel11af4b42014-07-18 15:51:28 +00001295 case lltok::kw_dereferenceable:
Sanjoy Das5ff59072015-04-16 20:29:50 +00001296 case lltok::kw_dereferenceable_or_null:
Reid Kleckner4b70bfc2013-12-19 02:14:12 +00001297 case lltok::kw_inalloca:
Bill Wendlingea007fa2013-02-08 00:52:31 +00001298 case lltok::kw_nest:
1299 case lltok::kw_noalias:
1300 case lltok::kw_nocapture:
Nick Lewyckyfe47ebf2014-05-20 01:23:40 +00001301 case lltok::kw_nonnull:
Stephen Lin456ca042013-04-20 05:14:40 +00001302 case lltok::kw_returned:
Bill Wendlingea007fa2013-02-08 00:52:31 +00001303 case lltok::kw_sret:
Manman Ren4bda8822016-04-01 21:41:15 +00001304 case lltok::kw_swifterror:
Manman Rend9e9e2b2016-03-29 17:37:21 +00001305 case lltok::kw_swiftself:
Bill Wendlingea007fa2013-02-08 00:52:31 +00001306 HaveError |=
1307 Error(Lex.getLoc(),
1308 "invalid use of parameter-only attribute on a function");
1309 break;
Bill Wendling95ce4c22013-02-06 06:52:58 +00001310 }
1311
1312 Lex.Lex();
1313 }
1314}
Chris Lattnerdf986172009-01-02 07:01:27 +00001315
1316//===----------------------------------------------------------------------===//
1317// GlobalValue Reference/Resolution Routines.
1318//===----------------------------------------------------------------------===//
1319
Karl Schimpfb80c5f52015-09-03 18:06:44 +00001320static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1321 const std::string &Name) {
1322 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Alexander Richardson47ff67b2018-08-23 09:25:17 +00001323 return Function::Create(FT, GlobalValue::ExternalWeakLinkage,
1324 PTy->getAddressSpace(), Name, M);
Karl Schimpfb80c5f52015-09-03 18:06:44 +00001325 else
1326 return new GlobalVariable(*M, PTy->getElementType(), false,
1327 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1328 nullptr, GlobalVariable::NotThreadLocal,
1329 PTy->getAddressSpace());
1330}
1331
Alexander Richardson47ff67b2018-08-23 09:25:17 +00001332Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1333 Value *Val, bool IsCall) {
1334 if (Val->getType() == Ty)
1335 return Val;
1336 // For calls we also accept variables in the program address space.
1337 Type *SuggestedTy = Ty;
1338 if (IsCall && isa<PointerType>(Ty)) {
1339 Type *TyInProgAS = cast<PointerType>(Ty)->getElementType()->getPointerTo(
1340 M->getDataLayout().getProgramAddressSpace());
1341 SuggestedTy = TyInProgAS;
1342 if (Val->getType() == TyInProgAS)
1343 return Val;
1344 }
1345 if (Ty->isLabelTy())
1346 Error(Loc, "'" + Name + "' is not a basic block");
1347 else
1348 Error(Loc, "'" + Name + "' defined with type '" +
1349 getTypeString(Val->getType()) + "' but expected '" +
1350 getTypeString(SuggestedTy) + "'");
1351 return nullptr;
1352}
1353
Chris Lattnerdf986172009-01-02 07:01:27 +00001354/// GetGlobalVal - Get a value with the specified name or ID, creating a
1355/// forward reference record if needed. This can return null if the value
1356/// exists but does not have the right type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001357GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Alexander Richardson47ff67b2018-08-23 09:25:17 +00001358 LocTy Loc, bool IsCall) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001359 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper0b6cb712014-04-15 06:32:26 +00001360 if (!PTy) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001361 Error(Loc, "global variable reference must have pointer type");
Craig Topper0b6cb712014-04-15 06:32:26 +00001362 return nullptr;
Chris Lattnerdf986172009-01-02 07:01:27 +00001363 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001364
Chris Lattnerdf986172009-01-02 07:01:27 +00001365 // Look this name up in the normal function symbol table.
1366 GlobalValue *Val =
1367 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001368
Chris Lattnerdf986172009-01-02 07:01:27 +00001369 // If this is a forward reference for the value, see if we already created a
1370 // forward ref record.
Craig Topper0b6cb712014-04-15 06:32:26 +00001371 if (!Val) {
David Blaikie6030b442015-09-21 21:07:50 +00001372 auto I = ForwardRefVals.find(Name);
Chris Lattnerdf986172009-01-02 07:01:27 +00001373 if (I != ForwardRefVals.end())
1374 Val = I->second.first;
1375 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001376
Chris Lattnerdf986172009-01-02 07:01:27 +00001377 // If we have the value in the symbol table or fwd-ref table, return it.
Alexander Richardson47ff67b2018-08-23 09:25:17 +00001378 if (Val)
1379 return cast_or_null<GlobalValue>(
1380 checkValidVariableType(Loc, "@" + Name, Ty, Val, IsCall));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001381
Chris Lattnerdf986172009-01-02 07:01:27 +00001382 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpfb80c5f52015-09-03 18:06:44 +00001383 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
Chris Lattnerdf986172009-01-02 07:01:27 +00001384 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1385 return FwdVal;
1386}
1387
Alexander Richardson47ff67b2018-08-23 09:25:17 +00001388GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc,
1389 bool IsCall) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001390 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper0b6cb712014-04-15 06:32:26 +00001391 if (!PTy) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001392 Error(Loc, "global variable reference must have pointer type");
Craig Topper0b6cb712014-04-15 06:32:26 +00001393 return nullptr;
Chris Lattnerdf986172009-01-02 07:01:27 +00001394 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001395
Craig Topper0b6cb712014-04-15 06:32:26 +00001396 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001397
Chris Lattnerdf986172009-01-02 07:01:27 +00001398 // If this is a forward reference for the value, see if we already created a
1399 // forward ref record.
Craig Topper0b6cb712014-04-15 06:32:26 +00001400 if (!Val) {
David Blaikie6030b442015-09-21 21:07:50 +00001401 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerdf986172009-01-02 07:01:27 +00001402 if (I != ForwardRefValIDs.end())
1403 Val = I->second.first;
1404 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001405
Chris Lattnerdf986172009-01-02 07:01:27 +00001406 // If we have the value in the symbol table or fwd-ref table, return it.
Alexander Richardson47ff67b2018-08-23 09:25:17 +00001407 if (Val)
1408 return cast_or_null<GlobalValue>(
1409 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val, IsCall));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001410
Chris Lattnerdf986172009-01-02 07:01:27 +00001411 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpfb80c5f52015-09-03 18:06:44 +00001412 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
Chris Lattnerdf986172009-01-02 07:01:27 +00001413 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1414 return FwdVal;
1415}
1416
Chris Lattnerdf986172009-01-02 07:01:27 +00001417//===----------------------------------------------------------------------===//
David Majnemerc8a11692014-06-27 18:19:56 +00001418// Comdat Reference/Resolution Routines.
1419//===----------------------------------------------------------------------===//
1420
1421Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1422 // Look this name up in the comdat symbol table.
1423 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1424 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1425 if (I != ComdatSymTab.end())
1426 return &I->second;
1427
1428 // Otherwise, create a new forward reference for this value and remember it.
1429 Comdat *C = M->getOrInsertComdat(Name);
1430 ForwardRefComdats[Name] = Loc;
1431 return C;
1432}
1433
David Majnemerc8a11692014-06-27 18:19:56 +00001434//===----------------------------------------------------------------------===//
Chris Lattnerdf986172009-01-02 07:01:27 +00001435// Helper Routines.
1436//===----------------------------------------------------------------------===//
1437
1438/// ParseToken - If the current token has the specified kind, eat it and return
1439/// success. Otherwise, emit the specified error and return failure.
1440bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1441 if (Lex.getKind() != T)
1442 return TokError(ErrMsg);
1443 Lex.Lex();
1444 return false;
1445}
1446
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001447/// ParseStringConstant
1448/// ::= StringConstant
1449bool LLParser::ParseStringConstant(std::string &Result) {
1450 if (Lex.getKind() != lltok::StringConstant)
1451 return TokError("expected string constant");
1452 Result = Lex.getStrVal();
1453 Lex.Lex();
1454 return false;
1455}
1456
1457/// ParseUInt32
1458/// ::= uint32
Leny Kholodovd9478f82016-09-06 10:46:28 +00001459bool LLParser::ParseUInt32(uint32_t &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001460 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1461 return TokError("expected integer");
1462 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1463 if (Val64 != unsigned(Val64))
1464 return TokError("expected 32-bit integer (too large)");
1465 Val = Val64;
1466 Lex.Lex();
1467 return false;
1468}
1469
Hal Finkel11af4b42014-07-18 15:51:28 +00001470/// ParseUInt64
1471/// ::= uint64
1472bool LLParser::ParseUInt64(uint64_t &Val) {
1473 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1474 return TokError("expected integer");
1475 Val = Lex.getAPSIntVal().getLimitedValue();
1476 Lex.Lex();
1477 return false;
1478}
1479
Hans Wennborgce718ff2012-06-23 11:37:03 +00001480/// ParseTLSModel
1481/// := 'localdynamic'
1482/// := 'initialexec'
1483/// := 'localexec'
1484bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1485 switch (Lex.getKind()) {
1486 default:
1487 return TokError("expected localdynamic, initialexec or localexec");
1488 case lltok::kw_localdynamic:
1489 TLM = GlobalVariable::LocalDynamicTLSModel;
1490 break;
1491 case lltok::kw_initialexec:
1492 TLM = GlobalVariable::InitialExecTLSModel;
1493 break;
1494 case lltok::kw_localexec:
1495 TLM = GlobalVariable::LocalExecTLSModel;
1496 break;
1497 }
1498
1499 Lex.Lex();
1500 return false;
1501}
1502
1503/// ParseOptionalThreadLocal
1504/// := /*empty*/
1505/// := 'thread_local'
1506/// := 'thread_local' '(' tlsmodel ')'
1507bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1508 TLM = GlobalVariable::NotThreadLocal;
1509 if (!EatIfPresent(lltok::kw_thread_local))
1510 return false;
1511
1512 TLM = GlobalVariable::GeneralDynamicTLSModel;
1513 if (Lex.getKind() == lltok::lparen) {
1514 Lex.Lex();
1515 return ParseTLSModel(TLM) ||
1516 ParseToken(lltok::rparen, "expected ')' after thread local model");
1517 }
1518 return false;
1519}
Chris Lattnerdf986172009-01-02 07:01:27 +00001520
1521/// ParseOptionalAddrSpace
1522/// := /*empty*/
1523/// := 'addrspace' '(' uint32 ')'
Alexander Richardson47ff67b2018-08-23 09:25:17 +00001524bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1525 AddrSpace = DefaultAS;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001526 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +00001527 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001528 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001529 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001530 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001531}
Chris Lattnerdf986172009-01-02 07:01:27 +00001532
Artur Pilipenko9987cb62015-08-03 14:31:49 +00001533/// ParseStringAttribute
1534/// := StringConstant
1535/// := StringConstant '=' StringConstant
1536bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1537 std::string Attr = Lex.getStrVal();
1538 Lex.Lex();
1539 std::string Val;
1540 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1541 return true;
1542 B.addAttribute(Attr, Val);
1543 return false;
1544}
1545
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001546/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1547bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1548 bool HaveError = false;
1549
1550 B.clear();
1551
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +00001552 while (true) {
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001553 lltok::Kind Token = Lex.getKind();
1554 switch (Token) {
1555 default: // End of attributes.
1556 return HaveError;
Artur Pilipenko9987cb62015-08-03 14:31:49 +00001557 case lltok::StringConstant: {
1558 if (ParseStringAttribute(B))
1559 return true;
1560 continue;
1561 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001562 case lltok::kw_align: {
1563 unsigned Alignment;
1564 if (ParseOptionalAlignment(Alignment))
1565 return true;
Bill Wendling03272442012-10-08 22:20:14 +00001566 B.addAlignmentAttr(Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +00001567 continue;
1568 }
Bill Wendling034b94b2012-12-19 07:18:57 +00001569 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkel11af4b42014-07-18 15:51:28 +00001570 case lltok::kw_dereferenceable: {
1571 uint64_t Bytes;
Sanjoy Das5ff59072015-04-16 20:29:50 +00001572 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkel11af4b42014-07-18 15:51:28 +00001573 return true;
1574 B.addDereferenceableAttr(Bytes);
1575 continue;
1576 }
Sanjoy Das5ff59072015-04-16 20:29:50 +00001577 case lltok::kw_dereferenceable_or_null: {
1578 uint64_t Bytes;
1579 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1580 return true;
1581 B.addDereferenceableOrNullAttr(Bytes);
1582 continue;
1583 }
Reid Kleckner4b70bfc2013-12-19 02:14:12 +00001584 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling034b94b2012-12-19 07:18:57 +00001585 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1586 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1587 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1588 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyfe47ebf2014-05-20 01:23:40 +00001589 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckydc897372013-07-06 00:29:58 +00001590 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1591 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Lin456ca042013-04-20 05:14:40 +00001592 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling034b94b2012-12-19 07:18:57 +00001593 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1594 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
Manman Ren4bda8822016-04-01 21:41:15 +00001595 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
Manman Rend9e9e2b2016-03-29 17:37:21 +00001596 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
Nicolai Haehnleb07f5402016-07-04 08:01:29 +00001597 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling034b94b2012-12-19 07:18:57 +00001598 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davis1e063d12010-02-12 00:31:15 +00001599
Stephen Linb0aeb3e2013-04-20 13:16:13 +00001600 case lltok::kw_alignstack:
1601 case lltok::kw_alwaysinline:
Igor Laevsky6690dbf2015-07-11 10:30:36 +00001602 case lltok::kw_argmemonly:
Michael Gottesman2253a2f2013-06-27 00:25:01 +00001603 case lltok::kw_builtin:
Stephen Linb0aeb3e2013-04-20 13:16:13 +00001604 case lltok::kw_inlinehint:
Tom Roeder5d0f7af2014-06-05 19:29:43 +00001605 case lltok::kw_jumptable:
Stephen Linb0aeb3e2013-04-20 13:16:13 +00001606 case lltok::kw_minsize:
1607 case lltok::kw_naked:
1608 case lltok::kw_nobuiltin:
1609 case lltok::kw_noduplicate:
1610 case lltok::kw_noimplicitfloat:
1611 case lltok::kw_noinline:
1612 case lltok::kw_nonlazybind:
1613 case lltok::kw_noredzone:
1614 case lltok::kw_noreturn:
Oren Ben Simhon10c992c2018-03-17 13:29:46 +00001615 case lltok::kw_nocf_check:
Stephen Linb0aeb3e2013-04-20 13:16:13 +00001616 case lltok::kw_nounwind:
Matt Morehouse7d085b62018-03-22 17:07:51 +00001617 case lltok::kw_optforfuzzing:
Andrea Di Biagio5768bb82013-08-23 11:53:55 +00001618 case lltok::kw_optnone:
Stephen Linb0aeb3e2013-04-20 13:16:13 +00001619 case lltok::kw_optsize:
Stephen Linb0aeb3e2013-04-20 13:16:13 +00001620 case lltok::kw_returns_twice:
1621 case lltok::kw_sanitize_address:
Evgeniy Stepanovd47b5b32017-12-09 00:21:41 +00001622 case lltok::kw_sanitize_hwaddress:
Stephen Linb0aeb3e2013-04-20 13:16:13 +00001623 case lltok::kw_sanitize_memory:
1624 case lltok::kw_sanitize_thread:
Chandler Carruthd2b1fb12018-09-04 12:38:00 +00001625 case lltok::kw_speculative_load_hardening:
Stephen Linb0aeb3e2013-04-20 13:16:13 +00001626 case lltok::kw_ssp:
1627 case lltok::kw_sspreq:
1628 case lltok::kw_sspstrong:
Peter Collingbourne7ffec832015-06-15 21:07:11 +00001629 case lltok::kw_safestack:
Vlad Tsyrklevich45013b22018-04-03 20:10:40 +00001630 case lltok::kw_shadowcallstack:
Andrew Kaylor68d0bd12017-08-14 21:15:13 +00001631 case lltok::kw_strictfp:
Stephen Linb0aeb3e2013-04-20 13:16:13 +00001632 case lltok::kw_uwtable:
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001633 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1634 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001635 }
Bill Wendlingdc998cc2012-09-28 22:30:18 +00001636
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001637 Lex.Lex();
1638 }
1639}
1640
1641/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1642bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1643 bool HaveError = false;
1644
1645 B.clear();
1646
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +00001647 while (true) {
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001648 lltok::Kind Token = Lex.getKind();
Bill Wendlingdc998cc2012-09-28 22:30:18 +00001649 switch (Token) {
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001650 default: // End of attributes.
1651 return HaveError;
Artur Pilipenko9987cb62015-08-03 14:31:49 +00001652 case lltok::StringConstant: {
1653 if (ParseStringAttribute(B))
1654 return true;
1655 continue;
1656 }
Hal Finkel11af4b42014-07-18 15:51:28 +00001657 case lltok::kw_dereferenceable: {
1658 uint64_t Bytes;
Sanjoy Das5ff59072015-04-16 20:29:50 +00001659 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkel11af4b42014-07-18 15:51:28 +00001660 return true;
1661 B.addDereferenceableAttr(Bytes);
1662 continue;
1663 }
Sanjoy Das5ff59072015-04-16 20:29:50 +00001664 case lltok::kw_dereferenceable_or_null: {
1665 uint64_t Bytes;
1666 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1667 return true;
1668 B.addDereferenceableOrNullAttr(Bytes);
1669 continue;
1670 }
Artur Pilipenko0c5094b2015-09-18 12:33:31 +00001671 case lltok::kw_align: {
1672 unsigned Alignment;
1673 if (ParseOptionalAlignment(Alignment))
1674 return true;
1675 B.addAlignmentAttr(Alignment);
1676 continue;
1677 }
Bill Wendling034b94b2012-12-19 07:18:57 +00001678 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1679 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyfe47ebf2014-05-20 01:23:40 +00001680 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling034b94b2012-12-19 07:18:57 +00001681 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1682 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendlingdc998cc2012-09-28 22:30:18 +00001683
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001684 // Error handling.
Chandler Carruth239e1e42013-04-09 19:46:46 +00001685 case lltok::kw_byval:
Reid Kleckner4b70bfc2013-12-19 02:14:12 +00001686 case lltok::kw_inalloca:
Chandler Carruth239e1e42013-04-09 19:46:46 +00001687 case lltok::kw_nest:
1688 case lltok::kw_nocapture:
Stephen Lin456ca042013-04-20 05:14:40 +00001689 case lltok::kw_returned:
Chandler Carruth239e1e42013-04-09 19:46:46 +00001690 case lltok::kw_sret:
Manman Ren4bda8822016-04-01 21:41:15 +00001691 case lltok::kw_swifterror:
Manman Rend9e9e2b2016-03-29 17:37:21 +00001692 case lltok::kw_swiftself:
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001693 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendlingdc998cc2012-09-28 22:30:18 +00001694 break;
James Molloy67ae1352012-12-20 16:04:27 +00001695
Chandler Carruth239e1e42013-04-09 19:46:46 +00001696 case lltok::kw_alignstack:
1697 case lltok::kw_alwaysinline:
Igor Laevsky6690dbf2015-07-11 10:30:36 +00001698 case lltok::kw_argmemonly:
Michael Gottesman2253a2f2013-06-27 00:25:01 +00001699 case lltok::kw_builtin:
Diego Novillo77226a02013-05-24 12:26:52 +00001700 case lltok::kw_cold:
Chandler Carruth239e1e42013-04-09 19:46:46 +00001701 case lltok::kw_inlinehint:
Tom Roeder5d0f7af2014-06-05 19:29:43 +00001702 case lltok::kw_jumptable:
Chandler Carruth239e1e42013-04-09 19:46:46 +00001703 case lltok::kw_minsize:
1704 case lltok::kw_naked:
1705 case lltok::kw_nobuiltin:
1706 case lltok::kw_noduplicate:
1707 case lltok::kw_noimplicitfloat:
1708 case lltok::kw_noinline:
1709 case lltok::kw_nonlazybind:
1710 case lltok::kw_noredzone:
1711 case lltok::kw_noreturn:
Oren Ben Simhon10c992c2018-03-17 13:29:46 +00001712 case lltok::kw_nocf_check:
Chandler Carruth239e1e42013-04-09 19:46:46 +00001713 case lltok::kw_nounwind:
Matt Morehouse7d085b62018-03-22 17:07:51 +00001714 case lltok::kw_optforfuzzing:
Andrea Di Biagio5768bb82013-08-23 11:53:55 +00001715 case lltok::kw_optnone:
Chandler Carruth239e1e42013-04-09 19:46:46 +00001716 case lltok::kw_optsize:
Chandler Carruth239e1e42013-04-09 19:46:46 +00001717 case lltok::kw_returns_twice:
1718 case lltok::kw_sanitize_address:
Evgeniy Stepanovd47b5b32017-12-09 00:21:41 +00001719 case lltok::kw_sanitize_hwaddress:
Chandler Carruth239e1e42013-04-09 19:46:46 +00001720 case lltok::kw_sanitize_memory:
1721 case lltok::kw_sanitize_thread:
Chandler Carruthd2b1fb12018-09-04 12:38:00 +00001722 case lltok::kw_speculative_load_hardening:
Chandler Carruth239e1e42013-04-09 19:46:46 +00001723 case lltok::kw_ssp:
1724 case lltok::kw_sspreq:
1725 case lltok::kw_sspstrong:
Peter Collingbourne7ffec832015-06-15 21:07:11 +00001726 case lltok::kw_safestack:
Vlad Tsyrklevich45013b22018-04-03 20:10:40 +00001727 case lltok::kw_shadowcallstack:
Andrew Kaylor68d0bd12017-08-14 21:15:13 +00001728 case lltok::kw_strictfp:
Chandler Carruth239e1e42013-04-09 19:46:46 +00001729 case lltok::kw_uwtable:
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001730 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendlingdc998cc2012-09-28 22:30:18 +00001731 break;
Nick Lewyckydc897372013-07-06 00:29:58 +00001732
1733 case lltok::kw_readnone:
1734 case lltok::kw_readonly:
1735 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendlingdc998cc2012-09-28 22:30:18 +00001736 }
1737
Chris Lattnerdf986172009-01-02 07:01:27 +00001738 Lex.Lex();
1739 }
1740}
1741
Rafael Espindola3bd20c62016-05-10 17:16:45 +00001742static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1743 HasLinkage = true;
1744 switch (Kind) {
1745 default:
1746 HasLinkage = false;
1747 return GlobalValue::ExternalLinkage;
1748 case lltok::kw_private:
1749 return GlobalValue::PrivateLinkage;
1750 case lltok::kw_internal:
1751 return GlobalValue::InternalLinkage;
1752 case lltok::kw_weak:
1753 return GlobalValue::WeakAnyLinkage;
1754 case lltok::kw_weak_odr:
1755 return GlobalValue::WeakODRLinkage;
1756 case lltok::kw_linkonce:
1757 return GlobalValue::LinkOnceAnyLinkage;
1758 case lltok::kw_linkonce_odr:
1759 return GlobalValue::LinkOnceODRLinkage;
1760 case lltok::kw_available_externally:
1761 return GlobalValue::AvailableExternallyLinkage;
1762 case lltok::kw_appending:
1763 return GlobalValue::AppendingLinkage;
1764 case lltok::kw_common:
1765 return GlobalValue::CommonLinkage;
1766 case lltok::kw_extern_weak:
1767 return GlobalValue::ExternalWeakLinkage;
1768 case lltok::kw_external:
1769 return GlobalValue::ExternalLinkage;
1770 }
1771}
1772
Chris Lattnerdf986172009-01-02 07:01:27 +00001773/// ParseOptionalLinkage
1774/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +00001775/// ::= 'private'
Chris Lattnerdf986172009-01-02 07:01:27 +00001776/// ::= 'internal'
1777/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +00001778/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +00001779/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +00001780/// ::= 'linkonce_odr'
Bill Wendling5e721d72010-07-01 21:55:59 +00001781/// ::= 'available_externally'
Chris Lattnerdf986172009-01-02 07:01:27 +00001782/// ::= 'appending'
Chris Lattnerdf986172009-01-02 07:01:27 +00001783/// ::= 'common'
Chris Lattnerdf986172009-01-02 07:01:27 +00001784/// ::= 'extern_weak'
1785/// ::= 'external'
Rafael Espindola26020e62016-05-12 12:37:52 +00001786bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1787 unsigned &Visibility,
Sean Fertile509132b2017-10-26 15:00:26 +00001788 unsigned &DLLStorageClass,
1789 bool &DSOLocal) {
Rafael Espindola3bd20c62016-05-10 17:16:45 +00001790 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1791 if (HasLinkage)
1792 Lex.Lex();
Sean Fertile509132b2017-10-26 15:00:26 +00001793 ParseOptionalDSOLocal(DSOLocal);
Rafael Espindola26020e62016-05-12 12:37:52 +00001794 ParseOptionalVisibility(Visibility);
1795 ParseOptionalDLLStorageClass(DLLStorageClass);
Sean Fertile509132b2017-10-26 15:00:26 +00001796
1797 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
1798 return Error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
1799 }
1800
Chris Lattnerdf986172009-01-02 07:01:27 +00001801 return false;
1802}
1803
Sean Fertile509132b2017-10-26 15:00:26 +00001804void LLParser::ParseOptionalDSOLocal(bool &DSOLocal) {
1805 switch (Lex.getKind()) {
1806 default:
1807 DSOLocal = false;
1808 break;
1809 case lltok::kw_dso_local:
1810 DSOLocal = true;
1811 Lex.Lex();
1812 break;
1813 case lltok::kw_dso_preemptable:
1814 DSOLocal = false;
1815 Lex.Lex();
1816 break;
1817 }
1818}
1819
Chris Lattnerdf986172009-01-02 07:01:27 +00001820/// ParseOptionalVisibility
1821/// ::= /*empty*/
1822/// ::= 'default'
1823/// ::= 'hidden'
1824/// ::= 'protected'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001825///
Rafael Espindola26020e62016-05-12 12:37:52 +00001826void LLParser::ParseOptionalVisibility(unsigned &Res) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001827 switch (Lex.getKind()) {
Rafael Espindola26020e62016-05-12 12:37:52 +00001828 default:
1829 Res = GlobalValue::DefaultVisibility;
1830 return;
1831 case lltok::kw_default:
1832 Res = GlobalValue::DefaultVisibility;
1833 break;
1834 case lltok::kw_hidden:
1835 Res = GlobalValue::HiddenVisibility;
1836 break;
1837 case lltok::kw_protected:
1838 Res = GlobalValue::ProtectedVisibility;
1839 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001840 }
1841 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001842}
1843
Nico Rieck38f68c52014-01-14 15:22:47 +00001844/// ParseOptionalDLLStorageClass
1845/// ::= /*empty*/
1846/// ::= 'dllimport'
1847/// ::= 'dllexport'
1848///
Rafael Espindola26020e62016-05-12 12:37:52 +00001849void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
Nico Rieck38f68c52014-01-14 15:22:47 +00001850 switch (Lex.getKind()) {
Rafael Espindola26020e62016-05-12 12:37:52 +00001851 default:
1852 Res = GlobalValue::DefaultStorageClass;
1853 return;
1854 case lltok::kw_dllimport:
1855 Res = GlobalValue::DLLImportStorageClass;
1856 break;
1857 case lltok::kw_dllexport:
1858 Res = GlobalValue::DLLExportStorageClass;
1859 break;
Nico Rieck38f68c52014-01-14 15:22:47 +00001860 }
1861 Lex.Lex();
Nico Rieck38f68c52014-01-14 15:22:47 +00001862}
1863
Chris Lattnerdf986172009-01-02 07:01:27 +00001864/// ParseOptionalCallingConv
1865/// ::= /*empty*/
1866/// ::= 'ccc'
1867/// ::= 'fastcc'
Reid Kleckner03c735b2014-12-01 21:04:44 +00001868/// ::= 'intel_ocl_bicc'
Chris Lattnerdf986172009-01-02 07:01:27 +00001869/// ::= 'coldcc'
1870/// ::= 'x86_stdcallcc'
1871/// ::= 'x86_fastcallcc'
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001872/// ::= 'x86_thiscallcc'
Reid Klecknerd5de3272014-10-28 01:29:26 +00001873/// ::= 'x86_vectorcallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001874/// ::= 'arm_apcscc'
1875/// ::= 'arm_aapcscc'
1876/// ::= 'arm_aapcs_vfpcc'
Sander de Smalen15889d42018-09-12 08:54:06 +00001877/// ::= 'aarch64_vector_pcs'
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001878/// ::= 'msp430_intrcc'
Dylan McKayca039022016-03-03 10:08:02 +00001879/// ::= 'avr_intrcc'
1880/// ::= 'avr_signalcc'
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001881/// ::= 'ptx_kernel'
1882/// ::= 'ptx_device'
Micah Villmowe53d6052012-10-01 17:01:31 +00001883/// ::= 'spir_func'
1884/// ::= 'spir_kernel'
Charles Davisac226bb2013-07-12 06:02:35 +00001885/// ::= 'x86_64_sysvcc'
Martin Storsjo6c132cb2017-07-17 20:05:19 +00001886/// ::= 'win64cc'
Andrew Trick2ddc56d2013-10-31 22:12:01 +00001887/// ::= 'webkit_jscc'
Juergen Ributzka623d2e62013-11-08 23:28:16 +00001888/// ::= 'anyregcc'
Juergen Ributzkaceaf8292014-01-17 19:47:03 +00001889/// ::= 'preserve_mostcc'
1890/// ::= 'preserve_allcc'
Reid Kleckner03c735b2014-12-01 21:04:44 +00001891/// ::= 'ghccc'
Manman Ren1f7638e2016-04-05 22:41:47 +00001892/// ::= 'swiftcc'
Amjad Aboud98891742015-12-21 14:07:14 +00001893/// ::= 'x86_intrcc'
Maksim Panchenko3b3752c2015-09-29 22:09:16 +00001894/// ::= 'hhvmcc'
1895/// ::= 'hhvm_ccc'
Manman Rencd2103d2015-12-04 17:40:13 +00001896/// ::= 'cxx_fast_tlscc'
Nicolai Haehnleea7a0c042016-04-06 19:40:20 +00001897/// ::= 'amdgpu_vs'
Tim Renouf8ba98f92017-09-29 09:51:22 +00001898/// ::= 'amdgpu_ls'
Marek Olsaka2057042017-05-02 15:41:10 +00001899/// ::= 'amdgpu_hs'
Tim Renouf8ba98f92017-09-29 09:51:22 +00001900/// ::= 'amdgpu_es'
Nicolai Haehnleea7a0c042016-04-06 19:40:20 +00001901/// ::= 'amdgpu_gs'
1902/// ::= 'amdgpu_ps'
1903/// ::= 'amdgpu_cs'
Nikolay Haustovac1dd292016-05-06 09:07:29 +00001904/// ::= 'amdgpu_kernel'
Chris Lattnerdf986172009-01-02 07:01:27 +00001905/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001906///
Alexey Samsonov5e4558e2014-09-10 18:00:17 +00001907bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001908 switch (Lex.getKind()) {
1909 default: CC = CallingConv::C; return false;
1910 case lltok::kw_ccc: CC = CallingConv::C; break;
1911 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1912 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1913 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1914 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Oren Ben Simhon4b6c3392016-10-13 07:53:43 +00001915 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001916 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Klecknerd5de3272014-10-28 01:29:26 +00001917 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001918 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1919 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1920 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Sander de Smalen15889d42018-09-12 08:54:06 +00001921 case lltok::kw_aarch64_vector_pcs:CC = CallingConv::AArch64_VectorCall; break;
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001922 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Dylan McKayca039022016-03-03 10:08:02 +00001923 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1924 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001925 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1926 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmowe53d6052012-10-01 17:01:31 +00001927 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1928 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovsky35752222012-10-24 14:46:16 +00001929 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davisac226bb2013-07-12 06:02:35 +00001930 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
Martin Storsjo6c132cb2017-07-17 20:05:19 +00001931 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
Andrew Trick2ddc56d2013-10-31 22:12:01 +00001932 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka623d2e62013-11-08 23:28:16 +00001933 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkaceaf8292014-01-17 19:47:03 +00001934 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1935 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner03c735b2014-12-01 21:04:44 +00001936 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Manman Ren1f7638e2016-04-05 22:41:47 +00001937 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
Amjad Aboud98891742015-12-21 14:07:14 +00001938 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
Maksim Panchenko3b3752c2015-09-29 22:09:16 +00001939 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1940 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
Manman Rencd2103d2015-12-04 17:40:13 +00001941 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
Nicolai Haehnleea7a0c042016-04-06 19:40:20 +00001942 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
Tim Renouf8ba98f92017-09-29 09:51:22 +00001943 case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break;
Marek Olsaka2057042017-05-02 15:41:10 +00001944 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
Tim Renouf8ba98f92017-09-29 09:51:22 +00001945 case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break;
Nicolai Haehnleea7a0c042016-04-06 19:40:20 +00001946 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1947 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1948 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
Nikolay Haustovac1dd292016-05-06 09:07:29 +00001949 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001950 case lltok::kw_cc: {
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001951 Lex.Lex();
Alexey Samsonov5e4558e2014-09-10 18:00:17 +00001952 return ParseUInt32(CC);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001953 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001954 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001955
Chris Lattnerdf986172009-01-02 07:01:27 +00001956 Lex.Lex();
1957 return false;
1958}
1959
Duncan P. N. Exon Smitheb713782015-04-24 21:21:57 +00001960/// ParseMetadataAttachment
1961/// ::= !dbg !42
1962bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1963 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1964
1965 std::string Name = Lex.getStrVal();
1966 Kind = M->getMDKindID(Name);
1967 Lex.Lex();
1968
1969 return ParseMDNode(MD);
1970}
1971
Chris Lattnerb8c46862009-12-30 05:31:19 +00001972/// ParseInstructionMetadata
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001973/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith233c2e72015-04-24 21:29:36 +00001974bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattnerb8c46862009-12-30 05:31:19 +00001975 do {
1976 if (Lex.getKind() != lltok::MetadataVar)
1977 return TokError("expected metadata after comma");
Devang Patel0475c912009-09-29 00:01:14 +00001978
Duncan P. N. Exon Smitheb713782015-04-24 21:21:57 +00001979 unsigned MDK;
Duncan P. N. Exon Smithe390a8e2015-01-12 22:26:48 +00001980 MDNode *N;
Duncan P. N. Exon Smitheb713782015-04-24 21:21:57 +00001981 if (ParseMetadataAttachment(MDK, N))
Chris Lattnere434d272009-12-30 04:56:59 +00001982 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001983
Duncan P. N. Exon Smith233c2e72015-04-24 21:29:36 +00001984 Inst.setMetadata(MDK, N);
Manman Ren804f0342013-09-28 00:22:27 +00001985 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith233c2e72015-04-24 21:29:36 +00001986 InstsWithTBAATag.push_back(&Inst);
Manman Ren804f0342013-09-28 00:22:27 +00001987
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001988 // If this is the end of the list, we're done.
Chris Lattnerb8c46862009-12-30 05:31:19 +00001989 } while (EatIfPresent(lltok::comma));
1990 return false;
Devang Patelf633a062009-09-17 23:04:48 +00001991}
1992
Peter Collingbourne6aef9f92016-05-31 23:01:54 +00001993/// ParseGlobalObjectMetadataAttachment
1994/// ::= !dbg !57
1995bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1996 unsigned MDK;
1997 MDNode *N;
1998 if (ParseMetadataAttachment(MDK, N))
1999 return true;
2000
Peter Collingbourned8d85ac2016-06-01 01:17:57 +00002001 GO.addMetadata(MDK, *N);
Peter Collingbourne6aef9f92016-05-31 23:01:54 +00002002 return false;
2003}
2004
Duncan P. N. Exon Smithae321142015-04-24 22:04:41 +00002005/// ParseOptionalFunctionMetadata
2006/// ::= (!dbg !57)*
2007bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
Peter Collingbourne6aef9f92016-05-31 23:01:54 +00002008 while (Lex.getKind() == lltok::MetadataVar)
2009 if (ParseGlobalObjectMetadataAttachment(F))
Duncan P. N. Exon Smithae321142015-04-24 22:04:41 +00002010 return true;
Duncan P. N. Exon Smithae321142015-04-24 22:04:41 +00002011 return false;
2012}
2013
Chris Lattnerdf986172009-01-02 07:01:27 +00002014/// ParseOptionalAlignment
2015/// ::= /* empty */
2016/// ::= 'align' 4
2017bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
2018 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002019 if (!EatIfPresent(lltok::kw_align))
2020 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00002021 LocTy AlignLoc = Lex.getLoc();
2022 if (ParseUInt32(Alignment)) return true;
2023 if (!isPowerOf2_32(Alignment))
2024 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmane16829b2010-07-30 21:07:05 +00002025 if (Alignment > Value::MaximumAlignment)
Dan Gohman138aa2a2010-07-28 20:12:04 +00002026 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00002027 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002028}
2029
Sanjoy Das5ff59072015-04-16 20:29:50 +00002030/// ParseOptionalDerefAttrBytes
Hal Finkel11af4b42014-07-18 15:51:28 +00002031/// ::= /* empty */
Sanjoy Das5ff59072015-04-16 20:29:50 +00002032/// ::= AttrKind '(' 4 ')'
2033///
2034/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2035bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
2036 uint64_t &Bytes) {
2037 assert((AttrKind == lltok::kw_dereferenceable ||
2038 AttrKind == lltok::kw_dereferenceable_or_null) &&
2039 "contract!");
2040
Hal Finkel11af4b42014-07-18 15:51:28 +00002041 Bytes = 0;
Sanjoy Das5ff59072015-04-16 20:29:50 +00002042 if (!EatIfPresent(AttrKind))
Hal Finkel11af4b42014-07-18 15:51:28 +00002043 return false;
2044 LocTy ParenLoc = Lex.getLoc();
2045 if (!EatIfPresent(lltok::lparen))
2046 return Error(ParenLoc, "expected '('");
2047 LocTy DerefLoc = Lex.getLoc();
2048 if (ParseUInt64(Bytes)) return true;
2049 ParenLoc = Lex.getLoc();
2050 if (!EatIfPresent(lltok::rparen))
2051 return Error(ParenLoc, "expected ')'");
2052 if (!Bytes)
2053 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
2054 return false;
2055}
2056
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00002057/// ParseOptionalCommaAlign
Michael Ilseman407a6162012-11-15 22:34:00 +00002058/// ::=
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00002059/// ::= ',' align 4
2060///
2061/// This returns with AteExtraComma set to true if it ate an excess comma at the
2062/// end.
2063bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
2064 bool &AteExtraComma) {
2065 AteExtraComma = false;
2066 while (EatIfPresent(lltok::comma)) {
2067 // Metadata at the end is an early exit.
Chris Lattner1d928312009-12-30 05:02:06 +00002068 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00002069 AteExtraComma = true;
2070 return false;
2071 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002072
Chris Lattner093eed12010-04-23 00:50:50 +00002073 if (Lex.getKind() != lltok::kw_align)
2074 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sandsbf9fc532010-10-21 16:07:10 +00002075
Chris Lattner093eed12010-04-23 00:50:50 +00002076 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00002077 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002078
Devang Patelf633a062009-09-17 23:04:48 +00002079 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002080}
2081
Matt Arsenaulte0b3c332017-04-10 22:27:50 +00002082/// ParseOptionalCommaAddrSpace
2083/// ::=
2084/// ::= ',' addrspace(1)
2085///
2086/// This returns with AteExtraComma set to true if it ate an excess comma at the
2087/// end.
2088bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace,
2089 LocTy &Loc,
2090 bool &AteExtraComma) {
2091 AteExtraComma = false;
2092 while (EatIfPresent(lltok::comma)) {
2093 // Metadata at the end is an early exit.
2094 if (Lex.getKind() == lltok::MetadataVar) {
2095 AteExtraComma = true;
2096 return false;
2097 }
2098
2099 Loc = Lex.getLoc();
2100 if (Lex.getKind() != lltok::kw_addrspace)
2101 return Error(Lex.getLoc(), "expected metadata or 'addrspace'");
2102
2103 if (ParseOptionalAddrSpace(AddrSpace))
2104 return true;
2105 }
2106
2107 return false;
2108}
2109
George Burgess IV274105b2016-04-12 01:05:35 +00002110bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2111 Optional<unsigned> &HowManyArg) {
2112 Lex.Lex();
2113
2114 auto StartParen = Lex.getLoc();
2115 if (!EatIfPresent(lltok::lparen))
2116 return Error(StartParen, "expected '('");
2117
2118 if (ParseUInt32(BaseSizeArg))
2119 return true;
2120
2121 if (EatIfPresent(lltok::comma)) {
2122 auto HowManyAt = Lex.getLoc();
2123 unsigned HowMany;
2124 if (ParseUInt32(HowMany))
2125 return true;
2126 if (HowMany == BaseSizeArg)
2127 return Error(HowManyAt,
2128 "'allocsize' indices can't refer to the same parameter");
2129 HowManyArg = HowMany;
2130 } else
2131 HowManyArg = None;
2132
2133 auto EndParen = Lex.getLoc();
2134 if (!EatIfPresent(lltok::rparen))
2135 return Error(EndParen, "expected ')'");
2136 return false;
2137}
2138
Eli Friedman47f35132011-07-25 23:16:38 +00002139/// ParseScopeAndOrdering
Konstantin Zhuravlyov8f856852017-07-11 22:23:00 +00002140/// if isAtomic: ::= SyncScope? AtomicOrdering
Eli Friedman47f35132011-07-25 23:16:38 +00002141/// else: ::=
2142///
2143/// This sets Scope and Ordering to the parsed values.
Konstantin Zhuravlyov8f856852017-07-11 22:23:00 +00002144bool LLParser::ParseScopeAndOrdering(bool isAtomic, SyncScope::ID &SSID,
Eli Friedman47f35132011-07-25 23:16:38 +00002145 AtomicOrdering &Ordering) {
2146 if (!isAtomic)
2147 return false;
2148
Konstantin Zhuravlyov8f856852017-07-11 22:23:00 +00002149 return ParseScope(SSID) || ParseOrdering(Ordering);
2150}
Tim Northoverca396e32014-03-11 10:48:52 +00002151
Konstantin Zhuravlyov8f856852017-07-11 22:23:00 +00002152/// ParseScope
2153/// ::= syncscope("singlethread" | "<target scope>")?
2154///
2155/// This sets synchronization scope ID to the ID of the parsed value.
2156bool LLParser::ParseScope(SyncScope::ID &SSID) {
2157 SSID = SyncScope::System;
2158 if (EatIfPresent(lltok::kw_syncscope)) {
2159 auto StartParenAt = Lex.getLoc();
2160 if (!EatIfPresent(lltok::lparen))
2161 return Error(StartParenAt, "Expected '(' in syncscope");
2162
2163 std::string SSN;
2164 auto SSNAt = Lex.getLoc();
2165 if (ParseStringConstant(SSN))
2166 return Error(SSNAt, "Expected synchronization scope name");
2167
2168 auto EndParenAt = Lex.getLoc();
2169 if (!EatIfPresent(lltok::rparen))
2170 return Error(EndParenAt, "Expected ')' in syncscope");
2171
2172 SSID = Context.getOrInsertSyncScopeID(SSN);
2173 }
2174
2175 return false;
Tim Northoverca396e32014-03-11 10:48:52 +00002176}
2177
2178/// ParseOrdering
2179/// ::= AtomicOrdering
2180///
2181/// This sets Ordering to the parsed value.
2182bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedman47f35132011-07-25 23:16:38 +00002183 switch (Lex.getKind()) {
2184 default: return TokError("Expected ordering on atomic instruction");
JF Bastienb36d1a82016-04-06 21:19:33 +00002185 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
2186 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
2187 // Not specified yet:
2188 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2189 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
2190 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
2191 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
2192 case lltok::kw_seq_cst:
2193 Ordering = AtomicOrdering::SequentiallyConsistent;
2194 break;
Eli Friedman47f35132011-07-25 23:16:38 +00002195 }
2196 Lex.Lex();
2197 return false;
2198}
2199
Charles Davis1e063d12010-02-12 00:31:15 +00002200/// ParseOptionalStackAlignment
2201/// ::= /* empty */
2202/// ::= 'alignstack' '(' 4 ')'
2203bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
2204 Alignment = 0;
2205 if (!EatIfPresent(lltok::kw_alignstack))
2206 return false;
2207 LocTy ParenLoc = Lex.getLoc();
2208 if (!EatIfPresent(lltok::lparen))
2209 return Error(ParenLoc, "expected '('");
2210 LocTy AlignLoc = Lex.getLoc();
2211 if (ParseUInt32(Alignment)) return true;
2212 ParenLoc = Lex.getLoc();
2213 if (!EatIfPresent(lltok::rparen))
2214 return Error(ParenLoc, "expected ')'");
2215 if (!isPowerOf2_32(Alignment))
2216 return Error(AlignLoc, "stack alignment is not a power of two");
2217 return false;
2218}
Devang Patelf633a062009-09-17 23:04:48 +00002219
Chris Lattner628c13a2009-12-30 05:14:00 +00002220/// ParseIndexList - This parses the index list for an insert/extractvalue
2221/// instruction. This sets AteExtraComma in the case where we eat an extra
2222/// comma at the end of the line and find that it is followed by metadata.
2223/// Clients that don't allow metadata can call the version of this function that
2224/// only takes one argument.
2225///
Chris Lattnerdf986172009-01-02 07:01:27 +00002226/// ParseIndexList
2227/// ::= (',' uint32)+
Chris Lattner628c13a2009-12-30 05:14:00 +00002228///
2229bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
2230 bool &AteExtraComma) {
2231 AteExtraComma = false;
Michael Ilseman407a6162012-11-15 22:34:00 +00002232
Chris Lattnerdf986172009-01-02 07:01:27 +00002233 if (Lex.getKind() != lltok::comma)
2234 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002235
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002236 while (EatIfPresent(lltok::comma)) {
Chris Lattner628c13a2009-12-30 05:14:00 +00002237 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer415561b2015-02-16 09:18:13 +00002238 if (Indices.empty()) return TokError("expected index");
Chris Lattner628c13a2009-12-30 05:14:00 +00002239 AteExtraComma = true;
2240 return false;
2241 }
Nick Lewycky28815c42010-09-29 23:32:20 +00002242 unsigned Idx = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002243 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002244 Indices.push_back(Idx);
2245 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002246
Chris Lattnerdf986172009-01-02 07:01:27 +00002247 return false;
2248}
2249
2250//===----------------------------------------------------------------------===//
2251// Type Parsing.
2252//===----------------------------------------------------------------------===//
2253
Chris Lattner1afcace2011-07-09 17:41:24 +00002254/// ParseType - Parse a type.
Duncan P. N. Exon Smith1ef70ff2014-12-15 19:07:53 +00002255bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002256 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00002257 switch (Lex.getKind()) {
2258 default:
Duncan P. N. Exon Smith1ef70ff2014-12-15 19:07:53 +00002259 return TokError(Msg);
Chris Lattnerdf986172009-01-02 07:01:27 +00002260 case lltok::Type:
Chris Lattner1afcace2011-07-09 17:41:24 +00002261 // Type ::= 'float' | 'void' (etc)
Chris Lattnerdf986172009-01-02 07:01:27 +00002262 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002263 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00002264 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00002265 case lltok::lbrace:
Chris Lattner1afcace2011-07-09 17:41:24 +00002266 // Type ::= StructType
2267 if (ParseAnonStructType(Result, false))
Chris Lattnerdf986172009-01-02 07:01:27 +00002268 return true;
2269 break;
2270 case lltok::lsquare:
Chris Lattner1afcace2011-07-09 17:41:24 +00002271 // Type ::= '[' ... ']'
Chris Lattnerdf986172009-01-02 07:01:27 +00002272 Lex.Lex(); // eat the lsquare.
2273 if (ParseArrayVectorType(Result, false))
2274 return true;
2275 break;
2276 case lltok::less: // Either vector or packed struct.
Chris Lattner1afcace2011-07-09 17:41:24 +00002277 // Type ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002278 Lex.Lex();
2279 if (Lex.getKind() == lltok::lbrace) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002280 if (ParseAnonStructType(Result, true) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002281 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00002282 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002283 } else if (ParseArrayVectorType(Result, true))
2284 return true;
2285 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00002286 case lltok::LocalVar: {
2287 // Type ::= %foo
2288 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman407a6162012-11-15 22:34:00 +00002289
Chris Lattner1afcace2011-07-09 17:41:24 +00002290 // If the type hasn't been defined yet, create a forward definition and
2291 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper0b6cb712014-04-15 06:32:26 +00002292 if (!Entry.first) {
Chris Lattner3ebb6492011-08-12 18:06:37 +00002293 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattner1afcace2011-07-09 17:41:24 +00002294 Entry.second = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00002295 }
Chris Lattner1afcace2011-07-09 17:41:24 +00002296 Result = Entry.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00002297 Lex.Lex();
2298 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00002299 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002300
Chris Lattner1afcace2011-07-09 17:41:24 +00002301 case lltok::LocalVarID: {
2302 // Type ::= %4
Chris Lattner1afcace2011-07-09 17:41:24 +00002303 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman407a6162012-11-15 22:34:00 +00002304
Chris Lattner1afcace2011-07-09 17:41:24 +00002305 // If the type hasn't been defined yet, create a forward definition and
2306 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper0b6cb712014-04-15 06:32:26 +00002307 if (!Entry.first) {
Chris Lattner3ebb6492011-08-12 18:06:37 +00002308 Entry.first = StructType::create(Context);
Chris Lattner1afcace2011-07-09 17:41:24 +00002309 Entry.second = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00002310 }
Chris Lattner1afcace2011-07-09 17:41:24 +00002311 Result = Entry.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00002312 Lex.Lex();
2313 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00002314 }
2315 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002316
2317 // Parse the type suffixes.
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +00002318 while (true) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002319 switch (Lex.getKind()) {
2320 // End of type.
Chris Lattner1afcace2011-07-09 17:41:24 +00002321 default:
2322 if (!AllowVoid && Result->isVoidTy())
2323 return Error(TypeLoc, "void type only allowed for function results");
2324 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002325
Chris Lattner1afcace2011-07-09 17:41:24 +00002326 // Type ::= Type '*'
Chris Lattnerdf986172009-01-02 07:01:27 +00002327 case lltok::star:
Chris Lattner1afcace2011-07-09 17:41:24 +00002328 if (Result->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002329 return TokError("basic block pointers are invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00002330 if (Result->isVoidTy())
2331 return TokError("pointers to void are invalid - use i8* instead");
2332 if (!PointerType::isValidElementType(Result))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00002333 return TokError("pointer to this type is invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00002334 Result = PointerType::getUnqual(Result);
Chris Lattnerdf986172009-01-02 07:01:27 +00002335 Lex.Lex();
2336 break;
2337
Chris Lattner1afcace2011-07-09 17:41:24 +00002338 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerdf986172009-01-02 07:01:27 +00002339 case lltok::kw_addrspace: {
Chris Lattner1afcace2011-07-09 17:41:24 +00002340 if (Result->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002341 return TokError("basic block pointers are invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00002342 if (Result->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00002343 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattner1afcace2011-07-09 17:41:24 +00002344 if (!PointerType::isValidElementType(Result))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00002345 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00002346 unsigned AddrSpace;
2347 if (ParseOptionalAddrSpace(AddrSpace) ||
2348 ParseToken(lltok::star, "expected '*' in address space"))
2349 return true;
2350
Chris Lattner1afcace2011-07-09 17:41:24 +00002351 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +00002352 break;
2353 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002354
Chris Lattnerdf986172009-01-02 07:01:27 +00002355 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2356 case lltok::lparen:
2357 if (ParseFunctionType(Result))
2358 return true;
2359 break;
2360 }
2361 }
2362}
2363
2364/// ParseParameterList
2365/// ::= '(' ')'
2366/// ::= '(' Arg (',' Arg)* ')'
2367/// Arg
2368/// ::= Type OptionalAttributes Value OptionalAttributes
2369bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner44b3a0b2014-08-26 00:33:28 +00002370 PerFunctionState &PFS, bool IsMustTailCall,
2371 bool InVarArgsFunc) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002372 if (ParseToken(lltok::lparen, "expected '(' in call"))
2373 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002374
Chris Lattnerdf986172009-01-02 07:01:27 +00002375 while (Lex.getKind() != lltok::rparen) {
2376 // If this isn't the first argument, we need a comma.
2377 if (!ArgList.empty() &&
2378 ParseToken(lltok::comma, "expected ',' in argument list"))
2379 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002380
Reid Kleckner44b3a0b2014-08-26 00:33:28 +00002381 // Parse an ellipsis if this is a musttail call in a variadic function.
2382 if (Lex.getKind() == lltok::dotdotdot) {
2383 const char *Msg = "unexpected ellipsis in argument list for ";
2384 if (!IsMustTailCall)
2385 return TokError(Twine(Msg) + "non-musttail call");
2386 if (!InVarArgsFunc)
2387 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2388 Lex.Lex(); // Lex the '...', it is purely for readability.
2389 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2390 }
2391
Chris Lattnerdf986172009-01-02 07:01:27 +00002392 // Parse the argument.
2393 LocTy ArgLoc;
Craig Topper0b6cb712014-04-15 06:32:26 +00002394 Type *ArgTy = nullptr;
Bill Wendling702cc912012-10-15 20:35:56 +00002395 AttrBuilder ArgAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002396 Value *V;
Victor Hernandez19715562009-12-03 23:40:58 +00002397 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00002398 return true;
Victor Hernandez19715562009-12-03 23:40:58 +00002399
Duncan P. N. Exon Smith1ef70ff2014-12-15 19:07:53 +00002400 if (ArgTy->isMetadataTy()) {
2401 if (ParseMetadataAsValue(V, PFS))
2402 return true;
2403 } else {
2404 // Otherwise, handle normal operands.
2405 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2406 return true;
2407 }
Reid Kleckner67077702017-03-21 16:57:19 +00002408 ArgList.push_back(ParamInfo(
Reid Kleckner06090402017-04-12 00:38:00 +00002409 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
Chris Lattnerdf986172009-01-02 07:01:27 +00002410 }
2411
Reid Kleckner44b3a0b2014-08-26 00:33:28 +00002412 if (IsMustTailCall && InVarArgsFunc)
2413 return TokError("expected '...' at end of argument list for musttail call "
2414 "in varargs function");
2415
Chris Lattnerdf986172009-01-02 07:01:27 +00002416 Lex.Lex(); // Lex the ')'.
2417 return false;
2418}
2419
Sanjoy Dasf70eb722015-09-24 23:34:52 +00002420/// ParseOptionalOperandBundles
2421/// ::= /*empty*/
2422/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2423///
2424/// OperandBundle
2425/// ::= bundle-tag '(' ')'
2426/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2427///
2428/// bundle-tag ::= String Constant
2429bool LLParser::ParseOptionalOperandBundles(
2430 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2431 LocTy BeginLoc = Lex.getLoc();
2432 if (!EatIfPresent(lltok::lsquare))
2433 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002434
Sanjoy Dasf70eb722015-09-24 23:34:52 +00002435 while (Lex.getKind() != lltok::rsquare) {
2436 // If this isn't the first operand bundle, we need a comma.
2437 if (!BundleList.empty() &&
2438 ParseToken(lltok::comma, "expected ',' in input list"))
2439 return true;
2440
2441 std::string Tag;
2442 if (ParseStringConstant(Tag))
2443 return true;
2444
Sanjoy Dasf70eb722015-09-24 23:34:52 +00002445 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2446 return true;
2447
Sanjoy Das26b7bf32015-11-18 08:30:07 +00002448 std::vector<Value *> Inputs;
Sanjoy Dasf70eb722015-09-24 23:34:52 +00002449 while (Lex.getKind() != lltok::rparen) {
2450 // If this isn't the first input, we need a comma.
Sanjoy Das26b7bf32015-11-18 08:30:07 +00002451 if (!Inputs.empty() &&
Sanjoy Dasf70eb722015-09-24 23:34:52 +00002452 ParseToken(lltok::comma, "expected ',' in input list"))
2453 return true;
2454
2455 Type *Ty = nullptr;
2456 Value *Input = nullptr;
2457 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2458 return true;
Sanjoy Das26b7bf32015-11-18 08:30:07 +00002459 Inputs.push_back(Input);
Sanjoy Dasf70eb722015-09-24 23:34:52 +00002460 }
2461
Sanjoy Das26b7bf32015-11-18 08:30:07 +00002462 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2463
Sanjoy Dasf70eb722015-09-24 23:34:52 +00002464 Lex.Lex(); // Lex the ')'.
2465 }
2466
2467 if (BundleList.empty())
2468 return Error(BeginLoc, "operand bundle set must not be empty");
2469
2470 Lex.Lex(); // Lex the ']'.
2471 return false;
2472}
Chris Lattnerdf986172009-01-02 07:01:27 +00002473
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002474/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattner1afcace2011-07-09 17:41:24 +00002475/// prototype.
Chris Lattnerdf986172009-01-02 07:01:27 +00002476/// ::= '(' ArgTypeListI ')'
2477/// ArgTypeListI
2478/// ::= /*empty*/
2479/// ::= '...'
2480/// ::= ArgTypeList ',' '...'
2481/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002482///
Chris Lattner1afcace2011-07-09 17:41:24 +00002483bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2484 bool &isVarArg){
Chris Lattnerdf986172009-01-02 07:01:27 +00002485 isVarArg = false;
2486 assert(Lex.getKind() == lltok::lparen);
2487 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002488
Chris Lattnerdf986172009-01-02 07:01:27 +00002489 if (Lex.getKind() == lltok::rparen) {
2490 // empty
2491 } else if (Lex.getKind() == lltok::dotdotdot) {
2492 isVarArg = true;
2493 Lex.Lex();
2494 } else {
2495 LocTy TypeLoc = Lex.getLoc();
Craig Topper0b6cb712014-04-15 06:32:26 +00002496 Type *ArgTy = nullptr;
Bill Wendling702cc912012-10-15 20:35:56 +00002497 AttrBuilder Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002498 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002499
Chris Lattner1afcace2011-07-09 17:41:24 +00002500 if (ParseType(ArgTy) ||
Bill Wendlinge01b81b2012-12-04 23:40:58 +00002501 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002502
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002503 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00002504 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002505
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00002506 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002507 Name = Lex.getStrVal();
2508 Lex.Lex();
2509 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002510
Nick Lewyckya5f54a02009-06-07 07:26:46 +00002511 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002512 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002513
Reid Kleckner7dde8e82017-04-10 23:31:05 +00002514 ArgList.emplace_back(TypeLoc, ArgTy,
Reid Kleckner06090402017-04-12 00:38:00 +00002515 AttributeSet::get(ArgTy->getContext(), Attrs),
Benjamin Kramer9589ff82015-05-29 19:43:39 +00002516 std::move(Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002517
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002518 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002519 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002520 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002521 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002522 break;
2523 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002524
Chris Lattnerdf986172009-01-02 07:01:27 +00002525 // Otherwise must be an argument type.
2526 TypeLoc = Lex.getLoc();
Bill Wendlinge01b81b2012-12-04 23:40:58 +00002527 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002528
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002529 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00002530 return Error(TypeLoc, "argument can not have void type");
2531
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00002532 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002533 Name = Lex.getStrVal();
2534 Lex.Lex();
2535 } else {
2536 Name = "";
2537 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002538
Chris Lattner1afcace2011-07-09 17:41:24 +00002539 if (!ArgTy->isFirstClassType())
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002540 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002541
Reid Kleckner7dde8e82017-04-10 23:31:05 +00002542 ArgList.emplace_back(TypeLoc, ArgTy,
Reid Kleckner06090402017-04-12 00:38:00 +00002543 AttributeSet::get(ArgTy->getContext(), Attrs),
Reid Kleckner7dde8e82017-04-10 23:31:05 +00002544 std::move(Name));
Chris Lattnerdf986172009-01-02 07:01:27 +00002545 }
2546 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002547
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002548 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00002549}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002550
Chris Lattnerdf986172009-01-02 07:01:27 +00002551/// ParseFunctionType
2552/// ::= Type ArgumentList OptionalAttrs
Chris Lattner1afcace2011-07-09 17:41:24 +00002553bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002554 assert(Lex.getKind() == lltok::lparen);
2555
Chris Lattnerd77d04c2009-01-05 08:04:33 +00002556 if (!FunctionType::isValidReturnType(Result))
2557 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002558
Chris Lattner1afcace2011-07-09 17:41:24 +00002559 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerdf986172009-01-02 07:01:27 +00002560 bool isVarArg;
Chris Lattner1afcace2011-07-09 17:41:24 +00002561 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerdf986172009-01-02 07:01:27 +00002562 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002563
Chris Lattnerdf986172009-01-02 07:01:27 +00002564 // Reject names on the arguments lists.
2565 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2566 if (!ArgList[i].Name.empty())
2567 return Error(ArgList[i].Loc, "argument name invalid in function type");
Reid Kleckner06090402017-04-12 00:38:00 +00002568 if (ArgList[i].Attrs.hasAttributes())
Chris Lattnera16546a2011-06-17 17:37:13 +00002569 return Error(ArgList[i].Loc,
2570 "argument attributes invalid in function type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002571 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002572
Jay Foad5fdd6c82011-07-12 14:06:48 +00002573 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerdf986172009-01-02 07:01:27 +00002574 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattner1afcace2011-07-09 17:41:24 +00002575 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002576
Chris Lattner1afcace2011-07-09 17:41:24 +00002577 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerdf986172009-01-02 07:01:27 +00002578 return false;
2579}
2580
Chris Lattner1afcace2011-07-09 17:41:24 +00002581/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2582/// other structs.
2583bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2584 SmallVector<Type*, 8> Elts;
2585 if (ParseStructBody(Elts)) return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00002586
Chris Lattner1afcace2011-07-09 17:41:24 +00002587 Result = StructType::get(Context, Elts, Packed);
2588 return false;
2589}
2590
2591/// ParseStructDefinition - Parse a struct in a 'type' definition.
2592bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2593 std::pair<Type*, LocTy> &Entry,
2594 Type *&ResultTy) {
2595 // If the type was already defined, diagnose the redefinition.
2596 if (Entry.first && !Entry.second.isValid())
2597 return Error(TypeLoc, "redefinition of type");
Michael Ilseman407a6162012-11-15 22:34:00 +00002598
Chris Lattner1afcace2011-07-09 17:41:24 +00002599 // If we have opaque, just return without filling in the definition for the
2600 // struct. This counts as a definition as far as the .ll file goes.
2601 if (EatIfPresent(lltok::kw_opaque)) {
2602 // This type is being defined, so clear the location to indicate this.
2603 Entry.second = SMLoc();
Michael Ilseman407a6162012-11-15 22:34:00 +00002604
Chris Lattner1afcace2011-07-09 17:41:24 +00002605 // If this type number has never been uttered, create it.
Craig Topper0b6cb712014-04-15 06:32:26 +00002606 if (!Entry.first)
Chris Lattner3ebb6492011-08-12 18:06:37 +00002607 Entry.first = StructType::create(Context, Name);
Chris Lattner1afcace2011-07-09 17:41:24 +00002608 ResultTy = Entry.first;
2609 return false;
2610 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002611
Chris Lattner1afcace2011-07-09 17:41:24 +00002612 // If the type starts with '<', then it is either a packed struct or a vector.
2613 bool isPacked = EatIfPresent(lltok::less);
2614
2615 // If we don't have a struct, then we have a random type alias, which we
2616 // accept for compatibility with old files. These types are not allowed to be
2617 // forward referenced and not allowed to be recursive.
2618 if (Lex.getKind() != lltok::lbrace) {
2619 if (Entry.first)
2620 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman407a6162012-11-15 22:34:00 +00002621
Craig Topper0b6cb712014-04-15 06:32:26 +00002622 ResultTy = nullptr;
Chris Lattner1afcace2011-07-09 17:41:24 +00002623 if (isPacked)
2624 return ParseArrayVectorType(ResultTy, true);
2625 return ParseType(ResultTy);
2626 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002627
Chris Lattner1afcace2011-07-09 17:41:24 +00002628 // This type is being defined, so clear the location to indicate this.
2629 Entry.second = SMLoc();
Michael Ilseman407a6162012-11-15 22:34:00 +00002630
Chris Lattner1afcace2011-07-09 17:41:24 +00002631 // If this type number has never been uttered, create it.
Craig Topper0b6cb712014-04-15 06:32:26 +00002632 if (!Entry.first)
Chris Lattner3ebb6492011-08-12 18:06:37 +00002633 Entry.first = StructType::create(Context, Name);
Michael Ilseman407a6162012-11-15 22:34:00 +00002634
Chris Lattner1afcace2011-07-09 17:41:24 +00002635 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman407a6162012-11-15 22:34:00 +00002636
Chris Lattner1afcace2011-07-09 17:41:24 +00002637 SmallVector<Type*, 8> Body;
2638 if (ParseStructBody(Body) ||
2639 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2640 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00002641
Chris Lattner1afcace2011-07-09 17:41:24 +00002642 STy->setBody(Body, isPacked);
2643 ResultTy = STy;
2644 return false;
2645}
2646
Chris Lattnerdf986172009-01-02 07:01:27 +00002647/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattner1afcace2011-07-09 17:41:24 +00002648/// StructType
Chris Lattnerdf986172009-01-02 07:01:27 +00002649/// ::= '{' '}'
Chris Lattner1afcace2011-07-09 17:41:24 +00002650/// ::= '{' Type (',' Type)* '}'
Chris Lattnerdf986172009-01-02 07:01:27 +00002651/// ::= '<' '{' '}' '>'
Chris Lattner1afcace2011-07-09 17:41:24 +00002652/// ::= '<' '{' Type (',' Type)* '}' '>'
2653bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002654 assert(Lex.getKind() == lltok::lbrace);
2655 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00002656
Chris Lattner1afcace2011-07-09 17:41:24 +00002657 // Handle the empty struct.
2658 if (EatIfPresent(lltok::rbrace))
Chris Lattnerdf986172009-01-02 07:01:27 +00002659 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002660
Chris Lattnera9a9e072009-03-09 04:49:14 +00002661 LocTy EltTyLoc = Lex.getLoc();
Craig Topper0b6cb712014-04-15 06:32:26 +00002662 Type *Ty = nullptr;
Chris Lattner1afcace2011-07-09 17:41:24 +00002663 if (ParseType(Ty)) return true;
2664 Body.push_back(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002665
Chris Lattner1afcace2011-07-09 17:41:24 +00002666 if (!StructType::isValidElementType(Ty))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00002667 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002668
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002669 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00002670 EltTyLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00002671 if (ParseType(Ty)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002672
Chris Lattner1afcace2011-07-09 17:41:24 +00002673 if (!StructType::isValidElementType(Ty))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00002674 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002675
Chris Lattner1afcace2011-07-09 17:41:24 +00002676 Body.push_back(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002677 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002678
Chris Lattner1afcace2011-07-09 17:41:24 +00002679 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerdf986172009-01-02 07:01:27 +00002680}
2681
2682/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2683/// token has already been consumed.
Chris Lattner1afcace2011-07-09 17:41:24 +00002684/// Type
Chris Lattnerdf986172009-01-02 07:01:27 +00002685/// ::= '[' APSINTVAL 'x' Types ']'
2686/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattner1afcace2011-07-09 17:41:24 +00002687bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002688 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2689 Lex.getAPSIntVal().getBitWidth() > 64)
2690 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002691
Chris Lattnerdf986172009-01-02 07:01:27 +00002692 LocTy SizeLoc = Lex.getLoc();
2693 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002694 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002695
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002696 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2697 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002698
2699 LocTy TypeLoc = Lex.getLoc();
Craig Topper0b6cb712014-04-15 06:32:26 +00002700 Type *EltTy = nullptr;
Chris Lattner1afcace2011-07-09 17:41:24 +00002701 if (ParseType(EltTy)) return true;
Chris Lattnera9a9e072009-03-09 04:49:14 +00002702
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002703 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2704 "expected end of sequential type"))
2705 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002706
Chris Lattnerdf986172009-01-02 07:01:27 +00002707 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00002708 if (Size == 0)
2709 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00002710 if ((unsigned)Size != Size)
2711 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00002712 if (!VectorType::isValidElementType(EltTy))
Duncan Sands2333e292012-11-13 12:59:33 +00002713 return Error(TypeLoc, "invalid vector element type");
Owen Andersondebcb012009-07-29 22:17:13 +00002714 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00002715 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00002716 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00002717 return Error(TypeLoc, "invalid array element type");
Chris Lattner1afcace2011-07-09 17:41:24 +00002718 Result = ArrayType::get(EltTy, Size);
Chris Lattnerdf986172009-01-02 07:01:27 +00002719 }
2720 return false;
2721}
2722
2723//===----------------------------------------------------------------------===//
2724// Function Semantic Analysis.
2725//===----------------------------------------------------------------------===//
2726
Chris Lattner09d9ef42009-10-28 03:39:23 +00002727LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2728 int functionNumber)
2729 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002730
2731 // Insert unnamed arguments into the NumberedVals list.
Duncan P. N. Exon Smith090db022015-10-20 01:12:49 +00002732 for (Argument &A : F.args())
2733 if (!A.hasName())
2734 NumberedVals.push_back(&A);
Chris Lattnerdf986172009-01-02 07:01:27 +00002735}
2736
2737LLParser::PerFunctionState::~PerFunctionState() {
2738 // If there were any forward referenced non-basicblock values, delete them.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002739
David Blaikie6030b442015-09-21 21:07:50 +00002740 for (const auto &P : ForwardRefVals) {
2741 if (isa<BasicBlock>(P.second.first))
2742 continue;
2743 P.second.first->replaceAllUsesWith(
2744 UndefValue::get(P.second.first->getType()));
Reid Kleckner816047d2017-05-18 17:24:10 +00002745 P.second.first->deleteValue();
David Blaikie6030b442015-09-21 21:07:50 +00002746 }
2747
2748 for (const auto &P : ForwardRefValIDs) {
2749 if (isa<BasicBlock>(P.second.first))
2750 continue;
2751 P.second.first->replaceAllUsesWith(
2752 UndefValue::get(P.second.first->getType()));
Reid Kleckner816047d2017-05-18 17:24:10 +00002753 P.second.first->deleteValue();
David Blaikie6030b442015-09-21 21:07:50 +00002754 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002755}
2756
Chris Lattner09d9ef42009-10-28 03:39:23 +00002757bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerdf986172009-01-02 07:01:27 +00002758 if (!ForwardRefVals.empty())
2759 return P.Error(ForwardRefVals.begin()->second.second,
2760 "use of undefined value '%" + ForwardRefVals.begin()->first +
2761 "'");
2762 if (!ForwardRefValIDs.empty())
2763 return P.Error(ForwardRefValIDs.begin()->second.second,
2764 "use of undefined value '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002765 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002766 return false;
2767}
2768
Chris Lattnerdf986172009-01-02 07:01:27 +00002769/// GetVal - Get a value with the specified name or ID, creating a
2770/// forward reference record if needed. This can return null if the value
2771/// exists but does not have the right type.
Joseph Tremouletd4a765f2015-08-23 00:26:33 +00002772Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
Alexander Richardsonb0b98842018-02-27 11:15:11 +00002773 LocTy Loc, bool IsCall) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002774 // Look this name up in the normal function symbol table.
Mehdi Aminid1e3c5a2016-09-17 06:00:02 +00002775 Value *Val = F.getValueSymbolTable()->lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002776
Chris Lattnerdf986172009-01-02 07:01:27 +00002777 // If this is a forward reference for the value, see if we already created a
2778 // forward ref record.
Craig Topper0b6cb712014-04-15 06:32:26 +00002779 if (!Val) {
David Blaikie6030b442015-09-21 21:07:50 +00002780 auto I = ForwardRefVals.find(Name);
Chris Lattnerdf986172009-01-02 07:01:27 +00002781 if (I != ForwardRefVals.end())
2782 Val = I->second.first;
2783 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002784
Chris Lattnerdf986172009-01-02 07:01:27 +00002785 // If we have the value in the symbol table or fwd-ref table, return it.
Alexander Richardson47ff67b2018-08-23 09:25:17 +00002786 if (Val)
2787 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val, IsCall);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002788
Chris Lattnerdf986172009-01-02 07:01:27 +00002789 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smithb72118f2014-08-05 18:22:58 +00002790 if (!Ty->isFirstClassType()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002791 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper0b6cb712014-04-15 06:32:26 +00002792 return nullptr;
Chris Lattnerdf986172009-01-02 07:01:27 +00002793 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002794
Chris Lattnerdf986172009-01-02 07:01:27 +00002795 // Otherwise, create a new forward reference for this value and remember it.
2796 Value *FwdVal;
Joseph Tremouletd4a765f2015-08-23 00:26:33 +00002797 if (Ty->isLabelTy()) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002798 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Joseph Tremouletd4a765f2015-08-23 00:26:33 +00002799 } else {
David Majnemer8cec2f22015-12-12 05:38:55 +00002800 FwdVal = new Argument(Ty, Name);
Joseph Tremouletd4a765f2015-08-23 00:26:33 +00002801 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002802
Chris Lattnerdf986172009-01-02 07:01:27 +00002803 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2804 return FwdVal;
2805}
2806
Alexander Richardsonb0b98842018-02-27 11:15:11 +00002807Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc,
2808 bool IsCall) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002809 // Look this name up in the normal function symbol table.
Craig Topper0b6cb712014-04-15 06:32:26 +00002810 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002811
Chris Lattnerdf986172009-01-02 07:01:27 +00002812 // If this is a forward reference for the value, see if we already created a
2813 // forward ref record.
Craig Topper0b6cb712014-04-15 06:32:26 +00002814 if (!Val) {
David Blaikie6030b442015-09-21 21:07:50 +00002815 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerdf986172009-01-02 07:01:27 +00002816 if (I != ForwardRefValIDs.end())
2817 Val = I->second.first;
2818 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002819
Chris Lattnerdf986172009-01-02 07:01:27 +00002820 // If we have the value in the symbol table or fwd-ref table, return it.
Alexander Richardson47ff67b2018-08-23 09:25:17 +00002821 if (Val)
2822 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val, IsCall);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002823
Duncan P. N. Exon Smithb72118f2014-08-05 18:22:58 +00002824 if (!Ty->isFirstClassType()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002825 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper0b6cb712014-04-15 06:32:26 +00002826 return nullptr;
Chris Lattnerdf986172009-01-02 07:01:27 +00002827 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002828
Chris Lattnerdf986172009-01-02 07:01:27 +00002829 // Otherwise, create a new forward reference for this value and remember it.
2830 Value *FwdVal;
Joseph Tremouletd4a765f2015-08-23 00:26:33 +00002831 if (Ty->isLabelTy()) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002832 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Joseph Tremouletd4a765f2015-08-23 00:26:33 +00002833 } else {
David Majnemer8cec2f22015-12-12 05:38:55 +00002834 FwdVal = new Argument(Ty);
Joseph Tremouletd4a765f2015-08-23 00:26:33 +00002835 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002836
Chris Lattnerdf986172009-01-02 07:01:27 +00002837 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2838 return FwdVal;
2839}
2840
2841/// SetInstName - After an instruction is parsed and inserted into its
2842/// basic block, this installs its name.
2843bool LLParser::PerFunctionState::SetInstName(int NameID,
2844 const std::string &NameStr,
2845 LocTy NameLoc, Instruction *Inst) {
2846 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002847 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002848 if (NameID != -1 || !NameStr.empty())
2849 return P.Error(NameLoc, "instructions returning void cannot have a name");
2850 return false;
2851 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002852
Chris Lattnerdf986172009-01-02 07:01:27 +00002853 // If this was a numbered instruction, verify that the instruction is the
2854 // expected value and resolve any forward references.
2855 if (NameStr.empty()) {
2856 // If neither a name nor an ID was specified, just use the next ID.
2857 if (NameID == -1)
2858 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002859
Chris Lattnerdf986172009-01-02 07:01:27 +00002860 if (unsigned(NameID) != NumberedVals.size())
2861 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002862 Twine(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002863
David Blaikie6030b442015-09-21 21:07:50 +00002864 auto FI = ForwardRefValIDs.find(NameID);
Chris Lattnerdf986172009-01-02 07:01:27 +00002865 if (FI != ForwardRefValIDs.end()) {
Joseph Tremouletd4a765f2015-08-23 00:26:33 +00002866 Value *Sentinel = FI->second.first;
2867 if (Sentinel->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002868 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002869 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremouletd4a765f2015-08-23 00:26:33 +00002870
2871 Sentinel->replaceAllUsesWith(Inst);
Reid Kleckner816047d2017-05-18 17:24:10 +00002872 Sentinel->deleteValue();
Chris Lattnerdf986172009-01-02 07:01:27 +00002873 ForwardRefValIDs.erase(FI);
2874 }
2875
2876 NumberedVals.push_back(Inst);
2877 return false;
2878 }
2879
2880 // Otherwise, the instruction had a name. Resolve forward refs and set it.
David Blaikie6030b442015-09-21 21:07:50 +00002881 auto FI = ForwardRefVals.find(NameStr);
Chris Lattnerdf986172009-01-02 07:01:27 +00002882 if (FI != ForwardRefVals.end()) {
Joseph Tremouletd4a765f2015-08-23 00:26:33 +00002883 Value *Sentinel = FI->second.first;
2884 if (Sentinel->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002885 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002886 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremouletd4a765f2015-08-23 00:26:33 +00002887
2888 Sentinel->replaceAllUsesWith(Inst);
Reid Kleckner816047d2017-05-18 17:24:10 +00002889 Sentinel->deleteValue();
Chris Lattnerdf986172009-01-02 07:01:27 +00002890 ForwardRefVals.erase(FI);
2891 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002892
Chris Lattnerdf986172009-01-02 07:01:27 +00002893 // Set the name on the instruction.
2894 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002895
Benjamin Krameraf812352010-10-16 11:28:23 +00002896 if (Inst->getName() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00002897 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00002898 NameStr + "'");
2899 return false;
2900}
2901
2902/// GetBB - Get a basic block with the specified name or ID, creating a
2903/// forward reference record if needed.
2904BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2905 LocTy Loc) {
Alexander Richardsonb0b98842018-02-27 11:15:11 +00002906 return dyn_cast_or_null<BasicBlock>(
2907 GetVal(Name, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
Chris Lattnerdf986172009-01-02 07:01:27 +00002908}
2909
2910BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Alexander Richardsonb0b98842018-02-27 11:15:11 +00002911 return dyn_cast_or_null<BasicBlock>(
2912 GetVal(ID, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
Chris Lattnerdf986172009-01-02 07:01:27 +00002913}
2914
2915/// DefineBB - Define the specified basic block, which is either named or
2916/// unnamed. If there is an error, this returns null otherwise it returns
2917/// the block being defined.
2918BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2919 LocTy Loc) {
2920 BasicBlock *BB;
2921 if (Name.empty())
2922 BB = GetBB(NumberedVals.size(), Loc);
2923 else
2924 BB = GetBB(Name, Loc);
Craig Topper0b6cb712014-04-15 06:32:26 +00002925 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002926
Chris Lattnerdf986172009-01-02 07:01:27 +00002927 // Move the block to the end of the function. Forward ref'd blocks are
2928 // inserted wherever they happen to be referenced.
2929 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002930
Chris Lattnerdf986172009-01-02 07:01:27 +00002931 // Remove the block from forward ref sets.
2932 if (Name.empty()) {
2933 ForwardRefValIDs.erase(NumberedVals.size());
2934 NumberedVals.push_back(BB);
2935 } else {
2936 // BB forward references are already in the function symbol table.
2937 ForwardRefVals.erase(Name);
2938 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002939
Chris Lattnerdf986172009-01-02 07:01:27 +00002940 return BB;
2941}
2942
2943//===----------------------------------------------------------------------===//
2944// Constants.
2945//===----------------------------------------------------------------------===//
2946
2947/// ParseValID - Parse an abstract value that doesn't necessarily have a
2948/// type implied. For example, if we parse "4" we don't know what integer type
2949/// it has. The value will later be combined with its type and checked for
Victor Hernandez24e64df2010-01-10 07:14:18 +00002950/// sanity. PFS is used to convert function-local operands of metadata (since
2951/// metadata operands are not just parsed here but also converted to values).
2952/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezbf170d42010-01-05 22:22:14 +00002953bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002954 ID.Loc = Lex.getLoc();
2955 switch (Lex.getKind()) {
2956 default: return TokError("expected value token");
2957 case lltok::GlobalID: // @42
2958 ID.UIntVal = Lex.getUIntVal();
2959 ID.Kind = ValID::t_GlobalID;
2960 break;
2961 case lltok::GlobalVar: // @foo
2962 ID.StrVal = Lex.getStrVal();
2963 ID.Kind = ValID::t_GlobalName;
2964 break;
2965 case lltok::LocalVarID: // %42
2966 ID.UIntVal = Lex.getUIntVal();
2967 ID.Kind = ValID::t_LocalID;
2968 break;
2969 case lltok::LocalVar: // %foo
Chris Lattnerdf986172009-01-02 07:01:27 +00002970 ID.StrVal = Lex.getStrVal();
2971 ID.Kind = ValID::t_LocalName;
2972 break;
2973 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002974 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002975 ID.Kind = ValID::t_APSInt;
2976 break;
2977 case lltok::APFloat:
2978 ID.APFloatVal = Lex.getAPFloatVal();
2979 ID.Kind = ValID::t_APFloat;
2980 break;
2981 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00002982 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002983 ID.Kind = ValID::t_Constant;
2984 break;
2985 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00002986 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002987 ID.Kind = ValID::t_Constant;
2988 break;
2989 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2990 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2991 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
David Majnemer83fc12a2015-11-11 21:57:16 +00002992 case lltok::kw_none: ID.Kind = ValID::t_None; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002993
Chris Lattnerdf986172009-01-02 07:01:27 +00002994 case lltok::lbrace: {
2995 // ValID ::= '{' ConstVector '}'
2996 Lex.Lex();
2997 SmallVector<Constant*, 16> Elts;
2998 if (ParseGlobalValueVector(Elts) ||
2999 ParseToken(lltok::rbrace, "expected end of struct constant"))
3000 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003001
David Blaikieafb53792015-08-03 20:08:41 +00003002 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
Chris Lattner1afcace2011-07-09 17:41:24 +00003003 ID.UIntVal = Elts.size();
David Blaikieafb53792015-08-03 20:08:41 +00003004 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3005 Elts.size() * sizeof(Elts[0]));
Chris Lattner1afcace2011-07-09 17:41:24 +00003006 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerdf986172009-01-02 07:01:27 +00003007 return false;
3008 }
3009 case lltok::less: {
3010 // ValID ::= '<' ConstVector '>' --> Vector.
3011 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3012 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003013 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003014
Chris Lattnerdf986172009-01-02 07:01:27 +00003015 SmallVector<Constant*, 16> Elts;
3016 LocTy FirstEltLoc = Lex.getLoc();
3017 if (ParseGlobalValueVector(Elts) ||
3018 (isPackedStruct &&
3019 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
3020 ParseToken(lltok::greater, "expected end of constant"))
3021 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003022
Chris Lattnerdf986172009-01-02 07:01:27 +00003023 if (isPackedStruct) {
David Blaikieafb53792015-08-03 20:08:41 +00003024 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
3025 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3026 Elts.size() * sizeof(Elts[0]));
Chris Lattner1afcace2011-07-09 17:41:24 +00003027 ID.UIntVal = Elts.size();
3028 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerdf986172009-01-02 07:01:27 +00003029 return false;
3030 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003031
Chris Lattnerdf986172009-01-02 07:01:27 +00003032 if (Elts.empty())
3033 return Error(ID.Loc, "constant vector must not be empty");
3034
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003035 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem16087692011-12-05 06:29:09 +00003036 !Elts[0]->getType()->isFloatingPointTy() &&
3037 !Elts[0]->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003038 return Error(FirstEltLoc,
Nadav Rotem16087692011-12-05 06:29:09 +00003039 "vector elements must have integer, pointer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003040
Chris Lattnerdf986172009-01-02 07:01:27 +00003041 // Verify that all the vector elements have the same type.
3042 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
3043 if (Elts[i]->getType() != Elts[0]->getType())
3044 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00003045 "vector element #" + Twine(i) +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003046 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003047
Chris Lattner2ca5c862011-02-15 00:14:00 +00003048 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerdf986172009-01-02 07:01:27 +00003049 ID.Kind = ValID::t_Constant;
3050 return false;
3051 }
3052 case lltok::lsquare: { // Array Constant
3053 Lex.Lex();
3054 SmallVector<Constant*, 16> Elts;
3055 LocTy FirstEltLoc = Lex.getLoc();
3056 if (ParseGlobalValueVector(Elts) ||
3057 ParseToken(lltok::rsquare, "expected end of array constant"))
3058 return true;
3059
3060 // Handle empty element.
3061 if (Elts.empty()) {
3062 // Use undef instead of an array because it's inconvenient to determine
3063 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00003064 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00003065 return false;
3066 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003067
Chris Lattnerdf986172009-01-02 07:01:27 +00003068 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00003069 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003070 getTypeString(Elts[0]->getType()));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003071
Owen Andersondebcb012009-07-29 22:17:13 +00003072 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003073
Chris Lattnerdf986172009-01-02 07:01:27 +00003074 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00003075 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003076 if (Elts[i]->getType() != Elts[0]->getType())
3077 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00003078 "array element #" + Twine(i) +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003079 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00003080 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003081
Jay Foad26701082011-06-22 09:24:39 +00003082 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerdf986172009-01-02 07:01:27 +00003083 ID.Kind = ValID::t_Constant;
3084 return false;
3085 }
3086 case lltok::kw_c: // c "foo"
3087 Lex.Lex();
Chris Lattner18c7f802012-02-05 02:29:43 +00003088 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
3089 false);
Chris Lattnerdf986172009-01-02 07:01:27 +00003090 if (ParseToken(lltok::StringConstant, "expected string")) return true;
3091 ID.Kind = ValID::t_Constant;
3092 return false;
3093
3094 case lltok::kw_asm: {
Chad Rosier27d844f2013-02-14 20:44:07 +00003095 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
3096 // STRINGCONSTANT
Chad Rosier581600b2012-09-05 19:00:49 +00003097 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerdf986172009-01-02 07:01:27 +00003098 Lex.Lex();
3099 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00003100 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosier581600b2012-09-05 19:00:49 +00003101 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003102 ParseStringConstant(ID.StrVal) ||
3103 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003104 ParseToken(lltok::StringConstant, "expected constraint string"))
3105 return true;
3106 ID.StrVal2 = Lex.getStrVal();
Chad Rosier36547342012-09-05 00:08:17 +00003107 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosier581600b2012-09-05 19:00:49 +00003108 (unsigned(AsmDialect)<<2);
Chris Lattnerdf986172009-01-02 07:01:27 +00003109 ID.Kind = ValID::t_InlineAsm;
3110 return false;
3111 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003112
Chris Lattner09d9ef42009-10-28 03:39:23 +00003113 case lltok::kw_blockaddress: {
3114 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3115 Lex.Lex();
3116
3117 ValID Fn, Label;
Michael Ilseman407a6162012-11-15 22:34:00 +00003118
Chris Lattner09d9ef42009-10-28 03:39:23 +00003119 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
3120 ParseValID(Fn) ||
3121 ParseToken(lltok::comma, "expected comma in block address expression")||
3122 ParseValID(Label) ||
3123 ParseToken(lltok::rparen, "expected ')' in block address expression"))
3124 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00003125
Chris Lattner09d9ef42009-10-28 03:39:23 +00003126 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3127 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattnercdfc9402009-11-01 01:27:45 +00003128 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner09d9ef42009-10-28 03:39:23 +00003129 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman407a6162012-11-15 22:34:00 +00003130
Duncan P. N. Exon Smith16589782014-08-19 00:13:19 +00003131 // Try to find the function (but skip it if it's forward-referenced).
3132 GlobalValue *GV = nullptr;
3133 if (Fn.Kind == ValID::t_GlobalID) {
3134 if (Fn.UIntVal < NumberedVals.size())
3135 GV = NumberedVals[Fn.UIntVal];
3136 } else if (!ForwardRefVals.count(Fn.StrVal)) {
3137 GV = M->getNamedValue(Fn.StrVal);
3138 }
3139 Function *F = nullptr;
3140 if (GV) {
3141 // Confirm that it's actually a function with a definition.
3142 if (!isa<Function>(GV))
3143 return Error(Fn.Loc, "expected function name in blockaddress");
3144 F = cast<Function>(GV);
3145 if (F->isDeclaration())
3146 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
3147 }
3148
3149 if (!F) {
3150 // Make a global variable as a placeholder for this reference.
David Blaikiede2cab92015-03-04 01:40:07 +00003151 GlobalValue *&FwdRef =
David Blaikiea5905332015-08-03 20:55:00 +00003152 ForwardRefBlockAddresses.insert(std::make_pair(
3153 std::move(Fn),
3154 std::map<ValID, GlobalValue *>()))
David Blaikiede2cab92015-03-04 01:40:07 +00003155 .first->second.insert(std::make_pair(std::move(Label), nullptr))
3156 .first->second;
Duncan P. N. Exon Smith16589782014-08-19 00:13:19 +00003157 if (!FwdRef)
3158 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
3159 GlobalValue::InternalLinkage, nullptr, "");
3160 ID.ConstantVal = FwdRef;
3161 ID.Kind = ValID::t_Constant;
3162 return false;
3163 }
3164
3165 // We found the function; now find the basic block. Don't use PFS, since we
3166 // might be inside a constant expression.
3167 BasicBlock *BB;
3168 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
3169 if (Label.Kind == ValID::t_LocalID)
3170 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
3171 else
3172 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
3173 if (!BB)
3174 return Error(Label.Loc, "referenced value is not a basic block");
3175 } else {
3176 if (Label.Kind == ValID::t_LocalID)
3177 return Error(Label.Loc, "cannot take address of numeric label after "
3178 "the function is defined");
3179 BB = dyn_cast_or_null<BasicBlock>(
Mehdi Aminid1e3c5a2016-09-17 06:00:02 +00003180 F->getValueSymbolTable()->lookup(Label.StrVal));
Duncan P. N. Exon Smith16589782014-08-19 00:13:19 +00003181 if (!BB)
3182 return Error(Label.Loc, "referenced value is not a basic block");
3183 }
3184
3185 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner09d9ef42009-10-28 03:39:23 +00003186 ID.Kind = ValID::t_Constant;
3187 return false;
3188 }
Michael Ilseman407a6162012-11-15 22:34:00 +00003189
Chris Lattnerdf986172009-01-02 07:01:27 +00003190 case lltok::kw_trunc:
3191 case lltok::kw_zext:
3192 case lltok::kw_sext:
3193 case lltok::kw_fptrunc:
3194 case lltok::kw_fpext:
3195 case lltok::kw_bitcast:
Matt Arsenault59d3ae62013-11-15 01:34:59 +00003196 case lltok::kw_addrspacecast:
Chris Lattnerdf986172009-01-02 07:01:27 +00003197 case lltok::kw_uitofp:
3198 case lltok::kw_sitofp:
3199 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00003200 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00003201 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00003202 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00003203 unsigned Opc = Lex.getUIntVal();
Craig Topper0b6cb712014-04-15 06:32:26 +00003204 Type *DestTy = nullptr;
Chris Lattnerdf986172009-01-02 07:01:27 +00003205 Constant *SrcVal;
3206 Lex.Lex();
3207 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3208 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00003209 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003210 ParseType(DestTy) ||
3211 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3212 return true;
3213 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3214 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003215 getTypeString(SrcVal->getType()) + "' to '" +
3216 getTypeString(DestTy) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003217 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00003218 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003219 ID.Kind = ValID::t_Constant;
3220 return false;
3221 }
3222 case lltok::kw_extractvalue: {
3223 Lex.Lex();
3224 Constant *Val;
3225 SmallVector<unsigned, 4> Indices;
3226 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
3227 ParseGlobalTypeAndValue(Val) ||
3228 ParseIndexList(Indices) ||
3229 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
3230 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00003231
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003232 if (!Val->getType()->isAggregateType())
3233 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foadfc6d3a42011-07-13 10:26:04 +00003234 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00003235 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00003236 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerdf986172009-01-02 07:01:27 +00003237 ID.Kind = ValID::t_Constant;
3238 return false;
3239 }
3240 case lltok::kw_insertvalue: {
3241 Lex.Lex();
3242 Constant *Val0, *Val1;
3243 SmallVector<unsigned, 4> Indices;
3244 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
3245 ParseGlobalTypeAndValue(Val0) ||
3246 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
3247 ParseGlobalTypeAndValue(Val1) ||
3248 ParseIndexList(Indices) ||
3249 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3250 return true;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003251 if (!Val0->getType()->isAggregateType())
3252 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemer749c0292015-02-23 07:13:52 +00003253 Type *IndexedType =
3254 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3255 if (!IndexedType)
Chris Lattnerdf986172009-01-02 07:01:27 +00003256 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemer749c0292015-02-23 07:13:52 +00003257 if (IndexedType != Val1->getType())
3258 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3259 getTypeString(Val1->getType()) +
3260 "' instead of '" + getTypeString(IndexedType) +
3261 "'");
Jay Foadfc6d3a42011-07-13 10:26:04 +00003262 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerdf986172009-01-02 07:01:27 +00003263 ID.Kind = ValID::t_Constant;
3264 return false;
3265 }
3266 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003267 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00003268 unsigned PredVal, Opc = Lex.getUIntVal();
3269 Constant *Val0, *Val1;
3270 Lex.Lex();
3271 if (ParseCmpPredicate(PredVal, Opc) ||
3272 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3273 ParseGlobalTypeAndValue(Val0) ||
3274 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3275 ParseGlobalTypeAndValue(Val1) ||
3276 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3277 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003278
Chris Lattnerdf986172009-01-02 07:01:27 +00003279 if (Val0->getType() != Val1->getType())
3280 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003281
Chris Lattnerdf986172009-01-02 07:01:27 +00003282 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003283
Chris Lattnerdf986172009-01-02 07:01:27 +00003284 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003285 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003286 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003287 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003288 } else {
3289 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003290 if (!Val0->getType()->isIntOrIntVectorTy() &&
Craig Topper10600822017-07-09 07:04:00 +00003291 !Val0->getType()->isPtrOrPtrVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003292 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003293 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003294 }
3295 ID.Kind = ValID::t_Constant;
3296 return false;
3297 }
Cameron McInallyca8cb682018-11-13 18:15:47 +00003298
3299 // Unary Operators.
3300 case lltok::kw_fneg: {
3301 unsigned Opc = Lex.getUIntVal();
3302 Constant *Val;
3303 Lex.Lex();
3304 if (ParseToken(lltok::lparen, "expected '(' in unary constantexpr") ||
3305 ParseGlobalTypeAndValue(Val) ||
3306 ParseToken(lltok::rparen, "expected ')' in unary constantexpr"))
3307 return true;
3308
3309 // Check that the type is valid for the operator.
3310 switch (Opc) {
3311 case Instruction::FNeg:
3312 if (!Val->getType()->isFPOrFPVectorTy())
3313 return Error(ID.Loc, "constexpr requires fp operands");
3314 break;
3315 default: llvm_unreachable("Unknown unary operator!");
3316 }
3317 unsigned Flags = 0;
3318 Constant *C = ConstantExpr::get(Opc, Val, Flags);
3319 ID.ConstantVal = C;
3320 ID.Kind = ValID::t_Constant;
3321 return false;
3322 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003323 // Binary Operators.
3324 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003325 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00003326 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003327 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00003328 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003329 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00003330 case lltok::kw_udiv:
3331 case lltok::kw_sdiv:
3332 case lltok::kw_fdiv:
3333 case lltok::kw_urem:
3334 case lltok::kw_srem:
Chris Lattnerf067d582011-02-07 16:40:21 +00003335 case lltok::kw_frem:
3336 case lltok::kw_shl:
3337 case lltok::kw_lshr:
3338 case lltok::kw_ashr: {
Dan Gohman59858cf2009-07-27 16:11:46 +00003339 bool NUW = false;
3340 bool NSW = false;
3341 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003342 unsigned Opc = Lex.getUIntVal();
3343 Constant *Val0, *Val1;
3344 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00003345 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnerf067d582011-02-07 16:40:21 +00003346 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3347 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman59858cf2009-07-27 16:11:46 +00003348 if (EatIfPresent(lltok::kw_nuw))
3349 NUW = true;
3350 if (EatIfPresent(lltok::kw_nsw)) {
3351 NSW = true;
3352 if (EatIfPresent(lltok::kw_nuw))
3353 NUW = true;
3354 }
Chris Lattnerf067d582011-02-07 16:40:21 +00003355 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3356 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman59858cf2009-07-27 16:11:46 +00003357 if (EatIfPresent(lltok::kw_exact))
3358 Exact = true;
3359 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003360 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3361 ParseGlobalTypeAndValue(Val0) ||
3362 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3363 ParseGlobalTypeAndValue(Val1) ||
3364 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3365 return true;
3366 if (Val0->getType() != Val1->getType())
3367 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003368 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00003369 if (NUW)
3370 return Error(ModifierLoc, "nuw only applies to integer operations");
3371 if (NSW)
3372 return Error(ModifierLoc, "nsw only applies to integer operations");
3373 }
Dan Gohman1eaac532010-05-03 22:44:19 +00003374 // Check that the type is valid for the operator.
3375 switch (Opc) {
3376 case Instruction::Add:
3377 case Instruction::Sub:
3378 case Instruction::Mul:
3379 case Instruction::UDiv:
3380 case Instruction::SDiv:
3381 case Instruction::URem:
3382 case Instruction::SRem:
Chris Lattnerf067d582011-02-07 16:40:21 +00003383 case Instruction::Shl:
3384 case Instruction::AShr:
3385 case Instruction::LShr:
Dan Gohman1eaac532010-05-03 22:44:19 +00003386 if (!Val0->getType()->isIntOrIntVectorTy())
3387 return Error(ID.Loc, "constexpr requires integer operands");
3388 break;
3389 case Instruction::FAdd:
3390 case Instruction::FSub:
3391 case Instruction::FMul:
3392 case Instruction::FDiv:
3393 case Instruction::FRem:
3394 if (!Val0->getType()->isFPOrFPVectorTy())
3395 return Error(ID.Loc, "constexpr requires fp operands");
3396 break;
3397 default: llvm_unreachable("Unknown binary operator!");
3398 }
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003399 unsigned Flags = 0;
3400 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3401 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00003402 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003403 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00003404 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00003405 ID.Kind = ValID::t_Constant;
3406 return false;
3407 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003408
Chris Lattnerdf986172009-01-02 07:01:27 +00003409 // Logical Operations
Chris Lattnerdf986172009-01-02 07:01:27 +00003410 case lltok::kw_and:
3411 case lltok::kw_or:
3412 case lltok::kw_xor: {
3413 unsigned Opc = Lex.getUIntVal();
3414 Constant *Val0, *Val1;
3415 Lex.Lex();
3416 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3417 ParseGlobalTypeAndValue(Val0) ||
3418 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3419 ParseGlobalTypeAndValue(Val1) ||
3420 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3421 return true;
3422 if (Val0->getType() != Val1->getType())
3423 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003424 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003425 return Error(ID.Loc,
3426 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003427 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003428 ID.Kind = ValID::t_Constant;
3429 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003430 }
3431
Chris Lattnerdf986172009-01-02 07:01:27 +00003432 case lltok::kw_getelementptr:
3433 case lltok::kw_shufflevector:
3434 case lltok::kw_insertelement:
3435 case lltok::kw_extractelement:
3436 case lltok::kw_select: {
3437 unsigned Opc = Lex.getUIntVal();
3438 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003439 bool InBounds = false;
David Blaikie5a70dd12015-03-13 18:20:45 +00003440 Type *Ty;
Chris Lattnerdf986172009-01-02 07:01:27 +00003441 Lex.Lex();
David Blaikie5a70dd12015-03-13 18:20:45 +00003442
Dan Gohmandd8004d2009-07-27 21:53:46 +00003443 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00003444 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikie5a70dd12015-03-13 18:20:45 +00003445
3446 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3447 return true;
3448
3449 LocTy ExplicitTypeLoc = Lex.getLoc();
3450 if (Opc == Instruction::GetElementPtr) {
3451 if (ParseType(Ty) ||
3452 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3453 return true;
3454 }
3455
Peter Collingbourneca668e12016-11-10 22:34:55 +00003456 Optional<unsigned> InRangeOp;
3457 if (ParseGlobalValueVector(
3458 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003459 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3460 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003461
Chris Lattnerdf986172009-01-02 07:01:27 +00003462 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem16087692011-12-05 06:29:09 +00003463 if (Elts.size() == 0 ||
Craig Topper10600822017-07-09 07:04:00 +00003464 !Elts[0]->getType()->isPtrOrPtrVectorTy())
David Majnemer15cf9242015-02-22 23:14:52 +00003465 return Error(ID.Loc, "base of getelementptr must be a pointer");
3466
3467 Type *BaseType = Elts[0]->getType();
3468 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikie5a70dd12015-03-13 18:20:45 +00003469 if (Ty != BasePointerType->getElementType())
3470 return Error(
3471 ExplicitTypeLoc,
3472 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003473
Michael Kupersteinf4bf6512016-12-21 18:29:47 +00003474 unsigned GEPWidth =
3475 BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
3476
Jay Foaddab3d292011-07-21 14:31:17 +00003477 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer15cf9242015-02-22 23:14:52 +00003478 for (Constant *Val : Indices) {
3479 Type *ValTy = Val->getType();
Craig Topper10600822017-07-09 07:04:00 +00003480 if (!ValTy->isIntOrIntVectorTy())
David Majnemer15cf9242015-02-22 23:14:52 +00003481 return Error(ID.Loc, "getelementptr index must be an integer");
David Majnemer15cf9242015-02-22 23:14:52 +00003482 if (ValTy->isVectorTy()) {
Elena Demikhovsky43afab32015-07-09 07:42:48 +00003483 unsigned ValNumEl = ValTy->getVectorNumElements();
Michael Kupersteinf4bf6512016-12-21 18:29:47 +00003484 if (GEPWidth && (ValNumEl != GEPWidth))
David Majnemer15cf9242015-02-22 23:14:52 +00003485 return Error(
3486 ID.Loc,
3487 "getelementptr vector index has a wrong number of elements");
Michael Kupersteinf4bf6512016-12-21 18:29:47 +00003488 // GEPWidth may have been unknown because the base is a scalar,
3489 // but it is known now.
3490 GEPWidth = ValNumEl;
David Majnemer15cf9242015-02-22 23:14:52 +00003491 }
3492 }
3493
Craig Topper84bbcfe2015-08-01 22:20:21 +00003494 SmallPtrSet<Type*, 4> Visited;
David Blaikie1436ff82015-04-22 16:37:35 +00003495 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer15cf9242015-02-22 23:14:52 +00003496 return Error(ID.Loc, "base element of getelementptr must be sized");
3497
David Blaikie19443c12015-04-02 18:55:32 +00003498 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer15cf9242015-02-22 23:14:52 +00003499 return Error(ID.Loc, "invalid getelementptr indices");
Peter Collingbourneca668e12016-11-10 22:34:55 +00003500
3501 if (InRangeOp) {
3502 if (*InRangeOp == 0)
3503 return Error(ID.Loc,
3504 "inrange keyword may not appear on pointer operand");
3505 --*InRangeOp;
3506 }
3507
3508 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3509 InBounds, InRangeOp);
Chris Lattnerdf986172009-01-02 07:01:27 +00003510 } else if (Opc == Instruction::Select) {
3511 if (Elts.size() != 3)
3512 return Error(ID.Loc, "expected three operands to select");
3513 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3514 Elts[2]))
3515 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00003516 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00003517 } else if (Opc == Instruction::ShuffleVector) {
3518 if (Elts.size() != 3)
3519 return Error(ID.Loc, "expected three operands to shufflevector");
3520 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3521 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00003522 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00003523 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00003524 } else if (Opc == Instruction::ExtractElement) {
3525 if (Elts.size() != 2)
3526 return Error(ID.Loc, "expected two operands to extractelement");
3527 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3528 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003529 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00003530 } else {
3531 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3532 if (Elts.size() != 3)
3533 return Error(ID.Loc, "expected three operands to insertelement");
3534 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3535 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00003536 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00003537 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00003538 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003539
Chris Lattnerdf986172009-01-02 07:01:27 +00003540 ID.Kind = ValID::t_Constant;
3541 return false;
3542 }
3543 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003544
Chris Lattnerdf986172009-01-02 07:01:27 +00003545 Lex.Lex();
3546 return false;
3547}
3548
3549/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003550bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper0b6cb712014-04-15 06:32:26 +00003551 C = nullptr;
Chris Lattnerdf986172009-01-02 07:01:27 +00003552 ValID ID;
Craig Topper0b6cb712014-04-15 06:32:26 +00003553 Value *V = nullptr;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003554 bool Parsed = ParseValID(ID) ||
Alexander Richardsonb0b98842018-02-27 11:15:11 +00003555 ConvertValIDToValue(Ty, ID, V, nullptr, /*IsCall=*/false);
Victor Hernandez92f238d2010-01-11 22:31:58 +00003556 if (V && !(C = dyn_cast<Constant>(V)))
3557 return Error(ID.Loc, "global values must be constants");
3558 return Parsed;
Chris Lattnerdf986172009-01-02 07:01:27 +00003559}
3560
Victor Hernandez92f238d2010-01-11 22:31:58 +00003561bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper0b6cb712014-04-15 06:32:26 +00003562 Type *Ty = nullptr;
Chris Lattner1afcace2011-07-09 17:41:24 +00003563 return ParseType(Ty) ||
3564 ParseGlobalValue(Ty, V);
Victor Hernandez92f238d2010-01-11 22:31:58 +00003565}
3566
Rafael Espindolaf907a262015-01-06 22:55:16 +00003567bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerc8a11692014-06-27 18:19:56 +00003568 C = nullptr;
Rafael Espindolaf907a262015-01-06 22:55:16 +00003569
3570 LocTy KwLoc = Lex.getLoc();
David Majnemerc8a11692014-06-27 18:19:56 +00003571 if (!EatIfPresent(lltok::kw_comdat))
3572 return false;
Rafael Espindolaf907a262015-01-06 22:55:16 +00003573
3574 if (EatIfPresent(lltok::lparen)) {
3575 if (Lex.getKind() != lltok::ComdatVar)
3576 return TokError("expected comdat variable");
3577 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3578 Lex.Lex();
3579 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3580 return true;
3581 } else {
3582 if (GlobalName.empty())
3583 return TokError("comdat cannot be unnamed");
3584 C = getComdat(GlobalName, KwLoc);
3585 }
3586
David Majnemerc8a11692014-06-27 18:19:56 +00003587 return false;
3588}
3589
Victor Hernandez92f238d2010-01-11 22:31:58 +00003590/// ParseGlobalValueVector
3591/// ::= /*empty*/
Peter Collingbourneca668e12016-11-10 22:34:55 +00003592/// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3593bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3594 Optional<unsigned> *InRangeOp) {
Victor Hernandez92f238d2010-01-11 22:31:58 +00003595 // Empty list.
3596 if (Lex.getKind() == lltok::rbrace ||
3597 Lex.getKind() == lltok::rsquare ||
3598 Lex.getKind() == lltok::greater ||
3599 Lex.getKind() == lltok::rparen)
3600 return false;
3601
Peter Collingbourneca668e12016-11-10 22:34:55 +00003602 do {
3603 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3604 *InRangeOp = Elts.size();
Victor Hernandez92f238d2010-01-11 22:31:58 +00003605
Peter Collingbourneca668e12016-11-10 22:34:55 +00003606 Constant *C;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003607 if (ParseGlobalTypeAndValue(C)) return true;
3608 Elts.push_back(C);
Peter Collingbourneca668e12016-11-10 22:34:55 +00003609 } while (EatIfPresent(lltok::comma));
Victor Hernandez92f238d2010-01-11 22:31:58 +00003610
3611 return false;
3612}
3613
Duncan P. N. Exon Smith9e8d3bc2015-01-12 21:23:11 +00003614bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +00003615 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smith1ef70ff2014-12-15 19:07:53 +00003616 if (ParseMDNodeVector(Elts))
Dan Gohman309b3af2010-08-24 02:24:03 +00003617 return true;
3618
Duncan P. N. Exon Smith0c51e0a2015-01-12 22:27:39 +00003619 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohman309b3af2010-08-24 02:24:03 +00003620 return false;
3621}
3622
Duncan P. N. Exon Smithe390a8e2015-01-12 22:26:48 +00003623/// MDNode:
3624/// ::= !{ ... }
3625/// ::= !7
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00003626/// ::= !DILocation(...)
Duncan P. N. Exon Smithe390a8e2015-01-12 22:26:48 +00003627bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith3b0fe4e2015-01-13 21:10:44 +00003628 if (Lex.getKind() == lltok::MetadataVar)
3629 return ParseSpecializedMDNode(N);
3630
Duncan P. N. Exon Smithe390a8e2015-01-12 22:26:48 +00003631 return ParseToken(lltok::exclaim, "expected '!' here") ||
3632 ParseMDNodeTail(N);
3633}
3634
3635bool LLParser::ParseMDNodeTail(MDNode *&N) {
3636 // !{ ... }
3637 if (Lex.getKind() == lltok::lbrace)
3638 return ParseMDTuple(N);
3639
3640 // !42
3641 return ParseMDNodeID(N);
3642}
3643
Duncan P. N. Exon Smith89aee382015-02-04 22:05:21 +00003644namespace {
3645
3646/// Structure to represent an optional metadata field.
3647template <class FieldTy> struct MDFieldImpl {
3648 typedef MDFieldImpl ImplTy;
3649 FieldTy Val;
3650 bool Seen;
3651
3652 void assign(FieldTy Val) {
3653 Seen = true;
3654 this->Val = std::move(Val);
3655 }
3656
3657 explicit MDFieldImpl(FieldTy Default)
3658 : Val(std::move(Default)), Seen(false) {}
3659};
Duncan P. N. Exon Smithb984c492015-02-13 01:10:38 +00003660
Sander de Smalen959cee72018-01-24 09:56:07 +00003661/// Structure to represent an optional metadata field that
3662/// can be of either type (A or B) and encapsulates the
3663/// MD<typeofA>Field and MD<typeofB>Field structs, so not
3664/// to reimplement the specifics for representing each Field.
3665template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
3666 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
3667 FieldTypeA A;
3668 FieldTypeB B;
3669 bool Seen;
3670
3671 enum {
3672 IsInvalid = 0,
3673 IsTypeA = 1,
3674 IsTypeB = 2
3675 } WhatIs;
3676
3677 void assign(FieldTypeA A) {
3678 Seen = true;
3679 this->A = std::move(A);
3680 WhatIs = IsTypeA;
3681 }
3682
3683 void assign(FieldTypeB B) {
3684 Seen = true;
3685 this->B = std::move(B);
3686 WhatIs = IsTypeB;
3687 }
3688
3689 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
3690 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
3691 WhatIs(IsInvalid) {}
3692};
3693
Duncan P. N. Exon Smith89aee382015-02-04 22:05:21 +00003694struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3695 uint64_t Max;
3696
3697 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3698 : ImplTy(Default), Max(Max) {}
3699};
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +00003700
Duncan P. N. Exon Smith783e0e42015-02-04 22:59:18 +00003701struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smith8713d992015-02-06 22:50:13 +00003702 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith783e0e42015-02-04 22:59:18 +00003703};
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +00003704
Duncan P. N. Exon Smith783e0e42015-02-04 22:59:18 +00003705struct ColumnField : public MDUnsignedField {
3706 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3707};
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +00003708
Duncan P. N. Exon Smith89aee382015-02-04 22:05:21 +00003709struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smithd4d3a432015-02-06 22:29:35 +00003710 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith9b18dbf2015-02-28 23:21:38 +00003711 DwarfTagField(dwarf::Tag DefaultTag)
3712 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith89aee382015-02-04 22:05:21 +00003713};
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +00003714
Amjad Aboud7db39802015-12-10 12:56:35 +00003715struct DwarfMacinfoTypeField : public MDUnsignedField {
3716 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3717 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3718 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3719};
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +00003720
Duncan P. N. Exon Smith95d71352015-02-13 01:17:35 +00003721struct DwarfAttEncodingField : public MDUnsignedField {
3722 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3723};
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +00003724
Duncan P. N. Exon Smith4730b902015-02-13 01:28:16 +00003725struct DwarfVirtualityField : public MDUnsignedField {
3726 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3727};
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +00003728
Duncan P. N. Exon Smith65e12272015-02-13 01:21:25 +00003729struct DwarfLangField : public MDUnsignedField {
3730 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3731};
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +00003732
Reid Kleckner3d3aca22016-06-08 20:34:29 +00003733struct DwarfCCField : public MDUnsignedField {
3734 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3735};
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +00003736
Adrian Prantl39bb84a2016-03-31 23:56:58 +00003737struct EmissionKindField : public MDUnsignedField {
3738 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3739};
Duncan P. N. Exon Smithb984c492015-02-13 01:10:38 +00003740
David Blaikiecf8a4a52018-08-16 21:29:55 +00003741struct NameTableKindField : public MDUnsignedField {
3742 NameTableKindField()
3743 : MDUnsignedField(
3744 0, (unsigned)
3745 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
3746};
3747
Leny Kholodovd9478f82016-09-06 10:46:28 +00003748struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3749 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
Duncan P. N. Exon Smith9f8d4032015-02-21 01:02:18 +00003750};
3751
Paul Robinsonccefd882018-11-28 21:14:32 +00003752struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
3753 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
3754};
3755
Duncan P. N. Exon Smithb984c492015-02-13 01:10:38 +00003756struct MDSignedField : public MDFieldImpl<int64_t> {
3757 int64_t Min;
3758 int64_t Max;
3759
3760 MDSignedField(int64_t Default = 0)
3761 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3762 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3763 : ImplTy(Default), Min(Min), Max(Max) {}
3764};
3765
Duncan P. N. Exon Smith65e12272015-02-13 01:21:25 +00003766struct MDBoolField : public MDFieldImpl<bool> {
3767 MDBoolField(bool Default = false) : ImplTy(Default) {}
3768};
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +00003769
Duncan P. N. Exon Smith89aee382015-02-04 22:05:21 +00003770struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smith2cee1c92015-03-27 17:56:39 +00003771 bool AllowNull;
3772
3773 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith89aee382015-02-04 22:05:21 +00003774};
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +00003775
Duncan P. N. Exon Smithed356a92015-02-13 01:26:47 +00003776struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3777 MDConstant() : ImplTy(nullptr) {}
3778};
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +00003779
Duncan P. N. Exon Smitha9902da2015-03-27 17:29:58 +00003780struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smithc0bf4a02015-03-31 01:28:22 +00003781 bool AllowEmpty;
3782 MDStringField(bool AllowEmpty = true)
3783 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith89aee382015-02-04 22:05:21 +00003784};
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +00003785
Duncan P. N. Exon Smith89aee382015-02-04 22:05:21 +00003786struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3787 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3788};
3789
Amjad Aboud4e2e80b2016-12-25 10:12:09 +00003790struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
Amjad Aboud4e2e80b2016-12-25 10:12:09 +00003791 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3792};
3793
Sander de Smalen959cee72018-01-24 09:56:07 +00003794struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
3795 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
3796 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
3797
3798 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
3799 bool AllowNull = true)
3800 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
3801
3802 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3803 bool isMDField() const { return WhatIs == IsTypeB; }
3804 int64_t getMDSignedValue() const {
3805 assert(isMDSignedField() && "Wrong field type");
3806 return A.Val;
3807 }
3808 Metadata *getMDFieldValue() const {
3809 assert(isMDField() && "Wrong field type");
3810 return B.Val;
3811 }
3812};
3813
Momchil Velikov0c69bf42018-02-12 16:10:09 +00003814struct MDSignedOrUnsignedField
3815 : MDEitherFieldImpl<MDSignedField, MDUnsignedField> {
3816 MDSignedOrUnsignedField() : ImplTy(MDSignedField(0), MDUnsignedField(0)) {}
3817
3818 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3819 bool isMDUnsignedField() const { return WhatIs == IsTypeB; }
3820 int64_t getMDSignedValue() const {
3821 assert(isMDSignedField() && "Wrong field type");
3822 return A.Val;
3823 }
3824 uint64_t getMDUnsignedValue() const {
3825 assert(isMDUnsignedField() && "Wrong field type");
3826 return B.Val;
3827 }
3828};
3829
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +00003830} // end anonymous namespace
Duncan P. N. Exon Smith89aee382015-02-04 22:05:21 +00003831
Duncan P. N. Exon Smith8054a412015-02-04 22:13:28 +00003832namespace llvm {
3833
Duncan P. N. Exon Smith89aee382015-02-04 22:05:21 +00003834template <>
Duncan P. N. Exon Smith3b0fe4e2015-01-13 21:10:44 +00003835bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith321b43e2015-02-04 21:57:52 +00003836 MDUnsignedField &Result) {
Duncan P. N. Exon Smith3b0fe4e2015-01-13 21:10:44 +00003837 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3838 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith3b0fe4e2015-01-13 21:10:44 +00003839
Duncan P. N. Exon Smith321b43e2015-02-04 21:57:52 +00003840 auto &U = Lex.getAPSIntVal();
3841 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith3b0fe4e2015-01-13 21:10:44 +00003842 return TokError("value for '" + Name + "' too large, limit is " +
3843 Twine(Result.Max));
Duncan P. N. Exon Smith321b43e2015-02-04 21:57:52 +00003844 Result.assign(U.getZExtValue());
3845 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith3b0fe4e2015-01-13 21:10:44 +00003846 Lex.Lex();
3847 return false;
3848}
3849
Duncan P. N. Exon Smith89aee382015-02-04 22:05:21 +00003850template <>
Duncan P. N. Exon Smith783e0e42015-02-04 22:59:18 +00003851bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3852 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3853}
3854template <>
3855bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3856 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3857}
3858
3859template <>
Duncan P. N. Exon Smith1602e582015-02-03 21:56:01 +00003860bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3861 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith321b43e2015-02-04 21:57:52 +00003862 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith1602e582015-02-03 21:56:01 +00003863
Duncan P. N. Exon Smith1602e582015-02-03 21:56:01 +00003864 if (Lex.getKind() != lltok::DwarfTag)
3865 return TokError("expected DWARF tag");
3866
3867 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3868 if (Tag == dwarf::DW_TAG_invalid)
3869 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smith99dc9452015-02-04 22:02:18 +00003870 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith1602e582015-02-03 21:56:01 +00003871
3872 Result.assign(Tag);
3873 Lex.Lex();
3874 return false;
3875}
3876
Duncan P. N. Exon Smith89aee382015-02-04 22:05:21 +00003877template <>
Duncan P. N. Exon Smith4730b902015-02-13 01:28:16 +00003878bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Amjad Aboud7db39802015-12-10 12:56:35 +00003879 DwarfMacinfoTypeField &Result) {
3880 if (Lex.getKind() == lltok::APSInt)
3881 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3882
3883 if (Lex.getKind() != lltok::DwarfMacinfo)
3884 return TokError("expected DWARF macinfo type");
3885
3886 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3887 if (Macinfo == dwarf::DW_MACINFO_invalid)
3888 return TokError(
3889 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3890 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3891
3892 Result.assign(Macinfo);
3893 Lex.Lex();
3894 return false;
3895}
3896
3897template <>
3898bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith4730b902015-02-13 01:28:16 +00003899 DwarfVirtualityField &Result) {
3900 if (Lex.getKind() == lltok::APSInt)
3901 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3902
3903 if (Lex.getKind() != lltok::DwarfVirtuality)
3904 return TokError("expected DWARF virtuality code");
3905
3906 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
Peter Collingbourne4c97b942016-03-17 23:58:03 +00003907 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
Duncan P. N. Exon Smith4730b902015-02-13 01:28:16 +00003908 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3909 Lex.getStrVal() + "'");
3910 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3911 Result.assign(Virtuality);
3912 Lex.Lex();
3913 return false;
3914}
3915
3916template <>
Duncan P. N. Exon Smith65e12272015-02-13 01:21:25 +00003917bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3918 if (Lex.getKind() == lltok::APSInt)
3919 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3920
3921 if (Lex.getKind() != lltok::DwarfLang)
3922 return TokError("expected DWARF language");
3923
3924 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3925 if (!Lang)
3926 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3927 "'");
3928 assert(Lang <= Result.Max && "Expected valid DWARF language");
3929 Result.assign(Lang);
3930 Lex.Lex();
3931 return false;
3932}
3933
3934template <>
Reid Kleckner3d3aca22016-06-08 20:34:29 +00003935bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3936 if (Lex.getKind() == lltok::APSInt)
3937 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3938
3939 if (Lex.getKind() != lltok::DwarfCC)
3940 return TokError("expected DWARF calling convention");
3941
3942 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3943 if (!CC)
3944 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3945 "'");
3946 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
3947 Result.assign(CC);
3948 Lex.Lex();
3949 return false;
3950}
3951
3952template <>
Adrian Prantl39bb84a2016-03-31 23:56:58 +00003953bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3954 if (Lex.getKind() == lltok::APSInt)
3955 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3956
3957 if (Lex.getKind() != lltok::EmissionKind)
3958 return TokError("expected emission kind");
3959
3960 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3961 if (!Kind)
3962 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3963 "'");
3964 assert(*Kind <= Result.Max && "Expected valid emission kind");
3965 Result.assign(*Kind);
3966 Lex.Lex();
3967 return false;
3968}
Fangrui Songaf7b1832018-07-30 19:41:25 +00003969
Adrian Prantl39bb84a2016-03-31 23:56:58 +00003970template <>
Duncan P. N. Exon Smithb984c492015-02-13 01:10:38 +00003971bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
David Blaikiecf8a4a52018-08-16 21:29:55 +00003972 NameTableKindField &Result) {
3973 if (Lex.getKind() == lltok::APSInt)
3974 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3975
3976 if (Lex.getKind() != lltok::NameTableKind)
3977 return TokError("expected nameTable kind");
3978
3979 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
3980 if (!Kind)
3981 return TokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
3982 "'");
3983 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
3984 Result.assign((unsigned)*Kind);
3985 Lex.Lex();
3986 return false;
3987}
3988
3989template <>
3990bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith95d71352015-02-13 01:17:35 +00003991 DwarfAttEncodingField &Result) {
3992 if (Lex.getKind() == lltok::APSInt)
3993 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3994
3995 if (Lex.getKind() != lltok::DwarfAttEncoding)
3996 return TokError("expected DWARF type attribute encoding");
3997
3998 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3999 if (!Encoding)
4000 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
4001 Lex.getStrVal() + "'");
4002 assert(Encoding <= Result.Max && "Expected valid DWARF language");
4003 Result.assign(Encoding);
4004 Lex.Lex();
4005 return false;
4006}
4007
Duncan P. N. Exon Smith9f8d4032015-02-21 01:02:18 +00004008/// DIFlagField
4009/// ::= uint32
4010/// ::= DIFlagVector
4011/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
4012template <>
4013bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
Duncan P. N. Exon Smith9f8d4032015-02-21 01:02:18 +00004014
4015 // Parser for a single flag.
Leny Kholodovd9478f82016-09-06 10:46:28 +00004016 auto parseFlag = [&](DINode::DIFlags &Val) {
4017 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4018 uint32_t TempVal = static_cast<uint32_t>(Val);
4019 bool Res = ParseUInt32(TempVal);
4020 Val = static_cast<DINode::DIFlags>(TempVal);
4021 return Res;
4022 }
Duncan P. N. Exon Smith9f8d4032015-02-21 01:02:18 +00004023
4024 if (Lex.getKind() != lltok::DIFlag)
4025 return TokError("expected debug info flag");
4026
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004027 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith9f8d4032015-02-21 01:02:18 +00004028 if (!Val)
4029 return TokError(Twine("invalid debug info flag flag '") +
4030 Lex.getStrVal() + "'");
4031 Lex.Lex();
4032 return false;
4033 };
4034
4035 // Parse the flags and combine them together.
Leny Kholodovd9478f82016-09-06 10:46:28 +00004036 DINode::DIFlags Combined = DINode::FlagZero;
Duncan P. N. Exon Smith9f8d4032015-02-21 01:02:18 +00004037 do {
Leny Kholodovd9478f82016-09-06 10:46:28 +00004038 DINode::DIFlags Val;
Duncan P. N. Exon Smith9f8d4032015-02-21 01:02:18 +00004039 if (parseFlag(Val))
4040 return true;
4041 Combined |= Val;
4042 } while (EatIfPresent(lltok::bar));
4043
4044 Result.assign(Combined);
4045 return false;
4046}
4047
Paul Robinsonccefd882018-11-28 21:14:32 +00004048/// DISPFlagField
4049/// ::= uint32
4050/// ::= DISPFlagVector
4051/// ::= DISPFlagVector '|' DISPFlag* '|' uint32
4052template <>
4053bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
4054
4055 // Parser for a single flag.
4056 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
4057 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4058 uint32_t TempVal = static_cast<uint32_t>(Val);
4059 bool Res = ParseUInt32(TempVal);
4060 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
4061 return Res;
4062 }
4063
4064 if (Lex.getKind() != lltok::DISPFlag)
4065 return TokError("expected debug info flag");
4066
4067 Val = DISubprogram::getFlag(Lex.getStrVal());
4068 if (!Val)
4069 return TokError(Twine("invalid subprogram debug info flag '") +
4070 Lex.getStrVal() + "'");
4071 Lex.Lex();
4072 return false;
4073 };
4074
4075 // Parse the flags and combine them together.
4076 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
4077 do {
4078 DISubprogram::DISPFlags Val;
4079 if (parseFlag(Val))
4080 return true;
4081 Combined |= Val;
4082 } while (EatIfPresent(lltok::bar));
4083
4084 Result.assign(Combined);
4085 return false;
4086}
4087
Duncan P. N. Exon Smith95d71352015-02-13 01:17:35 +00004088template <>
4089bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithb984c492015-02-13 01:10:38 +00004090 MDSignedField &Result) {
4091 if (Lex.getKind() != lltok::APSInt)
4092 return TokError("expected signed integer");
4093
4094 auto &S = Lex.getAPSIntVal();
4095 if (S < Result.Min)
4096 return TokError("value for '" + Name + "' too small, limit is " +
4097 Twine(Result.Min));
4098 if (S > Result.Max)
4099 return TokError("value for '" + Name + "' too large, limit is " +
4100 Twine(Result.Max));
4101 Result.assign(S.getExtValue());
4102 assert(Result.Val >= Result.Min && "Expected value in range");
4103 assert(Result.Val <= Result.Max && "Expected value in range");
4104 Lex.Lex();
4105 return false;
4106}
4107
4108template <>
Duncan P. N. Exon Smith65e12272015-02-13 01:21:25 +00004109bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
4110 switch (Lex.getKind()) {
4111 default:
4112 return TokError("expected 'true' or 'false'");
4113 case lltok::kw_true:
4114 Result.assign(true);
4115 break;
4116 case lltok::kw_false:
4117 Result.assign(false);
4118 break;
4119 }
4120 Lex.Lex();
4121 return false;
4122}
4123
4124template <>
Duncan P. N. Exon Smith3b0fe4e2015-01-13 21:10:44 +00004125bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smithed356a92015-02-13 01:26:47 +00004126 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smith2cee1c92015-03-27 17:56:39 +00004127 if (!Result.AllowNull)
4128 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smithed356a92015-02-13 01:26:47 +00004129 Lex.Lex();
4130 Result.assign(nullptr);
4131 return false;
4132 }
4133
Duncan P. N. Exon Smith3b0fe4e2015-01-13 21:10:44 +00004134 Metadata *MD;
4135 if (ParseMetadata(MD, nullptr))
4136 return true;
4137
4138 Result.assign(MD);
4139 return false;
4140}
4141
Duncan P. N. Exon Smith89aee382015-02-04 22:05:21 +00004142template <>
Sander de Smalen959cee72018-01-24 09:56:07 +00004143bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4144 MDSignedOrMDField &Result) {
4145 // Try to parse a signed int.
4146 if (Lex.getKind() == lltok::APSInt) {
4147 MDSignedField Res = Result.A;
4148 if (!ParseMDField(Loc, Name, Res)) {
4149 Result.assign(Res);
4150 return false;
4151 }
4152 return true;
4153 }
4154
4155 // Otherwise, try to parse as an MDField.
4156 MDField Res = Result.B;
4157 if (!ParseMDField(Loc, Name, Res)) {
4158 Result.assign(Res);
4159 return false;
4160 }
4161
4162 return true;
4163}
4164
4165template <>
Momchil Velikov0c69bf42018-02-12 16:10:09 +00004166bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4167 MDSignedOrUnsignedField &Result) {
4168 if (Lex.getKind() != lltok::APSInt)
4169 return false;
4170
4171 if (Lex.getAPSIntVal().isSigned()) {
4172 MDSignedField Res = Result.A;
4173 if (ParseMDField(Loc, Name, Res))
4174 return true;
4175 Result.assign(Res);
4176 return false;
4177 }
4178
4179 MDUnsignedField Res = Result.B;
4180 if (ParseMDField(Loc, Name, Res))
4181 return true;
4182 Result.assign(Res);
4183 return false;
4184}
4185
4186template <>
Duncan P. N. Exon Smith6adbfa32015-02-03 21:54:14 +00004187bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smithc0bf4a02015-03-31 01:28:22 +00004188 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith6adbfa32015-02-03 21:54:14 +00004189 std::string S;
4190 if (ParseStringConstant(S))
4191 return true;
4192
Duncan P. N. Exon Smithc0bf4a02015-03-31 01:28:22 +00004193 if (!Result.AllowEmpty && S.empty())
4194 return Error(ValueLoc, "'" + Name + "' cannot be empty");
4195
Duncan P. N. Exon Smitha9902da2015-03-27 17:29:58 +00004196 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith6adbfa32015-02-03 21:54:14 +00004197 return false;
4198}
4199
Duncan P. N. Exon Smith89aee382015-02-04 22:05:21 +00004200template <>
Duncan P. N. Exon Smith6adbfa32015-02-03 21:54:14 +00004201bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
4202 SmallVector<Metadata *, 4> MDs;
4203 if (ParseMDNodeVector(MDs))
4204 return true;
4205
4206 Result.assign(std::move(MDs));
4207 return false;
4208}
4209
Amjad Aboud4e2e80b2016-12-25 10:12:09 +00004210template <>
4211bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4212 ChecksumKindField &Result) {
Scott Linder48632522018-02-12 19:45:54 +00004213 Optional<DIFile::ChecksumKind> CSKind =
4214 DIFile::getChecksumKind(Lex.getStrVal());
4215
4216 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
Amjad Aboud4e2e80b2016-12-25 10:12:09 +00004217 return TokError(
4218 "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
4219
Scott Linder48632522018-02-12 19:45:54 +00004220 Result.assign(*CSKind);
Amjad Aboud4e2e80b2016-12-25 10:12:09 +00004221 Lex.Lex();
4222 return false;
4223}
4224
Duncan P. N. Exon Smith8054a412015-02-04 22:13:28 +00004225} // end namespace llvm
4226
Duncan P. N. Exon Smith3b0fe4e2015-01-13 21:10:44 +00004227template <class ParserTy>
Duncan P. N. Exon Smith3a18dcb2015-01-19 23:39:32 +00004228bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith3b0fe4e2015-01-13 21:10:44 +00004229 do {
4230 if (Lex.getKind() != lltok::LabelStr)
4231 return TokError("expected field label here");
4232
4233 if (parseField())
4234 return true;
4235 } while (EatIfPresent(lltok::comma));
4236
Duncan P. N. Exon Smith3a18dcb2015-01-19 23:39:32 +00004237 return false;
4238}
4239
4240template <class ParserTy>
4241bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
4242 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4243 Lex.Lex();
4244
4245 if (ParseToken(lltok::lparen, "expected '(' here"))
4246 return true;
4247 if (Lex.getKind() != lltok::rparen)
4248 if (ParseMDFieldsImplBody(parseField))
4249 return true;
4250
Duncan P. N. Exon Smith5d2d1f22015-01-19 23:32:36 +00004251 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith3b0fe4e2015-01-13 21:10:44 +00004252 return ParseToken(lltok::rparen, "expected ')' here");
4253}
4254
Duncan P. N. Exon Smithcb96a312015-01-20 02:42:29 +00004255template <class FieldTy>
4256bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
4257 if (Result.Seen)
4258 return TokError("field '" + Name + "' cannot be specified more than once");
4259
4260 LocTy Loc = Lex.getLoc();
4261 Lex.Lex();
4262 return ParseMDField(Loc, Name, Result);
4263}
4264
Duncan P. N. Exon Smith3b0fe4e2015-01-13 21:10:44 +00004265bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
4266 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithf4293bc2015-02-10 01:08:16 +00004267
4268#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith3b0fe4e2015-01-13 21:10:44 +00004269 if (Lex.getStrVal() == #CLASS) \
4270 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithf4293bc2015-02-10 01:08:16 +00004271#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith3b0fe4e2015-01-13 21:10:44 +00004272
4273 return TokError("expected metadata type");
4274}
4275
Duncan P. N. Exon Smithaec67492015-01-19 23:44:41 +00004276#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4277#define NOP_FIELD(NAME, TYPE, INIT)
4278#define REQUIRE_FIELD(NAME, TYPE, INIT) \
4279 if (!NAME.Seen) \
4280 return Error(ClosingLoc, "missing required field '" #NAME "'");
4281#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smithcb96a312015-01-20 02:42:29 +00004282 if (Lex.getStrVal() == #NAME) \
4283 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smithaec67492015-01-19 23:44:41 +00004284#define PARSE_MD_FIELDS() \
4285 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
4286 do { \
4287 LocTy ClosingLoc; \
4288 if (ParseMDFieldsImpl([&]() -> bool { \
4289 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
4290 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
4291 }, ClosingLoc)) \
4292 return true; \
4293 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
4294 } while (false)
Duncan P. N. Exon Smith6adbfa32015-02-03 21:54:14 +00004295#define GET_OR_DISTINCT(CLASS, ARGS) \
4296 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith3b0fe4e2015-01-13 21:10:44 +00004297
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004298/// ParseDILocationFields:
Calixte Denizet44db1d12018-09-20 08:53:06 +00004299/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
4300/// isImplicitCode: true)
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004301bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithaec67492015-01-19 23:44:41 +00004302#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith783e0e42015-02-04 22:59:18 +00004303 OPTIONAL(line, LineField, ); \
4304 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smith2cee1c92015-03-27 17:56:39 +00004305 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Calixte Denizet44db1d12018-09-20 08:53:06 +00004306 OPTIONAL(inlinedAt, MDField, ); \
4307 OPTIONAL(isImplicitCode, MDBoolField, (false));
Duncan P. N. Exon Smithaec67492015-01-19 23:44:41 +00004308 PARSE_MD_FIELDS();
4309#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith3b0fe4e2015-01-13 21:10:44 +00004310
Calixte Denizet44db1d12018-09-20 08:53:06 +00004311 Result =
4312 GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,
4313 inlinedAt.Val, isImplicitCode.Val));
Duncan P. N. Exon Smith3b0fe4e2015-01-13 21:10:44 +00004314 return false;
4315}
Duncan P. N. Exon Smith6adbfa32015-02-03 21:54:14 +00004316
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004317/// ParseGenericDINode:
4318/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4319bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith6adbfa32015-02-03 21:54:14 +00004320#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith1602e582015-02-03 21:56:01 +00004321 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith6adbfa32015-02-03 21:54:14 +00004322 OPTIONAL(header, MDStringField, ); \
4323 OPTIONAL(operands, MDFieldList, );
4324 PARSE_MD_FIELDS();
4325#undef VISIT_MD_FIELDS
4326
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004327 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith6adbfa32015-02-03 21:54:14 +00004328 (Context, tag.Val, header.Val, operands.Val));
4329 return false;
4330}
Duncan P. N. Exon Smithf4293bc2015-02-10 01:08:16 +00004331
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004332/// ParseDISubrange:
4333/// ::= !DISubrange(count: 30, lowerBound: 2)
Sander de Smalen959cee72018-01-24 09:56:07 +00004334/// ::= !DISubrange(count: !node, lowerBound: 2)
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004335bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithb984c492015-02-13 01:10:38 +00004336#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Sander de Smalen959cee72018-01-24 09:56:07 +00004337 REQUIRED(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
Duncan P. N. Exon Smithb984c492015-02-13 01:10:38 +00004338 OPTIONAL(lowerBound, MDSignedField, );
4339 PARSE_MD_FIELDS();
4340#undef VISIT_MD_FIELDS
4341
Sander de Smalen959cee72018-01-24 09:56:07 +00004342 if (count.isMDSignedField())
4343 Result = GET_OR_DISTINCT(
4344 DISubrange, (Context, count.getMDSignedValue(), lowerBound.Val));
4345 else if (count.isMDField())
4346 Result = GET_OR_DISTINCT(
4347 DISubrange, (Context, count.getMDFieldValue(), lowerBound.Val));
4348 else
4349 return true;
4350
Duncan P. N. Exon Smithb984c492015-02-13 01:10:38 +00004351 return false;
Duncan P. N. Exon Smithf4293bc2015-02-10 01:08:16 +00004352}
Duncan P. N. Exon Smithb984c492015-02-13 01:10:38 +00004353
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004354/// ParseDIEnumerator:
Momchil Velikov0c69bf42018-02-12 16:10:09 +00004355/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004356bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithaa7c9432015-02-13 01:14:11 +00004357#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithb5026b02015-02-18 21:16:33 +00004358 REQUIRED(name, MDStringField, ); \
Momchil Velikov0c69bf42018-02-12 16:10:09 +00004359 REQUIRED(value, MDSignedOrUnsignedField, ); \
4360 OPTIONAL(isUnsigned, MDBoolField, (false));
Duncan P. N. Exon Smithaa7c9432015-02-13 01:14:11 +00004361 PARSE_MD_FIELDS();
4362#undef VISIT_MD_FIELDS
4363
Momchil Velikov0c69bf42018-02-12 16:10:09 +00004364 if (isUnsigned.Val && value.isMDSignedField())
4365 return TokError("unsigned enumerator with negative value");
4366
4367 int64_t Value = value.isMDSignedField()
4368 ? value.getMDSignedValue()
4369 : static_cast<int64_t>(value.getMDUnsignedValue());
4370 Result =
4371 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
4372
Duncan P. N. Exon Smithaa7c9432015-02-13 01:14:11 +00004373 return false;
Duncan P. N. Exon Smithf4293bc2015-02-10 01:08:16 +00004374}
Duncan P. N. Exon Smithaa7c9432015-02-13 01:14:11 +00004375
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004376/// ParseDIBasicType:
Adrian Prantlc4d19092018-08-14 19:35:34 +00004377/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
4378/// encoding: DW_ATE_encoding, flags: 0)
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004379bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith57b4c152015-02-13 01:14:58 +00004380#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9b18dbf2015-02-28 23:21:38 +00004381 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith57b4c152015-02-13 01:14:58 +00004382 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith8a76ab62015-02-19 23:56:07 +00004383 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk58be60c2016-10-18 14:31:22 +00004384 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Adrian Prantlc4d19092018-08-14 19:35:34 +00004385 OPTIONAL(encoding, DwarfAttEncodingField, ); \
4386 OPTIONAL(flags, DIFlagField, );
Duncan P. N. Exon Smith57b4c152015-02-13 01:14:58 +00004387 PARSE_MD_FIELDS();
4388#undef VISIT_MD_FIELDS
4389
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004390 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Adrian Prantlc4d19092018-08-14 19:35:34 +00004391 align.Val, encoding.Val, flags.Val));
Duncan P. N. Exon Smith57b4c152015-02-13 01:14:58 +00004392 return false;
Duncan P. N. Exon Smithf4293bc2015-02-10 01:08:16 +00004393}
Duncan P. N. Exon Smith57b4c152015-02-13 01:14:58 +00004394
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004395/// ParseDIDerivedType:
4396/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smithdacf0002015-02-13 01:20:38 +00004397/// line: 7, scope: !1, baseType: !2, size: 32,
Konstantin Zhuravlyov2cee5cc2017-03-08 23:55:44 +00004398/// align: 32, offset: 0, flags: 0, extraData: !3,
4399/// dwarfAddressSpace: 3)
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004400bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithdacf0002015-02-13 01:20:38 +00004401#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4402 REQUIRED(tag, DwarfTagField, ); \
4403 OPTIONAL(name, MDStringField, ); \
4404 OPTIONAL(file, MDField, ); \
4405 OPTIONAL(line, LineField, ); \
4406 OPTIONAL(scope, MDField, ); \
4407 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smith8a76ab62015-02-19 23:56:07 +00004408 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk58be60c2016-10-18 14:31:22 +00004409 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smith8a76ab62015-02-19 23:56:07 +00004410 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith9f8d4032015-02-21 01:02:18 +00004411 OPTIONAL(flags, DIFlagField, ); \
Konstantin Zhuravlyov2cee5cc2017-03-08 23:55:44 +00004412 OPTIONAL(extraData, MDField, ); \
4413 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
Duncan P. N. Exon Smithdacf0002015-02-13 01:20:38 +00004414 PARSE_MD_FIELDS();
4415#undef VISIT_MD_FIELDS
4416
Konstantin Zhuravlyov2cee5cc2017-03-08 23:55:44 +00004417 Optional<unsigned> DWARFAddressSpace;
4418 if (dwarfAddressSpace.Val != UINT32_MAX)
4419 DWARFAddressSpace = dwarfAddressSpace.Val;
4420
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004421 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smithdacf0002015-02-13 01:20:38 +00004422 (Context, tag.Val, name.Val, file.Val, line.Val,
4423 scope.Val, baseType.Val, size.Val, align.Val,
Konstantin Zhuravlyov2cee5cc2017-03-08 23:55:44 +00004424 offset.Val, DWARFAddressSpace, flags.Val,
4425 extraData.Val));
Duncan P. N. Exon Smithdacf0002015-02-13 01:20:38 +00004426 return false;
Duncan P. N. Exon Smithf4293bc2015-02-10 01:08:16 +00004427}
Duncan P. N. Exon Smithdacf0002015-02-13 01:20:38 +00004428
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004429bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithdacf0002015-02-13 01:20:38 +00004430#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4431 REQUIRED(tag, DwarfTagField, ); \
4432 OPTIONAL(name, MDStringField, ); \
4433 OPTIONAL(file, MDField, ); \
4434 OPTIONAL(line, LineField, ); \
4435 OPTIONAL(scope, MDField, ); \
4436 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smith8a76ab62015-02-19 23:56:07 +00004437 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk58be60c2016-10-18 14:31:22 +00004438 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smith8a76ab62015-02-19 23:56:07 +00004439 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith9f8d4032015-02-21 01:02:18 +00004440 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smithdacf0002015-02-13 01:20:38 +00004441 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smith65e12272015-02-13 01:21:25 +00004442 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smithdacf0002015-02-13 01:20:38 +00004443 OPTIONAL(vtableHolder, MDField, ); \
4444 OPTIONAL(templateParams, MDField, ); \
Adrian Prantl04aa6502018-02-06 23:45:59 +00004445 OPTIONAL(identifier, MDStringField, ); \
4446 OPTIONAL(discriminator, MDField, );
Duncan P. N. Exon Smithdacf0002015-02-13 01:20:38 +00004447 PARSE_MD_FIELDS();
4448#undef VISIT_MD_FIELDS
4449
Duncan P. N. Exon Smithd33fbe42016-04-19 18:00:19 +00004450 // If this has an identifier try to build an ODR type.
4451 if (identifier.Val)
4452 if (auto *CT = DICompositeType::buildODRType(
Duncan P. N. Exon Smith511eb032016-04-19 14:55:09 +00004453 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
4454 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
4455 elements.Val, runtimeLang.Val, vtableHolder.Val,
Adrian Prantl04aa6502018-02-06 23:45:59 +00004456 templateParams.Val, discriminator.Val)) {
Duncan P. N. Exon Smith511eb032016-04-19 14:55:09 +00004457 Result = CT;
4458 return false;
4459 }
Duncan P. N. Exon Smith9bb5d5d2016-04-17 03:58:21 +00004460
4461 // Create a new node, and save it in the context if it belongs in the type
4462 // map.
Duncan P. N. Exon Smithdacf0002015-02-13 01:20:38 +00004463 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004464 DICompositeType,
Duncan P. N. Exon Smithdacf0002015-02-13 01:20:38 +00004465 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
4466 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
Adrian Prantl04aa6502018-02-06 23:45:59 +00004467 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
4468 discriminator.Val));
Duncan P. N. Exon Smithdacf0002015-02-13 01:20:38 +00004469 return false;
Duncan P. N. Exon Smithf4293bc2015-02-10 01:08:16 +00004470}
Duncan P. N. Exon Smithdacf0002015-02-13 01:20:38 +00004471
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004472bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c092c02015-02-13 01:22:59 +00004473#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9f8d4032015-02-21 01:02:18 +00004474 OPTIONAL(flags, DIFlagField, ); \
Reid Kleckner3d3aca22016-06-08 20:34:29 +00004475 OPTIONAL(cc, DwarfCCField, ); \
Duncan P. N. Exon Smith1c092c02015-02-13 01:22:59 +00004476 REQUIRED(types, MDField, );
4477 PARSE_MD_FIELDS();
4478#undef VISIT_MD_FIELDS
4479
Reid Kleckner3d3aca22016-06-08 20:34:29 +00004480 Result = GET_OR_DISTINCT(DISubroutineType,
4481 (Context, flags.Val, cc.Val, types.Val));
Duncan P. N. Exon Smith1c092c02015-02-13 01:22:59 +00004482 return false;
Duncan P. N. Exon Smithf4293bc2015-02-10 01:08:16 +00004483}
Duncan P. N. Exon Smith192d9c32015-02-13 01:19:14 +00004484
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004485/// ParseDIFileType:
Scott Linder5e4b5152018-02-23 23:01:06 +00004486/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
Amjad Aboud4e2e80b2016-12-25 10:12:09 +00004487/// checksumkind: CSK_MD5,
Scott Linder5e4b5152018-02-23 23:01:06 +00004488/// checksum: "000102030405060708090a0b0c0d0e0f",
4489/// source: "source file contents")
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004490bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Scott Linder48632522018-02-12 19:45:54 +00004491 // The default constructed value for checksumkind is required, but will never
4492 // be used, as the parser checks if the field was actually Seen before using
4493 // the Val.
Duncan P. N. Exon Smith192d9c32015-02-13 01:19:14 +00004494#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4495 REQUIRED(filename, MDStringField, ); \
Amjad Aboud4e2e80b2016-12-25 10:12:09 +00004496 REQUIRED(directory, MDStringField, ); \
Scott Linder48632522018-02-12 19:45:54 +00004497 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
Scott Linder5e4b5152018-02-23 23:01:06 +00004498 OPTIONAL(checksum, MDStringField, ); \
4499 OPTIONAL(source, MDStringField, );
Duncan P. N. Exon Smith192d9c32015-02-13 01:19:14 +00004500 PARSE_MD_FIELDS();
4501#undef VISIT_MD_FIELDS
4502
Scott Linder48632522018-02-12 19:45:54 +00004503 Optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
4504 if (checksumkind.Seen && checksum.Seen)
4505 OptChecksum.emplace(checksumkind.Val, checksum.Val);
4506 else if (checksumkind.Seen || checksum.Seen)
4507 return Lex.Error("'checksumkind' and 'checksum' must be provided together");
4508
Scott Linder5e4b5152018-02-23 23:01:06 +00004509 Optional<MDString *> OptSource;
4510 if (source.Seen)
4511 OptSource = source.Val;
Amjad Aboud4e2e80b2016-12-25 10:12:09 +00004512 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
Scott Linder5e4b5152018-02-23 23:01:06 +00004513 OptChecksum, OptSource));
Duncan P. N. Exon Smith192d9c32015-02-13 01:19:14 +00004514 return false;
Duncan P. N. Exon Smithf4293bc2015-02-10 01:08:16 +00004515}
Duncan P. N. Exon Smith192d9c32015-02-13 01:19:14 +00004516
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004517/// ParseDICompileUnit:
4518/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smith37742c32015-02-13 01:25:10 +00004519/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
Adrian Prantl39bb84a2016-03-31 23:56:58 +00004520/// splitDebugFilename: "abc.debug",
Adrian Prantl4eeaa0d2016-04-15 15:57:41 +00004521/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
Amjad Aboud7db39802015-12-10 12:56:35 +00004522/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004523bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc61bc482015-08-03 17:26:41 +00004524 if (!IsDistinct)
4525 return Lex.Error("missing 'distinct', required for !DICompileUnit");
4526
Duncan P. N. Exon Smith37742c32015-02-13 01:25:10 +00004527#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4528 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smith2f5cbb52015-03-31 00:47:15 +00004529 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith37742c32015-02-13 01:25:10 +00004530 OPTIONAL(producer, MDStringField, ); \
4531 OPTIONAL(isOptimized, MDBoolField, ); \
4532 OPTIONAL(flags, MDStringField, ); \
4533 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4534 OPTIONAL(splitDebugFilename, MDStringField, ); \
Adrian Prantl39bb84a2016-03-31 23:56:58 +00004535 OPTIONAL(emissionKind, EmissionKindField, ); \
Duncan P. N. Exon Smith37742c32015-02-13 01:25:10 +00004536 OPTIONAL(enums, MDField, ); \
4537 OPTIONAL(retainedTypes, MDField, ); \
Duncan P. N. Exon Smith37742c32015-02-13 01:25:10 +00004538 OPTIONAL(globals, MDField, ); \
Adrian Prantl849c7602015-05-21 20:37:30 +00004539 OPTIONAL(imports, MDField, ); \
Amjad Aboud7db39802015-12-10 12:56:35 +00004540 OPTIONAL(macros, MDField, ); \
David Blaikiebf471b72016-08-24 18:29:49 +00004541 OPTIONAL(dwoId, MDUnsignedField, ); \
Dehao Chenfe462302017-02-01 22:45:09 +00004542 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
Peter Collingbourne76221cb2017-09-12 21:50:41 +00004543 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
David Blaikieecc582a2018-11-13 20:08:10 +00004544 OPTIONAL(nameTableKind, NameTableKindField, ); \
4545 OPTIONAL(debugBaseAddress, MDBoolField, = false);
Duncan P. N. Exon Smith37742c32015-02-13 01:25:10 +00004546 PARSE_MD_FIELDS();
4547#undef VISIT_MD_FIELDS
4548
Duncan P. N. Exon Smithc61bc482015-08-03 17:26:41 +00004549 Result = DICompileUnit::getDistinct(
4550 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4551 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
David Blaikiebf471b72016-08-24 18:29:49 +00004552 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
David Blaikieecc582a2018-11-13 20:08:10 +00004553 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
4554 debugBaseAddress.Val);
Duncan P. N. Exon Smith37742c32015-02-13 01:25:10 +00004555 return false;
Duncan P. N. Exon Smithf4293bc2015-02-10 01:08:16 +00004556}
Duncan P. N. Exon Smith37742c32015-02-13 01:25:10 +00004557
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004558/// ParseDISubprogram:
4559/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smithed356a92015-02-13 01:26:47 +00004560/// file: !1, line: 7, type: !2, isLocal: false,
4561/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith4730b902015-02-13 01:28:16 +00004562/// virtuality: DW_VIRTUALTIY_pure_virtual,
Reid Klecknerbd79db22016-07-01 02:41:21 +00004563/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
Paul Robinsonccefd882018-11-28 21:14:32 +00004564/// spFlags: 10, isOptimized: false, templateParams: !4,
4565/// declaration: !5, retainedNodes: !6, thrownTypes: !7)
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004566bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha5ae7c12015-08-28 20:26:49 +00004567 auto Loc = Lex.getLoc();
Duncan P. N. Exon Smithed356a92015-02-13 01:26:47 +00004568#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4569 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3c0d9fa22015-03-16 19:01:54 +00004570 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed356a92015-02-13 01:26:47 +00004571 OPTIONAL(linkageName, MDStringField, ); \
4572 OPTIONAL(file, MDField, ); \
4573 OPTIONAL(line, LineField, ); \
4574 OPTIONAL(type, MDField, ); \
4575 OPTIONAL(isLocal, MDBoolField, ); \
4576 OPTIONAL(isDefinition, MDBoolField, (true)); \
4577 OPTIONAL(scopeLine, LineField, ); \
4578 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith4730b902015-02-13 01:28:16 +00004579 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smithed356a92015-02-13 01:26:47 +00004580 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Reid Klecknerbd79db22016-07-01 02:41:21 +00004581 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
Duncan P. N. Exon Smith9f8d4032015-02-21 01:02:18 +00004582 OPTIONAL(flags, DIFlagField, ); \
Paul Robinsonccefd882018-11-28 21:14:32 +00004583 OPTIONAL(spFlags, DISPFlagField, ); \
Duncan P. N. Exon Smithed356a92015-02-13 01:26:47 +00004584 OPTIONAL(isOptimized, MDBoolField, ); \
Adrian Prantl4eeaa0d2016-04-15 15:57:41 +00004585 OPTIONAL(unit, MDField, ); \
Duncan P. N. Exon Smithed356a92015-02-13 01:26:47 +00004586 OPTIONAL(templateParams, MDField, ); \
4587 OPTIONAL(declaration, MDField, ); \
Paul Robinsonccefd882018-11-28 21:14:32 +00004588 OPTIONAL(retainedNodes, MDField, ); \
Adrian Prantl1bf62972017-04-26 22:56:44 +00004589 OPTIONAL(thrownTypes, MDField, );
Duncan P. N. Exon Smithed356a92015-02-13 01:26:47 +00004590 PARSE_MD_FIELDS();
4591#undef VISIT_MD_FIELDS
4592
Paul Robinsonccefd882018-11-28 21:14:32 +00004593 // An explicit spFlags field takes precedence over individual fields in
4594 // older IR versions.
4595 DISubprogram::DISPFlags SPFlags =
4596 spFlags.Seen ? spFlags.Val
4597 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
4598 isOptimized.Val, virtuality.Val);
4599 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
Duncan P. N. Exon Smitha5ae7c12015-08-28 20:26:49 +00004600 return Lex.Error(
4601 Loc,
Paul Robinsonccefd882018-11-28 21:14:32 +00004602 "missing 'distinct', required for !DISubprogram that is a Definition");
Duncan P. N. Exon Smithed356a92015-02-13 01:26:47 +00004603 Result = GET_OR_DISTINCT(
Adrian Prantl1bf62972017-04-26 22:56:44 +00004604 DISubprogram,
4605 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
Paul Robinsoneaa73532018-11-19 18:29:28 +00004606 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
4607 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
Shiva Chena8a13bc2018-05-09 02:40:45 +00004608 declaration.Val, retainedNodes.Val, thrownTypes.Val));
Duncan P. N. Exon Smithed356a92015-02-13 01:26:47 +00004609 return false;
Duncan P. N. Exon Smithf4293bc2015-02-10 01:08:16 +00004610}
Duncan P. N. Exon Smithed356a92015-02-13 01:26:47 +00004611
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004612/// ParseDILexicalBlock:
4613/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4614bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7be07e2015-02-13 01:29:28 +00004615#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithd3ec0ca2015-03-30 16:37:48 +00004616 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc7be07e2015-02-13 01:29:28 +00004617 OPTIONAL(file, MDField, ); \
4618 OPTIONAL(line, LineField, ); \
4619 OPTIONAL(column, ColumnField, );
4620 PARSE_MD_FIELDS();
4621#undef VISIT_MD_FIELDS
4622
4623 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004624 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smithc7be07e2015-02-13 01:29:28 +00004625 return false;
Duncan P. N. Exon Smithf4293bc2015-02-10 01:08:16 +00004626}
Duncan P. N. Exon Smithc7be07e2015-02-13 01:29:28 +00004627
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004628/// ParseDILexicalBlockFile:
4629/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4630bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith246f0932015-02-13 01:30:42 +00004631#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithd3ec0ca2015-03-30 16:37:48 +00004632 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith246f0932015-02-13 01:30:42 +00004633 OPTIONAL(file, MDField, ); \
4634 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4635 PARSE_MD_FIELDS();
4636#undef VISIT_MD_FIELDS
4637
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004638 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith246f0932015-02-13 01:30:42 +00004639 (Context, scope.Val, file.Val, discriminator.Val));
4640 return false;
Duncan P. N. Exon Smithf4293bc2015-02-10 01:08:16 +00004641}
Duncan P. N. Exon Smith246f0932015-02-13 01:30:42 +00004642
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004643/// ParseDINamespace:
4644/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4645bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith7bd3d1d2015-02-13 01:32:09 +00004646#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4647 REQUIRED(scope, MDField, ); \
Duncan P. N. Exon Smith7bd3d1d2015-02-13 01:32:09 +00004648 OPTIONAL(name, MDStringField, ); \
Adrian Prantl60a7c432016-11-03 19:42:02 +00004649 OPTIONAL(exportSymbols, MDBoolField, );
Duncan P. N. Exon Smith7bd3d1d2015-02-13 01:32:09 +00004650 PARSE_MD_FIELDS();
4651#undef VISIT_MD_FIELDS
4652
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004653 Result = GET_OR_DISTINCT(DINamespace,
Adrian Prantl841400b2017-04-28 22:25:46 +00004654 (Context, scope.Val, name.Val, exportSymbols.Val));
Duncan P. N. Exon Smith7bd3d1d2015-02-13 01:32:09 +00004655 return false;
Duncan P. N. Exon Smithf4293bc2015-02-10 01:08:16 +00004656}
Duncan P. N. Exon Smith7bd3d1d2015-02-13 01:32:09 +00004657
Amjad Aboud7db39802015-12-10 12:56:35 +00004658/// ParseDIMacro:
4659/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4660bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4661#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4662 REQUIRED(type, DwarfMacinfoTypeField, ); \
Adrian Prantlee92d2e2016-12-22 00:29:00 +00004663 OPTIONAL(line, LineField, ); \
Amjad Aboud7db39802015-12-10 12:56:35 +00004664 REQUIRED(name, MDStringField, ); \
4665 OPTIONAL(value, MDStringField, );
4666 PARSE_MD_FIELDS();
4667#undef VISIT_MD_FIELDS
4668
4669 Result = GET_OR_DISTINCT(DIMacro,
4670 (Context, type.Val, line.Val, name.Val, value.Val));
4671 return false;
4672}
4673
4674/// ParseDIMacroFile:
4675/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4676bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4677#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4678 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
Adrian Prantlee92d2e2016-12-22 00:29:00 +00004679 OPTIONAL(line, LineField, ); \
Amjad Aboud7db39802015-12-10 12:56:35 +00004680 REQUIRED(file, MDField, ); \
4681 OPTIONAL(nodes, MDField, );
4682 PARSE_MD_FIELDS();
4683#undef VISIT_MD_FIELDS
4684
4685 Result = GET_OR_DISTINCT(DIMacroFile,
4686 (Context, type.Val, line.Val, file.Val, nodes.Val));
4687 return false;
4688}
4689
Adrian Prantl71776472015-06-29 23:03:47 +00004690/// ParseDIModule:
4691/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4692/// includePath: "/usr/include", isysroot: "/")
4693bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4694#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4695 REQUIRED(scope, MDField, ); \
4696 REQUIRED(name, MDStringField, ); \
4697 OPTIONAL(configMacros, MDStringField, ); \
4698 OPTIONAL(includePath, MDStringField, ); \
4699 OPTIONAL(isysroot, MDStringField, );
4700 PARSE_MD_FIELDS();
4701#undef VISIT_MD_FIELDS
4702
4703 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4704 configMacros.Val, includePath.Val, isysroot.Val));
4705 return false;
4706}
4707
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004708/// ParseDITemplateTypeParameter:
4709/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4710bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith8921bbc2015-02-13 01:34:32 +00004711#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith8921bbc2015-02-13 01:34:32 +00004712 OPTIONAL(name, MDStringField, ); \
4713 REQUIRED(type, MDField, );
4714 PARSE_MD_FIELDS();
4715#undef VISIT_MD_FIELDS
4716
Duncan P. N. Exon Smitheac950e2015-02-19 00:37:21 +00004717 Result =
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004718 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith8921bbc2015-02-13 01:34:32 +00004719 return false;
Duncan P. N. Exon Smithf4293bc2015-02-10 01:08:16 +00004720}
Duncan P. N. Exon Smith8921bbc2015-02-13 01:34:32 +00004721
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004722/// ParseDITemplateValueParameter:
4723/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smitheac950e2015-02-19 00:37:21 +00004724/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004725bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith8921bbc2015-02-13 01:34:32 +00004726#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9b18dbf2015-02-28 23:21:38 +00004727 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith8921bbc2015-02-13 01:34:32 +00004728 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith9b18dbf2015-02-28 23:21:38 +00004729 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith8921bbc2015-02-13 01:34:32 +00004730 REQUIRED(value, MDField, );
4731 PARSE_MD_FIELDS();
4732#undef VISIT_MD_FIELDS
4733
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004734 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smitheac950e2015-02-19 00:37:21 +00004735 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith8921bbc2015-02-13 01:34:32 +00004736 return false;
Duncan P. N. Exon Smithf4293bc2015-02-10 01:08:16 +00004737}
Duncan P. N. Exon Smith8921bbc2015-02-13 01:34:32 +00004738
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004739/// ParseDIGlobalVariable:
4740/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithfbc547d2015-02-13 01:35:40 +00004741/// file: !1, line: 7, type: !2, isLocal: false,
Matthew Vossfff44e62018-10-03 18:44:53 +00004742/// isDefinition: true, templateParams: !3,
4743/// declaration: !4, align: 8)
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004744bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithfbc547d2015-02-13 01:35:40 +00004745#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithc0bf4a02015-03-31 01:28:22 +00004746 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithfbc547d2015-02-13 01:35:40 +00004747 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithfbc547d2015-02-13 01:35:40 +00004748 OPTIONAL(linkageName, MDStringField, ); \
4749 OPTIONAL(file, MDField, ); \
4750 OPTIONAL(line, LineField, ); \
4751 OPTIONAL(type, MDField, ); \
4752 OPTIONAL(isLocal, MDBoolField, ); \
4753 OPTIONAL(isDefinition, MDBoolField, (true)); \
Matthew Vossfff44e62018-10-03 18:44:53 +00004754 OPTIONAL(templateParams, MDField, ); \
Victor Leschuke69c4592016-10-20 00:13:12 +00004755 OPTIONAL(declaration, MDField, ); \
4756 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smithfbc547d2015-02-13 01:35:40 +00004757 PARSE_MD_FIELDS();
4758#undef VISIT_MD_FIELDS
4759
Matthew Vossfff44e62018-10-03 18:44:53 +00004760 Result =
4761 GET_OR_DISTINCT(DIGlobalVariable,
4762 (Context, scope.Val, name.Val, linkageName.Val, file.Val,
4763 line.Val, type.Val, isLocal.Val, isDefinition.Val,
4764 declaration.Val, templateParams.Val, align.Val));
Duncan P. N. Exon Smithfbc547d2015-02-13 01:35:40 +00004765 return false;
Duncan P. N. Exon Smithf4293bc2015-02-10 01:08:16 +00004766}
Duncan P. N. Exon Smithfbc547d2015-02-13 01:35:40 +00004767
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004768/// ParseDILocalVariable:
Duncan P. N. Exon Smithbf2040f2015-07-31 18:58:39 +00004769/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
Victor Leschuke69c4592016-10-20 00:13:12 +00004770/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4771/// align: 8)
Duncan P. N. Exon Smithbf2040f2015-07-31 18:58:39 +00004772/// ::= !DILocalVariable(scope: !0, name: "foo",
Victor Leschuke69c4592016-10-20 00:13:12 +00004773/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4774/// align: 8)
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004775bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha342d822015-02-13 01:39:44 +00004776#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2cee1c92015-03-27 17:56:39 +00004777 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha342d822015-02-13 01:39:44 +00004778 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithbf2040f2015-07-31 18:58:39 +00004779 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smitha342d822015-02-13 01:39:44 +00004780 OPTIONAL(file, MDField, ); \
4781 OPTIONAL(line, LineField, ); \
4782 OPTIONAL(type, MDField, ); \
Victor Leschuke69c4592016-10-20 00:13:12 +00004783 OPTIONAL(flags, DIFlagField, ); \
4784 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smitha342d822015-02-13 01:39:44 +00004785 PARSE_MD_FIELDS();
4786#undef VISIT_MD_FIELDS
4787
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004788 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithbf2040f2015-07-31 18:58:39 +00004789 (Context, scope.Val, name.Val, file.Val, line.Val,
Victor Leschuke69c4592016-10-20 00:13:12 +00004790 type.Val, arg.Val, flags.Val, align.Val));
Duncan P. N. Exon Smitha342d822015-02-13 01:39:44 +00004791 return false;
Duncan P. N. Exon Smithf4293bc2015-02-10 01:08:16 +00004792}
Duncan P. N. Exon Smitha342d822015-02-13 01:39:44 +00004793
Shiva Chena8a13bc2018-05-09 02:40:45 +00004794/// ParseDILabel:
4795/// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
4796bool LLParser::ParseDILabel(MDNode *&Result, bool IsDistinct) {
4797#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4798 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4799 REQUIRED(name, MDStringField, ); \
4800 REQUIRED(file, MDField, ); \
4801 REQUIRED(line, LineField, );
4802 PARSE_MD_FIELDS();
4803#undef VISIT_MD_FIELDS
4804
4805 Result = GET_OR_DISTINCT(DILabel,
4806 (Context, scope.Val, name.Val, file.Val, line.Val));
4807 return false;
4808}
4809
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004810/// ParseDIExpression:
4811/// ::= !DIExpression(0, 7, -1)
4812bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha034e072015-02-13 01:42:09 +00004813 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4814 Lex.Lex();
4815
4816 if (ParseToken(lltok::lparen, "expected '(' here"))
4817 return true;
4818
4819 SmallVector<uint64_t, 8> Elements;
4820 if (Lex.getKind() != lltok::rparen)
4821 do {
4822 if (Lex.getKind() == lltok::DwarfOp) {
4823 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4824 Lex.Lex();
4825 Elements.push_back(Op);
4826 continue;
4827 }
4828 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4829 }
4830
4831 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4832 return TokError("expected unsigned integer");
4833
4834 auto &U = Lex.getAPSIntVal();
4835 if (U.ugt(UINT64_MAX))
4836 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4837 Elements.push_back(U.getZExtValue());
4838 Lex.Lex();
4839 } while (EatIfPresent(lltok::comma));
4840
4841 if (ParseToken(lltok::rparen, "expected ')' here"))
4842 return true;
4843
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004844 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smitha034e072015-02-13 01:42:09 +00004845 return false;
Duncan P. N. Exon Smithf4293bc2015-02-10 01:08:16 +00004846}
Duncan P. N. Exon Smitha034e072015-02-13 01:42:09 +00004847
Adrian Prantl7b500b42016-12-20 02:09:43 +00004848/// ParseDIGlobalVariableExpression:
4849/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4850bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
4851 bool IsDistinct) {
4852#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4853 REQUIRED(var, MDField, ); \
Adrian Prantl69e607f2017-08-30 18:06:51 +00004854 REQUIRED(expr, MDField, );
Adrian Prantl7b500b42016-12-20 02:09:43 +00004855 PARSE_MD_FIELDS();
4856#undef VISIT_MD_FIELDS
4857
4858 Result =
4859 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
4860 return false;
4861}
4862
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004863/// ParseDIObjCProperty:
4864/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smith3bfa8d02015-02-13 01:43:22 +00004865/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004866bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith3bfa8d02015-02-13 01:43:22 +00004867#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3c0d9fa22015-03-16 19:01:54 +00004868 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith3bfa8d02015-02-13 01:43:22 +00004869 OPTIONAL(file, MDField, ); \
4870 OPTIONAL(line, LineField, ); \
4871 OPTIONAL(setter, MDStringField, ); \
4872 OPTIONAL(getter, MDStringField, ); \
4873 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4874 OPTIONAL(type, MDField, );
4875 PARSE_MD_FIELDS();
4876#undef VISIT_MD_FIELDS
4877
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004878 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smith3bfa8d02015-02-13 01:43:22 +00004879 (Context, name.Val, file.Val, line.Val, setter.Val,
4880 getter.Val, attributes.Val, type.Val));
4881 return false;
Duncan P. N. Exon Smithf4293bc2015-02-10 01:08:16 +00004882}
Duncan P. N. Exon Smith3bfa8d02015-02-13 01:43:22 +00004883
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004884/// ParseDIImportedEntity:
4885/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith6a390dc2015-02-13 01:46:02 +00004886/// line: 7, name: "foo")
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004887bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith6a390dc2015-02-13 01:46:02 +00004888#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4889 REQUIRED(tag, DwarfTagField, ); \
4890 REQUIRED(scope, MDField, ); \
4891 OPTIONAL(entity, MDField, ); \
Adrian Prantl9563b5a2017-07-19 00:09:54 +00004892 OPTIONAL(file, MDField, ); \
Duncan P. N. Exon Smith6a390dc2015-02-13 01:46:02 +00004893 OPTIONAL(line, LineField, ); \
4894 OPTIONAL(name, MDStringField, );
4895 PARSE_MD_FIELDS();
4896#undef VISIT_MD_FIELDS
4897
Adrian Prantl9563b5a2017-07-19 00:09:54 +00004898 Result = GET_OR_DISTINCT(
4899 DIImportedEntity,
4900 (Context, tag.Val, scope.Val, entity.Val, file.Val, line.Val, name.Val));
Duncan P. N. Exon Smith6a390dc2015-02-13 01:46:02 +00004901 return false;
Duncan P. N. Exon Smithf4293bc2015-02-10 01:08:16 +00004902}
Duncan P. N. Exon Smith6a390dc2015-02-13 01:46:02 +00004903
Duncan P. N. Exon Smith3b0fe4e2015-01-13 21:10:44 +00004904#undef PARSE_MD_FIELD
Duncan P. N. Exon Smithaec67492015-01-19 23:44:41 +00004905#undef NOP_FIELD
4906#undef REQUIRE_FIELD
4907#undef DECLARE_FIELD
Duncan P. N. Exon Smith3b0fe4e2015-01-13 21:10:44 +00004908
Duncan P. N. Exon Smith1ef70ff2014-12-15 19:07:53 +00004909/// ParseMetadataAsValue
4910/// ::= metadata i32 %local
4911/// ::= metadata i32 @global
4912/// ::= metadata i32 7
4913/// ::= metadata !0
4914/// ::= metadata !{...}
4915/// ::= metadata !"string"
4916bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4917 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +00004918 Metadata *MD;
Duncan P. N. Exon Smith1ef70ff2014-12-15 19:07:53 +00004919 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +00004920 return true;
4921
Duncan P. N. Exon Smith1ef70ff2014-12-15 19:07:53 +00004922 V = MetadataAsValue::get(Context, MD);
4923 return false;
4924}
4925
4926/// ParseValueAsMetadata
4927/// ::= i32 %local
4928/// ::= i32 @global
4929/// ::= i32 7
Duncan P. N. Exon Smithed356a92015-02-13 01:26:47 +00004930bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4931 PerFunctionState *PFS) {
Duncan P. N. Exon Smith1ef70ff2014-12-15 19:07:53 +00004932 Type *Ty;
4933 LocTy Loc;
Duncan P. N. Exon Smithed356a92015-02-13 01:26:47 +00004934 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smith1ef70ff2014-12-15 19:07:53 +00004935 return true;
4936 if (Ty->isMetadataTy())
4937 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4938
4939 Value *V;
4940 if (ParseValue(Ty, V, PFS))
4941 return true;
4942
4943 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +00004944 return false;
4945}
4946
4947/// ParseMetadata
Duncan P. N. Exon Smith1ef70ff2014-12-15 19:07:53 +00004948/// ::= i32 %local
4949/// ::= i32 @global
4950/// ::= i32 7
Dan Gohman83448032010-07-14 18:26:50 +00004951/// ::= !42
4952/// ::= !{...}
4953/// ::= !"string"
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00004954/// ::= !DILocation(...)
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +00004955bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith3b0fe4e2015-01-13 21:10:44 +00004956 if (Lex.getKind() == lltok::MetadataVar) {
4957 MDNode *N;
4958 if (ParseSpecializedMDNode(N))
4959 return true;
4960 MD = N;
4961 return false;
4962 }
4963
Duncan P. N. Exon Smith1ef70ff2014-12-15 19:07:53 +00004964 // ValueAsMetadata:
4965 // <type> <value>
4966 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smithed356a92015-02-13 01:26:47 +00004967 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smith1ef70ff2014-12-15 19:07:53 +00004968
4969 // '!'.
4970 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4971 Lex.Lex();
Dan Gohman83448032010-07-14 18:26:50 +00004972
Duncan P. N. Exon Smith9e947912015-01-12 22:24:50 +00004973 // MDString:
4974 // ::= '!' STRINGCONSTANT
4975 if (Lex.getKind() == lltok::StringConstant) {
4976 MDString *S;
4977 if (ParseMDString(S))
4978 return true;
4979 MD = S;
4980 return false;
4981 }
4982
Dan Gohman83448032010-07-14 18:26:50 +00004983 // MDNode:
4984 // !{ ... }
Duncan P. N. Exon Smithe390a8e2015-01-12 22:26:48 +00004985 // !7
Duncan P. N. Exon Smith9e947912015-01-12 22:24:50 +00004986 MDNode *N;
Duncan P. N. Exon Smithe390a8e2015-01-12 22:26:48 +00004987 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +00004988 return true;
Duncan P. N. Exon Smith9e947912015-01-12 22:24:50 +00004989 MD = N;
Dan Gohman83448032010-07-14 18:26:50 +00004990 return false;
4991}
4992
Victor Hernandez92f238d2010-01-11 22:31:58 +00004993//===----------------------------------------------------------------------===//
4994// Function Parsing.
4995//===----------------------------------------------------------------------===//
4996
Chris Lattnerdb125cf2011-07-18 04:54:35 +00004997bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Alexander Richardsonb0b98842018-02-27 11:15:11 +00004998 PerFunctionState *PFS, bool IsCall) {
Duncan Sands1df98592010-02-16 11:11:14 +00004999 if (Ty->isFunctionTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00005000 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00005001
Chris Lattnerdf986172009-01-02 07:01:27 +00005002 switch (ID.Kind) {
Chris Lattnerdf986172009-01-02 07:01:27 +00005003 case ValID::t_LocalID:
Victor Hernandez92f238d2010-01-11 22:31:58 +00005004 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
Alexander Richardsonb0b98842018-02-27 11:15:11 +00005005 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc, IsCall);
Craig Topper0b6cb712014-04-15 06:32:26 +00005006 return V == nullptr;
Chris Lattnerdf986172009-01-02 07:01:27 +00005007 case ValID::t_LocalName:
Victor Hernandez92f238d2010-01-11 22:31:58 +00005008 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
Alexander Richardsonb0b98842018-02-27 11:15:11 +00005009 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc, IsCall);
Craig Topper0b6cb712014-04-15 06:32:26 +00005010 return V == nullptr;
Victor Hernandez92f238d2010-01-11 22:31:58 +00005011 case ValID::t_InlineAsm: {
Karl Schimpfe2dfa012015-09-03 16:18:32 +00005012 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez92f238d2010-01-11 22:31:58 +00005013 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie4f7a4bc2015-07-27 23:32:19 +00005014 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
5015 (ID.UIntVal >> 1) & 1,
5016 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez92f238d2010-01-11 22:31:58 +00005017 return false;
5018 }
Chris Lattnerdf986172009-01-02 07:01:27 +00005019 case ValID::t_GlobalName:
Alexander Richardson47ff67b2018-08-23 09:25:17 +00005020 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc, IsCall);
Craig Topper0b6cb712014-04-15 06:32:26 +00005021 return V == nullptr;
Chris Lattnerdf986172009-01-02 07:01:27 +00005022 case ValID::t_GlobalID:
Alexander Richardson47ff67b2018-08-23 09:25:17 +00005023 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc, IsCall);
Craig Topper0b6cb712014-04-15 06:32:26 +00005024 return V == nullptr;
Chris Lattnerdf986172009-01-02 07:01:27 +00005025 case ValID::t_APSInt:
Duncan Sands1df98592010-02-16 11:11:14 +00005026 if (!Ty->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00005027 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad40f8f622010-12-07 08:25:19 +00005028 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00005029 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00005030 return false;
5031 case ValID::t_APFloat:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00005032 if (!Ty->isFloatingPointTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00005033 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
5034 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00005035
Dan Gohmance163392011-12-17 00:04:22 +00005036 // The lexer has no type info, so builds all half, float, and double FP
5037 // constants as double. Fix this here. Long double does not need this.
Stephan Bergmann20a600c2016-12-14 11:57:17 +00005038 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00005039 bool Ignored;
Dan Gohmance163392011-12-17 00:04:22 +00005040 if (Ty->isHalfTy())
Stephan Bergmann20a600c2016-12-14 11:57:17 +00005041 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
Dan Gohmance163392011-12-17 00:04:22 +00005042 &Ignored);
5043 else if (Ty->isFloatTy())
Stephan Bergmann20a600c2016-12-14 11:57:17 +00005044 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Dan Gohmance163392011-12-17 00:04:22 +00005045 &Ignored);
Chris Lattnerdf986172009-01-02 07:01:27 +00005046 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00005047 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00005048
Chris Lattner959873d2009-01-05 18:24:23 +00005049 if (V->getType() != Ty)
5050 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00005051 getTypeString(Ty) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00005052
Chris Lattnerdf986172009-01-02 07:01:27 +00005053 return false;
5054 case ValID::t_Null:
Duncan Sands1df98592010-02-16 11:11:14 +00005055 if (!Ty->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00005056 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00005057 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00005058 return false;
5059 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00005060 // FIXME: LabelTy should not be a first-class type.
Chris Lattner1afcace2011-07-09 17:41:24 +00005061 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnere67c1aa2009-01-05 08:13:38 +00005062 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00005063 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00005064 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00005065 case ValID::t_EmptyArray:
Duncan Sands1df98592010-02-16 11:11:14 +00005066 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner081b5052009-01-05 07:52:51 +00005067 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00005068 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00005069 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00005070 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00005071 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00005072 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00005073 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00005074 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00005075 return false;
David Majnemer83fc12a2015-11-11 21:57:16 +00005076 case ValID::t_None:
5077 if (!Ty->isTokenTy())
5078 return Error(ID.Loc, "invalid type for none constant");
5079 V = Constant::getNullValue(Ty);
5080 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00005081 case ValID::t_Constant:
Chris Lattner61c70e92010-08-28 04:09:24 +00005082 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerdf986172009-01-02 07:01:27 +00005083 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattnerfdfeb692010-02-12 20:49:41 +00005084
Chris Lattnerdf986172009-01-02 07:01:27 +00005085 V = ID.ConstantVal;
5086 return false;
Chris Lattner1afcace2011-07-09 17:41:24 +00005087 case ValID::t_ConstantStruct:
5088 case ValID::t_PackedConstantStruct:
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005089 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattner1afcace2011-07-09 17:41:24 +00005090 if (ST->getNumElements() != ID.UIntVal)
5091 return Error(ID.Loc,
5092 "initializer with struct type has wrong # elements");
5093 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
5094 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman407a6162012-11-15 22:34:00 +00005095
Chris Lattner1afcace2011-07-09 17:41:24 +00005096 // Verify that the elements are compatible with the structtype.
5097 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
5098 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
5099 return Error(ID.Loc, "element " + Twine(i) +
5100 " of struct initializer doesn't match struct element type");
Michael Ilseman407a6162012-11-15 22:34:00 +00005101
David Blaikieafb53792015-08-03 20:08:41 +00005102 V = ConstantStruct::get(
5103 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
Chris Lattner1afcace2011-07-09 17:41:24 +00005104 } else
5105 return Error(ID.Loc, "constant expression type mismatch");
5106 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00005107 }
Chandler Carruth732f05c2012-01-10 18:08:01 +00005108 llvm_unreachable("Invalid ValID");
Chris Lattnerdf986172009-01-02 07:01:27 +00005109}
Daniel Dunbara279bc32009-09-20 02:20:51 +00005110
Alex Lorenz4b50ecb2015-07-17 22:07:03 +00005111bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
5112 C = nullptr;
5113 ValID ID;
5114 auto Loc = Lex.getLoc();
5115 if (ParseValID(ID, /*PFS=*/nullptr))
5116 return true;
5117 switch (ID.Kind) {
5118 case ValID::t_APSInt:
5119 case ValID::t_APFloat:
Alex Lorenzb9224cd2015-09-09 13:44:33 +00005120 case ValID::t_Undef:
Alex Lorenz4b50ecb2015-07-17 22:07:03 +00005121 case ValID::t_Constant:
5122 case ValID::t_ConstantStruct:
5123 case ValID::t_PackedConstantStruct: {
5124 Value *V;
Alexander Richardsonb0b98842018-02-27 11:15:11 +00005125 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr, /*IsCall=*/false))
Alex Lorenz4b50ecb2015-07-17 22:07:03 +00005126 return true;
5127 assert(isa<Constant>(V) && "Expected a constant value");
5128 C = cast<Constant>(V);
5129 return false;
5130 }
Eric Christopher95604f92017-03-30 22:34:20 +00005131 case ValID::t_Null:
5132 C = Constant::getNullValue(Ty);
5133 return false;
Alex Lorenz4b50ecb2015-07-17 22:07:03 +00005134 default:
5135 return Error(Loc, "expected a constant value");
5136 }
5137}
5138
David Majnemer8cec2f22015-12-12 05:38:55 +00005139bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper0b6cb712014-04-15 06:32:26 +00005140 V = nullptr;
Chris Lattnerdf986172009-01-02 07:01:27 +00005141 ValID ID;
Alexander Richardsonb0b98842018-02-27 11:15:11 +00005142 return ParseValID(ID, PFS) ||
5143 ConvertValIDToValue(Ty, ID, V, PFS, /*IsCall=*/false);
Chris Lattnerdf986172009-01-02 07:01:27 +00005144}
5145
Chris Lattner1afcace2011-07-09 17:41:24 +00005146bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper0b6cb712014-04-15 06:32:26 +00005147 Type *Ty = nullptr;
Chris Lattner1afcace2011-07-09 17:41:24 +00005148 return ParseType(Ty) ||
5149 ParseValue(Ty, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00005150}
5151
Chris Lattnerf9be95f2009-10-27 19:13:16 +00005152bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
5153 PerFunctionState &PFS) {
5154 Value *V;
5155 Loc = Lex.getLoc();
5156 if (ParseTypeAndValue(V, PFS)) return true;
5157 if (!isa<BasicBlock>(V))
5158 return Error(Loc, "expected a basic block");
5159 BB = cast<BasicBlock>(V);
5160 return false;
5161}
5162
Chris Lattnerdf986172009-01-02 07:01:27 +00005163/// FunctionHeader
Sean Fertile509132b2017-10-26 15:00:26 +00005164/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
5165/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
Alexander Richardson47ff67b2018-08-23 09:25:17 +00005166/// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
5167/// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerdf986172009-01-02 07:01:27 +00005168bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
5169 // Parse the linkage.
5170 LocTy LinkageLoc = Lex.getLoc();
5171 unsigned Linkage;
Kostya Serebryany164b86b2012-01-20 17:56:17 +00005172 unsigned Visibility;
Nico Rieck38f68c52014-01-14 15:22:47 +00005173 unsigned DLLStorageClass;
Sean Fertile509132b2017-10-26 15:00:26 +00005174 bool DSOLocal;
Bill Wendling702cc912012-10-15 20:35:56 +00005175 AttrBuilder RetAttrs;
Alexey Samsonov5e4558e2014-09-10 18:00:17 +00005176 unsigned CC;
Rafael Espindola26020e62016-05-12 12:37:52 +00005177 bool HasLinkage;
Craig Topper0b6cb712014-04-15 06:32:26 +00005178 Type *RetType = nullptr;
Chris Lattnerdf986172009-01-02 07:01:27 +00005179 LocTy RetTypeLoc = Lex.getLoc();
Sean Fertile509132b2017-10-26 15:00:26 +00005180 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
5181 DSOLocal) ||
Rafael Espindola26020e62016-05-12 12:37:52 +00005182 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00005183 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00005184 return true;
5185
5186 // Verify that the linkage is ok.
5187 switch ((GlobalValue::LinkageTypes)Linkage) {
5188 case GlobalValue::ExternalLinkage:
5189 break; // always ok.
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00005190 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00005191 if (isDefine)
5192 return Error(LinkageLoc, "invalid linkage for function definition");
5193 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00005194 case GlobalValue::PrivateLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00005195 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00005196 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00005197 case GlobalValue::LinkOnceAnyLinkage:
5198 case GlobalValue::LinkOnceODRLinkage:
5199 case GlobalValue::WeakAnyLinkage:
5200 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00005201 if (!isDefine)
5202 return Error(LinkageLoc, "invalid linkage for function declaration");
5203 break;
5204 case GlobalValue::AppendingLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00005205 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00005206 return Error(LinkageLoc, "invalid function linkage type");
5207 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00005208
Duncan P. N. Exon Smith76c17d32014-05-07 22:57:20 +00005209 if (!isValidVisibilityForLinkage(Visibility, Linkage))
5210 return Error(LinkageLoc,
5211 "symbol with local linkage must have default visibility");
5212
Chris Lattner1afcace2011-07-09 17:41:24 +00005213 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00005214 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00005215
Chris Lattnerdf986172009-01-02 07:01:27 +00005216 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00005217
5218 std::string FunctionName;
5219 if (Lex.getKind() == lltok::GlobalVar) {
5220 FunctionName = Lex.getStrVal();
5221 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
5222 unsigned NameID = Lex.getUIntVal();
5223
5224 if (NameID != NumberedVals.size())
5225 return TokError("function expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00005226 Twine(NumberedVals.size()) + "'");
Chris Lattnerf570e622009-02-18 21:48:13 +00005227 } else {
5228 return TokError("expected function name");
5229 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00005230
Chris Lattner3ed88ef2009-01-02 08:05:26 +00005231 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00005232
Chris Lattner3ed88ef2009-01-02 08:05:26 +00005233 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00005234 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00005235
Chris Lattner1afcace2011-07-09 17:41:24 +00005236 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerdf986172009-01-02 07:01:27 +00005237 bool isVarArg;
Bill Wendling702cc912012-10-15 20:35:56 +00005238 AttrBuilder FuncAttrs;
Bill Wendlingbaad55c2013-02-08 06:32:06 +00005239 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman2253a2f2013-06-27 00:25:01 +00005240 LocTy BuiltinLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00005241 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00005242 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00005243 std::string GC;
Peter Collingbourne63b34cd2016-06-14 21:01:22 +00005244 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
Alexander Richardson47ff67b2018-08-23 09:25:17 +00005245 unsigned AddrSpace = 0;
Craig Topper0b6cb712014-04-15 06:32:26 +00005246 Constant *Prefix = nullptr;
Peter Collingbournebb660fc2014-12-03 02:08:38 +00005247 Constant *Prologue = nullptr;
David Majnemercc714e22015-06-17 20:52:32 +00005248 Constant *PersonalityFn = nullptr;
David Majnemerc8a11692014-06-27 18:19:56 +00005249 Comdat *C;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00005250
Chris Lattner1afcace2011-07-09 17:41:24 +00005251 if (ParseArgumentList(ArgList, isVarArg) ||
Peter Collingbourne63b34cd2016-06-14 21:01:22 +00005252 ParseOptionalUnnamedAddr(UnnamedAddr) ||
Alexander Richardson47ff67b2018-08-23 09:25:17 +00005253 ParseOptionalProgramAddrSpace(AddrSpace) ||
Bill Wendling143d4642013-02-22 00:12:35 +00005254 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman2253a2f2013-06-27 00:25:01 +00005255 BuiltinLoc) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00005256 (EatIfPresent(lltok::kw_section) &&
5257 ParseStringConstant(Section)) ||
Rafael Espindolaf907a262015-01-06 22:55:16 +00005258 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00005259 ParseOptionalAlignment(Alignment) ||
5260 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne1e3037f2013-09-16 01:08:15 +00005261 ParseStringConstant(GC)) ||
5262 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbournebb660fc2014-12-03 02:08:38 +00005263 ParseGlobalTypeAndValue(Prefix)) ||
5264 (EatIfPresent(lltok::kw_prologue) &&
David Majnemercc714e22015-06-17 20:52:32 +00005265 ParseGlobalTypeAndValue(Prologue)) ||
5266 (EatIfPresent(lltok::kw_personality) &&
5267 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00005268 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00005269
Michael Gottesman2253a2f2013-06-27 00:25:01 +00005270 if (FuncAttrs.contains(Attribute::Builtin))
5271 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling143d4642013-02-22 00:12:35 +00005272
Chris Lattnerdf986172009-01-02 07:01:27 +00005273 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingf385f4c2012-10-08 23:27:46 +00005274 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendlingef99fe82012-09-21 15:26:31 +00005275 Alignment = FuncAttrs.getAlignment();
Bill Wendling034b94b2012-12-19 07:18:57 +00005276 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +00005277 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00005278
Chris Lattnerdf986172009-01-02 07:01:27 +00005279 // Okay, if we got here, the function is syntactically valid. Convert types
5280 // and do semantic checks.
Jay Foad5fdd6c82011-07-12 14:06:48 +00005281 std::vector<Type*> ParamTypeList;
Reid Kleckner06090402017-04-12 00:38:00 +00005282 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00005283
Chris Lattnerdf986172009-01-02 07:01:27 +00005284 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattner1afcace2011-07-09 17:41:24 +00005285 ParamTypeList.push_back(ArgList[i].Ty);
Reid Kleckner7dde8e82017-04-10 23:31:05 +00005286 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerdf986172009-01-02 07:01:27 +00005287 }
5288
Reid Klecknere9a46bf2017-04-13 00:58:09 +00005289 AttributeList PAL =
5290 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
5291 AttributeSet::get(Context, RetAttrs), Attrs);
Daniel Dunbara279bc32009-09-20 02:20:51 +00005292
Bill Wendling94e94b32012-12-30 13:50:49 +00005293 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbara279bc32009-09-20 02:20:51 +00005294 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
5295
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005296 FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00005297 FunctionType::get(RetType, ParamTypeList, isVarArg);
Alexander Richardson47ff67b2018-08-23 09:25:17 +00005298 PointerType *PFT = PointerType::get(FT, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +00005299
Craig Topper0b6cb712014-04-15 06:32:26 +00005300 Fn = nullptr;
Chris Lattnerdf986172009-01-02 07:01:27 +00005301 if (!FunctionName.empty()) {
5302 // If this was a definition of a forward reference, remove the definition
5303 // from the forward reference table and fill in the forward ref.
David Blaikie6030b442015-09-21 21:07:50 +00005304 auto FRVI = ForwardRefVals.find(FunctionName);
Chris Lattnerdf986172009-01-02 07:01:27 +00005305 if (FRVI != ForwardRefVals.end()) {
5306 Fn = M->getFunction(FunctionName);
Nick Lewycky64ea2752012-10-11 00:38:25 +00005307 if (!Fn)
5308 return Error(FRVI->second.second, "invalid forward reference to "
5309 "function as global value!");
Chris Lattnerf1cfb952010-04-20 04:49:11 +00005310 if (Fn->getType() != PFT)
5311 return Error(FRVI->second.second, "invalid forward reference to "
Alexander Richardson47ff67b2018-08-23 09:25:17 +00005312 "function '" + FunctionName + "' with wrong type: "
5313 "expected '" + getTypeString(PFT) + "' but was '" +
5314 getTypeString(Fn->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00005315 ForwardRefVals.erase(FRVI);
5316 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattnerd5890992011-06-17 07:06:44 +00005317 // Reject redefinitions.
5318 return Error(NameLoc, "invalid redefinition of function '" +
5319 FunctionName + "'");
Chris Lattner1d871c52009-10-25 23:22:50 +00005320 } else if (M->getNamedValue(FunctionName)) {
5321 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00005322 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00005323
Dan Gohman41905542009-08-29 23:37:49 +00005324 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00005325 // If this is a definition of a forward referenced function, make sure the
5326 // types agree.
David Blaikie6030b442015-09-21 21:07:50 +00005327 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00005328 if (I != ForwardRefValIDs.end()) {
5329 Fn = cast<Function>(I->second.first);
5330 if (Fn->getType() != PFT)
5331 return Error(NameLoc, "type of definition and forward reference of '@" +
Alexander Richardson47ff67b2018-08-23 09:25:17 +00005332 Twine(NumberedVals.size()) + "' disagree: "
5333 "expected '" + getTypeString(PFT) + "' but was '" +
5334 getTypeString(Fn->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00005335 ForwardRefValIDs.erase(I);
5336 }
5337 }
5338
Craig Topper0b6cb712014-04-15 06:32:26 +00005339 if (!Fn)
Alexander Richardson47ff67b2018-08-23 09:25:17 +00005340 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace,
5341 FunctionName, M);
Chris Lattnerdf986172009-01-02 07:01:27 +00005342 else // Move the forward-reference to the correct spot in the module.
5343 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
5344
Alexander Richardson47ff67b2018-08-23 09:25:17 +00005345 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
5346
Chris Lattnerdf986172009-01-02 07:01:27 +00005347 if (FunctionName.empty())
5348 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00005349
Chris Lattnerdf986172009-01-02 07:01:27 +00005350 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
Rafael Espindola1e1801c2018-01-11 22:15:05 +00005351 maybeSetDSOLocal(DSOLocal, *Fn);
Chris Lattnerdf986172009-01-02 07:01:27 +00005352 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck38f68c52014-01-14 15:22:47 +00005353 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerdf986172009-01-02 07:01:27 +00005354 Fn->setCallingConv(CC);
5355 Fn->setAttributes(PAL);
Rafael Espindolabea46262011-01-08 16:42:36 +00005356 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerdf986172009-01-02 07:01:27 +00005357 Fn->setAlignment(Alignment);
5358 Fn->setSection(Section);
David Majnemerc8a11692014-06-27 18:19:56 +00005359 Fn->setComdat(C);
David Majnemercc714e22015-06-17 20:52:32 +00005360 Fn->setPersonalityFn(PersonalityFn);
Benjamin Kramerac307e42016-05-29 10:46:35 +00005361 if (!GC.empty()) Fn->setGC(GC);
Peter Collingbourne1e3037f2013-09-16 01:08:15 +00005362 Fn->setPrefixData(Prefix);
Peter Collingbournebb660fc2014-12-03 02:08:38 +00005363 Fn->setPrologueData(Prologue);
Bill Wendlingbaad55c2013-02-08 06:32:06 +00005364 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbara279bc32009-09-20 02:20:51 +00005365
Chris Lattnerdf986172009-01-02 07:01:27 +00005366 // Add all of the arguments we parsed to the function.
5367 Function::arg_iterator ArgIt = Fn->arg_begin();
5368 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
5369 // If the argument has a name, insert it into the argument symbol table.
5370 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00005371
Chris Lattnerdf986172009-01-02 07:01:27 +00005372 // Set the name, if it conflicted, it will be auto-renamed.
5373 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00005374
Benjamin Krameraf812352010-10-16 11:28:23 +00005375 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerdf986172009-01-02 07:01:27 +00005376 return Error(ArgList[i].Loc, "redefinition of argument '%" +
5377 ArgList[i].Name + "'");
5378 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00005379
Duncan P. N. Exon Smith16589782014-08-19 00:13:19 +00005380 if (isDefine)
5381 return false;
5382
Robin Morisset217b38e2014-08-29 21:53:01 +00005383 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith16589782014-08-19 00:13:19 +00005384 ValID ID;
5385 if (FunctionName.empty()) {
5386 ID.Kind = ValID::t_GlobalID;
5387 ID.UIntVal = NumberedVals.size() - 1;
5388 } else {
5389 ID.Kind = ValID::t_GlobalName;
5390 ID.StrVal = FunctionName;
5391 }
5392 auto Blocks = ForwardRefBlockAddresses.find(ID);
5393 if (Blocks != ForwardRefBlockAddresses.end())
5394 return Error(Blocks->first.Loc,
5395 "cannot take blockaddress inside a declaration");
Chris Lattnerdf986172009-01-02 07:01:27 +00005396 return false;
5397}
5398
Duncan P. N. Exon Smith16589782014-08-19 00:13:19 +00005399bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
5400 ValID ID;
5401 if (FunctionNumber == -1) {
5402 ID.Kind = ValID::t_GlobalName;
5403 ID.StrVal = F.getName();
5404 } else {
5405 ID.Kind = ValID::t_GlobalID;
5406 ID.UIntVal = FunctionNumber;
5407 }
5408
5409 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
5410 if (Blocks == P.ForwardRefBlockAddresses.end())
5411 return false;
5412
5413 for (const auto &I : Blocks->second) {
5414 const ValID &BBID = I.first;
5415 GlobalValue *GV = I.second;
5416
5417 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
5418 "Expected local id or name");
5419 BasicBlock *BB;
5420 if (BBID.Kind == ValID::t_LocalName)
5421 BB = GetBB(BBID.StrVal, BBID.Loc);
5422 else
5423 BB = GetBB(BBID.UIntVal, BBID.Loc);
5424 if (!BB)
5425 return P.Error(BBID.Loc, "referenced value is not a basic block");
5426
5427 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
5428 GV->eraseFromParent();
5429 }
5430
5431 P.ForwardRefBlockAddresses.erase(Blocks);
5432 return false;
5433}
Chris Lattnerdf986172009-01-02 07:01:27 +00005434
5435/// ParseFunctionBody
Duncan P. N. Exon Smith78388182014-08-19 21:30:15 +00005436/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerdf986172009-01-02 07:01:27 +00005437bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner6b7c89e2011-06-17 06:42:57 +00005438 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerdf986172009-01-02 07:01:27 +00005439 return TokError("expected '{' in function body");
5440 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00005441
Chris Lattner09d9ef42009-10-28 03:39:23 +00005442 int FunctionNumber = -1;
5443 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman407a6162012-11-15 22:34:00 +00005444
Chris Lattner09d9ef42009-10-28 03:39:23 +00005445 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbara279bc32009-09-20 02:20:51 +00005446
Duncan P. N. Exon Smith16589782014-08-19 00:13:19 +00005447 // Resolve block addresses and allow basic blocks to be forward-declared
5448 // within this function.
5449 if (PFS.resolveForwardRefBlockAddresses())
5450 return true;
5451 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
5452
Chris Lattner2fdf8db2010-01-09 19:20:07 +00005453 // We need at least one basic block.
Duncan P. N. Exon Smith78388182014-08-19 21:30:15 +00005454 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattner2fdf8db2010-01-09 19:20:07 +00005455 return TokError("function body requires at least one basic block");
Michael Ilseman407a6162012-11-15 22:34:00 +00005456
Duncan P. N. Exon Smith78388182014-08-19 21:30:15 +00005457 while (Lex.getKind() != lltok::rbrace &&
5458 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerdf986172009-01-02 07:01:27 +00005459 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00005460
Duncan P. N. Exon Smith78388182014-08-19 21:30:15 +00005461 while (Lex.getKind() != lltok::rbrace)
5462 if (ParseUseListOrder(&PFS))
5463 return true;
5464
Chris Lattnerdf986172009-01-02 07:01:27 +00005465 // Eat the }.
5466 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00005467
Chris Lattnerdf986172009-01-02 07:01:27 +00005468 // Verify function is ok.
Chris Lattner09d9ef42009-10-28 03:39:23 +00005469 return PFS.FinishFunction();
Chris Lattnerdf986172009-01-02 07:01:27 +00005470}
5471
5472/// ParseBasicBlock
5473/// ::= LabelStr? Instruction*
5474bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
5475 // If this basic block starts out with a name, remember it.
5476 std::string Name;
5477 LocTy NameLoc = Lex.getLoc();
5478 if (Lex.getKind() == lltok::LabelStr) {
5479 Name = Lex.getStrVal();
5480 Lex.Lex();
5481 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00005482
Chris Lattnerdf986172009-01-02 07:01:27 +00005483 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson0923ca22015-03-02 05:25:09 +00005484 if (!BB)
5485 return Error(NameLoc,
5486 "unable to create block named '" + Name + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00005487
Chris Lattnerdf986172009-01-02 07:01:27 +00005488 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00005489
Chris Lattnerdf986172009-01-02 07:01:27 +00005490 // Parse the instructions in this block until we get a terminator.
5491 Instruction *Inst;
5492 do {
5493 // This instruction may have three possibilities for a name: a) none
5494 // specified, b) name specified "%foo =", c) number specified: "%4 =".
5495 LocTy NameLoc = Lex.getLoc();
5496 int NameID = -1;
5497 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00005498
Chris Lattnerdf986172009-01-02 07:01:27 +00005499 if (Lex.getKind() == lltok::LocalVarID) {
5500 NameID = Lex.getUIntVal();
5501 Lex.Lex();
5502 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
5503 return true;
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00005504 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00005505 NameStr = Lex.getStrVal();
5506 Lex.Lex();
5507 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
5508 return true;
5509 }
Devang Patelf633a062009-09-17 23:04:48 +00005510
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00005511 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Topper85814382012-02-07 05:05:23 +00005512 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00005513 case InstError: return true;
5514 case InstNormal:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00005515 BB->getInstList().push_back(Inst);
5516
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00005517 // With a normal result, we check to see if the instruction is followed by
5518 // a comma and metadata.
5519 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith233c2e72015-04-24 21:29:36 +00005520 if (ParseInstructionMetadata(*Inst))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00005521 return true;
5522 break;
5523 case InstExtraComma:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00005524 BB->getInstList().push_back(Inst);
5525
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00005526 // If the instruction parser ate an extra comma at the end of it, it
5527 // *must* be followed by metadata.
Duncan P. N. Exon Smith233c2e72015-04-24 21:29:36 +00005528 if (ParseInstructionMetadata(*Inst))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00005529 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00005530 break;
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00005531 }
Devang Patelf633a062009-09-17 23:04:48 +00005532
Chris Lattnerdf986172009-01-02 07:01:27 +00005533 // Set the name on the instruction.
5534 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
Chandler Carruth9179aee2018-08-26 09:51:22 +00005535 } while (!Inst->isTerminator());
Daniel Dunbara279bc32009-09-20 02:20:51 +00005536
Chris Lattnerdf986172009-01-02 07:01:27 +00005537 return false;
5538}
5539
5540//===----------------------------------------------------------------------===//
5541// Instruction Parsing.
5542//===----------------------------------------------------------------------===//
5543
5544/// ParseInstruction - Parse one of the many different instructions.
5545///
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00005546int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
5547 PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00005548 lltok::Kind Token = Lex.getKind();
5549 if (Token == lltok::Eof)
5550 return TokError("found end of file when expecting more instructions");
5551 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00005552 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00005553 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00005554
Chris Lattnerdf986172009-01-02 07:01:27 +00005555 switch (Token) {
5556 default: return Error(Loc, "expected instruction opcode");
5557 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00005558 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00005559 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
5560 case lltok::kw_br: return ParseBr(Inst, PFS);
5561 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerab21db72009-10-28 00:19:10 +00005562 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00005563 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingdccc03b2011-07-31 06:30:59 +00005564 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer4a45f082015-07-31 17:58:14 +00005565 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
5566 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
David Majnemer8cec2f22015-12-12 05:38:55 +00005567 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
5568 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
David Majnemer8cec2f22015-12-12 05:38:55 +00005569 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
Cameron McInallyca8cb682018-11-13 18:15:47 +00005570 // Unary Operators.
5571 case lltok::kw_fneg: {
5572 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5573 int Res = ParseUnaryOp(Inst, PFS, KeywordVal, 2);
5574 if (Res != 0)
5575 return Res;
5576 if (FMF.any())
5577 Inst->setFastMathFlags(FMF);
5578 return false;
5579 }
Chris Lattnerdf986172009-01-02 07:01:27 +00005580 // Binary Operators.
5581 case lltok::kw_add:
5582 case lltok::kw_sub:
Chris Lattnerf067d582011-02-07 16:40:21 +00005583 case lltok::kw_mul:
5584 case lltok::kw_shl: {
Chris Lattnerf067d582011-02-07 16:40:21 +00005585 bool NUW = EatIfPresent(lltok::kw_nuw);
5586 bool NSW = EatIfPresent(lltok::kw_nsw);
5587 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman407a6162012-11-15 22:34:00 +00005588
Chris Lattnerf067d582011-02-07 16:40:21 +00005589 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00005590
Chris Lattnerf067d582011-02-07 16:40:21 +00005591 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5592 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5593 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00005594 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00005595 case lltok::kw_fadd:
5596 case lltok::kw_fsub:
Michael Ilseman15c13d32012-11-27 00:42:44 +00005597 case lltok::kw_fmul:
5598 case lltok::kw_fdiv:
5599 case lltok::kw_frem: {
5600 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5601 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
5602 if (Res != 0)
5603 return Res;
5604 if (FMF.any())
5605 Inst->setFastMathFlags(FMF);
5606 return 0;
5607 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00005608
Chris Lattner35bda892011-02-06 21:44:57 +00005609 case lltok::kw_sdiv:
Chris Lattnerf067d582011-02-07 16:40:21 +00005610 case lltok::kw_udiv:
5611 case lltok::kw_lshr:
5612 case lltok::kw_ashr: {
5613 bool Exact = EatIfPresent(lltok::kw_exact);
5614
5615 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5616 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5617 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00005618 }
5619
Chris Lattnerdf986172009-01-02 07:01:27 +00005620 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00005621 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerdf986172009-01-02 07:01:27 +00005622 case lltok::kw_and:
5623 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00005624 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloyee0d9922015-07-10 12:52:00 +00005625 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
5626 case lltok::kw_fcmp: {
5627 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5628 int Res = ParseCompare(Inst, PFS, KeywordVal);
5629 if (Res != 0)
5630 return Res;
5631 if (FMF.any())
5632 Inst->setFastMathFlags(FMF);
5633 return 0;
5634 }
5635
Chris Lattnerdf986172009-01-02 07:01:27 +00005636 // Casts.
5637 case lltok::kw_trunc:
5638 case lltok::kw_zext:
5639 case lltok::kw_sext:
5640 case lltok::kw_fptrunc:
5641 case lltok::kw_fpext:
5642 case lltok::kw_bitcast:
Matt Arsenault59d3ae62013-11-15 01:34:59 +00005643 case lltok::kw_addrspacecast:
Chris Lattnerdf986172009-01-02 07:01:27 +00005644 case lltok::kw_uitofp:
5645 case lltok::kw_sitofp:
5646 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00005647 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00005648 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00005649 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00005650 // Other.
5651 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00005652 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00005653 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5654 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5655 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5656 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlinge6e88262011-08-12 20:24:12 +00005657 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner710c1a42014-04-24 20:14:34 +00005658 // Call.
5659 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5660 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5661 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Akira Hatanakac35973b2015-11-06 23:55:38 +00005662 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
Chris Lattnerdf986172009-01-02 07:01:27 +00005663 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00005664 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerfbe910e2011-11-27 06:56:53 +00005665 case lltok::kw_load: return ParseLoad(Inst, PFS);
5666 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedmanf03bb262011-08-12 22:50:01 +00005667 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5668 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedman47f35132011-07-25 23:16:38 +00005669 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00005670 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5671 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5672 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5673 }
5674}
5675
5676/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5677bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00005678 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00005679 switch (Lex.getKind()) {
David Tweedd80d6082013-01-07 13:32:38 +00005680 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerdf986172009-01-02 07:01:27 +00005681 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5682 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5683 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5684 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5685 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5686 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5687 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5688 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5689 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5690 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5691 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5692 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5693 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5694 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5695 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5696 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5697 }
5698 } else {
5699 switch (Lex.getKind()) {
David Tweedd80d6082013-01-07 13:32:38 +00005700 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerdf986172009-01-02 07:01:27 +00005701 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5702 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5703 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5704 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5705 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5706 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5707 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5708 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5709 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5710 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5711 }
5712 }
5713 Lex.Lex();
5714 return false;
5715}
5716
5717//===----------------------------------------------------------------------===//
5718// Terminator Instructions.
5719//===----------------------------------------------------------------------===//
5720
5721/// ParseRet - Parse a return instruction.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00005722/// ::= 'ret' void (',' !dbg, !1)*
5723/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner437544f2011-06-17 06:49:41 +00005724bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattner1afcace2011-07-09 17:41:24 +00005725 PerFunctionState &PFS) {
5726 SMLoc TypeLoc = Lex.getLoc();
Craig Topper0b6cb712014-04-15 06:32:26 +00005727 Type *Ty = nullptr;
Chris Lattnera9a9e072009-03-09 04:49:14 +00005728 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00005729
Chris Lattner1afcace2011-07-09 17:41:24 +00005730 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman407a6162012-11-15 22:34:00 +00005731
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00005732 if (Ty->isVoidTy()) {
Chris Lattner1afcace2011-07-09 17:41:24 +00005733 if (!ResType->isVoidTy())
5734 return Error(TypeLoc, "value doesn't match function result type '" +
5735 getTypeString(ResType) + "'");
Michael Ilseman407a6162012-11-15 22:34:00 +00005736
Owen Anderson1d0be152009-08-13 21:58:54 +00005737 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00005738 return false;
5739 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00005740
Chris Lattnerdf986172009-01-02 07:01:27 +00005741 Value *RV;
5742 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00005743
Chris Lattner1afcace2011-07-09 17:41:24 +00005744 if (ResType != RV->getType())
5745 return Error(TypeLoc, "value doesn't match function result type '" +
5746 getTypeString(ResType) + "'");
Michael Ilseman407a6162012-11-15 22:34:00 +00005747
Owen Anderson1d0be152009-08-13 21:58:54 +00005748 Inst = ReturnInst::Create(Context, RV);
Chris Lattner437544f2011-06-17 06:49:41 +00005749 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00005750}
5751
Chris Lattnerdf986172009-01-02 07:01:27 +00005752/// ParseBr
5753/// ::= 'br' TypeAndValue
5754/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5755bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5756 LocTy Loc, Loc2;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00005757 Value *Op0;
5758 BasicBlock *Op1, *Op2;
Chris Lattnerdf986172009-01-02 07:01:27 +00005759 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00005760
Chris Lattnerdf986172009-01-02 07:01:27 +00005761 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5762 Inst = BranchInst::Create(BB);
5763 return false;
5764 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00005765
Owen Anderson1d0be152009-08-13 21:58:54 +00005766 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00005767 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00005768
Chris Lattnerdf986172009-01-02 07:01:27 +00005769 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00005770 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00005771 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00005772 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00005773 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00005774
Chris Lattnerf9be95f2009-10-27 19:13:16 +00005775 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerdf986172009-01-02 07:01:27 +00005776 return false;
5777}
5778
5779/// ParseSwitch
5780/// Instruction
5781/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5782/// JumpTable
5783/// ::= (TypeAndValue ',' TypeAndValue)*
5784bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5785 LocTy CondLoc, BBLoc;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00005786 Value *Cond;
5787 BasicBlock *DefaultBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00005788 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5789 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00005790 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00005791 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5792 return true;
5793
Duncan Sands1df98592010-02-16 11:11:14 +00005794 if (!Cond->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00005795 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00005796
Chris Lattnerdf986172009-01-02 07:01:27 +00005797 // Parse the jump table pairs.
5798 SmallPtrSet<Value*, 32> SeenCases;
5799 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5800 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00005801 Value *Constant;
5802 BasicBlock *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00005803
Chris Lattnerdf986172009-01-02 07:01:27 +00005804 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5805 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00005806 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00005807 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00005808
David Blaikie5401ba72014-11-19 07:49:26 +00005809 if (!SeenCases.insert(Constant).second)
Chris Lattnerdf986172009-01-02 07:01:27 +00005810 return Error(CondLoc, "duplicate case value in switch");
5811 if (!isa<ConstantInt>(Constant))
5812 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00005813
Chris Lattnerf9be95f2009-10-27 19:13:16 +00005814 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerdf986172009-01-02 07:01:27 +00005815 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00005816
Chris Lattnerdf986172009-01-02 07:01:27 +00005817 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00005818
Chris Lattnerf9be95f2009-10-27 19:13:16 +00005819 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00005820 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5821 SI->addCase(Table[i].first, Table[i].second);
5822 Inst = SI;
5823 return false;
5824}
5825
Chris Lattnerab21db72009-10-28 00:19:10 +00005826/// ParseIndirectBr
Chris Lattnerf9be95f2009-10-27 19:13:16 +00005827/// Instruction
Chris Lattnerab21db72009-10-28 00:19:10 +00005828/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5829bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00005830 LocTy AddrLoc;
5831 Value *Address;
5832 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerab21db72009-10-28 00:19:10 +00005833 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5834 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattnerf9be95f2009-10-27 19:13:16 +00005835 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00005836
Duncan Sands1df98592010-02-16 11:11:14 +00005837 if (!Address->getType()->isPointerTy())
Chris Lattnerab21db72009-10-28 00:19:10 +00005838 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman407a6162012-11-15 22:34:00 +00005839
Chris Lattnerf9be95f2009-10-27 19:13:16 +00005840 // Parse the destination list.
5841 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman407a6162012-11-15 22:34:00 +00005842
Chris Lattnerf9be95f2009-10-27 19:13:16 +00005843 if (Lex.getKind() != lltok::rsquare) {
5844 BasicBlock *DestBB;
5845 if (ParseTypeAndBasicBlock(DestBB, PFS))
5846 return true;
5847 DestList.push_back(DestBB);
Michael Ilseman407a6162012-11-15 22:34:00 +00005848
Chris Lattnerf9be95f2009-10-27 19:13:16 +00005849 while (EatIfPresent(lltok::comma)) {
5850 if (ParseTypeAndBasicBlock(DestBB, PFS))
5851 return true;
5852 DestList.push_back(DestBB);
5853 }
5854 }
Michael Ilseman407a6162012-11-15 22:34:00 +00005855
Chris Lattnerf9be95f2009-10-27 19:13:16 +00005856 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5857 return true;
5858
Chris Lattnerab21db72009-10-28 00:19:10 +00005859 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattnerf9be95f2009-10-27 19:13:16 +00005860 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5861 IBI->addDestination(DestList[i]);
5862 Inst = IBI;
5863 return false;
5864}
5865
Chris Lattnerdf986172009-01-02 07:01:27 +00005866/// ParseInvoke
5867/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5868/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5869bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5870 LocTy CallLoc = Lex.getLoc();
Bill Wendling702cc912012-10-15 20:35:56 +00005871 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingbaad55c2013-02-08 06:32:06 +00005872 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling143d4642013-02-22 00:12:35 +00005873 LocTy NoBuiltinLoc;
Alexey Samsonov5e4558e2014-09-10 18:00:17 +00005874 unsigned CC;
Alexander Richardson47ff67b2018-08-23 09:25:17 +00005875 unsigned InvokeAddrSpace;
Craig Topper0b6cb712014-04-15 06:32:26 +00005876 Type *RetType = nullptr;
Chris Lattnerdf986172009-01-02 07:01:27 +00005877 LocTy RetTypeLoc;
5878 ValID CalleeID;
5879 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasf70eb722015-09-24 23:34:52 +00005880 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerdf986172009-01-02 07:01:27 +00005881
Chris Lattnerf9be95f2009-10-27 19:13:16 +00005882 BasicBlock *NormalBB, *UnwindBB;
Sanjoy Dasf70eb722015-09-24 23:34:52 +00005883 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Alexander Richardson47ff67b2018-08-23 09:25:17 +00005884 ParseOptionalProgramAddrSpace(InvokeAddrSpace) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00005885 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Sanjoy Dasf70eb722015-09-24 23:34:52 +00005886 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
Bill Wendling143d4642013-02-22 00:12:35 +00005887 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5888 NoBuiltinLoc) ||
Sanjoy Dasf70eb722015-09-24 23:34:52 +00005889 ParseOptionalOperandBundles(BundleList, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00005890 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00005891 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00005892 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00005893 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00005894 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00005895
Chris Lattnerdf986172009-01-02 07:01:27 +00005896 // If RetType is a non-function pointer type, then this is the short syntax
5897 // for the call, which means that RetType is just the return type. Infer the
5898 // rest of the function argument types from the arguments that are present.
David Blaikiee41f3842015-04-24 19:32:54 +00005899 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5900 if (!Ty) {
Chris Lattnerdf986172009-01-02 07:01:27 +00005901 // Pull out the types of all of the arguments...
Jay Foad5fdd6c82011-07-12 14:06:48 +00005902 std::vector<Type*> ParamTypes;
Chris Lattnerdf986172009-01-02 07:01:27 +00005903 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5904 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00005905
Chris Lattnerdf986172009-01-02 07:01:27 +00005906 if (!FunctionType::isValidReturnType(RetType))
5907 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00005908
Owen Andersondebcb012009-07-29 22:17:13 +00005909 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerdf986172009-01-02 07:01:27 +00005910 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00005911
David Blaikie4f7a4bc2015-07-27 23:32:19 +00005912 CalleeID.FTy = Ty;
5913
Chris Lattnerdf986172009-01-02 07:01:27 +00005914 // Look up the callee.
5915 Value *Callee;
Alexander Richardson47ff67b2018-08-23 09:25:17 +00005916 if (ConvertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID,
5917 Callee, &PFS, /*IsCall=*/true))
David Blaikiee41f3842015-04-24 19:32:54 +00005918 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00005919
Bill Wendling034b94b2012-12-19 07:18:57 +00005920 // Set up the Attribute for the function.
Reid Klecknere9a46bf2017-04-13 00:58:09 +00005921 SmallVector<Value *, 8> Args;
5922 SmallVector<AttributeSet, 8> ArgAttrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00005923
Chris Lattnerdf986172009-01-02 07:01:27 +00005924 // Loop through FunctionType's arguments and ensure they are specified
5925 // correctly. Also, gather any parameter attributes.
5926 FunctionType::param_iterator I = Ty->param_begin();
5927 FunctionType::param_iterator E = Ty->param_end();
5928 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper0b6cb712014-04-15 06:32:26 +00005929 Type *ExpectedTy = nullptr;
Chris Lattnerdf986172009-01-02 07:01:27 +00005930 if (I != E) {
5931 ExpectedTy = *I++;
5932 } else if (!Ty->isVarArg()) {
5933 return Error(ArgList[i].Loc, "too many arguments specified");
5934 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00005935
Chris Lattnerdf986172009-01-02 07:01:27 +00005936 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5937 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00005938 getTypeString(ExpectedTy) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00005939 Args.push_back(ArgList[i].V);
Reid Klecknere9a46bf2017-04-13 00:58:09 +00005940 ArgAttrs.push_back(ArgList[i].Attrs);
Chris Lattnerdf986172009-01-02 07:01:27 +00005941 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00005942
Chris Lattnerdf986172009-01-02 07:01:27 +00005943 if (I != E)
5944 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00005945
Reid Kleckner7dde8e82017-04-10 23:31:05 +00005946 if (FnAttrs.hasAlignmentAttr())
5947 return Error(CallLoc, "invoke instructions may not have an alignment");
David Majnemerdad44db2015-02-23 00:01:32 +00005948
Bill Wendling034b94b2012-12-19 07:18:57 +00005949 // Finish off the Attribute and check them
Reid Klecknere9a46bf2017-04-13 00:58:09 +00005950 AttributeList PAL =
5951 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
5952 AttributeSet::get(Context, RetAttrs), ArgAttrs);
Daniel Dunbara279bc32009-09-20 02:20:51 +00005953
Sanjoy Dasf70eb722015-09-24 23:34:52 +00005954 InvokeInst *II =
5955 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
Chris Lattnerdf986172009-01-02 07:01:27 +00005956 II->setCallingConv(CC);
5957 II->setAttributes(PAL);
Bill Wendlingbaad55c2013-02-08 06:32:06 +00005958 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerdf986172009-01-02 07:01:27 +00005959 Inst = II;
5960 return false;
5961}
5962
Bill Wendlingdccc03b2011-07-31 06:30:59 +00005963/// ParseResume
5964/// ::= 'resume' TypeAndValue
5965bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5966 Value *Exn; LocTy ExnLoc;
Bill Wendlingdccc03b2011-07-31 06:30:59 +00005967 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5968 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00005969
Bill Wendlingdccc03b2011-07-31 06:30:59 +00005970 ResumeInst *RI = ResumeInst::Create(Exn);
5971 Inst = RI;
5972 return false;
5973}
Chris Lattnerdf986172009-01-02 07:01:27 +00005974
David Majnemer4a45f082015-07-31 17:58:14 +00005975bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5976 PerFunctionState &PFS) {
Joseph Tremouletd4a765f2015-08-23 00:26:33 +00005977 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
David Majnemer4a45f082015-07-31 17:58:14 +00005978 return true;
5979
5980 while (Lex.getKind() != lltok::rsquare) {
5981 // If this isn't the first argument, we need a comma.
5982 if (!Args.empty() &&
5983 ParseToken(lltok::comma, "expected ',' in argument list"))
5984 return true;
5985
5986 // Parse the argument.
5987 LocTy ArgLoc;
5988 Type *ArgTy = nullptr;
5989 if (ParseType(ArgTy, ArgLoc))
5990 return true;
5991
5992 Value *V;
5993 if (ArgTy->isMetadataTy()) {
5994 if (ParseMetadataAsValue(V, PFS))
5995 return true;
5996 } else {
5997 if (ParseValue(ArgTy, V, PFS))
5998 return true;
5999 }
6000 Args.push_back(V);
6001 }
6002
6003 Lex.Lex(); // Lex the ']'.
6004 return false;
6005}
6006
6007/// ParseCleanupRet
David Majnemer8cec2f22015-12-12 05:38:55 +00006008/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
David Majnemer4a45f082015-07-31 17:58:14 +00006009bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremouletd4a765f2015-08-23 00:26:33 +00006010 Value *CleanupPad = nullptr;
David Majnemer4a45f082015-07-31 17:58:14 +00006011
David Majnemer8cec2f22015-12-12 05:38:55 +00006012 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
6013 return true;
6014
6015 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
Joseph Tremouletd4a765f2015-08-23 00:26:33 +00006016 return true;
David Majnemer4a45f082015-07-31 17:58:14 +00006017
6018 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
6019 return true;
6020
6021 BasicBlock *UnwindBB = nullptr;
6022 if (Lex.getKind() == lltok::kw_to) {
6023 Lex.Lex();
6024 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
6025 return true;
6026 } else {
6027 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
6028 return true;
6029 }
6030 }
6031
David Majnemer8cec2f22015-12-12 05:38:55 +00006032 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
David Majnemer4a45f082015-07-31 17:58:14 +00006033 return false;
6034}
6035
6036/// ParseCatchRet
David Majnemer8cec2f22015-12-12 05:38:55 +00006037/// ::= 'catchret' from Parent Value 'to' TypeAndValue
David Majnemer4a45f082015-07-31 17:58:14 +00006038bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremouletd4a765f2015-08-23 00:26:33 +00006039 Value *CatchPad = nullptr;
David Majnemerde17e772015-08-15 02:46:08 +00006040
David Majnemer8cec2f22015-12-12 05:38:55 +00006041 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
6042 return true;
6043
6044 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
David Majnemerde17e772015-08-15 02:46:08 +00006045 return true;
6046
David Majnemerde17e772015-08-15 02:46:08 +00006047 BasicBlock *BB;
6048 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
6049 ParseTypeAndBasicBlock(BB, PFS))
6050 return true;
6051
David Majnemer8cec2f22015-12-12 05:38:55 +00006052 Inst = CatchReturnInst::Create(CatchPad, BB);
6053 return false;
6054}
6055
6056/// ParseCatchSwitch
6057/// ::= 'catchswitch' within Parent
6058bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
6059 Value *ParentPad;
David Majnemer8cec2f22015-12-12 05:38:55 +00006060
6061 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
6062 return true;
6063
6064 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6065 Lex.getKind() != lltok::LocalVarID)
6066 return TokError("expected scope value for catchswitch");
6067
6068 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
6069 return true;
6070
6071 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
6072 return true;
6073
6074 SmallVector<BasicBlock *, 32> Table;
6075 do {
6076 BasicBlock *DestBB;
6077 if (ParseTypeAndBasicBlock(DestBB, PFS))
6078 return true;
6079 Table.push_back(DestBB);
6080 } while (EatIfPresent(lltok::comma));
6081
6082 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
6083 return true;
6084
6085 if (ParseToken(lltok::kw_unwind,
6086 "expected 'unwind' after catchswitch scope"))
6087 return true;
6088
6089 BasicBlock *UnwindBB = nullptr;
6090 if (EatIfPresent(lltok::kw_to)) {
6091 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
6092 return true;
6093 } else {
6094 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
6095 return true;
6096 }
6097
6098 auto *CatchSwitch =
6099 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
6100 for (BasicBlock *DestBB : Table)
6101 CatchSwitch->addHandler(DestBB);
6102 Inst = CatchSwitch;
David Majnemer4a45f082015-07-31 17:58:14 +00006103 return false;
6104}
6105
6106/// ParseCatchPad
Joseph Tremouletd4a765f2015-08-23 00:26:33 +00006107/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
David Majnemer4a45f082015-07-31 17:58:14 +00006108bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8cec2f22015-12-12 05:38:55 +00006109 Value *CatchSwitch = nullptr;
6110
6111 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
6112 return true;
6113
6114 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
6115 return TokError("expected scope value for catchpad");
6116
6117 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
6118 return true;
6119
David Majnemer4a45f082015-07-31 17:58:14 +00006120 SmallVector<Value *, 8> Args;
Joseph Tremouletd4a765f2015-08-23 00:26:33 +00006121 if (ParseExceptionArgs(Args, PFS))
David Majnemer4a45f082015-07-31 17:58:14 +00006122 return true;
6123
David Majnemer8cec2f22015-12-12 05:38:55 +00006124 Inst = CatchPadInst::Create(CatchSwitch, Args);
David Majnemer4a45f082015-07-31 17:58:14 +00006125 return false;
6126}
6127
David Majnemer4a45f082015-07-31 17:58:14 +00006128/// ParseCleanupPad
David Majnemer8cec2f22015-12-12 05:38:55 +00006129/// ::= 'cleanuppad' within Parent ParamList
David Majnemer4a45f082015-07-31 17:58:14 +00006130bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8cec2f22015-12-12 05:38:55 +00006131 Value *ParentPad = nullptr;
6132
6133 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
6134 return true;
6135
6136 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6137 Lex.getKind() != lltok::LocalVarID)
6138 return TokError("expected scope value for cleanuppad");
6139
6140 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
6141 return true;
6142
David Majnemer4a45f082015-07-31 17:58:14 +00006143 SmallVector<Value *, 8> Args;
Joseph Tremouletd4a765f2015-08-23 00:26:33 +00006144 if (ParseExceptionArgs(Args, PFS))
David Majnemer4a45f082015-07-31 17:58:14 +00006145 return true;
6146
David Majnemer8cec2f22015-12-12 05:38:55 +00006147 Inst = CleanupPadInst::Create(ParentPad, Args);
Joseph Tremoulet226889e2015-09-03 09:09:43 +00006148 return false;
6149}
6150
Chris Lattnerdf986172009-01-02 07:01:27 +00006151//===----------------------------------------------------------------------===//
Cameron McInallyca8cb682018-11-13 18:15:47 +00006152// Unary Operators.
6153//===----------------------------------------------------------------------===//
6154
6155/// ParseUnaryOp
6156/// ::= UnaryOp TypeAndValue ',' Value
6157///
6158/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
6159/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
6160bool LLParser::ParseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
6161 unsigned Opc, unsigned OperandType) {
6162 LocTy Loc; Value *LHS;
6163 if (ParseTypeAndValue(LHS, Loc, PFS))
6164 return true;
6165
6166 bool Valid;
6167 switch (OperandType) {
6168 default: llvm_unreachable("Unknown operand type!");
6169 case 0: // int or FP.
6170 Valid = LHS->getType()->isIntOrIntVectorTy() ||
6171 LHS->getType()->isFPOrFPVectorTy();
6172 break;
6173 case 1:
6174 Valid = LHS->getType()->isIntOrIntVectorTy();
6175 break;
6176 case 2:
6177 Valid = LHS->getType()->isFPOrFPVectorTy();
6178 break;
6179 }
6180
6181 if (!Valid)
6182 return Error(Loc, "invalid operand type for instruction");
6183
6184 Inst = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
6185 return false;
6186}
6187
6188//===----------------------------------------------------------------------===//
Chris Lattnerdf986172009-01-02 07:01:27 +00006189// Binary Operators.
6190//===----------------------------------------------------------------------===//
6191
6192/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00006193/// ::= ArithmeticOps TypeAndValue ',' Value
6194///
6195/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
6196/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00006197bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00006198 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00006199 LocTy Loc; Value *LHS, *RHS;
6200 if (ParseTypeAndValue(LHS, Loc, PFS) ||
6201 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
6202 ParseValue(LHS->getType(), RHS, PFS))
6203 return true;
6204
Chris Lattnere914b592009-01-05 08:24:46 +00006205 bool Valid;
6206 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006207 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00006208 case 0: // int or FP.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00006209 Valid = LHS->getType()->isIntOrIntVectorTy() ||
6210 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnere914b592009-01-05 08:24:46 +00006211 break;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00006212 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
6213 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnere914b592009-01-05 08:24:46 +00006214 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00006215
Chris Lattnere914b592009-01-05 08:24:46 +00006216 if (!Valid)
6217 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00006218
Chris Lattnerdf986172009-01-02 07:01:27 +00006219 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6220 return false;
6221}
6222
6223/// ParseLogical
6224/// ::= ArithmeticOps TypeAndValue ',' Value {
6225bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
6226 unsigned Opc) {
6227 LocTy Loc; Value *LHS, *RHS;
6228 if (ParseTypeAndValue(LHS, Loc, PFS) ||
6229 ParseToken(lltok::comma, "expected ',' in logical operation") ||
6230 ParseValue(LHS->getType(), RHS, PFS))
6231 return true;
6232
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00006233 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00006234 return Error(Loc,"instruction requires integer or integer vector operands");
6235
6236 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6237 return false;
6238}
6239
Chris Lattnerdf986172009-01-02 07:01:27 +00006240/// ParseCompare
6241/// ::= 'icmp' IPredicates TypeAndValue ',' Value
6242/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00006243bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
6244 unsigned Opc) {
6245 // Parse the integer/fp comparison predicate.
6246 LocTy Loc;
6247 unsigned Pred;
6248 Value *LHS, *RHS;
6249 if (ParseCmpPredicate(Pred, Opc) ||
6250 ParseTypeAndValue(LHS, Loc, PFS) ||
6251 ParseToken(lltok::comma, "expected ',' after compare value") ||
6252 ParseValue(LHS->getType(), RHS, PFS))
6253 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00006254
Chris Lattnerdf986172009-01-02 07:01:27 +00006255 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00006256 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00006257 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006258 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00006259 } else {
6260 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00006261 if (!LHS->getType()->isIntOrIntVectorTy() &&
Craig Topper10600822017-07-09 07:04:00 +00006262 !LHS->getType()->isPtrOrPtrVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00006263 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006264 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00006265 }
6266 return false;
6267}
6268
6269//===----------------------------------------------------------------------===//
6270// Other Instructions.
6271//===----------------------------------------------------------------------===//
6272
6273
6274/// ParseCast
6275/// ::= CastOpc TypeAndValue 'to' Type
6276bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
6277 unsigned Opc) {
Chris Lattner1afcace2011-07-09 17:41:24 +00006278 LocTy Loc;
6279 Value *Op;
Craig Topper0b6cb712014-04-15 06:32:26 +00006280 Type *DestTy = nullptr;
Chris Lattnerdf986172009-01-02 07:01:27 +00006281 if (ParseTypeAndValue(Op, Loc, PFS) ||
6282 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
6283 ParseType(DestTy))
6284 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00006285
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00006286 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
6287 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00006288 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00006289 getTypeString(Op->getType()) + "' to '" +
6290 getTypeString(DestTy) + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00006291 }
Chris Lattnerdf986172009-01-02 07:01:27 +00006292 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
6293 return false;
6294}
6295
6296/// ParseSelect
6297/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6298bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
6299 LocTy Loc;
6300 Value *Op0, *Op1, *Op2;
6301 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6302 ParseToken(lltok::comma, "expected ',' after select condition") ||
6303 ParseTypeAndValue(Op1, PFS) ||
6304 ParseToken(lltok::comma, "expected ',' after select value") ||
6305 ParseTypeAndValue(Op2, PFS))
6306 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00006307
Chris Lattnerdf986172009-01-02 07:01:27 +00006308 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
6309 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00006310
Chris Lattnerdf986172009-01-02 07:01:27 +00006311 Inst = SelectInst::Create(Op0, Op1, Op2);
6312 return false;
6313}
6314
Chris Lattner0088a5c2009-01-05 08:18:44 +00006315/// ParseVA_Arg
6316/// ::= 'va_arg' TypeAndValue ',' Type
6317bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00006318 Value *Op;
Craig Topper0b6cb712014-04-15 06:32:26 +00006319 Type *EltTy = nullptr;
Chris Lattner0088a5c2009-01-05 08:18:44 +00006320 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00006321 if (ParseTypeAndValue(Op, PFS) ||
6322 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00006323 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00006324 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00006325
Chris Lattner0088a5c2009-01-05 08:18:44 +00006326 if (!EltTy->isFirstClassType())
6327 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00006328
6329 Inst = new VAArgInst(Op, EltTy);
6330 return false;
6331}
6332
6333/// ParseExtractElement
6334/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
6335bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
6336 LocTy Loc;
6337 Value *Op0, *Op1;
6338 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6339 ParseToken(lltok::comma, "expected ',' after extract value") ||
6340 ParseTypeAndValue(Op1, PFS))
6341 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00006342
Chris Lattnerdf986172009-01-02 07:01:27 +00006343 if (!ExtractElementInst::isValidOperands(Op0, Op1))
6344 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00006345
Eric Christophera3500da2009-07-25 02:28:41 +00006346 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00006347 return false;
6348}
6349
6350/// ParseInsertElement
6351/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6352bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
6353 LocTy Loc;
6354 Value *Op0, *Op1, *Op2;
6355 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6356 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6357 ParseTypeAndValue(Op1, PFS) ||
6358 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6359 ParseTypeAndValue(Op2, PFS))
6360 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00006361
Chris Lattnerdf986172009-01-02 07:01:27 +00006362 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00006363 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00006364
Chris Lattnerdf986172009-01-02 07:01:27 +00006365 Inst = InsertElementInst::Create(Op0, Op1, Op2);
6366 return false;
6367}
6368
6369/// ParseShuffleVector
6370/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6371bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
6372 LocTy Loc;
6373 Value *Op0, *Op1, *Op2;
6374 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6375 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
6376 ParseTypeAndValue(Op1, PFS) ||
6377 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
6378 ParseTypeAndValue(Op2, PFS))
6379 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00006380
Chris Lattnerdf986172009-01-02 07:01:27 +00006381 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperaf393682012-02-01 23:43:12 +00006382 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00006383
Chris Lattnerdf986172009-01-02 07:01:27 +00006384 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
6385 return false;
6386}
6387
6388/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00006389/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00006390int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper0b6cb712014-04-15 06:32:26 +00006391 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00006392 Value *Op0, *Op1;
Daniel Dunbara279bc32009-09-20 02:20:51 +00006393
Chris Lattner1afcace2011-07-09 17:41:24 +00006394 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00006395 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
6396 ParseValue(Ty, Op0, PFS) ||
6397 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00006398 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00006399 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
6400 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00006401
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00006402 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00006403 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
Eugene Zelenko3d7ca1c2016-08-25 00:45:04 +00006404
6405 while (true) {
Chris Lattnerdf986172009-01-02 07:01:27 +00006406 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00006407
Chris Lattner3ed88ef2009-01-02 08:05:26 +00006408 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00006409 break;
6410
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00006411 if (Lex.getKind() == lltok::MetadataVar) {
6412 AteExtraComma = true;
Devang Patela43d46f2009-10-16 18:45:49 +00006413 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00006414 }
Devang Patela43d46f2009-10-16 18:45:49 +00006415
Chris Lattner3ed88ef2009-01-02 08:05:26 +00006416 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00006417 ParseValue(Ty, Op0, PFS) ||
6418 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00006419 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00006420 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
6421 return true;
6422 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00006423
Chris Lattnerdf986172009-01-02 07:01:27 +00006424 if (!Ty->isFirstClassType())
6425 return Error(TypeLoc, "phi node must have first class type");
6426
Jay Foad3ecfc862011-03-30 11:28:46 +00006427 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00006428 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
6429 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
6430 Inst = PN;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00006431 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00006432}
6433
Bill Wendlinge6e88262011-08-12 20:24:12 +00006434/// ParseLandingPad
6435/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
6436/// Clause
6437/// ::= 'catch' TypeAndValue
6438/// ::= 'filter'
6439/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
6440bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper0b6cb712014-04-15 06:32:26 +00006441 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlinge6e88262011-08-12 20:24:12 +00006442
David Majnemercc714e22015-06-17 20:52:32 +00006443 if (ParseType(Ty, TyLoc))
Bill Wendlinge6e88262011-08-12 20:24:12 +00006444 return true;
6445
David Majnemercc714e22015-06-17 20:52:32 +00006446 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlinge6e88262011-08-12 20:24:12 +00006447 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
6448
6449 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
6450 LandingPadInst::ClauseType CT;
6451 if (EatIfPresent(lltok::kw_catch))
6452 CT = LandingPadInst::Catch;
6453 else if (EatIfPresent(lltok::kw_filter))
6454 CT = LandingPadInst::Filter;
6455 else
6456 return TokError("expected 'catch' or 'filter' clause type");
6457
Rafael Espindoladcac1522014-06-04 18:51:31 +00006458 Value *V;
6459 LocTy VLoc;
Owen Anderson8e120d82015-03-09 07:13:42 +00006460 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlinge6e88262011-08-12 20:24:12 +00006461 return true;
Bill Wendlinge6e88262011-08-12 20:24:12 +00006462
Bill Wendling746c8822011-08-12 20:52:25 +00006463 // A 'catch' type expects a non-array constant. A filter clause expects an
6464 // array constant.
6465 if (CT == LandingPadInst::Catch) {
6466 if (isa<ArrayType>(V->getType()))
6467 Error(VLoc, "'catch' clause has an invalid type");
6468 } else {
6469 if (!isa<ArrayType>(V->getType()))
6470 Error(VLoc, "'filter' clause has an invalid type");
6471 }
6472
Owen Anderson8e120d82015-03-09 07:13:42 +00006473 Constant *CV = dyn_cast<Constant>(V);
6474 if (!CV)
6475 return Error(VLoc, "clause argument must be a constant");
6476 LP->addClause(CV);
Bill Wendlinge6e88262011-08-12 20:24:12 +00006477 }
6478
Owen Anderson8e120d82015-03-09 07:13:42 +00006479 Inst = LP.release();
Bill Wendlinge6e88262011-08-12 20:24:12 +00006480 return false;
6481}
6482
Chris Lattnerdf986172009-01-02 07:01:27 +00006483/// ParseCall
Sanjay Patela3a48d92015-12-14 21:59:03 +00006484/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
6485/// OptionalAttrs Type Value ParameterList OptionalAttrs
6486/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
6487/// OptionalAttrs Type Value ParameterList OptionalAttrs
6488/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
6489/// OptionalAttrs Type Value ParameterList OptionalAttrs
6490/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
6491/// OptionalAttrs Type Value ParameterList OptionalAttrs
Chris Lattnerdf986172009-01-02 07:01:27 +00006492bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner710c1a42014-04-24 20:14:34 +00006493 CallInst::TailCallKind TCK) {
Bill Wendling702cc912012-10-15 20:35:56 +00006494 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingbaad55c2013-02-08 06:32:06 +00006495 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman2253a2f2013-06-27 00:25:01 +00006496 LocTy BuiltinLoc;
Alexander Richardson47ff67b2018-08-23 09:25:17 +00006497 unsigned CallAddrSpace;
Alexey Samsonov5e4558e2014-09-10 18:00:17 +00006498 unsigned CC;
Craig Topper0b6cb712014-04-15 06:32:26 +00006499 Type *RetType = nullptr;
Chris Lattnerdf986172009-01-02 07:01:27 +00006500 LocTy RetTypeLoc;
6501 ValID CalleeID;
6502 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasf70eb722015-09-24 23:34:52 +00006503 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerdf986172009-01-02 07:01:27 +00006504 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00006505
Sanjay Patela3a48d92015-12-14 21:59:03 +00006506 if (TCK != CallInst::TCK_None &&
6507 ParseToken(lltok::kw_call,
6508 "expected 'tail call', 'musttail call', or 'notail call'"))
6509 return true;
6510
6511 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6512
6513 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Alexander Richardson47ff67b2018-08-23 09:25:17 +00006514 ParseOptionalProgramAddrSpace(CallAddrSpace) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00006515 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00006516 ParseValID(CalleeID) ||
Reid Kleckner44b3a0b2014-08-26 00:33:28 +00006517 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
6518 PFS.getFunction().isVarArg()) ||
Sanjoy Dasf70eb722015-09-24 23:34:52 +00006519 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
6520 ParseOptionalOperandBundles(BundleList, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00006521 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00006522
Sanjay Patela3a48d92015-12-14 21:59:03 +00006523 if (FMF.any() && !RetType->isFPOrFPVectorTy())
6524 return Error(CallLoc, "fast-math-flags specified for call without "
6525 "floating-point scalar or vector return type");
6526
Chris Lattnerdf986172009-01-02 07:01:27 +00006527 // If RetType is a non-function pointer type, then this is the short syntax
6528 // for the call, which means that RetType is just the return type. Infer the
6529 // rest of the function argument types from the arguments that are present.
David Blaikie32b845d2015-04-16 23:24:18 +00006530 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6531 if (!Ty) {
Chris Lattnerdf986172009-01-02 07:01:27 +00006532 // Pull out the types of all of the arguments...
Jay Foad5fdd6c82011-07-12 14:06:48 +00006533 std::vector<Type*> ParamTypes;
Eli Friedman83b4a972010-07-24 23:06:59 +00006534 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6535 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00006536
Chris Lattnerdf986172009-01-02 07:01:27 +00006537 if (!FunctionType::isValidReturnType(RetType))
6538 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00006539
Owen Andersondebcb012009-07-29 22:17:13 +00006540 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerdf986172009-01-02 07:01:27 +00006541 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00006542
David Blaikie4f7a4bc2015-07-27 23:32:19 +00006543 CalleeID.FTy = Ty;
6544
Chris Lattnerdf986172009-01-02 07:01:27 +00006545 // Look up the callee.
6546 Value *Callee;
Alexander Richardson47ff67b2018-08-23 09:25:17 +00006547 if (ConvertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,
6548 &PFS, /*IsCall=*/true))
David Blaikie32b845d2015-04-16 23:24:18 +00006549 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00006550
Bill Wendling034b94b2012-12-19 07:18:57 +00006551 // Set up the Attribute for the function.
Reid Kleckner06090402017-04-12 00:38:00 +00006552 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00006553
Chris Lattnerdf986172009-01-02 07:01:27 +00006554 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00006555
Chris Lattnerdf986172009-01-02 07:01:27 +00006556 // Loop through FunctionType's arguments and ensure they are specified
6557 // correctly. Also, gather any parameter attributes.
6558 FunctionType::param_iterator I = Ty->param_begin();
6559 FunctionType::param_iterator E = Ty->param_end();
6560 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper0b6cb712014-04-15 06:32:26 +00006561 Type *ExpectedTy = nullptr;
Chris Lattnerdf986172009-01-02 07:01:27 +00006562 if (I != E) {
6563 ExpectedTy = *I++;
6564 } else if (!Ty->isVarArg()) {
6565 return Error(ArgList[i].Loc, "too many arguments specified");
6566 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00006567
Chris Lattnerdf986172009-01-02 07:01:27 +00006568 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6569 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00006570 getTypeString(ExpectedTy) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00006571 Args.push_back(ArgList[i].V);
Reid Kleckner7dde8e82017-04-10 23:31:05 +00006572 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerdf986172009-01-02 07:01:27 +00006573 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00006574
Chris Lattnerdf986172009-01-02 07:01:27 +00006575 if (I != E)
6576 return Error(CallLoc, "not enough parameters specified for call");
6577
Reid Kleckner7dde8e82017-04-10 23:31:05 +00006578 if (FnAttrs.hasAlignmentAttr())
6579 return Error(CallLoc, "call instructions may not have an alignment");
David Majnemerdad44db2015-02-23 00:01:32 +00006580
Bill Wendling034b94b2012-12-19 07:18:57 +00006581 // Finish off the Attribute and check them
Reid Klecknere9a46bf2017-04-13 00:58:09 +00006582 AttributeList PAL =
6583 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6584 AttributeSet::get(Context, RetAttrs), Attrs);
Daniel Dunbara279bc32009-09-20 02:20:51 +00006585
Sanjoy Dasf70eb722015-09-24 23:34:52 +00006586 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
Reid Kleckner710c1a42014-04-24 20:14:34 +00006587 CI->setTailCallKind(TCK);
Chris Lattnerdf986172009-01-02 07:01:27 +00006588 CI->setCallingConv(CC);
Sanjay Patela3a48d92015-12-14 21:59:03 +00006589 if (FMF.any())
6590 CI->setFastMathFlags(FMF);
Chris Lattnerdf986172009-01-02 07:01:27 +00006591 CI->setAttributes(PAL);
Bill Wendlingbaad55c2013-02-08 06:32:06 +00006592 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerdf986172009-01-02 07:01:27 +00006593 Inst = CI;
6594 return false;
6595}
6596
6597//===----------------------------------------------------------------------===//
6598// Memory Instructions.
6599//===----------------------------------------------------------------------===//
6600
6601/// ParseAlloc
Manman Ren4bda8822016-04-01 21:41:15 +00006602/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
Yaxun Liu75811462017-10-14 03:23:18 +00006603/// (',' 'align' i32)? (',', 'addrspace(n))?
Chris Lattnerf3a789d2011-06-17 03:16:47 +00006604int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper0b6cb712014-04-15 06:32:26 +00006605 Value *Size = nullptr;
Matt Arsenaulte0b3c332017-04-10 22:27:50 +00006606 LocTy SizeLoc, TyLoc, ASLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00006607 unsigned Alignment = 0;
Matt Arsenaulte0b3c332017-04-10 22:27:50 +00006608 unsigned AddrSpace = 0;
Craig Topper0b6cb712014-04-15 06:32:26 +00006609 Type *Ty = nullptr;
David Majnemer39a09d22014-03-09 06:41:58 +00006610
6611 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
Manman Ren4bda8822016-04-01 21:41:15 +00006612 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
David Majnemer39a09d22014-03-09 06:41:58 +00006613
David Majnemerb3dd3c72015-02-16 08:38:03 +00006614 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00006615
David Majnemerb3dd3c72015-02-16 08:38:03 +00006616 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
6617 return Error(TyLoc, "invalid type for alloca");
David Majnemer5b71fff2015-02-11 09:13:11 +00006618
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00006619 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00006620 if (EatIfPresent(lltok::comma)) {
David Majnemer39a09d22014-03-09 06:41:58 +00006621 if (Lex.getKind() == lltok::kw_align) {
Matt Arsenaulte0b3c332017-04-10 22:27:50 +00006622 if (ParseOptionalAlignment(Alignment))
6623 return true;
6624 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6625 return true;
6626 } else if (Lex.getKind() == lltok::kw_addrspace) {
6627 ASLoc = Lex.getLoc();
6628 if (ParseOptionalAddrSpace(AddrSpace))
6629 return true;
David Majnemer39a09d22014-03-09 06:41:58 +00006630 } else if (Lex.getKind() == lltok::MetadataVar) {
6631 AteExtraComma = true;
6632 } else {
Yaxun Liu75811462017-10-14 03:23:18 +00006633 if (ParseTypeAndValue(Size, SizeLoc, PFS))
David Majnemer39a09d22014-03-09 06:41:58 +00006634 return true;
Yaxun Liu75811462017-10-14 03:23:18 +00006635 if (EatIfPresent(lltok::comma)) {
6636 if (Lex.getKind() == lltok::kw_align) {
6637 if (ParseOptionalAlignment(Alignment))
6638 return true;
6639 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6640 return true;
6641 } else if (Lex.getKind() == lltok::kw_addrspace) {
6642 ASLoc = Lex.getLoc();
6643 if (ParseOptionalAddrSpace(AddrSpace))
6644 return true;
6645 } else if (Lex.getKind() == lltok::MetadataVar) {
6646 AteExtraComma = true;
6647 }
6648 }
Chris Lattnerdf986172009-01-02 07:01:27 +00006649 }
6650 }
6651
Dan Gohmanf75a7d32010-05-28 01:14:11 +00006652 if (Size && !Size->getType()->isIntegerTy())
6653 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerdf986172009-01-02 07:01:27 +00006654
Yaxun Liu7c2d0492018-01-30 22:32:39 +00006655 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, Alignment);
Reid Kleckner3cbfa162014-01-17 23:58:17 +00006656 AI->setUsedWithInAlloca(IsInAlloca);
Manman Ren4bda8822016-04-01 21:41:15 +00006657 AI->setSwiftError(IsSwiftError);
Reid Kleckner3cbfa162014-01-17 23:58:17 +00006658 Inst = AI;
Chris Lattnerf3a789d2011-06-17 03:16:47 +00006659 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00006660}
6661
6662/// ParseLoad
Eli Friedmanf03bb262011-08-12 22:50:01 +00006663/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman407a6162012-11-15 22:34:00 +00006664/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedmanf03bb262011-08-12 22:50:01 +00006665/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerfbe910e2011-11-27 06:56:53 +00006666int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00006667 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00006668 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00006669 bool AteExtraComma = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00006670 bool isAtomic = false;
JF Bastienb36d1a82016-04-06 21:19:33 +00006671 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyov8f856852017-07-11 22:23:00 +00006672 SyncScope::ID SSID = SyncScope::System;
Eli Friedmanf03bb262011-08-12 22:50:01 +00006673
6674 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00006675 isAtomic = true;
6676 Lex.Lex();
6677 }
6678
Chris Lattnerfbe910e2011-11-27 06:56:53 +00006679 bool isVolatile = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00006680 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00006681 isVolatile = true;
6682 Lex.Lex();
6683 }
6684
David Blaikieaf102352015-04-06 20:59:48 +00006685 Type *Ty;
David Blaikie7c9c6ed2015-02-27 21:17:42 +00006686 LocTy ExplicitTypeLoc = Lex.getLoc();
6687 if (ParseType(Ty) ||
6688 ParseToken(lltok::comma, "expected comma after load's type") ||
6689 ParseTypeAndValue(Val, Loc, PFS) ||
Konstantin Zhuravlyov8f856852017-07-11 22:23:00 +00006690 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00006691 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6692 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00006693
David Blaikieaf102352015-04-06 20:59:48 +00006694 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerdf986172009-01-02 07:01:27 +00006695 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman21006d42011-08-09 23:02:53 +00006696 if (isAtomic && !Alignment)
6697 return Error(Loc, "atomic load must have explicit non-zero alignment");
JF Bastienb36d1a82016-04-06 21:19:33 +00006698 if (Ordering == AtomicOrdering::Release ||
6699 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman21006d42011-08-09 23:02:53 +00006700 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbara279bc32009-09-20 02:20:51 +00006701
David Blaikie7c9c6ed2015-02-27 21:17:42 +00006702 if (Ty != cast<PointerType>(Val->getType())->getElementType())
6703 return Error(ExplicitTypeLoc,
6704 "explicit pointee type doesn't match operand's pointee type");
6705
Konstantin Zhuravlyov8f856852017-07-11 22:23:00 +00006706 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, SSID);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00006707 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00006708}
6709
6710/// ParseStore
Eli Friedmanf03bb262011-08-12 22:50:01 +00006711
6712/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6713/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman21006d42011-08-09 23:02:53 +00006714/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerfbe910e2011-11-27 06:56:53 +00006715int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00006716 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00006717 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00006718 bool AteExtraComma = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00006719 bool isAtomic = false;
JF Bastienb36d1a82016-04-06 21:19:33 +00006720 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyov8f856852017-07-11 22:23:00 +00006721 SyncScope::ID SSID = SyncScope::System;
Eli Friedmanf03bb262011-08-12 22:50:01 +00006722
6723 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00006724 isAtomic = true;
6725 Lex.Lex();
6726 }
6727
Chris Lattnerfbe910e2011-11-27 06:56:53 +00006728 bool isVolatile = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00006729 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00006730 isVolatile = true;
6731 Lex.Lex();
6732 }
6733
Chris Lattnerdf986172009-01-02 07:01:27 +00006734 if (ParseTypeAndValue(Val, Loc, PFS) ||
6735 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00006736 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Konstantin Zhuravlyov8f856852017-07-11 22:23:00 +00006737 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00006738 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00006739 return true;
Devang Patelf633a062009-09-17 23:04:48 +00006740
Duncan Sands1df98592010-02-16 11:11:14 +00006741 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00006742 return Error(PtrLoc, "store operand must be a pointer");
6743 if (!Val->getType()->isFirstClassType())
6744 return Error(Loc, "store operand must be a first class value");
6745 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6746 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman21006d42011-08-09 23:02:53 +00006747 if (isAtomic && !Alignment)
6748 return Error(Loc, "atomic store must have explicit non-zero alignment");
JF Bastienb36d1a82016-04-06 21:19:33 +00006749 if (Ordering == AtomicOrdering::Acquire ||
6750 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman21006d42011-08-09 23:02:53 +00006751 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbara279bc32009-09-20 02:20:51 +00006752
Konstantin Zhuravlyov8f856852017-07-11 22:23:00 +00006753 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, SSID);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00006754 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00006755}
6756
Eli Friedmanff030482011-07-28 21:48:00 +00006757/// ParseCmpXchg
Tim Northover8f2a85e2014-06-13 14:24:07 +00006758/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6759/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedmanf03bb262011-08-12 22:50:01 +00006760int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanff030482011-07-28 21:48:00 +00006761 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6762 bool AteExtraComma = false;
JF Bastienb36d1a82016-04-06 21:19:33 +00006763 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6764 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyov8f856852017-07-11 22:23:00 +00006765 SyncScope::ID SSID = SyncScope::System;
Eli Friedmanf03bb262011-08-12 22:50:01 +00006766 bool isVolatile = false;
Tim Northover8f2a85e2014-06-13 14:24:07 +00006767 bool isWeak = false;
6768
6769 if (EatIfPresent(lltok::kw_weak))
6770 isWeak = true;
Eli Friedmanf03bb262011-08-12 22:50:01 +00006771
6772 if (EatIfPresent(lltok::kw_volatile))
6773 isVolatile = true;
6774
Eli Friedmanff030482011-07-28 21:48:00 +00006775 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6776 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6777 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6778 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6779 ParseTypeAndValue(New, NewLoc, PFS) ||
Konstantin Zhuravlyov8f856852017-07-11 22:23:00 +00006780 ParseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
Tim Northoverca396e32014-03-11 10:48:52 +00006781 ParseOrdering(FailureOrdering))
Eli Friedmanff030482011-07-28 21:48:00 +00006782 return true;
6783
JF Bastienb36d1a82016-04-06 21:19:33 +00006784 if (SuccessOrdering == AtomicOrdering::Unordered ||
6785 FailureOrdering == AtomicOrdering::Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00006786 return TokError("cmpxchg cannot be unordered");
JF Bastienb36d1a82016-04-06 21:19:33 +00006787 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6788 return TokError("cmpxchg failure argument shall be no stronger than the "
6789 "success argument");
6790 if (FailureOrdering == AtomicOrdering::Release ||
6791 FailureOrdering == AtomicOrdering::AcquireRelease)
6792 return TokError(
6793 "cmpxchg failure ordering cannot include release semantics");
Eli Friedmanff030482011-07-28 21:48:00 +00006794 if (!Ptr->getType()->isPointerTy())
6795 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6796 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6797 return Error(CmpLoc, "compare value and pointer type do not match");
6798 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6799 return Error(NewLoc, "new value and pointer type do not match");
Philip Reames3dbdebc2016-02-19 00:06:41 +00006800 if (!New->getType()->isFirstClassType())
6801 return Error(NewLoc, "cmpxchg operand must be a first class value");
Tim Northover8f2a85e2014-06-13 14:24:07 +00006802 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
Konstantin Zhuravlyov8f856852017-07-11 22:23:00 +00006803 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, SSID);
Eli Friedmanff030482011-07-28 21:48:00 +00006804 CXI->setVolatile(isVolatile);
Tim Northover8f2a85e2014-06-13 14:24:07 +00006805 CXI->setWeak(isWeak);
Eli Friedmanff030482011-07-28 21:48:00 +00006806 Inst = CXI;
6807 return AteExtraComma ? InstExtraComma : InstNormal;
6808}
6809
6810/// ParseAtomicRMW
Eli Friedmanf03bb262011-08-12 22:50:01 +00006811/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6812/// 'singlethread'? AtomicOrdering
6813int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanff030482011-07-28 21:48:00 +00006814 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6815 bool AteExtraComma = false;
JF Bastienb36d1a82016-04-06 21:19:33 +00006816 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyov8f856852017-07-11 22:23:00 +00006817 SyncScope::ID SSID = SyncScope::System;
Eli Friedmanf03bb262011-08-12 22:50:01 +00006818 bool isVolatile = false;
Eli Friedmanff030482011-07-28 21:48:00 +00006819 AtomicRMWInst::BinOp Operation;
Eli Friedmanf03bb262011-08-12 22:50:01 +00006820
6821 if (EatIfPresent(lltok::kw_volatile))
6822 isVolatile = true;
6823
Eli Friedmanff030482011-07-28 21:48:00 +00006824 switch (Lex.getKind()) {
6825 default: return TokError("expected binary operation in atomicrmw");
6826 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6827 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6828 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6829 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6830 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6831 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6832 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6833 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6834 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6835 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6836 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6837 }
6838 Lex.Lex(); // Eat the operation.
6839
6840 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6841 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6842 ParseTypeAndValue(Val, ValLoc, PFS) ||
Konstantin Zhuravlyov8f856852017-07-11 22:23:00 +00006843 ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
Eli Friedmanff030482011-07-28 21:48:00 +00006844 return true;
6845
JF Bastienb36d1a82016-04-06 21:19:33 +00006846 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00006847 return TokError("atomicrmw cannot be unordered");
6848 if (!Ptr->getType()->isPointerTy())
6849 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6850 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6851 return Error(ValLoc, "atomicrmw value and pointer type do not match");
Matt Arsenault9bda9a42018-10-03 02:37:15 +00006852
6853 if (!Val->getType()->isIntegerTy()) {
6854 return Error(ValLoc, "atomicrmw " +
6855 AtomicRMWInst::getOperationName(Operation) +
6856 " operand must be an integer");
6857 }
6858
Eli Friedmanff030482011-07-28 21:48:00 +00006859 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6860 if (Size < 8 || (Size & (Size - 1)))
6861 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6862 " integer");
6863
6864 AtomicRMWInst *RMWI =
Konstantin Zhuravlyov8f856852017-07-11 22:23:00 +00006865 new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID);
Eli Friedmanff030482011-07-28 21:48:00 +00006866 RMWI->setVolatile(isVolatile);
6867 Inst = RMWI;
6868 return AteExtraComma ? InstExtraComma : InstNormal;
6869}
6870
Eli Friedman47f35132011-07-25 23:16:38 +00006871/// ParseFence
6872/// ::= 'fence' 'singlethread'? AtomicOrdering
6873int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
JF Bastienb36d1a82016-04-06 21:19:33 +00006874 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyov8f856852017-07-11 22:23:00 +00006875 SyncScope::ID SSID = SyncScope::System;
6876 if (ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
Eli Friedman47f35132011-07-25 23:16:38 +00006877 return true;
6878
JF Bastienb36d1a82016-04-06 21:19:33 +00006879 if (Ordering == AtomicOrdering::Unordered)
Eli Friedman47f35132011-07-25 23:16:38 +00006880 return TokError("fence cannot be unordered");
JF Bastienb36d1a82016-04-06 21:19:33 +00006881 if (Ordering == AtomicOrdering::Monotonic)
Eli Friedman47f35132011-07-25 23:16:38 +00006882 return TokError("fence cannot be monotonic");
6883
Konstantin Zhuravlyov8f856852017-07-11 22:23:00 +00006884 Inst = new FenceInst(Context, Ordering, SSID);
Eli Friedman47f35132011-07-25 23:16:38 +00006885 return InstNormal;
6886}
6887
Chris Lattnerdf986172009-01-02 07:01:27 +00006888/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00006889/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00006890int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper0b6cb712014-04-15 06:32:26 +00006891 Value *Ptr = nullptr;
6892 Value *Val = nullptr;
Nadav Rotem16087692011-12-05 06:29:09 +00006893 LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00006894
Dan Gohmandcb40a32009-07-29 15:58:36 +00006895 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00006896
David Blaikie198d8ba2015-02-27 19:29:02 +00006897 Type *Ty = nullptr;
6898 LocTy ExplicitTypeLoc = Lex.getLoc();
6899 if (ParseType(Ty) ||
6900 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6901 ParseTypeAndValue(Ptr, Loc, PFS))
6902 return true;
6903
Eli Bendersky59eb5ee2013-04-22 17:03:42 +00006904 Type *BaseType = Ptr->getType();
6905 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6906 if (!BasePointerType)
Chris Lattnerdf986172009-01-02 07:01:27 +00006907 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00006908
David Blaikie22feef42015-03-09 23:08:44 +00006909 if (Ty != BasePointerType->getElementType())
6910 return Error(ExplicitTypeLoc,
6911 "explicit pointee type doesn't match operand's pointee type");
6912
Chris Lattnerdf986172009-01-02 07:01:27 +00006913 SmallVector<Value*, 16> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00006914 bool AteExtraComma = false;
Elena Demikhovsky43afab32015-07-09 07:42:48 +00006915 // GEP returns a vector of pointers if at least one of parameters is a vector.
6916 // All vector parameters should have the same vector width.
6917 unsigned GEPWidth = BaseType->isVectorTy() ?
6918 BaseType->getVectorNumElements() : 0;
6919
Chris Lattner3ed88ef2009-01-02 08:05:26 +00006920 while (EatIfPresent(lltok::comma)) {
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00006921 if (Lex.getKind() == lltok::MetadataVar) {
6922 AteExtraComma = true;
Devang Patel6225d642009-10-13 18:49:55 +00006923 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00006924 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00006925 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Craig Topper10600822017-07-09 07:04:00 +00006926 if (!Val->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00006927 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky43afab32015-07-09 07:42:48 +00006928
Nadav Rotem16087692011-12-05 06:29:09 +00006929 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky43afab32015-07-09 07:42:48 +00006930 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6931 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem16087692011-12-05 06:29:09 +00006932 return Error(EltLoc,
6933 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky43afab32015-07-09 07:42:48 +00006934 GEPWidth = ValNumEl;
Nadav Rotem16087692011-12-05 06:29:09 +00006935 }
Chris Lattnerdf986172009-01-02 07:01:27 +00006936 Indices.push_back(Val);
6937 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00006938
Craig Topper84bbcfe2015-08-01 22:20:21 +00006939 SmallPtrSet<Type*, 4> Visited;
David Blaikie72981cd2015-04-17 22:32:13 +00006940 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Bendersky59eb5ee2013-04-22 17:03:42 +00006941 return Error(Loc, "base element of getelementptr must be sized");
6942
David Blaikie72981cd2015-04-17 22:32:13 +00006943 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00006944 return Error(Loc, "invalid getelementptr indices");
David Blaikiebb939f02015-03-14 21:11:24 +00006945 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohmandd8004d2009-07-27 21:53:46 +00006946 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00006947 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00006948 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00006949}
6950
6951/// ParseExtractValue
6952/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00006953int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00006954 Value *Val; LocTy Loc;
6955 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00006956 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00006957 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00006958 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00006959 return true;
6960
Chris Lattnerfdfeb692010-02-12 20:49:41 +00006961 if (!Val->getType()->isAggregateType())
6962 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00006963
Jay Foadfc6d3a42011-07-13 10:26:04 +00006964 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00006965 return Error(Loc, "invalid indices for extractvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00006966 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00006967 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00006968}
6969
6970/// ParseInsertValue
6971/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00006972int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00006973 Value *Val0, *Val1; LocTy Loc0, Loc1;
6974 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00006975 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00006976 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6977 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6978 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00006979 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00006980 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00006981
Chris Lattnerfdfeb692010-02-12 20:49:41 +00006982 if (!Val0->getType()->isAggregateType())
6983 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00006984
David Majnemer94d09cb2015-02-11 07:43:58 +00006985 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6986 if (!IndexedType)
Chris Lattnerdf986172009-01-02 07:01:27 +00006987 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer94d09cb2015-02-11 07:43:58 +00006988 if (IndexedType != Val1->getType())
6989 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6990 getTypeString(Val1->getType()) + "' instead of '" +
6991 getTypeString(IndexedType) + "'");
Jay Foadfc6d3a42011-07-13 10:26:04 +00006992 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00006993 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00006994}
Nick Lewycky21cc4462009-04-04 07:22:01 +00006995
6996//===----------------------------------------------------------------------===//
6997// Embedded metadata.
6998//===----------------------------------------------------------------------===//
6999
7000/// ParseMDNodeVector
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +00007001/// ::= { Element (',' Element)* }
Nick Lewyckycb337992009-05-10 20:57:05 +00007002/// Element
7003/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smith1ef70ff2014-12-15 19:07:53 +00007004bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemerff3fa3d2014-12-11 20:44:09 +00007005 if (ParseToken(lltok::lbrace, "expected '{' here"))
7006 return true;
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +00007007
Dan Gohmanac809752010-07-13 19:33:27 +00007008 // Check for an empty list.
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +00007009 if (EatIfPresent(lltok::rbrace))
Dan Gohmanac809752010-07-13 19:33:27 +00007010 return false;
7011
Nick Lewycky21cc4462009-04-04 07:22:01 +00007012 do {
Chris Lattnera7352392009-12-30 04:42:57 +00007013 // Null is a special case since it is typeless.
7014 if (EatIfPresent(lltok::kw_null)) {
Craig Topper0b6cb712014-04-15 06:32:26 +00007015 Elts.push_back(nullptr);
Chris Lattnera7352392009-12-30 04:42:57 +00007016 continue;
Nick Lewyckycb337992009-05-10 20:57:05 +00007017 }
Michael Ilseman407a6162012-11-15 22:34:00 +00007018
Duncan P. N. Exon Smith1ef70ff2014-12-15 19:07:53 +00007019 Metadata *MD;
7020 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +00007021 return true;
Duncan P. N. Exon Smith1ef70ff2014-12-15 19:07:53 +00007022 Elts.push_back(MD);
Nick Lewycky21cc4462009-04-04 07:22:01 +00007023 } while (EatIfPresent(lltok::comma));
7024
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +00007025 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky21cc4462009-04-04 07:22:01 +00007026}
Duncan P. N. Exon Smith78388182014-08-19 21:30:15 +00007027
7028//===----------------------------------------------------------------------===//
7029// Use-list order directives.
7030//===----------------------------------------------------------------------===//
7031bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
7032 SMLoc Loc) {
7033 if (V->use_empty())
7034 return Error(Loc, "value has no uses");
7035
7036 unsigned NumUses = 0;
7037 SmallDenseMap<const Use *, unsigned, 16> Order;
7038 for (const Use &U : V->uses()) {
7039 if (++NumUses > Indexes.size())
7040 break;
7041 Order[&U] = Indexes[NumUses - 1];
7042 }
7043 if (NumUses < 2)
7044 return Error(Loc, "value only has one use");
7045 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
Vedant Kumar48fd38c2018-05-10 23:01:54 +00007046 return Error(Loc,
7047 "wrong number of indexes, expected " + Twine(V->getNumUses()));
Duncan P. N. Exon Smith78388182014-08-19 21:30:15 +00007048
7049 V->sortUseList([&](const Use &L, const Use &R) {
7050 return Order.lookup(&L) < Order.lookup(&R);
7051 });
7052 return false;
7053}
7054
7055/// ParseUseListOrderIndexes
7056/// ::= '{' uint32 (',' uint32)+ '}'
7057bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
7058 SMLoc Loc = Lex.getLoc();
7059 if (ParseToken(lltok::lbrace, "expected '{' here"))
7060 return true;
7061 if (Lex.getKind() == lltok::rbrace)
7062 return Lex.Error("expected non-empty list of uselistorder indexes");
7063
7064 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
7065 // indexes should be distinct numbers in the range [0, size-1], and should
7066 // not be in order.
7067 unsigned Offset = 0;
7068 unsigned Max = 0;
7069 bool IsOrdered = true;
7070 assert(Indexes.empty() && "Expected empty order vector");
7071 do {
7072 unsigned Index;
7073 if (ParseUInt32(Index))
7074 return true;
7075
7076 // Update consistency checks.
7077 Offset += Index - Indexes.size();
7078 Max = std::max(Max, Index);
7079 IsOrdered &= Index == Indexes.size();
7080
7081 Indexes.push_back(Index);
7082 } while (EatIfPresent(lltok::comma));
7083
7084 if (ParseToken(lltok::rbrace, "expected '}' here"))
7085 return true;
7086
7087 if (Indexes.size() < 2)
7088 return Error(Loc, "expected >= 2 uselistorder indexes");
7089 if (Offset != 0 || Max >= Indexes.size())
7090 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
7091 if (IsOrdered)
7092 return Error(Loc, "expected uselistorder indexes to change the order");
7093
7094 return false;
7095}
7096
7097/// ParseUseListOrder
7098/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
7099bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
7100 SMLoc Loc = Lex.getLoc();
7101 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
7102 return true;
7103
7104 Value *V;
7105 SmallVector<unsigned, 16> Indexes;
7106 if (ParseTypeAndValue(V, PFS) ||
7107 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
7108 ParseUseListOrderIndexes(Indexes))
7109 return true;
7110
7111 return sortUseListOrder(V, Indexes, Loc);
7112}
7113
7114/// ParseUseListOrderBB
7115/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
7116bool LLParser::ParseUseListOrderBB() {
7117 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
7118 SMLoc Loc = Lex.getLoc();
7119 Lex.Lex();
7120
7121 ValID Fn, Label;
7122 SmallVector<unsigned, 16> Indexes;
7123 if (ParseValID(Fn) ||
7124 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
7125 ParseValID(Label) ||
7126 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
7127 ParseUseListOrderIndexes(Indexes))
7128 return true;
7129
7130 // Check the function.
7131 GlobalValue *GV;
7132 if (Fn.Kind == ValID::t_GlobalName)
7133 GV = M->getNamedValue(Fn.StrVal);
7134 else if (Fn.Kind == ValID::t_GlobalID)
7135 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
7136 else
7137 return Error(Fn.Loc, "expected function name in uselistorder_bb");
7138 if (!GV)
7139 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
7140 auto *F = dyn_cast<Function>(GV);
7141 if (!F)
7142 return Error(Fn.Loc, "expected function name in uselistorder_bb");
7143 if (F->isDeclaration())
7144 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
7145
7146 // Check the basic block.
7147 if (Label.Kind == ValID::t_LocalID)
7148 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
7149 if (Label.Kind != ValID::t_LocalName)
7150 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
Mehdi Aminid1e3c5a2016-09-17 06:00:02 +00007151 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
Duncan P. N. Exon Smith78388182014-08-19 21:30:15 +00007152 if (!V)
7153 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
7154 if (!isa<BasicBlock>(V))
7155 return Error(Label.Loc, "expected basic block in uselistorder_bb");
7156
7157 return sortUseListOrder(V, Indexes, Loc);
7158}
Teresa Johnsonc6dda902018-06-26 13:56:49 +00007159
7160/// ModuleEntry
7161/// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
7162/// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
7163bool LLParser::ParseModuleEntry(unsigned ID) {
7164 assert(Lex.getKind() == lltok::kw_module);
7165 Lex.Lex();
7166
7167 std::string Path;
7168 if (ParseToken(lltok::colon, "expected ':' here") ||
7169 ParseToken(lltok::lparen, "expected '(' here") ||
7170 ParseToken(lltok::kw_path, "expected 'path' here") ||
7171 ParseToken(lltok::colon, "expected ':' here") ||
7172 ParseStringConstant(Path) ||
7173 ParseToken(lltok::comma, "expected ',' here") ||
7174 ParseToken(lltok::kw_hash, "expected 'hash' here") ||
7175 ParseToken(lltok::colon, "expected ':' here") ||
7176 ParseToken(lltok::lparen, "expected '(' here"))
7177 return true;
7178
7179 ModuleHash Hash;
7180 if (ParseUInt32(Hash[0]) || ParseToken(lltok::comma, "expected ',' here") ||
7181 ParseUInt32(Hash[1]) || ParseToken(lltok::comma, "expected ',' here") ||
7182 ParseUInt32(Hash[2]) || ParseToken(lltok::comma, "expected ',' here") ||
7183 ParseUInt32(Hash[3]) || ParseToken(lltok::comma, "expected ',' here") ||
7184 ParseUInt32(Hash[4]))
7185 return true;
7186
7187 if (ParseToken(lltok::rparen, "expected ')' here") ||
7188 ParseToken(lltok::rparen, "expected ')' here"))
7189 return true;
7190
7191 auto ModuleEntry = Index->addModule(Path, ID, Hash);
7192 ModuleIdMap[ID] = ModuleEntry->first();
7193
7194 return false;
7195}
7196
7197/// TypeIdEntry
7198/// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
7199bool LLParser::ParseTypeIdEntry(unsigned ID) {
7200 assert(Lex.getKind() == lltok::kw_typeid);
7201 Lex.Lex();
7202
7203 std::string Name;
7204 if (ParseToken(lltok::colon, "expected ':' here") ||
7205 ParseToken(lltok::lparen, "expected '(' here") ||
7206 ParseToken(lltok::kw_name, "expected 'name' here") ||
7207 ParseToken(lltok::colon, "expected ':' here") ||
7208 ParseStringConstant(Name))
7209 return true;
7210
7211 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
7212 if (ParseToken(lltok::comma, "expected ',' here") ||
7213 ParseTypeIdSummary(TIS) || ParseToken(lltok::rparen, "expected ')' here"))
7214 return true;
7215
7216 // Check if this ID was forward referenced, and if so, update the
7217 // corresponding GUIDs.
7218 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
7219 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
7220 for (auto TIDRef : FwdRefTIDs->second) {
7221 assert(!*TIDRef.first &&
7222 "Forward referenced type id GUID expected to be 0");
7223 *TIDRef.first = GlobalValue::getGUID(Name);
7224 }
7225 ForwardRefTypeIds.erase(FwdRefTIDs);
7226 }
7227
7228 return false;
7229}
7230
7231/// TypeIdSummary
7232/// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
7233bool LLParser::ParseTypeIdSummary(TypeIdSummary &TIS) {
7234 if (ParseToken(lltok::kw_summary, "expected 'summary' here") ||
7235 ParseToken(lltok::colon, "expected ':' here") ||
7236 ParseToken(lltok::lparen, "expected '(' here") ||
7237 ParseTypeTestResolution(TIS.TTRes))
7238 return true;
7239
7240 if (EatIfPresent(lltok::comma)) {
7241 // Expect optional wpdResolutions field
7242 if (ParseOptionalWpdResolutions(TIS.WPDRes))
7243 return true;
7244 }
7245
7246 if (ParseToken(lltok::rparen, "expected ')' here"))
7247 return true;
7248
7249 return false;
7250}
7251
7252/// TypeTestResolution
7253/// ::= 'typeTestRes' ':' '(' 'kind' ':'
7254/// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
7255/// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
7256/// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
7257/// [',' 'inlinesBits' ':' UInt64]? ')'
7258bool LLParser::ParseTypeTestResolution(TypeTestResolution &TTRes) {
7259 if (ParseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
7260 ParseToken(lltok::colon, "expected ':' here") ||
7261 ParseToken(lltok::lparen, "expected '(' here") ||
7262 ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7263 ParseToken(lltok::colon, "expected ':' here"))
7264 return true;
7265
7266 switch (Lex.getKind()) {
7267 case lltok::kw_unsat:
7268 TTRes.TheKind = TypeTestResolution::Unsat;
7269 break;
7270 case lltok::kw_byteArray:
7271 TTRes.TheKind = TypeTestResolution::ByteArray;
7272 break;
7273 case lltok::kw_inline:
7274 TTRes.TheKind = TypeTestResolution::Inline;
7275 break;
7276 case lltok::kw_single:
7277 TTRes.TheKind = TypeTestResolution::Single;
7278 break;
7279 case lltok::kw_allOnes:
7280 TTRes.TheKind = TypeTestResolution::AllOnes;
7281 break;
7282 default:
7283 return Error(Lex.getLoc(), "unexpected TypeTestResolution kind");
7284 }
7285 Lex.Lex();
7286
7287 if (ParseToken(lltok::comma, "expected ',' here") ||
7288 ParseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
7289 ParseToken(lltok::colon, "expected ':' here") ||
7290 ParseUInt32(TTRes.SizeM1BitWidth))
7291 return true;
7292
7293 // Parse optional fields
7294 while (EatIfPresent(lltok::comma)) {
7295 switch (Lex.getKind()) {
7296 case lltok::kw_alignLog2:
7297 Lex.Lex();
7298 if (ParseToken(lltok::colon, "expected ':'") ||
7299 ParseUInt64(TTRes.AlignLog2))
7300 return true;
7301 break;
7302 case lltok::kw_sizeM1:
7303 Lex.Lex();
7304 if (ParseToken(lltok::colon, "expected ':'") || ParseUInt64(TTRes.SizeM1))
7305 return true;
7306 break;
7307 case lltok::kw_bitMask: {
7308 unsigned Val;
7309 Lex.Lex();
7310 if (ParseToken(lltok::colon, "expected ':'") || ParseUInt32(Val))
7311 return true;
7312 assert(Val <= 0xff);
7313 TTRes.BitMask = (uint8_t)Val;
7314 break;
7315 }
7316 case lltok::kw_inlineBits:
7317 Lex.Lex();
7318 if (ParseToken(lltok::colon, "expected ':'") ||
7319 ParseUInt64(TTRes.InlineBits))
7320 return true;
7321 break;
7322 default:
7323 return Error(Lex.getLoc(), "expected optional TypeTestResolution field");
7324 }
7325 }
7326
7327 if (ParseToken(lltok::rparen, "expected ')' here"))
7328 return true;
7329
7330 return false;
7331}
7332
7333/// OptionalWpdResolutions
7334/// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
7335/// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
7336bool LLParser::ParseOptionalWpdResolutions(
7337 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
7338 if (ParseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
7339 ParseToken(lltok::colon, "expected ':' here") ||
7340 ParseToken(lltok::lparen, "expected '(' here"))
7341 return true;
7342
7343 do {
7344 uint64_t Offset;
7345 WholeProgramDevirtResolution WPDRes;
7346 if (ParseToken(lltok::lparen, "expected '(' here") ||
7347 ParseToken(lltok::kw_offset, "expected 'offset' here") ||
7348 ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(Offset) ||
7349 ParseToken(lltok::comma, "expected ',' here") || ParseWpdRes(WPDRes) ||
7350 ParseToken(lltok::rparen, "expected ')' here"))
7351 return true;
7352 WPDResMap[Offset] = WPDRes;
7353 } while (EatIfPresent(lltok::comma));
7354
7355 if (ParseToken(lltok::rparen, "expected ')' here"))
7356 return true;
7357
7358 return false;
7359}
7360
7361/// WpdRes
7362/// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
7363/// [',' OptionalResByArg]? ')'
7364/// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
7365/// ',' 'singleImplName' ':' STRINGCONSTANT ','
7366/// [',' OptionalResByArg]? ')'
7367/// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
7368/// [',' OptionalResByArg]? ')'
7369bool LLParser::ParseWpdRes(WholeProgramDevirtResolution &WPDRes) {
7370 if (ParseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
7371 ParseToken(lltok::colon, "expected ':' here") ||
7372 ParseToken(lltok::lparen, "expected '(' here") ||
7373 ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7374 ParseToken(lltok::colon, "expected ':' here"))
7375 return true;
7376
7377 switch (Lex.getKind()) {
7378 case lltok::kw_indir:
7379 WPDRes.TheKind = WholeProgramDevirtResolution::Indir;
7380 break;
7381 case lltok::kw_singleImpl:
7382 WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl;
7383 break;
7384 case lltok::kw_branchFunnel:
7385 WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel;
7386 break;
7387 default:
7388 return Error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
7389 }
7390 Lex.Lex();
7391
7392 // Parse optional fields
7393 while (EatIfPresent(lltok::comma)) {
7394 switch (Lex.getKind()) {
7395 case lltok::kw_singleImplName:
7396 Lex.Lex();
7397 if (ParseToken(lltok::colon, "expected ':' here") ||
7398 ParseStringConstant(WPDRes.SingleImplName))
7399 return true;
7400 break;
7401 case lltok::kw_resByArg:
7402 if (ParseOptionalResByArg(WPDRes.ResByArg))
7403 return true;
7404 break;
7405 default:
7406 return Error(Lex.getLoc(),
7407 "expected optional WholeProgramDevirtResolution field");
7408 }
7409 }
7410
7411 if (ParseToken(lltok::rparen, "expected ')' here"))
7412 return true;
7413
7414 return false;
7415}
7416
7417/// OptionalResByArg
7418/// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
7419/// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
7420/// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
7421/// 'virtualConstProp' )
7422/// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
7423/// [',' 'bit' ':' UInt32]? ')'
7424bool LLParser::ParseOptionalResByArg(
7425 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
7426 &ResByArg) {
7427 if (ParseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
7428 ParseToken(lltok::colon, "expected ':' here") ||
7429 ParseToken(lltok::lparen, "expected '(' here"))
7430 return true;
7431
7432 do {
7433 std::vector<uint64_t> Args;
7434 if (ParseArgs(Args) || ParseToken(lltok::comma, "expected ',' here") ||
7435 ParseToken(lltok::kw_byArg, "expected 'byArg here") ||
7436 ParseToken(lltok::colon, "expected ':' here") ||
7437 ParseToken(lltok::lparen, "expected '(' here") ||
7438 ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7439 ParseToken(lltok::colon, "expected ':' here"))
7440 return true;
7441
7442 WholeProgramDevirtResolution::ByArg ByArg;
7443 switch (Lex.getKind()) {
7444 case lltok::kw_indir:
7445 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir;
7446 break;
7447 case lltok::kw_uniformRetVal:
7448 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
7449 break;
7450 case lltok::kw_uniqueRetVal:
7451 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
7452 break;
7453 case lltok::kw_virtualConstProp:
7454 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
7455 break;
7456 default:
7457 return Error(Lex.getLoc(),
7458 "unexpected WholeProgramDevirtResolution::ByArg kind");
7459 }
7460 Lex.Lex();
7461
7462 // Parse optional fields
7463 while (EatIfPresent(lltok::comma)) {
7464 switch (Lex.getKind()) {
7465 case lltok::kw_info:
7466 Lex.Lex();
7467 if (ParseToken(lltok::colon, "expected ':' here") ||
7468 ParseUInt64(ByArg.Info))
7469 return true;
7470 break;
7471 case lltok::kw_byte:
7472 Lex.Lex();
7473 if (ParseToken(lltok::colon, "expected ':' here") ||
7474 ParseUInt32(ByArg.Byte))
7475 return true;
7476 break;
7477 case lltok::kw_bit:
7478 Lex.Lex();
7479 if (ParseToken(lltok::colon, "expected ':' here") ||
7480 ParseUInt32(ByArg.Bit))
7481 return true;
7482 break;
7483 default:
7484 return Error(Lex.getLoc(),
7485 "expected optional whole program devirt field");
7486 }
7487 }
7488
7489 if (ParseToken(lltok::rparen, "expected ')' here"))
7490 return true;
7491
7492 ResByArg[Args] = ByArg;
7493 } while (EatIfPresent(lltok::comma));
7494
7495 if (ParseToken(lltok::rparen, "expected ')' here"))
7496 return true;
7497
7498 return false;
7499}
7500
7501/// OptionalResByArg
7502/// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
7503bool LLParser::ParseArgs(std::vector<uint64_t> &Args) {
7504 if (ParseToken(lltok::kw_args, "expected 'args' here") ||
7505 ParseToken(lltok::colon, "expected ':' here") ||
7506 ParseToken(lltok::lparen, "expected '(' here"))
7507 return true;
7508
7509 do {
7510 uint64_t Val;
7511 if (ParseUInt64(Val))
7512 return true;
7513 Args.push_back(Val);
7514 } while (EatIfPresent(lltok::comma));
7515
7516 if (ParseToken(lltok::rparen, "expected ')' here"))
7517 return true;
7518
7519 return false;
7520}
7521
Benjamin Kramer114f0172019-01-12 18:36:22 +00007522static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
Eugene Leviantae9f7732018-11-23 10:54:51 +00007523
7524static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
7525 bool ReadOnly = Fwd->isReadOnly();
7526 *Fwd = Resolved;
7527 if (ReadOnly)
7528 Fwd->setReadOnly();
7529}
Teresa Johnsonc6dda902018-06-26 13:56:49 +00007530
7531/// Stores the given Name/GUID and associated summary into the Index.
7532/// Also updates any forward references to the associated entry ID.
7533void LLParser::AddGlobalValueToIndex(
7534 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
7535 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary) {
7536 // First create the ValueInfo utilizing the Name or GUID.
7537 ValueInfo VI;
7538 if (GUID != 0) {
7539 assert(Name.empty());
7540 VI = Index->getOrInsertValueInfo(GUID);
7541 } else {
7542 assert(!Name.empty());
7543 if (M) {
7544 auto *GV = M->getNamedValue(Name);
7545 assert(GV);
7546 VI = Index->getOrInsertValueInfo(GV);
7547 } else {
7548 assert(
7549 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
7550 "Need a source_filename to compute GUID for local");
7551 GUID = GlobalValue::getGUID(
7552 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
7553 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
7554 }
7555 }
7556
7557 // Add the summary if one was provided.
7558 if (Summary)
7559 Index->addGlobalValueSummary(VI, std::move(Summary));
7560
7561 // Resolve forward references from calls/refs
7562 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
7563 if (FwdRefVIs != ForwardRefValueInfos.end()) {
7564 for (auto VIRef : FwdRefVIs->second) {
Eugene Leviantae9f7732018-11-23 10:54:51 +00007565 assert(VIRef.first->getRef() == FwdVIRef &&
Teresa Johnsonc6dda902018-06-26 13:56:49 +00007566 "Forward referenced ValueInfo expected to be empty");
Eugene Leviantae9f7732018-11-23 10:54:51 +00007567 resolveFwdRef(VIRef.first, VI);
Teresa Johnsonc6dda902018-06-26 13:56:49 +00007568 }
7569 ForwardRefValueInfos.erase(FwdRefVIs);
7570 }
7571
7572 // Resolve forward references from aliases
7573 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
7574 if (FwdRefAliasees != ForwardRefAliasees.end()) {
7575 for (auto AliaseeRef : FwdRefAliasees->second) {
7576 assert(!AliaseeRef.first->hasAliasee() &&
7577 "Forward referencing alias already has aliasee");
7578 AliaseeRef.first->setAliasee(VI.getSummaryList().front().get());
7579 }
7580 ForwardRefAliasees.erase(FwdRefAliasees);
7581 }
7582
7583 // Save the associated ValueInfo for use in later references by ID.
7584 if (ID == NumberedValueInfos.size())
7585 NumberedValueInfos.push_back(VI);
7586 else {
7587 // Handle non-continuous numbers (to make test simplification easier).
7588 if (ID > NumberedValueInfos.size())
7589 NumberedValueInfos.resize(ID + 1);
7590 NumberedValueInfos[ID] = VI;
7591 }
7592}
7593
7594/// ParseGVEntry
7595/// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
7596/// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
7597/// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
7598bool LLParser::ParseGVEntry(unsigned ID) {
7599 assert(Lex.getKind() == lltok::kw_gv);
7600 Lex.Lex();
7601
7602 if (ParseToken(lltok::colon, "expected ':' here") ||
7603 ParseToken(lltok::lparen, "expected '(' here"))
7604 return true;
7605
7606 std::string Name;
7607 GlobalValue::GUID GUID = 0;
7608 switch (Lex.getKind()) {
7609 case lltok::kw_name:
7610 Lex.Lex();
7611 if (ParseToken(lltok::colon, "expected ':' here") ||
7612 ParseStringConstant(Name))
7613 return true;
7614 // Can't create GUID/ValueInfo until we have the linkage.
7615 break;
7616 case lltok::kw_guid:
7617 Lex.Lex();
7618 if (ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(GUID))
7619 return true;
7620 break;
7621 default:
7622 return Error(Lex.getLoc(), "expected name or guid tag");
7623 }
7624
7625 if (!EatIfPresent(lltok::comma)) {
7626 // No summaries. Wrap up.
7627 if (ParseToken(lltok::rparen, "expected ')' here"))
7628 return true;
7629 // This was created for a call to an external or indirect target.
7630 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
7631 // created for indirect calls with VP. A Name with no GUID came from
7632 // an external definition. We pass ExternalLinkage since that is only
7633 // used when the GUID must be computed from Name, and in that case
7634 // the symbol must have external linkage.
7635 AddGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
7636 nullptr);
7637 return false;
7638 }
7639
7640 // Have a list of summaries
7641 if (ParseToken(lltok::kw_summaries, "expected 'summaries' here") ||
7642 ParseToken(lltok::colon, "expected ':' here"))
7643 return true;
7644
7645 do {
7646 if (ParseToken(lltok::lparen, "expected '(' here"))
7647 return true;
7648 switch (Lex.getKind()) {
7649 case lltok::kw_function:
7650 if (ParseFunctionSummary(Name, GUID, ID))
7651 return true;
7652 break;
7653 case lltok::kw_variable:
7654 if (ParseVariableSummary(Name, GUID, ID))
7655 return true;
7656 break;
7657 case lltok::kw_alias:
7658 if (ParseAliasSummary(Name, GUID, ID))
7659 return true;
7660 break;
7661 default:
7662 return Error(Lex.getLoc(), "expected summary type");
7663 }
7664 if (ParseToken(lltok::rparen, "expected ')' here"))
7665 return true;
7666 } while (EatIfPresent(lltok::comma));
7667
7668 if (ParseToken(lltok::rparen, "expected ')' here"))
7669 return true;
7670
7671 return false;
7672}
7673
7674/// FunctionSummary
7675/// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
7676/// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
7677/// [',' OptionalTypeIdInfo]? [',' OptionalRefs]? ')'
7678bool LLParser::ParseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
7679 unsigned ID) {
7680 assert(Lex.getKind() == lltok::kw_function);
7681 Lex.Lex();
7682
7683 StringRef ModulePath;
7684 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
7685 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
7686 /*Live=*/false, /*IsLocal=*/false);
7687 unsigned InstCount;
7688 std::vector<FunctionSummary::EdgeTy> Calls;
7689 FunctionSummary::TypeIdInfo TypeIdInfo;
7690 std::vector<ValueInfo> Refs;
7691 // Default is all-zeros (conservative values).
7692 FunctionSummary::FFlags FFlags = {};
7693 if (ParseToken(lltok::colon, "expected ':' here") ||
7694 ParseToken(lltok::lparen, "expected '(' here") ||
7695 ParseModuleReference(ModulePath) ||
7696 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) ||
7697 ParseToken(lltok::comma, "expected ',' here") ||
7698 ParseToken(lltok::kw_insts, "expected 'insts' here") ||
7699 ParseToken(lltok::colon, "expected ':' here") || ParseUInt32(InstCount))
7700 return true;
7701
7702 // Parse optional fields
7703 while (EatIfPresent(lltok::comma)) {
7704 switch (Lex.getKind()) {
7705 case lltok::kw_funcFlags:
7706 if (ParseOptionalFFlags(FFlags))
7707 return true;
7708 break;
7709 case lltok::kw_calls:
7710 if (ParseOptionalCalls(Calls))
7711 return true;
7712 break;
7713 case lltok::kw_typeIdInfo:
7714 if (ParseOptionalTypeIdInfo(TypeIdInfo))
7715 return true;
7716 break;
7717 case lltok::kw_refs:
7718 if (ParseOptionalRefs(Refs))
7719 return true;
7720 break;
7721 default:
7722 return Error(Lex.getLoc(), "expected optional function summary field");
7723 }
7724 }
7725
7726 if (ParseToken(lltok::rparen, "expected ')' here"))
7727 return true;
7728
7729 auto FS = llvm::make_unique<FunctionSummary>(
Easwaran Ramanf1f1adc2018-12-13 19:54:27 +00007730 GVFlags, InstCount, FFlags, /*EntryCount=*/0, std::move(Refs),
7731 std::move(Calls), std::move(TypeIdInfo.TypeTests),
Teresa Johnsonc6dda902018-06-26 13:56:49 +00007732 std::move(TypeIdInfo.TypeTestAssumeVCalls),
7733 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
7734 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
7735 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls));
7736
7737 FS->setModulePath(ModulePath);
7738
7739 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
7740 ID, std::move(FS));
7741
7742 return false;
7743}
7744
7745/// VariableSummary
7746/// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
7747/// [',' OptionalRefs]? ')'
7748bool LLParser::ParseVariableSummary(std::string Name, GlobalValue::GUID GUID,
7749 unsigned ID) {
7750 assert(Lex.getKind() == lltok::kw_variable);
7751 Lex.Lex();
7752
7753 StringRef ModulePath;
7754 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
7755 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
7756 /*Live=*/false, /*IsLocal=*/false);
Eugene Leviantae9f7732018-11-23 10:54:51 +00007757 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false);
Teresa Johnsonc6dda902018-06-26 13:56:49 +00007758 std::vector<ValueInfo> Refs;
7759 if (ParseToken(lltok::colon, "expected ':' here") ||
7760 ParseToken(lltok::lparen, "expected '(' here") ||
7761 ParseModuleReference(ModulePath) ||
Eugene Leviantae9f7732018-11-23 10:54:51 +00007762 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) ||
7763 ParseToken(lltok::comma, "expected ',' here") ||
7764 ParseGVarFlags(GVarFlags))
Teresa Johnsonc6dda902018-06-26 13:56:49 +00007765 return true;
7766
7767 // Parse optional refs field
7768 if (EatIfPresent(lltok::comma)) {
7769 if (ParseOptionalRefs(Refs))
7770 return true;
7771 }
7772
7773 if (ParseToken(lltok::rparen, "expected ')' here"))
7774 return true;
7775
Eugene Leviantae9f7732018-11-23 10:54:51 +00007776 auto GS =
7777 llvm::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
Teresa Johnsonc6dda902018-06-26 13:56:49 +00007778
7779 GS->setModulePath(ModulePath);
7780
7781 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
7782 ID, std::move(GS));
7783
7784 return false;
7785}
7786
7787/// AliasSummary
7788/// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
7789/// 'aliasee' ':' GVReference ')'
7790bool LLParser::ParseAliasSummary(std::string Name, GlobalValue::GUID GUID,
7791 unsigned ID) {
7792 assert(Lex.getKind() == lltok::kw_alias);
7793 LocTy Loc = Lex.getLoc();
7794 Lex.Lex();
7795
7796 StringRef ModulePath;
7797 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
7798 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
7799 /*Live=*/false, /*IsLocal=*/false);
7800 if (ParseToken(lltok::colon, "expected ':' here") ||
7801 ParseToken(lltok::lparen, "expected '(' here") ||
7802 ParseModuleReference(ModulePath) ||
7803 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) ||
7804 ParseToken(lltok::comma, "expected ',' here") ||
7805 ParseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
7806 ParseToken(lltok::colon, "expected ':' here"))
7807 return true;
7808
7809 ValueInfo AliaseeVI;
7810 unsigned GVId;
7811 if (ParseGVReference(AliaseeVI, GVId))
7812 return true;
7813
7814 if (ParseToken(lltok::rparen, "expected ')' here"))
7815 return true;
7816
7817 auto AS = llvm::make_unique<AliasSummary>(GVFlags);
7818
7819 AS->setModulePath(ModulePath);
7820
7821 // Record forward reference if the aliasee is not parsed yet.
Eugene Leviantae9f7732018-11-23 10:54:51 +00007822 if (AliaseeVI.getRef() == FwdVIRef) {
Teresa Johnsonc6dda902018-06-26 13:56:49 +00007823 auto FwdRef = ForwardRefAliasees.insert(
7824 std::make_pair(GVId, std::vector<std::pair<AliasSummary *, LocTy>>()));
7825 FwdRef.first->second.push_back(std::make_pair(AS.get(), Loc));
7826 } else
7827 AS->setAliasee(AliaseeVI.getSummaryList().front().get());
7828
7829 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
7830 ID, std::move(AS));
7831
7832 return false;
7833}
7834
7835/// Flag
7836/// ::= [0|1]
7837bool LLParser::ParseFlag(unsigned &Val) {
7838 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
7839 return TokError("expected integer");
7840 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
7841 Lex.Lex();
7842 return false;
7843}
7844
7845/// OptionalFFlags
7846/// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
7847/// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
7848/// [',' 'returnDoesNotAlias' ':' Flag]? ')'
Teresa Johnson645cd312018-11-06 19:41:35 +00007849/// [',' 'noInline' ':' Flag]? ')'
Teresa Johnsonc6dda902018-06-26 13:56:49 +00007850bool LLParser::ParseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
7851 assert(Lex.getKind() == lltok::kw_funcFlags);
7852 Lex.Lex();
7853
7854 if (ParseToken(lltok::colon, "expected ':' in funcFlags") |
7855 ParseToken(lltok::lparen, "expected '(' in funcFlags"))
7856 return true;
7857
7858 do {
7859 unsigned Val;
7860 switch (Lex.getKind()) {
7861 case lltok::kw_readNone:
7862 Lex.Lex();
7863 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
7864 return true;
7865 FFlags.ReadNone = Val;
7866 break;
7867 case lltok::kw_readOnly:
7868 Lex.Lex();
7869 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
7870 return true;
7871 FFlags.ReadOnly = Val;
7872 break;
7873 case lltok::kw_noRecurse:
7874 Lex.Lex();
7875 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
7876 return true;
7877 FFlags.NoRecurse = Val;
7878 break;
7879 case lltok::kw_returnDoesNotAlias:
7880 Lex.Lex();
7881 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
7882 return true;
7883 FFlags.ReturnDoesNotAlias = Val;
7884 break;
Teresa Johnson645cd312018-11-06 19:41:35 +00007885 case lltok::kw_noInline:
7886 Lex.Lex();
7887 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
7888 return true;
7889 FFlags.NoInline = Val;
7890 break;
Teresa Johnsonc6dda902018-06-26 13:56:49 +00007891 default:
7892 return Error(Lex.getLoc(), "expected function flag type");
7893 }
7894 } while (EatIfPresent(lltok::comma));
7895
7896 if (ParseToken(lltok::rparen, "expected ')' in funcFlags"))
7897 return true;
7898
7899 return false;
7900}
7901
7902/// OptionalCalls
7903/// := 'calls' ':' '(' Call [',' Call]* ')'
7904/// Call ::= '(' 'callee' ':' GVReference
7905/// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')'
7906bool LLParser::ParseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) {
7907 assert(Lex.getKind() == lltok::kw_calls);
7908 Lex.Lex();
7909
7910 if (ParseToken(lltok::colon, "expected ':' in calls") |
7911 ParseToken(lltok::lparen, "expected '(' in calls"))
7912 return true;
7913
7914 IdToIndexMapType IdToIndexMap;
7915 // Parse each call edge
7916 do {
7917 ValueInfo VI;
7918 if (ParseToken(lltok::lparen, "expected '(' in call") ||
7919 ParseToken(lltok::kw_callee, "expected 'callee' in call") ||
7920 ParseToken(lltok::colon, "expected ':'"))
7921 return true;
7922
7923 LocTy Loc = Lex.getLoc();
7924 unsigned GVId;
7925 if (ParseGVReference(VI, GVId))
7926 return true;
7927
7928 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
7929 unsigned RelBF = 0;
7930 if (EatIfPresent(lltok::comma)) {
7931 // Expect either hotness or relbf
7932 if (EatIfPresent(lltok::kw_hotness)) {
7933 if (ParseToken(lltok::colon, "expected ':'") || ParseHotness(Hotness))
7934 return true;
7935 } else {
7936 if (ParseToken(lltok::kw_relbf, "expected relbf") ||
7937 ParseToken(lltok::colon, "expected ':'") || ParseUInt32(RelBF))
7938 return true;
7939 }
7940 }
7941 // Keep track of the Call array index needing a forward reference.
7942 // We will save the location of the ValueInfo needing an update, but
7943 // can only do so once the std::vector is finalized.
Eugene Leviantae9f7732018-11-23 10:54:51 +00007944 if (VI.getRef() == FwdVIRef)
Teresa Johnsonc6dda902018-06-26 13:56:49 +00007945 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
7946 Calls.push_back(FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, RelBF)});
7947
7948 if (ParseToken(lltok::rparen, "expected ')' in call"))
7949 return true;
7950 } while (EatIfPresent(lltok::comma));
7951
7952 // Now that the Calls vector is finalized, it is safe to save the locations
7953 // of any forward GV references that need updating later.
7954 for (auto I : IdToIndexMap) {
7955 for (auto P : I.second) {
Eugene Leviantae9f7732018-11-23 10:54:51 +00007956 assert(Calls[P.first].first.getRef() == FwdVIRef &&
Teresa Johnsonc6dda902018-06-26 13:56:49 +00007957 "Forward referenced ValueInfo expected to be empty");
7958 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
7959 I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
7960 FwdRef.first->second.push_back(
7961 std::make_pair(&Calls[P.first].first, P.second));
7962 }
7963 }
7964
7965 if (ParseToken(lltok::rparen, "expected ')' in calls"))
7966 return true;
7967
7968 return false;
7969}
7970
7971/// Hotness
7972/// := ('unknown'|'cold'|'none'|'hot'|'critical')
7973bool LLParser::ParseHotness(CalleeInfo::HotnessType &Hotness) {
7974 switch (Lex.getKind()) {
7975 case lltok::kw_unknown:
7976 Hotness = CalleeInfo::HotnessType::Unknown;
7977 break;
7978 case lltok::kw_cold:
7979 Hotness = CalleeInfo::HotnessType::Cold;
7980 break;
7981 case lltok::kw_none:
7982 Hotness = CalleeInfo::HotnessType::None;
7983 break;
7984 case lltok::kw_hot:
7985 Hotness = CalleeInfo::HotnessType::Hot;
7986 break;
7987 case lltok::kw_critical:
7988 Hotness = CalleeInfo::HotnessType::Critical;
7989 break;
7990 default:
7991 return Error(Lex.getLoc(), "invalid call edge hotness");
7992 }
7993 Lex.Lex();
7994 return false;
7995}
7996
7997/// OptionalRefs
7998/// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
7999bool LLParser::ParseOptionalRefs(std::vector<ValueInfo> &Refs) {
8000 assert(Lex.getKind() == lltok::kw_refs);
8001 Lex.Lex();
8002
8003 if (ParseToken(lltok::colon, "expected ':' in refs") |
8004 ParseToken(lltok::lparen, "expected '(' in refs"))
8005 return true;
8006
Eugene Leviantae9f7732018-11-23 10:54:51 +00008007 struct ValueContext {
8008 ValueInfo VI;
8009 unsigned GVId;
8010 LocTy Loc;
8011 };
8012 std::vector<ValueContext> VContexts;
Teresa Johnsonc6dda902018-06-26 13:56:49 +00008013 // Parse each ref edge
8014 do {
Eugene Leviantae9f7732018-11-23 10:54:51 +00008015 ValueContext VC;
8016 VC.Loc = Lex.getLoc();
8017 if (ParseGVReference(VC.VI, VC.GVId))
Teresa Johnsonc6dda902018-06-26 13:56:49 +00008018 return true;
Eugene Leviantae9f7732018-11-23 10:54:51 +00008019 VContexts.push_back(VC);
8020 } while (EatIfPresent(lltok::comma));
Teresa Johnsonc6dda902018-06-26 13:56:49 +00008021
Eugene Leviantae9f7732018-11-23 10:54:51 +00008022 // Sort value contexts so that ones with readonly ValueInfo are at the end
8023 // of VContexts vector. This is needed to match immutableRefCount() behavior.
Eugene Leviant5ae36ee2018-11-23 11:28:58 +00008024 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
Eugene Leviantae9f7732018-11-23 10:54:51 +00008025 return VC1.VI.isReadOnly() < VC2.VI.isReadOnly();
8026 });
8027
8028 IdToIndexMapType IdToIndexMap;
8029 for (auto &VC : VContexts) {
Teresa Johnsonc6dda902018-06-26 13:56:49 +00008030 // Keep track of the Refs array index needing a forward reference.
8031 // We will save the location of the ValueInfo needing an update, but
8032 // can only do so once the std::vector is finalized.
Eugene Leviantae9f7732018-11-23 10:54:51 +00008033 if (VC.VI.getRef() == FwdVIRef)
8034 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
8035 Refs.push_back(VC.VI);
8036 }
Teresa Johnsonc6dda902018-06-26 13:56:49 +00008037
8038 // Now that the Refs vector is finalized, it is safe to save the locations
8039 // of any forward GV references that need updating later.
8040 for (auto I : IdToIndexMap) {
8041 for (auto P : I.second) {
Eugene Leviantae9f7732018-11-23 10:54:51 +00008042 assert(Refs[P.first].getRef() == FwdVIRef &&
Teresa Johnsonc6dda902018-06-26 13:56:49 +00008043 "Forward referenced ValueInfo expected to be empty");
8044 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
8045 I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
8046 FwdRef.first->second.push_back(std::make_pair(&Refs[P.first], P.second));
8047 }
8048 }
8049
8050 if (ParseToken(lltok::rparen, "expected ')' in refs"))
8051 return true;
8052
8053 return false;
8054}
8055
8056/// OptionalTypeIdInfo
8057/// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
8058/// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
8059/// [',' TypeCheckedLoadConstVCalls]? ')'
8060bool LLParser::ParseOptionalTypeIdInfo(
8061 FunctionSummary::TypeIdInfo &TypeIdInfo) {
8062 assert(Lex.getKind() == lltok::kw_typeIdInfo);
8063 Lex.Lex();
8064
8065 if (ParseToken(lltok::colon, "expected ':' here") ||
8066 ParseToken(lltok::lparen, "expected '(' in typeIdInfo"))
8067 return true;
8068
8069 do {
8070 switch (Lex.getKind()) {
8071 case lltok::kw_typeTests:
8072 if (ParseTypeTests(TypeIdInfo.TypeTests))
8073 return true;
8074 break;
8075 case lltok::kw_typeTestAssumeVCalls:
8076 if (ParseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
8077 TypeIdInfo.TypeTestAssumeVCalls))
8078 return true;
8079 break;
8080 case lltok::kw_typeCheckedLoadVCalls:
8081 if (ParseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
8082 TypeIdInfo.TypeCheckedLoadVCalls))
8083 return true;
8084 break;
8085 case lltok::kw_typeTestAssumeConstVCalls:
8086 if (ParseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
8087 TypeIdInfo.TypeTestAssumeConstVCalls))
8088 return true;
8089 break;
8090 case lltok::kw_typeCheckedLoadConstVCalls:
8091 if (ParseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
8092 TypeIdInfo.TypeCheckedLoadConstVCalls))
8093 return true;
8094 break;
8095 default:
8096 return Error(Lex.getLoc(), "invalid typeIdInfo list type");
8097 }
8098 } while (EatIfPresent(lltok::comma));
8099
8100 if (ParseToken(lltok::rparen, "expected ')' in typeIdInfo"))
8101 return true;
8102
8103 return false;
8104}
8105
8106/// TypeTests
8107/// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
8108/// [',' (SummaryID | UInt64)]* ')'
8109bool LLParser::ParseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
8110 assert(Lex.getKind() == lltok::kw_typeTests);
8111 Lex.Lex();
8112
8113 if (ParseToken(lltok::colon, "expected ':' here") ||
8114 ParseToken(lltok::lparen, "expected '(' in typeIdInfo"))
8115 return true;
8116
8117 IdToIndexMapType IdToIndexMap;
8118 do {
8119 GlobalValue::GUID GUID = 0;
8120 if (Lex.getKind() == lltok::SummaryID) {
8121 unsigned ID = Lex.getUIntVal();
8122 LocTy Loc = Lex.getLoc();
8123 // Keep track of the TypeTests array index needing a forward reference.
8124 // We will save the location of the GUID needing an update, but
8125 // can only do so once the std::vector is finalized.
8126 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
8127 Lex.Lex();
8128 } else if (ParseUInt64(GUID))
8129 return true;
8130 TypeTests.push_back(GUID);
8131 } while (EatIfPresent(lltok::comma));
8132
8133 // Now that the TypeTests vector is finalized, it is safe to save the
8134 // locations of any forward GV references that need updating later.
8135 for (auto I : IdToIndexMap) {
8136 for (auto P : I.second) {
8137 assert(TypeTests[P.first] == 0 &&
8138 "Forward referenced type id GUID expected to be 0");
8139 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
8140 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
8141 FwdRef.first->second.push_back(
8142 std::make_pair(&TypeTests[P.first], P.second));
8143 }
8144 }
8145
8146 if (ParseToken(lltok::rparen, "expected ')' in typeIdInfo"))
8147 return true;
8148
8149 return false;
8150}
8151
8152/// VFuncIdList
8153/// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
8154bool LLParser::ParseVFuncIdList(
8155 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
8156 assert(Lex.getKind() == Kind);
8157 Lex.Lex();
8158
8159 if (ParseToken(lltok::colon, "expected ':' here") ||
8160 ParseToken(lltok::lparen, "expected '(' here"))
8161 return true;
8162
8163 IdToIndexMapType IdToIndexMap;
8164 do {
8165 FunctionSummary::VFuncId VFuncId;
8166 if (ParseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
8167 return true;
8168 VFuncIdList.push_back(VFuncId);
8169 } while (EatIfPresent(lltok::comma));
8170
8171 if (ParseToken(lltok::rparen, "expected ')' here"))
8172 return true;
8173
8174 // Now that the VFuncIdList vector is finalized, it is safe to save the
8175 // locations of any forward GV references that need updating later.
8176 for (auto I : IdToIndexMap) {
8177 for (auto P : I.second) {
8178 assert(VFuncIdList[P.first].GUID == 0 &&
8179 "Forward referenced type id GUID expected to be 0");
8180 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
8181 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
8182 FwdRef.first->second.push_back(
8183 std::make_pair(&VFuncIdList[P.first].GUID, P.second));
8184 }
8185 }
8186
8187 return false;
8188}
8189
8190/// ConstVCallList
8191/// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
8192bool LLParser::ParseConstVCallList(
8193 lltok::Kind Kind,
8194 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
8195 assert(Lex.getKind() == Kind);
8196 Lex.Lex();
8197
8198 if (ParseToken(lltok::colon, "expected ':' here") ||
8199 ParseToken(lltok::lparen, "expected '(' here"))
8200 return true;
8201
8202 IdToIndexMapType IdToIndexMap;
8203 do {
8204 FunctionSummary::ConstVCall ConstVCall;
8205 if (ParseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
8206 return true;
8207 ConstVCallList.push_back(ConstVCall);
8208 } while (EatIfPresent(lltok::comma));
8209
8210 if (ParseToken(lltok::rparen, "expected ')' here"))
8211 return true;
8212
8213 // Now that the ConstVCallList vector is finalized, it is safe to save the
8214 // locations of any forward GV references that need updating later.
8215 for (auto I : IdToIndexMap) {
8216 for (auto P : I.second) {
8217 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
8218 "Forward referenced type id GUID expected to be 0");
8219 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
8220 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
8221 FwdRef.first->second.push_back(
8222 std::make_pair(&ConstVCallList[P.first].VFunc.GUID, P.second));
8223 }
8224 }
8225
8226 return false;
8227}
8228
8229/// ConstVCall
Teresa Johnsond64c9dd2018-08-14 01:49:33 +00008230/// ::= '(' VFuncId ',' Args ')'
Teresa Johnsonc6dda902018-06-26 13:56:49 +00008231bool LLParser::ParseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
8232 IdToIndexMapType &IdToIndexMap, unsigned Index) {
Teresa Johnsond64c9dd2018-08-14 01:49:33 +00008233 if (ParseToken(lltok::lparen, "expected '(' here") ||
8234 ParseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
8235 return true;
8236
8237 if (EatIfPresent(lltok::comma))
8238 if (ParseArgs(ConstVCall.Args))
8239 return true;
8240
8241 if (ParseToken(lltok::rparen, "expected ')' here"))
Teresa Johnsonc6dda902018-06-26 13:56:49 +00008242 return true;
8243
8244 return false;
8245}
8246
8247/// VFuncId
8248/// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
8249/// 'offset' ':' UInt64 ')'
8250bool LLParser::ParseVFuncId(FunctionSummary::VFuncId &VFuncId,
8251 IdToIndexMapType &IdToIndexMap, unsigned Index) {
8252 assert(Lex.getKind() == lltok::kw_vFuncId);
8253 Lex.Lex();
8254
8255 if (ParseToken(lltok::colon, "expected ':' here") ||
8256 ParseToken(lltok::lparen, "expected '(' here"))
8257 return true;
8258
8259 if (Lex.getKind() == lltok::SummaryID) {
8260 VFuncId.GUID = 0;
8261 unsigned ID = Lex.getUIntVal();
8262 LocTy Loc = Lex.getLoc();
8263 // Keep track of the array index needing a forward reference.
8264 // We will save the location of the GUID needing an update, but
8265 // can only do so once the caller's std::vector is finalized.
8266 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
8267 Lex.Lex();
8268 } else if (ParseToken(lltok::kw_guid, "expected 'guid' here") ||
8269 ParseToken(lltok::colon, "expected ':' here") ||
8270 ParseUInt64(VFuncId.GUID))
8271 return true;
8272
8273 if (ParseToken(lltok::comma, "expected ',' here") ||
8274 ParseToken(lltok::kw_offset, "expected 'offset' here") ||
8275 ParseToken(lltok::colon, "expected ':' here") ||
8276 ParseUInt64(VFuncId.Offset) ||
8277 ParseToken(lltok::rparen, "expected ')' here"))
8278 return true;
8279
8280 return false;
8281}
8282
8283/// GVFlags
8284/// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
8285/// 'notEligibleToImport' ':' Flag ',' 'live' ':' Flag ','
8286/// 'dsoLocal' ':' Flag ')'
8287bool LLParser::ParseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
8288 assert(Lex.getKind() == lltok::kw_flags);
8289 Lex.Lex();
8290
8291 bool HasLinkage;
8292 if (ParseToken(lltok::colon, "expected ':' here") ||
8293 ParseToken(lltok::lparen, "expected '(' here") ||
8294 ParseToken(lltok::kw_linkage, "expected 'linkage' here") ||
8295 ParseToken(lltok::colon, "expected ':' here"))
8296 return true;
8297
8298 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
8299 assert(HasLinkage && "Linkage not optional in summary entry");
8300 Lex.Lex();
8301
8302 unsigned Flag;
8303 if (ParseToken(lltok::comma, "expected ',' here") ||
8304 ParseToken(lltok::kw_notEligibleToImport,
8305 "expected 'notEligibleToImport' here") ||
8306 ParseToken(lltok::colon, "expected ':' here") || ParseFlag(Flag))
8307 return true;
8308 GVFlags.NotEligibleToImport = Flag;
8309
8310 if (ParseToken(lltok::comma, "expected ',' here") ||
8311 ParseToken(lltok::kw_live, "expected 'live' here") ||
8312 ParseToken(lltok::colon, "expected ':' here") || ParseFlag(Flag))
8313 return true;
8314 GVFlags.Live = Flag;
8315
8316 if (ParseToken(lltok::comma, "expected ',' here") ||
8317 ParseToken(lltok::kw_dsoLocal, "expected 'dsoLocal' here") ||
8318 ParseToken(lltok::colon, "expected ':' here") || ParseFlag(Flag))
8319 return true;
8320 GVFlags.DSOLocal = Flag;
8321
8322 if (ParseToken(lltok::rparen, "expected ')' here"))
8323 return true;
8324
8325 return false;
8326}
8327
Eugene Leviantae9f7732018-11-23 10:54:51 +00008328/// GVarFlags
8329/// ::= 'varFlags' ':' '(' 'readonly' ':' Flag ')'
8330bool LLParser::ParseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
8331 assert(Lex.getKind() == lltok::kw_varFlags);
8332 Lex.Lex();
8333
8334 unsigned Flag;
8335 if (ParseToken(lltok::colon, "expected ':' here") ||
8336 ParseToken(lltok::lparen, "expected '(' here") ||
8337 ParseToken(lltok::kw_readonly, "expected 'readonly' here") ||
8338 ParseToken(lltok::colon, "expected ':' here"))
8339 return true;
8340
8341 ParseFlag(Flag);
8342 GVarFlags.ReadOnly = Flag;
8343
8344 if (ParseToken(lltok::rparen, "expected ')' here"))
8345 return true;
8346 return false;
8347}
8348
Teresa Johnsonc6dda902018-06-26 13:56:49 +00008349/// ModuleReference
8350/// ::= 'module' ':' UInt
8351bool LLParser::ParseModuleReference(StringRef &ModulePath) {
8352 // Parse module id.
8353 if (ParseToken(lltok::kw_module, "expected 'module' here") ||
8354 ParseToken(lltok::colon, "expected ':' here") ||
8355 ParseToken(lltok::SummaryID, "expected module ID"))
8356 return true;
8357
8358 unsigned ModuleID = Lex.getUIntVal();
8359 auto I = ModuleIdMap.find(ModuleID);
8360 // We should have already parsed all module IDs
8361 assert(I != ModuleIdMap.end());
8362 ModulePath = I->second;
8363 return false;
8364}
8365
8366/// GVReference
8367/// ::= SummaryID
8368bool LLParser::ParseGVReference(ValueInfo &VI, unsigned &GVId) {
Eugene Leviantae9f7732018-11-23 10:54:51 +00008369 bool ReadOnly = EatIfPresent(lltok::kw_readonly);
Teresa Johnsonc6dda902018-06-26 13:56:49 +00008370 if (ParseToken(lltok::SummaryID, "expected GV ID"))
8371 return true;
8372
8373 GVId = Lex.getUIntVal();
Teresa Johnsonc6dda902018-06-26 13:56:49 +00008374 // Check if we already have a VI for this GV
8375 if (GVId < NumberedValueInfos.size()) {
Eugene Leviantae9f7732018-11-23 10:54:51 +00008376 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
Teresa Johnsonc6dda902018-06-26 13:56:49 +00008377 VI = NumberedValueInfos[GVId];
8378 } else
8379 // We will create a forward reference to the stored location.
Eugene Leviantae9f7732018-11-23 10:54:51 +00008380 VI = ValueInfo(false, FwdVIRef);
Teresa Johnsonc6dda902018-06-26 13:56:49 +00008381
Eugene Leviantae9f7732018-11-23 10:54:51 +00008382 if (ReadOnly)
8383 VI.setReadOnly();
Teresa Johnsonc6dda902018-06-26 13:56:49 +00008384 return false;
8385}