blob: e2ee8d6c16773d495f73d4aad01a714e9109ed61 [file] [log] [blame]
Chris Lattnerac161bf2009-01-02 07:01:27 +00001//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the parser class for .ll files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "LLParser.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000015#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/None.h"
17#include "llvm/ADT/Optional.h"
David Blaikieadbda4b2015-08-03 20:08:41 +000018#include "llvm/ADT/STLExtras.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000019#include "llvm/ADT/SmallPtrSet.h"
Alex Lorenz8955f7d2015-06-23 17:10:10 +000020#include "llvm/AsmParser/SlotMapping.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000021#include "llvm/BinaryFormat/Dwarf.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000022#include "llvm/IR/Argument.h"
Chandler Carruth91065212014-03-05 10:34:14 +000023#include "llvm/IR/AutoUpgrade.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000024#include "llvm/IR/BasicBlock.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/CallingConv.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000026#include "llvm/IR/Comdat.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000028#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000030#include "llvm/IR/Function.h"
31#include "llvm/IR/GlobalIFunc.h"
32#include "llvm/IR/GlobalObject.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/InlineAsm.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000034#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/Instructions.h"
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +000036#include "llvm/IR/Intrinsics.h"
Manman Ren209b17c2013-09-28 00:22:27 +000037#include "llvm/IR/LLVMContext.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000038#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/Module.h"
40#include "llvm/IR/Operator.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000041#include "llvm/IR/Type.h"
42#include "llvm/IR/Value.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000043#include "llvm/IR/ValueSymbolTable.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000044#include "llvm/Support/Casting.h"
Torok Edwin56d06592009-07-11 20:10:48 +000045#include "llvm/Support/ErrorHandling.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000046#include "llvm/Support/MathExtras.h"
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +000047#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerac161bf2009-01-02 07:01:27 +000048#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000049#include <algorithm>
50#include <cassert>
51#include <cstring>
52#include <iterator>
53#include <vector>
54
Chris Lattnerac161bf2009-01-02 07:01:27 +000055using namespace llvm;
56
Chris Lattner229907c2011-07-18 04:54:35 +000057static std::string getTypeString(Type *T) {
Alp Tokere69170a2014-06-26 22:52:05 +000058 std::string Result;
59 raw_string_ostream Tmp(Result);
60 Tmp << *T;
61 return Tmp.str();
Chris Lattner0f214eb2011-06-18 21:18:23 +000062}
63
Chris Lattner3822f632009-01-02 08:05:26 +000064/// Run: module ::= toplevelentity*
Chris Lattnerad6f3352009-01-04 20:44:11 +000065bool LLParser::Run() {
Chris Lattner3822f632009-01-02 08:05:26 +000066 // Prime the lexer.
67 Lex.Lex();
68
Mehdi Amini50af49f2016-04-02 03:46:17 +000069 if (Context.shouldDiscardValueNames())
Mehdi Amini09b4a8d2016-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 Johnson63ee0e72018-06-26 13:56:49 +000074 return ParseTopLevelEntities() || ValidateEndOfModule() ||
75 ValidateEndOfIndex();
Chris Lattnerac161bf2009-01-02 07:01:27 +000076}
77
Alex Lorenz1de2acd2015-08-21 21:32:39 +000078bool LLParser::parseStandaloneConstantValue(Constant *&C,
79 const SlotMapping *Slots) {
80 restoreParsingState(Slots);
Alex Lorenzd2255952015-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 Colombetdafed5d2016-03-08 00:37:07 +000091bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
92 const SlotMapping *Slots) {
Quentin Colombet81e72b42016-03-07 22:09:05 +000093 restoreParsingState(Slots);
94 Lex.Lex();
95
Quentin Colombetdafed5d2016-03-08 00:37:07 +000096 Read = 0;
97 SMLoc Start = Lex.getLoc();
Quentin Colombet81e72b42016-03-07 22:09:05 +000098 Ty = nullptr;
99 if (ParseType(Ty))
100 return true;
Quentin Colombetdafed5d2016-03-08 00:37:07 +0000101 SMLoc End = Lex.getLoc();
102 Read = End.getPointer() - Start.getPointer();
103
Quentin Colombet81e72b42016-03-07 22:09:05 +0000104 return false;
105}
106
Alex Lorenz1de2acd2015-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 Lattnerac161bf2009-01-02 07:01:27 +0000120/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
121/// module.
122bool LLParser::ValidateEndOfModule() {
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000123 if (!M)
124 return false;
Bill Wendlingb32b0412013-02-08 06:32:06 +0000125 // Handle any function attribute group forward references.
Saleem Abdulrasool17995672016-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 Wendlingb32b0412013-02-08 06:32:06 +0000129 AttrBuilder B;
130
Saleem Abdulrasool17995672016-12-27 18:35:22 +0000131 for (const auto &Attr : Attrs)
132 B.merge(NumberedAttrBuilders[Attr]);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000133
134 if (Function *Fn = dyn_cast<Function>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000135 AttributeList AS = Fn->getAttributes();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000136 AttrBuilder FnAttrs(AS.getFnAttributes());
137 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendlingb32b0412013-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 Kleckner9d16fa02017-04-19 17:28:52 +0000148 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
149 AttributeSet::get(Context, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000150 Fn->setAttributes(AS);
151 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000152 AttributeList AS = CI->getAttributes();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000153 AttrBuilder FnAttrs(AS.getFnAttributes());
154 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendling59dce372013-02-12 10:13:06 +0000155 FnAttrs.merge(B);
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000156 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
157 AttributeSet::get(Context, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000158 CI->setAttributes(AS);
159 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000160 AttributeList AS = II->getAttributes();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000161 AttrBuilder FnAttrs(AS.getFnAttributes());
162 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendling59dce372013-02-12 10:13:06 +0000163 FnAttrs.merge(B);
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000164 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
165 AttributeSet::get(Context, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000166 II->setAttributes(AS);
Javed Absarf3d79042017-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 Wendlingb32b0412013-02-08 06:32:06 +0000171 } else {
172 llvm_unreachable("invalid object with forward attribute group reference");
173 }
174 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000175
Duncan P. N. Exon Smith17169902014-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 Ilseman26ee2b82012-11-15 22:34:00 +0000181
David Majnemer19b51052015-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 Lattnerb1ed91f2011-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 Dunbar7d6781b2009-09-20 02:20:51 +0000192
David Majnemerdad0a642014-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 Lattnerac161bf2009-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 Dunbar7d6781b2009-09-20 02:20:51 +0000202
Chris Lattnerac161bf2009-01-02 07:01:27 +0000203 if (!ForwardRefValIDs.empty())
204 return Error(ForwardRefValIDs.begin()->second.second,
205 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000206 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000207
Devang Pateld2541152009-07-08 19:23:54 +0000208 if (!ForwardRefMDNodes.empty())
209 return Error(ForwardRefMDNodes.begin()->second.second,
210 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000211 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000212
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000213 // Resolve metadata cycles.
David Majnemer19b51052015-02-11 07:43:56 +0000214 for (auto &N : NumberedMetadata) {
215 if (N.second && !N.second->isResolved())
216 N.second->resolveCycles();
217 }
Devang Pateld2541152009-07-08 19:23:54 +0000218
Mehdi Aminie4709272016-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 Smith29883862016-04-06 02:06:40 +0000226
Chris Lattnerac161bf2009-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 Smithac331fb2015-10-20 01:12:49 +0000229 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000230
Artur Pilipenko6c7a8ab2016-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 Prantla8b2ddb2017-10-02 18:31:29 +0000242 if (UpgradeDebugInfo)
243 llvm::UpgradeDebugInfo(*M);
Manman Ren8b4306c2013-12-02 21:29:56 +0000244
Manman Renb5d7ff42016-05-25 23:14:48 +0000245 UpgradeModuleFlags(*M);
Saleem Abdulrasool46a59fd2017-10-06 18:06:59 +0000246 UpgradeSectionAttributes(*M);
Manman Renb5d7ff42016-05-25 23:14:48 +0000247
Alex Lorenz8955f7d2015-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 Lorenz1de2acd2015-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 Lorenz8955f7d2015-06-23 17:10:10 +0000259
Chris Lattnerac161bf2009-01-02 07:01:27 +0000260 return false;
261}
262
Teresa Johnson63ee0e72018-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 Lattnerac161bf2009-01-02 07:01:27 +0000286//===----------------------------------------------------------------------===//
287// Top-Level Entities
288//===----------------------------------------------------------------------===//
289
290bool LLParser::ParseTopLevelEntities() {
Teresa Johnson63ee0e72018-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 Zelenko1804a772016-08-25 00:45:04 +0000311 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000312 switch (Lex.getKind()) {
313 default: return TokError("expected top-level entity");
314 case lltok::Eof: return false;
Chris Lattnerac161bf2009-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 Johnson83c517c2016-03-30 18:15:08 +0000319 case lltok::kw_source_filename:
320 if (ParseSourceFileName())
321 return true;
322 break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000323 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000324 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000325 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000326 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000327 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000328 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000329 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000330 case lltok::SummaryID:
331 if (ParseSummaryEntry())
332 return true;
333 break;
Bill Wendling63b88192013-02-06 06:52:58 +0000334 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Bill Wendlinga7c38772013-02-09 15:48:49 +0000335 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000336 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
337 case lltok::kw_uselistorder_bb:
Davide Italianof4e16612016-08-26 18:05:03 +0000338 if (ParseUseListOrderBB())
339 return true;
340 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000341 }
342 }
343}
344
Chris Lattnerac161bf2009-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 Dunbar7d6781b2009-09-20 02:20:51 +0000350
351 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000352 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
353 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000354
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000355 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-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 Lattner3822f632009-01-02 08:05:26 +0000364 std::string Str;
Chris Lattnerac161bf2009-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 Lattner3822f632009-01-02 08:05:26 +0000369 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
370 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000371 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000372 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000373 return false;
374 case lltok::kw_datalayout:
375 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000376 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
377 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000378 return true;
Yaxun Liuc00d81e2018-01-30 22:32:39 +0000379 if (DataLayoutStr.empty())
380 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000381 return false;
382 }
383}
384
Bill Wendling706d3d62012-11-28 08:41:48 +0000385/// toplevelentity
Teresa Johnson83c517c2016-03-30 18:15:08 +0000386/// ::= 'source_filename' '=' STRINGCONSTANT
387bool LLParser::ParseSourceFileName() {
388 assert(Lex.getKind() == lltok::kw_source_filename);
Teresa Johnson83c517c2016-03-30 18:15:08 +0000389 Lex.Lex();
390 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000391 ParseStringConstant(SourceFileName))
Teresa Johnson83c517c2016-03-30 18:15:08 +0000392 return true;
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000393 if (M)
394 M->setSourceFileName(SourceFileName);
Teresa Johnson83c517c2016-03-30 18:15:08 +0000395 return false;
396}
397
398/// toplevelentity
Bill Wendling706d3d62012-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 Gohman466876b2009-08-12 23:32:33 +0000420/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000421/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000422bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000423 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000424 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-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 Lattnerac161bf2009-01-02 07:01:27 +0000430
Craig Topper2617dcc2014-04-15 06:32:26 +0000431 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000432 if (ParseStructDefinition(TypeLoc, "",
433 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000434
Chris Lattnerb1ed91f2011-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 Lattnerac161bf2009-01-02 07:01:27 +0000441 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000442
Chris Lattnerac161bf2009-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 Lattner3822f632009-01-02 08:05:26 +0000451 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000452
Chris Lattner3822f632009-01-02 08:05:26 +0000453 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000454 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000455 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000456
Craig Topper2617dcc2014-04-15 06:32:26 +0000457 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000458 if (ParseStructDefinition(NameLoc, Name,
459 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000460
Chris Lattnerb1ed91f2011-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 Lattnerac161bf2009-01-02 07:01:27 +0000467 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000468
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000469 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000470}
471
Chris Lattnerac161bf2009-01-02 07:01:27 +0000472/// toplevelentity
473/// ::= 'declare' FunctionHeader
474bool LLParser::ParseDeclare() {
475 assert(Lex.getKind() == lltok::kw_declare);
476 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000477
Peter Collingbourne21521892016-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 Lattnerac161bf2009-01-02 07:01:27 +0000487 Function *F;
Peter Collingbourne21521892016-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 Lattnerac161bf2009-01-02 07:01:27 +0000493}
494
495/// toplevelentity
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000496/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
Chris Lattnerac161bf2009-01-02 07:01:27 +0000497bool LLParser::ParseDefine() {
498 assert(Lex.getKind() == lltok::kw_define);
499 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000500
Chris Lattnerac161bf2009-01-02 07:01:27 +0000501 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000502 return ParseFunctionHeader(F, true) ||
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000503 ParseOptionalFunctionMetadata(*F) ||
Chris Lattner3822f632009-01-02 08:05:26 +0000504 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000505}
506
Chris Lattner3822f632009-01-02 08:05:26 +0000507/// ParseGlobalType
508/// ::= 'constant'
509/// ::= 'global'
Chris Lattnerac161bf2009-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 Sandsd1de45a2009-02-10 16:24:55 +0000515 else {
516 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000517 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000518 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000519 Lex.Lex();
520 return false;
521}
522
Peter Collingbourne96efdd62016-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 Gohman466876b2009-08-12 23:32:33 +0000534/// ParseUnnamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000535/// OptionalVisibility (ALIAS | IFUNC) ...
Sean Fertilec70d28b2017-10-26 15:00:26 +0000536/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
537/// OptionalDLLStorageClass
Nico Rieck7157bb72014-01-14 15:22:47 +0000538/// ... -> global variable
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000539/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
Sean Fertilec70d28b2017-10-26 15:00:26 +0000540/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
541/// OptionalDLLStorageClass
Nico Rieck7157bb72014-01-14 15:22:47 +0000542/// ... -> global variable
Dan Gohman466876b2009-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 Kramerc7583112010-09-27 17:42:11 +0000552 Twine(VarID) + "'");
Dan Gohman466876b2009-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 Rieck7157bb72014-01-14 15:22:47 +0000560 unsigned Linkage, Visibility, DLLStorageClass;
Sean Fertilec70d28b2017-10-26 15:00:26 +0000561 bool DSOLocal;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000562 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000563 GlobalVariable::UnnamedAddr UnnamedAddr;
Sean Fertilec70d28b2017-10-26 15:00:26 +0000564 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
565 DSOLocal) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000566 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000567 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000568
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000569 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000570 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000571 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000572
573 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000574 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000575}
576
Chris Lattnerac161bf2009-01-02 07:01:27 +0000577/// ParseNamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000578/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
Sean Fertilec70d28b2017-10-26 15:00:26 +0000579/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
580/// OptionalVisibility OptionalDLLStorageClass
Nico Rieck7157bb72014-01-14 15:22:47 +0000581/// ... -> global variable
Chris Lattnerac161bf2009-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 Dunbar7d6781b2009-09-20 02:20:51 +0000587
Chris Lattnerac161bf2009-01-02 07:01:27 +0000588 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000589 unsigned Linkage, Visibility, DLLStorageClass;
Sean Fertilec70d28b2017-10-26 15:00:26 +0000590 bool DSOLocal;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000591 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000592 GlobalVariable::UnnamedAddr UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000593 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
Sean Fertilec70d28b2017-10-26 15:00:26 +0000594 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
595 DSOLocal) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000596 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000597 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000598
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000599 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000600 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000601 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000602
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000603 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000604 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000605}
606
David Majnemerdad0a642014-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 Patel8ff0f8d2009-07-20 19:00:08 +0000657// MDString:
658// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000659bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000660 std::string Str;
661 if (ParseStringConstant(Str)) return true;
Chris Lattner1797fc72009-12-29 21:53:55 +0000662 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000663 return false;
664}
665
666// MDNode:
667// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000668bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000669 // !{ ..., !42, ... }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000670 LocTy IDLoc = Lex.getLoc();
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000671 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000672 if (ParseUInt32(MID))
673 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000674
Chris Lattner8eff0152010-04-01 05:14:45 +0000675 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000676 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000677 Result = NumberedMetadata[MID];
678 return false;
679 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000680
Chris Lattner8eff0152010-04-01 05:14:45 +0000681 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000682 auto &FwdRef = ForwardRefMDNodes[MID];
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000683 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000684
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000685 Result = FwdRef.first.get();
686 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000687 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000688}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000689
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000690/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000691/// !foo = !{ !1, !2 }
692bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000693 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000694 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000695 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000696
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000697 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000698 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000699 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000700 return true;
701
Dan Gohman2637cc12010-07-21 23:38:33 +0000702 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000703 if (Lex.getKind() != lltok::rbrace)
704 do {
Craig Topper2617dcc2014-04-15 06:32:26 +0000705 MDNode *N = nullptr;
Reid Kleckner6d353342017-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 Gohman2637cc12010-07-21 23:38:33 +0000717 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000718 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000719
Rafael Espindolac7818fb2015-05-26 20:37:36 +0000720 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Patelbe626972009-07-29 00:34:02 +0000721}
722
Devang Patel39e64d42009-07-01 19:21:12 +0000723/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000724/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000725bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000726 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000727 Lex.Lex();
728 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000729
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000730 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000731 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-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 Smith090a19b2015-01-08 22:38:29 +0000739 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-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 Patele059ba6e2009-07-23 01:07:34 +0000745 return true;
746
Chris Lattnerfc58af22009-12-30 04:51:58 +0000747 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000748 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000749 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000750 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000751 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000752
Chris Lattnerfc58af22009-12-30 04:51:58 +0000753 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
754 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000755 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000756 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000757 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000758 }
759
Devang Patel39e64d42009-07-01 19:21:12 +0000760 return false;
761}
762
Teresa Johnson08d5b4e2018-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 Johnson63ee0e72018-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 Johnson08d5b4e2018-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 Johnson63ee0e72018-06-26 13:56:49 +0000799/// SummaryEntry
800/// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000801bool LLParser::ParseSummaryEntry() {
802 assert(Lex.getKind() == lltok::SummaryID);
Teresa Johnson63ee0e72018-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 Johnson08d5b4e2018-05-26 02:34:13 +0000808
809 Lex.Lex();
810 if (ParseToken(lltok::equal, "expected '=' here"))
811 return true;
812
Teresa Johnson63ee0e72018-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 Johnson08d5b4e2018-05-26 02:34:13 +0000829 return false;
830}
831
Duncan P. N. Exon Smithb80de102014-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 Espindolae4b02312018-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 Polukhina3d5b0b2016-04-05 08:47:51 +0000844/// parseIndirectSymbol:
Fangrui Songf78650a2018-07-30 19:41:25 +0000845/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
Sean Fertilec70d28b2017-10-26 15:00:26 +0000846/// OptionalVisibility OptionalDLLStorageClass
847/// OptionalThreadLocal OptionalUnnamedAddr
848// 'alias|ifunc' IndirectSymbol
Rafael Espindola6b238632014-05-16 19:35:39 +0000849///
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000850/// IndirectSymbol
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000851/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000852///
Eric Christopher536f0a92015-05-28 23:07:39 +0000853/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000854///
Sean Fertilec70d28b2017-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 Polukhina3d5b0b2016-04-05 08:47:51 +0000860 bool IsAlias;
861 if (Lex.getKind() == lltok::kw_alias)
862 IsAlias = true;
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000863 else if (Lex.getKind() == lltok::kw_ifunc)
864 IsAlias = false;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000865 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000866 llvm_unreachable("Not an alias or ifunc!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000867 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000868
Rafael Espindola78527052013-10-06 15:10:43 +0000869 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
870
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000871 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000872 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000873
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000874 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000875 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000876 "symbol with local linkage must have default visibility");
877
David Blaikie2f408302015-09-11 03:22:04 +0000878 Type *Ty;
879 LocTy ExplicitTypeLoc = Lex.getLoc();
880 if (ParseType(Ty) ||
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000881 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
David Blaikie2f408302015-09-11 03:22:04 +0000882 return true;
883
Rafael Espindola64c1e182014-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 Espindola6b238632014-05-16 19:35:39 +0000891 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000892 } else {
Rafael Espindola64c1e182014-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 Lattnerac161bf2009-01-02 07:01:27 +0000900 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000901
Rafael Espindola64c1e182014-06-03 02:41:57 +0000902 Type *AliaseeType = Aliasee->getType();
903 auto *PTy = dyn_cast<PointerType>(AliaseeType);
904 if (!PTy)
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000905 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
David Blaikie16a2f3e2015-09-14 18:01:59 +0000906 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000907
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000908 if (IsAlias && Ty != PTy->getElementType())
David Blaikie2f408302015-09-11 03:22:04 +0000909 return Error(
910 ExplicitTypeLoc,
911 "explicit pointee type doesn't match operand's pointee type");
912
Dmitry Polukhina3d5b0b2016-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 Collingbourne463ff6d2015-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 Lattnerac161bf2009-01-02 07:01:27 +0000936 // Okay, create the alias but do not insert it into the module yet.
Dmitry Polukhina3d5b0b2016-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 Polukhina1feff72016-04-07 12:32:19 +0000943 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
944 (GlobalValue::LinkageTypes)Linkage, Name,
945 Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000946 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000947 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000948 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000949 GA->setUnnamedAddr(UnnamedAddr);
Rafael Espindolae4b02312018-01-11 22:15:05 +0000950 maybeSetDSOLocal(DSOLocal, *GA);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000951
Rafael Espindola54fc2982015-06-17 17:53:31 +0000952 if (Name.empty())
953 NumberedVals.push_back(GA.get());
954
Peter Collingbourne463ff6d2015-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 Dunbar7d6781b2009-09-20 02:20:51 +0000961
Chris Lattnerac161bf2009-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 Collingbourne463ff6d2015-11-25 02:54:07 +0000964 GVal->replaceAllUsesWith(GA.get());
965 GVal->eraseFromParent();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000966 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000967
Chris Lattnerac161bf2009-01-02 07:01:27 +0000968 // Insert into the module, we know its name won't collide now.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000969 if (IsAlias)
970 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
971 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000972 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000973 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000974
Rafael Espindolaaa273822014-05-09 21:49:17 +0000975 // The module owns this now
976 GA.release();
977
Chris Lattnerac161bf2009-01-02 07:01:27 +0000978 return false;
979}
980
981/// ParseGlobal
Sean Fertilec70d28b2017-10-26 15:00:26 +0000982/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
983/// OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000984/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Javed Absarf3d79042017-05-11 12:28:08 +0000985/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
Sean Fertilec70d28b2017-10-26 15:00:26 +0000986/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
987/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
988/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
989/// Const OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +0000990///
Eric Christopher536f0a92015-05-28 23:07:39 +0000991/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000992/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000993///
994bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
995 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000996 unsigned Visibility, unsigned DLLStorageClass,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000997 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000998 GlobalVariable::UnnamedAddr UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-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 Lattnerac161bf2009-01-02 07:01:27 +00001003 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +00001004 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +00001005 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001006 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001007
Craig Topper2617dcc2014-04-15 06:32:26 +00001008 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +00001009 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +00001010 ParseOptionalToken(lltok::kw_externally_initialized,
1011 IsExternallyInitialized,
1012 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001013 ParseGlobalType(IsConstant) ||
1014 ParseType(Ty, TyLoc))
1015 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001016
Chris Lattnerac161bf2009-01-02 07:01:27 +00001017 // If the linkage is specified and is external, then no initializer is
1018 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +00001019 Constant *Init = nullptr;
Rafael Espindola4787ba32016-05-11 13:51:39 +00001020 if (!HasLinkage ||
1021 !GlobalValue::isValidDeclarationLinkage(
1022 (GlobalValue::LinkageTypes)Linkage)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001023 if (ParseGlobalValue(Ty, Init))
1024 return true;
1025 }
1026
David Majnemer49b3d9b2015-02-16 08:41:08 +00001027 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +00001028 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001029
David Majnemer598bd052014-12-09 05:56:09 +00001030 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001031
1032 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +00001033 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +00001034 GVal = M->getNamedValue(Name);
1035 if (GVal) {
Peter Collingbourne463ff6d2015-11-25 02:54:07 +00001036 if (!ForwardRefVals.erase(Name))
Chris Lattnere38317f2009-10-25 23:22:50 +00001037 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00001038 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001039 } else {
David Blaikie9ebdc692015-09-21 21:07:50 +00001040 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00001041 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +00001042 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001043 ForwardRefValIDs.erase(I);
1044 }
1045 }
1046
David Majnemer598bd052014-12-09 05:56:09 +00001047 GlobalVariable *GV;
1048 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +00001049 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
1050 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001051 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001052 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +00001053 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001054 return Error(TyLoc,
1055 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001056
David Majnemer598bd052014-12-09 05:56:09 +00001057 GV = cast<GlobalVariable>(GVal);
1058
Chris Lattnerac161bf2009-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 Dunbar7d6781b2009-09-20 02:20:51 +00001065
Chris Lattnerac161bf2009-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 Espindolae4b02312018-01-11 22:15:05 +00001071 maybeSetDSOLocal(DSOLocal, *GV);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001072 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00001073 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +00001074 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001075 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +00001076 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001077
Chris Lattnerac161bf2009-01-02 07:01:27 +00001078 // Parse attributes on the global.
1079 while (Lex.getKind() == lltok::comma) {
1080 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001081
Chris Lattnerac161bf2009-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 Collingbournecceae7f2016-05-31 23:01:54 +00001091 } else if (Lex.getKind() == lltok::MetadataVar) {
1092 if (ParseGlobalObjectMetadataAttachment(*GV))
1093 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001094 } else {
David Majnemerdad0a642014-06-27 18:19:56 +00001095 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +00001096 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-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 Lattnerac161bf2009-01-02 07:01:27 +00001102 }
1103 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001104
Javed Absarf3d79042017-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 Lattnerac161bf2009-01-02 07:01:27 +00001115 return false;
1116}
1117
Bill Wendling63b88192013-02-06 06:52:58 +00001118/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +00001119/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +00001120bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +00001121 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +00001122 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +00001123 Lex.Lex();
1124
David Majnemerb39e22b2014-12-09 18:33:57 +00001125 if (Lex.getKind() != lltok::AttrGrpID)
1126 return TokError("expected attribute group id");
1127
Bill Wendling63b88192013-02-06 06:52:58 +00001128 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +00001129 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +00001130 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +00001131 Lex.Lex();
1132
1133 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +00001134 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00001135 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +00001136 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +00001137 ParseToken(lltok::rbrace, "expected end of attribute group"))
1138 return true;
1139
Bill Wendlingb32b0412013-02-08 06:32:06 +00001140 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +00001141 return Error(AttrGrpLoc, "attribute group has no attributes");
1142
1143 return false;
1144}
1145
Bill Wendling8b0321d2013-02-08 00:52:31 +00001146/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +00001147/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +00001148bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
1149 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +00001150 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +00001151 bool HaveError = false;
1152
1153 B.clear();
1154
Bill Wendling63b88192013-02-06 06:52:58 +00001155 while (true) {
1156 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +00001157 if (Token == lltok::kw_builtin)
1158 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +00001159 switch (Token) {
1160 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001161 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +00001162 return Error(Lex.getLoc(), "unterminated attribute group");
1163 case lltok::rbrace:
1164 // Finished.
1165 return false;
1166
Bill Wendlingb32b0412013-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 Wendling63b88192013-02-06 06:52:58 +00001183 // Target-dependent attributes:
1184 case lltok::StringConstant: {
Artur Pilipenko17376c42015-08-03 14:31:49 +00001185 if (ParseStringAttribute(B))
Bill Wendling63b88192013-02-06 06:52:58 +00001186 return true;
Bill Wendlingb1ea9802013-02-10 10:12:50 +00001187 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001188 }
1189
1190 // Target-independent attributes:
1191 case lltok::kw_align: {
Bill Wendlingc62789f2013-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 Wendling63b88192013-02-06 06:52:58 +00001195 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001196 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001197 Lex.Lex();
Bill Wendling8b0321d2013-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 Wendling63b88192013-02-06 06:52:58 +00001205 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001206 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001207 }
1208 case lltok::kw_alignstack: {
1209 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001210 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001211 Lex.Lex();
Bill Wendling8b0321d2013-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 Wendling63b88192013-02-06 06:52:58 +00001219 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001220 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001221 }
George Burgess IV278199f2016-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 Laevsky39d662f2015-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 Nagarajfb3f4902015-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 Laevsky39d662f2015-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 Simhonfdd72fd2018-03-17 13:29:46 +00001252 case lltok::kw_nocf_check: B.addAttribute(Attribute::NoCfCheck); break;
James Molloye6f87ca2015-11-06 10:32:53 +00001253 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001254 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
Matt Morehouse236cdaf2018-03-22 17:07:51 +00001255 case lltok::kw_optforfuzzing:
1256 B.addAttribute(Attribute::OptForFuzzing); break;
Igor Laevsky39d662f2015-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 Arsenaultb19b57e2017-04-28 20:25:27 +00001263 case lltok::kw_speculatable: B.addAttribute(Attribute::Speculatable); break;
Igor Laevsky39d662f2015-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 Tsyrklevichd17f61e2018-04-03 20:10:40 +00001269 case lltok::kw_shadowcallstack:
1270 B.addAttribute(Attribute::ShadowCallStack); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001271 case lltok::kw_sanitize_address:
1272 B.addAttribute(Attribute::SanitizeAddress); break;
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00001273 case lltok::kw_sanitize_hwaddress:
1274 B.addAttribute(Attribute::SanitizeHWAddress); break;
Igor Laevsky39d662f2015-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 Carruth664aa862018-09-04 12:38:00 +00001279 case lltok::kw_speculative_load_hardening:
1280 B.addAttribute(Attribute::SpeculativeLoadHardening);
1281 break;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001282 case lltok::kw_strictfp: B.addAttribute(Attribute::StrictFP); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001283 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001284 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling8b0321d2013-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 Finkelb0407ba2014-07-18 15:51:28 +00001295 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001296 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001297 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001298 case lltok::kw_nest:
1299 case lltok::kw_noalias:
1300 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001301 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001302 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001303 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001304 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001305 case lltok::kw_swiftself:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001306 HaveError |=
1307 Error(Lex.getLoc(),
1308 "invalid use of parameter-only attribute on a function");
1309 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001310 }
1311
1312 Lex.Lex();
1313 }
1314}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001315
1316//===----------------------------------------------------------------------===//
1317// GlobalValue Reference/Resolution Routines.
1318//===----------------------------------------------------------------------===//
1319
Karl Schimpf77729782015-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 Richardson6bcf2ba2018-08-23 09:25:17 +00001323 return Function::Create(FT, GlobalValue::ExternalWeakLinkage,
1324 PTy->getAddressSpace(), Name, M);
Karl Schimpf77729782015-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 Richardson6bcf2ba2018-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 Lattnerac161bf2009-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 Lattner229907c2011-07-18 04:54:35 +00001357GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001358 LocTy Loc, bool IsCall) {
Chris Lattner229907c2011-07-18 04:54:35 +00001359 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001360 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001361 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001362 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001363 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001364
Chris Lattnerac161bf2009-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 Dunbar7d6781b2009-09-20 02:20:51 +00001368
Chris Lattnerac161bf2009-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 Topper2617dcc2014-04-15 06:32:26 +00001371 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001372 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001373 if (I != ForwardRefVals.end())
1374 Val = I->second.first;
1375 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001376
Chris Lattnerac161bf2009-01-02 07:01:27 +00001377 // If we have the value in the symbol table or fwd-ref table, return it.
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001378 if (Val)
1379 return cast_or_null<GlobalValue>(
1380 checkValidVariableType(Loc, "@" + Name, Ty, Val, IsCall));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001381
Chris Lattnerac161bf2009-01-02 07:01:27 +00001382 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001383 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001384 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1385 return FwdVal;
1386}
1387
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001388GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc,
1389 bool IsCall) {
Chris Lattner229907c2011-07-18 04:54:35 +00001390 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001391 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001392 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001393 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001394 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001395
Craig Topper2617dcc2014-04-15 06:32:26 +00001396 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001397
Chris Lattnerac161bf2009-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 Topper2617dcc2014-04-15 06:32:26 +00001400 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001401 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001402 if (I != ForwardRefValIDs.end())
1403 Val = I->second.first;
1404 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001405
Chris Lattnerac161bf2009-01-02 07:01:27 +00001406 // If we have the value in the symbol table or fwd-ref table, return it.
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001407 if (Val)
1408 return cast_or_null<GlobalValue>(
1409 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val, IsCall));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001410
Chris Lattnerac161bf2009-01-02 07:01:27 +00001411 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001412 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001413 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1414 return FwdVal;
1415}
1416
Chris Lattnerac161bf2009-01-02 07:01:27 +00001417//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-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 Majnemerdad0a642014-06-27 18:19:56 +00001434//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-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 Lattner3822f632009-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 Kholodov5fcc4182016-09-06 10:46:28 +00001459bool LLParser::ParseUInt32(uint32_t &Val) {
Chris Lattnerac161bf2009-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 Finkelb0407ba2014-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 Wennborgcbe34b42012-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 Lattnerac161bf2009-01-02 07:01:27 +00001520
1521/// ParseOptionalAddrSpace
1522/// := /*empty*/
1523/// := 'addrspace' '(' uint32 ')'
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001524bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1525 AddrSpace = DefaultAS;
Chris Lattner3822f632009-01-02 08:05:26 +00001526 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001527 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001528 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001529 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001530 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001531}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001532
Artur Pilipenko17376c42015-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 Wendling34c2eb22012-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 Zelenko1804a772016-08-25 00:45:04 +00001552 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001553 lltok::Kind Token = Lex.getKind();
1554 switch (Token) {
1555 default: // End of attributes.
1556 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001557 case lltok::StringConstant: {
1558 if (ParseStringAttribute(B))
1559 return true;
1560 continue;
1561 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001562 case lltok::kw_align: {
1563 unsigned Alignment;
1564 if (ParseOptionalAlignment(Alignment))
1565 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001566 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001567 continue;
1568 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001569 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001570 case lltok::kw_dereferenceable: {
1571 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001572 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001573 return true;
1574 B.addDereferenceableAttr(Bytes);
1575 continue;
1576 }
Sanjoy Das31ea6d12015-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 Klecknera534a382013-12-19 02:14:12 +00001584 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-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 Lewyckyd52b1522014-05-20 01:23:40 +00001589 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-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 Linb8bd2322013-04-20 05:14:40 +00001592 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-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 Ren9bfd0d02016-04-01 21:41:15 +00001595 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
Manman Renf46262e2016-03-29 17:37:21 +00001596 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001597 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001598 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001599
Stephen Lin7577ed52013-04-20 13:16:13 +00001600 case lltok::kw_alignstack:
1601 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001602 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001603 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001604 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001605 case lltok::kw_jumptable:
Stephen Lin7577ed52013-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 Simhonfdd72fd2018-03-17 13:29:46 +00001615 case lltok::kw_nocf_check:
Stephen Lin7577ed52013-04-20 13:16:13 +00001616 case lltok::kw_nounwind:
Matt Morehouse236cdaf2018-03-22 17:07:51 +00001617 case lltok::kw_optforfuzzing:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001618 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001619 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001620 case lltok::kw_returns_twice:
1621 case lltok::kw_sanitize_address:
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00001622 case lltok::kw_sanitize_hwaddress:
Stephen Lin7577ed52013-04-20 13:16:13 +00001623 case lltok::kw_sanitize_memory:
1624 case lltok::kw_sanitize_thread:
Chandler Carruth664aa862018-09-04 12:38:00 +00001625 case lltok::kw_speculative_load_hardening:
Stephen Lin7577ed52013-04-20 13:16:13 +00001626 case lltok::kw_ssp:
1627 case lltok::kw_sspreq:
1628 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001629 case lltok::kw_safestack:
Vlad Tsyrklevichd17f61e2018-04-03 20:10:40 +00001630 case lltok::kw_shadowcallstack:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001631 case lltok::kw_strictfp:
Stephen Lin7577ed52013-04-20 13:16:13 +00001632 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001633 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1634 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001635 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001636
Bill Wendling34c2eb22012-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 Zelenko1804a772016-08-25 00:45:04 +00001647 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001648 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001649 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001650 default: // End of attributes.
1651 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001652 case lltok::StringConstant: {
1653 if (ParseStringAttribute(B))
1654 return true;
1655 continue;
1656 }
Hal Finkelb0407ba2014-07-18 15:51:28 +00001657 case lltok::kw_dereferenceable: {
1658 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001659 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001660 return true;
1661 B.addDereferenceableAttr(Bytes);
1662 continue;
1663 }
Sanjoy Das31ea6d12015-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 Pilipenko84bc62f2015-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 Wendling3d7b0b82012-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 Lewyckyd52b1522014-05-20 01:23:40 +00001680 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-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 Wendling0be9c402012-09-28 22:30:18 +00001683
Bill Wendling34c2eb22012-12-04 23:40:58 +00001684 // Error handling.
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001685 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001686 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001687 case lltok::kw_nest:
1688 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001689 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001690 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001691 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001692 case lltok::kw_swiftself:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001693 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001694 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001695
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001696 case lltok::kw_alignstack:
1697 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001698 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001699 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001700 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001701 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001702 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-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 Simhonfdd72fd2018-03-17 13:29:46 +00001712 case lltok::kw_nocf_check:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001713 case lltok::kw_nounwind:
Matt Morehouse236cdaf2018-03-22 17:07:51 +00001714 case lltok::kw_optforfuzzing:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001715 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001716 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001717 case lltok::kw_returns_twice:
1718 case lltok::kw_sanitize_address:
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00001719 case lltok::kw_sanitize_hwaddress:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001720 case lltok::kw_sanitize_memory:
1721 case lltok::kw_sanitize_thread:
Chandler Carruth664aa862018-09-04 12:38:00 +00001722 case lltok::kw_speculative_load_hardening:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001723 case lltok::kw_ssp:
1724 case lltok::kw_sspreq:
1725 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001726 case lltok::kw_safestack:
Vlad Tsyrklevichd17f61e2018-04-03 20:10:40 +00001727 case lltok::kw_shadowcallstack:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001728 case lltok::kw_strictfp:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001729 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001730 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001731 break;
Nick Lewyckyc2ec0722013-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 Wendling0be9c402012-09-28 22:30:18 +00001736 }
1737
Chris Lattnerac161bf2009-01-02 07:01:27 +00001738 Lex.Lex();
1739 }
1740}
1741
Rafael Espindolac6269912016-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 Lattnerac161bf2009-01-02 07:01:27 +00001773/// ParseOptionalLinkage
1774/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001775/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001776/// ::= 'internal'
1777/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001778/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001779/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001780/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001781/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001782/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001783/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001784/// ::= 'extern_weak'
1785/// ::= 'external'
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001786bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1787 unsigned &Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +00001788 unsigned &DLLStorageClass,
1789 bool &DSOLocal) {
Rafael Espindolac6269912016-05-10 17:16:45 +00001790 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1791 if (HasLinkage)
1792 Lex.Lex();
Sean Fertilec70d28b2017-10-26 15:00:26 +00001793 ParseOptionalDSOLocal(DSOLocal);
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001794 ParseOptionalVisibility(Visibility);
1795 ParseOptionalDLLStorageClass(DLLStorageClass);
Sean Fertilec70d28b2017-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 Lattnerac161bf2009-01-02 07:01:27 +00001801 return false;
1802}
1803
Sean Fertilec70d28b2017-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 Lattnerac161bf2009-01-02 07:01:27 +00001820/// ParseOptionalVisibility
1821/// ::= /*empty*/
1822/// ::= 'default'
1823/// ::= 'hidden'
1824/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001825///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001826void LLParser::ParseOptionalVisibility(unsigned &Res) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001827 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-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 Lattnerac161bf2009-01-02 07:01:27 +00001840 }
1841 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001842}
1843
Nico Rieck7157bb72014-01-14 15:22:47 +00001844/// ParseOptionalDLLStorageClass
1845/// ::= /*empty*/
1846/// ::= 'dllimport'
1847/// ::= 'dllexport'
1848///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001849void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
Nico Rieck7157bb72014-01-14 15:22:47 +00001850 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-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 Rieck7157bb72014-01-14 15:22:47 +00001860 }
1861 Lex.Lex();
Nico Rieck7157bb72014-01-14 15:22:47 +00001862}
1863
Chris Lattnerac161bf2009-01-02 07:01:27 +00001864/// ParseOptionalCallingConv
1865/// ::= /*empty*/
1866/// ::= 'ccc'
1867/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001868/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001869/// ::= 'coldcc'
1870/// ::= 'x86_stdcallcc'
1871/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001872/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001873/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001874/// ::= 'arm_apcscc'
1875/// ::= 'arm_aapcscc'
1876/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001877/// ::= 'msp430_intrcc'
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001878/// ::= 'avr_intrcc'
1879/// ::= 'avr_signalcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001880/// ::= 'ptx_kernel'
1881/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001882/// ::= 'spir_func'
1883/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001884/// ::= 'x86_64_sysvcc'
Martin Storsjo2f24e932017-07-17 20:05:19 +00001885/// ::= 'win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001886/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001887/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001888/// ::= 'preserve_mostcc'
1889/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001890/// ::= 'ghccc'
Manman Renf8bdd882016-04-05 22:41:47 +00001891/// ::= 'swiftcc'
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001892/// ::= 'x86_intrcc'
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001893/// ::= 'hhvmcc'
1894/// ::= 'hhvm_ccc'
Manman Ren19c7bbe2015-12-04 17:40:13 +00001895/// ::= 'cxx_fast_tlscc'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001896/// ::= 'amdgpu_vs'
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001897/// ::= 'amdgpu_ls'
Marek Olsaka302a7362017-05-02 15:41:10 +00001898/// ::= 'amdgpu_hs'
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001899/// ::= 'amdgpu_es'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001900/// ::= 'amdgpu_gs'
1901/// ::= 'amdgpu_ps'
1902/// ::= 'amdgpu_cs'
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001903/// ::= 'amdgpu_kernel'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001904/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001905///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001906bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001907 switch (Lex.getKind()) {
1908 default: CC = CallingConv::C; return false;
1909 case lltok::kw_ccc: CC = CallingConv::C; break;
1910 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1911 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1912 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1913 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Oren Ben Simhon92ccbf22016-10-13 07:53:43 +00001914 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001915 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001916 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001917 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1918 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1919 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001920 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001921 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1922 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001923 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1924 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001925 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1926 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001927 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001928 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
Martin Storsjo2f24e932017-07-17 20:05:19 +00001929 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001930 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001931 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001932 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1933 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001934 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Manman Renf8bdd882016-04-05 22:41:47 +00001935 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001936 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001937 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1938 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
Manman Ren19c7bbe2015-12-04 17:40:13 +00001939 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001940 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001941 case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break;
Marek Olsaka302a7362017-05-02 15:41:10 +00001942 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001943 case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001944 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1945 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1946 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001947 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001948 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001949 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001950 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001951 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001952 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001953
Chris Lattnerac161bf2009-01-02 07:01:27 +00001954 Lex.Lex();
1955 return false;
1956}
1957
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001958/// ParseMetadataAttachment
1959/// ::= !dbg !42
1960bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1961 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1962
1963 std::string Name = Lex.getStrVal();
1964 Kind = M->getMDKindID(Name);
1965 Lex.Lex();
1966
1967 return ParseMDNode(MD);
1968}
1969
Chris Lattner5c427632009-12-30 05:31:19 +00001970/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001971/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001972bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001973 do {
1974 if (Lex.getKind() != lltok::MetadataVar)
1975 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001976
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001977 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001978 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001979 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001980 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001981
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001982 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001983 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001984 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001985
Chris Lattner596760d2009-12-29 21:25:40 +00001986 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001987 } while (EatIfPresent(lltok::comma));
1988 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001989}
1990
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001991/// ParseGlobalObjectMetadataAttachment
1992/// ::= !dbg !57
1993bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1994 unsigned MDK;
1995 MDNode *N;
1996 if (ParseMetadataAttachment(MDK, N))
1997 return true;
1998
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001999 GO.addMetadata(MDK, *N);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00002000 return false;
2001}
2002
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00002003/// ParseOptionalFunctionMetadata
2004/// ::= (!dbg !57)*
2005bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
Peter Collingbournecceae7f2016-05-31 23:01:54 +00002006 while (Lex.getKind() == lltok::MetadataVar)
2007 if (ParseGlobalObjectMetadataAttachment(F))
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00002008 return true;
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00002009 return false;
2010}
2011
Chris Lattnerac161bf2009-01-02 07:01:27 +00002012/// ParseOptionalAlignment
2013/// ::= /* empty */
2014/// ::= 'align' 4
2015bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
2016 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00002017 if (!EatIfPresent(lltok::kw_align))
2018 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00002019 LocTy AlignLoc = Lex.getLoc();
2020 if (ParseUInt32(Alignment)) return true;
2021 if (!isPowerOf2_32(Alignment))
2022 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00002023 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00002024 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00002025 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002026}
2027
Sanjoy Das31ea6d12015-04-16 20:29:50 +00002028/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00002029/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00002030/// ::= AttrKind '(' 4 ')'
2031///
2032/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2033bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
2034 uint64_t &Bytes) {
2035 assert((AttrKind == lltok::kw_dereferenceable ||
2036 AttrKind == lltok::kw_dereferenceable_or_null) &&
2037 "contract!");
2038
Hal Finkelb0407ba2014-07-18 15:51:28 +00002039 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00002040 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00002041 return false;
2042 LocTy ParenLoc = Lex.getLoc();
2043 if (!EatIfPresent(lltok::lparen))
2044 return Error(ParenLoc, "expected '('");
2045 LocTy DerefLoc = Lex.getLoc();
2046 if (ParseUInt64(Bytes)) return true;
2047 ParenLoc = Lex.getLoc();
2048 if (!EatIfPresent(lltok::rparen))
2049 return Error(ParenLoc, "expected ')'");
2050 if (!Bytes)
2051 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
2052 return false;
2053}
2054
Chris Lattnerb2f39502009-12-30 05:44:30 +00002055/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002056/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00002057/// ::= ',' align 4
2058///
2059/// This returns with AteExtraComma set to true if it ate an excess comma at the
2060/// end.
2061bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
2062 bool &AteExtraComma) {
2063 AteExtraComma = false;
2064 while (EatIfPresent(lltok::comma)) {
2065 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00002066 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00002067 AteExtraComma = true;
2068 return false;
2069 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002070
Chris Lattner95b0ff42010-04-23 00:50:50 +00002071 if (Lex.getKind() != lltok::kw_align)
2072 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00002073
Chris Lattner95b0ff42010-04-23 00:50:50 +00002074 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00002075 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002076
Devang Patelea8a4b92009-09-17 23:04:48 +00002077 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002078}
2079
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002080/// ParseOptionalCommaAddrSpace
2081/// ::=
2082/// ::= ',' addrspace(1)
2083///
2084/// This returns with AteExtraComma set to true if it ate an excess comma at the
2085/// end.
2086bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace,
2087 LocTy &Loc,
2088 bool &AteExtraComma) {
2089 AteExtraComma = false;
2090 while (EatIfPresent(lltok::comma)) {
2091 // Metadata at the end is an early exit.
2092 if (Lex.getKind() == lltok::MetadataVar) {
2093 AteExtraComma = true;
2094 return false;
2095 }
2096
2097 Loc = Lex.getLoc();
2098 if (Lex.getKind() != lltok::kw_addrspace)
2099 return Error(Lex.getLoc(), "expected metadata or 'addrspace'");
2100
2101 if (ParseOptionalAddrSpace(AddrSpace))
2102 return true;
2103 }
2104
2105 return false;
2106}
2107
George Burgess IV278199f2016-04-12 01:05:35 +00002108bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2109 Optional<unsigned> &HowManyArg) {
2110 Lex.Lex();
2111
2112 auto StartParen = Lex.getLoc();
2113 if (!EatIfPresent(lltok::lparen))
2114 return Error(StartParen, "expected '('");
2115
2116 if (ParseUInt32(BaseSizeArg))
2117 return true;
2118
2119 if (EatIfPresent(lltok::comma)) {
2120 auto HowManyAt = Lex.getLoc();
2121 unsigned HowMany;
2122 if (ParseUInt32(HowMany))
2123 return true;
2124 if (HowMany == BaseSizeArg)
2125 return Error(HowManyAt,
2126 "'allocsize' indices can't refer to the same parameter");
2127 HowManyArg = HowMany;
2128 } else
2129 HowManyArg = None;
2130
2131 auto EndParen = Lex.getLoc();
2132 if (!EatIfPresent(lltok::rparen))
2133 return Error(EndParen, "expected ')'");
2134 return false;
2135}
2136
Eli Friedmanfee02c62011-07-25 23:16:38 +00002137/// ParseScopeAndOrdering
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002138/// if isAtomic: ::= SyncScope? AtomicOrdering
Eli Friedmanfee02c62011-07-25 23:16:38 +00002139/// else: ::=
2140///
2141/// This sets Scope and Ordering to the parsed values.
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002142bool LLParser::ParseScopeAndOrdering(bool isAtomic, SyncScope::ID &SSID,
Eli Friedmanfee02c62011-07-25 23:16:38 +00002143 AtomicOrdering &Ordering) {
2144 if (!isAtomic)
2145 return false;
2146
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002147 return ParseScope(SSID) || ParseOrdering(Ordering);
2148}
Tim Northovere94a5182014-03-11 10:48:52 +00002149
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002150/// ParseScope
2151/// ::= syncscope("singlethread" | "<target scope>")?
2152///
2153/// This sets synchronization scope ID to the ID of the parsed value.
2154bool LLParser::ParseScope(SyncScope::ID &SSID) {
2155 SSID = SyncScope::System;
2156 if (EatIfPresent(lltok::kw_syncscope)) {
2157 auto StartParenAt = Lex.getLoc();
2158 if (!EatIfPresent(lltok::lparen))
2159 return Error(StartParenAt, "Expected '(' in syncscope");
2160
2161 std::string SSN;
2162 auto SSNAt = Lex.getLoc();
2163 if (ParseStringConstant(SSN))
2164 return Error(SSNAt, "Expected synchronization scope name");
2165
2166 auto EndParenAt = Lex.getLoc();
2167 if (!EatIfPresent(lltok::rparen))
2168 return Error(EndParenAt, "Expected ')' in syncscope");
2169
2170 SSID = Context.getOrInsertSyncScopeID(SSN);
2171 }
2172
2173 return false;
Tim Northovere94a5182014-03-11 10:48:52 +00002174}
2175
2176/// ParseOrdering
2177/// ::= AtomicOrdering
2178///
2179/// This sets Ordering to the parsed value.
2180bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00002181 switch (Lex.getKind()) {
2182 default: return TokError("Expected ordering on atomic instruction");
JF Bastien800f87a2016-04-06 21:19:33 +00002183 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
2184 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
2185 // Not specified yet:
2186 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2187 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
2188 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
2189 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
2190 case lltok::kw_seq_cst:
2191 Ordering = AtomicOrdering::SequentiallyConsistent;
2192 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00002193 }
2194 Lex.Lex();
2195 return false;
2196}
2197
Charles Davisbe5557e2010-02-12 00:31:15 +00002198/// ParseOptionalStackAlignment
2199/// ::= /* empty */
2200/// ::= 'alignstack' '(' 4 ')'
2201bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
2202 Alignment = 0;
2203 if (!EatIfPresent(lltok::kw_alignstack))
2204 return false;
2205 LocTy ParenLoc = Lex.getLoc();
2206 if (!EatIfPresent(lltok::lparen))
2207 return Error(ParenLoc, "expected '('");
2208 LocTy AlignLoc = Lex.getLoc();
2209 if (ParseUInt32(Alignment)) return true;
2210 ParenLoc = Lex.getLoc();
2211 if (!EatIfPresent(lltok::rparen))
2212 return Error(ParenLoc, "expected ')'");
2213 if (!isPowerOf2_32(Alignment))
2214 return Error(AlignLoc, "stack alignment is not a power of two");
2215 return false;
2216}
Devang Patelea8a4b92009-09-17 23:04:48 +00002217
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002218/// ParseIndexList - This parses the index list for an insert/extractvalue
2219/// instruction. This sets AteExtraComma in the case where we eat an extra
2220/// comma at the end of the line and find that it is followed by metadata.
2221/// Clients that don't allow metadata can call the version of this function that
2222/// only takes one argument.
2223///
Chris Lattnerac161bf2009-01-02 07:01:27 +00002224/// ParseIndexList
2225/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002226///
2227bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
2228 bool &AteExtraComma) {
2229 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002230
Chris Lattnerac161bf2009-01-02 07:01:27 +00002231 if (Lex.getKind() != lltok::comma)
2232 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002233
Chris Lattner3822f632009-01-02 08:05:26 +00002234 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002235 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00002236 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002237 AteExtraComma = true;
2238 return false;
2239 }
Nick Lewycky83e47112010-09-29 23:32:20 +00002240 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00002241 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002242 Indices.push_back(Idx);
2243 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002244
Chris Lattnerac161bf2009-01-02 07:01:27 +00002245 return false;
2246}
2247
2248//===----------------------------------------------------------------------===//
2249// Type Parsing.
2250//===----------------------------------------------------------------------===//
2251
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002252/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002253bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002254 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002255 switch (Lex.getKind()) {
2256 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002257 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002258 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002259 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002260 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002261 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002262 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002263 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002264 // Type ::= StructType
2265 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002266 return true;
2267 break;
2268 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002269 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002270 Lex.Lex(); // eat the lsquare.
2271 if (ParseArrayVectorType(Result, false))
2272 return true;
2273 break;
2274 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002275 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00002276 Lex.Lex();
2277 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002278 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002279 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002280 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002281 } else if (ParseArrayVectorType(Result, true))
2282 return true;
2283 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002284 case lltok::LocalVar: {
2285 // Type ::= %foo
2286 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002287
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002288 // If the type hasn't been defined yet, create a forward definition and
2289 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002290 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002291 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002292 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002293 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002294 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002295 Lex.Lex();
2296 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002297 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002298
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002299 case lltok::LocalVarID: {
2300 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002301 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002302
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002303 // If the type hasn't been defined yet, create a forward definition and
2304 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002305 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002306 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002307 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002308 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002309 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002310 Lex.Lex();
2311 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002312 }
2313 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002314
2315 // Parse the type suffixes.
Eugene Zelenko1804a772016-08-25 00:45:04 +00002316 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002317 switch (Lex.getKind()) {
2318 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002319 default:
2320 if (!AllowVoid && Result->isVoidTy())
2321 return Error(TypeLoc, "void type only allowed for function results");
2322 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002323
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002324 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002325 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002326 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002327 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002328 if (Result->isVoidTy())
2329 return TokError("pointers to void are invalid - use i8* instead");
2330 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002331 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002332 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002333 Lex.Lex();
2334 break;
2335
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002336 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002337 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002338 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002339 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002340 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00002341 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002342 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002343 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002344 unsigned AddrSpace;
2345 if (ParseOptionalAddrSpace(AddrSpace) ||
2346 ParseToken(lltok::star, "expected '*' in address space"))
2347 return true;
2348
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002349 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002350 break;
2351 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002352
Chris Lattnerac161bf2009-01-02 07:01:27 +00002353 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2354 case lltok::lparen:
2355 if (ParseFunctionType(Result))
2356 return true;
2357 break;
2358 }
2359 }
2360}
2361
2362/// ParseParameterList
2363/// ::= '(' ')'
2364/// ::= '(' Arg (',' Arg)* ')'
2365/// Arg
2366/// ::= Type OptionalAttributes Value OptionalAttributes
2367bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00002368 PerFunctionState &PFS, bool IsMustTailCall,
2369 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002370 if (ParseToken(lltok::lparen, "expected '(' in call"))
2371 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002372
Chris Lattnerac161bf2009-01-02 07:01:27 +00002373 while (Lex.getKind() != lltok::rparen) {
2374 // If this isn't the first argument, we need a comma.
2375 if (!ArgList.empty() &&
2376 ParseToken(lltok::comma, "expected ',' in argument list"))
2377 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002378
Reid Kleckner83498642014-08-26 00:33:28 +00002379 // Parse an ellipsis if this is a musttail call in a variadic function.
2380 if (Lex.getKind() == lltok::dotdotdot) {
2381 const char *Msg = "unexpected ellipsis in argument list for ";
2382 if (!IsMustTailCall)
2383 return TokError(Twine(Msg) + "non-musttail call");
2384 if (!InVarArgsFunc)
2385 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2386 Lex.Lex(); // Lex the '...', it is purely for readability.
2387 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2388 }
2389
Chris Lattnerac161bf2009-01-02 07:01:27 +00002390 // Parse the argument.
2391 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00002392 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002393 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002394 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00002395 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002396 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00002397
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002398 if (ArgTy->isMetadataTy()) {
2399 if (ParseMetadataAsValue(V, PFS))
2400 return true;
2401 } else {
2402 // Otherwise, handle normal operands.
2403 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2404 return true;
2405 }
Reid Klecknerb5180542017-03-21 16:57:19 +00002406 ArgList.push_back(ParamInfo(
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002407 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002408 }
2409
Reid Kleckner83498642014-08-26 00:33:28 +00002410 if (IsMustTailCall && InVarArgsFunc)
2411 return TokError("expected '...' at end of argument list for musttail call "
2412 "in varargs function");
2413
Chris Lattnerac161bf2009-01-02 07:01:27 +00002414 Lex.Lex(); // Lex the ')'.
2415 return false;
2416}
2417
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002418/// ParseOptionalOperandBundles
2419/// ::= /*empty*/
2420/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2421///
2422/// OperandBundle
2423/// ::= bundle-tag '(' ')'
2424/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2425///
2426/// bundle-tag ::= String Constant
2427bool LLParser::ParseOptionalOperandBundles(
2428 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2429 LocTy BeginLoc = Lex.getLoc();
2430 if (!EatIfPresent(lltok::lsquare))
2431 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002432
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002433 while (Lex.getKind() != lltok::rsquare) {
2434 // If this isn't the first operand bundle, we need a comma.
2435 if (!BundleList.empty() &&
2436 ParseToken(lltok::comma, "expected ',' in input list"))
2437 return true;
2438
2439 std::string Tag;
2440 if (ParseStringConstant(Tag))
2441 return true;
2442
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002443 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2444 return true;
2445
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002446 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002447 while (Lex.getKind() != lltok::rparen) {
2448 // If this isn't the first input, we need a comma.
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002449 if (!Inputs.empty() &&
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002450 ParseToken(lltok::comma, "expected ',' in input list"))
2451 return true;
2452
2453 Type *Ty = nullptr;
2454 Value *Input = nullptr;
2455 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2456 return true;
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002457 Inputs.push_back(Input);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002458 }
2459
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002460 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2461
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002462 Lex.Lex(); // Lex the ')'.
2463 }
2464
2465 if (BundleList.empty())
2466 return Error(BeginLoc, "operand bundle set must not be empty");
2467
2468 Lex.Lex(); // Lex the ']'.
2469 return false;
2470}
Chris Lattnerac161bf2009-01-02 07:01:27 +00002471
Chris Lattner2ed06b42009-01-05 18:34:07 +00002472/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002473/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00002474/// ::= '(' ArgTypeListI ')'
2475/// ArgTypeListI
2476/// ::= /*empty*/
2477/// ::= '...'
2478/// ::= ArgTypeList ',' '...'
2479/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00002480///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002481bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2482 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00002483 isVarArg = false;
2484 assert(Lex.getKind() == lltok::lparen);
2485 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002486
Chris Lattnerac161bf2009-01-02 07:01:27 +00002487 if (Lex.getKind() == lltok::rparen) {
2488 // empty
2489 } else if (Lex.getKind() == lltok::dotdotdot) {
2490 isVarArg = true;
2491 Lex.Lex();
2492 } else {
2493 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002494 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002495 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002496 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002497
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002498 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002499 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002500
Chris Lattnerfdd87902009-10-05 05:54:46 +00002501 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002502 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002503
Chris Lattnerdef19492011-06-17 06:36:20 +00002504 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002505 Name = Lex.getStrVal();
2506 Lex.Lex();
2507 }
Chris Lattner3822f632009-01-02 08:05:26 +00002508
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002509 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00002510 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002511
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002512 ArgList.emplace_back(TypeLoc, ArgTy,
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002513 AttributeSet::get(ArgTy->getContext(), Attrs),
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002514 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002515
Chris Lattner3822f632009-01-02 08:05:26 +00002516 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002517 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00002518 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002519 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002520 break;
2521 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002522
Chris Lattnerac161bf2009-01-02 07:01:27 +00002523 // Otherwise must be an argument type.
2524 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00002525 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00002526
Chris Lattnerfdd87902009-10-05 05:54:46 +00002527 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002528 return Error(TypeLoc, "argument can not have void type");
2529
Chris Lattnerdef19492011-06-17 06:36:20 +00002530 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002531 Name = Lex.getStrVal();
2532 Lex.Lex();
2533 } else {
2534 Name = "";
2535 }
Chris Lattner3822f632009-01-02 08:05:26 +00002536
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002537 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00002538 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002539
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002540 ArgList.emplace_back(TypeLoc, ArgTy,
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002541 AttributeSet::get(ArgTy->getContext(), Attrs),
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002542 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002543 }
2544 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002545
Chris Lattner3822f632009-01-02 08:05:26 +00002546 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002547}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002548
Chris Lattnerac161bf2009-01-02 07:01:27 +00002549/// ParseFunctionType
2550/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002551bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002552 assert(Lex.getKind() == lltok::lparen);
2553
Chris Lattnerce473c72009-01-05 08:04:33 +00002554 if (!FunctionType::isValidReturnType(Result))
2555 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002556
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002557 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002558 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002559 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002560 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002561
Chris Lattnerac161bf2009-01-02 07:01:27 +00002562 // Reject names on the arguments lists.
2563 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2564 if (!ArgList[i].Name.empty())
2565 return Error(ArgList[i].Loc, "argument name invalid in function type");
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002566 if (ArgList[i].Attrs.hasAttributes())
Chris Lattner6bc5c892011-06-17 17:37:13 +00002567 return Error(ArgList[i].Loc,
2568 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002569 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002570
Jay Foadb804a2b2011-07-12 14:06:48 +00002571 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002572 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002573 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002574
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002575 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002576 return false;
2577}
2578
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002579/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2580/// other structs.
2581bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2582 SmallVector<Type*, 8> Elts;
2583 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002584
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002585 Result = StructType::get(Context, Elts, Packed);
2586 return false;
2587}
2588
2589/// ParseStructDefinition - Parse a struct in a 'type' definition.
2590bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2591 std::pair<Type*, LocTy> &Entry,
2592 Type *&ResultTy) {
2593 // If the type was already defined, diagnose the redefinition.
2594 if (Entry.first && !Entry.second.isValid())
2595 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002596
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002597 // If we have opaque, just return without filling in the definition for the
2598 // struct. This counts as a definition as far as the .ll file goes.
2599 if (EatIfPresent(lltok::kw_opaque)) {
2600 // This type is being defined, so clear the location to indicate this.
2601 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002602
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002603 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002604 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002605 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002606 ResultTy = Entry.first;
2607 return false;
2608 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002609
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002610 // If the type starts with '<', then it is either a packed struct or a vector.
2611 bool isPacked = EatIfPresent(lltok::less);
2612
2613 // If we don't have a struct, then we have a random type alias, which we
2614 // accept for compatibility with old files. These types are not allowed to be
2615 // forward referenced and not allowed to be recursive.
2616 if (Lex.getKind() != lltok::lbrace) {
2617 if (Entry.first)
2618 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002619
Craig Topper2617dcc2014-04-15 06:32:26 +00002620 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002621 if (isPacked)
2622 return ParseArrayVectorType(ResultTy, true);
2623 return ParseType(ResultTy);
2624 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002625
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002626 // This type is being defined, so clear the location to indicate this.
2627 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002628
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002629 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002630 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002631 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002632
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002633 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002634
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002635 SmallVector<Type*, 8> Body;
2636 if (ParseStructBody(Body) ||
2637 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2638 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002639
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002640 STy->setBody(Body, isPacked);
2641 ResultTy = STy;
2642 return false;
2643}
2644
Chris Lattnerac161bf2009-01-02 07:01:27 +00002645/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002646/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002647/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002648/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002649/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002650/// ::= '<' '{' Type (',' Type)* '}' '>'
2651bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002652 assert(Lex.getKind() == lltok::lbrace);
2653 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002654
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002655 // Handle the empty struct.
2656 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002657 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002658
Chris Lattnerf880ca22009-03-09 04:49:14 +00002659 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002660 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002661 if (ParseType(Ty)) return true;
2662 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002663
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002664 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002665 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002666
Chris Lattner3822f632009-01-02 08:05:26 +00002667 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002668 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002669 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002670
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002671 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002672 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002673
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002674 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002675 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002676
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002677 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002678}
2679
2680/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2681/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002682/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002683/// ::= '[' APSINTVAL 'x' Types ']'
2684/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002685bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002686 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2687 Lex.getAPSIntVal().getBitWidth() > 64)
2688 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002689
Chris Lattnerac161bf2009-01-02 07:01:27 +00002690 LocTy SizeLoc = Lex.getLoc();
2691 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002692 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002693
Chris Lattner3822f632009-01-02 08:05:26 +00002694 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2695 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002696
2697 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002698 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002699 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002700
Chris Lattner3822f632009-01-02 08:05:26 +00002701 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2702 "expected end of sequential type"))
2703 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002704
Chris Lattnerac161bf2009-01-02 07:01:27 +00002705 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002706 if (Size == 0)
2707 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002708 if ((unsigned)Size != Size)
2709 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002710 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002711 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002712 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002713 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002714 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002715 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002716 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002717 }
2718 return false;
2719}
2720
2721//===----------------------------------------------------------------------===//
2722// Function Semantic Analysis.
2723//===----------------------------------------------------------------------===//
2724
Chris Lattner3432c622009-10-28 03:39:23 +00002725LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2726 int functionNumber)
2727 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002728
2729 // Insert unnamed arguments into the NumberedVals list.
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +00002730 for (Argument &A : F.args())
2731 if (!A.hasName())
2732 NumberedVals.push_back(&A);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002733}
2734
2735LLParser::PerFunctionState::~PerFunctionState() {
2736 // If there were any forward referenced non-basicblock values, delete them.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002737
David Blaikie9ebdc692015-09-21 21:07:50 +00002738 for (const auto &P : ForwardRefVals) {
2739 if (isa<BasicBlock>(P.second.first))
2740 continue;
2741 P.second.first->replaceAllUsesWith(
2742 UndefValue::get(P.second.first->getType()));
Reid Kleckner96ab8722017-05-18 17:24:10 +00002743 P.second.first->deleteValue();
David Blaikie9ebdc692015-09-21 21:07:50 +00002744 }
2745
2746 for (const auto &P : ForwardRefValIDs) {
2747 if (isa<BasicBlock>(P.second.first))
2748 continue;
2749 P.second.first->replaceAllUsesWith(
2750 UndefValue::get(P.second.first->getType()));
Reid Kleckner96ab8722017-05-18 17:24:10 +00002751 P.second.first->deleteValue();
David Blaikie9ebdc692015-09-21 21:07:50 +00002752 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002753}
2754
Chris Lattner3432c622009-10-28 03:39:23 +00002755bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002756 if (!ForwardRefVals.empty())
2757 return P.Error(ForwardRefVals.begin()->second.second,
2758 "use of undefined value '%" + ForwardRefVals.begin()->first +
2759 "'");
2760 if (!ForwardRefValIDs.empty())
2761 return P.Error(ForwardRefValIDs.begin()->second.second,
2762 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002763 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002764 return false;
2765}
2766
Chris Lattnerac161bf2009-01-02 07:01:27 +00002767/// GetVal - Get a value with the specified name or ID, creating a
2768/// forward reference record if needed. This can return null if the value
2769/// exists but does not have the right type.
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002770Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002771 LocTy Loc, bool IsCall) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002772 // Look this name up in the normal function symbol table.
Mehdi Aminia53d49e2016-09-17 06:00:02 +00002773 Value *Val = F.getValueSymbolTable()->lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002774
Chris Lattnerac161bf2009-01-02 07:01:27 +00002775 // If this is a forward reference for the value, see if we already created a
2776 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002777 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002778 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002779 if (I != ForwardRefVals.end())
2780 Val = I->second.first;
2781 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002782
Chris Lattnerac161bf2009-01-02 07:01:27 +00002783 // If we have the value in the symbol table or fwd-ref table, return it.
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00002784 if (Val)
2785 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val, IsCall);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002786
Chris Lattnerac161bf2009-01-02 07:01:27 +00002787 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002788 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002789 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002790 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002791 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002792
Chris Lattnerac161bf2009-01-02 07:01:27 +00002793 // Otherwise, create a new forward reference for this value and remember it.
2794 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002795 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002796 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002797 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002798 FwdVal = new Argument(Ty, Name);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002799 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002800
Chris Lattnerac161bf2009-01-02 07:01:27 +00002801 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2802 return FwdVal;
2803}
2804
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002805Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc,
2806 bool IsCall) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002807 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002808 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002809
Chris Lattnerac161bf2009-01-02 07:01:27 +00002810 // If this is a forward reference for the value, see if we already created a
2811 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002812 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002813 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002814 if (I != ForwardRefValIDs.end())
2815 Val = I->second.first;
2816 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002817
Chris Lattnerac161bf2009-01-02 07:01:27 +00002818 // If we have the value in the symbol table or fwd-ref table, return it.
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00002819 if (Val)
2820 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val, IsCall);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002821
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002822 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002823 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002824 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002825 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002826
Chris Lattnerac161bf2009-01-02 07:01:27 +00002827 // Otherwise, create a new forward reference for this value and remember it.
2828 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002829 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002830 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002831 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002832 FwdVal = new Argument(Ty);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002833 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002834
Chris Lattnerac161bf2009-01-02 07:01:27 +00002835 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2836 return FwdVal;
2837}
2838
2839/// SetInstName - After an instruction is parsed and inserted into its
2840/// basic block, this installs its name.
2841bool LLParser::PerFunctionState::SetInstName(int NameID,
2842 const std::string &NameStr,
2843 LocTy NameLoc, Instruction *Inst) {
2844 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002845 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002846 if (NameID != -1 || !NameStr.empty())
2847 return P.Error(NameLoc, "instructions returning void cannot have a name");
2848 return false;
2849 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002850
Chris Lattnerac161bf2009-01-02 07:01:27 +00002851 // If this was a numbered instruction, verify that the instruction is the
2852 // expected value and resolve any forward references.
2853 if (NameStr.empty()) {
2854 // If neither a name nor an ID was specified, just use the next ID.
2855 if (NameID == -1)
2856 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002857
Chris Lattnerac161bf2009-01-02 07:01:27 +00002858 if (unsigned(NameID) != NumberedVals.size())
2859 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002860 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002861
David Blaikie9ebdc692015-09-21 21:07:50 +00002862 auto FI = ForwardRefValIDs.find(NameID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002863 if (FI != ForwardRefValIDs.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002864 Value *Sentinel = FI->second.first;
2865 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002866 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002867 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002868
2869 Sentinel->replaceAllUsesWith(Inst);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002870 Sentinel->deleteValue();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002871 ForwardRefValIDs.erase(FI);
2872 }
2873
2874 NumberedVals.push_back(Inst);
2875 return false;
2876 }
2877
2878 // Otherwise, the instruction had a name. Resolve forward refs and set it.
David Blaikie9ebdc692015-09-21 21:07:50 +00002879 auto FI = ForwardRefVals.find(NameStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002880 if (FI != ForwardRefVals.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002881 Value *Sentinel = FI->second.first;
2882 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002883 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002884 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002885
2886 Sentinel->replaceAllUsesWith(Inst);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002887 Sentinel->deleteValue();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002888 ForwardRefVals.erase(FI);
2889 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002890
Chris Lattnerac161bf2009-01-02 07:01:27 +00002891 // Set the name on the instruction.
2892 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002893
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002894 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002895 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002896 NameStr + "'");
2897 return false;
2898}
2899
2900/// GetBB - Get a basic block with the specified name or ID, creating a
2901/// forward reference record if needed.
2902BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2903 LocTy Loc) {
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002904 return dyn_cast_or_null<BasicBlock>(
2905 GetVal(Name, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002906}
2907
2908BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002909 return dyn_cast_or_null<BasicBlock>(
2910 GetVal(ID, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002911}
2912
2913/// DefineBB - Define the specified basic block, which is either named or
2914/// unnamed. If there is an error, this returns null otherwise it returns
2915/// the block being defined.
2916BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2917 LocTy Loc) {
2918 BasicBlock *BB;
2919 if (Name.empty())
2920 BB = GetBB(NumberedVals.size(), Loc);
2921 else
2922 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002923 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002924
Chris Lattnerac161bf2009-01-02 07:01:27 +00002925 // Move the block to the end of the function. Forward ref'd blocks are
2926 // inserted wherever they happen to be referenced.
2927 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002928
Chris Lattnerac161bf2009-01-02 07:01:27 +00002929 // Remove the block from forward ref sets.
2930 if (Name.empty()) {
2931 ForwardRefValIDs.erase(NumberedVals.size());
2932 NumberedVals.push_back(BB);
2933 } else {
2934 // BB forward references are already in the function symbol table.
2935 ForwardRefVals.erase(Name);
2936 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002937
Chris Lattnerac161bf2009-01-02 07:01:27 +00002938 return BB;
2939}
2940
2941//===----------------------------------------------------------------------===//
2942// Constants.
2943//===----------------------------------------------------------------------===//
2944
2945/// ParseValID - Parse an abstract value that doesn't necessarily have a
2946/// type implied. For example, if we parse "4" we don't know what integer type
2947/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002948/// sanity. PFS is used to convert function-local operands of metadata (since
2949/// metadata operands are not just parsed here but also converted to values).
2950/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002951bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002952 ID.Loc = Lex.getLoc();
2953 switch (Lex.getKind()) {
2954 default: return TokError("expected value token");
2955 case lltok::GlobalID: // @42
2956 ID.UIntVal = Lex.getUIntVal();
2957 ID.Kind = ValID::t_GlobalID;
2958 break;
2959 case lltok::GlobalVar: // @foo
2960 ID.StrVal = Lex.getStrVal();
2961 ID.Kind = ValID::t_GlobalName;
2962 break;
2963 case lltok::LocalVarID: // %42
2964 ID.UIntVal = Lex.getUIntVal();
2965 ID.Kind = ValID::t_LocalID;
2966 break;
2967 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002968 ID.StrVal = Lex.getStrVal();
2969 ID.Kind = ValID::t_LocalName;
2970 break;
2971 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002972 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002973 ID.Kind = ValID::t_APSInt;
2974 break;
2975 case lltok::APFloat:
2976 ID.APFloatVal = Lex.getAPFloatVal();
2977 ID.Kind = ValID::t_APFloat;
2978 break;
2979 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002980 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002981 ID.Kind = ValID::t_Constant;
2982 break;
2983 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002984 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002985 ID.Kind = ValID::t_Constant;
2986 break;
2987 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2988 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2989 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
David Majnemerf0f224d2015-11-11 21:57:16 +00002990 case lltok::kw_none: ID.Kind = ValID::t_None; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002991
Chris Lattnerac161bf2009-01-02 07:01:27 +00002992 case lltok::lbrace: {
2993 // ValID ::= '{' ConstVector '}'
2994 Lex.Lex();
2995 SmallVector<Constant*, 16> Elts;
2996 if (ParseGlobalValueVector(Elts) ||
2997 ParseToken(lltok::rbrace, "expected end of struct constant"))
2998 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002999
David Blaikieadbda4b2015-08-03 20:08:41 +00003000 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003001 ID.UIntVal = Elts.size();
David Blaikieadbda4b2015-08-03 20:08:41 +00003002 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3003 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003004 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003005 return false;
3006 }
3007 case lltok::less: {
3008 // ValID ::= '<' ConstVector '>' --> Vector.
3009 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3010 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00003011 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003012
Chris Lattnerac161bf2009-01-02 07:01:27 +00003013 SmallVector<Constant*, 16> Elts;
3014 LocTy FirstEltLoc = Lex.getLoc();
3015 if (ParseGlobalValueVector(Elts) ||
3016 (isPackedStruct &&
3017 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
3018 ParseToken(lltok::greater, "expected end of constant"))
3019 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003020
Chris Lattnerac161bf2009-01-02 07:01:27 +00003021 if (isPackedStruct) {
David Blaikieadbda4b2015-08-03 20:08:41 +00003022 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
3023 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3024 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003025 ID.UIntVal = Elts.size();
3026 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003027 return false;
3028 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003029
Chris Lattnerac161bf2009-01-02 07:01:27 +00003030 if (Elts.empty())
3031 return Error(ID.Loc, "constant vector must not be empty");
3032
Duncan Sands9dff9be2010-02-15 16:12:20 +00003033 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00003034 !Elts[0]->getType()->isFloatingPointTy() &&
3035 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003036 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00003037 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003038
Chris Lattnerac161bf2009-01-02 07:01:27 +00003039 // Verify that all the vector elements have the same type.
3040 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
3041 if (Elts[i]->getType() != Elts[0]->getType())
3042 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00003043 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003044 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003045
Chris Lattner69229312011-02-15 00:14:00 +00003046 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003047 ID.Kind = ValID::t_Constant;
3048 return false;
3049 }
3050 case lltok::lsquare: { // Array Constant
3051 Lex.Lex();
3052 SmallVector<Constant*, 16> Elts;
3053 LocTy FirstEltLoc = Lex.getLoc();
3054 if (ParseGlobalValueVector(Elts) ||
3055 ParseToken(lltok::rsquare, "expected end of array constant"))
3056 return true;
3057
3058 // Handle empty element.
3059 if (Elts.empty()) {
3060 // Use undef instead of an array because it's inconvenient to determine
3061 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00003062 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003063 return false;
3064 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003065
Chris Lattnerac161bf2009-01-02 07:01:27 +00003066 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003067 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003068 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003069
Owen Anderson4056ca92009-07-29 22:17:13 +00003070 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003071
Chris Lattnerac161bf2009-01-02 07:01:27 +00003072 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00003073 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003074 if (Elts[i]->getType() != Elts[0]->getType())
3075 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00003076 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003077 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003078 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003079
Jay Foad83be3612011-06-22 09:24:39 +00003080 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003081 ID.Kind = ValID::t_Constant;
3082 return false;
3083 }
3084 case lltok::kw_c: // c "foo"
3085 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003086 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
3087 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003088 if (ParseToken(lltok::StringConstant, "expected string")) return true;
3089 ID.Kind = ValID::t_Constant;
3090 return false;
3091
3092 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00003093 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
3094 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00003095 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003096 Lex.Lex();
3097 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00003098 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00003099 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00003100 ParseStringConstant(ID.StrVal) ||
3101 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003102 ParseToken(lltok::StringConstant, "expected constraint string"))
3103 return true;
3104 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00003105 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00003106 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003107 ID.Kind = ValID::t_InlineAsm;
3108 return false;
3109 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003110
Chris Lattner3432c622009-10-28 03:39:23 +00003111 case lltok::kw_blockaddress: {
3112 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3113 Lex.Lex();
3114
3115 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003116
Chris Lattner3432c622009-10-28 03:39:23 +00003117 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
3118 ParseValID(Fn) ||
3119 ParseToken(lltok::comma, "expected comma in block address expression")||
3120 ParseValID(Label) ||
3121 ParseToken(lltok::rparen, "expected ')' in block address expression"))
3122 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003123
Chris Lattner3432c622009-10-28 03:39:23 +00003124 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3125 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00003126 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00003127 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003128
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003129 // Try to find the function (but skip it if it's forward-referenced).
3130 GlobalValue *GV = nullptr;
3131 if (Fn.Kind == ValID::t_GlobalID) {
3132 if (Fn.UIntVal < NumberedVals.size())
3133 GV = NumberedVals[Fn.UIntVal];
3134 } else if (!ForwardRefVals.count(Fn.StrVal)) {
3135 GV = M->getNamedValue(Fn.StrVal);
3136 }
3137 Function *F = nullptr;
3138 if (GV) {
3139 // Confirm that it's actually a function with a definition.
3140 if (!isa<Function>(GV))
3141 return Error(Fn.Loc, "expected function name in blockaddress");
3142 F = cast<Function>(GV);
3143 if (F->isDeclaration())
3144 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
3145 }
3146
3147 if (!F) {
3148 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00003149 GlobalValue *&FwdRef =
David Blaikie871b4112015-08-03 20:55:00 +00003150 ForwardRefBlockAddresses.insert(std::make_pair(
3151 std::move(Fn),
3152 std::map<ValID, GlobalValue *>()))
David Blaikieb9cc6592015-03-04 01:40:07 +00003153 .first->second.insert(std::make_pair(std::move(Label), nullptr))
3154 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003155 if (!FwdRef)
3156 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
3157 GlobalValue::InternalLinkage, nullptr, "");
3158 ID.ConstantVal = FwdRef;
3159 ID.Kind = ValID::t_Constant;
3160 return false;
3161 }
3162
3163 // We found the function; now find the basic block. Don't use PFS, since we
3164 // might be inside a constant expression.
3165 BasicBlock *BB;
3166 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
3167 if (Label.Kind == ValID::t_LocalID)
3168 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
3169 else
3170 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
3171 if (!BB)
3172 return Error(Label.Loc, "referenced value is not a basic block");
3173 } else {
3174 if (Label.Kind == ValID::t_LocalID)
3175 return Error(Label.Loc, "cannot take address of numeric label after "
3176 "the function is defined");
3177 BB = dyn_cast_or_null<BasicBlock>(
Mehdi Aminia53d49e2016-09-17 06:00:02 +00003178 F->getValueSymbolTable()->lookup(Label.StrVal));
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003179 if (!BB)
3180 return Error(Label.Loc, "referenced value is not a basic block");
3181 }
3182
3183 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00003184 ID.Kind = ValID::t_Constant;
3185 return false;
3186 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003187
Chris Lattnerac161bf2009-01-02 07:01:27 +00003188 case lltok::kw_trunc:
3189 case lltok::kw_zext:
3190 case lltok::kw_sext:
3191 case lltok::kw_fptrunc:
3192 case lltok::kw_fpext:
3193 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003194 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003195 case lltok::kw_uitofp:
3196 case lltok::kw_sitofp:
3197 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003198 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003199 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003200 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003201 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00003202 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003203 Constant *SrcVal;
3204 Lex.Lex();
3205 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3206 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00003207 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003208 ParseType(DestTy) ||
3209 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3210 return true;
3211 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3212 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003213 getTypeString(SrcVal->getType()) + "' to '" +
3214 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003215 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00003216 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003217 ID.Kind = ValID::t_Constant;
3218 return false;
3219 }
3220 case lltok::kw_extractvalue: {
3221 Lex.Lex();
3222 Constant *Val;
3223 SmallVector<unsigned, 4> Indices;
3224 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
3225 ParseGlobalTypeAndValue(Val) ||
3226 ParseIndexList(Indices) ||
3227 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
3228 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00003229
Chris Lattner392be582010-02-12 20:49:41 +00003230 if (!Val->getType()->isAggregateType())
3231 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00003232 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003233 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00003234 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003235 ID.Kind = ValID::t_Constant;
3236 return false;
3237 }
3238 case lltok::kw_insertvalue: {
3239 Lex.Lex();
3240 Constant *Val0, *Val1;
3241 SmallVector<unsigned, 4> Indices;
3242 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
3243 ParseGlobalTypeAndValue(Val0) ||
3244 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
3245 ParseGlobalTypeAndValue(Val1) ||
3246 ParseIndexList(Indices) ||
3247 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3248 return true;
Chris Lattner392be582010-02-12 20:49:41 +00003249 if (!Val0->getType()->isAggregateType())
3250 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00003251 Type *IndexedType =
3252 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3253 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003254 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00003255 if (IndexedType != Val1->getType())
3256 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3257 getTypeString(Val1->getType()) +
3258 "' instead of '" + getTypeString(IndexedType) +
3259 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00003260 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003261 ID.Kind = ValID::t_Constant;
3262 return false;
3263 }
3264 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003265 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003266 unsigned PredVal, Opc = Lex.getUIntVal();
3267 Constant *Val0, *Val1;
3268 Lex.Lex();
3269 if (ParseCmpPredicate(PredVal, Opc) ||
3270 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3271 ParseGlobalTypeAndValue(Val0) ||
3272 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3273 ParseGlobalTypeAndValue(Val1) ||
3274 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3275 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003276
Chris Lattnerac161bf2009-01-02 07:01:27 +00003277 if (Val0->getType() != Val1->getType())
3278 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003279
Chris Lattnerac161bf2009-01-02 07:01:27 +00003280 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003281
Chris Lattnerac161bf2009-01-02 07:01:27 +00003282 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00003283 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003284 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003285 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003286 } else {
3287 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003288 if (!Val0->getType()->isIntOrIntVectorTy() &&
Craig Topper95d23472017-07-09 07:04:00 +00003289 !Val0->getType()->isPtrOrPtrVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003290 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003291 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003292 }
3293 ID.Kind = ValID::t_Constant;
3294 return false;
3295 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003296
Chris Lattnerac161bf2009-01-02 07:01:27 +00003297 // Binary Operators.
3298 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00003299 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003300 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00003301 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003302 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00003303 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003304 case lltok::kw_udiv:
3305 case lltok::kw_sdiv:
3306 case lltok::kw_fdiv:
3307 case lltok::kw_urem:
3308 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003309 case lltok::kw_frem:
3310 case lltok::kw_shl:
3311 case lltok::kw_lshr:
3312 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003313 bool NUW = false;
3314 bool NSW = false;
3315 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003316 unsigned Opc = Lex.getUIntVal();
3317 Constant *Val0, *Val1;
3318 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00003319 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00003320 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3321 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003322 if (EatIfPresent(lltok::kw_nuw))
3323 NUW = true;
3324 if (EatIfPresent(lltok::kw_nsw)) {
3325 NSW = true;
3326 if (EatIfPresent(lltok::kw_nuw))
3327 NUW = true;
3328 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00003329 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3330 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003331 if (EatIfPresent(lltok::kw_exact))
3332 Exact = true;
3333 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003334 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3335 ParseGlobalTypeAndValue(Val0) ||
3336 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3337 ParseGlobalTypeAndValue(Val1) ||
3338 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3339 return true;
3340 if (Val0->getType() != Val1->getType())
3341 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003342 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003343 if (NUW)
3344 return Error(ModifierLoc, "nuw only applies to integer operations");
3345 if (NSW)
3346 return Error(ModifierLoc, "nsw only applies to integer operations");
3347 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00003348 // Check that the type is valid for the operator.
3349 switch (Opc) {
3350 case Instruction::Add:
3351 case Instruction::Sub:
3352 case Instruction::Mul:
3353 case Instruction::UDiv:
3354 case Instruction::SDiv:
3355 case Instruction::URem:
3356 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003357 case Instruction::Shl:
3358 case Instruction::AShr:
3359 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00003360 if (!Val0->getType()->isIntOrIntVectorTy())
3361 return Error(ID.Loc, "constexpr requires integer operands");
3362 break;
3363 case Instruction::FAdd:
3364 case Instruction::FSub:
3365 case Instruction::FMul:
3366 case Instruction::FDiv:
3367 case Instruction::FRem:
3368 if (!Val0->getType()->isFPOrFPVectorTy())
3369 return Error(ID.Loc, "constexpr requires fp operands");
3370 break;
3371 default: llvm_unreachable("Unknown binary operator!");
3372 }
Dan Gohman1b849082009-09-07 23:54:19 +00003373 unsigned Flags = 0;
3374 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3375 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00003376 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00003377 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00003378 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003379 ID.Kind = ValID::t_Constant;
3380 return false;
3381 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003382
Chris Lattnerac161bf2009-01-02 07:01:27 +00003383 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00003384 case lltok::kw_and:
3385 case lltok::kw_or:
3386 case lltok::kw_xor: {
3387 unsigned Opc = Lex.getUIntVal();
3388 Constant *Val0, *Val1;
3389 Lex.Lex();
3390 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3391 ParseGlobalTypeAndValue(Val0) ||
3392 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3393 ParseGlobalTypeAndValue(Val1) ||
3394 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3395 return true;
3396 if (Val0->getType() != Val1->getType())
3397 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003398 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003399 return Error(ID.Loc,
3400 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003401 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003402 ID.Kind = ValID::t_Constant;
3403 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003404 }
3405
Chris Lattnerac161bf2009-01-02 07:01:27 +00003406 case lltok::kw_getelementptr:
3407 case lltok::kw_shufflevector:
3408 case lltok::kw_insertelement:
3409 case lltok::kw_extractelement:
3410 case lltok::kw_select: {
3411 unsigned Opc = Lex.getUIntVal();
3412 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00003413 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00003414 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003415 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00003416
Dan Gohman1639c392009-07-27 21:53:46 +00003417 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00003418 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00003419
3420 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3421 return true;
3422
3423 LocTy ExplicitTypeLoc = Lex.getLoc();
3424 if (Opc == Instruction::GetElementPtr) {
3425 if (ParseType(Ty) ||
3426 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3427 return true;
3428 }
3429
Peter Collingbourned93620b2016-11-10 22:34:55 +00003430 Optional<unsigned> InRangeOp;
3431 if (ParseGlobalValueVector(
3432 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003433 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3434 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003435
Chris Lattnerac161bf2009-01-02 07:01:27 +00003436 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00003437 if (Elts.size() == 0 ||
Craig Topper95d23472017-07-09 07:04:00 +00003438 !Elts[0]->getType()->isPtrOrPtrVectorTy())
David Majnemer00303b62015-02-22 23:14:52 +00003439 return Error(ID.Loc, "base of getelementptr must be a pointer");
3440
3441 Type *BaseType = Elts[0]->getType();
3442 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00003443 if (Ty != BasePointerType->getElementType())
3444 return Error(
3445 ExplicitTypeLoc,
3446 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003447
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003448 unsigned GEPWidth =
3449 BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
3450
Jay Foaded8db7d2011-07-21 14:31:17 +00003451 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00003452 for (Constant *Val : Indices) {
3453 Type *ValTy = Val->getType();
Craig Topper95d23472017-07-09 07:04:00 +00003454 if (!ValTy->isIntOrIntVectorTy())
David Majnemer00303b62015-02-22 23:14:52 +00003455 return Error(ID.Loc, "getelementptr index must be an integer");
David Majnemer00303b62015-02-22 23:14:52 +00003456 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00003457 unsigned ValNumEl = ValTy->getVectorNumElements();
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003458 if (GEPWidth && (ValNumEl != GEPWidth))
David Majnemer00303b62015-02-22 23:14:52 +00003459 return Error(
3460 ID.Loc,
3461 "getelementptr vector index has a wrong number of elements");
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003462 // GEPWidth may have been unknown because the base is a scalar,
3463 // but it is known now.
3464 GEPWidth = ValNumEl;
David Majnemer00303b62015-02-22 23:14:52 +00003465 }
3466 }
3467
Craig Toppere3dcce92015-08-01 22:20:21 +00003468 SmallPtrSet<Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00003469 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00003470 return Error(ID.Loc, "base element of getelementptr must be sized");
3471
David Blaikie4a2e73b2015-04-02 18:55:32 +00003472 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00003473 return Error(ID.Loc, "invalid getelementptr indices");
Peter Collingbourned93620b2016-11-10 22:34:55 +00003474
3475 if (InRangeOp) {
3476 if (*InRangeOp == 0)
3477 return Error(ID.Loc,
3478 "inrange keyword may not appear on pointer operand");
3479 --*InRangeOp;
3480 }
3481
3482 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3483 InBounds, InRangeOp);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003484 } else if (Opc == Instruction::Select) {
3485 if (Elts.size() != 3)
3486 return Error(ID.Loc, "expected three operands to select");
3487 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3488 Elts[2]))
3489 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00003490 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003491 } else if (Opc == Instruction::ShuffleVector) {
3492 if (Elts.size() != 3)
3493 return Error(ID.Loc, "expected three operands to shufflevector");
3494 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3495 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00003496 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003497 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003498 } else if (Opc == Instruction::ExtractElement) {
3499 if (Elts.size() != 2)
3500 return Error(ID.Loc, "expected two operands to extractelement");
3501 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3502 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003503 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003504 } else {
3505 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3506 if (Elts.size() != 3)
3507 return Error(ID.Loc, "expected three operands to insertelement");
3508 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3509 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00003510 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003511 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003512 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003513
Chris Lattnerac161bf2009-01-02 07:01:27 +00003514 ID.Kind = ValID::t_Constant;
3515 return false;
3516 }
3517 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003518
Chris Lattnerac161bf2009-01-02 07:01:27 +00003519 Lex.Lex();
3520 return false;
3521}
3522
3523/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00003524bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003525 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003526 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00003527 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003528 bool Parsed = ParseValID(ID) ||
Alexander Richardsonc11ae182018-02-27 11:15:11 +00003529 ConvertValIDToValue(Ty, ID, V, nullptr, /*IsCall=*/false);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003530 if (V && !(C = dyn_cast<Constant>(V)))
3531 return Error(ID.Loc, "global values must be constants");
3532 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003533}
3534
Victor Hernandez9d75c962010-01-11 22:31:58 +00003535bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003536 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003537 return ParseType(Ty) ||
3538 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003539}
3540
Rafael Espindola83a362c2015-01-06 22:55:16 +00003541bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00003542 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003543
3544 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00003545 if (!EatIfPresent(lltok::kw_comdat))
3546 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003547
3548 if (EatIfPresent(lltok::lparen)) {
3549 if (Lex.getKind() != lltok::ComdatVar)
3550 return TokError("expected comdat variable");
3551 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3552 Lex.Lex();
3553 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3554 return true;
3555 } else {
3556 if (GlobalName.empty())
3557 return TokError("comdat cannot be unnamed");
3558 C = getComdat(GlobalName, KwLoc);
3559 }
3560
David Majnemerdad0a642014-06-27 18:19:56 +00003561 return false;
3562}
3563
Victor Hernandez9d75c962010-01-11 22:31:58 +00003564/// ParseGlobalValueVector
3565/// ::= /*empty*/
Peter Collingbourned93620b2016-11-10 22:34:55 +00003566/// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3567bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3568 Optional<unsigned> *InRangeOp) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00003569 // Empty list.
3570 if (Lex.getKind() == lltok::rbrace ||
3571 Lex.getKind() == lltok::rsquare ||
3572 Lex.getKind() == lltok::greater ||
3573 Lex.getKind() == lltok::rparen)
3574 return false;
3575
Peter Collingbourned93620b2016-11-10 22:34:55 +00003576 do {
3577 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3578 *InRangeOp = Elts.size();
Victor Hernandez9d75c962010-01-11 22:31:58 +00003579
Peter Collingbourned93620b2016-11-10 22:34:55 +00003580 Constant *C;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003581 if (ParseGlobalTypeAndValue(C)) return true;
3582 Elts.push_back(C);
Peter Collingbourned93620b2016-11-10 22:34:55 +00003583 } while (EatIfPresent(lltok::comma));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003584
3585 return false;
3586}
3587
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003588bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003589 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003590 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003591 return true;
3592
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003593 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003594 return false;
3595}
3596
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003597/// MDNode:
3598/// ::= !{ ... }
3599/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003600/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003601bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003602 if (Lex.getKind() == lltok::MetadataVar)
3603 return ParseSpecializedMDNode(N);
3604
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003605 return ParseToken(lltok::exclaim, "expected '!' here") ||
3606 ParseMDNodeTail(N);
3607}
3608
3609bool LLParser::ParseMDNodeTail(MDNode *&N) {
3610 // !{ ... }
3611 if (Lex.getKind() == lltok::lbrace)
3612 return ParseMDTuple(N);
3613
3614 // !42
3615 return ParseMDNodeID(N);
3616}
3617
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003618namespace {
3619
3620/// Structure to represent an optional metadata field.
3621template <class FieldTy> struct MDFieldImpl {
3622 typedef MDFieldImpl ImplTy;
3623 FieldTy Val;
3624 bool Seen;
3625
3626 void assign(FieldTy Val) {
3627 Seen = true;
3628 this->Val = std::move(Val);
3629 }
3630
3631 explicit MDFieldImpl(FieldTy Default)
3632 : Val(std::move(Default)), Seen(false) {}
3633};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003634
Sander de Smalenfdf40912018-01-24 09:56:07 +00003635/// Structure to represent an optional metadata field that
3636/// can be of either type (A or B) and encapsulates the
3637/// MD<typeofA>Field and MD<typeofB>Field structs, so not
3638/// to reimplement the specifics for representing each Field.
3639template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
3640 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
3641 FieldTypeA A;
3642 FieldTypeB B;
3643 bool Seen;
3644
3645 enum {
3646 IsInvalid = 0,
3647 IsTypeA = 1,
3648 IsTypeB = 2
3649 } WhatIs;
3650
3651 void assign(FieldTypeA A) {
3652 Seen = true;
3653 this->A = std::move(A);
3654 WhatIs = IsTypeA;
3655 }
3656
3657 void assign(FieldTypeB B) {
3658 Seen = true;
3659 this->B = std::move(B);
3660 WhatIs = IsTypeB;
3661 }
3662
3663 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
3664 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
3665 WhatIs(IsInvalid) {}
3666};
3667
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003668struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3669 uint64_t Max;
3670
3671 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3672 : ImplTy(Default), Max(Max) {}
3673};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003674
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003675struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003676 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003677};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003678
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003679struct ColumnField : public MDUnsignedField {
3680 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3681};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003682
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003683struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003684 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003685 DwarfTagField(dwarf::Tag DefaultTag)
3686 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003687};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003688
Amjad Abouda9bcf162015-12-10 12:56:35 +00003689struct DwarfMacinfoTypeField : public MDUnsignedField {
3690 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3691 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3692 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3693};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003694
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003695struct DwarfAttEncodingField : public MDUnsignedField {
3696 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3697};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003698
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003699struct DwarfVirtualityField : public MDUnsignedField {
3700 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3701};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003702
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003703struct DwarfLangField : public MDUnsignedField {
3704 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3705};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003706
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003707struct DwarfCCField : public MDUnsignedField {
3708 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3709};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003710
Adrian Prantlb939a252016-03-31 23:56:58 +00003711struct EmissionKindField : public MDUnsignedField {
3712 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3713};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003714
David Blaikie66cf14d2018-08-16 21:29:55 +00003715struct NameTableKindField : public MDUnsignedField {
3716 NameTableKindField()
3717 : MDUnsignedField(
3718 0, (unsigned)
3719 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
3720};
3721
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003722struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3723 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003724};
3725
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003726struct MDSignedField : public MDFieldImpl<int64_t> {
3727 int64_t Min;
3728 int64_t Max;
3729
3730 MDSignedField(int64_t Default = 0)
3731 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3732 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3733 : ImplTy(Default), Min(Min), Max(Max) {}
3734};
3735
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003736struct MDBoolField : public MDFieldImpl<bool> {
3737 MDBoolField(bool Default = false) : ImplTy(Default) {}
3738};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003739
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003740struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003741 bool AllowNull;
3742
3743 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003744};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003745
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003746struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3747 MDConstant() : ImplTy(nullptr) {}
3748};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003749
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003750struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003751 bool AllowEmpty;
3752 MDStringField(bool AllowEmpty = true)
3753 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003754};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003755
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003756struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3757 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3758};
3759
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003760struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003761 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3762};
3763
Sander de Smalenfdf40912018-01-24 09:56:07 +00003764struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
3765 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
3766 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
3767
3768 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
3769 bool AllowNull = true)
3770 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
3771
3772 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3773 bool isMDField() const { return WhatIs == IsTypeB; }
3774 int64_t getMDSignedValue() const {
3775 assert(isMDSignedField() && "Wrong field type");
3776 return A.Val;
3777 }
3778 Metadata *getMDFieldValue() const {
3779 assert(isMDField() && "Wrong field type");
3780 return B.Val;
3781 }
3782};
3783
Momchil Velikov08dc66e2018-02-12 16:10:09 +00003784struct MDSignedOrUnsignedField
3785 : MDEitherFieldImpl<MDSignedField, MDUnsignedField> {
3786 MDSignedOrUnsignedField() : ImplTy(MDSignedField(0), MDUnsignedField(0)) {}
3787
3788 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3789 bool isMDUnsignedField() const { return WhatIs == IsTypeB; }
3790 int64_t getMDSignedValue() const {
3791 assert(isMDSignedField() && "Wrong field type");
3792 return A.Val;
3793 }
3794 uint64_t getMDUnsignedValue() const {
3795 assert(isMDUnsignedField() && "Wrong field type");
3796 return B.Val;
3797 }
3798};
3799
Eugene Zelenko1804a772016-08-25 00:45:04 +00003800} // end anonymous namespace
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003801
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003802namespace llvm {
3803
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003804template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003805bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003806 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003807 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3808 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003809
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003810 auto &U = Lex.getAPSIntVal();
3811 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003812 return TokError("value for '" + Name + "' too large, limit is " +
3813 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003814 Result.assign(U.getZExtValue());
3815 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003816 Lex.Lex();
3817 return false;
3818}
3819
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003820template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003821bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3822 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3823}
3824template <>
3825bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3826 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3827}
3828
3829template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003830bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3831 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003832 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003833
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003834 if (Lex.getKind() != lltok::DwarfTag)
3835 return TokError("expected DWARF tag");
3836
3837 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3838 if (Tag == dwarf::DW_TAG_invalid)
3839 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003840 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003841
3842 Result.assign(Tag);
3843 Lex.Lex();
3844 return false;
3845}
3846
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003847template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003848bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003849 DwarfMacinfoTypeField &Result) {
3850 if (Lex.getKind() == lltok::APSInt)
3851 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3852
3853 if (Lex.getKind() != lltok::DwarfMacinfo)
3854 return TokError("expected DWARF macinfo type");
3855
3856 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3857 if (Macinfo == dwarf::DW_MACINFO_invalid)
3858 return TokError(
3859 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3860 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3861
3862 Result.assign(Macinfo);
3863 Lex.Lex();
3864 return false;
3865}
3866
3867template <>
3868bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003869 DwarfVirtualityField &Result) {
3870 if (Lex.getKind() == lltok::APSInt)
3871 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3872
3873 if (Lex.getKind() != lltok::DwarfVirtuality)
3874 return TokError("expected DWARF virtuality code");
3875
3876 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
Peter Collingbournea1f86252016-03-17 23:58:03 +00003877 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003878 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3879 Lex.getStrVal() + "'");
3880 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3881 Result.assign(Virtuality);
3882 Lex.Lex();
3883 return false;
3884}
3885
3886template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003887bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3888 if (Lex.getKind() == lltok::APSInt)
3889 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3890
3891 if (Lex.getKind() != lltok::DwarfLang)
3892 return TokError("expected DWARF language");
3893
3894 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3895 if (!Lang)
3896 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3897 "'");
3898 assert(Lang <= Result.Max && "Expected valid DWARF language");
3899 Result.assign(Lang);
3900 Lex.Lex();
3901 return false;
3902}
3903
3904template <>
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003905bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3906 if (Lex.getKind() == lltok::APSInt)
3907 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3908
3909 if (Lex.getKind() != lltok::DwarfCC)
3910 return TokError("expected DWARF calling convention");
3911
3912 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3913 if (!CC)
3914 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3915 "'");
3916 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
3917 Result.assign(CC);
3918 Lex.Lex();
3919 return false;
3920}
3921
3922template <>
Adrian Prantlb939a252016-03-31 23:56:58 +00003923bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3924 if (Lex.getKind() == lltok::APSInt)
3925 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3926
3927 if (Lex.getKind() != lltok::EmissionKind)
3928 return TokError("expected emission kind");
3929
3930 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3931 if (!Kind)
3932 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3933 "'");
3934 assert(*Kind <= Result.Max && "Expected valid emission kind");
3935 Result.assign(*Kind);
3936 Lex.Lex();
3937 return false;
3938}
Fangrui Songf78650a2018-07-30 19:41:25 +00003939
Adrian Prantlb939a252016-03-31 23:56:58 +00003940template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003941bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
David Blaikie66cf14d2018-08-16 21:29:55 +00003942 NameTableKindField &Result) {
3943 if (Lex.getKind() == lltok::APSInt)
3944 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3945
3946 if (Lex.getKind() != lltok::NameTableKind)
3947 return TokError("expected nameTable kind");
3948
3949 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
3950 if (!Kind)
3951 return TokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
3952 "'");
3953 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
3954 Result.assign((unsigned)*Kind);
3955 Lex.Lex();
3956 return false;
3957}
3958
3959template <>
3960bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003961 DwarfAttEncodingField &Result) {
3962 if (Lex.getKind() == lltok::APSInt)
3963 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3964
3965 if (Lex.getKind() != lltok::DwarfAttEncoding)
3966 return TokError("expected DWARF type attribute encoding");
3967
3968 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3969 if (!Encoding)
3970 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3971 Lex.getStrVal() + "'");
3972 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3973 Result.assign(Encoding);
3974 Lex.Lex();
3975 return false;
3976}
3977
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003978/// DIFlagField
3979/// ::= uint32
3980/// ::= DIFlagVector
3981/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3982template <>
3983bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003984
3985 // Parser for a single flag.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003986 auto parseFlag = [&](DINode::DIFlags &Val) {
3987 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
3988 uint32_t TempVal = static_cast<uint32_t>(Val);
3989 bool Res = ParseUInt32(TempVal);
3990 Val = static_cast<DINode::DIFlags>(TempVal);
3991 return Res;
3992 }
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003993
3994 if (Lex.getKind() != lltok::DIFlag)
3995 return TokError("expected debug info flag");
3996
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003997 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003998 if (!Val)
3999 return TokError(Twine("invalid debug info flag flag '") +
4000 Lex.getStrVal() + "'");
4001 Lex.Lex();
4002 return false;
4003 };
4004
4005 // Parse the flags and combine them together.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00004006 DINode::DIFlags Combined = DINode::FlagZero;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004007 do {
Leny Kholodov5fcc4182016-09-06 10:46:28 +00004008 DINode::DIFlags Val;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004009 if (parseFlag(Val))
4010 return true;
4011 Combined |= Val;
4012 } while (EatIfPresent(lltok::bar));
4013
4014 Result.assign(Combined);
4015 return false;
4016}
4017
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00004018template <>
4019bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004020 MDSignedField &Result) {
4021 if (Lex.getKind() != lltok::APSInt)
4022 return TokError("expected signed integer");
4023
4024 auto &S = Lex.getAPSIntVal();
4025 if (S < Result.Min)
4026 return TokError("value for '" + Name + "' too small, limit is " +
4027 Twine(Result.Min));
4028 if (S > Result.Max)
4029 return TokError("value for '" + Name + "' too large, limit is " +
4030 Twine(Result.Max));
4031 Result.assign(S.getExtValue());
4032 assert(Result.Val >= Result.Min && "Expected value in range");
4033 assert(Result.Val <= Result.Max && "Expected value in range");
4034 Lex.Lex();
4035 return false;
4036}
4037
4038template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00004039bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
4040 switch (Lex.getKind()) {
4041 default:
4042 return TokError("expected 'true' or 'false'");
4043 case lltok::kw_true:
4044 Result.assign(true);
4045 break;
4046 case lltok::kw_false:
4047 Result.assign(false);
4048 break;
4049 }
4050 Lex.Lex();
4051 return false;
4052}
4053
4054template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004055bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004056 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004057 if (!Result.AllowNull)
4058 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004059 Lex.Lex();
4060 Result.assign(nullptr);
4061 return false;
4062 }
4063
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004064 Metadata *MD;
4065 if (ParseMetadata(MD, nullptr))
4066 return true;
4067
4068 Result.assign(MD);
4069 return false;
4070}
4071
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00004072template <>
Sander de Smalenfdf40912018-01-24 09:56:07 +00004073bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4074 MDSignedOrMDField &Result) {
4075 // Try to parse a signed int.
4076 if (Lex.getKind() == lltok::APSInt) {
4077 MDSignedField Res = Result.A;
4078 if (!ParseMDField(Loc, Name, Res)) {
4079 Result.assign(Res);
4080 return false;
4081 }
4082 return true;
4083 }
4084
4085 // Otherwise, try to parse as an MDField.
4086 MDField Res = Result.B;
4087 if (!ParseMDField(Loc, Name, Res)) {
4088 Result.assign(Res);
4089 return false;
4090 }
4091
4092 return true;
4093}
4094
4095template <>
Momchil Velikov08dc66e2018-02-12 16:10:09 +00004096bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4097 MDSignedOrUnsignedField &Result) {
4098 if (Lex.getKind() != lltok::APSInt)
4099 return false;
4100
4101 if (Lex.getAPSIntVal().isSigned()) {
4102 MDSignedField Res = Result.A;
4103 if (ParseMDField(Loc, Name, Res))
4104 return true;
4105 Result.assign(Res);
4106 return false;
4107 }
4108
4109 MDUnsignedField Res = Result.B;
4110 if (ParseMDField(Loc, Name, Res))
4111 return true;
4112 Result.assign(Res);
4113 return false;
4114}
4115
4116template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004117bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004118 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004119 std::string S;
4120 if (ParseStringConstant(S))
4121 return true;
4122
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004123 if (!Result.AllowEmpty && S.empty())
4124 return Error(ValueLoc, "'" + Name + "' cannot be empty");
4125
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00004126 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004127 return false;
4128}
4129
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00004130template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004131bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
4132 SmallVector<Metadata *, 4> MDs;
4133 if (ParseMDNodeVector(MDs))
4134 return true;
4135
4136 Result.assign(std::move(MDs));
4137 return false;
4138}
4139
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004140template <>
4141bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4142 ChecksumKindField &Result) {
Scott Linder71603842018-02-12 19:45:54 +00004143 Optional<DIFile::ChecksumKind> CSKind =
4144 DIFile::getChecksumKind(Lex.getStrVal());
4145
4146 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004147 return TokError(
4148 "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
4149
Scott Linder71603842018-02-12 19:45:54 +00004150 Result.assign(*CSKind);
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004151 Lex.Lex();
4152 return false;
4153}
4154
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00004155} // end namespace llvm
4156
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004157template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00004158bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004159 do {
4160 if (Lex.getKind() != lltok::LabelStr)
4161 return TokError("expected field label here");
4162
4163 if (parseField())
4164 return true;
4165 } while (EatIfPresent(lltok::comma));
4166
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00004167 return false;
4168}
4169
4170template <class ParserTy>
4171bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
4172 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4173 Lex.Lex();
4174
4175 if (ParseToken(lltok::lparen, "expected '(' here"))
4176 return true;
4177 if (Lex.getKind() != lltok::rparen)
4178 if (ParseMDFieldsImplBody(parseField))
4179 return true;
4180
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00004181 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004182 return ParseToken(lltok::rparen, "expected ')' here");
4183}
4184
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00004185template <class FieldTy>
4186bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
4187 if (Result.Seen)
4188 return TokError("field '" + Name + "' cannot be specified more than once");
4189
4190 LocTy Loc = Lex.getLoc();
4191 Lex.Lex();
4192 return ParseMDField(Loc, Name, Result);
4193}
4194
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004195bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
4196 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004197
4198#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004199 if (Lex.getStrVal() == #CLASS) \
4200 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004201#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004202
4203 return TokError("expected metadata type");
4204}
4205
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004206#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4207#define NOP_FIELD(NAME, TYPE, INIT)
4208#define REQUIRE_FIELD(NAME, TYPE, INIT) \
4209 if (!NAME.Seen) \
4210 return Error(ClosingLoc, "missing required field '" #NAME "'");
4211#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00004212 if (Lex.getStrVal() == #NAME) \
4213 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004214#define PARSE_MD_FIELDS() \
4215 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
4216 do { \
4217 LocTy ClosingLoc; \
4218 if (ParseMDFieldsImpl([&]() -> bool { \
4219 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
4220 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
4221 }, ClosingLoc)) \
4222 return true; \
4223 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
4224 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004225#define GET_OR_DISTINCT(CLASS, ARGS) \
4226 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004227
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004228/// ParseDILocationFields:
4229/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
4230bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004231#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00004232 OPTIONAL(line, LineField, ); \
4233 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004234 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004235 OPTIONAL(inlinedAt, MDField, );
4236 PARSE_MD_FIELDS();
4237#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004238
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00004239 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004240 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004241 return false;
4242}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004243
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004244/// ParseGenericDINode:
4245/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4246bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004247#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00004248 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004249 OPTIONAL(header, MDStringField, ); \
4250 OPTIONAL(operands, MDFieldList, );
4251 PARSE_MD_FIELDS();
4252#undef VISIT_MD_FIELDS
4253
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004254 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004255 (Context, tag.Val, header.Val, operands.Val));
4256 return false;
4257}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004258
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004259/// ParseDISubrange:
4260/// ::= !DISubrange(count: 30, lowerBound: 2)
Sander de Smalenfdf40912018-01-24 09:56:07 +00004261/// ::= !DISubrange(count: !node, lowerBound: 2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004262bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004263#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Sander de Smalenfdf40912018-01-24 09:56:07 +00004264 REQUIRED(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004265 OPTIONAL(lowerBound, MDSignedField, );
4266 PARSE_MD_FIELDS();
4267#undef VISIT_MD_FIELDS
4268
Sander de Smalenfdf40912018-01-24 09:56:07 +00004269 if (count.isMDSignedField())
4270 Result = GET_OR_DISTINCT(
4271 DISubrange, (Context, count.getMDSignedValue(), lowerBound.Val));
4272 else if (count.isMDField())
4273 Result = GET_OR_DISTINCT(
4274 DISubrange, (Context, count.getMDFieldValue(), lowerBound.Val));
4275 else
4276 return true;
4277
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004278 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004279}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004280
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004281/// ParseDIEnumerator:
Momchil Velikov08dc66e2018-02-12 16:10:09 +00004282/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004283bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004284#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00004285 REQUIRED(name, MDStringField, ); \
Momchil Velikov08dc66e2018-02-12 16:10:09 +00004286 REQUIRED(value, MDSignedOrUnsignedField, ); \
4287 OPTIONAL(isUnsigned, MDBoolField, (false));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004288 PARSE_MD_FIELDS();
4289#undef VISIT_MD_FIELDS
4290
Momchil Velikov08dc66e2018-02-12 16:10:09 +00004291 if (isUnsigned.Val && value.isMDSignedField())
4292 return TokError("unsigned enumerator with negative value");
4293
4294 int64_t Value = value.isMDSignedField()
4295 ? value.getMDSignedValue()
4296 : static_cast<int64_t>(value.getMDUnsignedValue());
4297 Result =
4298 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
4299
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004300 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004301}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004302
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004303/// ParseDIBasicType:
Adrian Prantl55f42622018-08-14 19:35:34 +00004304/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
4305/// encoding: DW_ATE_encoding, flags: 0)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004306bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004307#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004308 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004309 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004310 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00004311 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Adrian Prantl55f42622018-08-14 19:35:34 +00004312 OPTIONAL(encoding, DwarfAttEncodingField, ); \
4313 OPTIONAL(flags, DIFlagField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004314 PARSE_MD_FIELDS();
4315#undef VISIT_MD_FIELDS
4316
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004317 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Adrian Prantl55f42622018-08-14 19:35:34 +00004318 align.Val, encoding.Val, flags.Val));
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004319 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004320}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004321
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004322/// ParseDIDerivedType:
4323/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004324/// line: 7, scope: !1, baseType: !2, size: 32,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004325/// align: 32, offset: 0, flags: 0, extraData: !3,
4326/// dwarfAddressSpace: 3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004327bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004328#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4329 REQUIRED(tag, DwarfTagField, ); \
4330 OPTIONAL(name, MDStringField, ); \
4331 OPTIONAL(file, MDField, ); \
4332 OPTIONAL(line, LineField, ); \
4333 OPTIONAL(scope, MDField, ); \
4334 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004335 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00004336 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004337 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004338 OPTIONAL(flags, DIFlagField, ); \
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004339 OPTIONAL(extraData, MDField, ); \
4340 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004341 PARSE_MD_FIELDS();
4342#undef VISIT_MD_FIELDS
4343
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004344 Optional<unsigned> DWARFAddressSpace;
4345 if (dwarfAddressSpace.Val != UINT32_MAX)
4346 DWARFAddressSpace = dwarfAddressSpace.Val;
4347
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004348 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004349 (Context, tag.Val, name.Val, file.Val, line.Val,
4350 scope.Val, baseType.Val, size.Val, align.Val,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004351 offset.Val, DWARFAddressSpace, flags.Val,
4352 extraData.Val));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004353 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004354}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004355
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004356bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004357#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4358 REQUIRED(tag, DwarfTagField, ); \
4359 OPTIONAL(name, MDStringField, ); \
4360 OPTIONAL(file, MDField, ); \
4361 OPTIONAL(line, LineField, ); \
4362 OPTIONAL(scope, MDField, ); \
4363 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004364 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00004365 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004366 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004367 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004368 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00004369 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004370 OPTIONAL(vtableHolder, MDField, ); \
4371 OPTIONAL(templateParams, MDField, ); \
Adrian Prantl8c599212018-02-06 23:45:59 +00004372 OPTIONAL(identifier, MDStringField, ); \
4373 OPTIONAL(discriminator, MDField, );
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004374 PARSE_MD_FIELDS();
4375#undef VISIT_MD_FIELDS
4376
Duncan P. N. Exon Smith97386022016-04-19 18:00:19 +00004377 // If this has an identifier try to build an ODR type.
4378 if (identifier.Val)
4379 if (auto *CT = DICompositeType::buildODRType(
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00004380 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
4381 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
4382 elements.Val, runtimeLang.Val, vtableHolder.Val,
Adrian Prantl8c599212018-02-06 23:45:59 +00004383 templateParams.Val, discriminator.Val)) {
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00004384 Result = CT;
4385 return false;
4386 }
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00004387
4388 // Create a new node, and save it in the context if it belongs in the type
4389 // map.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004390 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004391 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004392 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
4393 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
Adrian Prantl8c599212018-02-06 23:45:59 +00004394 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
4395 discriminator.Val));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004396 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004397}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004398
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004399bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004400#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004401 OPTIONAL(flags, DIFlagField, ); \
Reid Klecknerde3d8b52016-06-08 20:34:29 +00004402 OPTIONAL(cc, DwarfCCField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004403 REQUIRED(types, MDField, );
4404 PARSE_MD_FIELDS();
4405#undef VISIT_MD_FIELDS
4406
Reid Klecknerde3d8b52016-06-08 20:34:29 +00004407 Result = GET_OR_DISTINCT(DISubroutineType,
4408 (Context, flags.Val, cc.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004409 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004410}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004411
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004412/// ParseDIFileType:
Scott Linder16c7bda2018-02-23 23:01:06 +00004413/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004414/// checksumkind: CSK_MD5,
Scott Linder16c7bda2018-02-23 23:01:06 +00004415/// checksum: "000102030405060708090a0b0c0d0e0f",
4416/// source: "source file contents")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004417bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Scott Linder71603842018-02-12 19:45:54 +00004418 // The default constructed value for checksumkind is required, but will never
4419 // be used, as the parser checks if the field was actually Seen before using
4420 // the Val.
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004421#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4422 REQUIRED(filename, MDStringField, ); \
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004423 REQUIRED(directory, MDStringField, ); \
Scott Linder71603842018-02-12 19:45:54 +00004424 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
Scott Linder16c7bda2018-02-23 23:01:06 +00004425 OPTIONAL(checksum, MDStringField, ); \
4426 OPTIONAL(source, MDStringField, );
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004427 PARSE_MD_FIELDS();
4428#undef VISIT_MD_FIELDS
4429
Scott Linder71603842018-02-12 19:45:54 +00004430 Optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
4431 if (checksumkind.Seen && checksum.Seen)
4432 OptChecksum.emplace(checksumkind.Val, checksum.Val);
4433 else if (checksumkind.Seen || checksum.Seen)
4434 return Lex.Error("'checksumkind' and 'checksum' must be provided together");
4435
Scott Linder16c7bda2018-02-23 23:01:06 +00004436 Optional<MDString *> OptSource;
4437 if (source.Seen)
4438 OptSource = source.Val;
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004439 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
Scott Linder16c7bda2018-02-23 23:01:06 +00004440 OptChecksum, OptSource));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004441 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004442}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004443
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004444/// ParseDICompileUnit:
4445/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004446/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
Adrian Prantlb939a252016-03-31 23:56:58 +00004447/// splitDebugFilename: "abc.debug",
Adrian Prantl75819ae2016-04-15 15:57:41 +00004448/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
Amjad Abouda9bcf162015-12-10 12:56:35 +00004449/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004450bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004451 if (!IsDistinct)
4452 return Lex.Error("missing 'distinct', required for !DICompileUnit");
4453
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004454#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4455 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00004456 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004457 OPTIONAL(producer, MDStringField, ); \
4458 OPTIONAL(isOptimized, MDBoolField, ); \
4459 OPTIONAL(flags, MDStringField, ); \
4460 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4461 OPTIONAL(splitDebugFilename, MDStringField, ); \
Adrian Prantlb939a252016-03-31 23:56:58 +00004462 OPTIONAL(emissionKind, EmissionKindField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004463 OPTIONAL(enums, MDField, ); \
4464 OPTIONAL(retainedTypes, MDField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004465 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00004466 OPTIONAL(imports, MDField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004467 OPTIONAL(macros, MDField, ); \
David Blaikiea01f2952016-08-24 18:29:49 +00004468 OPTIONAL(dwoId, MDUnsignedField, ); \
Dehao Chen0944a8c2017-02-01 22:45:09 +00004469 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
Peter Collingbourneb52e2362017-09-12 21:50:41 +00004470 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
David Blaikie66cf14d2018-08-16 21:29:55 +00004471 OPTIONAL(nameTableKind, NameTableKindField, );
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004472 PARSE_MD_FIELDS();
4473#undef VISIT_MD_FIELDS
4474
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004475 Result = DICompileUnit::getDistinct(
4476 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4477 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
David Blaikiea01f2952016-08-24 18:29:49 +00004478 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
David Blaikie66cf14d2018-08-16 21:29:55 +00004479 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004480 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004481}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004482
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004483/// ParseDISubprogram:
4484/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004485/// file: !1, line: 7, type: !2, isLocal: false,
4486/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004487/// virtuality: DW_VIRTUALTIY_pure_virtual,
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004488/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
Peter Collingbourned4bff302015-11-05 22:03:56 +00004489/// isOptimized: false, templateParams: !4, declaration: !5,
Shiva Chen2c864552018-05-09 02:40:45 +00004490/// retainedNodes: !6, thrownTypes: !7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004491bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004492 auto Loc = Lex.getLoc();
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004493#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4494 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004495 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004496 OPTIONAL(linkageName, MDStringField, ); \
4497 OPTIONAL(file, MDField, ); \
4498 OPTIONAL(line, LineField, ); \
4499 OPTIONAL(type, MDField, ); \
4500 OPTIONAL(isLocal, MDBoolField, ); \
4501 OPTIONAL(isDefinition, MDBoolField, (true)); \
4502 OPTIONAL(scopeLine, LineField, ); \
4503 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004504 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004505 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004506 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004507 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004508 OPTIONAL(isOptimized, MDBoolField, ); \
Adrian Prantl75819ae2016-04-15 15:57:41 +00004509 OPTIONAL(unit, MDField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004510 OPTIONAL(templateParams, MDField, ); \
4511 OPTIONAL(declaration, MDField, ); \
Shiva Chen2c864552018-05-09 02:40:45 +00004512 OPTIONAL(retainedNodes, MDField, ); \
Adrian Prantl1d12b882017-04-26 22:56:44 +00004513 OPTIONAL(thrownTypes, MDField, );
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004514 PARSE_MD_FIELDS();
4515#undef VISIT_MD_FIELDS
4516
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004517 if (isDefinition.Val && !IsDistinct)
4518 return Lex.Error(
4519 Loc,
4520 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
4521
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004522 Result = GET_OR_DISTINCT(
Adrian Prantl1d12b882017-04-26 22:56:44 +00004523 DISubprogram,
4524 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
4525 type.Val, isLocal.Val, isDefinition.Val, scopeLine.Val,
4526 containingType.Val, virtuality.Val, virtualIndex.Val, thisAdjustment.Val,
4527 flags.Val, isOptimized.Val, unit.Val, templateParams.Val,
Shiva Chen2c864552018-05-09 02:40:45 +00004528 declaration.Val, retainedNodes.Val, thrownTypes.Val));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004529 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004530}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004531
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004532/// ParseDILexicalBlock:
4533/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4534bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004535#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004536 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004537 OPTIONAL(file, MDField, ); \
4538 OPTIONAL(line, LineField, ); \
4539 OPTIONAL(column, ColumnField, );
4540 PARSE_MD_FIELDS();
4541#undef VISIT_MD_FIELDS
4542
4543 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004544 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004545 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004546}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004547
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004548/// ParseDILexicalBlockFile:
4549/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4550bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004551#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004552 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004553 OPTIONAL(file, MDField, ); \
4554 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4555 PARSE_MD_FIELDS();
4556#undef VISIT_MD_FIELDS
4557
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004558 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004559 (Context, scope.Val, file.Val, discriminator.Val));
4560 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004561}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004562
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004563/// ParseDINamespace:
4564/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4565bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004566#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4567 REQUIRED(scope, MDField, ); \
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004568 OPTIONAL(name, MDStringField, ); \
Adrian Prantldbfda632016-11-03 19:42:02 +00004569 OPTIONAL(exportSymbols, MDBoolField, );
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004570 PARSE_MD_FIELDS();
4571#undef VISIT_MD_FIELDS
4572
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004573 Result = GET_OR_DISTINCT(DINamespace,
Adrian Prantlfed4f392017-04-28 22:25:46 +00004574 (Context, scope.Val, name.Val, exportSymbols.Val));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004575 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004576}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004577
Amjad Abouda9bcf162015-12-10 12:56:35 +00004578/// ParseDIMacro:
4579/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4580bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4581#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4582 REQUIRED(type, DwarfMacinfoTypeField, ); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004583 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004584 REQUIRED(name, MDStringField, ); \
4585 OPTIONAL(value, MDStringField, );
4586 PARSE_MD_FIELDS();
4587#undef VISIT_MD_FIELDS
4588
4589 Result = GET_OR_DISTINCT(DIMacro,
4590 (Context, type.Val, line.Val, name.Val, value.Val));
4591 return false;
4592}
4593
4594/// ParseDIMacroFile:
4595/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4596bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4597#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4598 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004599 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004600 REQUIRED(file, MDField, ); \
4601 OPTIONAL(nodes, MDField, );
4602 PARSE_MD_FIELDS();
4603#undef VISIT_MD_FIELDS
4604
4605 Result = GET_OR_DISTINCT(DIMacroFile,
4606 (Context, type.Val, line.Val, file.Val, nodes.Val));
4607 return false;
4608}
4609
Adrian Prantlab1243f2015-06-29 23:03:47 +00004610/// ParseDIModule:
4611/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4612/// includePath: "/usr/include", isysroot: "/")
4613bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4614#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4615 REQUIRED(scope, MDField, ); \
4616 REQUIRED(name, MDStringField, ); \
4617 OPTIONAL(configMacros, MDStringField, ); \
4618 OPTIONAL(includePath, MDStringField, ); \
4619 OPTIONAL(isysroot, MDStringField, );
4620 PARSE_MD_FIELDS();
4621#undef VISIT_MD_FIELDS
4622
4623 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4624 configMacros.Val, includePath.Val, isysroot.Val));
4625 return false;
4626}
4627
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004628/// ParseDITemplateTypeParameter:
4629/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4630bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004631#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004632 OPTIONAL(name, MDStringField, ); \
4633 REQUIRED(type, MDField, );
4634 PARSE_MD_FIELDS();
4635#undef VISIT_MD_FIELDS
4636
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004637 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004638 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004639 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004640}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004641
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004642/// ParseDITemplateValueParameter:
4643/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004644/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004645bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004646#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004647 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004648 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004649 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004650 REQUIRED(value, MDField, );
4651 PARSE_MD_FIELDS();
4652#undef VISIT_MD_FIELDS
4653
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004654 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004655 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004656 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004657}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004658
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004659/// ParseDIGlobalVariable:
4660/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004661/// file: !1, line: 7, type: !2, isLocal: false,
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004662/// isDefinition: true, declaration: !3, align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004663bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004664#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004665 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004666 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004667 OPTIONAL(linkageName, MDStringField, ); \
4668 OPTIONAL(file, MDField, ); \
4669 OPTIONAL(line, LineField, ); \
4670 OPTIONAL(type, MDField, ); \
4671 OPTIONAL(isLocal, MDBoolField, ); \
4672 OPTIONAL(isDefinition, MDBoolField, (true)); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004673 OPTIONAL(declaration, MDField, ); \
4674 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004675 PARSE_MD_FIELDS();
4676#undef VISIT_MD_FIELDS
4677
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004678 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004679 (Context, scope.Val, name.Val, linkageName.Val,
4680 file.Val, line.Val, type.Val, isLocal.Val,
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004681 isDefinition.Val, declaration.Val, align.Val));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004682 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004683}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004684
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004685/// ParseDILocalVariable:
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004686/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004687/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4688/// align: 8)
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004689/// ::= !DILocalVariable(scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004690/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4691/// align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004692bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004693#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004694 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004695 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004696 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004697 OPTIONAL(file, MDField, ); \
4698 OPTIONAL(line, LineField, ); \
4699 OPTIONAL(type, MDField, ); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004700 OPTIONAL(flags, DIFlagField, ); \
4701 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004702 PARSE_MD_FIELDS();
4703#undef VISIT_MD_FIELDS
4704
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004705 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004706 (Context, scope.Val, name.Val, file.Val, line.Val,
Victor Leschuk2ede1262016-10-20 00:13:12 +00004707 type.Val, arg.Val, flags.Val, align.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004708 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004709}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004710
Shiva Chen2c864552018-05-09 02:40:45 +00004711/// ParseDILabel:
4712/// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
4713bool LLParser::ParseDILabel(MDNode *&Result, bool IsDistinct) {
4714#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4715 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4716 REQUIRED(name, MDStringField, ); \
4717 REQUIRED(file, MDField, ); \
4718 REQUIRED(line, LineField, );
4719 PARSE_MD_FIELDS();
4720#undef VISIT_MD_FIELDS
4721
4722 Result = GET_OR_DISTINCT(DILabel,
4723 (Context, scope.Val, name.Val, file.Val, line.Val));
4724 return false;
4725}
4726
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004727/// ParseDIExpression:
4728/// ::= !DIExpression(0, 7, -1)
4729bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004730 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4731 Lex.Lex();
4732
4733 if (ParseToken(lltok::lparen, "expected '(' here"))
4734 return true;
4735
4736 SmallVector<uint64_t, 8> Elements;
4737 if (Lex.getKind() != lltok::rparen)
4738 do {
4739 if (Lex.getKind() == lltok::DwarfOp) {
4740 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4741 Lex.Lex();
4742 Elements.push_back(Op);
4743 continue;
4744 }
4745 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4746 }
4747
4748 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4749 return TokError("expected unsigned integer");
4750
4751 auto &U = Lex.getAPSIntVal();
4752 if (U.ugt(UINT64_MAX))
4753 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4754 Elements.push_back(U.getZExtValue());
4755 Lex.Lex();
4756 } while (EatIfPresent(lltok::comma));
4757
4758 if (ParseToken(lltok::rparen, "expected ')' here"))
4759 return true;
4760
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004761 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004762 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004763}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004764
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004765/// ParseDIGlobalVariableExpression:
4766/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4767bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
4768 bool IsDistinct) {
4769#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4770 REQUIRED(var, MDField, ); \
Adrian Prantl05782212017-08-30 18:06:51 +00004771 REQUIRED(expr, MDField, );
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004772 PARSE_MD_FIELDS();
4773#undef VISIT_MD_FIELDS
4774
4775 Result =
4776 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
4777 return false;
4778}
4779
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004780/// ParseDIObjCProperty:
4781/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004782/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004783bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004784#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004785 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004786 OPTIONAL(file, MDField, ); \
4787 OPTIONAL(line, LineField, ); \
4788 OPTIONAL(setter, MDStringField, ); \
4789 OPTIONAL(getter, MDStringField, ); \
4790 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4791 OPTIONAL(type, MDField, );
4792 PARSE_MD_FIELDS();
4793#undef VISIT_MD_FIELDS
4794
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004795 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004796 (Context, name.Val, file.Val, line.Val, setter.Val,
4797 getter.Val, attributes.Val, type.Val));
4798 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004799}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004800
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004801/// ParseDIImportedEntity:
4802/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004803/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004804bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004805#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4806 REQUIRED(tag, DwarfTagField, ); \
4807 REQUIRED(scope, MDField, ); \
4808 OPTIONAL(entity, MDField, ); \
Adrian Prantld63bfd22017-07-19 00:09:54 +00004809 OPTIONAL(file, MDField, ); \
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004810 OPTIONAL(line, LineField, ); \
4811 OPTIONAL(name, MDStringField, );
4812 PARSE_MD_FIELDS();
4813#undef VISIT_MD_FIELDS
4814
Adrian Prantld63bfd22017-07-19 00:09:54 +00004815 Result = GET_OR_DISTINCT(
4816 DIImportedEntity,
4817 (Context, tag.Val, scope.Val, entity.Val, file.Val, line.Val, name.Val));
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004818 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004819}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004820
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004821#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004822#undef NOP_FIELD
4823#undef REQUIRE_FIELD
4824#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004825
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004826/// ParseMetadataAsValue
4827/// ::= metadata i32 %local
4828/// ::= metadata i32 @global
4829/// ::= metadata i32 7
4830/// ::= metadata !0
4831/// ::= metadata !{...}
4832/// ::= metadata !"string"
4833bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4834 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004835 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004836 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004837 return true;
4838
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004839 V = MetadataAsValue::get(Context, MD);
4840 return false;
4841}
4842
4843/// ParseValueAsMetadata
4844/// ::= i32 %local
4845/// ::= i32 @global
4846/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004847bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4848 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004849 Type *Ty;
4850 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004851 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004852 return true;
4853 if (Ty->isMetadataTy())
4854 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4855
4856 Value *V;
4857 if (ParseValue(Ty, V, PFS))
4858 return true;
4859
4860 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004861 return false;
4862}
4863
4864/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004865/// ::= i32 %local
4866/// ::= i32 @global
4867/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00004868/// ::= !42
4869/// ::= !{...}
4870/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004871/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004872bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004873 if (Lex.getKind() == lltok::MetadataVar) {
4874 MDNode *N;
4875 if (ParseSpecializedMDNode(N))
4876 return true;
4877 MD = N;
4878 return false;
4879 }
4880
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004881 // ValueAsMetadata:
4882 // <type> <value>
4883 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004884 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004885
4886 // '!'.
4887 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4888 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00004889
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004890 // MDString:
4891 // ::= '!' STRINGCONSTANT
4892 if (Lex.getKind() == lltok::StringConstant) {
4893 MDString *S;
4894 if (ParseMDString(S))
4895 return true;
4896 MD = S;
4897 return false;
4898 }
4899
Dan Gohman8939ba332010-07-14 18:26:50 +00004900 // MDNode:
4901 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004902 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004903 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004904 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004905 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004906 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00004907 return false;
4908}
4909
Victor Hernandez9d75c962010-01-11 22:31:58 +00004910//===----------------------------------------------------------------------===//
4911// Function Parsing.
4912//===----------------------------------------------------------------------===//
4913
Chris Lattner229907c2011-07-18 04:54:35 +00004914bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Alexander Richardsonc11ae182018-02-27 11:15:11 +00004915 PerFunctionState *PFS, bool IsCall) {
Duncan Sands19d0b472010-02-16 11:11:14 +00004916 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004917 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004918
Chris Lattnerac161bf2009-01-02 07:01:27 +00004919 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004920 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004921 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
Alexander Richardsonc11ae182018-02-27 11:15:11 +00004922 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc, IsCall);
Craig Topper2617dcc2014-04-15 06:32:26 +00004923 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004924 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004925 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
Alexander Richardsonc11ae182018-02-27 11:15:11 +00004926 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc, IsCall);
Craig Topper2617dcc2014-04-15 06:32:26 +00004927 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004928 case ValID::t_InlineAsm: {
Karl Schimpf44876c52015-09-03 16:18:32 +00004929 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez9d75c962010-01-11 22:31:58 +00004930 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie41ba2b42015-07-27 23:32:19 +00004931 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4932 (ID.UIntVal >> 1) & 1,
4933 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00004934 return false;
4935 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004936 case ValID::t_GlobalName:
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00004937 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc, IsCall);
Craig Topper2617dcc2014-04-15 06:32:26 +00004938 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004939 case ValID::t_GlobalID:
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00004940 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc, IsCall);
Craig Topper2617dcc2014-04-15 06:32:26 +00004941 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004942 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00004943 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004944 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00004945 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00004946 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004947 return false;
4948 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00004949 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004950 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4951 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004952
Dan Gohman518cda42011-12-17 00:04:22 +00004953 // The lexer has no type info, so builds all half, float, and double FP
4954 // constants as double. Fix this here. Long double does not need this.
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004955 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004956 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00004957 if (Ty->isHalfTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004958 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00004959 &Ignored);
4960 else if (Ty->isFloatTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004961 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00004962 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004963 }
Owen Anderson69c464d2009-07-27 20:59:43 +00004964 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004965
Chris Lattner8f57d29e2009-01-05 18:24:23 +00004966 if (V->getType() != Ty)
4967 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004968 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004969
Chris Lattnerac161bf2009-01-02 07:01:27 +00004970 return false;
4971 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00004972 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004973 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004974 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004975 return false;
4976 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00004977 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004978 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00004979 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004980 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004981 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00004982 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00004983 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00004984 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004985 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00004986 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004987 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00004988 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00004989 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004990 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00004991 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004992 return false;
David Majnemerf0f224d2015-11-11 21:57:16 +00004993 case ValID::t_None:
4994 if (!Ty->isTokenTy())
4995 return Error(ID.Loc, "invalid type for none constant");
4996 V = Constant::getNullValue(Ty);
4997 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004998 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00004999 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005000 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00005001
Chris Lattnerac161bf2009-01-02 07:01:27 +00005002 V = ID.ConstantVal;
5003 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005004 case ValID::t_ConstantStruct:
5005 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00005006 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005007 if (ST->getNumElements() != ID.UIntVal)
5008 return Error(ID.Loc,
5009 "initializer with struct type has wrong # elements");
5010 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
5011 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005012
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005013 // Verify that the elements are compatible with the structtype.
5014 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
5015 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
5016 return Error(ID.Loc, "element " + Twine(i) +
5017 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005018
David Blaikieadbda4b2015-08-03 20:08:41 +00005019 V = ConstantStruct::get(
5020 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005021 } else
5022 return Error(ID.Loc, "constant expression type mismatch");
5023 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005024 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00005025 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005026}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005027
Alex Lorenzd2255952015-07-17 22:07:03 +00005028bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
5029 C = nullptr;
5030 ValID ID;
5031 auto Loc = Lex.getLoc();
5032 if (ParseValID(ID, /*PFS=*/nullptr))
5033 return true;
5034 switch (ID.Kind) {
5035 case ValID::t_APSInt:
5036 case ValID::t_APFloat:
Alex Lorenzb9a68db2015-09-09 13:44:33 +00005037 case ValID::t_Undef:
Alex Lorenzd2255952015-07-17 22:07:03 +00005038 case ValID::t_Constant:
5039 case ValID::t_ConstantStruct:
5040 case ValID::t_PackedConstantStruct: {
5041 Value *V;
Alexander Richardsonc11ae182018-02-27 11:15:11 +00005042 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr, /*IsCall=*/false))
Alex Lorenzd2255952015-07-17 22:07:03 +00005043 return true;
5044 assert(isa<Constant>(V) && "Expected a constant value");
5045 C = cast<Constant>(V);
5046 return false;
5047 }
Eric Christopherb9c56d12017-03-30 22:34:20 +00005048 case ValID::t_Null:
5049 C = Constant::getNullValue(Ty);
5050 return false;
Alex Lorenzd2255952015-07-17 22:07:03 +00005051 default:
5052 return Error(Loc, "expected a constant value");
5053 }
5054}
5055
David Majnemer8a1c45d2015-12-12 05:38:55 +00005056bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005057 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005058 ValID ID;
Alexander Richardsonc11ae182018-02-27 11:15:11 +00005059 return ParseValID(ID, PFS) ||
5060 ConvertValIDToValue(Ty, ID, V, PFS, /*IsCall=*/false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005061}
5062
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005063bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005064 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005065 return ParseType(Ty) ||
5066 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005067}
5068
Chris Lattner3ed871f2009-10-27 19:13:16 +00005069bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
5070 PerFunctionState &PFS) {
5071 Value *V;
5072 Loc = Lex.getLoc();
5073 if (ParseTypeAndValue(V, PFS)) return true;
5074 if (!isa<BasicBlock>(V))
5075 return Error(Loc, "expected a basic block");
5076 BB = cast<BasicBlock>(V);
5077 return false;
5078}
5079
Chris Lattnerac161bf2009-01-02 07:01:27 +00005080/// FunctionHeader
Sean Fertilec70d28b2017-10-26 15:00:26 +00005081/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
5082/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005083/// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
5084/// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00005085bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
5086 // Parse the linkage.
5087 LocTy LinkageLoc = Lex.getLoc();
5088 unsigned Linkage;
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00005089 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00005090 unsigned DLLStorageClass;
Sean Fertilec70d28b2017-10-26 15:00:26 +00005091 bool DSOLocal;
Bill Wendling50d27842012-10-15 20:35:56 +00005092 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005093 unsigned CC;
Rafael Espindola2615c9e2016-05-12 12:37:52 +00005094 bool HasLinkage;
Craig Topper2617dcc2014-04-15 06:32:26 +00005095 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005096 LocTy RetTypeLoc = Lex.getLoc();
Sean Fertilec70d28b2017-10-26 15:00:26 +00005097 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
5098 DSOLocal) ||
Rafael Espindola2615c9e2016-05-12 12:37:52 +00005099 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005100 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005101 return true;
5102
5103 // Verify that the linkage is ok.
5104 switch ((GlobalValue::LinkageTypes)Linkage) {
5105 case GlobalValue::ExternalLinkage:
5106 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00005107 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005108 if (isDefine)
5109 return Error(LinkageLoc, "invalid linkage for function definition");
5110 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00005111 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005112 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00005113 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00005114 case GlobalValue::LinkOnceAnyLinkage:
5115 case GlobalValue::LinkOnceODRLinkage:
5116 case GlobalValue::WeakAnyLinkage:
5117 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005118 if (!isDefine)
5119 return Error(LinkageLoc, "invalid linkage for function declaration");
5120 break;
5121 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00005122 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005123 return Error(LinkageLoc, "invalid function linkage type");
5124 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005125
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00005126 if (!isValidVisibilityForLinkage(Visibility, Linkage))
5127 return Error(LinkageLoc,
5128 "symbol with local linkage must have default visibility");
5129
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005130 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005131 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005132
Chris Lattnerac161bf2009-01-02 07:01:27 +00005133 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00005134
5135 std::string FunctionName;
5136 if (Lex.getKind() == lltok::GlobalVar) {
5137 FunctionName = Lex.getStrVal();
5138 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
5139 unsigned NameID = Lex.getUIntVal();
5140
5141 if (NameID != NumberedVals.size())
5142 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00005143 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00005144 } else {
5145 return TokError("expected function name");
5146 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005147
Chris Lattner3822f632009-01-02 08:05:26 +00005148 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005149
Chris Lattner3822f632009-01-02 08:05:26 +00005150 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005151 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005152
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005153 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005154 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00005155 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005156 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005157 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005158 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005159 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00005160 std::string GC;
Peter Collingbourne96efdd62016-06-14 21:01:22 +00005161 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005162 unsigned AddrSpace = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00005163 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00005164 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00005165 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00005166 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00005167
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005168 if (ParseArgumentList(ArgList, isVarArg) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00005169 ParseOptionalUnnamedAddr(UnnamedAddr) ||
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005170 ParseOptionalProgramAddrSpace(AddrSpace) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005171 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00005172 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00005173 (EatIfPresent(lltok::kw_section) &&
5174 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00005175 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00005176 ParseOptionalAlignment(Alignment) ||
5177 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00005178 ParseStringConstant(GC)) ||
5179 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00005180 ParseGlobalTypeAndValue(Prefix)) ||
5181 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00005182 ParseGlobalTypeAndValue(Prologue)) ||
5183 (EatIfPresent(lltok::kw_personality) &&
5184 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00005185 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005186
Michael Gottesman41748d72013-06-27 00:25:01 +00005187 if (FuncAttrs.contains(Attribute::Builtin))
5188 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00005189
Chris Lattnerac161bf2009-01-02 07:01:27 +00005190 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00005191 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00005192 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005193 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005194 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005195
Chris Lattnerac161bf2009-01-02 07:01:27 +00005196 // Okay, if we got here, the function is syntactically valid. Convert types
5197 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00005198 std::vector<Type*> ParamTypeList;
Reid Klecknerc2cb5602017-04-12 00:38:00 +00005199 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005200
Chris Lattnerac161bf2009-01-02 07:01:27 +00005201 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005202 ParamTypeList.push_back(ArgList[i].Ty);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00005203 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005204 }
5205
Reid Kleckner7f720332017-04-13 00:58:09 +00005206 AttributeList PAL =
5207 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
5208 AttributeSet::get(Context, RetAttrs), Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005209
Bill Wendling749a43d2012-12-30 13:50:49 +00005210 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005211 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
5212
Chris Lattner229907c2011-07-18 04:54:35 +00005213 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00005214 FunctionType::get(RetType, ParamTypeList, isVarArg);
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005215 PointerType *PFT = PointerType::get(FT, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005216
Craig Topper2617dcc2014-04-15 06:32:26 +00005217 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005218 if (!FunctionName.empty()) {
5219 // If this was a definition of a forward reference, remove the definition
5220 // from the forward reference table and fill in the forward ref.
David Blaikie9ebdc692015-09-21 21:07:50 +00005221 auto FRVI = ForwardRefVals.find(FunctionName);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005222 if (FRVI != ForwardRefVals.end()) {
5223 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00005224 if (!Fn)
5225 return Error(FRVI->second.second, "invalid forward reference to "
5226 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00005227 if (Fn->getType() != PFT)
5228 return Error(FRVI->second.second, "invalid forward reference to "
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005229 "function '" + FunctionName + "' with wrong type: "
5230 "expected '" + getTypeString(PFT) + "' but was '" +
5231 getTypeString(Fn->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005232 ForwardRefVals.erase(FRVI);
5233 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00005234 // Reject redefinitions.
5235 return Error(NameLoc, "invalid redefinition of function '" +
5236 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00005237 } else if (M->getNamedValue(FunctionName)) {
5238 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005239 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005240
Dan Gohman399d6ae2009-08-29 23:37:49 +00005241 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005242 // If this is a definition of a forward referenced function, make sure the
5243 // types agree.
David Blaikie9ebdc692015-09-21 21:07:50 +00005244 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005245 if (I != ForwardRefValIDs.end()) {
5246 Fn = cast<Function>(I->second.first);
5247 if (Fn->getType() != PFT)
5248 return Error(NameLoc, "type of definition and forward reference of '@" +
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005249 Twine(NumberedVals.size()) + "' disagree: "
5250 "expected '" + getTypeString(PFT) + "' but was '" +
5251 getTypeString(Fn->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005252 ForwardRefValIDs.erase(I);
5253 }
5254 }
5255
Craig Topper2617dcc2014-04-15 06:32:26 +00005256 if (!Fn)
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005257 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace,
5258 FunctionName, M);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005259 else // Move the forward-reference to the correct spot in the module.
5260 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
5261
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005262 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
5263
Chris Lattnerac161bf2009-01-02 07:01:27 +00005264 if (FunctionName.empty())
5265 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005266
Chris Lattnerac161bf2009-01-02 07:01:27 +00005267 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
Rafael Espindolae4b02312018-01-11 22:15:05 +00005268 maybeSetDSOLocal(DSOLocal, *Fn);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005269 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00005270 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005271 Fn->setCallingConv(CC);
5272 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00005273 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005274 Fn->setAlignment(Alignment);
5275 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00005276 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00005277 Fn->setPersonalityFn(PersonalityFn);
Benjamin Kramer728f4442016-05-29 10:46:35 +00005278 if (!GC.empty()) Fn->setGC(GC);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00005279 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00005280 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005281 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005282
Chris Lattnerac161bf2009-01-02 07:01:27 +00005283 // Add all of the arguments we parsed to the function.
5284 Function::arg_iterator ArgIt = Fn->arg_begin();
5285 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
5286 // If the argument has a name, insert it into the argument symbol table.
5287 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005288
Chris Lattnerac161bf2009-01-02 07:01:27 +00005289 // Set the name, if it conflicted, it will be auto-renamed.
5290 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005291
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00005292 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005293 return Error(ArgList[i].Loc, "redefinition of argument '%" +
5294 ArgList[i].Name + "'");
5295 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005296
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005297 if (isDefine)
5298 return false;
5299
Robin Morisset039781e2014-08-29 21:53:01 +00005300 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005301 ValID ID;
5302 if (FunctionName.empty()) {
5303 ID.Kind = ValID::t_GlobalID;
5304 ID.UIntVal = NumberedVals.size() - 1;
5305 } else {
5306 ID.Kind = ValID::t_GlobalName;
5307 ID.StrVal = FunctionName;
5308 }
5309 auto Blocks = ForwardRefBlockAddresses.find(ID);
5310 if (Blocks != ForwardRefBlockAddresses.end())
5311 return Error(Blocks->first.Loc,
5312 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005313 return false;
5314}
5315
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005316bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
5317 ValID ID;
5318 if (FunctionNumber == -1) {
5319 ID.Kind = ValID::t_GlobalName;
5320 ID.StrVal = F.getName();
5321 } else {
5322 ID.Kind = ValID::t_GlobalID;
5323 ID.UIntVal = FunctionNumber;
5324 }
5325
5326 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
5327 if (Blocks == P.ForwardRefBlockAddresses.end())
5328 return false;
5329
5330 for (const auto &I : Blocks->second) {
5331 const ValID &BBID = I.first;
5332 GlobalValue *GV = I.second;
5333
5334 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
5335 "Expected local id or name");
5336 BasicBlock *BB;
5337 if (BBID.Kind == ValID::t_LocalName)
5338 BB = GetBB(BBID.StrVal, BBID.Loc);
5339 else
5340 BB = GetBB(BBID.UIntVal, BBID.Loc);
5341 if (!BB)
5342 return P.Error(BBID.Loc, "referenced value is not a basic block");
5343
5344 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
5345 GV->eraseFromParent();
5346 }
5347
5348 P.ForwardRefBlockAddresses.erase(Blocks);
5349 return false;
5350}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005351
5352/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005353/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00005354bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00005355 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005356 return TokError("expected '{' in function body");
5357 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005358
Chris Lattner3432c622009-10-28 03:39:23 +00005359 int FunctionNumber = -1;
5360 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005361
Chris Lattner3432c622009-10-28 03:39:23 +00005362 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005363
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005364 // Resolve block addresses and allow basic blocks to be forward-declared
5365 // within this function.
5366 if (PFS.resolveForwardRefBlockAddresses())
5367 return true;
5368 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
5369
Chris Lattnerbbddd962010-01-09 19:20:07 +00005370 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005371 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00005372 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005373
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005374 while (Lex.getKind() != lltok::rbrace &&
5375 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005376 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005377
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005378 while (Lex.getKind() != lltok::rbrace)
5379 if (ParseUseListOrder(&PFS))
5380 return true;
5381
Chris Lattnerac161bf2009-01-02 07:01:27 +00005382 // Eat the }.
5383 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005384
Chris Lattnerac161bf2009-01-02 07:01:27 +00005385 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00005386 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00005387}
5388
5389/// ParseBasicBlock
5390/// ::= LabelStr? Instruction*
5391bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
5392 // If this basic block starts out with a name, remember it.
5393 std::string Name;
5394 LocTy NameLoc = Lex.getLoc();
5395 if (Lex.getKind() == lltok::LabelStr) {
5396 Name = Lex.getStrVal();
5397 Lex.Lex();
5398 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005399
Chris Lattnerac161bf2009-01-02 07:01:27 +00005400 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00005401 if (!BB)
5402 return Error(NameLoc,
5403 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005404
Chris Lattnerac161bf2009-01-02 07:01:27 +00005405 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005406
Chris Lattnerac161bf2009-01-02 07:01:27 +00005407 // Parse the instructions in this block until we get a terminator.
5408 Instruction *Inst;
5409 do {
5410 // This instruction may have three possibilities for a name: a) none
5411 // specified, b) name specified "%foo =", c) number specified: "%4 =".
5412 LocTy NameLoc = Lex.getLoc();
5413 int NameID = -1;
5414 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005415
Chris Lattnerac161bf2009-01-02 07:01:27 +00005416 if (Lex.getKind() == lltok::LocalVarID) {
5417 NameID = Lex.getUIntVal();
5418 Lex.Lex();
5419 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
5420 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00005421 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005422 NameStr = Lex.getStrVal();
5423 Lex.Lex();
5424 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
5425 return true;
5426 }
Devang Patelea8a4b92009-09-17 23:04:48 +00005427
Chris Lattner77b89dc2009-12-30 05:23:43 +00005428 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00005429 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00005430 case InstError: return true;
5431 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00005432 BB->getInstList().push_back(Inst);
5433
Chris Lattner77b89dc2009-12-30 05:23:43 +00005434 // With a normal result, we check to see if the instruction is followed by
5435 // a comma and metadata.
5436 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00005437 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00005438 return true;
5439 break;
5440 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00005441 BB->getInstList().push_back(Inst);
5442
Chris Lattner77b89dc2009-12-30 05:23:43 +00005443 // If the instruction parser ate an extra comma at the end of it, it
5444 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00005445 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00005446 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005447 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00005448 }
Devang Patelea8a4b92009-09-17 23:04:48 +00005449
Chris Lattnerac161bf2009-01-02 07:01:27 +00005450 // Set the name on the instruction.
5451 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
Chandler Carruth9ae926b2018-08-26 09:51:22 +00005452 } while (!Inst->isTerminator());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005453
Chris Lattnerac161bf2009-01-02 07:01:27 +00005454 return false;
5455}
5456
5457//===----------------------------------------------------------------------===//
5458// Instruction Parsing.
5459//===----------------------------------------------------------------------===//
5460
5461/// ParseInstruction - Parse one of the many different instructions.
5462///
Chris Lattner77b89dc2009-12-30 05:23:43 +00005463int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
5464 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005465 lltok::Kind Token = Lex.getKind();
5466 if (Token == lltok::Eof)
5467 return TokError("found end of file when expecting more instructions");
5468 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00005469 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00005470 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005471
Chris Lattnerac161bf2009-01-02 07:01:27 +00005472 switch (Token) {
5473 default: return Error(Loc, "expected instruction opcode");
5474 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00005475 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005476 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
5477 case lltok::kw_br: return ParseBr(Inst, PFS);
5478 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005479 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005480 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00005481 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer654e1302015-07-31 17:58:14 +00005482 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
5483 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005484 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
5485 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005486 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005487 // Binary Operators.
5488 case lltok::kw_add:
5489 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005490 case lltok::kw_mul:
5491 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00005492 bool NUW = EatIfPresent(lltok::kw_nuw);
5493 bool NSW = EatIfPresent(lltok::kw_nsw);
5494 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005495
Chris Lattnera676c0f2011-02-07 16:40:21 +00005496 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005497
Chris Lattnera676c0f2011-02-07 16:40:21 +00005498 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5499 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5500 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005501 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005502 case lltok::kw_fadd:
5503 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00005504 case lltok::kw_fmul:
5505 case lltok::kw_fdiv:
5506 case lltok::kw_frem: {
5507 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5508 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
5509 if (Res != 0)
5510 return Res;
5511 if (FMF.any())
5512 Inst->setFastMathFlags(FMF);
5513 return 0;
5514 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005515
Chris Lattner35315d02011-02-06 21:44:57 +00005516 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005517 case lltok::kw_udiv:
5518 case lltok::kw_lshr:
5519 case lltok::kw_ashr: {
5520 bool Exact = EatIfPresent(lltok::kw_exact);
5521
5522 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5523 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5524 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005525 }
5526
Chris Lattnerac161bf2009-01-02 07:01:27 +00005527 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00005528 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005529 case lltok::kw_and:
5530 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00005531 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00005532 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
5533 case lltok::kw_fcmp: {
5534 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5535 int Res = ParseCompare(Inst, PFS, KeywordVal);
5536 if (Res != 0)
5537 return Res;
5538 if (FMF.any())
5539 Inst->setFastMathFlags(FMF);
5540 return 0;
5541 }
5542
Chris Lattnerac161bf2009-01-02 07:01:27 +00005543 // Casts.
5544 case lltok::kw_trunc:
5545 case lltok::kw_zext:
5546 case lltok::kw_sext:
5547 case lltok::kw_fptrunc:
5548 case lltok::kw_fpext:
5549 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00005550 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005551 case lltok::kw_uitofp:
5552 case lltok::kw_sitofp:
5553 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005554 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005555 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00005556 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005557 // Other.
5558 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00005559 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005560 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5561 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5562 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5563 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00005564 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00005565 // Call.
5566 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5567 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5568 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00005569 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005570 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00005571 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00005572 case lltok::kw_load: return ParseLoad(Inst, PFS);
5573 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00005574 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5575 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005576 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005577 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5578 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5579 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5580 }
5581}
5582
5583/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5584bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005585 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005586 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005587 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005588 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5589 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5590 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5591 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5592 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5593 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5594 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5595 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5596 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5597 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5598 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5599 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5600 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5601 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5602 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5603 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5604 }
5605 } else {
5606 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005607 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005608 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5609 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5610 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5611 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5612 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5613 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5614 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5615 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5616 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5617 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5618 }
5619 }
5620 Lex.Lex();
5621 return false;
5622}
5623
5624//===----------------------------------------------------------------------===//
5625// Terminator Instructions.
5626//===----------------------------------------------------------------------===//
5627
5628/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00005629/// ::= 'ret' void (',' !dbg, !1)*
5630/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00005631bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005632 PerFunctionState &PFS) {
5633 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00005634 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00005635 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005636
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005637 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005638
Chris Lattnerfdd87902009-10-05 05:54:46 +00005639 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005640 if (!ResType->isVoidTy())
5641 return Error(TypeLoc, "value doesn't match function result type '" +
5642 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005643
Owen Anderson55f1c092009-08-13 21:58:54 +00005644 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005645 return false;
5646 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005647
Chris Lattnerac161bf2009-01-02 07:01:27 +00005648 Value *RV;
5649 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005650
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005651 if (ResType != RV->getType())
5652 return Error(TypeLoc, "value doesn't match function result type '" +
5653 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005654
Owen Anderson55f1c092009-08-13 21:58:54 +00005655 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00005656 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005657}
5658
Chris Lattnerac161bf2009-01-02 07:01:27 +00005659/// ParseBr
5660/// ::= 'br' TypeAndValue
5661/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5662bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5663 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005664 Value *Op0;
5665 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005666 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005667
Chris Lattnerac161bf2009-01-02 07:01:27 +00005668 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5669 Inst = BranchInst::Create(BB);
5670 return false;
5671 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005672
Owen Anderson55f1c092009-08-13 21:58:54 +00005673 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005674 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005675
Chris Lattnerac161bf2009-01-02 07:01:27 +00005676 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005677 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005678 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005679 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005680 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005681
Chris Lattner3ed871f2009-10-27 19:13:16 +00005682 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005683 return false;
5684}
5685
5686/// ParseSwitch
5687/// Instruction
5688/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5689/// JumpTable
5690/// ::= (TypeAndValue ',' TypeAndValue)*
5691bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5692 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005693 Value *Cond;
5694 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005695 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5696 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005697 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005698 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5699 return true;
5700
Duncan Sands19d0b472010-02-16 11:11:14 +00005701 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005702 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005703
Chris Lattnerac161bf2009-01-02 07:01:27 +00005704 // Parse the jump table pairs.
5705 SmallPtrSet<Value*, 32> SeenCases;
5706 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5707 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005708 Value *Constant;
5709 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005710
Chris Lattnerac161bf2009-01-02 07:01:27 +00005711 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5712 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005713 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005714 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005715
David Blaikie70573dc2014-11-19 07:49:26 +00005716 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005717 return Error(CondLoc, "duplicate case value in switch");
5718 if (!isa<ConstantInt>(Constant))
5719 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005720
Chris Lattner3ed871f2009-10-27 19:13:16 +00005721 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00005722 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005723
Chris Lattnerac161bf2009-01-02 07:01:27 +00005724 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005725
Chris Lattner3ed871f2009-10-27 19:13:16 +00005726 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005727 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5728 SI->addCase(Table[i].first, Table[i].second);
5729 Inst = SI;
5730 return false;
5731}
5732
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005733/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00005734/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005735/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5736bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005737 LocTy AddrLoc;
5738 Value *Address;
5739 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005740 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5741 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00005742 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005743
Duncan Sands19d0b472010-02-16 11:11:14 +00005744 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005745 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005746
Chris Lattner3ed871f2009-10-27 19:13:16 +00005747 // Parse the destination list.
5748 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005749
Chris Lattner3ed871f2009-10-27 19:13:16 +00005750 if (Lex.getKind() != lltok::rsquare) {
5751 BasicBlock *DestBB;
5752 if (ParseTypeAndBasicBlock(DestBB, PFS))
5753 return true;
5754 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005755
Chris Lattner3ed871f2009-10-27 19:13:16 +00005756 while (EatIfPresent(lltok::comma)) {
5757 if (ParseTypeAndBasicBlock(DestBB, PFS))
5758 return true;
5759 DestList.push_back(DestBB);
5760 }
5761 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005762
Chris Lattner3ed871f2009-10-27 19:13:16 +00005763 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5764 return true;
5765
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005766 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00005767 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5768 IBI->addDestination(DestList[i]);
5769 Inst = IBI;
5770 return false;
5771}
5772
Chris Lattnerac161bf2009-01-02 07:01:27 +00005773/// ParseInvoke
5774/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5775/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5776bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5777 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00005778 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005779 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00005780 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005781 unsigned CC;
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005782 unsigned InvokeAddrSpace;
Craig Topper2617dcc2014-04-15 06:32:26 +00005783 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005784 LocTy RetTypeLoc;
5785 ValID CalleeID;
5786 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005787 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005788
Chris Lattner3ed871f2009-10-27 19:13:16 +00005789 BasicBlock *NormalBB, *UnwindBB;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005790 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005791 ParseOptionalProgramAddrSpace(InvokeAddrSpace) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005792 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005793 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005794 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5795 NoBuiltinLoc) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005796 ParseOptionalOperandBundles(BundleList, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005797 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005798 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005799 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005800 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005801 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005802
Chris Lattnerac161bf2009-01-02 07:01:27 +00005803 // If RetType is a non-function pointer type, then this is the short syntax
5804 // for the call, which means that RetType is just the return type. Infer the
5805 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00005806 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5807 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005808 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005809 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005810 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5811 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005812
Chris Lattnerac161bf2009-01-02 07:01:27 +00005813 if (!FunctionType::isValidReturnType(RetType))
5814 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005815
Owen Anderson4056ca92009-07-29 22:17:13 +00005816 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005817 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005818
David Blaikie41ba2b42015-07-27 23:32:19 +00005819 CalleeID.FTy = Ty;
5820
Chris Lattnerac161bf2009-01-02 07:01:27 +00005821 // Look up the callee.
5822 Value *Callee;
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005823 if (ConvertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID,
5824 Callee, &PFS, /*IsCall=*/true))
David Blaikie445e3fb2015-04-24 19:32:54 +00005825 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005826
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005827 // Set up the Attribute for the function.
Reid Kleckner7f720332017-04-13 00:58:09 +00005828 SmallVector<Value *, 8> Args;
5829 SmallVector<AttributeSet, 8> ArgAttrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005830
Chris Lattnerac161bf2009-01-02 07:01:27 +00005831 // Loop through FunctionType's arguments and ensure they are specified
5832 // correctly. Also, gather any parameter attributes.
5833 FunctionType::param_iterator I = Ty->param_begin();
5834 FunctionType::param_iterator E = Ty->param_end();
5835 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005836 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005837 if (I != E) {
5838 ExpectedTy = *I++;
5839 } else if (!Ty->isVarArg()) {
5840 return Error(ArgList[i].Loc, "too many arguments specified");
5841 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005842
Chris Lattnerac161bf2009-01-02 07:01:27 +00005843 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5844 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005845 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005846 Args.push_back(ArgList[i].V);
Reid Kleckner7f720332017-04-13 00:58:09 +00005847 ArgAttrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005848 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005849
Chris Lattnerac161bf2009-01-02 07:01:27 +00005850 if (I != E)
5851 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005852
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00005853 if (FnAttrs.hasAlignmentAttr())
5854 return Error(CallLoc, "invoke instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00005855
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005856 // Finish off the Attribute and check them
Reid Kleckner7f720332017-04-13 00:58:09 +00005857 AttributeList PAL =
5858 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
5859 AttributeSet::get(Context, RetAttrs), ArgAttrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005860
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005861 InvokeInst *II =
5862 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005863 II->setCallingConv(CC);
5864 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005865 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005866 Inst = II;
5867 return false;
5868}
5869
Bill Wendlingf891bf82011-07-31 06:30:59 +00005870/// ParseResume
5871/// ::= 'resume' TypeAndValue
5872bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5873 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005874 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5875 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005876
Bill Wendlingf891bf82011-07-31 06:30:59 +00005877 ResumeInst *RI = ResumeInst::Create(Exn);
5878 Inst = RI;
5879 return false;
5880}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005881
David Majnemer654e1302015-07-31 17:58:14 +00005882bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5883 PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005884 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
David Majnemer654e1302015-07-31 17:58:14 +00005885 return true;
5886
5887 while (Lex.getKind() != lltok::rsquare) {
5888 // If this isn't the first argument, we need a comma.
5889 if (!Args.empty() &&
5890 ParseToken(lltok::comma, "expected ',' in argument list"))
5891 return true;
5892
5893 // Parse the argument.
5894 LocTy ArgLoc;
5895 Type *ArgTy = nullptr;
5896 if (ParseType(ArgTy, ArgLoc))
5897 return true;
5898
5899 Value *V;
5900 if (ArgTy->isMetadataTy()) {
5901 if (ParseMetadataAsValue(V, PFS))
5902 return true;
5903 } else {
5904 if (ParseValue(ArgTy, V, PFS))
5905 return true;
5906 }
5907 Args.push_back(V);
5908 }
5909
5910 Lex.Lex(); // Lex the ']'.
5911 return false;
5912}
5913
5914/// ParseCleanupRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005915/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
David Majnemer654e1302015-07-31 17:58:14 +00005916bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005917 Value *CleanupPad = nullptr;
David Majnemer654e1302015-07-31 17:58:14 +00005918
David Majnemer8a1c45d2015-12-12 05:38:55 +00005919 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5920 return true;
5921
5922 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005923 return true;
David Majnemer654e1302015-07-31 17:58:14 +00005924
5925 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5926 return true;
5927
5928 BasicBlock *UnwindBB = nullptr;
5929 if (Lex.getKind() == lltok::kw_to) {
5930 Lex.Lex();
5931 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5932 return true;
5933 } else {
5934 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5935 return true;
5936 }
5937 }
5938
David Majnemer8a1c45d2015-12-12 05:38:55 +00005939 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
David Majnemer654e1302015-07-31 17:58:14 +00005940 return false;
5941}
5942
5943/// ParseCatchRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005944/// ::= 'catchret' from Parent Value 'to' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005945bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005946 Value *CatchPad = nullptr;
David Majnemer0bc0eef2015-08-15 02:46:08 +00005947
David Majnemer8a1c45d2015-12-12 05:38:55 +00005948 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5949 return true;
5950
5951 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
David Majnemer0bc0eef2015-08-15 02:46:08 +00005952 return true;
5953
David Majnemer0bc0eef2015-08-15 02:46:08 +00005954 BasicBlock *BB;
5955 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5956 ParseTypeAndBasicBlock(BB, PFS))
5957 return true;
5958
David Majnemer8a1c45d2015-12-12 05:38:55 +00005959 Inst = CatchReturnInst::Create(CatchPad, BB);
5960 return false;
5961}
5962
5963/// ParseCatchSwitch
5964/// ::= 'catchswitch' within Parent
5965bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5966 Value *ParentPad;
David Majnemer8a1c45d2015-12-12 05:38:55 +00005967
5968 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5969 return true;
5970
5971 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5972 Lex.getKind() != lltok::LocalVarID)
5973 return TokError("expected scope value for catchswitch");
5974
5975 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5976 return true;
5977
5978 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5979 return true;
5980
5981 SmallVector<BasicBlock *, 32> Table;
5982 do {
5983 BasicBlock *DestBB;
5984 if (ParseTypeAndBasicBlock(DestBB, PFS))
5985 return true;
5986 Table.push_back(DestBB);
5987 } while (EatIfPresent(lltok::comma));
5988
5989 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5990 return true;
5991
5992 if (ParseToken(lltok::kw_unwind,
5993 "expected 'unwind' after catchswitch scope"))
5994 return true;
5995
5996 BasicBlock *UnwindBB = nullptr;
5997 if (EatIfPresent(lltok::kw_to)) {
5998 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5999 return true;
6000 } else {
6001 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
6002 return true;
6003 }
6004
6005 auto *CatchSwitch =
6006 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
6007 for (BasicBlock *DestBB : Table)
6008 CatchSwitch->addHandler(DestBB);
6009 Inst = CatchSwitch;
David Majnemer654e1302015-07-31 17:58:14 +00006010 return false;
6011}
6012
6013/// ParseCatchPad
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00006014/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00006015bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00006016 Value *CatchSwitch = nullptr;
6017
6018 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
6019 return true;
6020
6021 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
6022 return TokError("expected scope value for catchpad");
6023
6024 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
6025 return true;
6026
David Majnemer654e1302015-07-31 17:58:14 +00006027 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00006028 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00006029 return true;
6030
David Majnemer8a1c45d2015-12-12 05:38:55 +00006031 Inst = CatchPadInst::Create(CatchSwitch, Args);
David Majnemer654e1302015-07-31 17:58:14 +00006032 return false;
6033}
6034
David Majnemer654e1302015-07-31 17:58:14 +00006035/// ParseCleanupPad
David Majnemer8a1c45d2015-12-12 05:38:55 +00006036/// ::= 'cleanuppad' within Parent ParamList
David Majnemer654e1302015-07-31 17:58:14 +00006037bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00006038 Value *ParentPad = nullptr;
6039
6040 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
6041 return true;
6042
6043 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6044 Lex.getKind() != lltok::LocalVarID)
6045 return TokError("expected scope value for cleanuppad");
6046
6047 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
6048 return true;
6049
David Majnemer654e1302015-07-31 17:58:14 +00006050 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00006051 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00006052 return true;
6053
David Majnemer8a1c45d2015-12-12 05:38:55 +00006054 Inst = CleanupPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00006055 return false;
6056}
6057
Chris Lattnerac161bf2009-01-02 07:01:27 +00006058//===----------------------------------------------------------------------===//
6059// Binary Operators.
6060//===----------------------------------------------------------------------===//
6061
6062/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006063/// ::= ArithmeticOps TypeAndValue ',' Value
6064///
6065/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
6066/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00006067bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006068 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006069 LocTy Loc; Value *LHS, *RHS;
6070 if (ParseTypeAndValue(LHS, Loc, PFS) ||
6071 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
6072 ParseValue(LHS->getType(), RHS, PFS))
6073 return true;
6074
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006075 bool Valid;
6076 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00006077 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006078 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00006079 Valid = LHS->getType()->isIntOrIntVectorTy() ||
6080 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006081 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00006082 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
6083 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006084 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006085
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006086 if (!Valid)
6087 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006088
Chris Lattnerac161bf2009-01-02 07:01:27 +00006089 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6090 return false;
6091}
6092
6093/// ParseLogical
6094/// ::= ArithmeticOps TypeAndValue ',' Value {
6095bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
6096 unsigned Opc) {
6097 LocTy Loc; Value *LHS, *RHS;
6098 if (ParseTypeAndValue(LHS, Loc, PFS) ||
6099 ParseToken(lltok::comma, "expected ',' in logical operation") ||
6100 ParseValue(LHS->getType(), RHS, PFS))
6101 return true;
6102
Duncan Sands9dff9be2010-02-15 16:12:20 +00006103 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006104 return Error(Loc,"instruction requires integer or integer vector operands");
6105
6106 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6107 return false;
6108}
6109
Chris Lattnerac161bf2009-01-02 07:01:27 +00006110/// ParseCompare
6111/// ::= 'icmp' IPredicates TypeAndValue ',' Value
6112/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00006113bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
6114 unsigned Opc) {
6115 // Parse the integer/fp comparison predicate.
6116 LocTy Loc;
6117 unsigned Pred;
6118 Value *LHS, *RHS;
6119 if (ParseCmpPredicate(Pred, Opc) ||
6120 ParseTypeAndValue(LHS, Loc, PFS) ||
6121 ParseToken(lltok::comma, "expected ',' after compare value") ||
6122 ParseValue(LHS->getType(), RHS, PFS))
6123 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006124
Chris Lattnerac161bf2009-01-02 07:01:27 +00006125 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00006126 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006127 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00006128 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00006129 } else {
6130 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00006131 if (!LHS->getType()->isIntOrIntVectorTy() &&
Craig Topper95d23472017-07-09 07:04:00 +00006132 !LHS->getType()->isPtrOrPtrVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006133 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00006134 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006135 }
6136 return false;
6137}
6138
6139//===----------------------------------------------------------------------===//
6140// Other Instructions.
6141//===----------------------------------------------------------------------===//
6142
6143
6144/// ParseCast
6145/// ::= CastOpc TypeAndValue 'to' Type
6146bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
6147 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00006148 LocTy Loc;
6149 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00006150 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006151 if (ParseTypeAndValue(Op, Loc, PFS) ||
6152 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
6153 ParseType(DestTy))
6154 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006155
Chris Lattner89d856e2009-03-01 00:53:13 +00006156 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
6157 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006158 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00006159 getTypeString(Op->getType()) + "' to '" +
6160 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00006161 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006162 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
6163 return false;
6164}
6165
6166/// ParseSelect
6167/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6168bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
6169 LocTy Loc;
6170 Value *Op0, *Op1, *Op2;
6171 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6172 ParseToken(lltok::comma, "expected ',' after select condition") ||
6173 ParseTypeAndValue(Op1, PFS) ||
6174 ParseToken(lltok::comma, "expected ',' after select value") ||
6175 ParseTypeAndValue(Op2, PFS))
6176 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006177
Chris Lattnerac161bf2009-01-02 07:01:27 +00006178 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
6179 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006180
Chris Lattnerac161bf2009-01-02 07:01:27 +00006181 Inst = SelectInst::Create(Op0, Op1, Op2);
6182 return false;
6183}
6184
Chris Lattnerb55ab542009-01-05 08:18:44 +00006185/// ParseVA_Arg
6186/// ::= 'va_arg' TypeAndValue ',' Type
6187bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006188 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00006189 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00006190 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006191 if (ParseTypeAndValue(Op, PFS) ||
6192 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00006193 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006194 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006195
Chris Lattnerb55ab542009-01-05 08:18:44 +00006196 if (!EltTy->isFirstClassType())
6197 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006198
6199 Inst = new VAArgInst(Op, EltTy);
6200 return false;
6201}
6202
6203/// ParseExtractElement
6204/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
6205bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
6206 LocTy Loc;
6207 Value *Op0, *Op1;
6208 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6209 ParseToken(lltok::comma, "expected ',' after extract value") ||
6210 ParseTypeAndValue(Op1, PFS))
6211 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006212
Chris Lattnerac161bf2009-01-02 07:01:27 +00006213 if (!ExtractElementInst::isValidOperands(Op0, Op1))
6214 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006215
Eric Christopherc9742252009-07-25 02:28:41 +00006216 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006217 return false;
6218}
6219
6220/// ParseInsertElement
6221/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6222bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
6223 LocTy Loc;
6224 Value *Op0, *Op1, *Op2;
6225 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6226 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6227 ParseTypeAndValue(Op1, PFS) ||
6228 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6229 ParseTypeAndValue(Op2, PFS))
6230 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006231
Chris Lattnerac161bf2009-01-02 07:01:27 +00006232 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00006233 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006234
Chris Lattnerac161bf2009-01-02 07:01:27 +00006235 Inst = InsertElementInst::Create(Op0, Op1, Op2);
6236 return false;
6237}
6238
6239/// ParseShuffleVector
6240/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6241bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
6242 LocTy Loc;
6243 Value *Op0, *Op1, *Op2;
6244 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6245 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
6246 ParseTypeAndValue(Op1, PFS) ||
6247 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
6248 ParseTypeAndValue(Op2, PFS))
6249 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006250
Chris Lattnerac161bf2009-01-02 07:01:27 +00006251 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00006252 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006253
Chris Lattnerac161bf2009-01-02 07:01:27 +00006254 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
6255 return false;
6256}
6257
6258/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00006259/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006260int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006261 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006262 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006263
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00006264 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006265 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
6266 ParseValue(Ty, Op0, PFS) ||
6267 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00006268 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006269 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
6270 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006271
Chris Lattnerf4f03422009-12-30 05:27:33 +00006272 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006273 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
Eugene Zelenko1804a772016-08-25 00:45:04 +00006274
6275 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006276 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006277
Chris Lattner3822f632009-01-02 08:05:26 +00006278 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006279 break;
6280
Chris Lattnerf4f03422009-12-30 05:27:33 +00006281 if (Lex.getKind() == lltok::MetadataVar) {
6282 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00006283 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006284 }
Devang Patel8f842d32009-10-16 18:45:49 +00006285
Chris Lattner3822f632009-01-02 08:05:26 +00006286 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006287 ParseValue(Ty, Op0, PFS) ||
6288 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00006289 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006290 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
6291 return true;
6292 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006293
Chris Lattnerac161bf2009-01-02 07:01:27 +00006294 if (!Ty->isFirstClassType())
6295 return Error(TypeLoc, "phi node must have first class type");
6296
Jay Foad52131342011-03-30 11:28:46 +00006297 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00006298 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
6299 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
6300 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006301 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006302}
6303
Bill Wendlingfae14752011-08-12 20:24:12 +00006304/// ParseLandingPad
6305/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
6306/// Clause
6307/// ::= 'catch' TypeAndValue
6308/// ::= 'filter'
6309/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
6310bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006311 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00006312
David Majnemer7fddecc2015-06-17 20:52:32 +00006313 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00006314 return true;
6315
David Majnemer7fddecc2015-06-17 20:52:32 +00006316 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00006317 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
6318
6319 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
6320 LandingPadInst::ClauseType CT;
6321 if (EatIfPresent(lltok::kw_catch))
6322 CT = LandingPadInst::Catch;
6323 else if (EatIfPresent(lltok::kw_filter))
6324 CT = LandingPadInst::Filter;
6325 else
6326 return TokError("expected 'catch' or 'filter' clause type");
6327
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00006328 Value *V;
6329 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00006330 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00006331 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00006332
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00006333 // A 'catch' type expects a non-array constant. A filter clause expects an
6334 // array constant.
6335 if (CT == LandingPadInst::Catch) {
6336 if (isa<ArrayType>(V->getType()))
6337 Error(VLoc, "'catch' clause has an invalid type");
6338 } else {
6339 if (!isa<ArrayType>(V->getType()))
6340 Error(VLoc, "'filter' clause has an invalid type");
6341 }
6342
Owen Andersonf8f259d2015-03-09 07:13:42 +00006343 Constant *CV = dyn_cast<Constant>(V);
6344 if (!CV)
6345 return Error(VLoc, "clause argument must be a constant");
6346 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00006347 }
6348
Owen Andersonf8f259d2015-03-09 07:13:42 +00006349 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00006350 return false;
6351}
6352
Chris Lattnerac161bf2009-01-02 07:01:27 +00006353/// ParseCall
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006354/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
6355/// OptionalAttrs Type Value ParameterList OptionalAttrs
6356/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
6357/// OptionalAttrs Type Value ParameterList OptionalAttrs
6358/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
6359/// OptionalAttrs Type Value ParameterList OptionalAttrs
6360/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
6361/// OptionalAttrs Type Value ParameterList OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +00006362bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00006363 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00006364 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00006365 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00006366 LocTy BuiltinLoc;
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00006367 unsigned CallAddrSpace;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00006368 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00006369 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006370 LocTy RetTypeLoc;
6371 ValID CalleeID;
6372 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006373 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006374 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006375
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006376 if (TCK != CallInst::TCK_None &&
6377 ParseToken(lltok::kw_call,
6378 "expected 'tail call', 'musttail call', or 'notail call'"))
6379 return true;
6380
6381 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6382
6383 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00006384 ParseOptionalProgramAddrSpace(CallAddrSpace) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00006385 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006386 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00006387 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
6388 PFS.getFunction().isVarArg()) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006389 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
6390 ParseOptionalOperandBundles(BundleList, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006391 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006392
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006393 if (FMF.any() && !RetType->isFPOrFPVectorTy())
6394 return Error(CallLoc, "fast-math-flags specified for call without "
6395 "floating-point scalar or vector return type");
6396
Chris Lattnerac161bf2009-01-02 07:01:27 +00006397 // If RetType is a non-function pointer type, then this is the short syntax
6398 // for the call, which means that RetType is just the return type. Infer the
6399 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00006400 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6401 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006402 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00006403 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00006404 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6405 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006406
Chris Lattnerac161bf2009-01-02 07:01:27 +00006407 if (!FunctionType::isValidReturnType(RetType))
6408 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006409
Owen Anderson4056ca92009-07-29 22:17:13 +00006410 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006411 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006412
David Blaikie41ba2b42015-07-27 23:32:19 +00006413 CalleeID.FTy = Ty;
6414
Chris Lattnerac161bf2009-01-02 07:01:27 +00006415 // Look up the callee.
6416 Value *Callee;
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00006417 if (ConvertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,
6418 &PFS, /*IsCall=*/true))
David Blaikie23af6482015-04-16 23:24:18 +00006419 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006420
Bill Wendling3d7b0b82012-12-19 07:18:57 +00006421 // Set up the Attribute for the function.
Reid Klecknerc2cb5602017-04-12 00:38:00 +00006422 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006423
Chris Lattnerac161bf2009-01-02 07:01:27 +00006424 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006425
Chris Lattnerac161bf2009-01-02 07:01:27 +00006426 // Loop through FunctionType's arguments and ensure they are specified
6427 // correctly. Also, gather any parameter attributes.
6428 FunctionType::param_iterator I = Ty->param_begin();
6429 FunctionType::param_iterator E = Ty->param_end();
6430 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006431 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006432 if (I != E) {
6433 ExpectedTy = *I++;
6434 } else if (!Ty->isVarArg()) {
6435 return Error(ArgList[i].Loc, "too many arguments specified");
6436 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006437
Chris Lattnerac161bf2009-01-02 07:01:27 +00006438 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6439 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00006440 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006441 Args.push_back(ArgList[i].V);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00006442 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006443 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006444
Chris Lattnerac161bf2009-01-02 07:01:27 +00006445 if (I != E)
6446 return Error(CallLoc, "not enough parameters specified for call");
6447
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00006448 if (FnAttrs.hasAlignmentAttr())
6449 return Error(CallLoc, "call instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00006450
Bill Wendling3d7b0b82012-12-19 07:18:57 +00006451 // Finish off the Attribute and check them
Reid Kleckner7f720332017-04-13 00:58:09 +00006452 AttributeList PAL =
6453 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6454 AttributeSet::get(Context, RetAttrs), Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006455
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006456 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
Reid Kleckner5772b772014-04-24 20:14:34 +00006457 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006458 CI->setCallingConv(CC);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006459 if (FMF.any())
6460 CI->setFastMathFlags(FMF);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006461 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00006462 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006463 Inst = CI;
6464 return false;
6465}
6466
6467//===----------------------------------------------------------------------===//
6468// Memory Instructions.
6469//===----------------------------------------------------------------------===//
6470
6471/// ParseAlloc
Manman Ren9bfd0d02016-04-01 21:41:15 +00006472/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
Yaxun Liuadde4e42017-10-14 03:23:18 +00006473/// (',' 'align' i32)? (',', 'addrspace(n))?
Chris Lattner78103722011-06-17 03:16:47 +00006474int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006475 Value *Size = nullptr;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006476 LocTy SizeLoc, TyLoc, ASLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006477 unsigned Alignment = 0;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006478 unsigned AddrSpace = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00006479 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006480
6481 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006482 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
David Majnemerc4ab61c2014-03-09 06:41:58 +00006483
David Majnemera3b0eb22015-02-16 08:38:03 +00006484 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006485
David Majnemera3b0eb22015-02-16 08:38:03 +00006486 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
6487 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00006488
Chris Lattnerb2f39502009-12-30 05:44:30 +00006489 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00006490 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00006491 if (Lex.getKind() == lltok::kw_align) {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006492 if (ParseOptionalAlignment(Alignment))
6493 return true;
6494 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6495 return true;
6496 } else if (Lex.getKind() == lltok::kw_addrspace) {
6497 ASLoc = Lex.getLoc();
6498 if (ParseOptionalAddrSpace(AddrSpace))
6499 return true;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006500 } else if (Lex.getKind() == lltok::MetadataVar) {
6501 AteExtraComma = true;
6502 } else {
Yaxun Liuadde4e42017-10-14 03:23:18 +00006503 if (ParseTypeAndValue(Size, SizeLoc, PFS))
David Majnemerc4ab61c2014-03-09 06:41:58 +00006504 return true;
Yaxun Liuadde4e42017-10-14 03:23:18 +00006505 if (EatIfPresent(lltok::comma)) {
6506 if (Lex.getKind() == lltok::kw_align) {
6507 if (ParseOptionalAlignment(Alignment))
6508 return true;
6509 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6510 return true;
6511 } else if (Lex.getKind() == lltok::kw_addrspace) {
6512 ASLoc = Lex.getLoc();
6513 if (ParseOptionalAddrSpace(AddrSpace))
6514 return true;
6515 } else if (Lex.getKind() == lltok::MetadataVar) {
6516 AteExtraComma = true;
6517 }
6518 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006519 }
6520 }
6521
Dan Gohman2140a742010-05-28 01:14:11 +00006522 if (Size && !Size->getType()->isIntegerTy())
6523 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006524
Yaxun Liuc00d81e2018-01-30 22:32:39 +00006525 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, Alignment);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006526 AI->setUsedWithInAlloca(IsInAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006527 AI->setSwiftError(IsSwiftError);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006528 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00006529 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006530}
6531
6532/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00006533/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006534/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00006535/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006536int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006537 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006538 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006539 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006540 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006541 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006542 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006543
6544 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006545 isAtomic = true;
6546 Lex.Lex();
6547 }
6548
Chris Lattnerbc639292011-11-27 06:56:53 +00006549 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006550 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006551 isVolatile = true;
6552 Lex.Lex();
6553 }
6554
David Blaikie15d9a4c2015-04-06 20:59:48 +00006555 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00006556 LocTy ExplicitTypeLoc = Lex.getLoc();
6557 if (ParseType(Ty) ||
6558 ParseToken(lltok::comma, "expected comma after load's type") ||
6559 ParseTypeAndValue(Val, Loc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006560 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006561 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6562 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006563
David Blaikie15d9a4c2015-04-06 20:59:48 +00006564 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006565 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00006566 if (isAtomic && !Alignment)
6567 return Error(Loc, "atomic load must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006568 if (Ordering == AtomicOrdering::Release ||
6569 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006570 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006571
David Blaikiea79ac142015-02-27 21:17:42 +00006572 if (Ty != cast<PointerType>(Val->getType())->getElementType())
6573 return Error(ExplicitTypeLoc,
6574 "explicit pointee type doesn't match operand's pointee type");
6575
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006576 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, SSID);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006577 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006578}
6579
6580/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00006581
6582/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6583/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00006584/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006585int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006586 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006587 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006588 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006589 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006590 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006591 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006592
6593 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006594 isAtomic = true;
6595 Lex.Lex();
6596 }
6597
Chris Lattnerbc639292011-11-27 06:56:53 +00006598 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006599 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006600 isVolatile = true;
6601 Lex.Lex();
6602 }
6603
Chris Lattnerac161bf2009-01-02 07:01:27 +00006604 if (ParseTypeAndValue(Val, Loc, PFS) ||
6605 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006606 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006607 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006608 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006609 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00006610
Duncan Sands19d0b472010-02-16 11:11:14 +00006611 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006612 return Error(PtrLoc, "store operand must be a pointer");
6613 if (!Val->getType()->isFirstClassType())
6614 return Error(Loc, "store operand must be a first class value");
6615 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6616 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00006617 if (isAtomic && !Alignment)
6618 return Error(Loc, "atomic store must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006619 if (Ordering == AtomicOrdering::Acquire ||
6620 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006621 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006622
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006623 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, SSID);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006624 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006625}
6626
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006627/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00006628/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6629/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00006630int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006631 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6632 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006633 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6634 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006635 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006636 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00006637 bool isWeak = false;
6638
6639 if (EatIfPresent(lltok::kw_weak))
6640 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00006641
6642 if (EatIfPresent(lltok::kw_volatile))
6643 isVolatile = true;
6644
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006645 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6646 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6647 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6648 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6649 ParseTypeAndValue(New, NewLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006650 ParseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
Tim Northovere94a5182014-03-11 10:48:52 +00006651 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006652 return true;
6653
JF Bastien800f87a2016-04-06 21:19:33 +00006654 if (SuccessOrdering == AtomicOrdering::Unordered ||
6655 FailureOrdering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006656 return TokError("cmpxchg cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006657 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6658 return TokError("cmpxchg failure argument shall be no stronger than the "
6659 "success argument");
6660 if (FailureOrdering == AtomicOrdering::Release ||
6661 FailureOrdering == AtomicOrdering::AcquireRelease)
6662 return TokError(
6663 "cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006664 if (!Ptr->getType()->isPointerTy())
6665 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6666 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6667 return Error(CmpLoc, "compare value and pointer type do not match");
6668 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6669 return Error(NewLoc, "new value and pointer type do not match");
Philip Reames1960cfd2016-02-19 00:06:41 +00006670 if (!New->getType()->isFirstClassType())
6671 return Error(NewLoc, "cmpxchg operand must be a first class value");
Tim Northover420a2162014-06-13 14:24:07 +00006672 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006673 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, SSID);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006674 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00006675 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006676 Inst = CXI;
6677 return AteExtraComma ? InstExtraComma : InstNormal;
6678}
6679
6680/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00006681/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6682/// 'singlethread'? AtomicOrdering
6683int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006684 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6685 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006686 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006687 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006688 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006689 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00006690
6691 if (EatIfPresent(lltok::kw_volatile))
6692 isVolatile = true;
6693
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006694 switch (Lex.getKind()) {
6695 default: return TokError("expected binary operation in atomicrmw");
6696 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6697 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6698 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6699 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6700 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6701 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6702 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6703 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6704 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6705 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6706 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6707 }
6708 Lex.Lex(); // Eat the operation.
6709
6710 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6711 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6712 ParseTypeAndValue(Val, ValLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006713 ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006714 return true;
6715
JF Bastien800f87a2016-04-06 21:19:33 +00006716 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006717 return TokError("atomicrmw cannot be unordered");
6718 if (!Ptr->getType()->isPointerTy())
6719 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6720 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6721 return Error(ValLoc, "atomicrmw value and pointer type do not match");
6722 if (!Val->getType()->isIntegerTy())
6723 return Error(ValLoc, "atomicrmw operand must be an integer");
6724 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6725 if (Size < 8 || (Size & (Size - 1)))
6726 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6727 " integer");
6728
6729 AtomicRMWInst *RMWI =
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006730 new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006731 RMWI->setVolatile(isVolatile);
6732 Inst = RMWI;
6733 return AteExtraComma ? InstExtraComma : InstNormal;
6734}
6735
Eli Friedmanfee02c62011-07-25 23:16:38 +00006736/// ParseFence
6737/// ::= 'fence' 'singlethread'? AtomicOrdering
6738int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
JF Bastien800f87a2016-04-06 21:19:33 +00006739 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006740 SyncScope::ID SSID = SyncScope::System;
6741 if (ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
Eli Friedmanfee02c62011-07-25 23:16:38 +00006742 return true;
6743
JF Bastien800f87a2016-04-06 21:19:33 +00006744 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006745 return TokError("fence cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006746 if (Ordering == AtomicOrdering::Monotonic)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006747 return TokError("fence cannot be monotonic");
6748
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006749 Inst = new FenceInst(Context, Ordering, SSID);
Eli Friedmanfee02c62011-07-25 23:16:38 +00006750 return InstNormal;
6751}
6752
Chris Lattnerac161bf2009-01-02 07:01:27 +00006753/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00006754/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006755int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006756 Value *Ptr = nullptr;
6757 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006758 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00006759
Dan Gohman16cbbe42009-07-29 15:58:36 +00006760 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00006761
David Blaikie79e6c742015-02-27 19:29:02 +00006762 Type *Ty = nullptr;
6763 LocTy ExplicitTypeLoc = Lex.getLoc();
6764 if (ParseType(Ty) ||
6765 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6766 ParseTypeAndValue(Ptr, Loc, PFS))
6767 return true;
6768
Eli Benderskyd9806682013-04-22 17:03:42 +00006769 Type *BaseType = Ptr->getType();
6770 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6771 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006772 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006773
David Blaikie8d757942015-03-09 23:08:44 +00006774 if (Ty != BasePointerType->getElementType())
6775 return Error(ExplicitTypeLoc,
6776 "explicit pointee type doesn't match operand's pointee type");
6777
Chris Lattnerac161bf2009-01-02 07:01:27 +00006778 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006779 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006780 // GEP returns a vector of pointers if at least one of parameters is a vector.
6781 // All vector parameters should have the same vector width.
6782 unsigned GEPWidth = BaseType->isVectorTy() ?
6783 BaseType->getVectorNumElements() : 0;
6784
Chris Lattner3822f632009-01-02 08:05:26 +00006785 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00006786 if (Lex.getKind() == lltok::MetadataVar) {
6787 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00006788 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006789 }
Chris Lattner3822f632009-01-02 08:05:26 +00006790 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Craig Topper95d23472017-07-09 07:04:00 +00006791 if (!Val->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006792 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006793
Nadav Rotem3924cb02011-12-05 06:29:09 +00006794 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006795 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6796 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00006797 return Error(EltLoc,
6798 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006799 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006800 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006801 Indices.push_back(Val);
6802 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006803
Craig Toppere3dcce92015-08-01 22:20:21 +00006804 SmallPtrSet<Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00006805 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00006806 return Error(Loc, "base element of getelementptr must be sized");
6807
David Blaikied33bad32015-04-17 22:32:13 +00006808 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006809 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00006810 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00006811 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00006812 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006813 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006814}
6815
6816/// ParseExtractValue
6817/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006818int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006819 Value *Val; LocTy Loc;
6820 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006821 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006822 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006823 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006824 return true;
6825
Chris Lattner392be582010-02-12 20:49:41 +00006826 if (!Val->getType()->isAggregateType())
6827 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006828
Jay Foad57aa6362011-07-13 10:26:04 +00006829 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006830 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00006831 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006832 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006833}
6834
6835/// ParseInsertValue
6836/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006837int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006838 Value *Val0, *Val1; LocTy Loc0, Loc1;
6839 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006840 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006841 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6842 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6843 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006844 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006845 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006846
Chris Lattner392be582010-02-12 20:49:41 +00006847 if (!Val0->getType()->isAggregateType())
6848 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006849
David Majnemer30074532015-02-11 07:43:58 +00006850 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6851 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006852 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00006853 if (IndexedType != Val1->getType())
6854 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6855 getTypeString(Val1->getType()) + "' instead of '" +
6856 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00006857 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006858 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006859}
Nick Lewycky49f89192009-04-04 07:22:01 +00006860
6861//===----------------------------------------------------------------------===//
6862// Embedded metadata.
6863//===----------------------------------------------------------------------===//
6864
6865/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006866/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006867/// Element
6868/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006869bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00006870 if (ParseToken(lltok::lbrace, "expected '{' here"))
6871 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006872
Dan Gohman1e0213a2010-07-13 19:33:27 +00006873 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006874 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00006875 return false;
6876
Nick Lewycky49f89192009-04-04 07:22:01 +00006877 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006878 // Null is a special case since it is typeless.
6879 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006880 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006881 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006882 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006883
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006884 Metadata *MD;
6885 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006886 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006887 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00006888 } while (EatIfPresent(lltok::comma));
6889
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006890 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00006891}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006892
6893//===----------------------------------------------------------------------===//
6894// Use-list order directives.
6895//===----------------------------------------------------------------------===//
6896bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6897 SMLoc Loc) {
6898 if (V->use_empty())
6899 return Error(Loc, "value has no uses");
6900
6901 unsigned NumUses = 0;
6902 SmallDenseMap<const Use *, unsigned, 16> Order;
6903 for (const Use &U : V->uses()) {
6904 if (++NumUses > Indexes.size())
6905 break;
6906 Order[&U] = Indexes[NumUses - 1];
6907 }
6908 if (NumUses < 2)
6909 return Error(Loc, "value only has one use");
6910 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
Vedant Kumare0b5f862018-05-10 23:01:54 +00006911 return Error(Loc,
6912 "wrong number of indexes, expected " + Twine(V->getNumUses()));
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006913
6914 V->sortUseList([&](const Use &L, const Use &R) {
6915 return Order.lookup(&L) < Order.lookup(&R);
6916 });
6917 return false;
6918}
6919
6920/// ParseUseListOrderIndexes
6921/// ::= '{' uint32 (',' uint32)+ '}'
6922bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6923 SMLoc Loc = Lex.getLoc();
6924 if (ParseToken(lltok::lbrace, "expected '{' here"))
6925 return true;
6926 if (Lex.getKind() == lltok::rbrace)
6927 return Lex.Error("expected non-empty list of uselistorder indexes");
6928
6929 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6930 // indexes should be distinct numbers in the range [0, size-1], and should
6931 // not be in order.
6932 unsigned Offset = 0;
6933 unsigned Max = 0;
6934 bool IsOrdered = true;
6935 assert(Indexes.empty() && "Expected empty order vector");
6936 do {
6937 unsigned Index;
6938 if (ParseUInt32(Index))
6939 return true;
6940
6941 // Update consistency checks.
6942 Offset += Index - Indexes.size();
6943 Max = std::max(Max, Index);
6944 IsOrdered &= Index == Indexes.size();
6945
6946 Indexes.push_back(Index);
6947 } while (EatIfPresent(lltok::comma));
6948
6949 if (ParseToken(lltok::rbrace, "expected '}' here"))
6950 return true;
6951
6952 if (Indexes.size() < 2)
6953 return Error(Loc, "expected >= 2 uselistorder indexes");
6954 if (Offset != 0 || Max >= Indexes.size())
6955 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6956 if (IsOrdered)
6957 return Error(Loc, "expected uselistorder indexes to change the order");
6958
6959 return false;
6960}
6961
6962/// ParseUseListOrder
6963/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6964bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6965 SMLoc Loc = Lex.getLoc();
6966 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6967 return true;
6968
6969 Value *V;
6970 SmallVector<unsigned, 16> Indexes;
6971 if (ParseTypeAndValue(V, PFS) ||
6972 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6973 ParseUseListOrderIndexes(Indexes))
6974 return true;
6975
6976 return sortUseListOrder(V, Indexes, Loc);
6977}
6978
6979/// ParseUseListOrderBB
6980/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6981bool LLParser::ParseUseListOrderBB() {
6982 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6983 SMLoc Loc = Lex.getLoc();
6984 Lex.Lex();
6985
6986 ValID Fn, Label;
6987 SmallVector<unsigned, 16> Indexes;
6988 if (ParseValID(Fn) ||
6989 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6990 ParseValID(Label) ||
6991 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6992 ParseUseListOrderIndexes(Indexes))
6993 return true;
6994
6995 // Check the function.
6996 GlobalValue *GV;
6997 if (Fn.Kind == ValID::t_GlobalName)
6998 GV = M->getNamedValue(Fn.StrVal);
6999 else if (Fn.Kind == ValID::t_GlobalID)
7000 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
7001 else
7002 return Error(Fn.Loc, "expected function name in uselistorder_bb");
7003 if (!GV)
7004 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
7005 auto *F = dyn_cast<Function>(GV);
7006 if (!F)
7007 return Error(Fn.Loc, "expected function name in uselistorder_bb");
7008 if (F->isDeclaration())
7009 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
7010
7011 // Check the basic block.
7012 if (Label.Kind == ValID::t_LocalID)
7013 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
7014 if (Label.Kind != ValID::t_LocalName)
7015 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
Mehdi Aminia53d49e2016-09-17 06:00:02 +00007016 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00007017 if (!V)
7018 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
7019 if (!isa<BasicBlock>(V))
7020 return Error(Label.Loc, "expected basic block in uselistorder_bb");
7021
7022 return sortUseListOrder(V, Indexes, Loc);
7023}
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007024
7025/// ModuleEntry
7026/// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
7027/// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
7028bool LLParser::ParseModuleEntry(unsigned ID) {
7029 assert(Lex.getKind() == lltok::kw_module);
7030 Lex.Lex();
7031
7032 std::string Path;
7033 if (ParseToken(lltok::colon, "expected ':' here") ||
7034 ParseToken(lltok::lparen, "expected '(' here") ||
7035 ParseToken(lltok::kw_path, "expected 'path' here") ||
7036 ParseToken(lltok::colon, "expected ':' here") ||
7037 ParseStringConstant(Path) ||
7038 ParseToken(lltok::comma, "expected ',' here") ||
7039 ParseToken(lltok::kw_hash, "expected 'hash' here") ||
7040 ParseToken(lltok::colon, "expected ':' here") ||
7041 ParseToken(lltok::lparen, "expected '(' here"))
7042 return true;
7043
7044 ModuleHash Hash;
7045 if (ParseUInt32(Hash[0]) || ParseToken(lltok::comma, "expected ',' here") ||
7046 ParseUInt32(Hash[1]) || ParseToken(lltok::comma, "expected ',' here") ||
7047 ParseUInt32(Hash[2]) || ParseToken(lltok::comma, "expected ',' here") ||
7048 ParseUInt32(Hash[3]) || ParseToken(lltok::comma, "expected ',' here") ||
7049 ParseUInt32(Hash[4]))
7050 return true;
7051
7052 if (ParseToken(lltok::rparen, "expected ')' here") ||
7053 ParseToken(lltok::rparen, "expected ')' here"))
7054 return true;
7055
7056 auto ModuleEntry = Index->addModule(Path, ID, Hash);
7057 ModuleIdMap[ID] = ModuleEntry->first();
7058
7059 return false;
7060}
7061
7062/// TypeIdEntry
7063/// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
7064bool LLParser::ParseTypeIdEntry(unsigned ID) {
7065 assert(Lex.getKind() == lltok::kw_typeid);
7066 Lex.Lex();
7067
7068 std::string Name;
7069 if (ParseToken(lltok::colon, "expected ':' here") ||
7070 ParseToken(lltok::lparen, "expected '(' here") ||
7071 ParseToken(lltok::kw_name, "expected 'name' here") ||
7072 ParseToken(lltok::colon, "expected ':' here") ||
7073 ParseStringConstant(Name))
7074 return true;
7075
7076 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
7077 if (ParseToken(lltok::comma, "expected ',' here") ||
7078 ParseTypeIdSummary(TIS) || ParseToken(lltok::rparen, "expected ')' here"))
7079 return true;
7080
7081 // Check if this ID was forward referenced, and if so, update the
7082 // corresponding GUIDs.
7083 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
7084 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
7085 for (auto TIDRef : FwdRefTIDs->second) {
7086 assert(!*TIDRef.first &&
7087 "Forward referenced type id GUID expected to be 0");
7088 *TIDRef.first = GlobalValue::getGUID(Name);
7089 }
7090 ForwardRefTypeIds.erase(FwdRefTIDs);
7091 }
7092
7093 return false;
7094}
7095
7096/// TypeIdSummary
7097/// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
7098bool LLParser::ParseTypeIdSummary(TypeIdSummary &TIS) {
7099 if (ParseToken(lltok::kw_summary, "expected 'summary' here") ||
7100 ParseToken(lltok::colon, "expected ':' here") ||
7101 ParseToken(lltok::lparen, "expected '(' here") ||
7102 ParseTypeTestResolution(TIS.TTRes))
7103 return true;
7104
7105 if (EatIfPresent(lltok::comma)) {
7106 // Expect optional wpdResolutions field
7107 if (ParseOptionalWpdResolutions(TIS.WPDRes))
7108 return true;
7109 }
7110
7111 if (ParseToken(lltok::rparen, "expected ')' here"))
7112 return true;
7113
7114 return false;
7115}
7116
7117/// TypeTestResolution
7118/// ::= 'typeTestRes' ':' '(' 'kind' ':'
7119/// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
7120/// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
7121/// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
7122/// [',' 'inlinesBits' ':' UInt64]? ')'
7123bool LLParser::ParseTypeTestResolution(TypeTestResolution &TTRes) {
7124 if (ParseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
7125 ParseToken(lltok::colon, "expected ':' here") ||
7126 ParseToken(lltok::lparen, "expected '(' here") ||
7127 ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7128 ParseToken(lltok::colon, "expected ':' here"))
7129 return true;
7130
7131 switch (Lex.getKind()) {
7132 case lltok::kw_unsat:
7133 TTRes.TheKind = TypeTestResolution::Unsat;
7134 break;
7135 case lltok::kw_byteArray:
7136 TTRes.TheKind = TypeTestResolution::ByteArray;
7137 break;
7138 case lltok::kw_inline:
7139 TTRes.TheKind = TypeTestResolution::Inline;
7140 break;
7141 case lltok::kw_single:
7142 TTRes.TheKind = TypeTestResolution::Single;
7143 break;
7144 case lltok::kw_allOnes:
7145 TTRes.TheKind = TypeTestResolution::AllOnes;
7146 break;
7147 default:
7148 return Error(Lex.getLoc(), "unexpected TypeTestResolution kind");
7149 }
7150 Lex.Lex();
7151
7152 if (ParseToken(lltok::comma, "expected ',' here") ||
7153 ParseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
7154 ParseToken(lltok::colon, "expected ':' here") ||
7155 ParseUInt32(TTRes.SizeM1BitWidth))
7156 return true;
7157
7158 // Parse optional fields
7159 while (EatIfPresent(lltok::comma)) {
7160 switch (Lex.getKind()) {
7161 case lltok::kw_alignLog2:
7162 Lex.Lex();
7163 if (ParseToken(lltok::colon, "expected ':'") ||
7164 ParseUInt64(TTRes.AlignLog2))
7165 return true;
7166 break;
7167 case lltok::kw_sizeM1:
7168 Lex.Lex();
7169 if (ParseToken(lltok::colon, "expected ':'") || ParseUInt64(TTRes.SizeM1))
7170 return true;
7171 break;
7172 case lltok::kw_bitMask: {
7173 unsigned Val;
7174 Lex.Lex();
7175 if (ParseToken(lltok::colon, "expected ':'") || ParseUInt32(Val))
7176 return true;
7177 assert(Val <= 0xff);
7178 TTRes.BitMask = (uint8_t)Val;
7179 break;
7180 }
7181 case lltok::kw_inlineBits:
7182 Lex.Lex();
7183 if (ParseToken(lltok::colon, "expected ':'") ||
7184 ParseUInt64(TTRes.InlineBits))
7185 return true;
7186 break;
7187 default:
7188 return Error(Lex.getLoc(), "expected optional TypeTestResolution field");
7189 }
7190 }
7191
7192 if (ParseToken(lltok::rparen, "expected ')' here"))
7193 return true;
7194
7195 return false;
7196}
7197
7198/// OptionalWpdResolutions
7199/// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
7200/// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
7201bool LLParser::ParseOptionalWpdResolutions(
7202 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
7203 if (ParseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
7204 ParseToken(lltok::colon, "expected ':' here") ||
7205 ParseToken(lltok::lparen, "expected '(' here"))
7206 return true;
7207
7208 do {
7209 uint64_t Offset;
7210 WholeProgramDevirtResolution WPDRes;
7211 if (ParseToken(lltok::lparen, "expected '(' here") ||
7212 ParseToken(lltok::kw_offset, "expected 'offset' here") ||
7213 ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(Offset) ||
7214 ParseToken(lltok::comma, "expected ',' here") || ParseWpdRes(WPDRes) ||
7215 ParseToken(lltok::rparen, "expected ')' here"))
7216 return true;
7217 WPDResMap[Offset] = WPDRes;
7218 } while (EatIfPresent(lltok::comma));
7219
7220 if (ParseToken(lltok::rparen, "expected ')' here"))
7221 return true;
7222
7223 return false;
7224}
7225
7226/// WpdRes
7227/// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
7228/// [',' OptionalResByArg]? ')'
7229/// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
7230/// ',' 'singleImplName' ':' STRINGCONSTANT ','
7231/// [',' OptionalResByArg]? ')'
7232/// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
7233/// [',' OptionalResByArg]? ')'
7234bool LLParser::ParseWpdRes(WholeProgramDevirtResolution &WPDRes) {
7235 if (ParseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
7236 ParseToken(lltok::colon, "expected ':' here") ||
7237 ParseToken(lltok::lparen, "expected '(' here") ||
7238 ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7239 ParseToken(lltok::colon, "expected ':' here"))
7240 return true;
7241
7242 switch (Lex.getKind()) {
7243 case lltok::kw_indir:
7244 WPDRes.TheKind = WholeProgramDevirtResolution::Indir;
7245 break;
7246 case lltok::kw_singleImpl:
7247 WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl;
7248 break;
7249 case lltok::kw_branchFunnel:
7250 WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel;
7251 break;
7252 default:
7253 return Error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
7254 }
7255 Lex.Lex();
7256
7257 // Parse optional fields
7258 while (EatIfPresent(lltok::comma)) {
7259 switch (Lex.getKind()) {
7260 case lltok::kw_singleImplName:
7261 Lex.Lex();
7262 if (ParseToken(lltok::colon, "expected ':' here") ||
7263 ParseStringConstant(WPDRes.SingleImplName))
7264 return true;
7265 break;
7266 case lltok::kw_resByArg:
7267 if (ParseOptionalResByArg(WPDRes.ResByArg))
7268 return true;
7269 break;
7270 default:
7271 return Error(Lex.getLoc(),
7272 "expected optional WholeProgramDevirtResolution field");
7273 }
7274 }
7275
7276 if (ParseToken(lltok::rparen, "expected ')' here"))
7277 return true;
7278
7279 return false;
7280}
7281
7282/// OptionalResByArg
7283/// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
7284/// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
7285/// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
7286/// 'virtualConstProp' )
7287/// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
7288/// [',' 'bit' ':' UInt32]? ')'
7289bool LLParser::ParseOptionalResByArg(
7290 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
7291 &ResByArg) {
7292 if (ParseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
7293 ParseToken(lltok::colon, "expected ':' here") ||
7294 ParseToken(lltok::lparen, "expected '(' here"))
7295 return true;
7296
7297 do {
7298 std::vector<uint64_t> Args;
7299 if (ParseArgs(Args) || ParseToken(lltok::comma, "expected ',' here") ||
7300 ParseToken(lltok::kw_byArg, "expected 'byArg here") ||
7301 ParseToken(lltok::colon, "expected ':' here") ||
7302 ParseToken(lltok::lparen, "expected '(' here") ||
7303 ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7304 ParseToken(lltok::colon, "expected ':' here"))
7305 return true;
7306
7307 WholeProgramDevirtResolution::ByArg ByArg;
7308 switch (Lex.getKind()) {
7309 case lltok::kw_indir:
7310 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir;
7311 break;
7312 case lltok::kw_uniformRetVal:
7313 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
7314 break;
7315 case lltok::kw_uniqueRetVal:
7316 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
7317 break;
7318 case lltok::kw_virtualConstProp:
7319 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
7320 break;
7321 default:
7322 return Error(Lex.getLoc(),
7323 "unexpected WholeProgramDevirtResolution::ByArg kind");
7324 }
7325 Lex.Lex();
7326
7327 // Parse optional fields
7328 while (EatIfPresent(lltok::comma)) {
7329 switch (Lex.getKind()) {
7330 case lltok::kw_info:
7331 Lex.Lex();
7332 if (ParseToken(lltok::colon, "expected ':' here") ||
7333 ParseUInt64(ByArg.Info))
7334 return true;
7335 break;
7336 case lltok::kw_byte:
7337 Lex.Lex();
7338 if (ParseToken(lltok::colon, "expected ':' here") ||
7339 ParseUInt32(ByArg.Byte))
7340 return true;
7341 break;
7342 case lltok::kw_bit:
7343 Lex.Lex();
7344 if (ParseToken(lltok::colon, "expected ':' here") ||
7345 ParseUInt32(ByArg.Bit))
7346 return true;
7347 break;
7348 default:
7349 return Error(Lex.getLoc(),
7350 "expected optional whole program devirt field");
7351 }
7352 }
7353
7354 if (ParseToken(lltok::rparen, "expected ')' here"))
7355 return true;
7356
7357 ResByArg[Args] = ByArg;
7358 } while (EatIfPresent(lltok::comma));
7359
7360 if (ParseToken(lltok::rparen, "expected ')' here"))
7361 return true;
7362
7363 return false;
7364}
7365
7366/// OptionalResByArg
7367/// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
7368bool LLParser::ParseArgs(std::vector<uint64_t> &Args) {
7369 if (ParseToken(lltok::kw_args, "expected 'args' here") ||
7370 ParseToken(lltok::colon, "expected ':' here") ||
7371 ParseToken(lltok::lparen, "expected '(' here"))
7372 return true;
7373
7374 do {
7375 uint64_t Val;
7376 if (ParseUInt64(Val))
7377 return true;
7378 Args.push_back(Val);
7379 } while (EatIfPresent(lltok::comma));
7380
7381 if (ParseToken(lltok::rparen, "expected ')' here"))
7382 return true;
7383
7384 return false;
7385}
7386
7387static ValueInfo EmptyVI =
7388 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
7389
7390/// Stores the given Name/GUID and associated summary into the Index.
7391/// Also updates any forward references to the associated entry ID.
7392void LLParser::AddGlobalValueToIndex(
7393 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
7394 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary) {
7395 // First create the ValueInfo utilizing the Name or GUID.
7396 ValueInfo VI;
7397 if (GUID != 0) {
7398 assert(Name.empty());
7399 VI = Index->getOrInsertValueInfo(GUID);
7400 } else {
7401 assert(!Name.empty());
7402 if (M) {
7403 auto *GV = M->getNamedValue(Name);
7404 assert(GV);
7405 VI = Index->getOrInsertValueInfo(GV);
7406 } else {
7407 assert(
7408 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
7409 "Need a source_filename to compute GUID for local");
7410 GUID = GlobalValue::getGUID(
7411 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
7412 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
7413 }
7414 }
7415
7416 // Add the summary if one was provided.
7417 if (Summary)
7418 Index->addGlobalValueSummary(VI, std::move(Summary));
7419
7420 // Resolve forward references from calls/refs
7421 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
7422 if (FwdRefVIs != ForwardRefValueInfos.end()) {
7423 for (auto VIRef : FwdRefVIs->second) {
7424 assert(*VIRef.first == EmptyVI &&
7425 "Forward referenced ValueInfo expected to be empty");
7426 *VIRef.first = VI;
7427 }
7428 ForwardRefValueInfos.erase(FwdRefVIs);
7429 }
7430
7431 // Resolve forward references from aliases
7432 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
7433 if (FwdRefAliasees != ForwardRefAliasees.end()) {
7434 for (auto AliaseeRef : FwdRefAliasees->second) {
7435 assert(!AliaseeRef.first->hasAliasee() &&
7436 "Forward referencing alias already has aliasee");
7437 AliaseeRef.first->setAliasee(VI.getSummaryList().front().get());
7438 }
7439 ForwardRefAliasees.erase(FwdRefAliasees);
7440 }
7441
7442 // Save the associated ValueInfo for use in later references by ID.
7443 if (ID == NumberedValueInfos.size())
7444 NumberedValueInfos.push_back(VI);
7445 else {
7446 // Handle non-continuous numbers (to make test simplification easier).
7447 if (ID > NumberedValueInfos.size())
7448 NumberedValueInfos.resize(ID + 1);
7449 NumberedValueInfos[ID] = VI;
7450 }
7451}
7452
7453/// ParseGVEntry
7454/// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
7455/// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
7456/// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
7457bool LLParser::ParseGVEntry(unsigned ID) {
7458 assert(Lex.getKind() == lltok::kw_gv);
7459 Lex.Lex();
7460
7461 if (ParseToken(lltok::colon, "expected ':' here") ||
7462 ParseToken(lltok::lparen, "expected '(' here"))
7463 return true;
7464
7465 std::string Name;
7466 GlobalValue::GUID GUID = 0;
7467 switch (Lex.getKind()) {
7468 case lltok::kw_name:
7469 Lex.Lex();
7470 if (ParseToken(lltok::colon, "expected ':' here") ||
7471 ParseStringConstant(Name))
7472 return true;
7473 // Can't create GUID/ValueInfo until we have the linkage.
7474 break;
7475 case lltok::kw_guid:
7476 Lex.Lex();
7477 if (ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(GUID))
7478 return true;
7479 break;
7480 default:
7481 return Error(Lex.getLoc(), "expected name or guid tag");
7482 }
7483
7484 if (!EatIfPresent(lltok::comma)) {
7485 // No summaries. Wrap up.
7486 if (ParseToken(lltok::rparen, "expected ')' here"))
7487 return true;
7488 // This was created for a call to an external or indirect target.
7489 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
7490 // created for indirect calls with VP. A Name with no GUID came from
7491 // an external definition. We pass ExternalLinkage since that is only
7492 // used when the GUID must be computed from Name, and in that case
7493 // the symbol must have external linkage.
7494 AddGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
7495 nullptr);
7496 return false;
7497 }
7498
7499 // Have a list of summaries
7500 if (ParseToken(lltok::kw_summaries, "expected 'summaries' here") ||
7501 ParseToken(lltok::colon, "expected ':' here"))
7502 return true;
7503
7504 do {
7505 if (ParseToken(lltok::lparen, "expected '(' here"))
7506 return true;
7507 switch (Lex.getKind()) {
7508 case lltok::kw_function:
7509 if (ParseFunctionSummary(Name, GUID, ID))
7510 return true;
7511 break;
7512 case lltok::kw_variable:
7513 if (ParseVariableSummary(Name, GUID, ID))
7514 return true;
7515 break;
7516 case lltok::kw_alias:
7517 if (ParseAliasSummary(Name, GUID, ID))
7518 return true;
7519 break;
7520 default:
7521 return Error(Lex.getLoc(), "expected summary type");
7522 }
7523 if (ParseToken(lltok::rparen, "expected ')' here"))
7524 return true;
7525 } while (EatIfPresent(lltok::comma));
7526
7527 if (ParseToken(lltok::rparen, "expected ')' here"))
7528 return true;
7529
7530 return false;
7531}
7532
7533/// FunctionSummary
7534/// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
7535/// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
7536/// [',' OptionalTypeIdInfo]? [',' OptionalRefs]? ')'
7537bool LLParser::ParseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
7538 unsigned ID) {
7539 assert(Lex.getKind() == lltok::kw_function);
7540 Lex.Lex();
7541
7542 StringRef ModulePath;
7543 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
7544 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
7545 /*Live=*/false, /*IsLocal=*/false);
7546 unsigned InstCount;
7547 std::vector<FunctionSummary::EdgeTy> Calls;
7548 FunctionSummary::TypeIdInfo TypeIdInfo;
7549 std::vector<ValueInfo> Refs;
7550 // Default is all-zeros (conservative values).
7551 FunctionSummary::FFlags FFlags = {};
7552 if (ParseToken(lltok::colon, "expected ':' here") ||
7553 ParseToken(lltok::lparen, "expected '(' here") ||
7554 ParseModuleReference(ModulePath) ||
7555 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) ||
7556 ParseToken(lltok::comma, "expected ',' here") ||
7557 ParseToken(lltok::kw_insts, "expected 'insts' here") ||
7558 ParseToken(lltok::colon, "expected ':' here") || ParseUInt32(InstCount))
7559 return true;
7560
7561 // Parse optional fields
7562 while (EatIfPresent(lltok::comma)) {
7563 switch (Lex.getKind()) {
7564 case lltok::kw_funcFlags:
7565 if (ParseOptionalFFlags(FFlags))
7566 return true;
7567 break;
7568 case lltok::kw_calls:
7569 if (ParseOptionalCalls(Calls))
7570 return true;
7571 break;
7572 case lltok::kw_typeIdInfo:
7573 if (ParseOptionalTypeIdInfo(TypeIdInfo))
7574 return true;
7575 break;
7576 case lltok::kw_refs:
7577 if (ParseOptionalRefs(Refs))
7578 return true;
7579 break;
7580 default:
7581 return Error(Lex.getLoc(), "expected optional function summary field");
7582 }
7583 }
7584
7585 if (ParseToken(lltok::rparen, "expected ')' here"))
7586 return true;
7587
7588 auto FS = llvm::make_unique<FunctionSummary>(
7589 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
7590 std::move(TypeIdInfo.TypeTests),
7591 std::move(TypeIdInfo.TypeTestAssumeVCalls),
7592 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
7593 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
7594 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls));
7595
7596 FS->setModulePath(ModulePath);
7597
7598 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
7599 ID, std::move(FS));
7600
7601 return false;
7602}
7603
7604/// VariableSummary
7605/// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
7606/// [',' OptionalRefs]? ')'
7607bool LLParser::ParseVariableSummary(std::string Name, GlobalValue::GUID GUID,
7608 unsigned ID) {
7609 assert(Lex.getKind() == lltok::kw_variable);
7610 Lex.Lex();
7611
7612 StringRef ModulePath;
7613 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
7614 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
7615 /*Live=*/false, /*IsLocal=*/false);
7616 std::vector<ValueInfo> Refs;
7617 if (ParseToken(lltok::colon, "expected ':' here") ||
7618 ParseToken(lltok::lparen, "expected '(' here") ||
7619 ParseModuleReference(ModulePath) ||
7620 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags))
7621 return true;
7622
7623 // Parse optional refs field
7624 if (EatIfPresent(lltok::comma)) {
7625 if (ParseOptionalRefs(Refs))
7626 return true;
7627 }
7628
7629 if (ParseToken(lltok::rparen, "expected ')' here"))
7630 return true;
7631
7632 auto GS = llvm::make_unique<GlobalVarSummary>(GVFlags, std::move(Refs));
7633
7634 GS->setModulePath(ModulePath);
7635
7636 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
7637 ID, std::move(GS));
7638
7639 return false;
7640}
7641
7642/// AliasSummary
7643/// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
7644/// 'aliasee' ':' GVReference ')'
7645bool LLParser::ParseAliasSummary(std::string Name, GlobalValue::GUID GUID,
7646 unsigned ID) {
7647 assert(Lex.getKind() == lltok::kw_alias);
7648 LocTy Loc = Lex.getLoc();
7649 Lex.Lex();
7650
7651 StringRef ModulePath;
7652 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
7653 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
7654 /*Live=*/false, /*IsLocal=*/false);
7655 if (ParseToken(lltok::colon, "expected ':' here") ||
7656 ParseToken(lltok::lparen, "expected '(' here") ||
7657 ParseModuleReference(ModulePath) ||
7658 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) ||
7659 ParseToken(lltok::comma, "expected ',' here") ||
7660 ParseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
7661 ParseToken(lltok::colon, "expected ':' here"))
7662 return true;
7663
7664 ValueInfo AliaseeVI;
7665 unsigned GVId;
7666 if (ParseGVReference(AliaseeVI, GVId))
7667 return true;
7668
7669 if (ParseToken(lltok::rparen, "expected ')' here"))
7670 return true;
7671
7672 auto AS = llvm::make_unique<AliasSummary>(GVFlags);
7673
7674 AS->setModulePath(ModulePath);
7675
7676 // Record forward reference if the aliasee is not parsed yet.
7677 if (AliaseeVI == EmptyVI) {
7678 auto FwdRef = ForwardRefAliasees.insert(
7679 std::make_pair(GVId, std::vector<std::pair<AliasSummary *, LocTy>>()));
7680 FwdRef.first->second.push_back(std::make_pair(AS.get(), Loc));
7681 } else
7682 AS->setAliasee(AliaseeVI.getSummaryList().front().get());
7683
7684 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
7685 ID, std::move(AS));
7686
7687 return false;
7688}
7689
7690/// Flag
7691/// ::= [0|1]
7692bool LLParser::ParseFlag(unsigned &Val) {
7693 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
7694 return TokError("expected integer");
7695 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
7696 Lex.Lex();
7697 return false;
7698}
7699
7700/// OptionalFFlags
7701/// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
7702/// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
7703/// [',' 'returnDoesNotAlias' ':' Flag]? ')'
7704bool LLParser::ParseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
7705 assert(Lex.getKind() == lltok::kw_funcFlags);
7706 Lex.Lex();
7707
7708 if (ParseToken(lltok::colon, "expected ':' in funcFlags") |
7709 ParseToken(lltok::lparen, "expected '(' in funcFlags"))
7710 return true;
7711
7712 do {
7713 unsigned Val;
7714 switch (Lex.getKind()) {
7715 case lltok::kw_readNone:
7716 Lex.Lex();
7717 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
7718 return true;
7719 FFlags.ReadNone = Val;
7720 break;
7721 case lltok::kw_readOnly:
7722 Lex.Lex();
7723 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
7724 return true;
7725 FFlags.ReadOnly = Val;
7726 break;
7727 case lltok::kw_noRecurse:
7728 Lex.Lex();
7729 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
7730 return true;
7731 FFlags.NoRecurse = Val;
7732 break;
7733 case lltok::kw_returnDoesNotAlias:
7734 Lex.Lex();
7735 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
7736 return true;
7737 FFlags.ReturnDoesNotAlias = Val;
7738 break;
7739 default:
7740 return Error(Lex.getLoc(), "expected function flag type");
7741 }
7742 } while (EatIfPresent(lltok::comma));
7743
7744 if (ParseToken(lltok::rparen, "expected ')' in funcFlags"))
7745 return true;
7746
7747 return false;
7748}
7749
7750/// OptionalCalls
7751/// := 'calls' ':' '(' Call [',' Call]* ')'
7752/// Call ::= '(' 'callee' ':' GVReference
7753/// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')'
7754bool LLParser::ParseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) {
7755 assert(Lex.getKind() == lltok::kw_calls);
7756 Lex.Lex();
7757
7758 if (ParseToken(lltok::colon, "expected ':' in calls") |
7759 ParseToken(lltok::lparen, "expected '(' in calls"))
7760 return true;
7761
7762 IdToIndexMapType IdToIndexMap;
7763 // Parse each call edge
7764 do {
7765 ValueInfo VI;
7766 if (ParseToken(lltok::lparen, "expected '(' in call") ||
7767 ParseToken(lltok::kw_callee, "expected 'callee' in call") ||
7768 ParseToken(lltok::colon, "expected ':'"))
7769 return true;
7770
7771 LocTy Loc = Lex.getLoc();
7772 unsigned GVId;
7773 if (ParseGVReference(VI, GVId))
7774 return true;
7775
7776 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
7777 unsigned RelBF = 0;
7778 if (EatIfPresent(lltok::comma)) {
7779 // Expect either hotness or relbf
7780 if (EatIfPresent(lltok::kw_hotness)) {
7781 if (ParseToken(lltok::colon, "expected ':'") || ParseHotness(Hotness))
7782 return true;
7783 } else {
7784 if (ParseToken(lltok::kw_relbf, "expected relbf") ||
7785 ParseToken(lltok::colon, "expected ':'") || ParseUInt32(RelBF))
7786 return true;
7787 }
7788 }
7789 // Keep track of the Call array index needing a forward reference.
7790 // We will save the location of the ValueInfo needing an update, but
7791 // can only do so once the std::vector is finalized.
7792 if (VI == EmptyVI)
7793 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
7794 Calls.push_back(FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, RelBF)});
7795
7796 if (ParseToken(lltok::rparen, "expected ')' in call"))
7797 return true;
7798 } while (EatIfPresent(lltok::comma));
7799
7800 // Now that the Calls vector is finalized, it is safe to save the locations
7801 // of any forward GV references that need updating later.
7802 for (auto I : IdToIndexMap) {
7803 for (auto P : I.second) {
7804 assert(Calls[P.first].first == EmptyVI &&
7805 "Forward referenced ValueInfo expected to be empty");
7806 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
7807 I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
7808 FwdRef.first->second.push_back(
7809 std::make_pair(&Calls[P.first].first, P.second));
7810 }
7811 }
7812
7813 if (ParseToken(lltok::rparen, "expected ')' in calls"))
7814 return true;
7815
7816 return false;
7817}
7818
7819/// Hotness
7820/// := ('unknown'|'cold'|'none'|'hot'|'critical')
7821bool LLParser::ParseHotness(CalleeInfo::HotnessType &Hotness) {
7822 switch (Lex.getKind()) {
7823 case lltok::kw_unknown:
7824 Hotness = CalleeInfo::HotnessType::Unknown;
7825 break;
7826 case lltok::kw_cold:
7827 Hotness = CalleeInfo::HotnessType::Cold;
7828 break;
7829 case lltok::kw_none:
7830 Hotness = CalleeInfo::HotnessType::None;
7831 break;
7832 case lltok::kw_hot:
7833 Hotness = CalleeInfo::HotnessType::Hot;
7834 break;
7835 case lltok::kw_critical:
7836 Hotness = CalleeInfo::HotnessType::Critical;
7837 break;
7838 default:
7839 return Error(Lex.getLoc(), "invalid call edge hotness");
7840 }
7841 Lex.Lex();
7842 return false;
7843}
7844
7845/// OptionalRefs
7846/// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
7847bool LLParser::ParseOptionalRefs(std::vector<ValueInfo> &Refs) {
7848 assert(Lex.getKind() == lltok::kw_refs);
7849 Lex.Lex();
7850
7851 if (ParseToken(lltok::colon, "expected ':' in refs") |
7852 ParseToken(lltok::lparen, "expected '(' in refs"))
7853 return true;
7854
7855 IdToIndexMapType IdToIndexMap;
7856 // Parse each ref edge
7857 do {
7858 ValueInfo VI;
7859 LocTy Loc = Lex.getLoc();
7860 unsigned GVId;
7861 if (ParseGVReference(VI, GVId))
7862 return true;
7863
7864 // Keep track of the Refs array index needing a forward reference.
7865 // We will save the location of the ValueInfo needing an update, but
7866 // can only do so once the std::vector is finalized.
7867 if (VI == EmptyVI)
7868 IdToIndexMap[GVId].push_back(std::make_pair(Refs.size(), Loc));
7869 Refs.push_back(VI);
7870 } while (EatIfPresent(lltok::comma));
7871
7872 // Now that the Refs vector is finalized, it is safe to save the locations
7873 // of any forward GV references that need updating later.
7874 for (auto I : IdToIndexMap) {
7875 for (auto P : I.second) {
7876 assert(Refs[P.first] == EmptyVI &&
7877 "Forward referenced ValueInfo expected to be empty");
7878 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
7879 I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
7880 FwdRef.first->second.push_back(std::make_pair(&Refs[P.first], P.second));
7881 }
7882 }
7883
7884 if (ParseToken(lltok::rparen, "expected ')' in refs"))
7885 return true;
7886
7887 return false;
7888}
7889
7890/// OptionalTypeIdInfo
7891/// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
7892/// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
7893/// [',' TypeCheckedLoadConstVCalls]? ')'
7894bool LLParser::ParseOptionalTypeIdInfo(
7895 FunctionSummary::TypeIdInfo &TypeIdInfo) {
7896 assert(Lex.getKind() == lltok::kw_typeIdInfo);
7897 Lex.Lex();
7898
7899 if (ParseToken(lltok::colon, "expected ':' here") ||
7900 ParseToken(lltok::lparen, "expected '(' in typeIdInfo"))
7901 return true;
7902
7903 do {
7904 switch (Lex.getKind()) {
7905 case lltok::kw_typeTests:
7906 if (ParseTypeTests(TypeIdInfo.TypeTests))
7907 return true;
7908 break;
7909 case lltok::kw_typeTestAssumeVCalls:
7910 if (ParseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
7911 TypeIdInfo.TypeTestAssumeVCalls))
7912 return true;
7913 break;
7914 case lltok::kw_typeCheckedLoadVCalls:
7915 if (ParseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
7916 TypeIdInfo.TypeCheckedLoadVCalls))
7917 return true;
7918 break;
7919 case lltok::kw_typeTestAssumeConstVCalls:
7920 if (ParseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
7921 TypeIdInfo.TypeTestAssumeConstVCalls))
7922 return true;
7923 break;
7924 case lltok::kw_typeCheckedLoadConstVCalls:
7925 if (ParseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
7926 TypeIdInfo.TypeCheckedLoadConstVCalls))
7927 return true;
7928 break;
7929 default:
7930 return Error(Lex.getLoc(), "invalid typeIdInfo list type");
7931 }
7932 } while (EatIfPresent(lltok::comma));
7933
7934 if (ParseToken(lltok::rparen, "expected ')' in typeIdInfo"))
7935 return true;
7936
7937 return false;
7938}
7939
7940/// TypeTests
7941/// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
7942/// [',' (SummaryID | UInt64)]* ')'
7943bool LLParser::ParseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
7944 assert(Lex.getKind() == lltok::kw_typeTests);
7945 Lex.Lex();
7946
7947 if (ParseToken(lltok::colon, "expected ':' here") ||
7948 ParseToken(lltok::lparen, "expected '(' in typeIdInfo"))
7949 return true;
7950
7951 IdToIndexMapType IdToIndexMap;
7952 do {
7953 GlobalValue::GUID GUID = 0;
7954 if (Lex.getKind() == lltok::SummaryID) {
7955 unsigned ID = Lex.getUIntVal();
7956 LocTy Loc = Lex.getLoc();
7957 // Keep track of the TypeTests array index needing a forward reference.
7958 // We will save the location of the GUID needing an update, but
7959 // can only do so once the std::vector is finalized.
7960 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
7961 Lex.Lex();
7962 } else if (ParseUInt64(GUID))
7963 return true;
7964 TypeTests.push_back(GUID);
7965 } while (EatIfPresent(lltok::comma));
7966
7967 // Now that the TypeTests vector is finalized, it is safe to save the
7968 // locations of any forward GV references that need updating later.
7969 for (auto I : IdToIndexMap) {
7970 for (auto P : I.second) {
7971 assert(TypeTests[P.first] == 0 &&
7972 "Forward referenced type id GUID expected to be 0");
7973 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
7974 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
7975 FwdRef.first->second.push_back(
7976 std::make_pair(&TypeTests[P.first], P.second));
7977 }
7978 }
7979
7980 if (ParseToken(lltok::rparen, "expected ')' in typeIdInfo"))
7981 return true;
7982
7983 return false;
7984}
7985
7986/// VFuncIdList
7987/// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
7988bool LLParser::ParseVFuncIdList(
7989 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
7990 assert(Lex.getKind() == Kind);
7991 Lex.Lex();
7992
7993 if (ParseToken(lltok::colon, "expected ':' here") ||
7994 ParseToken(lltok::lparen, "expected '(' here"))
7995 return true;
7996
7997 IdToIndexMapType IdToIndexMap;
7998 do {
7999 FunctionSummary::VFuncId VFuncId;
8000 if (ParseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
8001 return true;
8002 VFuncIdList.push_back(VFuncId);
8003 } while (EatIfPresent(lltok::comma));
8004
8005 if (ParseToken(lltok::rparen, "expected ')' here"))
8006 return true;
8007
8008 // Now that the VFuncIdList vector is finalized, it is safe to save the
8009 // locations of any forward GV references that need updating later.
8010 for (auto I : IdToIndexMap) {
8011 for (auto P : I.second) {
8012 assert(VFuncIdList[P.first].GUID == 0 &&
8013 "Forward referenced type id GUID expected to be 0");
8014 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
8015 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
8016 FwdRef.first->second.push_back(
8017 std::make_pair(&VFuncIdList[P.first].GUID, P.second));
8018 }
8019 }
8020
8021 return false;
8022}
8023
8024/// ConstVCallList
8025/// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
8026bool LLParser::ParseConstVCallList(
8027 lltok::Kind Kind,
8028 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
8029 assert(Lex.getKind() == Kind);
8030 Lex.Lex();
8031
8032 if (ParseToken(lltok::colon, "expected ':' here") ||
8033 ParseToken(lltok::lparen, "expected '(' here"))
8034 return true;
8035
8036 IdToIndexMapType IdToIndexMap;
8037 do {
8038 FunctionSummary::ConstVCall ConstVCall;
8039 if (ParseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
8040 return true;
8041 ConstVCallList.push_back(ConstVCall);
8042 } while (EatIfPresent(lltok::comma));
8043
8044 if (ParseToken(lltok::rparen, "expected ')' here"))
8045 return true;
8046
8047 // Now that the ConstVCallList vector is finalized, it is safe to save the
8048 // locations of any forward GV references that need updating later.
8049 for (auto I : IdToIndexMap) {
8050 for (auto P : I.second) {
8051 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
8052 "Forward referenced type id GUID expected to be 0");
8053 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
8054 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
8055 FwdRef.first->second.push_back(
8056 std::make_pair(&ConstVCallList[P.first].VFunc.GUID, P.second));
8057 }
8058 }
8059
8060 return false;
8061}
8062
8063/// ConstVCall
Teresa Johnsonc7816802018-08-14 01:49:33 +00008064/// ::= '(' VFuncId ',' Args ')'
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008065bool LLParser::ParseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
8066 IdToIndexMapType &IdToIndexMap, unsigned Index) {
Teresa Johnsonc7816802018-08-14 01:49:33 +00008067 if (ParseToken(lltok::lparen, "expected '(' here") ||
8068 ParseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
8069 return true;
8070
8071 if (EatIfPresent(lltok::comma))
8072 if (ParseArgs(ConstVCall.Args))
8073 return true;
8074
8075 if (ParseToken(lltok::rparen, "expected ')' here"))
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008076 return true;
8077
8078 return false;
8079}
8080
8081/// VFuncId
8082/// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
8083/// 'offset' ':' UInt64 ')'
8084bool LLParser::ParseVFuncId(FunctionSummary::VFuncId &VFuncId,
8085 IdToIndexMapType &IdToIndexMap, unsigned Index) {
8086 assert(Lex.getKind() == lltok::kw_vFuncId);
8087 Lex.Lex();
8088
8089 if (ParseToken(lltok::colon, "expected ':' here") ||
8090 ParseToken(lltok::lparen, "expected '(' here"))
8091 return true;
8092
8093 if (Lex.getKind() == lltok::SummaryID) {
8094 VFuncId.GUID = 0;
8095 unsigned ID = Lex.getUIntVal();
8096 LocTy Loc = Lex.getLoc();
8097 // Keep track of the array index needing a forward reference.
8098 // We will save the location of the GUID needing an update, but
8099 // can only do so once the caller's std::vector is finalized.
8100 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
8101 Lex.Lex();
8102 } else if (ParseToken(lltok::kw_guid, "expected 'guid' here") ||
8103 ParseToken(lltok::colon, "expected ':' here") ||
8104 ParseUInt64(VFuncId.GUID))
8105 return true;
8106
8107 if (ParseToken(lltok::comma, "expected ',' here") ||
8108 ParseToken(lltok::kw_offset, "expected 'offset' here") ||
8109 ParseToken(lltok::colon, "expected ':' here") ||
8110 ParseUInt64(VFuncId.Offset) ||
8111 ParseToken(lltok::rparen, "expected ')' here"))
8112 return true;
8113
8114 return false;
8115}
8116
8117/// GVFlags
8118/// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
8119/// 'notEligibleToImport' ':' Flag ',' 'live' ':' Flag ','
8120/// 'dsoLocal' ':' Flag ')'
8121bool LLParser::ParseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
8122 assert(Lex.getKind() == lltok::kw_flags);
8123 Lex.Lex();
8124
8125 bool HasLinkage;
8126 if (ParseToken(lltok::colon, "expected ':' here") ||
8127 ParseToken(lltok::lparen, "expected '(' here") ||
8128 ParseToken(lltok::kw_linkage, "expected 'linkage' here") ||
8129 ParseToken(lltok::colon, "expected ':' here"))
8130 return true;
8131
8132 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
8133 assert(HasLinkage && "Linkage not optional in summary entry");
8134 Lex.Lex();
8135
8136 unsigned Flag;
8137 if (ParseToken(lltok::comma, "expected ',' here") ||
8138 ParseToken(lltok::kw_notEligibleToImport,
8139 "expected 'notEligibleToImport' here") ||
8140 ParseToken(lltok::colon, "expected ':' here") || ParseFlag(Flag))
8141 return true;
8142 GVFlags.NotEligibleToImport = Flag;
8143
8144 if (ParseToken(lltok::comma, "expected ',' here") ||
8145 ParseToken(lltok::kw_live, "expected 'live' here") ||
8146 ParseToken(lltok::colon, "expected ':' here") || ParseFlag(Flag))
8147 return true;
8148 GVFlags.Live = Flag;
8149
8150 if (ParseToken(lltok::comma, "expected ',' here") ||
8151 ParseToken(lltok::kw_dsoLocal, "expected 'dsoLocal' here") ||
8152 ParseToken(lltok::colon, "expected ':' here") || ParseFlag(Flag))
8153 return true;
8154 GVFlags.DSOLocal = Flag;
8155
8156 if (ParseToken(lltok::rparen, "expected ')' here"))
8157 return true;
8158
8159 return false;
8160}
8161
8162/// ModuleReference
8163/// ::= 'module' ':' UInt
8164bool LLParser::ParseModuleReference(StringRef &ModulePath) {
8165 // Parse module id.
8166 if (ParseToken(lltok::kw_module, "expected 'module' here") ||
8167 ParseToken(lltok::colon, "expected ':' here") ||
8168 ParseToken(lltok::SummaryID, "expected module ID"))
8169 return true;
8170
8171 unsigned ModuleID = Lex.getUIntVal();
8172 auto I = ModuleIdMap.find(ModuleID);
8173 // We should have already parsed all module IDs
8174 assert(I != ModuleIdMap.end());
8175 ModulePath = I->second;
8176 return false;
8177}
8178
8179/// GVReference
8180/// ::= SummaryID
8181bool LLParser::ParseGVReference(ValueInfo &VI, unsigned &GVId) {
8182 if (ParseToken(lltok::SummaryID, "expected GV ID"))
8183 return true;
8184
8185 GVId = Lex.getUIntVal();
8186
8187 // Check if we already have a VI for this GV
8188 if (GVId < NumberedValueInfos.size()) {
8189 assert(NumberedValueInfos[GVId] != EmptyVI);
8190 VI = NumberedValueInfos[GVId];
8191 } else
8192 // We will create a forward reference to the stored location.
8193 VI = EmptyVI;
8194
8195 return false;
8196}